text:
Q: Django CSRF missing or Sessions middleware required When trying to create a django(2) rest framework api, I keep getting this error.
Forbidden (CSRF token missing or incorrect.): /login/

After doing some research the problem might be with sessions authentication which I don't really need since I will be replying on token based auth. When I try to remove some of the session auth from my settings I end up getting this.
AssertionError: The Django authentication middleware requires session middleware to be installed. Edit your MIDDLEWARE setting to insert 'django.contrib.sessions.middleware.SessionMiddleware' before 'django.contrib.auth.middleware.AuthenticationMiddleware'.

Settings.py snippet
INSTALLED_APPS = [
    # API (v1)
    'apiV1.v1.accounts.apps.AccountsConfig',

    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # Requirements
    'corsheaders',
    'rest_framework',
    'rest_framework.authtoken',
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    # 'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'apiV1.urls'

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticatedOrReadOnly',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.TokenAuthentication',
        # 'rest_framework.authentication.SessionAuthentication',
    ),
}

Views.py
from django.contrib.auth import authenticate
from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from apiV1.v1.accounts.models.user import User
from apiV1.v1.accounts.serializers.user import UserSerializerLogin

# login
class LoginView(APIView):
    authentication_classes = ()
    permission_classes = ()

    @staticmethod
    def post(request):
        """
        Get user data and API token
        """

        user = get_object_or_404(User, email=request.data.get('email'))
        user = authenticate(username=user.email, password=request.data.get('password'))
        if user:
            serializer = UserSerializerLogin(user)
            return Response(serializer.data)
        return Response(status=status.HTTP_400_BAD_REQUEST)

A: If you don't need session for authentication you have to use token authentication.
Here is the example of view
from rest_framework.authtoken.models import Token
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.response import Response

class Login(ObtainAuthToken):
    def post(self, request, *args, **kwargs):
        """
        ---
        serializer: AuthTokenSerializer
        """

        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        token, created = Token.objects.get_or_create(user=user)

        return Response({
            'pk': user.pk,
            'first_name': user.first_name,
            'last_name': user.last_name,
        })

Or you can use JWT authentication.
Here are some helpful links for you.
http://www.django-rest-framework.org/api-guide/authentication/
http://getblimp.github.io/django-rest-framework-jwt/


text:
Q: What is ACTUALLY happening with parenthesis '()' in Clojure? I'm looking for the technical answer answer here. How is Clojure interpreting these symbols? My current working understanding is that the opening paren '(' is a kind of call that calls the succeeding operator on the operands while the closing paren ')' is a terminate that wraps up the previous evaluation and returns the final value generated (whether function or value).
Any and all details on the truth here would be appreciated. I'm looking to go deep here as well as seeing/knowing every level of abstraction along the way. It bugs me to know that I may have some imaginal thinking going on currently.

A: (foo x1 x2)

is the syntax for calling a special form or var (function or macro).
So the compiler will analyze the form (foo x1 x2) and will check if foo is a special form (if, try, let*, etc.) and if not, the symbol will be resolved to a var in the context of the current namespace. If that var is macro, then macroexpansion will happen, else the call will be treated as a normal function call.
To prevent treating (foo x1 x2) as a function call you can quote the expression: '(foo x1 x2) and then it will just remain a list of symbols.
More info:

*

*https://clojure.org/reference/special_forms

*https://clojure.org/reference/macros

A: You are trying to do too much at once when you say

'(' is a kind of call that calls the succeeding operator on the operands while the closing paren ')' is a terminate that wraps up the previous evaluation and returns the final value generated

The Clojure evaluation model does not assign semantics to characters directly. Instead, evaluation of a Clojure program goes through two broad phases:

*

*First, read the characters in the source file according to the language's lexical rules, yielding a Clojure data structure

*Second, evaluate that data structure, according to the language's evaluation rules, yielding a value

So when we write an expression like (+ (* 4 5) 2), what happens? The reader matches up parentheses to create lists, and yields as its result a list of three elements: the symbol +, another list (containing the symbol * and the numbers 4 and 5), and the number 2.
Next we move to evaluate that expression. Notice, crucially, that at this point there is no trace of parentheses. The textual source of the program is no longer material. We're evaluating a list. Of course, if we printed that list, conventionally we would surround it with parentheses, but that does not concern the evaluator. How do we evaluate this list? Well, the evaluation rule for lists is to, first, evaluate each of the components, and then invoke the first component as a function, passing the remaining components as arguments1. So our list of pending tasks is:

*

*Evaluate +

*Evaluate (* 4 5)

*Evaluate 2

*Invoke the result of (1), passing the results of (2) and (3) as arguments

(1), of course, evaluates to the addition function, (2) evaluates (in a similar manner) to the number 20, and (3) evaluates to the number 2 (since numbers evaluate to themselves). Thus, (4) becomes "Invoke the addition function, passing the numbers 20 and 2 as arguments". Of course, the final result is 22.

1 The rule is actually more complicated than this, because of macros, but for functions this suffices.

A: The other 2 answers are great. The simple summary is:
foo( x1, x2 )  // Java function call

(foo x1  x2)   // Clojure function call

In both cases, the compiler will evaluate any nested function calls in x1 or x2 before calling foo on the resulting values.

redpajama_set_name: RedPajamaStackExchange


text:
Q: one ajax request, multiple response? ok here is what I'm doing. check out the php and java script script below
PHP
ini_set("soap.wsdl_cache_enabled", "0");

$client = new SoapClient("server/test.wsdl");

$origtext = array('user'=>$_GET['pointname']);
$lastmodif    = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = $client->getTime($origtext)->{"timest"};

while ($currentmodif <= $lastmodif) // check if the data file has been modified
{
  // sleep(1);
  usleep(10000); // sleep 10ms to unload the CPU
  clearstatcache();
  $currentmodif = $client->getTime($origtext)->{"timest"};
}

$response = array();
$response['msg']       = $client->getMobile($origtext)->{"phone-num"};
$response['timestamp'] = $currentmodif;

echo json_encode($response);

flush();

Javascript
var timestamp = 0;
var pointname = "test1";
var noerror = true;

function wait() {
    $.ajax({
        type: "GET",
        url: "backend.php",
        data: "timestamp=" + this.timestamp + "&pointname=" + pointname,
        success: function (transp) {
            var response = eval('(' + transp + ')');
            timestamp = response['timestamp'];
            $("#page1b").html(response['msg']);
            $("#page1c").html(timestamp);
            noerror = true;
        },
        complete: function (transp) {
            if (!noerror) setTimeout(function () {
                wait()
            }, 5000);
            else wait();
            noerror = false;
        }
    });
}
wait();

once the ajax request is fired, from the server side will do a while loop check time value until time has changed, then it will echo a new value back to client and display on the webpage.(and all this will be automatically, and not much memory consuming on client side ) my ultimate target is to build a table  with 100 value inside,  firing 100 ajax request is obviously impossible. I want to treat those values separately but all sharing the same php script, meaning each value will only change when it changed and not affected by the others, but only one php script shown above required. any advice?

A: No you can't. In older browsers this was possible, and there was even a JQuery plug-in to facilitate it, but newer browser only fire the event when the whole request is received, and don't allow you to read the partial response before that.


text:
Q: How to separate ActiveRecord collection into multiple collections by group? I have a game, which creates logs. On display of the logs, I'd like to group them by turn to create an overall table, with a nested table for each turn within. In order to accomplish this, I am trying to group the logs by turn, so I can then iterate over them with an outer loop that runs once per turn, and an inner loop for each log item within that turn.
Right now, I have:
# logs_controller.rb
@logs = @game.logs.order("created_at ASC").group(:turn)

and in the view:
# logs/index.html.erb
<% @logs.each do |turn_logs| %>

        <%= turn_logs.first.turn%>

                <% turn_logs.each do |log| %>

<%= log.text %>

                <% end %>

This doesn't work, since Postgres complains that:
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  column "logs.id" must appear in the GROUP BY clause or be used in an aggregate function

I'm sure there's a simple way to do this that I'm overlooking, and I'll slap my head when it's pointed out, but right now it's eluding me.

A: Okay, I've got a good solution, I think. It involves using group_by to make an array of an array of log objects, with the turn as the key:
Controller:
# logs_controller.rb
@logs_by_turn = @game.logs.order("created_at ASC").group_by {|log| log.turn}

and in the view:
# logs/index.html.erb

<%  @logs_by_turn.each do |turn, turn_logs| %>

            <%= turn_logs.first.turn %>

                    <% turn_logs.each do |log| %>

<%= log.text %>

                    <% end %>

<% end %>


text:
Q: JFileChooser doesn't disappear after cancelSelection() I'm trying to close a JFileChooser. Could you, please, let me know why the cancelSelection method in the following snippet doesn't make it disappear after 5 seconds:
public static void main(String [] args){
    JFrame frame = new JFrame();
    frame.setVisible(true);
    final JFileChooser fchooser = new JFileChooser();
    fchooser.showOpenDialog(frame);
    try {Thread.sleep(5000);} catch (Exception e){}
    fchooser.cancelSelection();
}

Any help is much appreciated.

A: You should use a Swing Timer to do this since updates to the GUI should be done on the Event Dispatch Thread (EDT).
You need to start the Timer BEFORE you invoke the showOpenDialog() method.

A: The call to showOpenDialog() will not return until a selection is made or the dialog is canceled. If you want to close the dialog after a timeout, you will have to do the timing in another thread.

A: I agree that you should use a Swing Timer, but if you want more logic when to disable/dismiss the dialog (for example a progressbar that should close when no more data is available), either implement a SwingWorker or use the following:
  public static void main(String... args) {
    JFrame frame = new JFrame();
    frame.setVisible(true);
    final JFileChooser fchooser = new JFileChooser();

    new Thread() {
        @Override
        public void run() {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {}

            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    // This is run in EDT
                    fchooser.cancelSelection();
                }
            });
        }
    } .start();

    fchooser.showOpenDialog(frame);
}


text:
Q: Using multiple cassettes with VCR in one test I am using VCR to record http interactions with an external API. This is my (working) code:
it 'does xyz....' do
    hook_payload = {ruby_hash: 'here'}

    VCR.use_cassette('my_folder/create_project') do
      VCR.use_cassette('my_folder/get_project') do
        update = Update.new(hook_payload)
        expect { update.call }.to change { Projects.count }.by(1)
      end
    end
  end

The code above works, but the organization isn't good, as I prefer to have the expect{} call outside the block. So, I tried this, but the following code does not work:
context 'my context', vcr: { group: 'my_folder', cassettes: %w[create_project get_project] } do
    it 'does xyz....' do
        hook_payload = {ruby_hash: 'here'}

        update = Update.new(hook_payload)
        expect { update.call }.to change { Projects.count }.by(1)
      end

However this code doesn't work and I get the following error:
VCR is currently using the following cassette:  - /Users/me/this_project/spec/fixtures/vcr/my_folder/create_project.yml.
Under the current configuration VCR can not find a suitable HTTP interaction to replay and is prevented from recording new requests.
I am 100% sure that my_folder/get_project.yml is valid, and it works in other tests in the project.
I even put the cassettes (%w[create_project get_project]) in the same order that they are used in my code. What am I doing incorrectly here?

A: It's recommended to use the block but there are options if you don't want to do that. There are two ways: use an around hook or a before and an after hook.
If you load cassettes manually, you'll need to eject them if you reuse cassettes between tests as they don't like being loaded twice (the VCR analogy holds well here!).
https://www.rubydoc.info/github/vcr/vcr/VCR:insert_cassette
Try using VCR.insert_cassette which does not require a block. You'll need to call eject_cassette in your tear downs. I tried it and it worked. The ordering doesn't matter.
it 'does xyz....' do
  hook_payload = {ruby_hash: 'here'}

  VCR.insert_cassette('my_folder/create_project')
  VCR.insert_cassette('my_folder/get_project')

  update = Update.new(hook_payload)

  expect { update.call }.to change { Projects.count }.by(1)
end

Call eject to avoid loading cassettes twice:

VCR.eject_cassette(name: 'my_folder/create_project')
VCR.eject_cassette(name: 'my_folder/get_project')

The around hook might work for you too:
around do |example|
  cassettes = [
    { name: 'my_folder/create_project' },
    { name: 'my_folder/get_project' }
  ]
  VCR.use_cassettes cassettes do
    example.run
  end
end

You can even combine this with cassette config:
it 'whateva', vcr: { cassette_name: 'load another' } do

end


text:
Q: Dynamic, code based, breadcrumbs are not working in SharePoint 2010 I am currently porting an application from SharePoint 2007 to 2010. As a single page can be invoked in different contexts, we rely on a  code based SiteMapResolveEventHandler to dynamically populate the breadcrumb.
This all works great in SharePoint 2007, but for some reason in SharePoint 2010 it doesn't hit the 'SPXmlContentMapProvider' event handler even though this provider is available in the list of SiteMap.Providers.
If I hook up the event to a different provider, e.g. the CombinedNavSiteMapProvider then it does trigger the event handler, but this provider does not contain the nodes I am interested in.
The following code is being used (and works fine in SP2007)
In the application page's OnLoad
SiteMap.Providers["SPXmlContentMapProvider"].SiteMapResolve += new SiteMapResolveEventHandler(provider_SiteMapResolve);

which calls the following method (simplified version)
public SiteMapNode provider_SiteMapResolve(object sender, SiteMapResolveEventArgs e)
{
    e.Provider.EnableLocalization = false;

    // ** First request uses the current user's account to load sitemap file, so elevate.
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
        SiteMapNode listNode = e.Provider.RootNode.ChildNodes[0].Clone();
        listNode.Url = "http://some url";
        listNode.Title = "Some title";
        listNode.ChildNodes = new SiteMapNodeCollection();

        SiteMapNode pageTitleNode = new SiteMapNode(e.Provider, Guid.NewGuid().ToString());
        pageTitleNode.Title = "Some sub title";
        listNode.ChildNodes.Add(pageTitleNode);
        pageTitleNode.ParentNode = listNode;
    });

    return pageTitleNode;
}

I have checked that the event handler is never invoked by adding trace logging to the method as well as breakpoints.

A: In SharePoint 2010 Application pages need to override the PlaceHolderTitleBreadcrumb section from v4.master in order to specify that the SPXMLContentMapProvider be used. This will allow the breadcrumb control to work.  Additionally the title area needs to be adjusted to show a "breadcrumb like" navigation.
I've posted all of the code changes required on my blog:
http://blogs.visigo.com/chriscoulson/adding-breadcrumb-navigation-to-sharepoint-2010-application-pages/

A: Have u tried using another Provider?
I think SP2010 uses SPSiteMapProvider or SPContentMapProvider...


text:
Q: 3G modem is getting disconnected and not showing anymore in network manager icon I am using a BSNL 3G modem in India. I've noticed that, after using it for a time, internet is getting disconnected and it is disappearing from network manager icon. In order to connect again, modem must be removed and re-inserted. How can this be corrected?

A: *

*Open 'Network Tools".

*Select 'Ping' tab.

*Type www.google.com for the network address.

*Select 'Unlimited requests'

*Finally click PING!

Leave the window alone, and continue your work. This will keep your Internet connection busy, so the service provider (Airtel) can't drop your connection.

A: Type the ping www.bing.com -s 1 in the terminal and press enter after you are connected to the Internet.
This will keep your Internet Service Provider busy, so they can't drop your connection.
Make sure you have updated your OS to gain the best hardware support for your USB modem.

A: Whenever it disappears from network manager applet.
Do disable/enable mobile broadband from network applet.
Most of the time it works for me.


text:
Q: Elasticsearch what's the difference between null and empty value? I have a mapping, like this
{
  "properties": {
    "id": {
      "type": "keyword"
    },
    "name": {
      "type": "keyword"
    }
  }
}

about name field, in my original data the name can be empty "".
I have two choose to put the doc to ES:
{
    "id" : 6 ,
    "name" : ""
}

or
{
    "id" : 6 ,
    "name" : null
}

I don't need to search data like name == "" or name != "" or name == null or name != null.
I saw that a mount of empty values will cause the performance problem somewhere else. And saw that null value will not be index and search. So I want to put null field.
Is there any difference in my use case ?

A: A field with an empty "" string value will yield true to an exists query, which means that even if your value doesn't really contain a value, for Elasticsearch it does.
The only way to tell ES that your field doesn't contain a value is by assigning null.

A: An empty string is a string instance of zero length, whereas a null string has no value at all.


text:
Q: p:ajax feature not working in Liferay portal I can't get the PrimeFaces 6.1 built-in ajax feature to work when using a liferay portal. I've started with the very initial use case example, that is the one shown in the PF User's Guide documentation and nothing happens, absolutely nothing happens.
xhtml side
<h:form id="form">
    <h:inputText value="#{bEntityTree.text}">
        <p:ajax process="@form" update="output" onstart="onStart" oncomplete="onComplete" onsuccess="onSuccess" onerror="onError"/>
    </h:inputText>
    <br/>
    <h:outputText id="output" value="valor:#{bEntityTree.text}"/>

</h:form>

Bean side:
@ManagedBean(name = "bean")
@ViewScoped
public class Bean implements Serializable {

private static Logger logger = Logger.getLogger(BEntityTree.class);

private String text;

public Bean() {
    logger.trace("bean created");
}

@PostConstruct
private void onPostConstruct() {
    logger.trace("start");
}

public String getText() {
    logger.trace("getting text:" + text);
    return text;
}

public void setText(String text) {
    logger.trace("setting text:" + text);
    this.text = text;
}
}

JS side:
function onStart(){
    console.log("onStart");
}

function onComplete(){
    console.log("onComplete");
}

function onSuccess(){
    console.log("onSuccess");
}

function onError(){
    console.log("onError");
}

According to what the documentation states, each time the input changes an ajax request is sent to the server. My understanding is that the input changes when 'onchange' event is fired (default client side event). Well, every time I type a character in the <h:inputText> element nothing happens. When <p:inputText> looses the focus nothing happens, that is, <h:outputText> isn't updated and any trace console is displayed on the console of my chrome browser. The only trace log I get is the one from my IDE console:
[TRACE] Bean:<init>():bean created
[TRACE] Bean:onPostConstruct():start
[TRACE] Bean:getText():getting text:null
[TRACE] Bean:getText():getting text:null

I don't know what I'm doing wrong, what I'm missing.
Any help would be pretty appreciated.

A: I've just sorted the problem out. There were 2 problems. The first one (the less serious one) is that the js callbacks are being invoked wrong. The right way to invoke them should be as follows:
<p:ajax process="@form" update="output" onstart="onStart()" oncomplete="onComplete()" onsuccess="onSuccess()" onerror="onError()" />

The serious problem is related to a missing parameter in the liferay-portlet.xml config file.
Well, it maybe I should haved started saying that I was dealing with a Liferay portlet containing a JSF portlet which uses Primefaces. It all implies that liferay-portlet.xml config file is required. And this config file has to contain the following parameter:
<requires-namespaced-parameters>false</requires-namespaced-parameters>

The problem is that the default liferay-portlet.xml file, that is, the one that the eclipse IDE wizard creates DOES NOT automatically include such a parameter. After including such a parameter, it all works as expected.
UPDATE: The way I create the Liferay Plugin Project.

*

*New > Project > Liferay Plugin Project
Plugin Type: portlet
Include Sample code -> unchecked
Launch New Portlet Wizard afer project is created -> checked

*Next > JSF 2.x

*Next > Primefaces

*Finish
Steps when Wizard is displayed:

*

*Portlet class: javax.portlet.faces.GenericFacesPortlet

*Next
View template: Primefaces

*Next

*Finish

Major result after those steps is that file liferay-portlet.xml doesn't have the element:
<requires-namespaced-parameters>false</requires-namespaced-parameters>

Development settings:

*

*Eclipse Java EE IDE for Web Developers
Version: Mars.2 Release (4.5.2) - Build id: 20160218-0600

*Liferay IDE 2.2.4.201507230603-ga5

Any clarification would be appreciated.


text:
Q: How to save memory from unpopular/cold Redis? We have a lot of Redis instances, consuming TBs of memory and hundreds of machines.
With our business activities goes up and down, some Redis instances are just not used that frequent any more -- they are "unpopular" or "cold". But Redis stores everything in memory, so a lot of infrequent data that should have been stored in cheap disk are occupying expensive memory.
We are exploring a way to save the memory from these unpopular/cold Redis, as to reduce our machines usage.
We cannot delete data, nor can we migrate to other database. Are there some way to achieve our goals?
PS: We are thinking of some Redis compatible product that can "mix" memory and disk, i.e. it stores hot data in memory but cold in disk, and USING LIMITED RESOURCES. We know RedisLabs' "Redis on Flash(ROF)" solution, but it uses RocksDB, which is very memory unfriendly. What we want is a very memory restrained product. Besides, ROF is not open source :(
Thanks in advance!

A: ElastiCache Redis now supports data tiering. Data tiering provides a new cost optimal option for storing data in Redis by utilizing lower-cost local NVMe SSDs in each cluster node in addition to storing data in memory. It is ideal for workloads that access up to 20 percent of their overall dataset regularly, and for applications that can tolerate additional latency when accessing data on SSD. More details about data tiering can be found here.

A: Your problem might be solved by using an orchestrator approach: scaledown when not in use, scale up when in demand.
Implementation depends much on your infrastructure, but a base requirement is proper monitoring of Redis instances usage.
Based on that, if you are running on Kubernetes, you can leverage pod autoscaling.
Otherwise you can implement Consul and use HAProxy to handle the shutdown/spin-up logic. A starting point for that strategy is this article.
Of course Reiner's idea of using swap is a quick win if it works the intended way!


text:
Q: Get earliest date, vendor, qty for two joined tables I have a query I use to bring data into a Crystal Report; it collapses data so that I get one record for each unique STOCK_ID, and logic and formatting in Crystal depends on that.
Now I need to add three more columns on the report.  Isolated, the query looks something like this:
*SELECT LINE.STOCK_ID ,LINE.QTY ,LINE.ORD_NUMB ,LINE.LINE_NUMB ,ORDER.DATE ,ORDER.VENDOR ,ORDER.STATUS ,PRODUCT.COUNT
FROM tbl_LINE LINE
JOIN tbl_ORDER ORDER ON LINE.ORD_NUMB = ORDER.ORD_NUMB
JOIN tbl_PRODUCT PRODUCT ON LINE.STOCK_ID = PRODUCT.STOCK_ID
WHERE ORDER.STATUS < 600 AND PRODUCT.COUNT > 1
ORDER BY LINE.STOCK_ID ,ORDER.DATE*

This pulls in multiple LINE.QTY, ORDER.DATE, ORDER.VENDOR, and for a STOCK_ID, but I need to collapse to get only the most recent ORDER.DATE, along with the other two associated columns.
I have no solution for doing this with joined tables.
Any insights.

A: How about something like this?
SELECT LINE.STOCK_ID ,LINE.QTY ,LINE.ORD_NUMB ,LINE.LINE_NUMB ,ORDER.DATE ,ORDER.VENDOR ,ORDER.STATUS ,PRODUCT.COUNT
FROM tbl_LINE LINE
JOIN tbl_ORDER ORDER ON LINE.ORD_NUMB = ORDER.ORD_NUMB
JOIN tbl_PRODUCT PRODUCT ON LINE.STOCK_ID = PRODUCT.STOCK_ID
JOIN
(
    SELECT PRODUCT.STOCK_ID, max(ORDER.DATE) as MaxOrderDate
    FROM tbl_LINE LINE
    JOIN tbl_ORDER ORDER ON LINE.ORD_NUMB = ORDER.ORD_NUMB
    JOIN tbl_PRODUCT PRODUCT ON LINE.STOCK_ID = PRODUCT.STOCK_ID
    WHERE ORDER.STATUS < 600 AND PRODUCT.COUNT > 1
    GROUP BY PRODUCT.STOCK_ID
) x on LINE.STOCK_ID = x.STOCK_ID and ORDER.DATE = x.MaxOrderDate
WHERE ORDER.STATUS < 600 AND PRODUCT.COUNT > 1
ORDER BY LINE.STOCK_ID ,ORDER.DATE


text:
Q: Seek details in SPIFFS for a specific date I have a ESP8266,
I've  stored the below details in SPIFFS.
How can I seek all details like employee number ,name ,age for a specific date?
Structure I am using ,
struct
{

char date[4];

char emp_number;

char name;

char age;

}std_detail;

Details that stored in SPIFFS

2019-10-21,employe number1,name,age

2019-10-21,employe number2,name,age

2019-10-21,employe number3,name,age

2019-10-22,employe number1,name,age

2019-10-22,employe number2,name,age

2019-10-22,employe number3,name,age

2019-10-22,employe number4,name,age


text:
Q: Initialize additional object in Django model instance and pass model instance Some calculations became too complex to maintain inside my model, so I decided to move them out and break the code in several classes and modules.
There's a single class serving as a facade which I would like to have available in a model instance to pass data to it.
It is being constructed from model instance:
class Calculator:

    def __init__(self, field1: date, field2: float):
        self.field1= field1
        self.field2 = field2

    @classmethod
    def from_django_model(cls, django_model_instance):
        field1 = django_model_instance.field1
        field2 = float(django_model_instance.field2)

Currently I call it inside each property on my model like so:

class DjangoModel(models.Model):
    # initialize the calculator
    def calculator(self, group):
        return calculator.Calculator.from_django_model(self)

    # use it
    @cached_property
    def calculated_field(self):

        try:
            return self.calculator().calculation_method
        except AttributeError:
            return "Field not set!"

I feel this is not a good solution, since now on multiple methods I'm initializing the calculator object multiple times.
I would like to construct it once when the model is initialized and then pass it to the model instance.
I tried doing this with model manager, but the model instance is not available with it.


text:
Q: Linphone failure: There is no object pool created in thread If I let my application sit for a while or after a couple calls I get the following crash on linphone:

2016-11-09 09:21:17:372 ortp-message-Listening point [0x1740fe480] on
  [sip:0.0.0.0:5060;transport=UDP] destroyed 2016-11-09 09:21:17:372
  ortp-message-Listening point [0x1740fe500] on
  [sip:0.0.0.0:5060;transport=TCP] destroyed 2016-11-09 09:21:17:373
  ortp-message-Listening point [0x1740fe580] on
  [sip:0.0.0.0:49391;transport=TLS] destroyed 2016-11-09 09:21:17:373
  ortp-message-sal_unlisten_ports done 2016-11-09 09:21:17:373
  ortp-message-http provider destroyed. 2016-11-09 09:21:17:373
  ortp-message-stack [0x17434dd60] destroyed. 2016-11-09 09:32:44.566120
  Setec[249:9352] [MC] Invalidating cache 2016-11-09 09:32:44.567110
  Setec[249:7759] [MC] Reading from public effective user settings.
  SetupCalls 2016-11-09 09:45:36.743273 Setec[249:10714] MakeCall..
  2016-11-09 09:45:36.743842 Setec[249:10714] identity:
  sip:5612954779@phoneserverhere 2016-11-09 09:45:36:744
  ortp-warning-There is no object pool created in thread [6140047360].
  Use belle_sip_object_pool_push() to create one. Unowned objects not
  unref'd will be leaked.

The code I am using is:
     DispatchQueue.global(qos: .background).async {
        NSLog("MakeCall..")

    guard let _ = self.setIdentify() else {
        print("no identity in makeCall")
        return
    }

    linphone_core_invite(lc, numberToCall)
    self.mainLoop(sec: 5)
    self.shutdown()
    }

and it gets caught in the guard.

A: Select "Enable Bitcode" = Yes from Build Settings.


text:
Q: Visual Studio equivalent of Eclipse's Control+Q shortcut is there an equivalent of Eclipse's control Q shortcut (go to the last edit) in Visual Studio 2015?
I've tried control shift backspace but doesn't work
I'm using it quite a lot and it's really tedious having to do without it.


text:
Q: How to make items reorderable *using touch* in an UWP 10.0 XAML/C# project According to the example on this page, the following code would enable reordering of the items in a ListView. Actually it does, but only using the mouse. If I put the window on my touchscreen and touch the items, it'll show the 'scroll failed' animation (move vertically then pop back) and items won't reorder. Any suggestions?
<ListView CanReorderItems="True" AllowDrop="True">
    <ListView.ItemTemplate>
        <DataTemplate><TextBlock Text="{Binding}"/></DataTemplate>
    </ListView.ItemTemplate>
    <x:String>One</x:String>
    <x:String>Two</x:String>
    <x:String>Three</x:String>
    <x:String>Four</x:String>
</ListView>

This is all in an UWP 10.0 project (frameworks: uap10.0), to be specific.
I'd hope this to work without having to write drag and drop code.

A: Spent an hour on this before moving on, ending up here three hours later trying to solve yet another problem.

Tap & hold, then drag to reorder

Scott uses hamburgers for grips...good choice. The tip is something static has got to be in the list to be reordered, to be able to 'grab' the item or the reordering might not work because gestures are being handled to do something else. My list was short but had checkboxes in it which would get checked/unchecked and you can't reorder after that. In the image, the list is longer than the screen. Once it starts scrolling you can't reorder anymore.
Seems I had been too hasty with my fingers too. I didn't seem to be able to reorder even if no checkboxes changed state or with the exact code from the question, containing only strings.
Quite happy with the amount of code this required ;)


text:
Q: Installed OS on SSD and now it's full, how can I offload storage issues? I have a new Windows 10 PC with a small SSD and a large standard hard drive. I had the OS installed on the SSD since I've seen so many articles about that making your computer a ton faster.
Now months later I'm having issues with the space on my C:\ drive (the SSD) being full. I'm mitigating what I can with uninstalling / reinstalling programs onto the larger drive and I have managed to find ways to change a small few system folders (Downloads, Documents->Pictures, Documents->Videos) to the other drive by default, but I fear that this is just delaying the inevitable as system files pile up.
What are my options to mitigate the memory load?
More specifically, what options do I have in Windows to have nearly everything non-essential exist on my secondary drive without heavily impacting daily operation?

A: You are on the right trail:

*

*Change the path of the User's folders (Documents, Downloads, Pictures, Videos,...) to point to directories on the larger drive,

*

*If you tend to use other folders on your SSD for your documents, pictures, ..., relocate them to the larger drive, too.

*Install as many programmes as you can on the larger drive.

*

*Also check that Windows Store Apps (if you have some) are installed on the larger drive (Settings Menu -> System -> Storage -> Save Locations).

*Take a tool such as WinDirStat and see which folder(s) and files are taking up the most space. Best case scenario: C:\Windows, C:\ProgramData and C:\Users\<USER>\AppData are among the top.

*If you can live without them, disable hibernation, fast startup and hybrid standby, so your hiberfil.sys will become smaller.

*Run cleanmgr.exe and clean up your SSD - you can usually delete all (System-)Files without anything going wrong, though I have seen some (very old) programs rely on TEMP, so they might "forget" some settings afterwards (so no personal files should get deleted, anyway).

*You could reduce the size of your pagefile, though I would not recommend it as the pagefile is there for a reason.

*Also, you can uninstall Windows features - though this is a desperate measure, as I don't think that you can free more than a few MiB with that.

Except from that, I don't think that one can do much to reduce Windows's desire for space (except, of course, Steve's suggestion to move TEMP away from the SSD)

A: You have to check if your Apps or programs are not stocking too much data on your C:.
I don't know programs you use but they store data where they are installed, same for Apps coming from the Windows Store. Consider to change the location of some programs you don't use everydays.
Hope it will help


text:
Q: Windows Event Log SystemTime format The follwing timestamp was created during an Windows Security Log
TimeCreated

   [ SystemTime]  2013-10-07T07:31:09.122037600Z

In this timestamp I can't understand what 122037600Z part means? Do they represent milliseconds or something? Please i need your help.
Placeholder
String  Meaning
YYYY    four-digit year
MM  two-digit month (01=January, etc.)
DD  two-digit day of month (01 through 31)
hh  two digits of hour (00 through 23)
mm  two digits of minute (00 through 59)
ss  two digits of second (00 through 59)
s   one or more digits representing a decimal fraction of a second
TZD time zone designator ("Z" or +hh:mm or -hh:mm)

A: The part after the integer second is the fractional second.  The Z takes the place of the time zone to indicate UTC.  It could also be written 2013-10-07T07:31:09.122037600+00:00
122037600 fractional second
Z         Zulu, indicating UTC as time zone


text:
Q: Why does Annotate and Count in Django behave this way? I have two models Post and Tag(given by django-taggit app). So they make use of generic foreign key concept.
If i query posts like:
posts = Post.objects.annotate(num_tags=Count('tags'))

and try to retrieve value of num_tags for first result in queryset like:
posts[0].num_tags
>> 7 (which is true, there are 7 tags related with this post)

Now, say if i have a post with tag ids = [4,5,6] and I query similar posts to this one like:
similar_posts = Post.objects.filter(tags__in=tag_list).annotate(num_tags=Count('tags'))

Now, if I try to retrieve the num tags value like:
similar_posts[0].num_tags
>> 1

Here 1 is referring to the number of tags that matched from the tag list. But why does Django not explain this behavior anywhere in their documentation, or am i missing some parts of documentation?
Can someone please explain the actual working of 'annotate' and 'count' in different scenarios?
Note: similar_posts[0] and posts[0] is the same object.
I was expecting the num_tags to show 7 in both cases. However showing 1 in the latter case actually helps in my usecase. But need to know why does Count behave differently in the latter case.


text:
Q: WP custom featured image size not working if image is smaller than defined crop size? I am trying to manually add more featured image sizes in the functions.php, but if the set image size is larger than the image width, the crop is not being created?
add_theme_support( 'post-thumbnails' );
add_image_size( 'custom-square', 400, 400, true );
add_image_size( 'custom-medium', 1440, 9999 );
add_image_size( 'custom-large', 1920, 9999 );

So if I upload an image with a width of 1000px, the 1440px version is not being created for some reason. How can I correct this?


text:
Q: How to debug the error: 'Apex CPU time limit exceeded' The trigger written in my salesforce org is hitting the apex cpu time limit . Hence I am trying to optimize apex code and reducing the workflow updates. But below log is confusing me about the apex governor limits:
> 16:11:02.820 |CUMULATIVE_LIMIT_USAGE
16:11:02.820 |LIMIT_USAGE_FOR_NS|(default)|
  Number of SOQL queries: 2 out of 100
  Number of query rows: 203 out of 50000
  Number of SOSL queries: 0 out of 20
  Number of DML statements: 2 out of 150
  Number of DML rows: 201 out of 10000
  Maximum CPU time: 19336 out of 10000 ******* CLOSE TO LIMIT
  Maximum heap size: 0 out of 6000000
  Number of callouts: 0 out of 100
  Number of Email Invocations: 0 out of 10
  Number of future calls: 0 out of 50
  Number of queueable jobs added to the queue: 0 out of 50
  Number of Mobile Apex push calls: 0 out of 10
16:11:02.820 (91820619113)|CUMULATIVE_LIMIT_USAGE_END

Can anyone help me understand why does it show

Maximum CPU time: 19336 out of 10000 * CLOSE TO LIMIT

As salesforce governor limit for CPU time is 10000ms, it should throw error right after 10000ms. Am I missing something here? I am not able to see the actual consumption of CPU time in the logs,as the debug log size is big and salesforce is supressing the system.debugs I have put in the code. Can anyone suggest if there is any effective way to debug the apex CPU limit consumption?


text:
Q: Adicionar links aos textos dinamicamente sem alterar os atributos dos elementos Estou criando uma ferramenta para adicionar um link ao texto caso ele seja igual a um dos títulos no objeto links, estou usando replace e regex, o problema é que dessa maneira ele afeta os atributos dos elementos que contenha a texto desejado, tentei usar textContent no lugar de innerHTML, mas dessa forma o elemento a é retornado em formato de texto.
O que devo fazer para adicionar links aos textos sem que afete a integridade dos elementos HTML?

let conteudo = document.getElementById("conteudo");
let links = [
  {
    title: 'Teste',
    link: '/test.html'
  }
];

links.forEach(link => {
  conteudo.innerHTML = conteudo.innerHTML.replace(new RegExp( link.title, 'gi' ), `<a href="${link.link}">${link.title}</a>`);
});

    Essa é uma frase de teste

A: Eu não tenho certeza se entendi o que você quer, mas aqui vai uma explicação sobre como transformar pedaços de texto em link, sem alterar o formato em CSS, da forma mais simples que eu conseguir!

Primeiro, você cria, no seu escopo CSS, a caracterização dos links, e tenta deixar o mais próximo do texto comum, com mesma fonte,
tamanho, cor, etc. É importante especificar o máximo de coisas
possíveis, porque o HTML adota um padrão já predefinido em algumas
características.
Segundo, o elemento onde se encontra seu texto, seja ele uma , um , ... enfim, o objeto onde sua string vai ficar
armazenada.
É importante deixar bem claras as especificações de ID ou Class, pra
que você não acabe se confundindo depois.
Terceiro, programar seu script, que vai ter apenas 3 tarefas bem claras:

*

*Receber o objeto de texto como input assim que carregado na página;

*Fazer um loop pelo objeto de texto e comparar com os títulos do objeto com títulos

*Substituir o valor que, quando comparado, retorna true.

Tendo isso explicado, segue então um modelo de script.

const keywords =
[
{title: 'Jogos', link: 'https://pt.wikipedia.org/wiki/Desporto'}
]

function update_text(txt, id){

/// recebe txt como o corpo do texto e id como ID do texto

    let txt_elements = []
    txt_elements = txt.split(' '); // separa o texto em palavras

  /// loop pelos elementos do texto
  for(let i = 0; i < txt_elements.length-1; i++){

    if(txt_elements[i] === keywords[0].title){ // elemento bate com a pesquisa
      txt_elements.splice(i, 1, `<a class='link-pattern' href='${keywords[0].link}'>${keywords[0].title}</a>`) // modifica elementos
    }

  }

  txt = txt_elements.join(' '); // txt recebe elementos modificados
  document.querySelector(`#${id}`).innerHTML = txt; // muda texto em HTML para o que há dentro da variável txt
}
#test-content {
  font-family: Verdana;
  font-size: 10px;
  color: rgb(20, 20, 20)
}

.link-pattern {
  font-family: Verdana;
  font-size: 10px;
  color: rgb(20, 20, 20);
  text-decoration: none
}
<!DOCTYPE html>

    <title>Teste</title>

Os Jogos têm crescido em escala, a ponto de quase todas as nações serem representadas. Tal crescimento tem criado inúmeros desafios, incluindo boicotes, doping, corrupção de agentes públicos e terrorismo. A cada dois anos, os Jogos Olímpicos e sua exposição à mídia proporcionam a atletas desconhecidos a chance de alcançar fama nacional e, em casos especiais, a fama internacional. Os Jogos também constituem uma oportunidade importante para a cidade e o país se promover e mostrar-se para o mundo.

Pronto, a partir de agora seu código substitui automaticamente strings comuns para links :D
(Se a resposta tiver ajudado, por favor marca sua pergunta como Respondida kskssksk)


text:
Q: How check with Angular 8 unit test if image exists in given path? I have a picture in assets/logo.png and i wanna check inside the .spec.ts if this picture exists and if not throw error (to be truthy or not). How can i implement something like this ?

A: You can try below code:
    it('should set image logo path as expected', () => {
        const ele = fixture.debugElement.nativeElement.querySelectorAll('img');
        expect(ele[0]['src']).toContain('logo.png'); // if you dont have `id` in `img` , you need to provide index as `ele[index]`
        // OR use
       const ele1 = fixture.debugElement.nativeElement.querySelector("#img-id");
       expect(ele1['src']).toContain('logo.png');
    });

It checks if below image is present in src attribute.  You can be more specific by using .toEqual('assets/logo.png')

A: create a html for image , assign the image path to source and check if the image tag has height and width of the assigned image
it('should set image logo path as expected', () => {
  let ele = document.createElement("img");
  ele.id = 'eee';
  ele.src = this.source;
  setTimeout(() => {
     expect(ele.height).toBeGreaterThan(0);
     expect(ele.width).toBeGreaterThan(0);
   }, 5000);
 });

if the image path is not correct the width and height of ele will be 0.

A: Since I also had to test if 'my-image.png' is not only correctly referred to but also really displayed, I elaborated a bit on Shlok Nangia's answer and came up with the following snippet, which works for me (the else-part is actually not needed):
it('should display my-image.png', () => {
    const fixture = TestBed.createComponent(MyComponent);
    const compiled = fixture.debugElement.nativeElement;
    const imgElement = compiled.querySelector('img.my-class');
    if (imgElement) {
        const rectangle = imgElement.getBoundingClientRect();
        setTimeout(() => {
            expect(rectangle.height).toBeGreaterThan(0);
            expect(rectangle.width).toBeGreaterThan(0);
        }, 10000);
    } else {
        window.alert('should display my-image.png: failed');
    }
});


text:
Q: Oracle's set nls_date_format corrupts the date I have some code to do replication from an oracle database (not mine) and I'm having problems with the date format.
I'm doing a set nls_date_format='yyyy-mm-dd hh24:mi:ss' and most fields are returned just fine, eg: 2013-04-03 03:48:46
However, two columns are being mangled by this ans return some thing like: 0001-03-20 13:00:00
Now if you squint you can see that it's simply forced the formatting on what looks like a string. I have checked and those columns are of type 'date'.
So what gives? I don't particularly want a one-time solution because this is a general purpose replicator.

A: I meet that problem when I was migrating data from a Java app based database. It is nothing wrong with the date formatting in Oracle. The way I handled it:
CREATE TABLE table_dt(d_date DATE);

INSERT INTO table_dt VALUES (TO_DATE('0001-03-20 13:00:00', 'YYYY-MM-DD HH24:Mi:SS'));
COMMIT;

SELECT * FROM table_dt;
-- 0001-03-20 13:00:00

SELECT  CASE
            WHEN SUBSTR(TO_CHAR(d_date, 'YYYY-MM-DD HH24:Mi:SS'), 1, 1) = '0'
            THEN TO_DATE('2' || SUBSTR(TO_CHAR(d_date, 'YYYY-MM-DD HH24:Mi:SS'), 2), 'YYYY-MM-DD HH24:Mi:SS')
            ELSE d_date
        END AS parsed_d_date
FROM    table_dt;
-- 2001-03-20 13:00:00

Just to have the hands clear show it to business owner, agree and migrate.


text:
Q: How MediaCodec finds the codec inside the framework in Android? I am trying to understanding how MediaCodec is used for hardware decoding.
My knowledge in android internal is very limited.
Here is my findings:
There is a xml file which represents the codec details in the android system .
 device/ti/omap3evm/media_codecs.xml for an example.

Which means, that If we create a codec from the Java Application with Media Codec
MediaCodec codec = MediaCodec.createDecoderByType(type);

It should be finding out respective coder with the help of xml file.
What am I  doing?
I am trying to figure our which part of the code is reading xml and find the codec based on given 'type'.
1)   Application Layer :
   MediaCodec codec = MediaCodec.createDecoderByType(type);

2)   MediaCodec.java  ->  [ frameworks/base/media/java/android/media/MediaCodec.java  ]
     public static MediaCodec createDecoderByType(String type) {

    return new MediaCodec(type, true /* nameIsType */, false /* encoder */);
}

3)
private MediaCodec(
        String name, boolean nameIsType, boolean encoder) {
    native_setup(name, nameIsType, encoder);    --> JNI Call.
}

4)
JNI Implementation -> [ frameworks/base/media/jni/android_media_MediaCodec.cpp ]
static void android_media_MediaCodec_native_setup (..) {
        .......
    const char *tmp = env->GetStringUTFChars(name, NULL);
    sp<JMediaCodec> codec = new JMediaCodec(env, thiz, tmp, nameIsType, encoder);     ---> Here
}

from frameworks/base/media/jni/android_media_MediaCodec.cpp
    JMediaCodec::JMediaCodec( ..) {
         ....
          mCodec = MediaCodec::CreateByType(mLooper, name, encoder); //Call goes to libstagefright
          .... }

    sp<MediaCodec> MediaCodec::CreateByType(
            const sp<ALooper> &looper, const char *mime, bool encoder) {
        sp<MediaCodec> codec = new MediaCodec(looper);
        if (codec->init(mime, true /* nameIsType */, encoder) != OK) {  --> HERE.
            return NULL;
        }
    return codec;
   }

    status_t MediaCodec::init(const char *name, bool nameIsType, bool encoder) {
           // MediaCodec
    }

I am struck with this flow. If someone points out how to take it forward would help a lot.
thanks.

A: Let's take the flow step by step.

*

*MediaCodec::CreateByType will create a new MediaCodec object

*MediaCodec constructor would create a new ACodec object and store it as mCodec

*When MediaCodec::init is invoked, it internally instructs the underlying ACodec to allocate the OMX component through mCodec->initiateAllocateComponent.

*ACodec::initiateAllocateComponent would invoke onAllocateComponent

*ACodec::UninitializedState::onAllocateComponent would invoke OMXCodec::findMatchingCodecs to find the codecs matching the MIME type passed from the caller.

*In OMXCodec::findMatchingCodecs, there is a call to retrieve an instance of MediaCodecList as MediaCodecList::getInstance().

*In MediaCodecList::getInstance, there is a check if there is an existing MediaCodecList or else a new object of MediaCodecList is created.

*In the constructor of MediaCodecList, there is a call to parseXMLFile with the file name as /etc/media_codecs.xml.

*parseXMLFile reads the contents and stores the different component names etc into MediaCodecList which can be used for any other codec instance too. The helper function employed for the parsing is startElementHandler . A function of interest could be addMediaCodec.
Through these steps, the XML file contents are translated into a list which can be employed by any other module. MediaCodecList is exposed at Java layer too as can be referred from here.
I have skipped a few hops wherein MediaCodec and ACodec employ messages to actually communicate and invoke methods, but the flow presented should give a good idea about the underlying mechanism.


text:
Q: How to get Example and solution as in the style of the attached jpg file How to get Example and solution as in the style with boundaries of the attached jpg file.

  \documentclass{book}
\usepackage{graphicx,amssymb,amsmath}
\usepackage{exercise,chngcntr}
\counterwithin{Exercise}{chapter}
\counterwithin{Answer}{chapter}
\renewcounter{Exercise}[chapter]
\renewcommand{\theExercise}{\thechapter.\arabic{Exercise}}
\begin{document}
\begin{Exercise}
Prove that $    \frac{1}{2}\Delta(f_{ij}f^{ij}) =\nabla^{k}f^{ij}+f^{ij}f^{k}[2 \nabla_{i}R_{jk}-\nabla_{k}R_{ij}]$
\end{Exercise}
\begin{Answer}
Answer 2.2
        \end{Answer}
  \end{document}

A: I've created the new environment Example which puts the Exercise one within a tcolorbox.
\documentclass{book}
\usepackage{graphicx,amssymb,amsmath}
\usepackage[lastexercise]{exercise}
\usepackage{chngcntr}
\usepackage{xcolor}
\usepackage{tcolorbox}
\tcbset{arc=0mm,boxrule=1pt,colback=white,colframe=cyan,leftrule=3mm}

\counterwithin{Exercise}{chapter}
\counterwithin{Answer}{chapter}
\renewcounter{Exercise}[chapter]
\renewcommand{\theExercise}{\thechapter.\arabic{Exercise}}
\renewcommand{\AnswerHeader}{\medskip\noindent\textcolor{red}{\textbf{SOLUTION}}\;}
\renewcommand{\ExerciseName}{EXAMPLE}
\renewcommand{\ExerciseHeader}{\noindent\textbf{\ExerciseName\;\ExerciseHeaderNB}}
\newenvironment{Example}{\begin{tcolorbox}\begin{Exercise}}{\end{Exercise}\end{tcolorbox}}
\setlength{\ExerciseSkipBefore}{0pt}
\setlength{\AnswerSkipAfter}{\baselineskip}
\begin{document}
    \chapter{My first set of exercises}
    \begin{Example}
        Prove that $\frac{1}{2}\Delta(f_{ij}f^{ij}) =\nabla^{k}f^{ij}+f^{ij}f^{k}[2\nabla_{i}R_{jk}-\nabla_{k}R_{ij}]$
    \end{Example}
    \begin{Answer}
        From \dots
    \end{Answer}

    \begin{Example}
        Prove that Paulinho is smart.
    \end{Example}
    \begin{Answer}
        All ducks are smart. Paulinho is a duck. Therefore, Paulinho is smart.
    \end{Answer}

    \begin{Example}
        Prove that Paulinho is smart.
    \end{Example}
    \begin{Answer}
        All ducks are smart. Paulinho is a duck. Therefore, Paulinho is smart.
    \end{Answer}

    \chapter{My second set of exercises}
    \begin{Example}
        Prove that Paulinho is smart.
    \end{Example}
    \begin{Answer}
        All ducks are smart. Paulinho is a duck. Therefore, Paulinho is smart.
    \end{Answer}

    \begin{Example}
        Prove that Paulinho is smart.
    \end{Example}
    \begin{Answer}
        All ducks are smart. Paulinho is a duck. Therefore, Paulinho is smart.
    \end{Answer}
\end{document}

I hope this is the output you are looking for:

A: Using the xsim package with tcolorbox (questions and answers stolen from CarLaTeX's answer):
\documentclass{article}
\usepackage{xsim,tcolorbox,needspace}

\xsimsetup{
  exercise/within = section ,
  exercise/the-counter = \thesection.\arabic{exercise} ,
  exercise/template = cyan-box ,
  exercise/name = Example ,
  solution/template = red ,
  solution/print = true
}

\DeclareExerciseEnvironmentTemplate{cyan-box}
  {%
    \begin{tcolorbox}[arc=0mm,boxrule=1pt,colback=white,colframe=cyan,leftrule=3mm]
      \textsf{%
        \MakeUppercase{%
          \XSIMmixedcase{\GetExerciseName}~\GetExerciseProperty{counter}%
        }%
      }%
      \GetExercisePropertyT{subtitle}{ \textit{#1}}%
      \quad
  }
  {\end{tcolorbox}}

\DeclareExerciseEnvironmentTemplate{red}
  {%
    \par
    \Needspace*{2\baselineskip}
    \noindent
    \textsf{\textcolor{red}{\MakeUppercase{\XSIMmixedcase{\GetExerciseName}}}}%
    \quad
  }
  {\par\bigskip}

\begin{document}

\section{My first set of exercises}
\begin{exercise}
  Prove that $\frac{1}{2}\Delta(f_{ij}f^{ij})
  =\nabla^{k}f^{ij}+f^{ij}f^{k}[2\nabla_{i}R_{jk}-\nabla_{k}R_{ij}]$
\end{exercise}
\begin{solution}
  From \dots
\end{solution}

\begin{exercise}
  Prove that Paulinho is smart.
\end{exercise}
\begin{solution}
  All ducks are smart. Paulinho is a duck. Therefore, Paulinho is smart.
\end{solution}

\begin{exercise}
  Prove that Paulinho is smart.
\end{exercise}
\begin{solution}
  All ducks are smart. Paulinho is a duck. Therefore, Paulinho is smart.
\end{solution}

\section{My second set of exercises}
\begin{exercise}
  Prove that Paulinho is smart.
\end{exercise}
\begin{solution}
  All ducks are smart. Paulinho is a duck. Therefore, Paulinho is smart.
\end{solution}

\begin{exercise}
  Prove that Paulinho is smart.
\end{exercise}
\begin{solution}
  All ducks are smart. Paulinho is a duck. Therefore, Paulinho is smart.
\end{solution}

\end{document}


text:
Q: GridBagLayout Constraints not being respected once one of the JPanel has Content added to it Trying to figure out how to keep the size ratio between these two panels 3:1.
What is looks like when I simply add the two JPanels to the GridBagLayout with the right constraints:

And this is what the code looks like:
class MainPanel extends JPanel {

    MainPanel() {

        setLayout(new GridBagLayout());

        GridBagConstraints constraints = new GridBagConstraints();

        constraints.gridwidth = GridBagConstraints.RELATIVE;
        constraints.gridheight = GridBagConstraints.REMAINDER;
        constraints.weightx = 3;
        constraints.weighty = 1;
        constraints.fill = GridBagConstraints.BOTH;
        constraints.gridx = 0;
        constraints.gridy = 0;
        JPanel pane1 = new JPanel();
        pane1.setBackground(Color.GRAY);
        add(pane1, constraints);

        constraints.gridwidth = GridBagConstraints.REMAINDER;
        constraints.gridx = 3;
        constraints.gridy = 0;
        constraints.weightx = 1;
        JPanel pane2 = new JPanel();
        pane2.setBackground(Color.DARK_GRAY);
        add(new RightPanel(), constraints);
    }
}

But then, once I start adding things like JButtons or JLabels in the right Panel, the 3:1 ratio is completely forgotten and the right Panel seems to take an arbitrary amount of space, no matter how small I make the objects inside of it.
Here's what it looks like:

And this is what the code looks like:
class RightPanel extends JPanel {

    class ComboPanel extends JPanel {

        ComboPanel(String labelText) {
            JTextField textField = new JTextField();

            textField.setPreferredSize(new Dimension(80, 30));
            add(new JLabel(labelText));
            add(textField);

        }
    }

    RightPanel() {

        Box componentBox = Box.createVerticalBox();

        add(componentBox);

        JLabel currentPosX = new JLabel("Current X position: ( X )");
        currentPosX.setAlignmentX(Component.CENTER_ALIGNMENT);

        JLabel currentPosY = new JLabel("Current Y position: ( Y )");
        currentPosY.setAlignmentX(Component.CENTER_ALIGNMENT);

        Box positionBox = Box.createVerticalBox();

        positionBox.add(currentPosX);
        positionBox.add(Box.createRigidArea(new Dimension(0, 5)));
        positionBox.add(currentPosY);
        positionBox.add(Box.createRigidArea(new Dimension(0, 10)));
        positionBox.setBackground(Color.LIGHT_GRAY);
        positionBox.setOpaque(true);

        componentBox.add(positionBox);

        componentBox.add(Box.createRigidArea(new Dimension(0, 5)));

        ComboPanel comboPanelX = new ComboPanel("Target X Position: ");
        comboPanelX.setAlignmentX(Component.CENTER_ALIGNMENT);
        componentBox.add(comboPanelX);

        componentBox.add(Box.createRigidArea(new Dimension(0, 5)));

        ComboPanel comboPanelY = new ComboPanel("Target Y Position: ");
        comboPanelY.setAlignmentX(Component.CENTER_ALIGNMENT);
        componentBox.add(comboPanelY);

        componentBox.add(Box.createRigidArea(new Dimension(0, 5)));

        JButton commandButton = new JButton("Move");
        commandButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        componentBox.add(commandButton);

    }
}

I'd like to know if there's a way to add stuff to the JPanel on the right without screwing up the size ratio between the two main Panels.


text:
Q: How to get Android Material TextInputLayout startIcon View? Is there a way to get a reference to the Android Material Library TextInputLayout startIcon's View? TextInputLayout.startIconDrawable only gets the Drawable, not the View. I'm trying to animate this View, so I need a reference. Here's an example below, I would like a View reference to the heart icon.

A: You can access the startIcon of the TextInputLayout using its resource identifier name to get the resource integer id using getIdentifer() of the Resources class.
The identifier name of the TextInputLayout is text_input_start_icon
To get the id of startIcon:
Kotlin
val startIconViewId = resources.getIdentifier("text_input_start_icon", "id", packageName)

Java
int startIconViewId = getResources().getIdentifier("text_input_start_icon", "id", getPackageName());

And to get the view itself (which is CheckableImageButton) to make your animation:
Kotlin
val textInputLayout = findViewById<TextInputLayout>(R.id.my_text_input_layout)
val startIcon: CheckableImageButton = textInputLayout.findViewById(startIconViewId)

Java
TextInputLayout textInputLayout = findViewById(R.id.my_text_input_layout);
CheckableImageButton startIcon = textInputLayout.findViewById(startIconViewId);

Note: To use this procedure you must set app:startIconDrawable in TextInputLayout in your layout.
Demo of my test:


text:
Q: Corona audio bug on mac? audio.setMaxVolume( ) not working on mac? audio.setMaxVolume( volume, options ) not working on mac in corona simulator, I haven't tested it on the actual iOS device yet though It works perfectly on windows and Android device:
audio.setMaxVolume( 0, { channel=1 } )

Has anyone else encountered such a bug in Corona?
I have tested it on the actual device now iphone-4S - and it is working... Still not working in simulator on mac though.

A: Firstly, is the simulator outputting an error to the terminal?
Secondly, the setMaxVolume method returns true on success and false otherwise. So try:
local volumeSet = audio.setMaxVolume( 0, { channel=1 } )
print("Volume set? "..tostring(volumeSet))

This will let you know if Corona thinks it has worked.
NB: The corona documentation 'gotcha' says there is no max volume for the master volume, which means the device itself can set the volume to whatever the user tells it, but you can limit your app's sounds. Source


text:
Q: Parallel `for` loop with an array as output How can I run a for loop in parallel (so I can use all the processors on my windows machine) with the result being a 3 dimension array? The code I have now takes about an hour to run and is something like:
guad = array(NA,c(1680,170,15))
for (r in 1:15)
{
  name = paste("P:/......",r,".csv",sep="")
  pp = read.table(name,sep=",",header=T)
    #lots of stuff to calculate x (which is a matrix)
  guad[,,r]= x  #
}

I have been looking at related questions and thought I could use foreach but I couldn't find a way to combine the matrices into an array.
I am new to parallel programming so any help will be very much appreciated!

A: You could do that with foreach using the abind function.  Here's an example using the doParallel package as the parallel backend which is fairly portable:
library(doParallel)
library(abind)
cl <- makePSOCKcluster(3)
registerDoParallel(cl)
acomb <- function(...) abind(..., along=3)
guad <- foreach(r=1:4, .combine='acomb', .multicombine=TRUE) %dopar% {
  x <- matrix(rnorm(16), 4)  # compute x somehow
  x  # return x as the task result
}

This uses a combine function called acomb that uses the abind function from the abind package to combine the matrices generated by the cluster workers into a 3 dimensional array.
In this case, you can also combine the results using cbind and then modify the dim attribute afterwards to convert the resulting matrix into a 3 dimensional array:
guad <- foreach(r=1:4, .combine='cbind') %dopar% {
  x <- matrix(rnorm(16), 4)  # compute x somehow
  x  # return x as the task result
}
dim(guad) <- c(4,4,4)

The use of abind is useful since it can combine matrices and arrays in a variety of ways.  Also, be aware that resetting the dim attribute may cause the matrix to be duplicated which could be a problem for large arrays.
Note that it's a good idea to shutdown the cluster at the end of the script using stopCluster(cl).


text:
Q: Checkbox filter using Mysql and PHP In my application there is a filter option with checkboxes.Checkboxes indicates top five categories and all other categories under another single checkbox.That means total I have six checkboxes(top five + other).When all checked which will fetch all values from database table and when all unchecked which never fetch any values from table.Please anybody give any suggestions for my unchecked case...What will be the condition there?

A: In the unchecked case i wouldn't do a mysql query - cause it is not necessary and you can save that time. Depending on your application and your code you need to implement a switch here and insert the result on your page as if no result (or entry) has been found. For further details more application code is needed.


text:
Q: xhtml transitional vs strict? iframes are not supported in xhtml strict. However, in my application I am using php recaptcha which requires the use of iframes.  What are the downsides of just switching to xhtml transitional (if any)?

A: Has hobbs said, there is no practical downside. However, theoretically the strict DTD is more "future-proof".
Here's a link to a quick fix in PHP that will make recaptcha valid XHTML 1.0 Strict:
http://www.boriel.com/2009/07/29/xhtml-strict-valid-recaptcha/

A: Nothing, really. In practical terms, when it comes to browser compatibility, functionality, and tool/generator friendliness, XHTML 1.0 Transitional (following the "HTML compatibility" guidelines and served as text/html) is your best bet.

A: Here you have an small comparison that can help you regarding each type of document.
But in "practical" terms if you want to keep your site using strict, why just add the iframe. the only issue with this is that page wont be correctly validated

A: At the time HTML4 was written, it was thought that iframes would be phased out in future.
However, that was a long time ago, and it looks like that is no longer the case.  Thus, you could say that the 'strict' subset is no longer as accurate a representation of the future of HTML/XHTML as it once was.
Use transitional if there's a reason you need some of its features, but have a good understanding about which features are 'deprecated' and in general avoid them where there's a better alternative.
Note that browser support for transitional features implemented today probably isn't going to disappear in my lifetime.  Backward compatibility has proven a tough nut to crack on the web.


text:
Q: connecting vs code to gcp cloudshell via ss I'm trying to connect vscode to cloud shell through ssh.  I found the following article https://medium.com/@alex.burdenko/vs-code-happens-to-be-my-favorite-code-editor-and-ive-been-lucky-to-participate-so-many-diverse-952102856a7a.  I followed all the steps and I'm able to ssh via the command line.  However when I try to ssh via vscode I get an error.
This is what I have specified in the config file
Host tmp_user@35.186.145.21
   Port 6000
   ForwardAgent yes
   HostName tmp_user@35.186.145.21
   User tmp_user
   IdentityFile ~/.ssh/google_compute_engine

When I execute gcloud alpha cloud-shell ssh --dry-run I get the following
/user/bin/ssh -t -p 6000 -i /home/tmpus/.ssh/google_compute_engine -o StrictHostKeyChecking=no tmp_user@35.186.145.21 -- DEVSHELL_PROJECT_ID=myprj 'bash -l'

A: Google's Cloud Code extension for VS Code should automatically connect you to Cloud Shell via SSH.  You can use one of the documented links here to automatically install the extension and open a sample or you can install Cloud Code directly from the marketplace and utilize the command palette (ctrl/cmd-shift-p) to run Cloud Code: Open in Cloud Shell....  This will also create the requisite entry in your host file but please keep in mind that IPs, host names, etc are temporary and only valid while the instance of your Cloud Shell session is live.  This is likely the reason your connection fails with access is denied.

A: Remove "tmp_user@" from the HostName field.
Try this:
Host tmp_user@35.186.145.21
   Port 6000
   ForwardAgent yes
   HostName 35.186.145.21
   User tmp_user
   IdentityFile ~/.ssh/google_compute_engine

A: When you create cloud shell with
gcloud cloud-shell ssh --authorize-session --dry-run

In the answer you have something like this:
/usr/bin/ssh -t -p 6000 -i /home/tmp_user/.ssh/google_compute_engine -o StrictHostKeyChecking=no tmp_user@35.186.145.21 -- DEVSHELL_PROJECT_ID=XXXXXXXX 'bash -l'
So you add StrictHostKeyChecking parameter (UserKnownHostsFile /dev/null because it's temporary).
Your config file is like this:
Host tmp_user@35.186.145.21
    Port 6000
    ForwardAgent yes
    HostName 35.186.145.21
    User tmp_user
    StrictHostKeyChecking no
    UserKnownHostsFile /dev/null
    IdentityFile ~/.ssh/google_compute_engine


text:
Q: Drawing a model from different viewpoints on HTML5  Well this is for a project I chose to do for my computer graphics class - drawing a grand piano that can be viewed from different angles.
I haven't yet begun the work, and I just completed lynda.com course on HTML5:Graphics and Animation with Canvas. I can see how one could make a cube, or a ball, those sorts of simple figures. But I don't know how I should proceed on my project. Defining each small surface one by one, sure will be very tedious. Should I learn some more? WebGL or something else? Or is the 'tedious' way an 'okay' way? What would you suggest?

A: "The different angles" implies that you want to model and render a three dimensional object.
Here is one recipe to success:

*

*Design your model (grand piano) in any open source and free modelling application, like Blender

*Then, learn basics of Three.js or similar WebGL framework which simplifies the complex process of rendering a 3D scene

*Export your model from Blender and import it to your Three.js JavaScript.
It is possible to render objects to <canvas> on Three.js without WebGL, but using WebGL backend simplies the process a lot and I highly recommend  sticking with WebGL.
Here are is one of Three.js examples showing some modeled cars from different angles (cameras).
HTML5 Canvas API is mostly useful for 2D graphics and does not suit for your purpose very well, as you have noticed with its limitations.

A: Use WebGL, Three.js aims to be very accessible. www.udacity.com have a course on 3d graphics that uses Three.js that is very good for beginning.
Real-time 3D graphics is basically about creating a 2d image that re-creates that effect of a 3d perspective and can be updated in real-time.
Going about this in a brute force way won't teach you anything about how this effect is achieved.


text:
Q: Does using pseudo elements like :first-child or :last-child I firstly say that i don't know anything about how css rules are assigned to DOM elements by browser, so that my question is more around it, but i got wondering this in this particular situation I got into, so I use it for formalizing my curiosity:
I do have an HTML snippet like this:

I'd like to be blue

I am quite
self confident
 about my styles

I'd like to be biig

The text's content of the divs tries to describe my requirements: The first div MUST be blue, the second one i don't care because I will probably use inherited properties or I will set through js or whatever.
The p should be bold,
So I want to assign styles to do that, and I do something like this:
section div {
 color: blue;
}

section p {
 font-weight: bold;
}

And that obviously works as expected. But, CSS has nice features to target more specific elements. So I could do, for doing the same thing:
section > div:first-child {
 color: blue;
}

section > p {
 font-weight: bold;
}

This will affect only elements that are direct children of the section, and only the first div of the set, so that i will have the same result, but selecting elements more specifically.
I wonder if this helps browsers assigning css rules to elements.
I think that at some level the browser check for each DOM element the css' rules that target it, and if it finds matches (a css class is actually targeting it), it checks for conflicts and performs overriding if needed.
Would excluding elements from that sets, by targeting them more specifically help the browser to assign style (increase performance or decrease) ?
If it increases, is it meaningful or it is so little that everyone ignores it ?
If it decreases, how much and why ?
Thanks for any advice.

A: According to this article from Mozilla Development Network, the more specific your selectors are, the better. So if you do not bother how many divs get colored blue, the general selector section div is better. The longer your selector chain is, the harder it is for the browser to find that element since it needs to match more things. The most performant option in this case would actually assigning a class named for example .blue to the div you want blue.
The element>element (direct child) selector is more performant than the element element (descendand) selector in the sandbox but will probably force you to write a longer selector chain if you wish to overwrite it at another point.
To answer your question, in your example (at least in a nutshell), the overall performance will probably decrease by a little (meaningless) bit since pseudo-elements like :first-child are the least performant selectors and you furtherly have a longer selector chain.
If you actually asked me which of those to use in a project with more than just six lines of css, I'd encourage you to use the first example aswell since it's much more easy to overwrite and reuse.


text:
Q: Creating a Model I want to create a model called 'Persona' (which belongs_to model User). The user chooses a name in a form and then clicks the create button, so I need the attribute 'name' in the Persona model. I also want the Persona model to have a lower case version of the persona's name, so I need a second attribute 'downcase_name'. For example, the user may choose the persona's name to be Fooey Barman, so the downcase_name would be fooey barman.
My questions is, how do you initialise the downcase_name attribute? Do you put it in the Persona controller? In the new or create methods? Something like:
def create
  @persona = Persona.new(persona_params)
  @persona.downcase_name = @persona.name.downcase
  if @persona.save
    flash[:success] = "Welcome, " + @persona.name
    redirect_to @persona
  else
    render 'new'
  end
end

Or do you put it in the model?
class Persona < ActiveRecord::Base
  before_create :make_downcase_name
  validates :name, presence: true, length: { maximum: 50 }
  private
    def make_downcase_name
      self.downcase_name = name.downcase
    end
end

Or perhaps like this?
class Persona < ActiveRecord::Base
  validates :name, presence: true, length: { maximum: 50 }
  validates :downcase_name, presence: true
end

EDIT:
So, am I right in thinking the way to do it is in the model, with a before_save and a validation, like this?:
class Persona < ActiveRecord::Base
  before_save :make_downcase_name
  validates :name, presence: true, length: { maximum: 50 }
  validates :downcase_name, presence: true
  private
    def make_downcase_name
      self.downcase_name = name.downcase
    end
end

A: The use of the before_* callback seems pretty idiomatic. Alternatively, you can also have a service object created in the controller (say PersonaCreator) that would handle the logic and set the appropriate attributes on the model.
Note that before_create will be called only once, meaning that if the user changes the persona's name later, the callback will not be called. You might want to do something like before_save and check whether the name has been changed.


text:
Q: Calculate difference between times in results SQL I have a table with results:
C_EventTime        L_TID
20130228162022     27200
20130228162059     27200

How would I calculate difference in seconds between the two?
In the end, I need to calculate all the differences to make a total for the month.
I've tried:
declare @startdt  '20130228162022'
declare @enddt    '20140101000001'

set @startdt =  cast('20130101000001' as datetime)
set @enddt   =  cast('20140101000001' as datetime)

SELECT DATEDIFF(C_EventTime) FROM tTerminalStateLog
WHERE C_EventTime BETWEEN @startDate and @endDate
and L_TID = 27200

but suspect with my limited SQL knowledge I'm way off! Any help appreciated.
Tx

A: The strings you are using, don't convert nicely to a valid datetime format.
Credit to http://rdineshkumar.wordpress.com/tag/how-to-convert-yyyymmddhhmmss-to-datetimedatetime-in-sql-server/ for the formula here.
First off, DATEDIFF() takes 3 arguments.  The return value, be it seconds, days, etc.  Then the start/end dates.  Ex DATEDIFF(SS,startdate,enddate) Doc.
Here is a sample on how to convert your two start/end values to a datetime, and calculate the difference between them.
declare @startdt datetime
declare @enddt datetime

select @startdt =
Convert(time,Dateadd(SECOND,
        Right('20130228162022',2)/1,
        Dateadd(MINUTE,
                Right('20130228162022',4)/100,
                Dateadd(hour,
                        Right('20130228162022',6)/10000,
                        '1900-01-01')))) +
convert(datetime,LEFT('20130228162022',8))

select @enddt =
Convert(time,Dateadd(SECOND,
        Right('20140101000001',2)/1,
        Dateadd(MINUTE,
                Right('20140101000001',4)/100,
                Dateadd(hour,
                        Right('20140101000001',6)/10000,
                        '1900-01-01')))) +
convert(datetime,LEFT('20140101000001',8))

select @startdt, @enddt
select DATEDIFF(ss, @startdt, @enddt)

However your table shows the values split into separate rows...  This makes it slightly more complicated.
Assuming you have 2 results per L_Tid (no more, or this won't work) and you always want to compare the oldest-to-newest date (they'll never write backwards), you could do this:
declare @tTerminalStateLog table (C_EventTime varchar(15), L_Tid INT)

insert into @tTerminalStateLog
select '20130228162022',27200 union all
select '20130228162059',27200

declare @startdt varchar(15), @enddt varchar(15)
set @startdt = '20130228162022'
set @enddt =  '20140101000001'

; with datesdata as
(
SELECT Convert(time,Dateadd(SECOND,
        Right(C_EventTime,2)/1,
        Dateadd(MINUTE,
                Right(C_EventTime,4)/100,
                Dateadd(hour,
                        Right(C_EventTime,6)/10000,
                        '1900-01-01')))) +
        convert(datetime,LEFT(C_EventTime,8)) myDate,
        L_Tid,
        ROW_NUMBER() over(order by C_EventTime) as myID
FROM @tTerminalStateLog
WHERE C_EventTime BETWEEN @startdt and @enddt
and L_Tid=27200
)

select d1.myDate, d2.myDate, DATEDIFF(ss, d1.myDate, d2.myDate) [sec_diff]
from datesdata d1
left outer join datesdata d2
   on d1.L_Tid=d2.L_Tid
   and d2.myID=2
where d1.myID=1


text:
Q: Fourier Transform Problem - having trouble getting answer in the back of the book I'm working on the following problem:

Compute the Fourier transform of the function $f(x) = \begin{cases} -1 & \text{if}\,-2<x<-1 \\ 2 & \text{if}\,\,0<x<2 \\ 0 & \text{otherwise}  \end{cases}$.

First, I checked to make sure $f \in L^{2}(-\infty, \infty)$:
$\displaystyle \begin{align}\int_{-\infty}^{\infty} (f(x))^{2}dx = \int_{-2}^{-1}(-1)^2 dx + \int_{0}^{2} (2)^{2} dx = \left[x \right]_{-2}^{-1} + \left[4x \right]_{0}^{2} \\= -1 - (-2) + (4(2) - 4(0))
= -1 + 2 + 8 = 9 < \infty \end{align}$
And it is, so then, using the definition of the Fourier transform: $\displaystyle F(\alpha) = \frac{1}{2 \pi}\int_{-\infty}^{\infty} f(x)e^{-i\alpha x} dx,$
I got $\displaystyle \begin{align} F(\alpha) = \frac{1}{2\pi} \int_{-2}^{-1}(-1) \cdot e^{-i\alpha x} dx + \frac{1}{2\pi}\int_{0}^{2}(2) \cdot e^{-i\alpha x}dx \end{align}$.
Then, letting $u = -i \alpha x$, $\displaystyle \frac{-du}{i \alpha} = dx$, this became
$\displaystyle \begin{align} -\frac{1}{2\pi}\frac{-1}{i \alpha}\left[\int e^{u}du\right]_{x=-2}^{x=-1} + \frac{2}{2\pi}\frac{-1}{i \alpha} \left[\int e^{u} du \right]_{x=0}^{x=2} = \frac{1}{2\pi \alpha i}\left[ e^{u} \right]_{x=-2}^{x=-1} - \frac{1}{\pi \alpha i} \left[e^{u} \right]_{x=0}^{x=2} \\ = \frac{1}{2\pi \alpha i}\left[ e^{-i\alpha x} \right]_{-2}^{-1} - \frac{1}{\pi \alpha i} \left[e^{-i \alpha x} \right]_{0}^{2} \\ =  \frac{1}{2\pi \alpha i}\left[ e^{-i\alpha (-2)} - e^{-i \alpha (-1)} \right] - \frac{1}{\pi \alpha i} \left[e^{-i \alpha (2)} - e^{-i \alpha (0)} \right] \\ = \frac{1}{2\pi \alpha i}\left[ e^{2 \alpha i} - e^{\alpha i} \right] - \frac{1}{\pi \alpha i} \left[e^{-2 \alpha i} - 1 \right]  \end{align}$.
But, the final answer given in the textbook is $\displaystyle F(\alpha) = \frac{2 e^{-i\alpha}\sin \alpha}{\pi \alpha} - \frac{\left(e^{\displaystyle \left(\frac{3i\alpha}{2}\right)}\right)\cdot \left(\sin \left( \displaystyle \frac{\alpha}{2}\right)\right)}{\pi \alpha}$.
How do I get my answer to look like the textbook's so that I know whether I'm doing it right?? I've been trying to do so for 3 hours now, but all I'm succeeding in doing is getting bogged down in the details of trig identities, and not even getting anywhere with those. How can you learn if you can't figure out whether you're doing something right? And how can you figure out whether you're doing something right when the solutions in the textbook are in such a difficult to obtain form?
That is, of course, assuming I am doing this right...
If I'm not computing the Fourier transforms correctly, please let me know and instruct me on the proper way of doing it.
If I am computing the Fourier transforms correctly, would you please demonstrate to me, in great detail, how I would go about putting my answers in the same form as they are in the back of the book? This is not homework, and you won't be preventing me from learning by showing me all the details worked out. If anything, due to the lack of examples of this type of problem I've seen so far, you'll be helping me learn. Then, I can apply these principles to other exercises in the textbook I want to work on as practice.
Thank you.

A: Using the hint given by Daniel Fischer that $\displaystyle \sin(z) = \frac{e^{iz}-e^{-iz}}{2i}$, and picking up where I left off in my question, I have that:
$\displaystyle \begin{align}= \frac{1}{2\pi \alpha i}\left[ e^{2 \alpha i} - e^{\alpha i} \right] - \frac{1}{\pi \alpha i} \left[e^{-2 \alpha i} - 1 \right] =  = \frac{1}{2\pi \alpha i}\left[ e^{2 \alpha i} - e^{\alpha i} \right] - \frac{1}{\pi \alpha i} \left[e^{-2 \alpha i} - e^{-0\alpha i} \right] \\ = \frac{1}{2\pi \alpha i}e^{2 \alpha i} - \frac{1}{2 \pi \alpha i}e^{\alpha i} - \frac{1}{\pi \alpha i} e^{-2 \alpha i} + \frac{1}{\pi \alpha i}e^{-0 \alpha i}  \\ = \frac{1}{2\pi \alpha i}e^{2 \alpha i} - \frac{1}{2 \pi \alpha i}e^{\alpha i} + \frac{2}{2\pi \alpha i}e^{-0 \alpha i} - \frac{2}{2\pi \alpha i} e^{-2 \alpha i} \\= \frac{1}{2\pi \alpha i}e^{2 \alpha i} - \frac{1}{2 \pi \alpha i}e^{\alpha i} + \frac{2}{2\pi \alpha i}\left[e^{-0 \alpha i} - e^{-2 \alpha i}\right] \\ = \frac{1}{2\pi \alpha i}e^{2 \alpha i} - \frac{1}{2 \pi \alpha i}e^{\alpha i} + \frac{2}{2\pi \alpha i}\left[e^{-\alpha i + \alpha i} - e^{-2 \alpha i}\right]\\ = \frac{1}{2\pi \alpha i}e^{2 \alpha i} - \frac{1}{2 \pi \alpha i}e^{\alpha i} + \frac{2}{\pi \alpha }e^{-\alpha i}\frac{\left[e^{ \alpha i} - e^{-\alpha i}\right]}{2i} \\ = \frac{1}{2\pi \alpha i}e^{2 \alpha i} - \frac{1}{2 \pi \alpha i}e^{\alpha i} + \frac{2}{\pi \alpha }e^{-\alpha i}\sin(\alpha)  \\= \frac{1}{2\pi \alpha i}e^{(3\alpha/2) i}\left(e^{(\alpha/2) i} - e^{-(\alpha/2) i}\right) + \frac{2}{\pi \alpha }e^{-\alpha i}\sin(\alpha) \\= \frac{1}{2\pi \alpha i}e^{(3\alpha/2) i}\left(- e^{-(\alpha/2) i} + e^{(\alpha/2) i} \right) + \frac{2}{\pi \alpha }e^{-\alpha i}\sin(\alpha)\\  = \frac{-1}{\pi \alpha }e^{(3\alpha/2) i}\left(\frac{ e^{-(\alpha/2) i} - e^{(\alpha/2) i}}{2i} \right) + \frac{2}{\pi \alpha }e^{-\alpha i}\sin(\alpha) \\  = \frac{-1}{\pi \alpha }e^{(3\alpha/2) i}\sin(\alpha/2)  + \frac{2}{\pi \alpha }e^{-\alpha i}\sin(\alpha) \\ = \frac{2e^{-\alpha i}\sin(\alpha) }{\pi \alpha }- \frac{e^{(3\alpha/2) i}\sin(\alpha/2) }{\pi \alpha }.\end{align}$

A: In the last of your passages, for each of the two differences of exponentials,  take the average (half sum) of the exponents (call it $m$) and deviation (half difference = $d$) and then express each of them as $m \pm d$. Factorize $e^m$, the other factor is a $\sin$. That's all.
You made a sign mistake at $$\left[ {e^{ - i\alpha x} } \right]_{x =  - 2}^{x =  - 1}  = e^{i\alpha }  - e^{i2\alpha }
$$, correct that, apply what suggested above, and you'll get the right result.


text:
Q: Try to broadcast video to multiple clients using cheroot flask and opencv I am trying to create a video streaming from my Raspberry Pi to multiple clients. Flask does not support WSGI server so i use the cheroot.wsgi Server. i have created a ddns server using noip in order to broadcast the video stream over the internet. Till now i manage to serve the video only to one client even if i use a wsgi server.
Here is the video feeder
from flask import Flask, render_template, Response
from camera import VideoCamera
import RPi.GPIO as gpio

gpio.setmode(gpio.BCM)
gpio.setup(21, gpio.OUT)

app = Flask(__name__)

def gen(camera):
    while True:
        frame = camera.get_frame()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/video_feed')
def video_feed():
    return Response(gen(VideoCamera()),mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/background_process_test')
def background_process_test():
    gpio.output(21, gpio.HIGH)

    print ("Hello")
    return ("nothing")

@app.route('/background_process_test2')
def background_process_test2():
    gpio.output(21, gpio.LOW)

    print ("Hello")
    return ("nothing")

if __name__ == '__main__':
    app.run()

here is the wsgi server using cheroot
try:
    from cheroot.wsgi import Server as WSGIServer, PathInfoDispatcher
except ImportError:
    print("OK")
    from cherrypy.wsgiserver import CherryPyWSGIServer as WSGIServer, WSGIPathInfoDispatcher as PathInfoDispatcher
from main import app
d = PathInfoDispatcher({'/': app})
server = WSGIServer(('0.0.0.0', 5000), d)
if __name__ == '__main__':
    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()

The opencv module that captures the camera frames
import cv2

class VideoCamera(object):
    def __init__(self):
        # Using OpenCV to capture from device 0. If you have trouble capturing
        # from a webcam, comment the line below out and use a video file
        # instead.
        self.video = cv2.VideoCapture(0)
        self.video.set(cv2.CAP_PROP_FRAME_WIDTH, 160)
        self.video.set(cv2.CAP_PROP_FRAME_HEIGHT, 200)
        # If you decide to use video.mp4, you must have this file in the folder
        # as the main.py.
        # self.video = cv2.VideoCapture('video.mp4')

    def __del__(self):
        self.video.release()

    def get_frame(self):
        success, image = self.video.read()
        # We are using Motion JPEG, but OpenCV defaults to capture raw images,
        # so we must encode it into JPEG in order to correctly display the
        # video stream.
        ret, jpeg = cv2.imencode('.jpg', image)
        return jpeg.tobytes()

finally the web page that serves the video feed
<!doctype html>

    <title>jindeath</title>

hello

Test

        <form>

            <button class='btn btn-default'>Test</button>
            <button class='btn btn-default'>Test</button>

        </form>

Further more when more than one devices connect to the page my rpi uses 100% of its cpu. any suggestions


text:
Q: Chart Macro In User Macro With Dynamic Content I was trying to use the Chart macro inside user macro by using the following code,
## @noparams
<ac:structured-macro ac:name="chart">
              <ac:parameter ac:name="type">line</ac:parameter>
              <ac:parameter ac:name="Tables">Sample</ac:parameter>
</ac:structured-macro>

<table id="sample">

                 ... body goes here...

</table>

I am getting No Data Available in my confluence page. How can I provide the data to a chart macro dynamically?

A: Andre from atlassian community answered my question. We can make use of <ac:rich-text-body> tag to provide the table. Syntax is following,
<ac:structured-macro ac:name="chart">
     <ac:parameter ac:name="type">line</ac:parameter>
     <ac:rich-text-body>
         here goes the table
     </ac:rich-text-body>
</ac:structured-macro>

Full discussion is available in this url.


text:
Q: jQueryMobile: Button action not getting called The code below tries to implements a button action in jQueryMobile,but it is not working for me. Please let me know where I am wrong.Everything is written in a HTML file.
I am facing some problem in providing my code here. Here is what I am trying.
In standard HTML format, I am writing the below code between script tags
$('#theButton').click(function() {
   alert('The Button has been clicked,');

});

And in the body tag ---

    <input type="button" id="theButton" name="theButton" value="The Button">

But the action is not getting called.

A: EDIT: Please try the code below:

<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />

    <input type="button" id="theButton" name="theButton" value="The Button">


text:
Q: How to get a date object from a different timezone in utc format in js I am located in the PDT timezone. When I type in new Date() into the browser's console, I get Tue Aug 31 2021 09:43:15 GMT-0700 (Pacific Daylight Time).
Now, I want the date in the same format from the central time region.
So I want the time object to look like this: Aug 31 2021 11:43:15 GMT-0500 (Central Daylight Time)
I've been reading the docs about Intl, Intl.DateTimeFormat() and toLocalTimeString() but can't seem to find it.
I tried new Date().toLocaleString(undefined, { timeZone: "US/Central" }) which gives me "8/31/2021, 11:46:30 AM", which is correct but not the right format.
I tried new Intl.DateTimeFormat('en-US', { dateStyle: 'full', timeStyle: 'long', timeZone:"US/Central" }).format(new Date()) which also gives me a string and not a date object in UTC format.
What am I doing wrong?

A: Date in JS is a tricky issue - I agree 100% with you:
I did it once the hard way:

*

*splitting the resulting date object into parts

*concat all the parts according to my desired custom format

Maybe not the most elegant way, but it worked.
Any suggestions from other contributors are very welcome.
Edit:
Added let oTZPartsReduced = ... in reply to valuable comment from @RobG

let myTimeZone = new Date();
console.log(myTimeZone);
//console.log((myTimeZone.getTimezoneOffset()/60).toFixed(2));

// oTZ = otherTimeZone  (to keep it short)
let oTZ = new Date(myTimeZone).toLocaleString("en-US", {timeZone: "US/Central"});

let oTZFormatted;

let oTZParts = new Intl.DateTimeFormat('en', {
  weekday: 'short',
  day:'2-digit',
  month: 'short',
  year: 'numeric',
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit',
  timeZone: 'US/Central' // <-- here it goes, your wished timeZone
}).formatToParts(new Date(myTimeZone));

oTZFormatted = oTZParts[2].value + ' ' + oTZParts[4].value + ' '+ oTZParts[6].value + ' '+ oTZParts[8].value + ':'+ oTZParts[10].value + ':'+ oTZParts[12].value + ' GMT-0500 (Central Daylight Time)';

// order within above array could vary due to language as @RobG stated - thanks
// hence following reduced version of above array:
let oTZPartsReduced = oTZParts.reduce((acc, part) => {
  if (part.type != 'literal') {
    acc[part.type] = part.value;
  }
  return acc;
}, Object.create(null));

oTZFormatted = oTZPartsReduced.month + ' ' + oTZPartsReduced.day + ' '+ oTZPartsReduced.year + ' '+ oTZPartsReduced.hour + ':'+ oTZPartsReduced.minute + ':'+ oTZPartsReduced.second + ' GMT-0500 (Central Daylight Time)';

console.log(oTZFormatted);
console.log('Array of Parts for reference:');
console.log(oTZParts);
console.log('Object (reduced) of Parts for reference:');
console.log(oTZPartsReduced);


text:
Q: Heroku, R and Gdal So my app suddenly stopped working and after investigation it seems that the problem came from the fact that leaflet wasn't being installed correctly when the app was being deployed and this was due to the fact that basically Heroku does not support gdal. The error I was getting while the app was being built was checking for gdal-config... no.
I went to the GitHub of the R buildpack (https://github.com/virtualstaticvoid/heroku-buildpack-r) and it said I need to containerize the app, so I did.
I did what was said in the following link (https://github.com/virtualstaticvoid/heroku-docker-r) and in my dockerfile I added some comands so my docker file looks like this:
FROM virtualstaticvoid/heroku-docker-r:shiny
ENV PORT=8080
RUN apt-get update &&\
    apt-get install -y libcurl4-openssl-dev libssl-dev binutils libproj-dev proj-bin libgdal-dev gdal-bin
CMD ["/usr/bin/R", "--no-save", "--gui-none", "-f", "/app/run.R"]

Sadly, I still get the same error.
Furthermore I cannot download the openssl module and I have no idea how to implement/try the handful of answers I found online:
Using PKG_CFLAGS=
--------------------------- [ANTICONF] --------------------------------
Configuration failed because openssl was not found. Try installing:
 * deb: libssl-dev (Debian, Ubuntu, etc)
 * rpm: openssl-devel (Fedora, CentOS, RHEL)
 * csw: libssl_dev (Solaris)
 * brew: openssl@1.1 (Mac OSX)
If openssl is already installed, check that 'pkg-config' is in your
PATH and PKG_CONFIG_PATH contains a openssl.pc file. If pkg-config
is unavailable you can set INCLUDE_DIR and LIB_DIR manually via:
R CMD INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'
-------------------------- [ERROR MESSAGE] ---------------------------
tools/version.c:1:10: fatal error: openssl/opensslv.h: No such file or directory
    1 | #include <openssl/opensslv.h>
      |          ^~~~~~~~~~~~~~~~~~~~
compilation terminated.

I need help please.
EDIT:
I think that the problem comes from the fact that I am istalling the libraries after building the image from docker (this image installs R without installing the libgdal, gdal-config,... packages) so these need to be installed before the FROM statement or I need to build an image of my own (no idea how to) or the person needs to do update his image so that it supports gdal and openssl.

A: As you guessed, the issue is that the libgdal-dev dependency isn't installed prior to the rgdal R package being installed.
heroku-docker-r makes provision for this with an "Aptfile" to specify dependencies to be installed (as per Applications with Additional Dependencies in the documentation).
I've created an example project, heroku-docker-r-rgdal-example to show how to structure the project with the required files etc.


text:
Q: How to mention multiple projections in MapServer MAPFILE? Is there a way to mention multiple projection systems / spatial reference systems in MapServer's (ms4w 3.0.3) MAPFILE? For example for Malaysia - GIS data could lie across three spatial references WGS 84 / UTM zone 47N, WGS 84 / UTM zone 48N and WGS 84 / UTM zone 49N. The GIS data stored in Oracle DB has no SRID mentioned and each layer may consist of data that may lie in any of the above mentioned 3 spatial references. Is there a way we can dynamically project GIS data through mapfile?
Regards,
Shiva

A: Yes you can configure multiple projections that your service will support in your map file, as part of the METADATA block of either your MAP in which case the projections apply to all layers, or in your LAYER in which case the projections apply to just that layer.
METADATA
  ...
  "WMS_SRS" "EPSG:4326 EPSG:3857 EPSG:27700 EPSG:4258"
  # Change above to meet your requirements
  ...
END

The reprojection is done by MapServer (not by the underlying data store).  In your map file you need to specify the projection your data is actual in (e.g. as it is within your data store) with the LAYER > PROJECTION block.

A: I suggest to store all data in lat/lon degrees.
Then you can decide later independently in which projection you want to display all or part of the data.
For areas stretching over several UTM zones, a lcc or Mercator projection sounds better.


text:
Q: Changing JSSOR Idle time dynamically Changing idle time dynamically doesn't work for me.
I try (as user 'jssor' suggested in other threads):

    ...

or

    ...

in which I change value 2000 by JS anytime, but without luck even after some more slides gone.
I need see change at current or next slide
jsfiddle example: https://jsfiddle.net/d80o10kb/1/


text:
Q: Axios GET Request Param with Whitespace Goal
I want to pass query params for a GET request using axios. The param value is a variable of type string and has whitespace.
Problem
It seems axios is encoding the param in a format that my backend does not understand. I have done research on axios encoding and it appears axios encodes whitespace to a + and not %20.
Example
Let's say you have this request:
 const whitespace = "white space";
 const encodeWhitespace = encodeURI(whitespace);
 const noSpace = "no";

 axios.get('/api', {
   params: {
     'foo': 'bar',
     'bar': 'hello world',
     'space': whitespace,
     'encode': 'hello%20world',
     'encoded': encodeWhitespace,
     'simple': noSpace
   }
}

The params foo, bar, encode, simple all work and generate a response with the correct data. The params space, encoded do not generate the correct data. The request is successful with 200 but returns no data.
I created the same request in Postman with the same queries to see if the GET returns the expected result and it does. I added the %20 in Postman and it returns just fine. I added the + in Postman and that returns the expected result as well.
Question
What might be going wrong with the variable implementation? I can't do it without the variable like the bar param because the value is being passed to a function (Redux action). Any ideas or thoughts on this would be helpful. Please comment if more information is needed.

A: Seems like this is an issue (or the default parameter serialization behavior) of Axios library.
So to overcome this, you have 2 options.

*

*Define your query params in the URL itself

const whitespace = "white space";
axios.get(`/api?space=${whitespace}`);

*Write your own paramsSerializer to build the query string.

const whitespace = "white space";
const encodeWhitespace = encodeURI(whitespace);
const noSpace = "no";

axios.get('/api', {
    params: {
        'foo': 'bar',
        'bar': 'hello world',
        'space': whitespace,
        'simple': noSpace
    },
    paramsSerializer: (params) => {
        // Sample implementation of query string building
        let result = '';
        Object.keys(params).forEach(key => {
            result += `${key}=${encodeURIComponent(params[key])}&`;
        });
        return result.substring(0, result.length - 1);
    }
});

Note: The above paramsSerializer can be defined in the global level or Axios instance level as well.

*

*Global level

axios.defaults.paramsSerializer = (params) => { /* ... */ };

*

*Instance level

let axInstance = axios.create({ paramsSerializer: (params) => { /* ... */ } })