text:
Q: Track acquisition channels for 302 redirects (/app) to app stores We created a smart link unblnd.com/app
This link detects the device: desktop, iphone, or android.
Depending on the device it goes to the main page or the specific app store.
The link is a 302 redirect which is not indexed.
Goal:
Include the /app redirect route within google analytics and track the acquisition channels
Ideas:

*

*change unblnd.com/sitemap.xml

*do not use redirect, just go the mainpage

*use google tag manager

*some third party

Is there some clean, easy approach which is considered best practice?
More info:
To create the redirect we use this Laravel controller method
routes/web.php
Route::get('/app', 'LandingController@app');

LandingController
public function app(Request $request)
    {
        if (!Agent::isMobile()) {
            return redirect('/');
        }
        else if(Agent::isAndroidOS()) {
            return Redirect::away(config('app.android_url'));
        }
        else if (Agent::isIphone()) {
            return Redirect::away(config('app.apple_url'));
        }
        return redirect('/');
    }

A: Okay, I believe we found a good answer!
We changed the controller method to always redirect to the main page, but with a query string param:
    public function app(Request $request)
    {
        if (!Agent::isMobile()) {
            return redirect('/?app=desktop');
        }
        else if(Agent::isAndroidOS()) {
            return redirect('/?app=android');
        }
        else if (Agent::isIphone()) {
            return redirect('/?app=iphone');
        }
        return redirect('/?app=desktop');
    }

When the main view in mounted in the browser it checks the query params and redirects if necessary:
    let app_url = false;
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('app') && urlParams.get('app') === 'android') app_url = "{{config('app.android_url')}}";
    if (urlParams.get('app') && urlParams.get('app') === 'iphone') app_url = "{{config('app.apple_url')}}";
    if (app_url) {
        window.location.href = app_url;
    }


text:
Q: Robo Script No suitable run configuration found want to create a robo script for test lab in firebase. When I click on Record Robo Script I get a prompt No suitable run configuration found in Andriod Studio.

i don't know how to fixx it..
how to generate robo scripr i am building flutter app

A: To launch Roboscript Recorder, you need to have an Android Application Run configuration - it's the same you create to launch your app in Android Studio. So, make sure you can launch your app in Android Studio, and Roboscript Recorder will be able to launch as well.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Firebreath NPAPI plugin rendering video to top level browser window (HWND) I am working on a audio/video rendering plugin that is using FireBreath and we have a need to get HTML elements to overlay on top of the video. I am aware that to do this I need to use the  windowless mode in FireBreath. However since I am using DirectX to render the video I cannot initialize DirectX with the HDC handle (it requires a HWND) that I get when I am instructed to render in windowless mode.
Also for other software security reasons I cannot render the video to an off-screen surface then Blt the bits to the HDC.
The alternative I was trying to accomplish is to use the Hardware Overlay feature in DirectX and use the browser's TOP level HWND to initialize DirectX, then use the HDC and coordinates to tell directX where in the TOP browser window to render the video frame. And render it directly to the top parent browser window.
I have tired a proof of concept, but I am seeing my video frames getting erased quite often after I draw them and thus the video appears to be flickering. I am trying to understand why that might be and I am wondering if this is not a viable solution given my parameters.
Also I am wide open to suggestions on how to accomplish this given my constraints.
Any help would be greatly appreciated!

A:
In the FireBreath-dev group, John Tan wrote:
As what I know, you practically have no control precisely when the screen is going to draw. What can only be done is:
1) Inform the browser to repaint by issuing the windowless invalidatewindow
2) browser draw event arrives with the hdc. Draw on the hdc

John is completely correct.  In addition, the HDC could potentially (perhaps likely will) be different each time your draw is called.  I don't know of anyone who has successfully gotten directx drawing using windowless mode, and you have absolutely no guarantee that what you are doing will ever work as even if you got it working the browser may change the way or order that it draws in in a way that would break it.
You might want to look at the async surface API; I don't know which browsers this works on but I suspect likely only Firefox and IE.  It was implemented in this commit.
I haven't used this at all, so I can't tell you how it works, but it was intended to solve exactly the problem you're describing.  Your main issue will be browser support.  What documentation there is is here.
Hope this helps


text:
Q: Insert dot after each words in string I need to realize method, which accept string and insert a dot (.) after each word. example:
Source string: "Hello! It is nice day today."
Result string: "Hello!. It. is. nice. day. today.."
How can I do that?

A: For the most part you can use String.Replace:
var dotted = "Your string".Replace(" ", ". ");

Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.

I'm sure you can elaborate from here to get your trailing period/any other nuances you find. (:

A: string.Join(".","Hello! It is nice day today.".Split(' '));

A: dotted = string.Join(". ","Hello! It is nice day today.".Split(' ')) + ".";

this should work, but the other 2 answers should get you pretty close.


text:
Q: JMeter 3.0 testplan doesn't work in non GUI mode The plan runs fine in GUI mode.
It also runs in non GUI-mode, but doesn't send proper(?) HTTP requests...
This is how I launch it:
sh jmeter.sh -n -t thread-test.jmx -l thread-test.csv
When running in the GUI the request is correct:
GET http://www.bing.com/

[no cookies]

Request Headers:
Connection: keep-alive
Host: www.bing.com
User-Agent: Apache-HttpClient/4.5.2 (Java/1.8.0_73)

But when run using non GUI-mode the request has no data to display:
No data to display
The sampler result looks like this:
Thread Name: Thread Group 1-1
Sample Start: 2016-11-01 15:24:04 CET
Load time: 141
Connect Time: 0
Latency: 141
Size in bytes: 85790
Headers size in bytes: 0
Body size in bytes: 0
Sample Count: 1
Error Count: 0
Data type ("text"|"bin"|""): text
Response code: 200
Response message: OK

Response headers:
SampleResult fields:
ContentType:
DataEncoding: null
Any idea? I'm stumped...
Here's the test plan:
 <?xml version="1.0" encoding="UTF-8"?>
<jmeterTestPlan version="1.2" properties="2.9" jmeter="3.0 r1743807">
  <hashTree>
    <TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="Test Plan" enabled="true">
      <stringProp name="TestPlan.comments"></stringProp>
      <boolProp name="TestPlan.functional_mode">false</boolProp>
      <boolProp name="TestPlan.serialize_threadgroups">false</boolProp>
      <elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
        <collectionProp name="Arguments.arguments"/>
      </elementProp>
      <stringProp name="TestPlan.user_define_classpath"></stringProp>
    </TestPlan>
    <hashTree>
      <ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Thread Group" enabled="true">
        <stringProp name="ThreadGroup.on_sample_error">stoptest</stringProp>
        <elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" testname="Loop Controller" enabled="true">
          <boolProp name="LoopController.continue_forever">false</boolProp>
          <stringProp name="LoopController.loops">1</stringProp>
        </elementProp>
        <stringProp name="ThreadGroup.num_threads">1</stringProp>
        <stringProp name="ThreadGroup.ramp_time">1</stringProp>
        <longProp name="ThreadGroup.start_time">1478003529000</longProp>
        <longProp name="ThreadGroup.end_time">1478003529000</longProp>
        <boolProp name="ThreadGroup.scheduler">false</boolProp>
        <stringProp name="ThreadGroup.duration"></stringProp>
        <stringProp name="ThreadGroup.delay"></stringProp>
      </ThreadGroup>
      <hashTree>
        <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Request" enabled="true">
          <elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" enabled="true">
            <collectionProp name="Arguments.arguments"/>
          </elementProp>
          <stringProp name="HTTPSampler.domain">www.bing.com</stringProp>
          <stringProp name="HTTPSampler.port"></stringProp>
          <stringProp name="HTTPSampler.connect_timeout"></stringProp>
          <stringProp name="HTTPSampler.response_timeout"></stringProp>
          <stringProp name="HTTPSampler.protocol"></stringProp>
          <stringProp name="HTTPSampler.contentEncoding"></stringProp>
          <stringProp name="HTTPSampler.path"></stringProp>
          <stringProp name="HTTPSampler.method">GET</stringProp>
          <boolProp name="HTTPSampler.follow_redirects">true</boolProp>
          <boolProp name="HTTPSampler.auto_redirects">false</boolProp>
          <boolProp name="HTTPSampler.use_keepalive">true</boolProp>
          <boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
          <boolProp name="HTTPSampler.BROWSER_COMPATIBLE_MULTIPART">true</boolProp>
          <boolProp name="HTTPSampler.image_parser">true</boolProp>
          <boolProp name="HTTPSampler.concurrentDwn">true</boolProp>
          <boolProp name="HTTPSampler.monitor">false</boolProp>
          <stringProp name="HTTPSampler.embedded_url_re"></stringProp>
        </HTTPSamplerProxy>
        <hashTree/>
        <ResultCollector guiclass="ViewResultsFullVisualizer" testclass="ResultCollector" testname="View Results Tree" enabled="true">
          <boolProp name="ResultCollector.error_logging">false</boolProp>
          <objProp>
            <name>saveConfig</name>
            <value class="SampleSaveConfiguration">
              <time>true</time>
              <latency>true</latency>
              <timestamp>true</timestamp>
              <success>true</success>
              true
              true
              <message>true</message>
              <threadName>true</threadName>
              <dataType>true</dataType>
              <encoding>false</encoding>
              <assertions>true</assertions>
              <subresults>true</subresults>
              <responseData>false</responseData>
              <samplerData>false</samplerData>
              <xml>false</xml>
              <fieldNames>true</fieldNames>
              <responseHeaders>false</responseHeaders>
              <requestHeaders>false</requestHeaders>
              <responseDataOnError>false</responseDataOnError>
              <saveAssertionResultsFailureMessage>true</saveAssertionResultsFailureMessage>
              <assertionsResultsToSave>0</assertionsResultsToSave>
              <bytes>true</bytes>
              <threadCounts>true</threadCounts>
              <idleTime>true</idleTime>
            </value>
          </objProp>
          <stringProp name="filename">/Users/jboive/Downloads/apache-jmeter-3.0/bin/thread-test.csv</stringProp>
        </ResultCollector>
        <hashTree/>
      </hashTree>
    </hashTree>
  </hashTree>
</jmeterTestPlan>

Here's the log:
2016/11/01 15:24:31 INFO  - jmeter.util.JMeterUtils: Setting Locale to en_US
2016/11/01 15:24:31 INFO  - jmeter.JMeter: Loading user properties from: /Users/jboive/Downloads/apache-jmeter-3.0/bin/user.properties
2016/11/01 15:24:31 INFO  - jmeter.JMeter: Loading system properties from: /Users/jboive/Downloads/apache-jmeter-3.0/bin/system.properties
2016/11/01 15:24:31 INFO  - jmeter.JMeter: Copyright (c) 1998-2016 The Apache Software Foundation
2016/11/01 15:24:31 INFO  - jmeter.JMeter: Version 3.0 r1743807
2016/11/01 15:24:31 INFO  - jmeter.JMeter: java.version=1.8.0_73
2016/11/01 15:24:31 INFO  - jmeter.JMeter: java.vm.name=Java HotSpot(TM) 64-Bit Server VM
2016/11/01 15:24:31 INFO  - jmeter.JMeter: os.name=Mac OS X
2016/11/01 15:24:31 INFO  - jmeter.JMeter: os.arch=x86_64
2016/11/01 15:24:31 INFO  - jmeter.JMeter: os.version=10.12.1
2016/11/01 15:24:31 INFO  - jmeter.JMeter: file.encoding=UTF-8
2016/11/01 15:24:31 INFO  - jmeter.JMeter: Max memory     =514850816
2016/11/01 15:24:31 INFO  - jmeter.JMeter: Available Processors =8
2016/11/01 15:24:31 INFO  - jmeter.JMeter: Default Locale=English (United States)
2016/11/01 15:24:31 INFO  - jmeter.JMeter: JMeter  Locale=English (United States)
2016/11/01 15:24:31 INFO  - jmeter.JMeter: JMeterHome=/Users/jboive/Downloads/apache-jmeter-3.0
2016/11/01 15:24:31 INFO  - jmeter.JMeter: user.dir  =/Users/jboive/Downloads/apache-jmeter-3.0/bin
2016/11/01 15:24:31 INFO  - jmeter.JMeter: PWD       =/Users/jboive/Downloads/apache-jmeter-3.0/bin
2016/11/01 15:24:31 INFO  - jmeter.JMeter: IP: 10.0.1.19 Name: iMac.local FullName: 10.0.1.19
2016/11/01 15:24:31 INFO  - jmeter.gui.action.LookAndFeelCommand: Using look and feel: com.apple.laf.AquaLookAndFeel [Mac OS X, System]
2016/11/01 15:24:31 INFO  - jmeter.JMeter: Loaded icon properties from org/apache/jmeter/images/icon.properties
2016/11/01 15:24:33 INFO  - jmeter.engine.util.CompoundVariable: Note: Function class names must contain the string: '.functions.'
2016/11/01 15:24:33 INFO  - jmeter.engine.util.CompoundVariable: Note: Function class names must not contain the string: '.gui.'
2016/11/01 15:24:35 INFO  - org.jmeterplugins.repository.PluginManager: Plugins Status: [jpgc-graphs-basic=2.0, jpgc-graphs-additional=2.0, jpgc-autostop=0.1, blazemeter-debugger=0.3, jpgc-functions=2.0, jmeter-ftp=3.0, jpgc-filterresults=2.1, jmeter-http=3.0, jmeter-jdbc=3.0, jmeter-jms=3.0, jmeter-monitors=3.0, jmeter-core=3.0, jmeter-junit=3.0, jmeter-java=3.0, jmeter-ldap=3.0, jmeter-mail=3.0, jmeter-mongodb=3.0, jmeter-native=3.0, jpgc-plugins-manager=0.10, jpgc-synthesis=2.0, jmeter-tcp=3.0, jmeter-components=3.0]
2016/11/01 15:24:36 INFO  - jmeter.util.BSFTestElement: Registering JMeter version of JavaScript engine as work-round for BSF-22
2016/11/01 15:24:36 INFO  - jmeter.protocol.http.sampler.HTTPSamplerBase: Parser for text/html is org.apache.jmeter.protocol.http.parser.LagartoBasedHtmlParser
2016/11/01 15:24:36 INFO  - jmeter.protocol.http.sampler.HTTPSamplerBase: Parser for application/xhtml+xml is org.apache.jmeter.protocol.http.parser.LagartoBasedHtmlParser
2016/11/01 15:24:36 INFO  - jmeter.protocol.http.sampler.HTTPSamplerBase: Parser for application/xml is org.apache.jmeter.protocol.http.parser.LagartoBasedHtmlParser
2016/11/01 15:24:36 INFO  - jmeter.protocol.http.sampler.HTTPSamplerBase: Parser for text/xml is org.apache.jmeter.protocol.http.parser.LagartoBasedHtmlParser
2016/11/01 15:24:36 INFO  - jmeter.protocol.http.sampler.HTTPSamplerBase: Parser for text/vnd.wap.wml is org.apache.jmeter.protocol.http.parser.RegexpHTMLParser
2016/11/01 15:24:36 INFO  - jmeter.protocol.http.sampler.HTTPSamplerBase: Parser for text/css is org.apache.jmeter.protocol.http.parser.CssParser
2016/11/01 15:24:37 INFO  - jorphan.exec.KeyToolUtils: keytool found at 'keytool'
2016/11/01 15:24:37 INFO  - jmeter.protocol.http.proxy.ProxyControl: HTTP(S) Test Script Recorder SSL Proxy will use keys that support embedded 3rd party resources in file /Users/jboive/Downloads/apache-jmeter-3.0/bin/proxyserver.jks
2016/11/01 15:24:37 INFO  - jmeter.gui.util.MenuFactory: Skipping org.apache.jmeter.protocol.mongodb.config.MongoSourceElement
2016/11/01 15:24:37 INFO  - jmeter.gui.util.MenuFactory: Skipping org.apache.jmeter.protocol.mongodb.sampler.MongoScriptSampler
2016/11/01 15:24:37 INFO  - jmeter.gui.util.MenuFactory: Skipping org.apache.jmeter.visualizers.DistributionGraphVisualizer
2016/11/01 15:24:37 INFO  - jmeter.samplers.SampleResult: Note: Sample TimeStamps are START times
2016/11/01 15:24:37 INFO  - jmeter.samplers.SampleResult: sampleresult.default.encoding is set to ISO-8859-1
2016/11/01 15:24:37 INFO  - jmeter.samplers.SampleResult: sampleresult.useNanoTime=true
2016/11/01 15:24:37 INFO  - jmeter.samplers.SampleResult: sampleresult.nanoThreadSleep=5000
2016/11/01 15:24:37 INFO  - jmeter.gui.util.MenuFactory: Skipping org.apache.jmeter.visualizers.SplineVisualizer
2016/11/01 15:24:49 INFO  - jmeter.services.FileServer: Default base='/Users/jboive/Downloads/apache-jmeter-3.0/bin'
2016/11/01 15:24:49 INFO  - jmeter.gui.action.Load: Loading file: /Users/jboive/Downloads/apache-jmeter-3.0/bin/thread-test.jmx
2016/11/01 15:24:49 INFO  - jmeter.services.FileServer: Set new base='/Users/jboive/Downloads/apache-jmeter-3.0/bin'
2016/11/01 15:24:49 INFO  - jmeter.save.SaveService: Testplan (JMX) version: 2.2. Testlog (JTL) version: 2.2
2016/11/01 15:24:49 INFO  - jmeter.save.SaveService: Using SaveService properties file encoding UTF-8
2016/11/01 15:24:49 INFO  - jmeter.save.SaveService: Using SaveService properties version 2.9
2016/11/01 15:24:49 INFO  - jmeter.save.SaveService: All converter versions present and correct
2016/11/01 15:24:49 INFO  - jmeter.save.SaveService: Loading file: /Users/jboive/Downloads/apache-jmeter-3.0/bin/thread-test.jmx
2016/11/01 15:24:49 INFO  - jmeter.services.FileServer: Set new base='/Users/jboive/Downloads/apache-jmeter-3.0/bin'
2016/11/01 15:24:53 INFO  - jmeter.samplers.SampleEvent: List of sample_variables: []
2016/11/01 15:29:59 INFO  - jmeter.engine.StandardJMeterEngine: Running the test!
2016/11/01 15:29:59 INFO  - jmeter.samplers.SampleEvent: List of sample_variables: []
2016/11/01 15:29:59 INFO  - jmeter.gui.util.JMeterMenuBar: setRunning(true,*local*)
2016/11/01 15:29:59 INFO  - jmeter.engine.StandardJMeterEngine: Starting ThreadGroup: 1 : Thread Group
2016/11/01 15:29:59 INFO  - jmeter.engine.StandardJMeterEngine: Starting 1 threads for group Thread Group.
2016/11/01 15:29:59 INFO  - jmeter.engine.StandardJMeterEngine: Test will stop on error
2016/11/01 15:29:59 INFO  - jmeter.threads.ThreadGroup: Starting thread group number 1 threads 1 ramp-up 1 perThread 1000.0 delayedStart=false
2016/11/01 15:29:59 INFO  - jmeter.threads.ThreadGroup: Started thread group number 1
2016/11/01 15:29:59 INFO  - jmeter.engine.StandardJMeterEngine: All thread groups have been started
2016/11/01 15:29:59 INFO  - jmeter.threads.JMeterThread: Thread started: Thread Group 1-1
2016/11/01 15:29:59 INFO  - jmeter.protocol.http.sampler.HTTPHCAbstractImpl: Local host = iMac.local
2016/11/01 15:29:59 INFO  - jmeter.protocol.http.sampler.HTTPHC4Impl: HTTP request retry count = 0
2016/11/01 15:29:59 INFO  - jmeter.protocol.http.parser.BaseParser: Created org.apache.jmeter.protocol.http.parser.LagartoBasedHtmlParser
2016/11/01 15:29:59 INFO  - jmeter.threads.JMeterThread: Thread is done: Thread Group 1-1
2016/11/01 15:29:59 INFO  - jmeter.threads.JMeterThread: Thread finished: Thread Group 1-1
2016/11/01 15:29:59 INFO  - jmeter.engine.StandardJMeterEngine: Notifying test listeners of end of test
2016/11/01 15:29:59 INFO  - jmeter.gui.util.JMeterMenuBar: setRunning(false,*local*)

A: There's nothing wrong here.
In GUI mode, View Results Tree shows all fields.
In non GUI mode, the  output you have set for View Results Tree is CSV which does not store all fields like response data, encoding ...
That's why you don't have all data.
To have what you want, click on "Configure" button in View Results Tree and select XML fields. Rename you file to thread-test.xml.

A: Actually your Test Plan does work, it just stores a limited subset of metrics in the .jtl results file which is enough to populate listeners like Aggregate Report or to build HTML Reporting Dashboard.
The data is being cut as saving requests and especially responses causes massive disk IO overhead and consumes a lot of memory, that's why it is recommended avoid saving the extra data or to do it only when an error occur.
If for some reason you need to have the full picture in non-GUI mode it is controllable via JMeter Properties. In order to get the same level of details as for the GUI mode add the following lines to user.properties file (lives in JMeter's "bin" folder)
jmeter.save.saveservice.output_format=xml
jmeter.save.saveservice.response_data=true
jmeter.save.saveservice.samplerData=true
jmeter.save.saveservice.requestHeaders=true
jmeter.save.saveservice.url=true
jmeter.save.saveservice.responseHeaders=true

JMeter restart will be required to pick the properties up. See Apache JMeter Properties Customization Guide to learn more about JMeter Properties and ways of setting and/or overriding them


text:
Q: django adding real time probelm this is html include that add the product and make multi adding random , once it dosnt make duplicate , and once work normally .
{% load i18n %}
{% load static %}
<form  >

{% for productss in my_products %}

                    {% if productss.product_icon %}

                    {% else %}

                    {% endif %}

{% translate "Qty" %}: {{productss.bpq_real_quantity}}

{{productss}}

{{productss.bpq_product_sell_price}}

                            <input type="button" value="-" onclick="decrementValue{{productss.id}}()" class="button-minus dec button">
                            <input type="text" name="child"  value="1" class="quantity-field" id="plus_field{{productss.id}}" name="quantity_required">
                            <input   type="button" value="+" onclick="incrementValue{{productss.id}}()" class="button-plus inc button" >
                            <input  type="submit" value="{% translate "Add" %}" id="add_item_{{productss.id}}">

    </form>

    {% comment %} var quantity = $("#quantity_required").val();
    $.ajax({
      type: "POST",
      url: {% url 'view_detail' %},
      data: search_word,
      success: function(result){
        alert("Success");
      }
    }); {% endcomment %}

{% comment %}
    $('#add_item_{{productss.id}}').hide();
    setTimeout(function()
    {
        $('#add_item_{{productss.id}}').show();
    }, 1000); {% endcomment %}

    {% csrf_token %}

        {% endfor %}

{% comment %}

    <input id="search" name="search" type="text" class="query-search" placeholder="Search...">
    <input onclick="setGetParameter()" type="button" class="btn btn-primary" value = "View Details"/>

and in views :

def search_view(request):
    if request.method == "POST":
        search_word = request.POST['data']

{% endcomment %}

this is views.py
def add_item_resturant(request,pk):
    print(f"This is request.POST: {request.POST}")
    current_user=request.user
    customer=Customer.objects.get(customer_name=request.POST['customer'])
    CstPoints=customer.customer_Points
    user_branch=request.user.user_profile.user_branch
current_order=OrderDetail.objects.select_related('order_order').select_related('order_product_name').filter(order_order__order_progress="In Progress",order_order__order_who_created=current_user)
    current_product=BrancheProductQuantity.objects.get(id=pk)
    branch_tax=current_product.bpq_branch_name.branch_Tax
    real_quantity=current_product.bpq_real_quantity
    sell_price=current_product.bpq_product_sell_price
    returned_order=Order.objects.get(order_who_created=current_user,order_progress="In Progress")
    get_quantity = request.POST['quantity']
    if float(real_quantity) - float(get_quantity) < 0 :
        messages.warning(request,"Product Quantity is Error and the Quantity of it=" + str(real_quantity) +"and you enter" + get_quantity)
        return redirect("orders:add_resturant_order")
    if request.method =="POST" :
        order_detail , created =OrderDetail.objects.get_or_create(
            order_order = returned_order,
            order_product_name = current_product)
        qfloat=float(get_quantity)
        sfloat=float(sell_price)
        total_item=float(qfloat*sfloat)
        tax=(total_item*branch_tax/100)
        price_iclude_tax=tax+total_item
        order_detail.order_tax_value=float(tax)
        order_detail.order_product_name=current_product
        order_detail.order_product_price=current_product.bpq_product_sell_price
        order_detail.order_product_quantity=float(get_quantity)
        order_detail.order_detail_total=float(total_item)
        order_detail.total= float(price_iclude_tax)
        order_detail.order_biller_user = str(current_user)
        order_detail.order_branch = str(user_branch)
        order_detail.save()
    final_total_value=current_order.aggregate(Sum('total'))['total__sum']
    final_tax_value=current_order.aggregate(Sum('order_tax_value'))['order_tax_value__sum']
    full_sub_total=current_order.aggregate(Sum('order_detail_total'))['order_detail_total__sum']
    returned_order=returned_order.refresh_from_db()
    html = render_to_string('include/add_item_resturant.html',{'CstPoints':CstPoints,'final_total_value':final_total_value,'final_tax_value':final_tax_value,'full_sub_total':full_sub_total,'returned_order':returned_order,'order_detailed':current_order,  request:request})
    return JsonResponse({'result':html})

enter image description here
I want to solve this problem it make adding product twice and may be 3 or 4 times as showd in page I donst know why is this problem appear.


text:
Q: Error in the implementation of a voting system I'm writing a program to create a list of voter IDs, and allow them to vote for a candidate. If a voter tries to vote for a candidate that doesn't exist this name should be added to the list.
When I try copying the name that has been entered on to the candidate_name field using "strcpy" I get a segmentation fault, I tried copying it directly but this overwrites the values of all the previous nodes to the one I enter last. As mentioned in one of the previous solutions for a linked list being overwritten problem I tried strdup as well, but when I do this I don't get the result I'm supposed to. For eg. If I vote for "a" now, and "a" immediately after the function returns "EXISTS", but if I try to vote for "a" first, then "b", then "a" again the function returns "NEW" and for some reason the loop that checks for the existence of a name in the list executes only once even though it has to execute twice.
I'd be grateful if someone could tell me what I should do to make this right.
Also, why is "strcpy" resulting in a segmentation fault?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct candidate{
    char *candidate_name;
    int vote_count;
    struct candidate *next;
}candidate;
struct candidate *candidate_head=NULL;
typedef struct voter{
    int voterid;
    int has_voted;
    struct voter *next;
}voter;
struct voter *voter_head=NULL;

    char *add_voter(int voterid){
        struct voter *v=voter_head;
        while(v!=NULL){
            if(v->voterid==voterid)
                return "Already exists";
            v=v->next;
        }

        voter *v1=malloc(sizeof(voter));
        v1->voterid=voterid;
        v1->has_voted=0;
        v1->next=voter_head;
        voter_head=v1;
        return "Added";
    }

    char *add_candidate(char *c_name, int voterid){
        int flag=0;
        struct voter *v=voter_head;
        while(v!=NULL){
            if(v->voterid==voterid){
                flag=1;
                if(v->has_voted==1){
                    return "ALREADY VOTED";
                }
                else{
                    v->has_voted=1;
                }
            }
            v=v->next;
        }

        if(flag==0)
            return "Invalid Voter ID";

            struct candidate *c=candidate_head;
            if(candidate_head!=NULL)
            printf("see-%s\n",candidate_head->candidate_name);
                while(c!=NULL){
                    printf("name0 c%s\n",c->candidate_name);
                    printf("name1 c%s\n",c_name);
                    if(strcmp(c_name,c->candidate_name)==0){
                        c->vote_count++;
                        return "EXISTS";
                    }
                c=c->next;
                }

                struct candidate *c1=malloc(sizeof(candidate));
                // strcpy(c1->candidate_name,c_name);
                c1->candidate_name=strdup(c_name);
                printf("\nname1 %s\n",c1->candidate_name);
                printf("name2 %s\n",c_name);
                c1->vote_count=1;
                c1->next=candidate_head;
                candidate_head=c1;
                candidate_head->next = NULL;
                return "NEW";

    }

    int main(){

        int voterid,count;
        char *cand=malloc(sizeof(char));
        struct candidate *c=malloc(sizeof(candidate));
        for(count=0;count<4;count++){
            printf("Enter voter ID\n");
            scanf("%d",&voterid);
            printf("%s\n",add_voter(voterid));
        }

        for(count=0;count<4;count++){
            printf("Enter candidate name\n");
            scanf("%s",cand);
            printf("Enter voter ID\n");
            scanf("%d",&voterid);
            printf("%s\n", add_candidate(cand,voterid));

        }

        return 0;

    }

A: After addressing errors in your code that have to do with allocating memory, it seemed to run without error.
First, the line:
char *cand=malloc(sizeof(char));   //(second line in main)
only allocates 1 byte to the intended character array cand, so in the next line, scanf() returns
Attempt to write beyond string.  Allocate more memory for your candidates name.  And free() cand when you are
done with it.
providing more memory:
char *cand = malloc(100); // will hold a 99 character name (plus \0)
Second, c1->candidate_name has never been given space.  You are attempting to copy into memory that you do not own.
Note:  the line:
struct candidate *c1=malloc(sizeof(candidate));

does not allocate memory for the member candidate_name, you have to do that explicitly
c1->candidate_name = malloc(SOME_NUMBER_OF_BYTES);
// then when you are done, free it:
free(c1->candidate_name);


text:
Q: codeigniter autoload file issue I have uploaded codeigniter file in my linux server using php version 5.5. I got issue on application\config\autoload.php file.
$autoload['libraries'] = array(); //default code
//$autoload['libraries'] = array('database');

When  i  run the program using default code. program runs fine. But when i load database library, we didn't get any error or output. it shows blank page.
you can check here.
Sample Code:

class Test extends CI_Controller {

    function show() {
        echo 'methos call';
    }
}

This program runs in my local without issue.
Is that server problem or codeignitor issue.
Thanks

A: In autoload.php file Change
$autoload['libraries'] = array('database')

Then go to database.php and configure your database.(Bottom of page).
if CodeIgnitor 2.0.0
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = '';
$db['default']['password'] = '';
$db['default']['database'] = '';//database name
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

If CodeIgnitor 3.0.0
$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => '',
    'password' => '',
    'database' => '',//database name
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => TRUE,
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

If you correct these it should work fine.

A: If the code is running fine on local machine and giving problem on server please check the name of file.  It should in lowercase and the class name should in camelcase.
It worked for me please try.

A: Try using following code,
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors',1);
ini_set('html_errors', 1);

It will show all the errors which sometimes hidden by default.


text:
Q: Buttons strange behavior when pressing I've an Android activity that has some buttons in the bottom of it, these buttons have a one pressed and a three released as a default,

and when any of them pressed it's background supposed to change to the background of the pressed buttons and the others background supposed to change to the background of the released buttons, but when clicking any button I got that result:

this is my code:
xml:
<LinearLayout
            android:id="@+id/GrandThree"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_marginTop="10dp"
            android:layout_gravity="center"
            android:gravity="center"
            android:orientation="horizontal"
            android:background="@android:color/transparent">

            <Button
                android:id="@+id/BedRoom_bottom"
                android:layout_width="200dp"
                android:layout_height="fill_parent"
                android:background="@drawable/light_bottom_buttons_pressed"
                android:text="Bedroom"
                android:textSize="20dp"
                android:textColor="#FFFFFF"
                android:layout_gravity="center"
                android:layout_marginTop="3dp"
                android:layout_marginLeft="3dp"
                android:layout_marginBottom="3dp"
                android:layout_marginRight="3dp"
                android:tag="pressed"
                android:clickable="true" />

            <Button
                android:id="@+id/livingroom"
                android:layout_width="200dp"
                android:layout_height="fill_parent"
                android:background="@drawable/light_bottombuttons"
                android:text="Living Room"
                android:layout_gravity="center"
                android:textSize="20dp"
                android:padding="20px"
                android:textColor="#FFFFFF"
                android:layout_marginTop="3dp"
                android:layout_marginLeft="3dp"
                android:layout_marginBottom="3dp"
                android:layout_marginRight="3dp"
                android:tag="released"
                android:clickable="true" />
            <!.. then two buttons the same way ..!>
</LinearLayout>

JAVA:
        // the onClickListener method for the Navigation buttons
            public OnClickListener onNavigationClick = new OnClickListener() {

             @Override
                public void onClick(View v) {

                  if(v == bedRoom){

                String tag = bedRoom.getTag().toString().trim();
                    if (tag.equals("released")) {

                       bedRoom.setBackgroundColor(R.drawable.light_bottom_buttons_pressed);
                       bedRoom.setTag("pressed");
                       livingRoom.setBackgroundColor(R.drawable.light_bottombuttons);
                       livingRoom.setTag("released");
                       masterBedroom.setBackgroundColor(R.drawable.light_bottombuttons);
                       masterBedroom.setTag("released");
                       kitchen.setBackgroundColor(R.drawable.light_bottombuttons);
                       kitchen.setTag("released");

      }
   }
       //then another 3 blocks the same way for the other buttons
}
};

Hint: light_bottombuttons & light_bottom_buttons_pressed are shapes with gradient colors:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="30dp"/>

    <gradient
        android:startColor="#353535"
        android:centerColor="#212121"
        android:endColor="#121212"  <!.. the values of the other is just upside down these values ..!>
        android:angle="270"/>

    </shape>

A: Create a file called button-drawable.xml in your drawable folder containing this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:state_selected="true"
    android:@drawable/light_bottom_buttons_pressed" />
<item
    android:drawable="@drawable/light_bottom_buttons_pressed" />
</selector>

Add a tag to all the buttons in the layout file.
android:background="@drawable/button_drawable"

Now, in your button's click listener set the button's selected state to true any time a new button is chosen.
Example code :
public OnClickListener onNavigationClick = new OnClickListener() {

         @Override
            public void onClick(View v) {

              if(v == bedRoom){

            String tag = bedRoom.getTag().toString().trim();
                if (tag.equals("released")) {

                   bedRoom.setTag("pressed");
                   bedRoom.setSelected(true);
                   livingRoom.setTag("released");
                   livingRoom.setSelected(false);
                   masterBedroom.setTag("released");
                   masterBedroom.setSelected(false);
                   kitchen.setTag("released");
                   kitchen.setSelected(false);

  }
}
    //then another 3 blocks the same way for the other buttons
}
};

A: Use radio group and radio button for this.
Your radio group will contain multiple buttons and at a time only one can be selected.

A: When you get your drawable you should do it like the following
        bedRoom.setBackgroundColor(MyActivity.this.getResources().getDrawable(R.drawable.light_bottom_buttons_pressed));

MyActivity Would change to be whatever your activity name is


text:
Q: What to choose with n-tier application in .NET typed datasets or something else? So I'm doing a project. MS SQL->WCF->Client (win32 application + asp.net MVC 3 web) I have worker with ado.net typed datasets till now, but now I have question...
What's your opinion what should I use for WCF->Client Typed Datasets or something else?
Performance (speed) is preety important also....
Thanks in advance

A: Strongly typed entities is the way to go. Dataset generally must be avoided for performance reasons.
ORMs such as NHibernate or Entity Fframework 4 must be used for turning database state to and from entities.

A: I have done the mistake to confuse typed datasets with business entities in the past and would not fall this way again ever. They are handy and easy to design and use but a typed dataset is not a business entity.
I think the best way is to use classes and interfaces properly combined so you could have a general approach and specialize with derived classes as needed, in WCF there is the concept of DataContract which is very useful as well.

A: WCF per se does not support DataSets. Use serializable DTO´s instead.


text:
Q: Change a class name and call a new function I need to remove a class and change its name to another name in jQuery and need to run a method for the new class name.
My divs are here

I have a div called instruments as the class name
I need to change that class name to inst, when fire my first jQuery function
then when I press the new added div It need to say hello.

A: You should unbind the first event handler when it is triggered, otherwise it will be triggered again when you click on the element again. You can use the one method to automatically unbind the event handler.
Just bind the other event handler to the element in the first event handler:
$(".instruments").one("click", function(){
  $("#drop-area").append($(this));
  console.log($(this).attr('class'));
  $(this).removeClass("instruments");
  console.log($(this).attr('class'));
  $(this).addClass("inst");
  console.log($(this).attr('class'));
  $(this).click(function(){
    alert("Hello");
  });
});

A: Try using event delegation in order to select the dynamically added element:
    $(document).on("click", ".inst", function() {
        alert("Hello");
    });


text:
Q: Como desativar spring security Boa noite, estou aprendendo jsf, então acompanhei uns videos do Leandro Costa no youtube, achei bem didático e etc. No final do curso ele disponibiliza o código fonte, porém como o projeto usa spring security no login e ele não passou o script sql toda página que tento acessar dá o erro HTTP Status 403 - Access to the requested resource has been denied.
Já tentei criar o banco manualmente, porém sem sucesso. Então cheguei a conclusão que é melhor tirar a autenticação pra poder usar a aplicação.
spring-security.xml
<b:beans xmlns="http://www.springframework.org/schema/security"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:b="http://www.springframework.org/schema/beans"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/security
                        http://www.springframework.org/schema/security/spring-security-3.0.xsd">

    <http auto-config="true" use-expressions="true">
    <intercept-url pattern="/login.faces" access="permitAll" />
    <intercept-url pattern="/restrict/**" access="isAuthenticated()" />
    <intercept-url pattern="/public/**" access="permitAll"/>

    <form-login login-page="/login.faces" authentication-failure-url="/login.faces?erro=true"
                default-target-url="/restrict/home.faces"/>
    <access-denied-handler error-page="/acessonegado.faces" />
</http>

<!-- NO PROJETO SEMERU PADRÃO FIZEMOS DESSA FORMA -->
<authentication-manager>
    <authentication-provider>
        <password-encoder hash="sha"/>
        <jdbc-user-service data-source-ref="dataSource"
                           users-by-username-query="SELECT Login, Senha, 'true' as enable FROM pessoa WHERE Login=?"
                           authorities-by-username-query="SELECT Login as username, Permissao as authority  FROM pessoa WHERE Login=?"/>
    </authentication-provider>
</authentication-manager>

<b:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
    <b:property name="url" value="jdbc:mysql://localhost:3306/semeru_jsf_maven_db" />
    <b:property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <b:property name="username" value="root" />
    <b:property name="password" value="admin" />
</b:bean>

Web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
     id="WebApp_ID" version="2.5">

<display-name>semeru_jsf_maven</display-name>

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    <!--        <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>-->
</welcome-file-list>

<!-- Duração da sessão -->

<session-config>
    <session-timeout>
        30
    </session-timeout>
</session-config>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/spring-security.xml
    </param-value>
</context-param>

<!-- Configurações do tema do PrimeFaces -->
<context-param>
    <param-name>primefaces.THEME</param-name>
    <param-value>sam</param-value>
</context-param>

<!-- Filtros do Spring  -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>

    <!-- Configurações do JavaServer Faces -->

<context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Development</param-value>
</context-param>

<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.faces</url-pattern>
</servlet-mapping>

<security-constraint>
    <display-name>Bloqueia o browser de acessar arquivos xhtml</display-name>
    <web-resource-collection>
        <web-resource-name>xhtml files</web-resource-name>
        <url-pattern>*.xhtml</url-pattern>
    </web-resource-collection>
    <auth-constraint/>
</security-constraint>

<!-- Configurações do PrimeFaces -->

<servlet>
    <servlet-name>Resource Servlet</servlet-name>
    <servlet-class>org.primefaces.resource.ResourceServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>Resource Servlet</servlet-name>
    <url-pattern>/primefaces_resource/*</url-pattern>
</servlet-mapping>

A: comentei os trechos que ativam o spring security do seu web.xml tentando explicar o que cada trecho é responsável por fazer, é importante salientar, que embora o spring security vá ficar desativado com este web.xml, a aplicação pode estar utilizando este contexto em vários lugares e não funcionar corretamente.
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
     id="WebApp_ID" version="2.5">

<display-name>semeru_jsf_maven</display-name>

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    <!--        <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>-->
</welcome-file-list>

<!-- Duração da sessão -->

<session-config>
    <session-timeout>
        30
    </session-timeout>
</session-config>

<!-- Este parâmetro refere-se ao contexto do Spring
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/spring-security.xml
    </param-value>
</context-param>  -->

<!-- Configurações do tema do PrimeFaces -->
<context-param>
    <param-name>primefaces.THEME</param-name>
    <param-value>sam</param-value>
</context-param>

<!-- Estes filtros são responsáveis por interceptar qualquer request e direcioná-lo para o Spring
Filtros do Spring
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>
-->

    <!-- Configurações do JavaServer Faces -->

<context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Development</param-value>
</context-param>

<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.faces</url-pattern>
</servlet-mapping>

<!-- Aqui como explicado abaixo, é responsável por blqouear acesso ao xhtml caso o usuário não esteja autenticado
<security-constraint>
    <display-name>Bloqueia o browser de acessar arquivos xhtml</display-name>
    <web-resource-collection>
        <web-resource-name>xhtml files</web-resource-name>
        <url-pattern>*.xhtml</url-pattern>
    </web-resource-collection>
    <auth-constraint/>
</security-constraint>
-->

<!-- Configurações do PrimeFaces -->

<servlet>
    <servlet-name>Resource Servlet</servlet-name>
    <servlet-class>org.primefaces.resource.ResourceServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>Resource Servlet</servlet-name>
    <url-pattern>/primefaces_resource/*</url-pattern>
</servlet-mapping>

Espero ter ajudado.


text:
Q: How to fill vertical space with flexbox? If .right item stretch height to any size, how to make .item elements inside .left to fill vertical space equally?
From:

To:

.container {
  display: flex;
  background: #ccc;
}

.left {
  flex: 2;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: stretch;
  height: 100%;
}

.right {
  flex: 1;
  border: 1px solid #000;
}

.item {
  border: 1px solid #000;
  flex: 1 0 100%;
  align-self: stretch;
}

      Item 1

      Item 2

    Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
    sanctus est Lorem ipsum dolor sit amet.

https://jsfiddle.net/d7o58kaj/1/

A: Removed height: 100% from .left

.container {
  display: flex;
  background: #ccc;
}

.left {
  flex: 2;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: stretch;
}

.right {
  flex: 1;
  border: 1px solid #000;
}

.item {
  border: 1px solid #000;
  flex: 1 0 100%;
  align-self: stretch;
}

      Item 1

      Item 2

    Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
    sanctus est Lorem ipsum dolor sit amet.

A: An initial setting of a flex container is align-content: stretch.
That means that flex lines will equally share all available space in the container along the cross axis. (A similar effect to flex: 1 on all items on the main axis.)
However, when you define a height for a flex item when the cross axis is vertical, or width, when the cross axis is horizontal, you override the align-content default.
In your row-direction container, the cross axis is vertical. So if you remove height: 100%, that allows align-content: stretch to work.
Learn more about flex alignment on the cross axis here:

*

*How does flex-wrap work with align-self, align-items and align-content?
Learn more about flex alignment on the main axis here:

*

*In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

.container {
  display: flex;
  background: #ccc;
}

.left {
  flex: 2;
  display: flex;
  flex-wrap: wrap;      /* <--- this brings align-content into play */
  /* flex-direction: row;  <--- default setting; can be omitted */
  /* align-items: stretch; <--- default setting; can be omitted */
  /* height: 100%; */
}

.right {
  flex: 1;
  border: 1px solid #000;
}

.item {
  border: 1px solid #000;
  flex: 1 0 100%;
  align-self: stretch;
}

Item 1

Item 2

    Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
    sanctus est Lorem ipsum dolor sit amet.

A: You can use flex property

align-items: stretch ;

for achieving this.


text:
Q: Error message '405 method not allowed' when using php cURL with jQuery
This is the error message I receive when I try to run my code using jQuery. I don't think there's anything wrong with the jQuery package which would suggest it has something to do with my code.
Here is my code:
<?php

// ini_set('display errors', 'On');
// error_reporting(E_ALL);

$executionStartTime = microtime(true) / 1000;

$url= 'http://api.geonames.org/postalCodeCountryInfoJSON?formatted=true' . $_REQUEST['countryName'] . '&username=jessed&style=full';

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);

$result=curl_exec($ch);

curl_close($ch);

$decode = json_decode($result,true);

$output['status']['code'] = "200";
$output['status']['name'] = "ok";
$output['status']['description'] = "mission saved";
$output['status']['returnedIn'] = (microtime(true) - $executionStartTime) / 1000 . " ms ";
$output['data'] = $decode["geonames"];

header('Content-Type: application/json; charset=UTF-8');

echo json_encode($output);

?>

What can I try next?


text:
Q: converting individual string elements to their decimal equivalents in c++ I have a string str ( "1 + 2 = 3" ). I want to obtain the individual numbers of the string in their decimal values( not ASCII ). I have tried atoi and c_str(). But both them require the entire string to consist of only numbers. I am writing my code in C++.
Any help would be great.
My challenge is to evaluate a prefix expression. I am reading from a file where each line contains a prefix expression. My code snippet to tokenize and and store the variables is as shown below. Each line of the file contains numbers and operators(+,-,*) which are separated by a space.
Ex - line = ( * + 2 3 4);
    ifstream file;
    string line;

    file.open(argv[1]);
    while(!file.eof())
    {
            getline(file,line);
            if(line.length()==0)
                    continue;
            else
            {
                    vector<int> vec;
                    string delimiters = " ";
                    size_t current;
                    size_t next = -1;
                    do
                    {
                            current = next + 1;
                            next = line.find_first_of( delimiters, current );
                            if((line[next] <=57)&&(line[next] >=48))
                                   vec.push_back(atoi((line.substr( current, next - current )).c_str()));
                    }while (next != string::npos);
                    cout << vec[0] << endl;
            }
    }
    file.close();

In this case vec[0] prints 50 not 2.

A: You need to learn to delimit a string. Your delimiting characters would be mathematical operators (ie:
C: creating array of strings from delimited source string
http://www.gnu.org/software/libc/manual/html_node/Finding-Tokens-in-a-String.html
In the case of the second link, you would do something like:
const char delimiters[] = "+-=";

With this knowledge, you can create an array of strings, and call atoi() on each string to get the numeric equivalent. Then you can use the address (array index) of each delimiter to determine which operator is there.
For just things like addition and subtraction, this will be dead simple. If you want order of operations and multiplication, parentheses, etc, your process flow logic will be more complicated.
For a more in-depth example, please see this final link. A simple command-line calculator in C. That should make it crystal clear.
http://stevehanov.ca/blog/index.php?id=26

A: You will not fall into your if, since your next position will be at a delimiter.
                string delimiters = " ";
                ...
                        next = line.find_first_of( delimiters, current );
                        if((line[next] <=57)&&(line[next] >=48))
                        ...

Since your delimiters consist of " ", then line[next] will be a space character.
From the description of your problem, you are missing code that will save away your operators. There is no code to attempt to find the operators.
You don't have to assume ASCII for testing for a digit. You can use is_digit() for example, or you can compare against '9' and '0'.
When you print your vector element, you may be accessing the vector inappropriately, because no item may have ever been inserted into the array.

A: Don't use fin.eof() to control a loop. That function is only useful after a read has failed.
There are a number of ways to get ints from a std::string, I'm choosing std::stoi() from the C++11 standard in this case.
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>

typedef std::vector<int> ints;

bool is_known_operator(std::string const& token)
{
    static char const* tokens[] = {"*", "/", "+", "-"};
    return std::find(std::begin(tokens), std::end(tokens), token) != std::end(tokens);
}

ints tokenise(std::string const& line)
{
    ints vec;
    std::string token;
    std::istringstream iss(line);

    while (iss >> token)
    {
        if (is_known_operator(token))
        {
            std::cout << "Handle operator [" << token << "]" << std::endl;
        }
        else
        {
            try
            {
                auto number = std::stoi(token);
                vec.push_back(number);
            }
            catch (const std::invalid_argument&)
            {
                std::cerr << "Unexpected item in the bagging area ["
                    << token << "]" << std::endl;
            }
        }
    }
    return vec;
}

int main(int, const char *argv[])
{
    std::ifstream file(argv[1]);
    std::string line;
    ints vec;

    while (std::getline(file, line))
    {
        vec = tokenise(line);
    }

    std::cout << "The following " << vec.size() << " numbers were read:\n";
    std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, "\n"));
}


text:
Q: window--display-buffer: How to precisely set window width at time of creation With respect to the function window--display-buffer, I have been unable to precisely set the window width using a number -- e.g., '((window-width . 82)).  The width is always slightly less than it should be.  Any assistance to reliably use a number to set the window width would be greatly appreciated.
The documentation ( https://www.gnu.org/software/emacs/manual/html_node/elisp/Display-Action-Functions.html ) states as follows:
To adjust the window's width, use an entry whose car is window-width and whose cdr is one of:

*

*nil means to leave the width of the new window alone.

*A number specifies the desired width of the new window. An integer number specifies the number of columns of the window. A floating point number gives the fraction of the window's width with respect to the width of the frame's root window.

*If the cdr specifies a function, that function is called with one argument: the new window. The function is supposed to adjust the width of the window; its return value is ignored.

Here is a broken-example that demonstrates the problem with window--display-buffer when using a number -- e.g., '((window-width . 82))
(defun broken-example ()
  (interactive)
  (window--display-buffer
   ;; buffer
   (get-buffer-create "*test*")
   ;; window
   (split-window (selected-window) nil 'right)
   ;; type
   'window
   ;; alist
   '((window-width . 82))
   ;; dedicated
   t)
  (message "Window Width:  %s" (window-width (get-buffer-window "*test*"))) )

Here is a working-example that uses the third option -- i.e., a function whose argument is the new window:
(defun working-example ()
  (interactive)
  (window--display-buffer
   ;; buffer
   (get-buffer-create "*test*")
   ;; window
   (split-window (selected-window) nil 'right)
   ;; type
   'window
   ;; alist
   '((window-width . set-window-width))
   ;; dedicated
   t)
  (message "Window Width:  %s" (window-width (get-buffer-window "*test*"))) )

(defun set-window-width (window)
  "Set the selected window's width."
  (window-resize window (- 82 (window-width)) t) )

A: As to a current version of Emacs Trunk built on March 19, 2014, the following modification of line 5944 of window.el from (delta (- new-width (window-total-width window)))) to (delta (- new-width (window-width window)))) resolves this issue.
EDIT (March 22, 2014):  Here is a link to the open bug report on this issue -- http://debbugs.gnu.org/cgi/bugreport.cgi?bug=17065


text:
Q: Downsides of having a model with too many independent variables (factors)? It is often tempting in experimental design to make distinctions of all sorts in the manipulated variables, and thus to end up with a lot of factors in one's model (e.g. a 3x2x2x2x2 ANOVA).  The same holds (I think) for covarying for many extraneous variables, as in ANCOVA.
If I understand correctly, the reason why this is not recommended is because it decreases statistical power by decreasing the degrees of freedom of statistical (e.g. F-) tests. Is this true, and is there any other reason why it is desirable to minimise the number of factors (independent variables) in one's design?
Also, is there a way to quantitatively assess exactly how much power is lost by adding each factor, such that an experimenter can decide where to situate themselves in this trade-off and whether it is worth it or not including a certain factor in the model?

A: There are at least two other problems:
1) Parsimony.  Many people view parsimonious models as superior to less parsimonious ones, other things being equal.  This goes back to Ockham's razor.  However, there's always the question of just how parsimonious a model should be.
2) Overfitting. E.g in a 3x2x2x2x2 ANOVA there are 48 cells to estimate. Is there enough data?  In the extreme, if there is 1 observation in each cell, you can estimate them perfectly with noise.


text:
Q: Extend the timeout duration of a setTimeout timer Hi Everyone I know it is basic and silly to ask but this question is eating me up .
If I have a below following code .
var timerVal = 900000
function myFunction() {
  setTimeout(function(){ alert("Hello"); }, timerVal);
}
myFunction()

As per the above code an alert will come at 15 mins . But after ten minutes I thought to extend it for more 5 mins by changing the value of timerVal to 1200000. Now would the alert will come after another 10 mins . i.e. total 20 mins after the alert will come or it will come after 15 mins of the completion .
Suppose the code is like this :
var timerVal = 900000
function myFunction() {
  setTimeout(function(){ alert("Hello"); }, timerVal);
}
function change(){
   setTimeout(function(){
     timerVal = 1200000;
   },60000);
}
myFunction();
change();

Can Anyone give let me know what will be the result and brief description why ?

A: The result will be that the timer will be executed at the 900000 millisecond mark, although you have tried to change it to 1200000 millisecond by changing the value of the timerVal variable.
This is because in JavaScript it is pass by value and since you have passed 900000 initially, the timer is already queued at 900000 and hence cannot be altered by changing the value of the timerVal variable again.
So this code, is simply making the timerVal point to the new number 1200000 not really changing the timeout set earlier:
function change(){
   setTimeout(function(){
     timerVal = 1200000; //timerVal reference is pointing to a new number
   }, 60000);
}

To really change the timer behavior you need to clear the timeout using the id returned by the setTimeout call and create another one with the new timeout value.

let timerVal = 9000;
function myFunction() {
  return setTimeout(function(){ alert("Hello"); }, timerVal); //returning the id
}
function change(id, newVal){
  clearTimeout(id); //clearing the previous timer using the id
  setTimeout(function(){ alert("Hello"); }, newVal);
}
let id = myFunction();
change(id, 5000);

A: Well, in general to be able to "extend" a timer, you'll need to cancel it (using clearTimeout), and re-create it. For this you'll need to keep track of how long has elapsed since it originally started and calculate a new time.
The code below demonstrates a function extendableTimeout which you can use like the normal setTimeout, except it returns an object with an extend function you can use for your purpose.
The demo has 2 button, the first starts an action delayed for 5s. Clicking the extend button extends the timeout by another 5 seconds. You can compare clicking the extend or not to see the timings.

function extendableTimeout(fn, time){
    var id = setTimeout(fn, time);
    var timeStart = new Date();
    return {
       timerId: id,
       extend: function(time){
           clearTimeout(id);
           var elapsed = new Date() - timeStart;
           var newTime = time - elapsed;
           setTimeout(fn,newTime);
       }
    }
}

var myTimer;
$('#start').on("click", function(){
  console.log("Started at " + new Date());
  myTimer = extendableTimeout(() => console.log("Finished at " + new Date()), 5000);
})

$("#extend").on("click", function(){
  myTimer.extend(10000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="start">Start</button>
<button id="extend"> + 5s </button>

A: AFAIU, you cannot extend the time of a setTimeout. What you can do is stopping it from executing, and create another setTimeout with the new value. Like this:

var timer = setTimeout(()=>console.log("first"), 2000);

clearTimeout(timer);

var timer = setTimeout(()=>console.log("second"), 2000);

You cannot extend it because the timer is created with the value the variable had at the time of creation event. It's not a reference that can be evaluated from time to time. It's a fixed value that is evaluated only on creation time.


text:
Q: XMPP Smack - Message Being Modified I'm developing a chat system based on xmpp (smack+openfire). I'm having issues when i try to send, along with a normal message, some "extra data". When preparing the message I do the following:
MyData myObject = new MyData("some text");

Message msg = new Message("a@me", Message.Type.chat);

DefaultPacketExtension dpe = new DefaultPacketExtension("packetName", "http://namespace.stuff");
dpe.setValue("dataTag", myObject.toXMLString());

msg.addExtension(dpe);
msg.setBody("Hello World!");

The myObject.toXmlString() returns an XML representation (using dom4j) of the MyData object.
After this I proceed with the sending of this message:
Chat personalChat = chatmanager.createChat(msg.getTo(),new MessageListener() {
        @Override
        public void processMessage(Chat chat, Message message) {
            System.out.println("MESSAGE RECEIVED:");
            System.out.println("From: "+message.getFrom());
            System.out.println(message);
        }
});

personalChat.sendMessage(msg);

The debug client reports the following messages.
Out message:
<message id="Fx5bQ-4" to="a@me" from="a@me/Smack" type="chat">
     Hello World!
     <thread>ef9632e3-6d27-4fea-a5c8-b3f7c85052d8</thread>
     <packetName xmlns="http://namespace.stuff">
         <dataTag>
             <myData xmlns:me="namespace">
                 <name>some text</name>
                 <points>0</points>
                 <res>0</res>
                 <contract/>
                 <bonuses/>
                 <position>0</position>
                 <secret/>
             </myData>
         </dataTag>
     </packetName>
</message>

In message:
<message id="Fx5bQ-4" to="a@me" from="a@me/Smack" type="chat">
     Hello World!
     <thread>ef9632e3-6d27-4fea-a5c8-b3f7c85052d8</thread>
     <packetName xmlns="http://namespace.stuff">
          <bonuses/>
          <name>some text</name>
          <res>0</res>
          <contract/>
          <position>0</position>
          <secret/>
          <points>0</points>
     </packetName>
</message>

As you can see there has been "a loss" of some data. In fact "dataTag" and "myData" simply are logged as part of the outgoing message but does not appear in the incoming one! Is this meant to be (performance stuff..."useless" to send "empty" nodes) or is there something wrong with openfire setup?
This is just a small example...in the real project I have 1000+ lines of a "myData" object in the outgoing message and in the incoming one most of them are missing (like 90% of the packetExtension is lost, and is not just "empty" nodes of the xml)!

A: The reason is you lack a specific packetExtensionProvider and therefore when your packet arrives the DefaultPacketExtensionProvider cannot parse it correctly. Indeed, this DefaultPacketExtensionProvider is very simple and can parse only simple XML with 1 level child or so.
For your case you need to define something like:
class MyExtensionProvider implements PacketExtensionProvider{
    @Override
    public PacketExtension parseExtension(XmlPullParser parser)throws Exception {
        LOGGER.info("[parseExtension] Executing parseExtension()");

        DefaultPacketExtension extension = new DefaultPacketExtension(MyExtension.ELEMENT_NAME,MyExtension.NAMESPACE);

        boolean done = false;

        int eventType = parser.getEventType();

        while (!done) {
            System.out.println(parser.getText());

            if (eventType == XmlPullParser.START_TAG) {

                String name = parser.getName();
                System.out.println(name);

                // If an empty element, set the value with the empty string.
                if (parser.isEmptyElementTag()) {
                    extension.setValue(name,"");
                }else {
                    eventType = parser.next();
                    if (eventType == XmlPullParser.TEXT) {
                        String value = parser.getText();
                        System.out.println(value);
                        extension.setValue(name, value);
                        done=true;
                    }
                }
            }

            eventType = parser.next();
        }
        return extension;
    }
}

This is a simple one so you want to define your own. Then you need to register your provider with:
ProviderManager providerManager = ProviderManager.getInstance();
    providerManager.addExtensionProvider(MyExtension.ELEMENT_NAME, MyExtension.NAMESPACE,new MyExtensionProvider());

REMEMBER: when you send the message it has to have MyExtension.ELEMENT_NAME and MyExtension.NAMESPACE set correctly otherwise it will not work. The ProviderManager will not recognize the packet and will not call the proper PacketExtensionProvider.


text:
Q: Keycloak Javascript Mapper not working as expected I did the following script for mapping an attribute called DocumentType for a SAML response, I have the document type and also document number of the person inside this attribute called LDAP_ID so I need to separate them, I tried like so:
DocumentType=(user.LDAP_ID).substring(0,2);

But when I check the response the value of attribute DocumentType is empty, but my user.LDAP_ID does contain a value like for example cc23143212, what am I doing wrong?
I also tried to do
DocumentType = String(user.LDAP_ID); // but this is returning undefined

what am I missing?
If I set DocumentType = user.LDAP_ID; then in the response, this attribute DocumentType contains value cc23143212
UPDATE:
I have another user attribute called username, which also contains the document number and documenttype of the user together like cc23143212, I tried using this attribute and it works, like so:
DocumentType = (user.username).substring(0,2); // returns cc as expected

so I think that the problem is something with the type of variable user.LDAP_ID is not an string or idk really why it does not work with attribute LDAP_ID, please help.

A: If LDAP_ID is stored in an attribute LDAP_ID, you can try
String(user.getAttribute("LDAP_ID")).substring(0,2)


text:
Q: Exclude jar from tomcat/lib folder I have a tomcat server with 10 apps.
Yesterday we did an update of our jdbc driver into tomcat/lib folder.
The new version works fine for 9 apps but not the 10th because the code is too outdated
Until we evolve the code too , i want for a specific app to exclude the jdbc driver loaded during runtime from tomcat/lib folder but instead pick the old one compatible in WEB-INF/lib folder.
I tired many things but it seems that the lib into tomcat folder has always the highest priority so the old driver in WEB-INF/lib is ignored
In context.xml i tried postResources and preResources in order to alter classpath during app runtime but it's not working :/
Any advices ? Thank you very much
<Context reloadable="true">
<Resources>
  <PreResources base="/usr/local/myapp-web/WEB-INF/lib/ojdbc6-11.2.0.2.0.jar"
                 className="org.apache.catalina.webresources.FileResourceSet"
                 webAppMount="/WEB-INF/lib/ojdbc6-11.2.0.2.0.jar"/>
</Resources>
</Context>


text:
Q: JavaScript - How do I dynamically assign a new key value pair to an object, using object-literal, and bracket notation, spread syntax in a one-liner? I want to dynamically specify negative values as seen in this exact question.
Rules for unquoted JavaScript Object Literal Keys?
I want to also accomplish this using some method of dynamic bracket notation, using a string equivalent of a negative remainder (modulus operation).
bucketObj[key] reports undefined, since I have not pre set a key to store a corresponding value.  How do I dynamically set a key of an object in either bracket notation, dot notation, or both?

 function toDigitBuckets(array, radix) {
    let bucket = JSON.parse(JSON.stringify([...Array(radix).fill([])]));
    let bucketObj = Object.assign(bucket);
    array.forEach(val => { let key = String.toString(val % 10); bucketObj[key].push(val) });
    return bucket;
  }

  let array = [-7, -49, 84, 39, -31, 95, 7, -8, -13, -32, 93, 40, -81, -30, -57, -57, 49, 66, -64, 42, 35, 29, -57, 41, 93, 34, -45, -15, 51, 16, 97, -88, 52, -69, 56, -16, -91, 51, 10, -21, 80, 78, -5, 18, -20, -98, 72, -94, 11, -83, -31, 13, -21, 39, -47, 8, -98, 95, 52, -18, 77, -11, -38, -46, -98, 48, -45, -4, 76, -32, -81, 67, -82, 9, -60, -20, 0, 33, -12, 77, 65, 45, -22, 99, -47, -83, -81, 10, -99, 16, 23, 5, -57, 89, -62, 9, -16, 79, 5, -2];

  let radix = 10;
  console.log(JSON.stringify(toDigitBuckets(array, radix)));

A: You can use Array#reduce with an object as the accumulator. Each time a new key is encountered, first set that property value to be an empty array.

function toDigitBuckets(array, radix) {
  return array.reduce((acc, curr) =>
    ((acc[curr % radix] ??= []).push(curr), acc), {});
}
let array = [-7, -49, 84, 39, -31, 95, 7, -8, -13, -32, 93, 40, -81, -30, -57, -57, 49, 66, -64, 42, 35, 29, -57, 41, 93, 34, -45, -15, 51, 16, 97, -88, 52, -69, 56, -16, -91, 51, 10, -21, 80, 78, -5, 18, -20, -98, 72, -94, 11, -83, -31, 13, -21, 39, -47, 8, -98, 95, 52, -18, 77, -11, -38, -46, -98, 48, -45, -4, 76, -32, -81, 67, -82, 9, -60, -20, 0, 33, -12, 77, 65, 45, -22, 99, -47, -83, -81, 10, -99, 16, 23, 5, -57, 89, -62, 9, -16, 79, 5, -2];
let radix = 10;
console.log(toDigitBuckets(array, radix));
.as-console-wrapper{max-height:100%!important;top:0}


text:
Q: Zend Framework: Is it possible to override some of the validator error messages, when using built in translator? I've used validator errors customization example from this answer: https://stackoverflow.com/a/4881030/822947, but I need to override some of translated errors with addValidator() or setMessage()/setMessages(). Examples below doesn't work (seems, built in translator has priority?)... How can I do it?
$field->addValidator ('Alpha', false, array ('messages' => array (Zend_Validate_Alpha::NOT_ALPHA => 'My msg')));

$Alpha = new Zend_Validate_Alpha ();
$Alpha->setDisableTranslator (true);
$Alpha->setMessage ('My msg', Zend_Validate_Alpha::NOT_ALPHA);

$Alpha->setMessages (array (Zend_Validate_Alpha::NOT_ALPHA  => 'My msg'));
$field->addValidator ($Alpha);

UPDATE
The problem not in the way I add validator and set messages to it.
My goal is to localize all error messages. But for some form fields I need to add more specific messages.
For example, in my lang/translate.php I have common
Zend_Validate_Alpha::NOT_ALPHA => 'Value contains non alphabetic characters',
but for name field I need more specific
Zend_Validate_Alpha::NOT_ALPHA => 'Field can contain only alphabetic characters and spaces',
The problem is specific message ignored when I enable built in translator. So for example code
$form = new Zend_Form ();

$validator = new Zend_Validate_Alpha ();
$validator->setMessages (array (
    Zend_Validate_Alpha::NOT_ALPHA => 'xxx %value% x'
));

$form->addElement ('text', 'digit', array (
    'validators' => array (
        $validator
    )
));

$name = new Zend_Form_Element_Text ('name');
$name->addValidator ('Alpha', true, array (
    'allowWhiteSpace' => true,
    'messages' => array
    (
        Zend_Validate_Alpha::NOT_ALPHA => 'my more specific localized msg',
    )
));

$form->addElement ($name);

$form->isValid (array (
    'digit' => '___',
    'name' => '___',
));

Zend_Debug::dump ($form->getMessages ());

when translator disabled, I have
array(2) {
  'digit' =>
  array(1) {
    'notAlpha' =>
    string(9) "xxx ___ x"
  }
  'name' =>
  array(1) {
    'notAlpha' =>
    string(30) "my more specific localized msg"
  }
}

when translator enabled, I have messages from lang/translate.php
array(2) {
  'digit' =>
  array(1) {
    'notAlpha' =>
    string(104) "common localized msg"
  }
  'name' =>
  array(1) {
    'notAlpha' =>
    string(104) "common localized msg"
  }
}

A: The problem is that Alpha validator does not support options array in parameters to constructor. You have to set them separatelly.
    $form = new Zend_Form ();

    $validator = new Zend_Validate_Alpha ();

    /* Custom error message */
    $validator->setMessages (array (
        Zend_Validate_Alpha::NOT_ALPHA => 'xxx %value% x'
    ));

    $form->addElement ('text', 'digit', array (
        'validators' => array (
            $validator
        )
    ));

    $form->isValid (array (
        'digit' => '___'
    ));

    Zend_Debug::dump ($form->getMessages ());

Update
The problem is with your translator then.
I have my translator configured like this:
resources.translate.adapter = Array
resources.translate.data = APPLICATION_PATH "/test-translate"

file en.php:
return array (
                "notAlpha" => 'my Translated alpha'
);

and it works.


text:
Q: Who is the boy who gives Superman of other Earth his suit? In the animated movie Justice Society: World War II, there is a boy who gives Superman of other Earth his suit, and said that someone said to give it to him. Who is the boy, and who gave the suit to him?

A: It was almost certainly Dr. Fate who gave the package to the boy. This is strongly hinted at by something he says in a later scene:

Dr. Fate: No! He's not ready yet! Yes, he's received the package, but he doesn't know what it means!

It was implied that Dr. Fate knew certain things about the future...

 ... for example, he told Hawkman that he'd "see her again soon" (likely referring to Hawkgirl, who apparently died a long time ago in this movie),  seemingly predicting the fact that Hawkman would later be killed by the Atlanteans.

He also muttered the following (seemingly to himself, though he was probably talking to Nabu)...

Dr. Fate: Should we tell them? Yes, yes. They should know. They should know.

Dr. Fate: Dead. They're all going to be dead. They need to know. They should know.

... implying that he knew about some impending catastrophe, possibly involving the demise of everyone in the JSA.

 This event did not occur in the movie, so it may be something that will come to pass in a sequel.

And we saw that Dr. Fate was at least partially responsible for the Barry Allen Flash  arriving on Earth-One, so it definitely seemed like he was orchestrating events to ensure that all the heroes would be where they were required at the appropriate time, almost like a Chess master moving pieces around a board.
As for the identity of the boy in your image, that's much harder to determine. There is at least a possibility that he's a new character created for the movie, rather than one adapted from the comics. However, he did say something (which I've bolded in the quote below) implying that there may be more to his story, which could be expanded upon in a sequel:

Unnamed Boy: It's you. He said you would come... and here you are. This is yours. I'm supposed to give this to you.
Clark Kent: What are you talking about, kid?
Unnamed Boy: Take it. Use it. You have to make sure it never happens. I'm sure that's why I'm back here now. He said you'd know what to do.
Clark Kent: Who said?!

This dialogue is very much open to interpretation, but it implies that he may be from the future, perhaps from the time of the impending catastrophe hinted at by Dr. Fate. It's impossible to say with certainty though, because, aside from his appearance, the movie doesn't offer any more clues as to who he is, and the character isn't listed in any credits that I've been able to find. It's also a little too soon after the movie's release to expect any Word of God clarification on this.
I've seen some speculation that he could be Kamandi, the Last Boy on Earth. Again, there's no way to be sure of that, but there is a vague physical resemblance, and it would fit with him being sent back from a post-apocalyptic future, if that is indeed what happened. That said, I'm not aware of Kamandi ever interacting with Superman or the JSA in the comics.


text:
Q: append the text to the route when use enter the site i want when use enter the site append the ?rtl=false or ?rtl=true ;
i write this code in the appcomponent.ts :
this.router.events.pipe(
      filter(event => event instanceof NavigationEnd)).subscribe(event => {
  let lang = this.translationService.getCurrentLang().lang
  if(lang==='fa')
  {
    this.router.navigate([event['url']+'rtl=true'])
  }else{
    this.router.navigate([event['url']+'?rtl=false'])
  }
});

but it redirect me to this url and the browser is going to hang .
localhost:4200/apps/dahboard/user-manager?12252525252525252DUfalse26556465465465465465465465464646897489........................ .
how can i sovle this problem ????

A: UPDATED
After discussion in the comments, unfortunately, was realised that the problem belongs not to this piece of code. I've tested it on an angular app and it works as expected. You need to check other listeners on router, perhaps one of them spoils the url.
ORIGINAL
Looks like you missed ? in this.router.navigate([event['url']+'rtl=true']).
this.router.navigate([event['url']+'rtl=true'])

this.router.navigate([event['url']+'?rtl=true']) // <- here ?

and the best way would be to use queryParams
this.router.events.pipe(filter(event => event instanceof NavigationEnd)).subscribe(event => {
  let lang = this.translationService.getCurrentLang().lang
  if (event['url'].match(/\brtl=\b/)) {
    // nothing to do, we've been redirected already
  } else if (lang === 'fa') {
    this.router.navigate([event['url']], {queryParams: {rtl: 'true'}});
  } else {
    this.router.navigate([event['url']], {queryParams: {rtl: 'false'}});
  }
});


text:
Q: Disable Spotlight to search certain type of files (e.g. based on file extension)? I have searched for this one.. without luck.
Especially, I would like Spotlight not to index target/ folders.
Thanks for any hint.


text:
Q: Where does Juju store a log of all commands run and their output for each unit? Sometimes when deploying a service (and more specifically a new unit) for a Juju charm, an error occurs and there seems to be no way of finding out exactly what it was.
Is there some sort of output log of all commands the unit ran?

A: It appears that each unit stores a log of the commands run in /var/log/juju/unit/unit-service_name-service_number.log. You can access it by taking advantage of Juju's ssh command like so:
juju ssh service_name/service_number
This will drop you into a shell for that unit. You can then use a text editor or even just cat | less to read the log.

A: you can use juju debug-log to get a distributed log of all operations by all agents. It allows suppressing things by log level, so give juju debug-log -h a read. It does miss a few things, but for the most part it should give you what you are looking for.
The following command shows all the logs from the beginning of time. So it will also show the logs from before you started juju debug-log
juju debug-log --replay

A: You can find the complete log inside the data-dir set in your environments.yaml file.
Open it with gksudo <path_to_data-dir>, navigate thru the folders to your units folder, open the service folder you want to have a look at and look at the unit.log file.


text:
Q: houghlinesp and thresholding I am using opencv Houghlinesp to detect lines in a parking lot. Here is the source image
When I did a hough transform-p to detect the lines, I got final image like this.
It did detect empty spaces. Any ideas how these noisy lines on top of the cars can be removed? Or any direction on alternative algorithms or approaches highly appreciated.
img = cv.imread('Parking-Lot.jpg')
threshold=100
minLineLength = 60
rho=2
maxLineGap=20
theta = np.pi/180
edges = cv.Canny(img, 100, 200)
lines = cv.HoughLinesP(edges, rho, theta, threshold, np.array([]), minLineLength =minLineLength , maxLineGap=maxLineGap)
 for i in range(len(lines)):
    for line in lines[i]:
        cv.line(img, (line[0],line[1]), (line[2],line[3]), (0,255,0), 2)
cv2.imwrite("lines.jpg", img)

A: You can remove most of the noise by thresholding your image before you apply the edge detection. That way you will remove (most of) the cars and keep your white space lines you are interested in:
import cv2
import numpy as np

img = cv2.imread('Parking-Lot.jpg')
threshold=100
minLineLength = 60
rho=2
maxLineGap=20
theta = np.pi/180

# here you convert the image to grayscale and then threshhold to binary
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray,180,255,cv2.THRESH_BINARY)

# continue with the threshholded image instead
edges = cv2.Canny(thresh, 100, 200)
lines = cv2.HoughLinesP(edges, rho, theta, threshold, np.array([]), minLineLength =minLineLength , maxLineGap=maxLineGap)
for i in range(len(lines)):
  for line in lines[i]:
     cv2.line(img, (line[0],line[1]), (line[2],line[3]), (0,255,0), 2)
cv2.imwrite("lines.jpg", img)

This will yield you a much cleaner result:

Feel free to experiment with the threshold parameters; you will need to find a threshold that excludes most of the cars while keeping all the lines that you want to detect.


text:
Q: ModuleNotFoundError: No module named 'websockets' My python version is 3.6. And I am using this tutorial for Statecraft AI (https://pythonprogramming.net/building-neural-network-starcraft-ii-ai-python-sc2-tutorial/). I imported SC2 module from here (https://github.com/daniel-kukiela/python-sc2).
I am facing this error while I run
ModuleNotFoundError: No module named 'websockets'

A: try using pip3, it worked for me.

A: Needed to install websockets for this
https://websockets.readthedocs.io/en/stable/intro.html#installation

A: I've spent hours trying to install and uninstall websocket and websocket-client but the true module that I need is named websocket_client.
pip install websocket_client


text:
Q: CocosSharp game on Android startup takes a long time to draw graphics We have a somewhat simple game written using CocosSharp. The game is within another Xamarin.Forms app. When the player clicks to play the game, we bring them to a splash screen. On iOS this screen displays immediately but on Android, the screen is just black for about 15 seconds. The music plays pretty much immediately on both platforms.
The following is called from the ViewCreated event of the CocosSharpView.
InitializeAudio();
var scene = new Scenes.SplashScene(GameView);
GameView.RunWithScene(scene);

The hang up seems to be when creating labels. The following take ~10 seconds to complete with 99% of it being in the constructor of the first label. We call our CreateText in the constructor.
    private void CreateText()
    {
        var label = new CCLabel("Text 1", "BD_CARTOON_SHOUT.TTF", 80)
        {
            PositionX = layer.ContentSize.Width / 2.0f,
            PositionY = layer.ContentSize.Height / 1.5f,
            Color = CCColor3B.DarkGray
        };
        layer.AddChild(label);

        label = new CCLabel("Text 2", "BD_CARTOON_SHOUT.TTF", 60)
        {
            PositionX = layer.ContentSize.Width / 2.0f,
            PositionY = 50f,
            Color = CCColor3B.DarkGray
        };

        layer.AddChild(label);
    }

Keep in mind this only happens on Android.
Thanks in advance!

A: I had the same issue several weeks ago. The problem was CCLabel constructor
where it didn't know which type of font are you using and therefore trying all other types before finally trying the last one which is correct. You need to specify font type in CCLabel constructor like this:

    var label = new CCLabel("Text 1", "BD_CARTOON_SHOUT.TTF", 80, CCLabelFormat.SystemFont);

Hope it helps.


text:
Q: What does "off my case" mean? What does "off my case" mean? It is the title of a part in a book. I tried to google it and I find "get off my case", meaning "stop nagging me".
The book is called "Case for Christ - for kids" and is a book where the author investigates whether the stories about Jesus in the Bible are true or not.
I have only just begun to read that part of the book, so I cannot say exactly what its about. But it seems to be different stories about kids in different situations together with other kids and they are "doing the right thing". Helping others and sometimes sharing their faith, even to people that have been mean to them.

A: A quick check on Amazon tells us the following about the book:
The Case for Christ: A Journalist's Personal Investigation of the Evidence for Jesus (Case for ... Series)
A closer looks shows that there is a series of books on religious faith entitled The Case For......
The expression: The case for... generally means the evidence for or the argument for.
Presumably, the chapter heading that you are referring to is a play on the title of the book and the series.
As you say, off my case is often proceeded by Get and means stop pestering me.
In this case, it is not possible to say how the author is using the chapter heading without reading more. But it might be a way of saying that what follows does not relate to the theme of the book. It's hard to know.

A: The idioms "the case for/against" and "on/off the case" generally refer to an investigation in order to prove something. A defense lawyer pursues a case for their client, a detective builds the case against a suspect. Their bosses would put them on the case, or if they perform poorly, take them off the case. If someone says, "I can't find my keys!" You might humorously say, "I'm on the case!" before rushing off to search for them.
When outside the context of some actual investigation, "getting on/off someone's case" is a specific usage of this broader sense. This casual slang usually sounds like an immature or rude complaint. It stretches the meaning of investigating to mean nagging or pestering with questions.


text: Q: Newforms are eigenforms for the diamond operators Let $S_k(\Gamma_1(N))^{\textrm{new}}$ denote the new subspace of the space of weight $k$ cusp forms on $\Gamma_1(N)$. Section 5.8 of Diamond and Shurman's modular forms book is supposed to show that if $f \in S_k(\Gamma_1(N))^{\textrm{new}}$, then $f$ is an eigenform for all of the Hecke operators $T_n$ and diamond operators $\left<n\right>$. It seems to me there is a gap though, as the first paragraph of the section ends by noting that it is clear that $f$ is an eigenform for $\left<n\right>$ if $\gcd(n,N) > 1$. since in this case  $\left<n\right>$ is the zero operator. Then it says, "Thus the only operators in question are the $T_n$." Well, no... The operators $\left<n\right>$ for $\gcd(n,N) = 1$ are never addressed. In fact  it seems to me that then the entire new subspace must be contained in a single $\chi$-eigenspace $S_k(N,\chi)$ for some Dirichlet character $\chi$ modulo $N$, since these eigenspaces are linearly disjoint.


text:
Q: How to create a point cloud in Octave? I'm trying to run a MATLAB script to reconstruct a point cloud in Octave. Unfortunately the functions ptCloud and pcwrite are not implemented in Octave. Is there a way to replace them in Octave?
My code looks like this.
rad = data(:,1).*3.14./180;
[x,y,z] = pol2cart(rad,data(:,2),data(:,3));
M = [x,y,z];
ptCloud = pointCloud(M);
pcwrite(ptCloud,'S4P1','PLYFormat','ascii');


text:
Q: Why am I getting error CS0120 if I have no "static" in my code? I'm making a FPS game and I was trying some scripts for the guns but Unity keeps showing the error CS0120 but the problem is that I'm not using anything "static" or that needs it, at least I think I'm not using.
Main code:
{
    public float damage = 10f;
    public float range = 100f;

    public Camera fpsCam;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Mouse0))
        {
            Shoot();
        }
    }

    void Shoot()
    {
        RaycastHit hit;
        if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
        {
            Debug.Log(hit.transform.name);

            healthPoints hp = hit.transform.GetComponent<healthPoints>();
            if(hp != null)
            {
                //Here is where I get the error
                healthPoints.TakeDamage(damage);
            }

        }
    }

}

HP code:
public class healthPoints : MonoBehaviour
{
    public float health = 100f;

    public void TakeDamage(float amount)
    {
        health -= amount;

        if (health <= 0f)
        {
            Die();
        }
    }

    void Die()
    {
        Destroy(gameObject);
    }
}

"Error  CS0120  An object reference is required for the non-static field, method, or property 'healthPoints.TakeDamage(float)'"

A: The problem with this code snippet is, that you have to use the instantiated object hp, not the class healthPoints to call the non-static method TakeDamage():
if(hp != null)
{
   // Here is where I get the error
   hp.TakeDamage(damage);
}

Only static methods of a class can be accessed without instantiating an object first of the class.


text:
Q: Removing non-alphanumeric characters from string in MapBasic? I have a user-entered string which I am using as a search term. I would like to display the results in a table named "SearchResults_"+SearchString. However the string could feasibly contain characters that can't be used for table names - spaces would be the most common and there are plenty of other strange characters in place names.
I would like to strip all special, non-alphanumeric characters from a string.
As far as I can see there aren't any built-in functions that would achieve this.
I can loop through the characters easily enough but comparing each one to a white-list is proving harder than I expected. I could do it with a epic if/else statement but that's just dirty! VB.net has IsLetterOrDigit() which would be nice. PHP has ctype_alnum(). In Python I'd just check it against a white-list string.
Any ideas?

A: Well that wasn't so hard.
Declare Sub Main
Declare Function RemoveSpecialChars(byval str as string) as String

Sub Main
    Dim t as string
    t = "this is a string with spaces and ' ! * & ^ % $ £ punctuation"

    Print Chr$(12) + "Original String: " + t
    Print "Tidy string: " + RemoveSpecialChars(t)

    End Program
End Sub

Function RemoveSpecialChars(byval str as string) as String
    Dim chr, out, nicechars as String
    Dim i, l as Integer

    nicechars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
    l = Len(str)

    For i = 1 to l
        chr = Mid$(str, i, 1)
        If InStr(1, nicechars, chr) > 0 Then
            out = out + chr
        End If
    Next

    RemoveSpecialChars = out
End Function