text:
Q: How to write postgres query for below table? This is very weird query and I am not sure how to proceed with it.
Below is the table.
id  descendentId    attr_type   attr_value
1   {4}               type_a
2   {5}               type_a
3   {6}               type_a
4   {7,8}             type_b
5   {9,10}            type_b
6   {11,12}           type_b
7   {}                type_x    TRUE
8   {}                type_y    "ABC"
9   {}                type_x    FALSE
10  {}                type_y    "PQR"
11  {}                type_x    FALSE
12  {}                type_y    "XYZ"

Input for the query will be 1,2,3.. output should be "ABC".
Logic is - loop through descendantId from 1,2,3 until attr_type x is reached. If attr_type x is reached which is 7,9 and 11 then check which one is true. For e.g. 7 is true, then
get it's sibling of type type_y (check row 4) which is 8 and return it's value.
All this is string format.

A: This is really a complicated data model for such a query, but my way is to flatten out the hierarchy first:
WITH RECURSIVE
   typex(id, use) AS (
         SELECT id, attr_value::boolean
         FROM weird
         WHERE attr_type = 'type_x'
      UNION
         SELECT w.id, typex.use
         FROM weird w
            JOIN typex
               ON ARRAY[typex.id] <@ w.descendentid
   ),
   typey(id, value) AS (
         SELECT id, attr_value
         FROM weird
         WHERE attr_type = 'type_y'
      UNION
         SELECT w.id, typey.value
         FROM weird w
            JOIN typey
               ON ARRAY[typey.id] <@ w.descendentid
   )
SELECT id, value
FROM typex
   NATURAL JOIN typey
WHERE use
  AND id = 1;

┌────┬───────┐
│ id │ value │
├────┼───────┤
│  1 │ ABC   │
└────┴───────┘
(1 row)

A: This can be solved with recursive CTEs:
with recursive params(id) as (
  select e::int
  from   unnest(string_to_array('1,2,3', ',')) e -- input parameter
),
rcte as (
    select '{}'::int[] parents,
           id,
           descendent_id,
           attr_type,
           attr_value
    from   attrs
    join   params using (id)
  union all
    select     parents || rcte.id,
               attrs.id,
               attrs.descendent_id,
               attrs.attr_type,
               attrs.attr_value
    from       rcte
    cross join unnest(descendent_id) d
    join       attrs on attrs.id = d
    where      d <> all (parents) -- stop at loops in hierarchy
)
select y.attr_value
from   rcte x
join   rcte y using (parents) -- join siblings
where  x.attr_type  = 'type_x'
and    x.attr_value = 'true'
and    y.attr_type  = 'type_y'

http://rextester.com/YDLDH11322


text:
Q: Connect to AWS MQTT Trying to connect to AWS IOT device from C# by using M2MQTT library :
public void connect()
        {

            const string IotEndpoint =  "a3cnel9bxxxxx-ats.iot.eu-central-1.amazonaws.com";
            const int BrokerPort = 8883;

            const string Topic = "topic_1";

            X509Certificate clientCert = X509Certificate2.CreateFromCertFile("C:\\cpp_test\\certs\\pi4\\certificate.pem.crt");
            X509Certificate caCert = X509Certificate.CreateFromCertFile("C:\\cpp_test\\certs\\Amazon-root-CA-1.pem");

            MqttClient client = new MqttClient(IotEndpoint, BrokerPort, true, caCert, clientCert, MqttSslProtocols.TLSv1_2);

            String message = "Test message";
            string clientId = Guid.NewGuid().ToString();

        try
        {
            client.Connect(clientId);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            if (ex.InnerException != null)

                MessageBox.Show("Inner exception: {0}", ex.InnerException.Message);

        }

            client.Publish(Topic, Encoding.UTF8.GetBytes(message));

        }

Got exception:
 Received an unexpected EOF or 0 bytes from the transport stream.

What might be wrong? Where is starting point of problem solving?

A: Getting no data is often a result of the SSL handshake failing or protocols not being supported, verify the certificates and protocols are correct.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to completely DISABLE any MOUSE CLICK After the user clicks on...."log in" button, and other events, I made a loading script -to let users know they have to wait (Until ajax replies back).
How can I DISABLE any MOUSE CLICKS (right click, left click, double click, middle click, x click), on div id="doc"?

I want to add that code to loading.js

HTML

...

   ...
   <input type="button" value="Login" id="login" />
   ...

loading.js
function load_bar(x)
{
    if (x==0)
    {
    $(document.body).css( {"cursor": "default"} );
    $("body").css( {"cursor": "default"} );
    $("#loading").css("visibility", "hidden"); //modal window
//  $("#doc").....ENABLE all clicks (left/right/etc)
    }

    else if (x==1)
    {
    $(document.body).css( {"cursor": "wait"} );
    $("body").css( {"cursor": "wait"} );
    $("#loading").css( {"visibility": "visible"} ); //modal window
//  $("#doc").....DISABLE all clicks (left/right/etc)
    }

    else
    {
    return alert("Wrong argument!");
    }
}

jQuery
$(document).ready(function()
{
//AJAX
$("#login").click(function()
{
    load_bar(1); //DISABLE clicks and show load_bar
    $(":input").attr("disabled", true);

$.post(
    ...
    function(data)
    {
    ...
    load_bar(0); //ENABLE clicks and hide load_bar
    ...
    } //END: if:else
}); //END:$.post
    ...
}); //END:ajax
}); //END:jQuery

A: something like:
    $('#doc').click(function(e){
       e.preventDefault()
       e.stopImmediatePropagation() //charles ma is right about that, but stopPropagation isn't also needed
});

should do the job
you could also bind more mouse events with replacing for:
edit:
add this in the feezing part
    $('#doc').bind('click mousedown dblclick',function(e){
       e.preventDefault()
       e.stopImmediatePropagation()
});

and this in the unfreezing:
  $('#doc').unbind();

A: You can add a simple css3 rule in the body or in specific div, use pointer-events: none; property.

A: You can overlay a big, semi-transparent
 that takes all the clicks. Just append a new
 to  with this style:
.overlay {
    background-color: rgba(1, 1, 1, 0.7);
    bottom: 0;
    left: 0;
    position: fixed;
    right: 0;
    top: 0;
}

A: To disable all mouse click
var event = $(document).click(function(e) {
    e.stopPropagation();
    e.preventDefault();
    e.stopImmediatePropagation();
    return false;
});

// disable right click
$(document).bind('contextmenu', function(e) {
    e.stopPropagation();
    e.preventDefault();
    e.stopImmediatePropagation();
    return false;
});

to enable it again:
$(document).unbind('click');
$(document).unbind('contextmenu');

A: The easiest way to freeze the UI would be to make the AJAX call synchronous.
Usually synchronous AJAX calls defeat the purpose of using AJAX because it freezes the UI, but if you want to prevent the user from interacting with the UI, then do it.


text:
Q: Checkbox checked based on Databased value I have a dynamic checkbox. All the checkbox has dynamic ID as shown in code below. This checkbox is bind using "TABLE1".
<input type="checkbox" class="level-one" id="22" name="chkRoles" value="RecordOne">
<input type="checkbox" class="level-one" id="22" name="chkRoles" value="Recordtwo">
<input type="checkbox" class="level-one" id="19" name="chkRoles" value="Recordthree">
<input type="checkbox" class="level-one" id="30" name="chkRoles" value="RecordFour">
<input type="checkbox" class="level-one" id="35" name="chkRoles" value="RecordFive">
<input type="checkbox" class="level-one" id="25" name="chkRoles" value="RecordSix">

I am fetching the data from other TABLE, let's say TABLE2. Which contain value19,22,25.
var sectionLevelOne = "19,22,25";
var levelArrayOne = sectionLevelOne.split(",");
$.each(levelArrayOne, function (index, value){
       $("chkRoles_"+id).prop("checked",true);
});

I want to checked those CHECKBOX whose ID is "19,22,25".

A: Firstly note that you have multiple elements with the same id. This is invalid as id attributes have to be unique. If you cannot achieve that, use data-id to store custom data on the element.
That aside, your code is not building a valid id selector based on the HTML you've shown as chkRoles is the class, not the id. You can also simplify the logic. Try this:

"19,22,25".split(',').forEach(id => {
  $(`[data-id="${id}"]`).prop('checked', true);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="level-one" data-id="22" name="chkRoles" value="RecordOne">
<input type="checkbox" class="level-one" data-id="22" name="chkRoles" value="Recordtwo">
<input type="checkbox" class="level-one" data-id="19" name="chkRoles" value="Recordthree">
<input type="checkbox" class="level-one" data-id="30" name="chkRoles" value="RecordFour">
<input type="checkbox" class="level-one" data-id="35" name="chkRoles" value="RecordFive">
<input type="checkbox" class="level-one" data-id="25" name="chkRoles" value="RecordSix">


text:
Q: Update Facebook Page Tab with PHP GraphApi Is there a way to update a Facebook Page Tab details (custom_name, custom_image_url) via GraphAPI? In earlier API versions it was possible to update a tab by issuing POST request to this endpoint:
[PAGE_ID]/tabs/app_[APP_ID]
But now, I get an exception (#803) Some of the aliases you requested do not exist: v2.2110615188986707...
Update:
I just figured out that it works, but I'm currently having problems with custom_image_url [as I have a local development url that is not accessible by facebook ;)] so I'll try to upload a file instead of giving the url to it...

A: Updating
You can't perform this operation on this endpoint.
https://developers.facebook.com/docs/graph-api/reference/page/tabs/
ps: no more update in latest fb api, i also can update page tab custom name, etc previous, by recently fb api had remove this api, so we can't do anything about it.


text:
Q: xpath - get value of sibling of node if node contains text I have this XML structure:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <a xmlns="#">
             <b>
                <c>
                   <d>dd</d>
                   <e>ee</e>
                   <f>ff</f>
                   <g>gg</g>
                </c>
                <c>
                   <d>ddd</d>
                   <e>eee</e>
                   <f>fff</f>
                   <g>ggg</g>
                </c>
                <c>
                   <d>dddd</d>
                   <e>eeee</e>
                   <f>ffff</f>
                   <g>gggg</g>
                </c>
             </b>
       </a>
     </soap:Envelope>

My goal, is get all <f>, which contains specific string (lets say "f" for this example).
This is done, by this:
$result = $xml->xpath("//*[text()[contains(.,'f')]]");

This example, returns me an array, which looks like this:
    array (3)
      0 => SimpleXMLElement #f4ff
         0 => "ff" (2)
      1 => SimpleXMLElement #617e
         0 => "fff" (3)
      2 => SimpleXMLElement #863a
         0 => "ffff" (4)

Now, this is everything all right. Now comes the problem. What I need, is value of <d>, if <f> contains "f", but I need it both in same array, like this:
 array (3)
      0 => SimpleXMLElement #f4ff
         0 => "dd" (2)
         1 => "ff" (2)
      1 => SimpleXMLElement #617e
         0 => "ddd" (3)
         0 => "fff" (3)
      2 => SimpleXMLElement #863a
         0 => "ffff" (4)
         0 => "ffff" (4)

I hope that my question is understandable. Can somebody please advice me, how to achieve this?

A:
What I need, is value of <d>, if <f> contains "f"

That's easy:
//f[contains(. 'f')]/../d

but I need it both in same array

That's not so easy. You could do this:
//f[contains(. 'f')]/../*[self::f or self::d]

which would give you a list of <f>s and <d>s where <f> contains "f", but they would not be "grouped" into pairs. Nothing you can select with a single XPath expression would be - flat node lists is the only thing XPath can give you. Depending on how regular your input data is, this might be good enough.
If you need the "pairs" context, break up the operation. Select all <c> where the <f> contains "f":
//c[contains(f, 'f')]

and for each of those, select <f> and <d> in a second step:
./*[self::f or self::d]

Note that XPath returns nodes in document order. If that's not predictable in your input, select the nodes individually instead of with a single expression.

A: The answers is :
$result = $xml->xpath("//*[text()[contains(.,'f')]]/parent::*");

Thank all those, who tried to think about the problem. Have a nice day.


text:
Q: how to make file accessible to administrators only?
Possible Duplicate:
setting UAC settings of a file in C#

I want to set file permissions so only those with administrative privileges can change it.
Can anyone give me a good example on how to do this in c#?
UPDATE
I've tried various things with FileSecurity, and I simply can't get a hang of it.
Here are the permissions that I'd like to impose on file:

A: Administrators can access anything (doesn't matter privileges, so the problem will be other users. The fourth argument of System.Io.File.Create. is an System.Security.AccessControl.FileSecurity object. That's what you need.


text:
Q: Don't want that Postfix+Dovecot reject "recipient not found" mails I'm writing a Milter for Postfix, that handles incoming messages in a server (Postfix+Dovecot) with virtual domains and users. Communication beetweend Postfix and the Milter are done with the Sendmail Milter Protocol V 2
I really need that Dovecot (and Postfix by consequence) does not reject messages with invalid recipient, because I need the Milter to do this check (and reject as weel).
This is needed because i'm writing a PEC mail server (Pec stand for Posta Elettronica Certificata, that is an Italian implementation for certified mail).
When receiving mails with incorrect recipient, I need to produce a specific receipt in a form of an e-mail.
But Postfix in this case (told by dovecot) reject the mail BEFORE sending it to the Milter.
I've tried to search this in the documentation, but were not able to find this specific need.
I've attached PostFix configuration....
compatibility_level = 2
queue_directory = /var/spool/postfix
command_directory = /usr/local/sbin
daemon_directory = /usr/local/libexec/postfix
data_directory = /var/db/postfix
mail_owner = postfix
myhostname = me2.andxor.it
mydomain = nessuno
myorigin = $myhostname
mydestination = localhost.$mydomain, localhost, localhost.localdomain
local_recipient_maps =
mynetworks = cidr:$config_directory/mynetworks
    recipient_delimiter = +
home_mailbox = Maildir/
debug_peer_level = 2
debugger_command =
     PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin
     ddd $daemon_directory/$process_name $process_id & sleep 5
sendmail_path = /usr/local/sbin/sendmail
newaliases_path = /usr/local/bin/newaliases
mailq_path = /usr/local/bin/mailq
setgid_group = maildrop
html_directory = /usr/local/share/doc/postfix
manpage_directory = /usr/local/man
sample_directory = /usr/local/etc/postfix
readme_directory = /usr/local/share/doc/postfix

inet_protocols = ipv4
meta_directory = /usr/local/libexec/postfix
shlib_directory = /usr/local/lib/postfix
#smtpd_milters = inet:127.0.0.1:10099, { inet:127.0.0.1:11332, default_action=accept}
#smtpd_milters = inet:127.0.0.1:11332, inet:127.0.0.1:10099
#smtpd_milters = { inet:127.0.0.1:11332, default_action=accept }, inet:127.0.0.1:10099
smtpd_milters = inet:127.0.0.1:10099

virtual_mailbox_domains=me2.andxor.it
virtual_mailbox_maps = mysql:$config_directory/mysql-virtual-mailbox-maps.cf
virtual_alias_maps = hash:$config_directory/hash-aliases.txt
virtual_transport = lmtp:unix:private/dovecot-lmtp
lmtp_destination_recipient_limit = 1

smtpd_sasl_auth_enable = yes
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_relay_restrictions =
    permit_mynetworks,
    permit_sasl_authenticated,
    reject_unauth_destination
smtpd_sasl_authenticated_header=yes

And dovecot configuration
protocols = imap pop3 lmtp
protocols = imap pop3 lmtp

dict {
  #quota = mysql:/usr/local/etc/dovecot/dovecot-dict-sql.conf.ext
  #expire = sqlite:/usr/local/etc/dovecot/dovecot-dict-sql.conf.ext
}

!include conf.d/*.conf

disable_plaintext_auth=no

namespace inbox {
  inbox = yes
  location =
  prefix =
}

passdb {
  driver = sql
  args = /usr/local/etc/dovecot/dovecot-sql.conf.ext
}

userdb {
  driver = static
  args = uid=vmail gid=vmail home=/usr/local/data/mail/domains/%d/%n allow_all_users=yes
}

plugin {
  quota = maildir:User quota
  quota_rule = *:storage=1GB
  # 10% of 1GB = 100MB
  quota_rule2 = Trash:storage=+10%%
  # 20% of 1GB = 200MB
  quota_rule3 = Spam:storage=+20%%
}

service auth {
  unix_listener /var/spool/postfix/private/auth {
    group = wheel
    mode = 0600
    user = postfix
   }
}

service lmtp {
  unix_listener /var/spool/postfix/private/dovecot-lmtp {
    group = wheel
    mode = 0600
    user = postfix
    }
}

service quota-status {
    executable = quota-status -p postfix
    inet_listener {
        port = 12345
        # You can choose any port you want
    }
    client_limit = 1
}

  #quota = mysql:/usr/local/etc/dovecot/dovecot-dict-sql.conf.ext
  #expire = sqlite:/usr/local/etc/dovecot/dovecot-dict-sql.conf.ext
}

A: I've found a solution:
I need to set in main.cf
virtual_mailbox_maps =

and leave it empty.


text:
Q: Convert hex to decimal in swift how to convert hex to decimal in swift?
I have string "423fdf4dfb1115" and I need get this => 18647576781459733.
I try this:
let result = UInt8(strtoul("423fdf4dfb1115", nil, 16))

but app crash...
I use this online convert:
http://www.binaryhexconverter.com/hex-to-decimal-converter

A: let result = UInt64(strtoul("423fdf4dfb1115", nil, 16))

A: The result must be UInt64 (UInt8.max is 255).
There is a convenience initializer, strtoul is not needed.
let string = "423fdf4dfb1115"
let result = UInt64(string, radix:16)


text:
Q: Custom Thread run() not invoke via Spring AOP
I could not able to invoke the thread run() via Spring aop , ie
  Application not invoked the Aspect code .Any suggestion?
Spring 4.0/ Java 1.7

spring-context.xml
    <bean id="pocServiceAspect" class="kbsql.com.poc.POCServiceAspect" />
<aop:config>
        <aop:aspect id="pocServiceAspectId" ref="pocServiceAspect">

         <aop:pointcut id="pointCutAround"
                expression="execution(* kbsql.com.poc.WorkThread.threadRun(..) )" />
            <aop:around method="aroundServiceExtractData"
                pointcut-ref="pointCutAround" />
        </aop:aspect>

    </aop:config>

Given below is Java code to execute :

public class App
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );

        //To get the data using query.
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-context-poc.xml");

        Class<?> myclass=WorkThread.class;
        List<AbsThread> list= new ArrayList<AbsThread>();
        for(int i=0;i<5 ;i++) {
            AbsThread t=(AbsThread)context.getBean(myclass.getSimpleName());
            list.add(t);

        }
        for(int i=0;i<list.size();i++) {
            AbsThread abst=(AbsThread)list.get(i);
            Thread t = new Thread(abst);
            t.start();
        }

    }

 //
}

Given below is Abstract Thread Class:

     public abstract class AbsThread implements Runnable{
        @Autowired protected ApplicationContext context;
        protected String name;
        public String getName() {
            return name;
        }

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

        public void run() {
            try{
                System.out.println(" Abstract Thread starts ");
                threadRun();
                System.out.println(" Abstract Thread ends ");

            }catch(Exception ex){
                System.out.println("Exception "+ex);
            }finally{

            }
        }

        protected abstract void threadRun() throws Exception;
    }

Given below is Thread Implementation:

 @Component("WorkThread")
 public class WorkThread extends AbsThread{

@Override
protected void threadRun() throws Exception {
    // TODO Auto-generated method stub
    System.out.println("Thread Starts Id : "+Thread.currentThread().getId());
    System.out.println("Logic invoked Sucessfully");
    System.out.println("Thread Ends Id : "+Thread.currentThread().getId());
}

}

The Aspect Code given below

 public class POCServiceAspect {
    public void aroundServiceExtractData(ProceedingJoinPoint joinPoint) throws Throwable {
            try{
                System.out.println("Aspect Starts");
                Date startTime = new Date();
                joinPoint.proceed();
                System.out.println("Aspect ends");

            }catch(Exception ex){
                throw ex;
            }
        }

Why aspect is not invoked  when i am starting the thread?


text:
Q: How to set same function property for multiple variable? I was searching for a shortcut to set same property function to multiple variables.
I am trying to achieve something like {var1, var2, var3}.setSomething(true) and (var1, var2, var3).setSomething(true) but it is not working. Is there anyway to get this done?
instead of
var1.setSomething(true)
var2.setSomething(true)
var3.setSomething(true)

How can I write all these in a same line or setting it only once?

A: old school way, write a helper function:
public static void setSomeThing(boolean value, Target ... targets){
    if(targets == null)
        return;

    for(Target target : targets){
        target.setSomeThing(value);
    }
}

for using:
setSomeThing(true,var1,var2,var3);


text:
Q: Troubles with sharing values between different processes I've different processes which waits for an event to occur (changing the state of a sensor)
I coded something like:
def Sensor_1():
    wait_for_change_in_status
    set counter to X
    activate_LED_process.start()

def Sensor_2():
    same function
def Sensor_3():
    same function

def LED():
    start LEDs
    while counter > 0:
        counter -= 1
        time.sleep(1)
    turn off LEDs
    active_LED_process.join()

...

if __name__ == '__main__':
    Sensor_1_process = multiprocessing.Process(target=Sensor_1)
    Sensor_2_process = same
    Sensor... you get it.
    activate_LED_process = multiprocessing.Process(target=LED)

Now I'm stuck with the exchange of the counter value. Having different processes to be able to change the counter to a specific value.
Each sensor should be able to reset the value of the counter.
The LED process should be able to "countdown the counter" and react if the counter reached zero.
What be a proper solution? I read about values, arrays, pipes and queues.
For values and arrays I couldn't find a good documentation. Pipes seem to work only for two processes. And queues seem to not only hold one value (I'd compare a queue to a list - is this correct?)
import RPi.GPIO as GPIO
import time
import multiprocessing
import sys
GPIO.setmode(GPIO.BCM)
GPIO.setup(25, GPIO.IN, pull_up_down=GPIO.PUD_UP)
LED_time = 40  #time how long LEDs stay active (not important at this point)

def Sens_GT():
    name = multiprocessing.current_process().name
    print(name, 'Starting')
    while True:
        GPIO.wait_for_edge(25, GPIO.FALLING)
        time.sleep(0.1)
        print("Open")
        LED_count = multiprocessing.value('i', 40) #For later: implementation of LED_time as a variable
        print(LED_count) #For checking if the counter is set properly
"""
Missing code:

    if "Process is already running":
        go on
    else:
        Count_proc.start()

"""
    print(name, 'Exiting') #Shouldn't happen because of the "while True:"

"""
Missing code:

def Sens_GAR():

def Sens_HT():

"""

def Count():
    name = multiprocessing.current_process().name
    print(name, 'Starting')

"""
Missing code:

Import counter value

"""

    while countdown > 0:
        print(countdown)
        time.sleep(1)
        LED_count -= 1
    print(name, 'Exiting')
    GPIO.cleanup()           # clean up GPIO on normal exit
    Count_proc.join()
    sys.exit(1)

if __name__ == '__main__':
    value_count = mutliprocessing.value('i', 0)
    lock = Lock()

    Sens_GT_proc = multiprocessing.Process(target=Sens_GT)
    Count_proc = multiprocessing.Process(target=Count)

    Sens_GT_proc.start()
    Sens_GT_proc.join()

A: Value
seems to be a good choice for your use case.
However, you don't use it the right way.
After instanciating a value with multiprocessing.Value(), you have to pass the object as an arguments to your sub-processes, as shown in the multiprocessing guide.
So your code should be something like:
def Sens_GT(counter):
    ...
    counter = 40
    ...

def Count(counter):
    ...
    while counter > 0:
        counter -= 1
        time.sleep(1)
    ...
...

if __name__ == '__main__':
    value_count = mutliprocessing.value('i', 0)

    Sens_GT_proc = multiprocessing.Process(target=Sens_GT, args=(value_count,))
    Count_proc = multiprocessing.Process(target=Count, args=(value_count,))

For me, pipes and queues are similar mechanisms, that are very useful in multi-processing contexts.
If you can probably use them in your case, I think they are more suited for data exchange (producers, consumers) than for shared state/value between processes.


text:
Q: How to prevent JavaFX GUI to auto-close after closing the graph generated by JGraphX? There's a button btn in my JavaFX GUI interface. When clicking btn, a graph will be drawn.
But when I close the graph, my JavaFX GUI will auto-close as well, which is not desired.
How can I prevent the JavaFX GUI from auto-close?
If the solution involve embedding the generated graph inside the JavaFX GUI, I am also fine. Thanks!
import javax.swing.JFrame;
import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.view.mxGraph;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class MainFx extends Application {

    @Override
    public void start(Stage primaryStage) {
    Button btn = new Button();
    btn.setText("Draw Graph");
    btn.setOnAction(new EventHandler<ActionEvent>() {

        // draw graph when clicking the button
        @Override
        public void handle(ActionEvent event) {

        JGraphXLearning1 frame = new JGraphXLearning1();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 320);
        frame.setVisible(true);

        }
    });

    StackPane root = new StackPane();
    root.getChildren().add(btn);

    Scene scene = new Scene(root, 300, 250);

    primaryStage.setScene(scene);
    primaryStage.show();
    }

    public static void main(String[] args) {
    launch(args);
    }

    public class JGraphXLearning1 extends JFrame {

          public JGraphXLearning1() {
            super("JGraphXLearning1");
            mxGraph graph = new mxGraph();
            Object defaultParent = graph.getDefaultParent();
            graph.getModel().beginUpdate();
            Object v1 = graph.insertVertex(defaultParent, null, "Hello", 20, 20, 80, 30);
            Object v2 = graph.insertVertex(defaultParent, null, "World", 240, 150, 80, 30);
            graph.insertEdge(defaultParent, null, "Edge", v1, v2);
            graph.getModel().endUpdate();
            mxGraphComponent graphComponent = new mxGraphComponent(graph);
            getContentPane().add(graphComponent);
          }

        }
}


text:
Q: Regex for AMon:1 I'm a bit rubbish with Regex and was wondering if some kind person would be happy to assist!
The format is:

optionally 1, 2 , A or B
Day Name, possibly short or full, eg
  Mon, Tuesday, Thursday, Fr
Colon :  or Space
Integer

The following are valid:
EDIT: included "Mon:20"

Mon:3, Tuesday:6, AWe:9, 2Fr:2, 2Wed 3, Friday 6, Mon:20

The following is not valid:

3Mon:1, Mon3, 3:Wed

I would presume for the day name, we can just check for A-Z,a-z starting with Mo,Tu,We,Th,Fr,Sa,Su ending with a colon or use piping and specify every possibility ie Mo|Mon|Monday|Tu|Tue|Tues|Tuesday, etc.
Thanks ever so much

A: [12AB]?(Mo|Tu|We|Th|Fr|Sa|Su)\w*[: ]\d+

A: This checks the days of the week more strictly than the other answer:
/[12AB]?(
    Mon?|
    Tu(es?)?|
    We(d(n(es?)?)?)?|
    Th(u(rs?)?)?|
    Fri?|
    Sa(t(ur?)?)?|
    Sun?
)(d(ay?)?)?
[: ]\d+/

A: Realised I needed to return true for
TuA:2

This is the solution I've ended up with for the moment:
([12AB]?)[: ]*(Mo|Tu|We|Th|Fr|Sa|Su)(\w*)[: ]*(\d)+

This allows me to pick out the leading A,B,1,2, the day Mo,Tu,We... and whats after the day, "A" in the example above or otherwise "esday" for "Tuesday", and it returns the last digit too.
Thanks everyone for putting me on the right track.


text:
Q: AFNetworking returns no connection despite internet connectivity I'm using AFNetworking to determine whether the user has an internet connection.  It returns false on both wifi and 4G LTE and I have checked to make sure they're operational.
  I have the following code:
-(void)viewDidLoad{
 [[AFNetworkReachabilityManager sharedManager] startMonitoring];

     if ([self connected])
        [self doSomething];
     else
        [self noConnection];
}

- (BOOL)connected {
     NSLog(@"This returns 0 %hhd", [AFNetworkReachabilityManager sharedManager].reachable);
     return [AFNetworkReachabilityManager sharedManager].reachable;
}

-(void)noConnection{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Internet!"
                                                message:@"Sorry, but you don't have an internet      connection at this time.  Please try again later."
                                               delegate:self
                                      cancelButtonTitle:@"OK"
                                      otherButtonTitles:nil];
     [alert show];

 }

A: This is not a solution using AFNetworking but using sample code from apple
Once you have downloaded and imported Reachbility.m and Reachbility.h  files
create a helper function:
-(BOOL)isConnected{
  Reachability *reachability = [Reachability reachabilityForInternetConnection];
  NetworkStatus networkStatus = [reachability currentReachabilityStatus];

  return !(networkStatus == NotReachable);
}

Then use it
if([self isConnected]){
 //connected!
}
else{
  //not connected to internet!
}

Very important
If your project is not using arc

*

*go to target >

*Build Phase >

*double click the Reachability file

*add -fno-objc-arc
Hope this helps


text:
Q: How to query an Entity from a Many-to-Many realtionship dependendt on two ore more conditions in Ktor with the Kotlin Exposed Framework? I have 3 entities:

User

id: Int

name: String

Room

id: Int

name: String

RoomUser

id: Int

room_id: Int (Reference on Room.id)

user_id: Int (Reference on User.id)

Now lets say we have 2 rooms and 3 users:
Rooms:

id
name

1
Room1

2
Room2

Users:

id
name

3
User3

7
User7

9
User9

RoomUsers:

id
room_id
user_id

1
1
3

2
1
7

3
2
7

4
2
9

As you can see, User3 and User7 are in the room Room1 and User7 and User9 are in the room Room2.
In my use case I have given for example 2 users. Now I want to get the room, in which these both Users are.
In this case, when I have given the users User3 and User7 I want to get the room Room1 or when I have given the users User7 and User9 I want to get the room Room2.
How can I write an query with the Kotlin Exposed Framework to get this specific room?

A: In SQL notation it should be like:
SELECT room_id
FROM RoomUsers
where user_id in (3,7)
GROUP BY room_id
HAVING count(*) = 2

In Exposed:
RoomUsers
  .slice(RoomUsers.roomId)
  .select{
     RoomUsers.userId inList listOf(User3.id, User7.id)
  }
  .groupBy(RoomUsers.roomId)
  .having {
    RoomUsers.userId.count() eq 2
  }.map {
    it[RoomUsers.roomId]
  }


text:
Q: JBOSS 7.1 war deployment issue I am new to JBOSS Application server 7.1.
I created war for my application and put it in deployments folder.
Then I started the JBoss 7.1 application server.
War got extracted at some temporary location.
Now for my application We have some configurable properties.
From inside application these properties get modified and get saved in context/web-inf/properties folder.
This works for me when server is running.
But if I restart the server then JBOSS 7.1 again redeploys the war at some different temporary location (instead of using previous location).
Due to this my saved properties get lost.
Is there any way I can prevent this?
Any help will be greatly appreciated.
Thank you in advance.

A: Modifying the resources inside your war at runtime is a very bad idea.
Instead of saving this property file in /web-inf/properties/ put it somewhere else. (for instance $USER_HOME/.myapp/config/)
Why is it a bad idea ?

*

*the problem you have is a good reason (i.e. overridden/lost on re-deploy)

*you can configure some app server so that it re-deploy the app when a resource is modified. (and so it may trigger a re-deploy unexpectedly)

A: Try deploying your WAR through the jboss-cli or through the admin console. It may be re-loading the item in the deployment folder every reboot since that folder is used for hot deployments.
Doing it through the two methods I mentioned may preserve the war and keep the same tmp files.
Tho ben75 is correct and you should move your property files externally.
JBoss also operates by using a Virtual File System (VFS) which I'm not sure if Weblogic, Tomcat or WebSphere utilize themselves.

A: *

*It may work in other application servers, but I have not found that the behaviour you expect is guaranteed by the servlet specification.

*Normally data centers never accept a self-modifying application. One of the reasons is that there is normally no regular backup of extracted war files, because data is just not supposed to be there. Another reason is the need to differ between environments: Initial configuration is most often not the same, and so you have to ship it separately, because the .ear/.war file must always be identical.

*Your implementation is quite complex, if it implements cluster-wide property synchronization correctly.

So if you are not running in a cluster, just write the properties file into a defined directory outside of the application server, and make sure that there is a regular backup. This way configuration is kept, if the application is updated.
In case of a cluster persist the changes into a database, and synchronize the values using JGroups/Infinispan, for example.


text:
Q: Unable to view webpage when url is changed to https in dedicated server i have transered my asp.net website to a dedicated server two days back.earlier it was hosted in a shared hosting.In payment acceptance page rewriting the url using.
If Request.IsSecureConnection = False Then
         HttpContext.Current.Response.Redirect(HttpContext.Current.Request.Url.AbsoluteUri.Replace("http://", "https://"))
End If

this was working fine in shared hosting.
but in dedicated server it is showing 'Unable to connect'
How can i solve this issue.
Thanks in advance.

A: It seems that you don't have a SSL certificate installed and configured in your new server

A: The new site hasn't been configured to allow SSL traffic over 443.
You should verify that the SSL certificate has been installed and that the host headers for your site have been configured to route traffic over 443 to your site using the correct cert.
Try following these steps outlined in the tutotrial.  You should be able to modify your site's binding to handle the HTTPS requests.


text: Q: Custom tool bar menu item xamarin forms I would like to achieve similar tool bar menu item. I would like to add image in left and text in right. Image is font awesome icon. So I would like to create custom template with label . And show like this menu item . I have tried absolute layout with listview . It not working. I am thinking to use picker but it occupy full screen.but it needs to display like in image .. any one please help on this to overcome issue.


text:
Q: Guessing Game program. User thinks of number, computer tries to guess it import java.util.Scanner;
import java.util.Random;

public class GuessHarder {

public static void main(String[] args) {

    Random generator = new Random();
    Scanner reader = new Scanner(System.in);

    String higher = "higher", lower = "lower", correct = "correct", input;
    int guess, random, random2 = 1, random3 = 100, randomLast, cntr = 1;

    random = generator.nextInt(100) + 1;
    randomLast = random;
    System.out.println("Is your number: " + random);
    System.out.println("Input if number should be higher, lower, or correct: ");
    input = reader.next();

    while (!input.equals("correct")){
        if (input.equals("lower")){
            randomLast = random2;
            random2 = generator.nextInt(100) + 1;
            if ((random2 < random) && (random2 < randomLast)){
            random = random2;
            cntr += 1;
            System.out.println("Is your number: " + random);
            System.out.println("Input if number should be higher, lower, or correct: ");
            input = reader.next();
            } else {
                input = lower;
            }
        } else if (input.equals("higher")){
            randomLast = random3;
            random3 = generator.nextInt(100) + 1;
            if ((random3 > random) && (random3 > randomLast)){
            random = random3;
            cntr += 1;
            System.out.println("Is your number: " + random);
            System.out.println("Input if number should be higher, lower, or correct: ");
            input = reader.next();
            } else {
                input = higher;
            }
        }

    }

    System.out.println("Computer took " + cntr + " amount of tries to guess your number");

    }
}

When I input higher or lower it will give me the number higher or lower than the previous respectively but it won't remember previous numbers.
For clarity an example would be:
"Is your number: 65
Input if number should be higher, lower, or correct:
higher
Is your number: 96
Input if number should be higher, lower, or correct:
lower
Is your number: 59
Input if number should be higher, lower, or correct:"
The range by the last input should have been 65-96, but instead it just does 0-96 so I get numbers like 59 that shouldn't be in the range.
What should I change to set it up to remember last two inputs for range instead of just the last.

A: So keep two variables that "remember" the lower and upper bounds.
int lowerBound = 0;
int upperBound = MAX_NUMBER;

Then each time the computer makes a guess you need to update these two numbers.
Once you update the two numbers you need to generate a new guess based on those numbers.
generator.nextInt(upperBound - lowerBound + 1) + lowerBound;

The +1 makes the value inclusive.

A: You have to remember the lower and the upper bound and try to make a random number between them instead of
generator.nextInt(100) + 1;


text:
Q: What is the best way to check the correct work of subdirectory rails production application before update in the production server? I have the production application in the server in a subdirectory like www.server.cl/myapp.
But when I am in the development enviroment (running rails server) the application run on localhost:3000 and I can not check if the routes are 100% correct in the production enviroment (subdirectory) especially the assets paths.

A: Create staging environment (similar or identical to production environment) and deploy and test in this environment before deploy to production environment.
Here is more detail description.


text:
Q: Start bash in certain directory from Windows I am trying to start Bash.exe in the "/mnt" directory.
The following command properly starts bash:
C:\Windows\Sysnative\bash.exe

I have the following .bat file:
C:\Windows\Sysnative\bash.exe -c "cd /mnt/"

Unfortunately, this does not do anything. The same applies to:
C:\Windows\Sysnative\bash.exe --cd "/mnt/"

A: Try:
C:\Windows\Sysnative\bash.exe -c "cd /mnt/ ; exec bash"

That starts a Bash process that cds to '/mnt/' and then replaces itself with a new (interactive) Bash process that is running in the '/mnt' directory.
The code above is only lightly tested, and may or may not meet your requirements.  For alternatives see run bash command in new shell and stay in new shell after this command executes and "Linked" pages from that.


text:
Q: Running ARM docker container with JRE on MACOS I run into the following problem, trying to run ARM docker container on MAC host.
Here is the resource I was referring to
Cross Building and Running Multi-Arch Docker Images
According to the blog above, Docker for Mac has binfmt_misc support built-in, which allows it to execute arm containers on x86 without any additional configuration.
What I need is to test a java app on ARM arch.
To achieve this goal I'm using the following image
arm64v7/openjdk
The problem is when I try to run a java app I'm constantly getting the following error

Digest: sha256:657b2419b8407ee009e4400034e1821426d16305eb6334873b5938030f1d5f85
Status: Downloaded newer image for arm32v7/tomcat:latest
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0xf4de0b90, pid=1, tid=0xe13ff470
#
# JRE version: OpenJDK Runtime Environment (8.0_171-b11) (build 1.8.0_171-8u171-b11-1~deb9u1-b11)
# Java VM: OpenJDK Client VM (25.171-b11 mixed mode linux-aarch32 )
# Problematic frame:
# V  [libjvm.so+0x12eb90]
#
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# An error report file with more information is saved as:
# /usr/local/tomcat/hs_err_pid1.log
Compiled method (c1)    3946  116             java.lang.StringBuilder::toString (17 bytes)
 total in heap  [0xf290f308,0xf290f598] = 656
 relocation     [0xf290f3d4,0xf290f3f4] = 32
 main code      [0xf290f400,0xf290f4e0] = 224
 stub code      [0xf290f4e0,0xf290f530] = 80
 metadata       [0xf290f530,0xf290f53c] = 12
 scopes data    [0xf290f53c,0xf290f554] = 24
 scopes pcs     [0xf290f554,0xf290f594] = 64
 dependencies   [0xf290f594,0xf290f598] = 4
Compiled method (c1)    3951  116             java.lang.StringBuilder::toString (17 bytes)
 total in heap  [0xf290f308,0xf290f598] = 656
 relocation     [0xf290f3d4,0xf290f3f4] = 32
 main code      [0xf290f400,0xf290f4e0] = 224
 stub code      [0xf290f4e0,0xf290f530] = 80
 metadata       [0xf290f530,0xf290f53c] = 12
 scopes data    [0xf290f53c,0xf290f554] = 24
 scopes pcs     [0xf290f554,0xf290f594] = 64
 dependencies   [0xf290f594,0xf290f598] = 4
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
#
qemu: uncaught target signal 6 (Aborted) - core dumped

any thoughts will be appreciated.
Thanks in advance.


text:
Q: TypeScript API for SourceFile creation: how to get syntactic errors information TypeScript API Program has method getSyntacticDiagnostics to get syntactic errors. But if there is no Program, just SourceFile how can I get the same kind of information?
I created SourceFile through
function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile;

A: Remember that fileName (string) parameter in createSourceFile is virtual file name. This fileName (string) is used globaly while using TypeScript library.
The most important thing what you need is what doc comment on createProgam method says. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' that represent a compilation unit. createProgam method as first parameter requires list of strings which are virtual names of files used in this program.
If you don't understand previous 2 theoretical paragraphs I think that comments in sample will help you.
// this is the real code of file. Use fs.readFile, fs.readFileSync or something other to load file real source code.
var code = "class 1X {}";

// I will use this virtual name to reference SourceFile while working with TypeScript API.
var virtualFileName = "aaa.ts";

// initialize SourceFile instance
var sf = ts.createSourceFile(virtualFileName, code, ts.ScriptTarget.ES5);

// Make program as collection of my one virtual file
var prog = ts.createProgram([virtualFileName], {});

// process response as you need.
console.log(prog.getSyntacticDiagnostics(sf));


text:
Q: Max array size using #define
Possible Duplicate:
stack overflow c++

I have the following program for generating prime numbers:
#include<iostream>
#include<cmath>
#include<algorithm>

#define MAX 10000000
using namespace std;

int main(int argc, const char *argv[])
{
    bool prime[MAX+1];
    fill_n(prime,MAX+1,true);
    int baseSqrt,i,j;
    baseSqrt = int(sqrt(MAX+1));
    for(i=2;i<=baseSqrt;i++){
        if(prime[i]){
            for(j=i+i;j<=MAX;j+=i){
                    prime[j]=false;
            }
        }
    }
    return 0;
}

The program works fine for MAX value = 1000000. But when I increase the value to 10000000 the program gives segfault. I tried using gdb but it stops on main giving segfault there. I am using a 64 bit OS. Even if I remove MAX and write 10000000 rather than MAX, I get the same error. Where am I going wrong? Please help.

A: You shouldn't declare very large arrays as local variables (i.e. on the stack), as the stack size is usually quite limited.  Instead, dynamically allocate them with new[] and delete[].  Or for idiomatic C++, use a container class like std::deque.

A: In this particular case, would it not be a reasonable idea to make "prime" a global variable. I do understand that global variables aren't always a good solution, but for this particular case, it would be a fairly obvious solution. It's not like MAX isn't a constant, so using new/delete or vector as a solution seems a little unnecessary.
And to answer the question of "is if slower to use 'new' vs global variable', then I can say that it's probably irrelevant. I used #define MAX 1000000000 in the above code, moved prime to be a global, and ran it using time, then altered the code to use new/delete, and it took around 0.5s longer - but the overall runtime is 20.4 or 20.9 seconds, so it's about 2% of the total runtime, and I'm pretty sure more than 2% can be gained by doing other things.


text:
Q: Values changing in class? I assign a with "abc", b with "def", add them together and a changes. I want a to stay as abc. instead its "abcdef". C is the only value that should be "abcdef". What am I doing wrong here?
    #include <iostream>
    #include <conio.h>
    #include <string>

    using namespace std;

    class String {
    public:
        void print();
        String operator=(const String& Other)
        {
            message = Other.message;
            return *this;
        }
        String operator+(const String& Other)const
        {
            return String(strcat(message, Other.message));
        }
        String operator+=(const String& Other)
        {

        }
        String(char* def = "Default")
        {
            message = new char[strlen(def) + 1];
            strcpy(message, doub);
        }
        String(const String &obj)
        {
            message = obj.message;
        }
        ~String();
    private:
        char * message;
    };
    void String::print()
    {
        cout << message;
    }
    String::~String(void) {

        cout << "Object is being deleted" << endl;
    }

    // Main function for the program
    int main() {
        String a("abc");
        String b("def");
        String c;
        c = a + b;
        _getch();
        return 0;
    }

A: You're using strcat which basically appends Other.message to your message memory block. You can read about this in here
To fix your issue you can make something like :
return String(strcat(strcat(str.message, this->message), Other.message))

online verification

A: "abc" and "def" are C-string read-only literals, which are stored in executable in read-only section, and later is mapped to read-only memory.
When you are using strcat, you are invoking undefined behavior, as you are trying to modify "abc" value.
Correct way here is to allocate memory in constructor and strcpy value of argument to internal allocated pointer. And later - in operator+ you shall re-allocate such pointer to allow more memory.

A: You have multiple problems with the class, most of them stemming from your use of the pointer message.
One thing is, for example, the operator+ function which calls strcat using the pointer, without reallocating the memory it points to so it will fit the old and new string.
And you really can't reallocate the pointer, because you don't really own the data your pointer is pointing to. Prominent example: You assignment operator copies the pointer and not the string it points to. That means you will have two String objects both pointing to the same memory.
You also have no destructor, so each String object you create will lead to a memory leak. However just adding a destructor that deletes the memory is not enough, unless you fix the pointer-copying.


text:
Q: Fundamental group of the following figure: (half-full sphere with two "quotiented" holes) Let $X$ be the following figure:

I want to find the fundamental groups $\pi_{1}(X)$ and $\pi_{1}(X/\beta)$ (up to isomorphism), determine whether $B$, the part of the image including the "$\beta$-circle" and below, is a retract of $X$, and determine whether the equator cirlce (the "filling" of the circle contains the equator) is a retract of $X$.

Unfortunately, I wasn't able to get too far on my own, but here's everything I got: first, $X$ is homotopic to a sphere with a "filled-in" equator, because we can contract the "filling" into a single disc. Then, we can contract that disc into a point, and get the wedge sum of two spheres, of which one has a disc-shaped hole with the $\alpha$ identification, and the other one has a circle with a triple $\beta$ identification. I've included a picture in case my explanation isn't clear:
I know the upper sphere of the wedge sum is the real projective plane, whose fundamental group is $\mathbb{Z_{2}}$; however, I can't find the other one. $\pi_{1}(X)$ would then be the free product of $\mathbb{Z_{2}}$ and the other fundamental group.
As far as $\pi_{1}(X/\beta)$ goes, I would hazard to guess that we could then contract the circle on the first picture with the $\beta$ identification, and that $\pi_{1}(X/\beta) \cong \mathbb{Z_{2}}$ then. Is this true? It sounds too easy to be true, but that's the only reasoning that I could think of.
As far as the retract questions go, I have made no progress in answering them. I would appreciate any assistance with this problem.


text:
Q: bootstrap-ui 0.12.0 popover-template not working I upgraded to bootstrap-ui version from 0.8.0 to 0.12.0 and the popover-template attribute stopped working.
 <a ng-if="offer.countryIds.length > 6"
    popover-placement="top"
    popover-trigger="mouseenter"
    popover-template="countries.popover.html">
         {{offer.countryIds.length}} Countries
  </a>

I know that the popover-template never was official and still i want to use her
Does anyone have an idea how to solve this problem?
thanks.

A: Now, you can upgrade to version 0.13.0 it work


text:
Q: What are some good code searching web interfaces? I'm looking for a good web framework/plugin/what have you that greps over a specific codebase.
I've done many searches for something like this including on GitHub and Google code and haven't found what I'm looking for...
Specifically I would like something that can index my code and present a Web UI to search over said codebase for class names, function names or just free text and regexes.
Ideally I could run the indexers at set intervals with cron and maybe the same script could even refresh the code from Git automatically before re-indexing, presenting an always fresh view of my code in the same Web UI.
Phabricator offers code browsing but no code search as far as I can tell.
This should also allow to browser code from the search results.
Are there open source options for doing this?

A: If you have access to Java, I've had some luck using lucene to index source code.

A: Krugle for Git and github may be worth a look.


text:
Q: Using Functions in Visual Basic The program I'm working on has two different functions, one that calculates the number of syllables in a text file, and another that calculates the readability of the text file based on the formula
206.835-85.6*(Number of Syllables/Number of Words)-1.015*(Number of Words/Number of   Sentences)

Here are the problems I'm having:

*

*I'm supposed to display the contents of the text file in a multi-line text box.

*I'm supposed to display the answer I get from the function indexCalculation in a label below the text box.

*I'm having trouble calling the function to actually have the program calculate the answer to be displayed in the label.

Here is the code I have so far.
Option Strict On

Imports System.IO

Public Class Form1

    Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
        Me.Close()
    End Sub

    Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
        Dim open As New OpenFileDialog

        open.Filter = "text files |project7.txt|All file |*.*"
        open.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)

        If open.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Dim selectedFileName As String = System.IO.Path.GetFileName(open.FileName)
            If selectedFileName.ToLower = "project7.txt" Then
                    Dim text As String = File.ReadAllText("Project7.txt")
                    Dim words = text.Split(" "c)
                    Dim wordCount As Integer = words.Length
                    Dim separators As Char() = {"."c, "!"c, "?"c, ":"c}
                    Dim sentences = text.Split(separators, StringSplitOptions.RemoveEmptyEntries)
                Dim sentenceCount As Integer = sentences.Length
                Dim vowelCount As Integer = 0
                For Each word As String In words
                vowelCount += CountSyllables(word)
                Next
                vowelCount = CountSyllables(text)
                Label1.Show(indexCalculation(wordCount, sentenceCount, vowelCount))
            Else
                MessageBox.Show("You cannot use that file!")
            End If
        End If

    End Sub

    Function CountSyllables(word As String) As Integer
        word = word.ToLower()
        Dim dipthongs = {"oo", "ou", "ie", "oi", "ea", "ee", _
                         "eu", "ai", "ua", "ue", "au", "io"}
        For Each dipthong In dipthongs
            word = word.Replace(dipthong, dipthong(0))
        Next
        Dim vowels = "aeiou"
        Dim vowelCount = 0
        For Each c In word
            If vowels.IndexOf(c) >= 0 Then vowelCount += 1
        Next
        If vowelCount = 0 Then
            vowelCount = 1
        End If
        Return vowelCount
    End Function

    Function indexCalculation(ByRef wordCount As Integer, ByRef sentenceCount As Integer, ByRef vowelCount As Integer) As Integer
        Dim answer As Integer = CInt(206.835 - 85.6 * (vowelCount / wordCount) - 1.015 * (wordCount / sentenceCount))
        Return answer
    End Function
End Class

Any suggestions would be greatly appreciated.

A: Here are my suggestions:

*

*update your indexCalculation function to take in Integers, not strings. that way you don't have to convert them to numbers.

*remove all of your extra variables you are not using. this will clean things up a bit.

*remove your streamreader. it appears you are reading the text via File.ReadAllText

*Label1.Show(answer) should be changed to Label1.Show(indexCalculation(wordCount,sentenceCount,vowelCount)) -- unless Label1 is something other than a regular label, use Label1.Text = indexCalculation(wordCount,sentenceCount,vowelCount))

Then for the vowelCount, you need to do the following:
Dim vowelCount as Integer = 0
For Each word as String in words
 vowelCount += CountSyllables(word)
Next

Also, add the logic to the CountSyllables function to make it 1 if 0. If you don't want to include the last character in your vowel counting, then use a for loop instead of a for each loop and stop 1 character short.


text:
Q: TimeZoneInfo lock contention Our system handles multiple streams of real-time calculations in parallel - roughly 300-500 calculations a second. We're seeing an occasional issue in production where the ThreadPool expands out to 400-500 threads, and performance drops to a crawl. The calculations are still continuing, but at a much slower rate.
Process dumps + Parallel Stacks window in VS shows several hundred threadpool threads with call stacks that all end in a Monitor.Enter in TimeZoneInfo. Our calculations involves timezone conversion.
I would have thought we should be able to acquire that lock thousands or millions of times a second without issue. The fact a few hundred threads are backed up by this lock is surprising. The fact the app continues to process work implies this isn't deadlock, just very costly contention.
Here's an example callstack - all of the threads are variations on this:
[Managed to Native Transition]
mscorlib.dll!System.Threading.Monitor.Enter(object obj, ref bool lockTaken) Unknown
mscorlib.dll!System.TimeZoneInfo.ConvertTimeToUtc(System.DateTime dateTime, System.TimeZoneInfoOptions flags)   Unknown
mscorlib.dll!System.DateTime.ToUniversalTime()  Unknown
<our code>
mscorlib.dll!System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(object state)  Unknown
...

We're running .Net 4.0. It looks like the locking implementation in TimeZoneInfo has changed in .Net 4.5 - there is a lot less locking in 4.5.
Searching on this problem hasn't yielded much. It looks like there may have been a fix for this in .Net 4.5. Does anyone have any knowledge possibly related to this?


text:
Q: Forward all ports from one local IP address to localhost, while also allowing localhost to use that IP address I am trying to set up WireGuard so that I can access the localhost of A on B. However, that's not possible, so I thought of mapping 10.200.200.1 (the WireGuard IP of A) to 127.0.0.1 using
sudo iptables -t nat -A  PREROUTING -d 10.200.200.1 -j DNAT --to-destination 127.0.0.1
sudo iptables -t nat -A POSTROUTING -s 127.0.0.1 -j SNAT --to-source 10.200.200.1

This works (when B requests 10.200.200.1:2001 while in Wireguard, it actually requests 127.0.0.1:2001 from the perspective of A), but A can't access 10.200.200.1:2001. How would I fix that?
EDIT: sudo iptables -t nat -A OUTPUT -d 10.200.200.1 -j DNAT --to-destination 127.0.0.1
works to expose 10.200.200.1 on A, but now B can't connect to 10.200.200.1

A: Ok, I figured it out -- there's three parts to this:
sysctl

sudo sysctl -w net.ipv4.conf.all.route_localnet=1

sudo sysctl -w net.ipv4.ip_forward=1

For connection to work on A:
sudo iptables -t nat -A OUTPUT -d 10.200.200.1 -j DNAT --to-destination 127.0.0.1

For connection to work on B:
sudo iptables -t nat -A  PREROUTING -d 10.200.200.1 -j DNAT --to-destination 127.0.0.1

You may also need:
sudo iptables -t nat -A POSTROUTING -s 127.0.0.1 -j SNAT --to-source 10.200.200.1


text:
Q: OpenTok fragment Video publishing with MvvmCross I'm trying to implement video streaming with OpenTok video streaming solution, based on MvvmCross architecture (Android app).
My video page is a MvxFragment, that is instantiated from MvxCachingFragmentCompatActivity. That activity manages a couple of fragments, and on custom command it shows my video fragment.
The problem is that i receive video and audio from subscriber, but unable to send the publisher data. Publisher view always shows black screen.
Here is my publisher creation block:
public void OnConnected(Session p0)
{
    if (_publisher != null)
        return;

    _publisher = new Publisher(Activity, "publisher", true, true);
    _publisher.SetPublisherListener(this);
    AttachPublisherView(_publisher);
    p0.Publish(_publisher);
}

But if i am not using mvvmcross, and implement OpenTok interfaces in FragmentActivity, instead of fragment, everything works fine.
I suppose that, the problem somehow depends on the provided context when i create Publisher, but cannot find the way to get it work.
Will be thankfull to any thoughts or help.

A: Finally i found what caused the problem. It was incompatible target android version. After i set it to "Use compile using SDK version" the problem is gone.


text:
Q: How does Python's slice function in PySpice accept a fractional value for step size? I am using PySpice for circuit simulation in Python and find it puzzling that the slice() function is used in this context with a fractional value for step size. For example, the following line of code from docs sweeps over an input voltage from -2 volts to 5 volts in increments of 0.01 volts.
analysis = simulator.dc(Vinput=slice(-2, 5, .01))

Looking up slice() in Python, docs state that the step is integer-valued.

Step: (Optional) An integer that specifies the step of the slicing process.

Wouldn't it be more natural to use a numpy array created with np.arange(-2, 5, 0.01) in place of slice? The method simulator.dc() however only accepts slice as shown.
What gives?


text:
Q: When subclassing Xamarin Android.Views.View (or any of its subclasses), do I need to call dispose on objects I created? If I have a class like this below where I create Drawables and then use them while this button is on the page, is it standard to dispose of all of the ImageDrawable 's when overriding the Dispose method, or should I dispose of them in OnDetachedFromWindow, or is this not needed at all.
1.
public class ExampleImageButton : ImageButton
{
    private IList<AnimationDrawable> _animations;

....

    protected override void Dispose (bool disposing)
    {
        if(disposing)
        {
            foreach(var item in _animations)
            {
                item.Dispose();
            }
            _animations = null;
        }
        base.Dispose (disposing);
    }
}

2.
public class ExampleImageButton : ImageButton
{
    private IList<AnimationDrawable> _animations;

....

    protected override void OnDetachedFromWindow()
    {
        foreach(var item in _animations)
        {
            item.Dispose();
        }
        _animations = null;
    }
}

A: It is standard practice to Dispose() child objects within the parents Dispose() method. When an object derives from Java.Lang.Object it will have a corresponding Java peer object.
After you invoke Dispose() on a class that subclasses Java.Lang.Object, its peer connection is broken (as held by the IntPtr Handle property in Java.Lang.Object) and is no longer safe to use. Dispose() effectively marks an object as a GC candidate in both the Mono and Dalvik virtual machines.
In your example above, the safe way to destroy IList<AnimationDrawable> _animations is in example 1. As Dispose is guaranteed to be the last method called before an object has it's peer connection broken, you shouldn't dispose child objects in other callbacks (such as OnDetachedFromWindow) unless you are absolutely certain it won't be used again.
Further reading:

*

*Xamarin.Android Garbage Collection

*Xamarin Android Finalizer not getting called when leaving the activity to go to another Activity

*System.ArgumentException'jobject' must not be IntPtr.Zero. Parameter name: jobject


text:
Q: move_uploaded_file não move ficheiros Eu tenho um form (em php, queria perguntar se funciona sem problema?) para inserir imagens (o path delas) e quando eu insiro aparece a notificação que foram inseridas na base de dados mas a imagem não move para a pasta que peço.
Este é o código que fiz para transferir:
<?php

    include '../conn.php';
    mysqli_set_charset($con,"utf8");

    $id = $_GET['id'];

    $imagem    = $_FILES['imagem']['tmp_name'];
    $img_name = $_FILES['imagem']['name'];

    $dir      = "../imagens/viaturas/";
    $path     = $dir.$img_name;

    move_uploaded_file( $imagem, $path );

    $sql = "INSERT INTO carros_img(id_fk, img) VALUES ($id, '$img_name')";

    if(mysqli_query($con, $sql)){
    echo "<script>
             document.location.href = '../admin/carros.php?id=$id';
     </script>";
    }
    else{
        echo "<script>
            alert('Imagem não enviada');
            document.location.href = '../admin/quem.php?id=$id';
        </script>";
     }
?>

O path da imagem aparece na bd mas a imagem não move de pasta. Algum problema com o código?


text:
Q: Prove Left Module Over Ring of Matrices is Cyclic Let $R=\text{Mat}_{n\times n}(\mathbb{C})$ and $M=\mathbb{C}^n$ be the left $R$-module with $A\cdot v=Av$ (given by left matrix multiplication). Prove that $M$ is a cyclic $R$-module.
This question seems to be fairly straightforward but I have no idea how to go about proving it.
The definition of cyclic I am working with is $M$ is cyclic if $M=R\{a\}=\{ra|r\in R\}$ for some $a\in M$.
Edit (Proof)
Let $R=\text{Mat}_{n\times n}(\mathbb{C})$ and let $M=\mathbb{C}^n$ be a left $R$-module.
Consider the element $v=e_1=\begin{bmatrix}1\\0\\\vdots\\0\end{bmatrix}\in M$.
Then for any $A\in R$ where $A=\begin{bmatrix}c_{11} & ... & c_{1n}\\c_{21} & ... & c_{2n}\\ \vdots\\c_{n1} & ... & c_{nn}\end{bmatrix}$ for $c_{ii}\in\mathbb{C}$,
$A\cdot v=\begin{bmatrix}c_{11} & ... & c_{1n}\\c_{21} & ... & c_{2n}\\ \vdots\\c_{n1} & ... & c_{nn}\end{bmatrix}\cdot \begin{bmatrix}1\\0\\\vdots\\0\end{bmatrix}=\begin{bmatrix}c_{11}\\c_{21}\\\vdots\\c_{n1}\\\end{bmatrix}$.
If we consider $Rv=\{Av|A\in R\}=\left\{\begin{bmatrix}c_{11}\\\vdots\\ c_{n1}\\\end{bmatrix}|c_{11},...,c_{n1}\in\mathbb{C}\right\}$, it is clear that this set of vectors produces all of $\mathbb{C}^n$. Therefore, $M$ is a cyclic $R$-module.

A: Take any $v\in M\setminus 0$ whatsoever and show that $Rv=M$.
Do an example: take $n=2$, and, say $v=e_1$. What is the set of vectors you can get as $Av$ with $A$ a matrix?
After you have done that little example, think about what happens when $n=3$.
After that, you will see how to do this.

A: Hints.

*

*For every $v\in\mathbb{C}^n$ there exists a linear map $f\colon\mathbb{C}^n\to\mathbb{C}^n$ such that $f(e_1)=v$, where $\{e_1,\dots,e_n\}$ is the standard basis.

*What are the linear maps $\mathbb{C}^n\to\mathbb{C}^n$? (Look at their associated matrices with respect to the standard basis.)


text:
Q: How to change TextBlock foreground color on text changed for Windows Phone 8.1 (WinRT)? My TextBlock is bound to my viewmodel and I'd like to flash the text when it changes. I'm finding it difficult to implement this for Windows Phone 8.1 (WinRT). I'm thinking I have to use an EventTriggerBehavior and change the textBlock to a textBox then select the "TextChanged" event. Is there an easy way to do this?
Here's my attempt at doing so with a TextBox and using the EventTriggerBehavior.
<TextBlock x:Name="TestTypeTextBox"
           TextWrapping="Wrap"
           Text="{Binding TestTypeText}"
           FontSize="48" TextAlignment="Center"
           HorizontalAlignment="Center"
           VerticalAlignment="Center"
           Margin="0"
           FontWeight="Bold"
           FontFamily="Segoe UI Black"
           Foreground="White"
           Padding="0">
    <i:Interaction.Behaviors>
        <core:EventTriggerBehavior EventName="SelectionChanged">
            <Media:ControlStoryboardAction Storyboard="{StaticResource FlashingText}"/>
        </core:EventTriggerBehavior>
    </i:Interaction.Behaviors>
</TextBlock>

A: Instead of relying on events to invoke the storyboard, how about monitoring the property change of the TestTypeText, given that you are already doing this in a mvvm fashion?
Doing so, you will need a DataTriggerBehavior rather than an EventTriggerBehavior。
<TextBlock x:Name="TestTypeTextBox"
           TextWrapping="Wrap"
           Text="{Binding TestTypeText,FallbackValue=sss}"
           FontSize="48" TextAlignment="Center"
           HorizontalAlignment="Center"
           VerticalAlignment="Center"
           Margin="0"
           FontWeight="Bold"
           FontFamily="Segoe UI Black"
           Foreground="White"
           Padding="0" RenderTransformOrigin="0.5,0.5">
    <TextBlock.RenderTransform>
        <CompositeTransform/>
    </TextBlock.RenderTransform>
    <Interactivity:Interaction.Behaviors>
        <Core:DataTriggerBehavior Binding="{Binding TestTypeText}" ComparisonCondition="NotEqual" Value="{Binding TestTypeText}">
            <Media:ControlStoryboardAction Storyboard="{StaticResource FlashingText}" />
        </Core:DataTriggerBehavior>
    </Interactivity:Interaction.Behaviors>
</TextBlock>

The code above is pretty much yours, I've only edited the behaivor so it will invoke the storyboard when the TestTypeText is changed.


text:
Q: How to intersect two tables without losing the duplicate values oracle How to intersect two tables without losing the duplicate values in Oracle?
TAB1:

A
A
B
C

TAB2:

A
A
B
D

Output:

A
A
B

A: A subquery will filter the rows:
select *
  from tab1
 where col in (select col from tab2)

A: If I understand correctly:
select a.*, row_number() over (partition by col1 order by col1)
from a
intersect
select b.*, row_number() over (partition by col1 order by col1)
from b;

This adds a new sequential number to each row.  Intersect will go up to the matching number.
This uses partition by col1 -- the col1 is arbitrary.  You may need to include all columns in the partition by.


text:
Q: Button press does not talk to main timeline (as2) _root.backMusicOn.onPress = function () {
    _root.backgroundMsc = true;
    trace(_root.backgroundMsc)
}

Hello guys, I have a boolean and this is set to false when initiated and declared.
When you press this button, I want it to be true and play the music, but it doesn't become true and my music doesn't play.
I've used traced command trace (_root.backgroundMsc), when I click on the button it says true.
But when the game starts, it says not true.
Can you please help me, I think flash is confused.
static private function level1Loop():Void
{
    if (_root._currentframe == 19)
    {

        shoutPicha();
        checkBackGroundMusic();

        switchCharacter();
        gravityEngine(); //and jump lol // and controls rofl
        shootCollision();
        vCam();
        collisionWithGround();
        getHudtoFollowPlayer();
        ifPlayersFallTelethem();
        changeItems();
        collisionWithShapes();
        timer();
        attachItems();
        backButtonLevel1();
        gameWinCondition();
        ifonGamescreen();
        portal();
        candyCollision();
        makePointSfollow();
    }
}
static private function checkBackGroundMusic():Void
{
    if (backgroundMsc)
    {
        trace("hey")
        soundTrack.start();
        trace(backgroundMsc);
        //if this is true, play sound

    }
    else
    {
        //dont play sound
        trace("nej");
    }
}

this is where i declare
static var game:Platform;

static public var backgroundMsc:Boolean = true;
static public var SoundFx:Boolean;
static public var myData:LoadVars;
static public var canJumpFrickingHight:Boolean = false;
static private var totalBytes;

A: I'm an idiot.
It doesn't know what I'm targetting, because I'm not using "_root."
    if (backgroundMsc) //should be _root.backgroundMsc
    {
        trace("hey")
        soundTrack.start();
        trace(backgroundMsc);
        //if this is true, play sound

    }

Cheers for the help guys, i just switched from As3 to As2 and I need to code in the main timeline >.M;


text:
Q: Why do online tested regular expressions behave completely different in C++? When using the C++(msvc compiler) regular expressions library(boost and stl), I have found that many of Online Tested(all from the Regex Stack Overflow FAQ) regular Expressions do not work, For Example:
\w
([\w]+)
[a-z]
[abcdef] \\etc...

I am using Raw Literals for my regex's So that's not the problem.
The Code i am currently using to test them is
string somestring="something othersomething";
regex Test(R"(\w)",boost::regex_constants::JavaScript);
smatch match;
if(regex_match(somestring,match,Test))cout<<"True"<<endl;
else cout<<"false"<<endl;

When I try it in different Languages like Java this works why doesn't it C++?
P.S I have a feeling it is something to do with reading white spaces differently.

A: Regular Expression engines vary between different programming languages.  These are unofficially known as 'flavors'.
Java Regex != C++ Regex != PRCE != .NET Regex ...you get the picture.
If you are going to use an online regex tester, make sure it's for the flavor of regex you plan on using.

A: As JNYRanger Said there is a matter of flavors but If you have noticed
I used regex_match not regex_search in my code
which is why the program was giving me a false Match Every time. Simply because I assumed that it would only match parts of a string, like the online Testers do and Other Languages.


text:
Q: FragmentTransaction.AddToBackStack causes memory leaks I have an activity with two fragments. In FragmentOne I have button which replaces it with FragmentTwo on OnClick. But when I add FragmentOne to backstack using fragmentTransaction.addToaBackstac(null) leak canary is detecting memory leaks. Why is it a memory leak? Below is the trace.
In com.example.sohail.sampleleakcanary:1.0:1.
* com.example.sohail.sampleleakcanary.FragmentOne has leaked:
* GC ROOT static android.view.WindowManagerGlobal.sDefaultWindowManager
* references android.view.WindowManagerGlobal.mRoots
* references java.util.ArrayList.array
* references array java.lang.Object[].[0]
* references android.view.ViewRootImpl.mContext
* references com.example.sohail.sampleleakcanary.MainActivity.mFragments
* references android.support.v4.app.FragmentController.mHost
* references android.support.v4.app.FragmentActivity$HostCallbacks.mFragmentManager
* references android.support.v4.app.FragmentManagerImpl.mActive
* references java.util.ArrayList.array
* references array java.lang.Object[].[0]
* leaks com.example.sohail.sampleleakcanary.FragmentOne instance

BaseActivity

public class BaseActivity extends AppCompatActivity {

    protected void replaceFragment(int containerId, Fragment fragment, boolean addToBackStack) {

        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction().replace(containerId, fragment);

        if (addToBackStack) {
            fragmentTransaction.addToBackStack(null);
        }

        fragmentTransaction.commit();
    }

}

MainActivity

public class MainActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        if (savedInstanceState == null) {
            replaceFragment(R.id.fragment_container, FragmentOne.newInstance(), true);
        }
    }

    public void goToTwo() {

        replaceFragment(R.id.fragment_container, FragmentTwo.newInstance("two", "two"), true);
    }

}

FragmentOne

public class FragmentOne extends Fragment {

    public FragmentOne() {
        // Required empty public constructor
    }

    public static FragmentOne newInstance() {
        FragmentOne fragment = new FragmentOne();
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View root = inflater.inflate(R.layout.fragment_fragment_one, container, false);
        ButterKnife.bind(this, root);
        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

        ButterKnife.unbind(this);

        RefWatcher refWatcher = SampleApplication.getRefWatcher(getActivity());
        refWatcher.watch(this);

    }

    @OnClick(R.id.button_second_fragment)
    public void onClick() {

        ((MainActivity) getActivity()).goToTwo();
    }
}


text:
Q: Matlab atan2 for angle between two 3D vectors I need to calculate the angle between two plane. One plane is the hand plane and the second is the forearm plane. I calculated the normals of that planes and used the formula atan2(norm(cross(var.n1,var.n2)),dot(var.n1,var.n2)); in MATLAB. I want to see the flexion/extension angle of the wrist that is characterised by positive and negative peaks but with this formula I obtain only positive peaks.
%% Script to compute the angles of wrist flexion/extension and adduction/abduction based on Vicon data
% REF: Cheryl et al., March 2008
% Order of the markers: 1.WRR 2.WRU 3.FAU 4.FAR 5.CMC2 6.CMC5 7.MCP5 8.MCP2

clc
close all
clear all

%% Initialization
% dir_kinematic = input('Path of the folder containing the kinematic files: ','s');
dir_kinematic = 'C:\Users\Utente\Desktop\TESI\Vicon\test.mat';
cd(dir_kinematic);

fileList = getAllFiles(dir_kinematic,0); % Get names of all kinematic files
f=1;
%% Conversion to angles
 for f = 1:length(fileList)
    if ~isempty(strfind(fileList{f},'mat')) % Take only mat files

        % 0. Loading
        load(fileList{f});

        % 1. Filtering
        frameRate = kinematic.framerate;
        n = 9;
        Wn = 2/(frameRate/2);
        ftype = 'low';
        [b,a] = butter(n,Wn,ftype);
        kinematic.x = filtfilt(b,a,kinematic.x);
        kinematic.y = filtfilt(b,a,kinematic.y);
        kinematic.z = filtfilt(b,a,kinematic.z);

        % 2. Create vectors
        var.n=length(kinematic.x);

        % Forearm plane
        var.FAU_WRU=[kinematic.x(:,2)-kinematic.x(:,3),kinematic.y(:,2)-kinematic.y(:,3),kinematic.z(:,2)-kinematic.z(:,3)];
        var.WRR_WRU=[kinematic.x(:,2)-kinematic.x(:,1),kinematic.y(:,2)-kinematic.y(:,1),kinematic.z(:,2)-kinematic.z(:,1)];

        % Hand plane
        var.CMC5_MCP5=[kinematic.x(:,7)-kinematic.x(:,6),kinematic.y(:,7)-kinematic.y(:,6),kinematic.z(:,7)-kinematic.z(:,6)];
        var.MCP2_MCP5=[kinematic.x(:,7)-kinematic.x(:,8),kinematic.y(:,7)-kinematic.y(:,8),kinematic.z(:,7)-kinematic.z(:,8)];

        % Transpose
        var.FAU_WRU = var.FAU_WRU';
        var.WRR_WRU = var.WRR_WRU';
        var.CMC5_MCP5 = var.CMC5_MCP5';
        var.MCP2_MCP5 = var.MCP2_MCP5';

        % 3. Calculate angle of wrist flexion/extension
        % Cross vector function for all time => create normal vector plane
        var.forearm_n=[];
        var.hand_n=[];
        var.theta_rad=[];

        for i = 1:var.n % Loop through experiment

            % vector x and y of the forearm plane
            var.v1=var.FAU_WRU(:,i); % take x,y,z of the vector for every time
            var.v2=var.WRR_WRU(:,i);

            % vector x and y of the hand plane
            var.v3=var.CMC5_MCP5(:,i);
            var.v4=var.MCP2_MCP5(:,i);

            var.forearm_n= [var.forearm_n, cross(var.v1,var.v2)];
            var.hand_n=[var.hand_n, cross(var.v3,var.v4)];

        end

        % Calculate angle
        for i = 1:var.n

            var.n1=(var.forearm_n(:,i));
            var.n2=var.hand_n(:,i);

            var.scalar_product(i) = dot(var.n1,var.n2);

            %Equation (2) of the paper
            var.theta_rad=[var.theta_rad, atan2(norm(cross(var.n1,var.n2)),dot(var.n1,var.n2))]; % result in radian

            angle.flex_deflex_wrist{f}=(var.theta_rad*180)/pi;

        end

        % 4. Calculate angle of wrist adduction/abduction

        % Projection vector onto plane

        var.MCP2_MCP5_forearmproj=[];
        var.WRR_WRU_forearmproj=[];
        var.rad_ul_angle_rad=[];

        for i=1:var.n

            %take x,y,z of the vector for each time
            var.v1=var.MCP2_MCP5(:,i);
            var.v2=var.WRR_WRU(:,i);

            % vector x and y of the forearm plane
            var.vfx=var.FAU_WRU(:,i); % take x,y,z of the vector for every time
            var.vfy=var.WRR_WRU(:,i);

            %projection of vector MCP2_MCP5 and WRR_WRU onto forearm plane
            var.squNorm1=(norm(var.vfx)*norm(var.vfx));
            var.squNorm2=(norm(var.vfy)*norm(var.vfy));

            var.MCP2_MCP5_forearmproj=[var.MCP2_MCP5_forearmproj,((((var.v1')*var.vfx)*var.vfx/var.squNorm1)+(((var.v1')*var.vfy)*var.vfy/var.squNorm2))];
            var.WRR_WRU_forearmproj=[var.WRR_WRU_forearmproj,((var.vfx*((var.v2')*var.vfx/var.squNorm1))+(var.vfy*((var.v2')*var.vfy/var.squNorm2)))];
        end

        % Calculate angle

        for i=1:var.n

            var.n1=var.MCP2_MCP5_forearmproj(:,i)';
            var.n2=var.WRR_WRU_forearmproj(:,i);
            var.product=var.n1*var.n2;

            var.rad_ul_angle_rad=[var.rad_ul_angle_rad, atan2(norm(cross(var.n1,var.n2)),dot(var.n1,var.n2))];% en rad
            angle.rad_ul_wrist{f}=(var.rad_ul_angle_rad*180)/pi;
        end

    end
end

I want to know why my angles are always positive? I need to see positive and negative peaks...
Thanks for the help!

A: Since the angle between two planes is the same as that between it's normals, I will constrain the discussion to angle between two vectors.
We know that the cross product between two vectors (a and b) is another vector, perpendicular to both of them.
We are dealing with the problem of distinguishing angles -T and +T, where T is some angle.
Using the formula you used, these two angles would give the same result, due to the fundamental formula itself that is used:
atan2 (|a x b|, a.b)
This is because while a.b is the same in both cases, a x b differs, exactly in the sign of the normal to the two vectors, and nothing else (verify yourself using hand rules). When we compute the norm of this vector, information about its sign is lost, due to which the function always returns positive values.
What you can do about it
You need to keep track of the sign of a x b, to determine if the angle is positive or negative.
Note: As I'm replying from my phone I am unable to add better formatting or code, will update the answer soon.


text:
Q: IPhone, Android - how to make one app on install complete, install second app? I have an app in iTune and Android. iTune on every updates take weeks to release my app and its pointless to renew the app in iTune and Android store.
For new feature i made a second app for iTune and Android store. Is there any option when someone install this new app or my old app. That automatically after installation is completed it checks for dependencies and complete the other app too?
Does anything exist already for iTune and Android store?
EDIT:
Like in desktop world

A:
That automatically after installation is completed it checks for dependencies and complete the other app too?

No. You must do your checks yourself and suggest installing missing apps.


text:
Q: Oracle versus DB2 on data Validation Most forums cite minor differences in speed, backup, etc.
It's about time someone tell how the two differ when it comes to GUI data validation.
Do this 2 Database always depend on java(or other software), or do they have the ability to create a user interface the accepts only valid input. Things like: positive numbers only, age between 1 to 100 only, email must be correct. I would be scared if my software accepts 500 years old for age.

A: Both offer native development tools that are roughly comparable and able to what you ask about.
Both also offer the ability for all main languages to interact with the RDBMS and so therefore the ability to to do the type of thing you discuss is as diverse as the options of a range of languages including Java, .Net, Ruby, Python, C++, VB, etc, etc
However what they don't really offer is a simple Access type 'forms and tables' type RAD tool.  In simple terms the increased flexibility and power of both Oracle and DB2 comes at the price of simplicity.

A: Neither database DEPENDS on Java for implementing field level constraints. Data constraints can be implemented directly at the database level, and it is good practice to do so.
But you also need field level validation - users do not want to get constraint violation errors on insert.
As for tools that generate GUI applications from the database itself - I don't see that as an Oracle vs DB2 database question - it's more Oracle Apex vs IBMs equivalent - but even within Oracle you've got Forms (deceased), JDeveloper, Apex.


text:
Q: Posting JSON to Restlet using xstream and jettison results in "Unsupported Media Type" I am using the jse edition of Restlet 2.1.0 with the xstream and jettison extensions that enable me to have a resource that is declared like this:
@Get("json")
public Customer retrieve();

This allows me to have a client that can choose whether to get a JSON string or get a Customer object, with xstream+jettison doing the serialization/deserialization.
I also have a resource method declared like this:
@Post
public Customer store(Customer customer);

Which I can post to using something like:
clientResource.post(customer, Customer.class);

This all seems to work nicely.  However the one thing that doesn't work is the simplest scenario, of posting a JSON String to this Post Restlet resource.
When I try to post the following JSON String:
{"com.redprairie.task.common.Customer":{"firstName":"George","lastName":"Shaw","birthDate":"1856-07-26 07:00:00.0 UTC","address":"Bibbs Hall Lane, Ayot St. Lawrence, AL6 9BX  United Kingdom"}}

I get this stack trace:
<failure message="Unsupported Media Type (415) - Unsupported Media Type" type="org.restlet.resource.ResourceException">Unsupported Media Type (415) - Unsupported Media Type
    at org.restlet.resource.ClientResource.doError(ClientResource.java:612)
    at org.restlet.resource.ClientResource.handleInbound(ClientResource.java:1203)
    at org.restlet.resource.ClientResource.handle(ClientResource.java:1070)
    at org.restlet.resource.ClientResource.handle(ClientResource.java:1087)
    at org.restlet.resource.ClientResource.post(ClientResource.java:1438)
    at com.redprairie.task.common.rest.RestletResource.post(RestletResource.java:99)
    at com.redprairie.task.common.rest.ServerResourceTest.testPostMethodUsingJSON(ServerResourceTest.java:165)

I'm guessing there is something simple that I'm doing wrong, but I'm not sure what it is.

A: I was able to resolve my issue.
I was trying to post a JSON string using:
String jsonString = "{some valid json}";
clientResource.post(jsonString, MediaType.APPLICATION_JSON);

That didn't work.  Not sure exactly why it didn't work, but doing it the following way works:
Representation rep = new StringRepresentation(jsonString, MediaType.APPLICATION_JSON);
clientResource.post(rep);

A: Are you specifying the content-type in your POST request header?


text:
Q: How to access Enum of arrays I have two sets of Products
public enum ProductType {

    FOUNDATION_OR_PAYMENT ("946", "949", "966"),
    NOVA_L_S_OR_SESAM ("907", "222");

    private String[] type;

    ProductType(String... type) {
        this.type = type;
    }
}

Then given a value"actualProductType" I need to check if it is part of the productType ..How do I do this  ..
isAnyProductTypes(requestData.getProductType(), ProductType.NOVA_L_S_SESAM)

 public boolean isAnyProductTypes(String actualProductType, ProductType productTypes) {
        return Arrays.stream(productTypes).anyMatch(productType -> productType.equals(actualProductType));
    }

I get an error at this part Arrays.stream(productTypes)

A: Since your enum does not change, you could build a Map inside it for faster look-up:
public enum ProductType {

    FOUNDATION_OR_PAYMENT("946", "949", "966"),
    NOVA_L_S_OR_SESAM("907", "222");

    static Map<String, ProductType> MAP;

    static {
        MAP = Arrays.stream(ProductType.values())
                    .flatMap(x -> Arrays.stream(x.type)
                                        .map(y -> new SimpleEntry<>(x, y)))
                    .collect(Collectors.toMap(Entry::getValue, Entry::getKey));
    }

    private String[] type;

    ProductType(String... type) {
        this.type = type;
    }

    public boolean isAnyProductTypes(String actualProductType, ProductType productTypes) {
        return Optional.ofNullable(MAP.get(actualProductType))
                       .map(productTypes::equals)
                       .orElse(false);
    }
}

A: you should change the type to Set<String> and the constructor as well
ProductType(String... type) {
    this.type = new HashSet<>(Arrays.asList(type));
}

and the lookup will be very simple
return productType.getType().contains(requestData.getProductType())


text:
Q: GetDevicePowerState what should hDevice enter? I am new to python Ctypes, i use GetDevicePowerState  function I don't know how to input hDevice ?
https://learn.microsoft.com/zh-TW/windows/win32/api/winbase/nf-winbase-getdevicepowerstate
import ctypes as ct
from ctypes import wintypes as w

Kernel32 = ct.WinDLL('Kernel32')

Kernel32.GetDevicePowerState.argtypes = w.HANDLE,w.BOOLEAN
Kernel32.GetDevicePowerState.restype = w.BOOLEAN

hDevice = 'USB'
pfOn = True

result = Kernel32.GetDevicePowerState(hDevice,pfOn)

print(result)


text:
Q: HTML CSS Table Design Guidance
I am trying to create this type of table or design in HTML/CSS/PHP.
In each block, there will be 3 variables. One with horizontal orientation in center and two with vertical orientation in either direction of a center variable.
I have tried to replicate this by using HTML tables but not getting proper results. This is what I have managed to get.

I already did the programming to configure variables and putting them where they should be with orientation but kind of stuck at proper UI. Kindly help me to design this.

A: Adding in HTML :

      1

       3

      1
       45
       3

      1

      3

      1

       3

      1
       45
       3

      1

      3

      1

       3

      1
       45
       3

      1

      3

Adding in css:
th, td {
   padding: 15px;
}

Solve It :)
Good luck !!!


text:
Q: How would I stop user creating custom POST requests with JWT? The way I understand access tokens is that the server grants an access token to the client, which the client would then send back alongside any requests in the request header to the server to prove their authentication/claims.
What would stop a user from grabbing their granted access token and using it in the header of a custom made POST request in Postman, giving them the ability to add whatever data they pleased into the database?
Is there any way to defend against this?

A: You are not in control of a client side app at all once it's out there, and you're right it's very easy to pretend to be your app and make custom requests. Anything in your client side code is changeable or replicable by a user.
Because of this you should assume that all users are evil and any checks you make client side on inputted data should be replicated server side.
It's also not enough to consider data going in, you should also check that a given user has the rights to query things that they ask for as it's trivial to change an id in a request for some data. Especially when ids are incremental ints, they are very prone to simply changing a url, without going anywhere near postman.

A: A valid token won't be block.
So you can't stop a person to take the token and put in "POSTMAN".
But they can only use to call your API. So a proper API design can mitigate the issue.
The other thing you can do is add different privilege level to your application


text:
Q: Why are pointwise measurable functions not measurable? Let $(X,\mathcal{X})$, $(Y,\mathcal{Y})$ and $(Z,\mathcal{Z})$ be measurable spaces. Let $(X \times Y, \mathcal{X} \otimes \mathcal{Y})$ be the product of the two spaces, where $\mathcal{X} \otimes \mathcal{Y} := \sigma(\mathcal{X} \times \mathcal{Y})$.
Let $f:X \times Y \to Z$ be a pointwise measurable function (my own term) in the sense that

*

*$\forall x \in X: f(x, \cdot):Y \to Z$ is measurable

*$\forall y \in Y: f(\cdot, y):X \to Z$ is measurable

Sufficient conditions for separately measurable functions being jointly measurable. claims that $f:X \times Y \to Z$ is not necessarily measurable. Why? Is there a simple counter-example?

A: Yes, there is. Indeed consider the Borel measure on $[0,1]$ and let $A$ be your favorite non measurable subset of the unit interval. Then define a function $f$ on $[0,1]^2$ as follows:
$$f(x,y) =
\begin{cases}
0 & \text{if } x \notin A \text{ or if } x \neq y , \\
1 & \text{otherwise}.
\end{cases}
$$
One can easily check that $f$ is separately measurable, but if it were measurable on the product space, its composition with the function $g \colon [0,1] \to [0,1]^2$ defined via $g(x) = (x,x)$ would also be measurable (composition of Borel measurable functions is measurable). Clearly this is not the case since $$f \circ g = \chi_{A},$$ which by assumption is not measurable.


text:
Q: Searching from MySql database and display the results as a hyperlink Here is my code, what I want to do is display the first names of my friends in another page as Hyperlinks and when a link is clicked I want to display the data.
<?php
$con=mysqli_connect("localhost","root","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM friends");

while($row = mysqli_fetch_array($result))
{

echo "
" . $row['FirstName'] . "
";
echo "
" . $row['LastName'] . "
";
echo "
" . $row['Email'] . "
";
echo "
" . $row['Address'] . "
";
}

mysqli_close($con);
?>

A: <?php
$con=mysqli_connect("localhost","root","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM friends");

while($row = mysqli_fetch_array($result))
{?>php

<a href=<?php "echo "
" . $row['FirstName'] . "
";"?>> `your page name`<?php
echo "
" . $row['LastName'] . "
";
echo "
" . $row['Email'] . "
";
echo "
" . $row['Address'] . "
";
}

mysqli_close($con);
?>

A: Your file from questions change:
while($row = mysqli_fetch_array($result))
{

echo "
" . $row['FirstName'] . "
";
echo "
" . $row['LastName'] . "
";
echo "
" . $row['Email'] . "
";
echo "
" . $row['Address'] . "
";
}

to
while($row = mysqli_fetch_array($result))
{
echo ' . $row['FirstName'] . "";
}

show.php
$con=mysqli_connect("localhost","root","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_GET['UserId'])){
if(is_numeric($_GET['UserId'])){
$UserId = (int)$_GET['UserId'];

$result = mysqli_query($con,"SELECT * FROM friends WHERE UserId= $UserId");
if(count($result)){
while($row = mysqli_fetch_array($result))
{

echo "
" . $row['FirstName'] . "
";
echo "
" . $row['LastName'] . "
";
echo "
" . $row['Email'] . "
";
echo "
" . $row['Address'] . "
";
}}}}

Important: I'm not sure what is UserId column name, so change it.
Also, please check for syntax errors.

A: Try connection it with an incremental ID out of the database. So every row in your friends table must have a unique ID. In that way you can connect it and get the row data from your friends table.
So your friends table must look like this:
friend_id (unique id)
firstname
lastname
email
address

And your code can be something like (this is not save from any attacks):
<?php
$con = mysqli_connect("localhost","root","abc123","my_db");
if (mysqli_connect_errno()) {
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

if(isset($_GET['friendid'])) {
    $result = mysqli_query($con,"SELECT * FROM friends");
    while($row = mysqli_fetch_array($result)) {
       echo "
" . $row['FirstName'] . "
";
       echo "
" . $row['LastName'] . "
";
       echo "
" . $row['Email'] . "
";
       echo "
" . $row['Address'] . "
";
       echo "
Details
";
    }
} else {
   $result = mysqli_query($con,"SELECT * FROM friends WHERE friend_id = '".$_GET['friendid']."'");
   $row = mysqli_fetch_assoc($result);
   echo "
" . $row['FirstName'] . "
";
   echo "
" . $row['LastName'] . "
";
   echo "
" . $row['Email'] . "
";
   echo "
" . $row['Address'] . "
";
}
mysqli_close($con);
?>


text:
Q: How do I prevent circular references in a hierarchy? The problem I am trying to solve is to prevent circular references not just between an immediate parent and child, but I also want to ensure that a new child is not already used as a parent somewhere in the hierarchy of records.
I thought I might solve the problem by intercepting the assignment of a parent before executing the code,
    self.parent = maybe_the_wrong_choice
and then do important validation before saving the change.
Am I on the right path? If so, how do I grab the old value of an attribute in my Model validation (e.g. self.old_parent) and compare it with the new parent (self.parent) before saving the record?
Thanks in anticipation!

A: You can get the old parent by self.parent_was and new parent by self.parent.