text:
Q: php updating serialized fields in wordpress with xml-rpc I'm trying to create/update wordpress custom posts using xml-rpc.
The post includes some serialized fields such as location data:
a:2:{s:3:"lat";s:2:"51";s:3:"lng";s:3:"-3.2";}

I'm using php xmlrpc_encode_request which is "experimental".
If I send the serialized string then wordpress serializes it again and I end up with a serialized string:
s:46:"a:2:{s:3:"lat";s:2:"51";s:3:"lng";s:3:"-3.2";}";

and I haven't found any combination of arrays or objects that will parse to a valid wordpress serialized field.
Can anyone point me in the right direction?
Is this a wordpress xml-rpc bug, an issue with xmlrpc_encode_request or just me being a numpty?
Thanks
Basically I'm doing this:
$content=array();
$custom_fields=array();

$gps=array("latitude"=>"$lat","longitude"=>"$lng");
//do something in here so that xmlrpc will encode the array correctly

$custom_fields[]=array("key"=>"_post_location", "value"=>$gps);
$content['post_title']="the title";
$content['post_status']='publish';
$content['post_content']="the content";
$content['custom_fields]=$custom_fields;
$request = xmlrpc_encode_request( "wp.newPost", array( 0, $username, $password, $content));

//then send request to xmlrpc.php

No matter how I try to encode, serialize or unserialize the custom field array $gps it does not get encoded by xmlrpc.php correctly. I either get a serialized string or an empty field.


text:
Q: Dynamically add panelGroup without refreshing entire parent I want to add h:panelGroup dynamically from backendBean but without refresh entire parent component.
Here is my code:
<h:panelGroup layout="block" id="dialogs">
</h:panelGroup>

To this panelGroup I want to add other panelGroup from backendBean:
public void addPanelGroup() {
    RequestContext rc = RequestContext.getCurrentInstance();
    doFind(FacesContext.getCurrentInstance(), "dialogs");
    HtmlPanelGroup div = new HtmlPanelGroup();
    div.setLayout("block");
    div.setId(id);
    found.getChildren().add(div);
}

private void doFind(FacesContext context, String clientId) {
    FacesContext.getCurrentInstance().getViewRoot().invokeOnComponent(context, clientId, new ContextCallback() {
        @Override
        public void invokeContextCallback(FacesContext context,
                UIComponent component) {
            found = component;
        }
    });
}

If I call
    RequestContext.getCurrentInstance().update("dialogs")
at the end of addPanelGroup method it works. But when I add second panelGroup on dialogs I must refresh dialogs second time. Is there any way to add new panelGroup without refresh entire parent panelGroup?
Thanks for help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Big white spaces between items of recycler view? when i add items to my recyclerview it always puts big white spaces between them (5 cm between items). I implemented the recyclerview just like my other recyclerviews but here it always adds these white spots.. Does anyone know how to fix it?
the recycler view is inside a Nestedscrollview but this doesn't have impact on spaces of this recylcerview.
<androidx.recyclerview.widget.RecyclerView
                android:id="@+id/recyclerview"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/cardView"
                android:clipToPadding="true"
                android:nestedScrollingEnabled="false"
                tools:listitem="@layout/txt" />

And here is my Code from activity:
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(adapter);

Here is my XML item code
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginTop="5dp"
            android:layout_marginBottom="5dp"
            android:layout_marginRight="15dp"
            android:layout_marginLeft="15dp"
            android:weightSum="100">

            <TextView
                android:id="@+id/name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="name"
                android:layout_gravity="left"
                android:gravity="left"/>

            <TextView
                android:id="@+id/time"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Uhrzeit"
                android:layout_marginLeft="10dp"/>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="100"
                android:layout_gravity="right"
                android:gravity="right">

                <ImageView
                    android:id="@+id/settings"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/ic_three_dots"
                    android:layout_gravity="right"/>
            </LinearLayout>

        </LinearLayout>

        <TextView
            android:id="@+id/content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="text"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="15dp"
            android:layout_marginBottom="15dp"/>

    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

A: Change the android:layout_height="match_parent" to android:layout_height="wrap_content" in the androidx.constraintlayout.widget.ConstraintLayout XML code of RecyclerView items


text:
Q: Why does adding URL to IE Compatibility View fix PowerShell 'Cannot find an overload for getElementByName' error? I had a similar issue compared to the following SO threads:
Powershell System.__ComObject.document property no longer works under IE 9
PowerShell IE9 ComObject has all null properties after navigating to webpage
Cannot find an overload for "getElementById" and the argument count: "1"
My error was something to the effect of:

Cannot find an overload for "getElementsByName" and the argument count: "1"...

So I looked at each of these threads to help determine the why and the solutions to this problem.
I'm running PowerShell 4.0 on Windows Server 2012 R2. The script runs with Execution Policy Bypass and I am also running PowerShell as an Administrator (i..e. Administrator: Windows PowerShell ISE) AND my user account is part of the Administrator group. The URL the script is accessing is on the Intranet (one would think Internet Explorer isolates it to the proper zone, namely the Intranet Zone).
The script worked fine on my local machine but not on this server.
Here are the list of things I tried--one at at time, never in combination--that failed to yield a successful outcome:

*

*Disabled Protected Mode in the Internet Zone.

*Added URL to Trusted Zone Sites. Note that Protected Mode was already disabled. Only change I made here was adding the URL to the Trusted Sites list.

*Disabled IE Enhanced Security Configuration completely. Administrators was already set to Off, but Users was set to On. I set Users to Off, which had no effect.

*Ensured PowerShell ISE was running in Administrator mode (elevated privileges). It didn't seem to matter what mode PowerShell ISE was running in, likely because Execution Policy is set to Bypass.

*Added URL to Intranet Zone Site List. Note that Protected Mode was set to disabled, prior to. Only change I made in this zone was adding the URL to its Site List. Initially worked but then I tried again and same problem. May have been a fluke that it worked.

Here are the list of things that I tried--again, one at a time--that solved the problem:

*

*Added URL to Compatibility View with Display intranet sites in Compatibility View unchecked.

*Added URL to Compatibility View with Display intranet sites in Compatibility View checked.

So the question is why does employing Compatibility View resolve the problem? What's different about this that the other things I tried didn't work?
One would think Trusted Zone Site List should do the trick. Security Level for Trusted Zone is set to Medium. For Intranet Zone, it's Medium-low. And for Internet Zone, it's set to Custom.
Is it related to one or more of the individual properties that you can set in a Security Level? Is it something under the covers with Registry, COM, IE?
Good thing is I found 2 solutions which worked. Bad thing is I don't quite understand why. Obviously, it works because of some relaxed security permissions. Maybe it's also tied to Group Policy settings. I'm not sure.
Anyone have any ideas here? Thank you.


text:
Q: Java: producer-consumer two threads stop working, freeze I have this code that takes data from the first array and puts it in the second array and then removes it from the first array. It works fine for a while, but then stops, while there are still values in the first array to paste:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main  {
    private static String buffer;
    private static String lock = "lock";

    public static void main(String[] args) throws  Exception  {
        Usb usb1 = new Usb(getListFromValues("1", "2", "3", "4", "5"));
        Usb usb2 = new Usb(getListFromValues("10", "20", "30", "40", "50"));

        Thread usbCutThread = new Thread(new UsbCutThread(usb1));
        Thread usbPasteThread = new Thread(new UsbPasteThread(usb2));

        usbCutThread.start();
        usbPasteThread.start();

        usbCutThread.join();
        usbPasteThread.join();

    }

    static class UsbCutThread implements Runnable  {
      private Usb usb;
      public UsbCutThread(Usb usb)  {this.usb = usb;}

      @Override
      public void run() {
          try {
              System.out.println("inside cut");
              for (int i = 0; i < usb.getData().size(); i++) {
                  buffer = usb.getValue();
                  System.out.println("cutting value " + buffer);

                  synchronized (lock) {
                      System.out.println("copied to buffer, waiting for paste");
                      lock.notify();
                      try {
                          lock.wait();
                      } catch (Exception e) {
                          e.printStackTrace();
                      }
                      System.out.println("erasing");
                      usb.eraseValue();
                  }
              }
          }
        catch (Exception e)  {
              e.printStackTrace();
        }
      }
    }

    static class UsbPasteThread implements Runnable  {
        private Usb usb;
        public UsbPasteThread(Usb usb)  {this.usb = usb;}

        @Override
        public void run() {
            try {
                while (true) {
                    System.out.println("inside paste");
                    //while it copies, cut thread can't erase - what if copy fails
                    synchronized (lock) {
                        usb.addValue("stuff");
                        System.out.println("pasted");
                        lock.notify();
                        try {
                            lock.wait();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
            catch (Exception e)  {
                e.printStackTrace();
            }
        }

    }

    static class Usb  {
      List<String> data = new ArrayList<>();

      public Usb(List<String> data)  {this.data = data;}

        public String getValue()  {return data.get(data.size() - 1);}

        public void addValue(String value)  {
          data.add(value);
        }

        public void eraseValue()  {
          data.remove(data.size() - 1);
        }

        public List<String> getData()  {return data;}
    }

    public static ArrayList<String> getListFromValues(String... values)  {
        ArrayList<String> result = new ArrayList<>();
        for (String v: values)  {
            result.add(v);
        }
        return result;
    }
}

Output:
inside cut
inside paste
pasted
cutting value 5
copied to buffer, waiting for paste
inside paste
pasted
erasing
cutting value 4
copied to buffer, waiting for paste
inside paste
pasted
erasing
cutting value 3
copied to buffer, waiting for paste
inside paste
pasted
erasing

A: UsbCutThread iterates from 0 to usb.getData().size():
              for (int i = 0; i < usb.getData().size(); i++) {

In the loop you are changing the size of usb.getData() by usb.eraseValue(). This will obviously affect the amount of iterations. In your case you'll get 3 iterations until i == usb.getData().size() is true and you exit the loop.
The other thread goes into lock.wait() as you've put the whole thing into a while (true). Here is where your program won't terminate.
To solve the first problem you just need to iterate to a fixed limit:
              int n = usb.getData().size();
              for (int i = 0; i < n; i++) {

I think the second problem is actually not a problem for you and is what you want. So I just stop here.


text:
Q: How can I do sessions URL is very long I cannot append JSESSIONID=389729387392.What is the solution for this? I got the answer for If I disabled the cookies then using URL ReDirect I can pass the JSESSIONID but my URL is already very long as I use the GET method it has constraint. Then how
should I use my sessions.I want my application to be very security intensive.
This is one of the question asked to my friend in GOOGLE interview.

A: As far as I understand, your main problem with JSESSIONID in the URL is the total length.
Perhaps you should have a closer look at why the length of the URLs are too long in the first place. Since you allready have a session, it is not unlikely you can move some GET parameters to the session. There are also lots of different way to make shorter URLs for pages (a la mod_rewrite).
With regards to security, JSESSIONID is just as vunerable with HTTP GET as HTTP POST. The base64 encoding HTTP POST does is not a security measure at all. The best way to gain a bit more security is to encrypt the transport channel through TLS/SSL, in effect enable HTTPS. This will make sure that eavesdropping (or man in the middle attacks) will not have access to the plain text.

A: Apart from using one-letter parameter names (e.g. ?a=value1&b=value2&c=value3 or using RESTFul-like URL's (i.e. just the pathinfo, no query parameters, e.g. /value1/value2/value3, which is accessible by HttpServletRequest#getPathInfo() in the servlet) instead of ?name1=value1&name2=value2&name3=value3, you can also consider to Gzip and Base64-encode the query string so that it becomes shorter. Both JavaScript and Java are capable of (de)compressing and (d)e(n)coding it. You can eventually format the query string in JSON before compressing/encoding, it will be shorter in case of arrays/collections/maps.
That said, are you sure that the request URL's are often that unfriendly long (assuming that it's over 255 characters)? Why would you need to pass that much information in? Are they supposed to maintain the client state? If so, you shouldn't use the URL for this, but the HttpSession instance in the server side which is already associated with the jsessionid cooke. Use HttpSession#setAttribute() to store some information in session and use HttpSession#getAttribute() to retrieve it.

A: If you want your application to be security intensive why are you using GET. Use POST. This will also reduce the URL length.
As such, as per the HTTP protocol there is no max length limit to URL length. Most of the time its the browser that puts in the max length limit. Try different browsers
You should put forward the above points to the interviewer. They might be more interested in your ability to assess the system as a whole and identify any fundamental flaws.

A: If the URL is too long then you have to store that data somewhere else.  Most sites would put the session ID in a cookie.


text:
Q: Passing user defined variable into get_permalink I'm trying to use a predefined variable (generated from an earlier sweep of the database) in wordpress' standard get_permalink( get_page_by_title) function.
I'm assuming that this is possible? But I can't get it working, it always returns the url of the current page.
For the sake of clarity below I'm just manually assigning the variable.
Code...
<?php $mypagename = "My First Page"; ?>
<a href="<?php echo esc_url( get_permalink( get_page_by_title( $mypagename ) ) ); ?>">LINK

N.B - My First Page (my-first-page) does exist in the database
Any ideas where I'm going wrong or if it's not possible to do it like this do you have any other suggestions?
Many thanks!

A: get_page_by_title() returns a object by default and get_permalink() needs the ID as first parameter. Try:
$mypagename = "My First Page";

$permalink = get_permalink( get_page_by_title( $mypagename )->ID );


text:
Q: Leap motion -> Node.js -> Arduino. Error: SerialPort not open repost I've been trying to connect my leap with my arduino using node.js, following this guide, but I keep getting this error:
1442170022060 Device(s) /dev/cu.usbmodem1421
1442170022073 Connected /dev/cu.usbmodem1421
1442170025540 Repl Initialized
>> events.js:85
  throw er; // Unhandled 'error' event
        ^
Error: Serialport not open.
    at SerialPortFactory.SerialPort.write (/Users/Kenny/Documents/src/node_modules/johnny-five/node_modules/serialport/serialport.js:288:17)
    at Board.analogWrite (/Users/Kenny/Documents/src/node_modules/johnny-five/node_modules/firmata/lib/firmata.js:643:18)
    at Board.servoWrite (/Users/Kenny/Documents/src/node_modules/johnny-five/node_modules/firmata/lib/firmata.js:690:20)
    at Servo.Controllers.Standard.servoWrite.value (/Users/Kenny/Documents/src/node_modules/johnny-five/lib/servo.js:108:17)
    at Servo.to (/Users/Kenny/Documents/src/node_modules/johnny-five/lib/servo.js:315:12)
    at Object._move [as move] (/Users/Kenny/Documents/src/lib/joint.js:28:10)
    at WebSocket.<anonymous> (/Users/Kenny/Documents/src/proj.js:41:26)
    at WebSocket.emit (events.js:110:17)
    at Receiver.ontext (/Users/Kenny/Documents/src/node_modules/ws/lib/WebSocket.js:816:10)
    at /Users/Kenny/Documents/src/node_modules/ws/lib/Receiver.js:477:18

This is my code
var five = require('johnny-five'),
WebSocket = require('ws'),
ws = new WebSocket('ws://127.0.0.1:6437'),
board = new five.Board(),
LeapFrame = require('./lib/leapFrame'),
Joint = require('./lib/joint'),
frame,
i = 0;

board.on('ready',function() {
     var servoPitch = new Joint({

        minPos: 50,
        maxPos: 100,
        pin: 11,
        range: [70,100]
     });

     var servoNod = new Joint({
        minPos: 0,
        maxPos: 100,
        pin: 10,
        range: [70, 130]
     })

     var servoRoll = new Joint({
        minPos: -60,
        maxPos: 430,
        pin: 9,
        range: [0,200]
     })

     ws.on('message',function(data,flags) {
           i++;
           if (i%3 == 0) {
            frame = new LeapFrame(data);
            if(frame.valid) {
            servoPitch.move(frame.deltaHandFinger.y);
           servoRoll.move(200 - frame.palmPosition.x);
           servoNod.move(frame.palmPosition.y);

            }
           i = 0;
           }
           });

     });

I uploaded standardfirmata onto my arduino
im able to use servoRoll fine, but the other two are giving me the error
Anyone know what the problem is?


text:
Q: Admin client not registering to spring boot admin server I have created personal microservice and registered it to spring boot admin. Its working fine. But when I applied same dependency and properties in my organisation project then admin clients are not registering to spring boot admin server.
Even though both have same properties and dependencies, why my microservice is not registering
I tried creating spring boot admin server and trying to register admin clients on this server.

A: I am currently working on a small project where I'm connecting MSs to a spring boot admin server. Had some problems (my clients would not connect to the server) and that's how I ended up here.
From what you provided, it is very difficult to pinpoint the exact problem, so there will be a lot of guessing on my part. I can only share my experience in hope it can help you too. In the end, the problem for me was the configuration parameter
spring.boot.admin.client.url=...

which was misspelled... And since this will not raise any error messages, it took some time to fix.
Go through following steps:

*

*add client dependencies:
 <dependency>
     <groupId>de.codecentric</groupId>
     <artifactId>spring-boot-admin-starter-client</artifactId>
 </dependency>

*guessing you are using actuator, make sure there is a dependency
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-actuator</artifactId>
 </dependency>

*expose actuator endpoints (probably not all like in my example) in application.properties
 management.endpoints.web.exposure.include=*

*point your MS client to the admin server (use correct url!)
 spring.boot.admin.client.url=http://localhost:9080

*make sure your admin server has following dependencies
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
 </dependency>
 <dependency>
     <groupId>de.codecentric</groupId>
     <artifactId>spring-boot-admin-starter-server</artifactId>
 </dependency>

*make sure your admin server has the following annotation in the main class
 @EnableAdminServer

*make sure both server and client(s) are running correctly and can bind defined ports (change the default port if they run on the same machine - in the application.properties)
 server.port=...

If there is no additional security level, these steps should be enough to connect client to the server. With security I have no experience, but the online documentation did seem straight forward.
In the end, you can always try to build a new MS with nothing except actuator and client, and try to connect it to the server. If nothing else, it will maybe provide insight which side is broken.
Without more details it is very difficult to provide more help.
Oh yeah, I do remember one more detail: I was mixing up versions of the spring boot and JDK and since JDK17 (and spring boot version >= 3.x)  moved from javax to jakarta, had some problems with running the MS. But those errors were easy to fix from log info.


text:
Q: Play Framework async controller blocks subsequent calls for the same controller My goal is to do some database queries from the async controller, then return the answer.
I'm playing with the example project, for now just simulating the DB queries with a sleep, but what I noticed is that whatever I do, the REST interface won't even start the sleep of the second query until the first one finishes.
E.g.: If I call the REST interface from one tab in the browser, then 1 second later again from an another tab, I'd expect that the second one gets the reply too in 10 seconds, but actually it's 19.
Also it doesn't seem to use the "database-io" pool either:

1: application-akka.actor.default-dispatcher-2
2: application-akka.actor.default-dispatcher-5

My code:
@Singleton
class AsyncController @Inject()(cc: ControllerComponents, actorSystem: ActorSystem) extends AbstractController(cc) {

  implicit val executionContext = actorSystem.dispatchers.lookup("database-io")

  def message = Action.async {
    getFutureMessage().map { msg => Ok(msg) }
  }

  private def getFutureMessage(): Future[String] = {
    val defaultThreadPool = Thread.currentThread().getName;
    println(s"""1: $defaultThreadPool""")

    val promise: Promise[String] = Promise[String]()
    actorSystem.scheduler.scheduleOnce(0 second) {
      val blockingPool = Thread.currentThread().getName;
      println(s"""2: $blockingPool""")

      Thread.sleep(10000)
      promise.success("Hi!")
    }(actorSystem.dispatcher)
    promise.future
  }

}

A: It could be two reasons for this behavior:

*

*You use the development mode (1 thread), or your product configuration is configured only for one thread.

*The browser blocks the second request until receiving the response from the first. This phrase: "If I call the REST interface from one tab in the browser." Try to do the same from different browsers.

A: You need to avoid blocking code. Basically:

*

*You can a method that returns the Future.

*You map into it.

*You recover any failure the Future result might bring.
Lets say I have:
def userAge (userId: String): Future[Int] = ???

Then you map into it:
userAge.map{
  age => ??? //everything is ok
}.recover{ case e: Throwable => ??? //Do something when it fails

Note that if you have more than one call the other map becomes flatMap because you want Future[...] something and not Future[Future[...]].


text:
Q: Java getDefaultEnvironment() does not rescan hardware I am trying to get a refresh button to reload a list of controllers however the hardware check is only preformed once no matter how many times I call it
Controller[] controllers = ControllerEnvironment.getDefaultEnvironment().getControllers();

This works fine the first time it is executed and even prints this into the console:
Jul 13, 2015 1:22:58 PM net.java.games.input.ControllerEnvironment log
INFO: Linux plugin claims to have found 2 controllers

These two controllers then are properly displayed in my list.
The issue is that this only runs once and never re-preforms the hardware scan thus not showing when a controller is disconnected. I have found a question very similar to this already here on stack overflow but I am not really sure how it works or if it works for linux.
Could someone please explain why getDefaultEnvironment() does not rerun and what is a simple way of forcing this?


text:
Q: Implementing a bidirectional listview in Flutter How do you implement a bidirectional scroll view in Flutter? ListView has a scrollDirection field however it can only take either Axis.horizontal or Axis.vertical. Is is possible to have both?

A: Here's a potential solution using an outer SingleChildScrollView. You could also use a PageView of multiple ListViews if you're ok with the offscreen ListViews being torn down.
import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(
    home: new MyHomePage(),
  ));
}

class MyHomePage extends StatelessWidget {
  Widget build(BuildContext context) {
    ThemeData themeData = Theme.of(context);
    return new Scaffold(
      body: new SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: new SizedBox(
          width: 1000.0,
          child: new ListView.builder(
            itemBuilder: (BuildContext context, int i) {
              return new Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: new List.generate(5, (int j) {
                  return new Text("$i,$j", style: themeData.textTheme.display2);
                }),
              );
            },
          ),
        ),
      ),
    );
  }
}

A: See my answer on this question that I posted and self-answered. I'm not aware of a way to do it with a single Scrollable, although I can imagine it being useful.

You can't easily solve this with an infinite-length ListView.builder
  because it only goes in one direction. If you want to wrap in both
  directions, it is possible to simulate bidirectional wrapping with a
  Stack of two Viewports going in opposite directions.

There's a code sample on the question too (you might have to modify the answer a bit if you don't want wrapping).


text:
Q: recipient rejected in a SMTP connection from a OpenVz container I'm facing a strange problem. I'm getting a recipient rejected on a SMTP server only from inside an OpenVZ container, while  from the physical server everything works fine.
Here's an example of a telnet test connection while inside a routed Vz container:
telnet mx.adomain.com 25
[...]
rcpt to: username@adomain.com
550 5.1.1 <username@adomain.com> recipient rejected
Connection closed by foreign host.

While the same telnet connection from a physical server works as expected. The problem arises only with the mx.adomain.com server, on other SMTP servers like for example gmail.com everything works fine even inside the virtual container.
I've checked and the IPs of the Vz containers don't belong to any blacklist. More strange is that until 3 days ago everything worked fine.
Any ideas?

A: Because you get delivery from one machine  but not the other, I'd assume that the remote MTA is being reticent or lying outright on the 'recipient rejected' bit - qmail, for instance, does it all the time.
So possible causes would be:

*

*One client is on a BL, the other is not.

*One client not in the SPF record for the domain

*Something fishy in the smtp chat "[...]" (e.g. wrong helo line)

*Container has "wrong" reverse resolution or no reverse resolution

*Assorted local policies at the receiving end

NOte that points 1 and 2 assume the host and the container talk from different IPs (no NAT).
Best bet would be asking to the postmaster at the receiving end - assuming he/she's listening.
Cheers,


text:
Q: Changing .cs file code but it is not really changing I am changing code in a .cs file, but in the frontend it is not changing, this .net project is built with the help of Telerik Framework, this is the source code side script, that i am trying to change, but its not changing for me in the frontend.
Contact.aspx
<%@ Page language="c#" Codebehind="Contact.aspx.cs" AutoEventWireup="True"  MasterPageFile="~/DP.Master" Inherits="divorce.Contact" %> <asp:Content ID="Content1" ContentPlaceHolderID="ContentLeft" runat="server">
Contact Us

Feel
                                free to browse around this site. If you have comments or questions about our
                                services, or simply need more information and want to contact us, click on the
                                contact button on any page within this site.

                                We promptly respond to all inquiries.

Label

Your
                                                    Name:

<input id="contactName" type="text" size="50" name="ContactName" runat="server">

Your
                                                    Email Address:

<input id="email" type="text" size="50" name="Email" runat="server">

Comments:

<textarea id="comments" name="Comments" rows="15" cols="38" runat="server"></textarea>

<input id="contactSubmit" type="submit" value="Submit" name="contactSubmit">

 </asp:Content>

Contact.aspx.cs
using Pobk.OpenMail.Message;
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Mail;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace divorce
{
    public partial class Contact : System.Web.UI.Page
    {

        protected void Page_Load(object sender, System.EventArgs e)
        {
            this.lblError.Visible = false;

            if (this.IsPostBack == true)
            {

                if (this.contactName.Value.Trim().Length == 0 ||
                    this.email.Value.Trim().Length == 0 ||
                    this.comments.Value.Trim().Length == 0)
                {
                    lblError.InnerText = "Please fill out all three fields - your name, email address, and message.";
                    lblError.Visible = true;
                }
                else if (IsValidEmail(this.email.Value) == false)
                {
                    lblError.InnerText = "Please enter a valid email address.  Example: MyName@MyServiceProvider.com.";
                    lblError.Visible = true;
                }
                else
                {
                    MailMessage msg = new MailMessage();
                    msg.From = "andrew@divorcepacket.com";
                    msg.To = "andrew@divorcepacket.com";
                    msg.Subject = "DivorcePacket Contract Form";
                    msg.Body = this.email.Value + " " + this.comments.Value;
                    msg.BodyFormat = MailFormat.Text;

                    try
                    {
                        SmtpMail.SmtpServer = @"relay-hosting.secureserver.net";
                        SmtpMail.Send(msg);
                        this.Response.Redirect("messagesent.aspx?s=y", false);
                    }
                    catch (Exception ex)
                    {
                        this.Response.Redirect("messagesent.aspx?s=n", false);
                    }

                }

            }

        }

        private bool IsValidEmail(string strEmail)
        {

            try
            {
                return (new EmailAddress(strEmail)).IsValid;
            }
            catch (Exception ex)
            {
                return true;
            }

        }

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        ///
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        ///
        private void InitializeComponent()
        {

        }
        #endregion
    }

}

Can anyone help me on this?
What the problem coming is, when i am trying to change the .cs file, it is not changing things on my aspx file, for example if i m trying to change the the code this.Response.Redirect("messagesent.aspx?s=n", false); to this.Response.Redirect("messagesent234343.aspx?s=n", false); it is not changing after form submission the form is going to the same old place i.e. messagesent.aspx?s=n and not to messagesent234343.aspx?s=n in short: i am doing the changes, but its not changing in the aspx file –

A: This sounds sort of like what happened to me yesterday. I eventually found out that my visual studio which hadn't been restarted in awhile was not actually saving the files even though it appeared to be rebuilding and running the code. A computer and visual studio restart got it working for me.


text:
Q: The knowledge of $n=n(s)$ can be used to determine the curvature $k(s)$ and the torsion $\tau (s)$ Question:

Show that the knowledge of the vector function $n=n(s)$ of a curve $\alpha:I\rightarrow \mathbb{R^3}$ with nonzero torsion everywhere, determines the curvature $k(s)$ and the torsion $\tau (s)$ of $\alpha$.

Notes: $n$ is the normal versor to $\alpha$.
Attempt: I tried using Frenet-Serret formulas, and then using the vector product between $n$ and $n'$, but it seems like I can't get to any result.

A: The Question as posed here is not solvable (as is indicated by the comments in the answer above). One needs the knowledge of the function $\frac{\kappa}{\tau}$ at one point $t_0$.
Lets give a counterexample:
Consider the Helix
$$ c(s) := (a \cdot \cos(s) , a \cdot \sin(s) , b \cdot s) \text{ for } s \in \mathbb{R}$$
with $a^2 +b^2 = 1$, $a,b>0$. Then $c(s)$ ist parametrized by arclength.
The normal vector is given by
$$ n(s) = (- \cos(s) , -\sin(s), 0) \text{ for all } s\in \mathbb{R}.  $$
One has in general $\kappa=a, \tau= -b$ and $\frac{\kappa}{\tau}=-a/b$.
The choices $a_1=b_1= 1/\sqrt{2}$ and $a_2= 1/2 ,b_2= \sqrt{3}/2$ give two different curves parametrized by arclength. Both curves have the same normal vector for all times and non-vanishing torsion. And both curves have different curvature and torsion.

A: Hint: This is rather a long calculation. If you need any more steps feel free to ask.
The idea though is to show that $$\frac{(n \wedge n') \cdot n''}{|n'|^2} = \frac{(\frac{\kappa}{\tau})'}{(\frac{\kappa}{\tau})^2  + 1} : = a (s)$$
Then,
$$\int a(s) ds = \arctan \left(\frac{\kappa}{\tau}\right)$$
Thus $\kappa/\tau$ can be determined, plus we have that $\kappa > 0$ then we may get the sign of $\tau$. Finally, use
$$|n'|^2 = |- \kappa t - \tau b|^2 = \kappa ^2 + \tau^2$$
to determine $\kappa^2$ and $\tau^2$.


text:
Q: spark-shell initiation error /tmp/hive not writable I have installed Scala, Spark, SBT and winutils on the windows box. Also configured JAVA_HOME, SPARK_HOME, SCALA_HOME, SBT_HOME appropriately. Still, when I try to run 'spark-shell', I run into a very common problem which I see many people have faced.
I have tried giving access to c:/tmp/hive directory through winutils as well as through windows explorer. Yet the same issue. I would appreciate if anyone can tell me what else I might be missing?
Versions:
Spark: 2.1.1
Scala: 2.11
Below are the links to screenshots:
https://filedropper.com/filemanager/public.php?service=files&t=b5cc12549b9ae19ff969c65cb952c135
https://filedropper.com/filemanager/public.php?service=files&t=cb5b9b8f14980963be6f0a6511f71455
https://filedropper.com/filemanager/public.php?service=files&t=a2d471abfe57ca020a700c226b906faf
Appreciate your help!
Thanks,
Manish

A: Thank you cricket_007 and Jacek. I appreciate your comments.
It turned out an issue with version compatibility with winutils. Had to try several versions until the right version changed the permissions on /tmp/hive


text:
Q: Window style not being applied when DataTemplate build dynamically I have a ResourceDictionary that contains Style definitions for controls used within my application.
All of the styles are applied properly to the controls in the window.
In one specific case, I need to build DataTemplate and Grid dynamically by code (in code behind). When my control is display, all items and data are correctly displayed but, it's seems that Style are not applied. When I clicked on border of my screen to resize, the Style is applied at this specific moment.
Why? And what can I do to applied Style when control is displayed?
EDIT
Here's my Xaml:
<Common:MyPopUpWindow
  ...
  ...
  >
   <Common:MyPopUpWindow.DataContext>
      <Controls:DynamicPicklistControlViewModel/>
   </Common:MyPopUpWindow.DataContext>
   <Grid x:Name="LayoutRoot" Margin="2" Behaviours:ToolbakKeyBehaviour.IsEnabled="True">
      <Grid.RowDefinitions>
         <RowDefinition Height="*"/>
         <RowDefinition Height="auto" />
      </Grid.RowDefinitions>

      <Grid x:Name="grdPicklist">
         <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="*"/>
         </Grid.RowDefinitions>

         <Common:MyBlockListBox x:Name="lbxPicklist"
                                Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="99" />
      </Grid>
      <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right">
         ...
         ...
      </StackPanel>
   </Grid>
</Common:MyPopUpWindow  >

And this is my code behind:
  private void OnShowPicklist(DynamicPicklistControlViewModel.ShowPicklistMessage obj)
  {
     if (!IsVisible)
     {
        CreateDataTemplate(obj.ColumnSpecs);
        CreateGridLayout(obj.ColumnSpecs);
        ShowDialog();
     }
  }

  private void CreateDataTemplate(IEnumerable<AdmPicklistColSpec> columnSpecs)
  {
     var xaml = new StringBuilder();

     xaml.AppendLine("<ResourceDictionary xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' ");
     xaml.AppendLine("                    xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' ");
     xaml.AppendLine("                    xmlns:Common='clr-namespace:Xxx.Xxxxxxxxxx.Xxx.Xxxx.Client.Common'>");
     xaml.AppendLine("");
     xaml.AppendLine("   <DataTemplate x:Key='dtplPicklist'>");
     xaml.AppendLine("      <Grid x:Name='grdPicklist'>");
     xaml.AppendLine("         <Grid.ColumnDefinitions>");

     for (var i = 0; i < columnSpecs.Count(); i++)
     {
        xaml.AppendLine("            <ColumnDefinition Width='*'/>");
     }

     xaml.AppendLine("         </Grid.ColumnDefinitions>");
     xaml.AppendLine("         <Grid.RowDefinitions>");
     xaml.AppendLine("            <RowDefinition Height='{StaticResource DefaultListBoxItemHeight}' />");
     xaml.AppendLine("         </Grid.RowDefinitions>");
     xaml.AppendLine("");

     var iCol = 0;
     foreach (var colSpec in columnSpecs)
     {
        xaml.AppendLine("         <Common:MyFormTextBox x:Name='txtCol" + colSpec.DisplaySeqNbr + "' ");
        xaml.AppendLine("                                    Grid.Column='" + iCol + "' ");
        xaml.AppendLine("                                    Text='{Binding Path=Col" + colSpec.DisplaySeqNbr + "}' />");

        iCol++;
     }

     xaml.AppendLine("      </Grid>");
     xaml.AppendLine("   </DataTemplate>");
     xaml.AppendLine("</ResourceDictionary>");

     var xamlParse = (ResourceDictionary)XamlReader.Parse(xaml.ToString());
     foreach (var key in xamlParse.Keys)
     {
        Resources.Add(key, xamlParse[key]);
     }
  }

  private void CreateGridLayout(IEnumerable<AdmPicklistColSpec> columnSpecs)
  {
     var grid = grdPicklist;

     if (_multiplePicklist)
        grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Auto) });

     // <ColumnDefinition>
     for (var i = 0; i < columnSpecs.Count(); i++)
     {
        var colDef = new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) };
        grid.ColumnDefinitions.Add(colDef);
     }
     // Adding extra column for scrollbar
     grid.ColumnDefinitions.Add(new ColumnDefinition { Width = (GridLength)Application.Current.Resources["DefaultListBoxScrollBarWidth"] });
     // </ColumnDefinition>

     // Defines Labels
     var iCol = 0;
     foreach (var label in columnSpecs.Select(colSpec => new MyStackLabel { Content = colSpec.LabelTxt }))
     {
        Grid.SetRow(label, 0);
        Grid.SetColumn(label, iCol);
        grid.Children.Add(label);
        iCol++;
     }

     // Block list box
     lbxPicklist.ItemTemplate = Resources["dtplPicklist"] as DataTemplate;
     lbxPicklist.SetBinding(MyBlockListBox.ItemsSourceProperty, new Binding("Items"));
     var colSpan = columnSpecs.Count() + 1;
     Grid.SetColumnSpan(lbxPicklist, colSpan);
  }

A: I fixed to problem by setting the property SizeToContent to Manual instead of WidthAndHeight and specified a Width and Height in my Xaml.


text:
Q: How to summarize column value by multiple non-excluding dummy columns? I want to summarize (min, max, mean, sd) my distance value by group, which are non-exclusive and are denoted by a dummy column. Converting to a long format would be a solution but this does not work when groups are non-exclusive.
My data looks like this:

distance
group1
group2
group3

51
1
1
0

25
1
0
0

33
0
0
0

92
0
0
1

A: I think we can use pivot_longer() even with non-exclusive groups. Below distance 51 is included in group1 and  group2:
library(tidyverse)

dat %>%
  pivot_longer(cols = starts_with("group"),
               names_to = "group") %>%
  filter(value == 1) %>%
  group_by(group) %>%
  summarise(across(distance, list(min = min,
                                  max = max,
                                  mean = mean,
                                  sd = sd)))
#> # A tibble: 3 x 5
#>   group  distance_min distance_max distance_mean distance_sd
#>   <chr>         <dbl>        <dbl>         <dbl>       <dbl>
#> 1 group1           25           51            38        18.4
#> 2 group2           51           51            51        NA
#> 3 group3           92           92            92        NA

As @moodymudskipper points out in the comments, we can use .by since dplyr v. >= 1.1.0 and the tibble package (attached with tidyverse) also offers  lst as replacement for list which automatically names the list elements after their input objects:
dat %>%
  pivot_longer(cols = starts_with("group"),
               names_to = "group") %>%
  filter(value == 1) %>%
  summarise(across(distance,
                   lst(min, max, mean, sd)
                   ),
            .by = group)

Data from OP
dat <- tribble(
  ~distance,    ~group1,    ~group2,    ~group3,
  51,   1,  1,  0,
  25,   1,  0,  0,
  33,   0,  0,  0,
  92,   0,  0,  1
  )

Created on 2023-03-01 by the reprex package (v2.0.1)

A: If you want a horizontal output the following might fit
library(dplyr, w = F)

summarize(data, across(starts_with("group"), list(
  min = ~min(distance[. == 1]),
  max = ~max(distance[. == 1]),
  mean = ~mean(distance[. == 1]),
  sd = ~sd(distance[. == 1])
)))
#>   group1_min group1_max group1_mean group1_sd group2_min group2_max group2_mean
#> 1         25         51          38  18.38478         51         51          51
#>   group2_sd group3_min group3_max group3_mean group3_sd
#> 1        NA         92         92          92        NA

Created on 2023-03-01 with reprex v2.0.2

A: A base R answer:
mySummary <- function(x) c(summary(x), SD = round(sd(x), 2))
sapply(dat[-1], \(x) mySummary(dat$distance[x == 1]))

        group1 group2 group3
Min.     25.00     51     92
1st Qu.  31.50     51     92
Median   38.00     51     92
Mean     38.00     51     92
3rd Qu.  44.50     51     92
Max.     51.00     51     92
SD       18.38     NA     NA

A: A data.table option
library(data.table)
melt(setDT(df), id.var = "distance", variable.name = "group")[
  value == 1,
  lapply(
    c(min = min, max = max, mean = mean, sd = sd),
    function(f) do.call(f, list(distance))
  ),
  group
]

gives
    group min max mean       sd
1: group1  25  51   38 18.38478
2: group2  51  51   51       NA
3: group3  92  92   92       NA

A: An alternative with reframe + map_dfr():
library(dplyr)
library(purrr)

dat %>%
  reframe(map_dfr(pick(starts_with("group")),
                  ~ filter(pick(distance), .x == 1) %>%
                    summarise(across(distance, lst(min, max, mean, sd))),
                  .id = "group"))

# A tibble: 3 × 5
  group  distance_min distance_max distance_mean distance_sd
  <chr>         <dbl>        <dbl>         <dbl>       <dbl>
1 group1           25           51            38        18.4
2 group2           51           51            51        NA
3 group3           92           92            92        NA


text:
Q: Servlet 3.0 AsyncContext and EJB @RolesAllowed in JBoss reading new Servlet 3.0 specifications, I found startAsynch method for HttpServletRequest, which claims to make things in asynchronous way propagating the right contextual information to the passed runnable.
I wrote this code inside doGet method of my servlet:
@EJB
private EJBManagerLocal manager;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
     if(request.getUserPrincipal() != null && request.isUserInRole("admin"))
          //Method protected by @RolesAllowes("admin") annotation EJB-side
          manager.verify();

     final AsyncContext ctx = request.startAsync(request,response);
     ctx.start(new Runnable(){
          HttpServletRequest = (HttpServletRequest)ctx.getRequest();
          if(request.getUserPrincipal() != null && request.isUserInRole("admin"))
               //Method protected by @RolesAllowes("admin") annotation EJB-side
               manager.verify();
     });
}

When calling manager.verify() the first time, outside AsyncContext everything works fine, but when entering inside the Runnable in debug, i can see that, even the 'if' is succesfully passed (so the principal has been correctly propagated to the Runnable in AsyncContext), when calling the EJB method protected by the @RolesAllowed annotation, JBoss throws an exception saying that "The invocation of method verify" is not allowed.
Can anyone help me?
Platform: JBoss EAP 6.2.0
EDIT: Same behavior in JBoss EAP 6.3.0

A:
which claims to make things in asynchronous way propagating the right
  contextual information to the passed runnable.

The propagation to runnable is met, you are able to access the principal and their roles.
if(request.getUserPrincipal() != null && request.isUserInRole("admin"))

I think the best approach for ejb asynchronous invocations is use @Asynchronous annotation.
See also: Asynchronous Method Invocation
EDIT:
According Java™ Servlet Specification Version 3.0:

Java Enterprise Edition features such as Section 15.2.2, "Web
  Application Environment" on page 15-174 and Section 15.3.1,
  "Propagation of Security Identity in EJB™ Calls" on page 15-176 are
  available only to threads executing the initial request or when the
  request is dispatched to the container via the AsyncContext.dispatch
  method.  Java Enterprise Edition features may be available to other
  threads operating directly on the response object via the
  AsyncContext.start(Runnable) method.

See this thread in jboss forum, is a similar problem: Anonymous principal when invoking EJB from a thread inside a servlet.


text:
Q: How do I get the Hibernate reverse engineering tools to generate  or  for inverse associations? I want to add elements to a collection that ends up getting mapped like this:
<set name="others" inverse="true" lazy="true" table="other" fetch="select">
  <key>
    <column name="otherId" not-null="true" />
  </key>
  <one-to-many class="my.pkg.OtherEntity" />
</set>

I'd like Hibernate to use  instead, because I don't care about the order they're retrieved in, I just want to keep that side of the association up-to-date.  According to https://www.hibernate.org/117.html, "Hibernate can add to a <bag>, <idbag> or <list> declared with inverse="true" without initializing the collection."
My problem is I don't know how to force (or suggest to) the reverse engineering tools (hibernate-tools.jar) to use <bag> or <list>--it ALWAYS uses <set>.
Thanks!

A: You can customize the reverse engineering procedure with a reverse-engineering configuration file, which uses an XML syntax. I haven't tried this myself, but this example may work for you:
<?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-reverse-engineering SYSTEM
    "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
    <table name="MYTABLE">
        <column name="others" type="bag"/>
    </table>
</hibernate-reverse-engineering>

If it does not work as it is, you may find more details about controlling the reverse engineering process here.

A: Ever you would have List-type instead of Set-type you may use ant-java-task using:
<java classname="de.wedeaf.beans.BeanHelper" classpath="WebContent/WEB-INF/classes" args="${basedir}/JavaSource"/>

Using the class "de.wedeaf.beans.BeanHelper":
package de.wedeaf.beans;
import java.io.*;
import org.w3c.dom.NodeList;
import com.sun.org.apache.xerces.internal.parsers.DOMParser;
public class BeanHelper {
 public static void main(String[] args) throws Exception {
  DOMParser parser = new DOMParser();
  parser.parse("file:///"+args[0]+"/hibernate.cfg.xml");
  NodeList list = parser.getDocument().getElementsByTagName("mapping");
  for (int i = 0; list.item(i) != null; i++) {
   String entityFile = args[0] + File.separatorChar + list.item(i)   .getAttributes().getNamedItem("class").getNodeValue().replace('.', File.separatorChar) + ".java";
   // Eingabe
   FileInputStream in = new FileInputStream(entityFile);
   byte[] code=new byte[in.available()];
   in.read(code);
   in.close();
   // Verarbeitung
   String content=new String(code);
   content = content.replaceAll("java.util.Set", "java.util.List");
   content = content.replaceAll("java.util.HashSet", "jav   a.util.ArrayList");
   content = content.replaceAll(" HashSet<", " ArrayList<");
   content = content.replaceAll("Set<", "List<");
       // Ausgabe
   FileWriter fw = new FileWriter(entityFile);
   fw.write(content);
   fw.close();
     }
 }
}


text:
Q: How to run a command / binary without sudo? (Debian/Linux) I installed psensor on my server which I access with RDP.
The problem is psensor requires permissions to read SMART status of hard drives, and I have about 10 installed.
To avoid typing my root password 10 times I ran with sudo, but this does not work because Xlib cannot open the display.
How can I permit psensor to run with higher level privilages as a non sudo-user?
#Update:
This is for example
/dev/sda: brw-rw---- 1 root disk 8, 0 Sep 28 20:35 /dev/sda

(see comments)

A: You just need to follow through with the appropriate authentication. By default sudo removes all non-essential variables from the environment and sets HOME to the target user, but in this case you need to revert one or two of them back:
sudo HOME="$HOME" psensor …

If that's insufficient, try this
sudo HOME="$HOME" DISPLAY="$DISPLAY" psensor …

Note that this will enable root to write to your home directory as if it is its own. Occasionally that will result in root-owned files (or worse, directories) in your own directory that you cannot directly access or delete. If that's not acceptable, try one of these more long-winded alternatives
sudo bash -c "cp -p $HOME/.Xauthority ~ && psensor …"
sudo DISPLAY="$DISPLAY" bash -c "cp -p $HOME/.Xauthority ~ && psensor …"


text:
Q: Is there a reason to check for null inside multiple using clausule in c#? Is there a reason to check for null in the last using? Seems to me like it's most likely not gonna be needed?
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand(commandString, connection))
{
    using (var reader = command.ExecuteReader())
    {
      if (reader != null) {
         // Use the reader
      }
    }
   }
}

EDIT:
Should i close reader.Close() and connection.Close() inside the using if i use it like that:
            using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetailsDZP))
            using (var sqlWrite = new SqlCommand(preparedCommand, varConnection)) {
                 while (sqlWrite.Read()) {
                  //something to do.
                 }
                 sqlWrite.Close();
                 varConnection.Close();
            }

    public static SqlConnection sqlConnectOneTime(string varSqlConnectionDetails) {
        SqlConnection sqlConnection = new SqlConnection(varSqlConnectionDetails);
        sqlConnect(sqlConnection);
        if (sqlConnection.State == ConnectionState.Open) {
            return sqlConnection;
        }
        return null;
    }

Is using of close necessary in following example or i can skip those two?
             sqlWrite.Close();
             varConnection.Close();
With regards,
MadBoy

A: No, this is not necessary.
But that follows from the definition of ExecuteReader, it is not related to the using clause. ExecuteReader either returns a (non-null) DataReader object or it throws an exception.
The expresion in  the if statement will always be true (if it is reached).
And by leaving out the if and all the superfluous brace-pairs you can make this much easier to read:
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(commandString, connection))
using (var reader = command.ExecuteReader())
{
    // Use the reader
}

A: No.  Why would you do that? The documentation doesn't suggest that it might be null.  What would you do if it was null, anyway?  Try it again?

A: the using statements are not going to check for null for you, so if command.ExecuteReader() can return null you have to check for it explicitly, just like in your code snippet.
EDIT: Looks like in this particular case ExecuteReader() should now return null, so you can avoid it. Please remember that you need it in general case though.

A: Seems like the null check is worth it simply to avoid that slim chance that the object is null. Take a look at my answer to How can I modify a queue collection in a loop?
In the example Queue.Dequeue() should never return a null but it does. It's an extreme case but I don't see why you wouldn't want to avoid an unhandled exception, especially if it's as easy as if (object != null)
For Henk (you can run the code yourself and get similar results):
alt text http://www.ccswe.com/temp/Untitled.png
Either way I was simply stating my opinion that just because the documentation says it will do one thing doesn't mean it always will. Not sure why I got the downvote simply because someone has a different opinion :-)
Edit: Stupid tool tip, either way you can see the processed is 9998065 and the null values encountered is 2264. If there is something fundamentally wrong with my example code I'd be interested in hearing it. I'm gonna back away from this thread now.

A: Since you are specifically using SqlConnection and SqlCommand - no, there is no reason for this check.
However, the ADO interfaces are so that you can plug in any other DB provider and use them via the ADO base classes (DbConnection, DbCommand etc). It seems that some providers are returning null sometimes (MySQL maybe?), which may be why the programmer inserted this. Or just because ReSharper issues a warning here? These may be reasons for this, even though it is not necessary if the providers used follow the contract.

A: In this case you should not check reader for null.
But you may use Code Contracts library and use Contract.Assume (or Contract.Assert) to write your assumptions about code. In this case you can use tools for static analysis and easily remove this checks from your release builds.


text:
Q: No solutions with exponents in python sympy When I run this program, I get no solution at the end, but there should be a solution ( I believe).  Any idea what I am doing wrong?  If you take away the Q from e2 equation it seems to work correctly.
#!/usr/bin/python
from sympy import *

a,b,w,r = symbols('a b w r',real=True,positive=True)
L,K,Q = symbols('L K Q',real=True,positive=True)

e1=K
e2=(K*Q/2)**(a)

print solve(e1-e2,K)

It works if we do the following:

*

*Set Q=1 or,

*Change e2 to e2=(K*a)(Q/2)**(a)

I would still like it to work in the original way though, as my equations are more complicated than this.

A: This is just a deficiency of solve. solve is based mostly on heuristics, so sometimes it isn't able to figure out how to solve an equation when it's given in a particular form. The workaround here is to just call expand_power_base on the expression, since SymPy is able to solve K - K**a*(Q/2)**a:
In [8]: print(solve(expand_power_base(e1-e2),K))
[(2/Q)**(a/(a - 1))]

It's also worth pointing out that the result of [] from solve does not in any way mean that there are no solutions, only that solve was unable to find any. See the first note at http://docs.sympy.org/latest/tutorial/solvers.html.


text:
Q: Collision with enemy in pygame making player lose multiple lives I'm trying to make it so then when an enemy collides with the player, a single life is lost and the player is positioned at the center of the screen. It works about half of the time, but the other half of the time two or three lives are lost from one collision.
def collide(self):
        for enemy in enemies:
            if ((robot.hitbox[0] < enemy.x + 16 < robot.hitbox[0] + robot.hitbox[2]) or (robot.hitbox[0] < enemy.x - 16 < robot.hitbox[0] + robot.hitbox[2])) and ((robot.hitbox[1] < enemy.y + 16  < robot.hitbox[1] + robot.hitbox[3]) or (robot.hitbox[1] < enemy.y - 16  < robot.hitbox[1] + robot.hitbox[3])):
                robot.alive = False
                robot.x = 400
                robot.y = 300
                for enemy in enemies:
                    enemies.remove(enemy)
                robot.lives -= 1
                robot.alive = True

This is a function under the class Enemy which is called inside of the Enemy's draw function, which is called in the while loop.
while running:
    ## add if robot.alive == True into loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    userInput = pygame.key.get_pressed()

    if len(enemies) <= 3:
        randSpawnX = random.randint(32, 768)
        randSpawnY = random.randint(77, 568)
        if (robot.x - 100 <= randSpawnX <= robot.x + 100) or (robot.y - 100 <= randSpawnY <= robot.y + 100):
            randSpawnX = random.randint(32, 768)
            randSpawnY = random.randint(77, 568)
        else:
            enemy = Enemy(randSpawnX, randSpawnY)
            enemies.append(enemy)

    if robot.alive == True:
        for enemy in enemies:
            enemy.move()
        robot.shoot()
        robot.movePlayer(userInput)

    drawGame()

Could anyone help me figure out why this is occurring? I believe it's because multiple collisions are registering but since I move the robot to the middle of the screen as soon as the first hit is registered and before the lives are lost, why is this happening?

A: Read How do I detect collision in pygame? and use pygame.Rect / colliderect() for the collision detection.
Read How to remove items from a list while iterating? and iterate through a copy of the list.
If you encounter a collision, it is not enough to change the player's x and y attributes. You also need to change the hitbox. Additionally break the loop when a collision is detected:
def collide(self):
    robot_rect = pygame.Rect(*robot.hitbox)
    for enemy in enemies[:]:
        enemy_rect = pygame.Rect(enemy.x, enemy.y, 16, 16)
        if robot_rect.colliderrect(enemy_rect):
            enemies.remove(enemy)
            robot.x, robot.y = 400, 300
            robot.hitbox[0] = robot.x
            robot.hitbox[1] = robot.y
            robot.lives -= 1
            break


text:
Q: Transparent bitmap is black I have two overlapping imageviews. I want one to stay unchanged while the other one is completely transparent. I am drawing with canvas to the transparent one, but I can not get a transparent bitmap.  How can I rectify this?
When I set its color closer to the transparent color (by diminishing alpha channel) using bitmap.eraseColor(color), it becomes closer and closer to black. When I set it to bm.eraseColor(Color.Transparent) it appears completely black. The imageview that contains the bitmap has a transparent background, so I can show it from the outside of the black bitmap (which is supposed to transparent).
bm.add(decodeSampledBitmapFromResource(
    getIntent().getExtras().getString("filePath"),
    iv.getHeight(), iv.getWidth()).copy(
        Bitmap.Config.ARGB_8888, true));

    scaleBitmap();

    originalImage.setImageBitmap(bm.get(N).copy(
        Bitmap.Config.ARGB_8888, false));

    bm.get(N).eraseColor(Color.TRANSPARENT);
    iv.setImageBitmap(bm.get(N));

Here is the related part of the layout code:
<RelativeLayout
    android:id="@+id/myImages"
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_weight="6"
     >

    <ImageView
        android:id="@+id/originalImage"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:paddingLeft="0dp"
        android:paddingRight="0dp"
        android:scaleType="centerInside"
        android:visibility="visible" />

    <com.abacus.colorsketch.MyImageView
        android:id="@+id/workingImage"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@android:color/transparent"
        android:paddingLeft="0dp"
        android:paddingRight="0dp"
        android:scaleType="centerInside" />
</RelativeLayout>

A: You need to call setHasAlpha before eraseColor.


text:
Q: Classifying singularities and determing orders of complex functions Here are a few functions for reference purposes:
$f(z) = \frac{sin(2z)}{z^3}$, $ \space g(z) = \frac{sin(z)}{tan(z)}$, $ \space h(z) = z^2 sin(\frac{1}{z})$
Suppose I was calculating the singularities of these functions at $z_0 = 0$ and I had to find the order of each function at $z_0$
I understand what all the different singularities are:- removable, pole and essential.
If I plot the graph of say $f(z)$ in the real plane where $z$ is a real number, it looks like the singularity is a pole. This is only a visual guess. It's definitely not removable.
It seems correctable ("fixable"), by multiplying $f$ by $\frac{z^3}{sin(2z)}$, but this would imply any bijective function with a singularity that is not removable must be a pole, right?
I don't think the function is essential, but my understanding of essential singularities is very weak.
When it comes to orders of a function at $z_0$, I know how to factorize polynomials and determine the order but I'm a bit stuck on the trigonometric functions.
Do I need to represent them as a polynomial using Taylor Series, or Laurent Series?
Also, is it a bad idea visualizing these complex functions as real functions.
If anyone has any better examples for explanation purposes, that's fine, I only have the functions above for referencing in the question.
Thanks in advance for any help.

My guesses for $g$ and $h$ are pole and essential respectively.

A: A singularity of a holomorphic function $w$ at a point $a$ is:

*

*Removable if the limit of $w$ at $a$ exists, and if $w$ were extended to have the limit as its value at $a$, then the extended function is holomorphic at $a$. ("Holomorphic at $a$" = "analytic at $a$" = "derivative exists in some neighborhood of $a$".)

*A pole, if it is not removable, but there is a positive integer $n$ such that $(z - a)^nw(z)$ has a removable singularity at $a$. The order of the pole (not the function) is the smallest value of $n$ that works.

*Essential if it is not removable nor a pole.

I.e.,

*

*A removable singularity is one that doesn't really need to be there. It is just an artifact of how the function is defined, not a natural part of the function's behavior.

*A pole is a real singularity, but one that is well-behaved. In some neighborhood of the singularity, the function acts like $\frac1{z^n}$ does near $0$.

*An essential singularity is not well-behaved. Unlike poles, it may not be isolated, and even when it is isolated, its behavior is complicated (per Picard's theorem, it is very complicated).

For your functions,

*

*Note that multiplying $f(z)$ by $z^3$ gives a function with an obviously removable singularity, so $f(z)$ has a pole. The order of that pole is at most $3$, but in fact it is smaller (I'll let you try to figure out what it really is).

*For $g(z)$, recall that $\tan z = \frac {\sin z}{\cos z}$ and simplify. How does $\cos z$ behave at $0$? (Note that $g(z)$ itself is not defined at $0$, so it does have a singularity there.)

*While $\lim_{z\to0} h(z)$ exists, consider $\lim_{z\to0} h'(z)$. If it is analytic, all derivatives of $h$ would exist. Multiplying $h(z)$ by $z^n$ just puts off the derivative where the limit fails to exist. It does not solve the issue altogether.

Your concept on $f$ that it is fixable by multiplying by $\frac {z^3}{\sin 2z}$ is of no value. Every singularity of any analytic function is "fixable" by multiplying by the function's inverse! This is not a useful property.


text:
Q: Property and name at runtime from a class I have a class
public class ProjectTask
{
    public ProjectTask();

    [XmlElement("task_creator_id")]
    public string task_creator_id { get; set; }
    [XmlElement("task_owner_id")]
    public string task_owner_id { get; set; }
    [XmlElement("task_owner_location")]
    public TaskOwnerLocation task_owner_location { get; set; }
    [XmlElement("task_owner_type")]
    public string task_owner_type { get; set; }
    [XmlElement("task_type_description")]
    public string task_type_description { get; set; }
    [XmlElement("task_type_id")]
    public string task_type_id { get; set; }
    [XmlElement("task_type_name")]
    public string task_type_name { get; set; }
}

An xml will be deserialized to this at runtime.
Is there way to get the field name and value?
Using reflection I can get the property names like so:
PropertyInfo[] projectAttributes = typeof(ProjectTask).GetProperties();

A foreach loop can be applied to get the properties
foreach(PropertyInfo taskName in projectAttributes)
       {
           Console.WriteLine(taskName.Name);
       }

but how do I print the property and the value?
Like
    task_creator_id = 1
where task_Id is one of the properties and the value of that at runtime is 1.

A: Use  taskName.GetValue(yourObject,null)
where yourObject should be of an instance of ProjectTask. For ex,
ProjectTask yourObject = (ProjectTask)xmlSerializer.Deserialize(stream)

var propDict = typeof(ProjectTask)
                  .GetProperties()
                  .ToDictionary(p => p.Name, p => p.GetValue(yourObject, null));

A: You can do that using your PropertyInfo object :
var propertyName = MyPropertyInfoObject.Name;
var propertyValue = MyPropertyInfoObject.GetValue(myObject, null);

A foreach loop give you access to all properties of your type, you can also have a specefic property knowing its name, like so :
var MyPropertyInfoObject = myType.GetProperty("propertyName");


text:
Q: checking whether a number is prime i am trying to create a for loop that goes through numbers in within range and check if they are divisible. Here is my code:
user_input = input("pick a number")

for i in range(1, int(user_input)):
    if int(user_input) % i == 0 and i != 1 and i != int(user_input):
        print("Your number is prime")
    else:
        print("your number is not prime")

the second condition keeps getting executed even for prime numbers. What am I doing wrong?

A: When you use a for loop, you are iterating the number of times that are in range(1, int(user_input)) and so your if/else gets executed over and over again, and in each iteration is printing something. Instead you only want to print when you are done.
To pull this off, you want to use a boolean True/False variable to track if the number is prime or not, and set it accordingly in your for loop.
user_input = input("pick a number")

is_prime = True
for i in range(2, int(user_input)):
    if int(user_input) % i == 0 :
        is_prime = False
        break #break out of the for loop since the number isn't prime

if is_prime:
   print("Your number is prime")
else:
   print("your number is not prime")

Some other small changes:

*

*Removed condition and i != 1 as any iteration past 1 would fail this test and you want to check EVERY number in your iterations

*Removed condition and i != int(user_input) since in your iterations you will never reach this number range() is not inclusive of the highest number.

*Added a break once we determine that the number is not a prime so we don't waste iterations checking if it's even more not-prime.

A: There are some issues with your code range should be  2 not 1. Add a break statemnt once condition satisfies.
user_input = input("pick a number")
user_input  = int(user_input)

for i in range(2, user_input)::  #for i in range(2, int(user_input /2)+1) also works
    if (user_input  % i) == 0:
        print("Your number is prime")
        break
else:
    print("Your number is not a prime")

More simpler approch
user_input = int(input("pick a number"))
result = all(user_input % i for i in range(2, user_input))

if result:
     print("Your number is prime")
else:
     print("Your number not a is prime")


text:
Q: Result are not equals from CryptoJS and Kotlin/Java encryption I need to replicate the same cryptography of CryptoJS on my Kotlin android application, I already set the same algorithm and transformation for both.
Kotlin code
Extension to encrypt/decrypt: (I not tested decrypt)
private val ALGORITHM = "AES"
private val TRANSFORMATION = "AES/CBC/PKCS7Padding"

fun ByteArray.toEncryptedHash(key: String): String {

    var outputBytes = ByteArray(0)
    try {
        val secretKey = SecretKeySpec(key.toByteArray(), ALGORITHM)
        val cipher = Cipher.getInstance(TRANSFORMATION)
        val ivParameterSpec = IvParameterSpec("1234567891234567".toByteArray())
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec)

        outputBytes = cipher.doFinal(this)

    } catch (ex: IOException) {
        //throw CryptoException("Error encrypting/decrypting file", ex)
    }

    return Base64.encodeToString(outputBytes, 0)
}

fun String.toDecryptedByteArray(key: String): ByteArray {

    var outputBytes = ByteArray(0)

    try {
        val secretKey = SecretKeySpec(key.toByteArray(), ALGORITHM)
        val cipher = Cipher.getInstance(TRANSFORMATION)
        cipher.init(Cipher.DECRYPT_MODE, secretKey)

        val inputByte = Base64.decode(this.toByteArray(), 0)

        outputBytes = cipher.doFinal(inputByte)

    } catch (ex: IOException) {
        //throw CryptoException("Error encrypting/decrypting file", ex)
    }

    return outputBytes
}

MainActivity:
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        Log.d("ENCRYPT TEST", "DSDASSADAS DAS ADSD".toByteArray().toEncryptedHash("ZGFzZGFzZGZhZ2Y="))

    }
}

CryptoJS code (on postman:)
const payload = "DSDASSADAS DAS ADSD";

const encrypted = CryptoJS.AES.encrypt(
      CryptoJS.enc.Utf8.parse(payload),
      "ZGFzZGFzZGZhZ2Y=",
         {
          keySize: 128,
          iv: CryptoJS.enc.Utf8.parse('1234567891234567'),
          mode: CryptoJS.mode.CBC,
          padding: CryptoJS.pad.Pkcs7
        }
);
console.log(encrypted.toString())
pm.globals.set("userEncrypted", encrypted.toString());

Result from Kotlin Android app:
bsOVFANvitVwybiPCcjLe189KuQV5Jb70iLoLQOog8Q=
Result from CryptoJS (postman console):
U2FsdGVkX19tqC2bt+P4KddWhhxQrHyIsRpggPDQX79gI24fg64Cl14rDtuosN44
It's not the same hash, I think CryptoJS do many things, not only cripto with AES.
How to get the same hash on Kotlin? (I don't have permission to change the js application, I need to replicate on Kotlin).
The answer can be on Java, no problem.


text:
Q: how to return current datetime of the server and pass it through ajax to my jquery script? I want to display the current time of the server on my webpage. I know that jquery works on client's side, so I want to import the datetime from my server, for example using ajax.
I found the following code:
try {
  var date = new Date($.ajax({'type': 'HEAD', 'url': 'timeoftheserver.php'}).getResponseHeader('Date'));
}
catch(err) {
  var date = null;
}

but how can I prepare a php page that will return me that particular time?
Thanks!

A: In your timeoftheserver.php:
<?php
   echo date('D, d M y H:i:s')." +0000";
?>


text:
Q: Javascript onClick and onmouseover and onmouseOut I would like to ask how to differentiate between onClick and onMouseOver and onMouseOut.
For instance,
I use onMouseOver to change the tab background to grey using
onMouseOver="this.style.backgroundColor=Blue;"

onMouseOut takes away this background
onMouseOut="this.style.backgroundColor=White;"

How do I write a call for onClick that gives a blue background and keeps it there even when the mouse cursor moves away from the tab?
Thanks

A: How about you have two CSS classes, "active" and "clicked". They both set the background to blue. On click, you add the "clicked" class. On mouse over, you add the "active" class. On mouse out, you remove the "active" class. If the element had the "clicked" class it'd still have it, and hence keep its color.

A: You need to work with event listeners. I recommend using a framework for this, like prototypejs or jquery.
You will need event listeners / observers for observing the mouseOver, mouseOut and click events. When your click event fires, you stop observing for mouseOver and mouseOut. This should do the trick.

A: I would do a check in the MouseOut that only changes the color if it's not already blue.

A: Normally I would add a CSS class to the element which has the active (last clicked on item) state. That CSS class can have priority over the normal styling of the element.
I would even use CSS and not JavaScript for hover state changes.

A: Very simple solution is here for your help. Hope it works for you.

<script type="text/javascript">
function row_mout(mout_value) {
  document.getElementById(mout_value).style.background = "#FFFFFF";
}

function row_mover(mover_value){
  document.getElementById(mover_value).style.background = "#123456";
}

function row_click(click_value) {
 if(document.getElementById('chk_'+click_value).checked == true){
  document.getElementById(click_value).style.background = "#123456";
  document.getElementById(click_value).onmouseout = "";
  document.getElementById(click_value).onmouseover = "";
 }//if over
 else if(document.getElementById('chk_'+click_value).checked == false){
  document.getElementById(click_value).style.background = "#FFFFFF";
  document.getElementById(click_value).onmouseout = function onmouseout(event){
          row_mout(click_value);
        }
  document.getElementById(click_value).onmouseover = function onmouseover(event){
          row_mover(click_value);
        }
 }//else if over
}


text:
Q: Tensorflow LSTM: How to use different weights for each batch? I'm talking about the tf.keras.layers.LSTM implementation, as I want to use cuDNN for my batched LSTM.
Right now, I use a "hand made" LSTM implementation, because I want to have different weights/biases for each batch. Do you know a way how to use TensorFlows LSTM implementation of the LSTM with a unique set of weights/biases for each batch?

A: Maybe you can use something like this. It is an example for a fully-connected layer for a CNN
def dense_fc4(n_objects):
        initializer = lambda: tf.contrib.layers.xavier_initializer()(shape=(1024,512))
        return tf.Variable(initial_value=initializer, name='fc4/kernel',
                           shape=(n_objects.shape[0], 1024, 512))

    W4 = tf.map_fn(dense_fc4, samples_flat)
    b4 = tf.get_variable('fc4/bias', shape=512, initializer=tf.zeros_initializer())
    fc4 = tf.add(tf.matmul(samples_flat, W4), b4)
    fc4 = tf.nn.relu(fc4)


text:
Q: NSURL code to display an image from a sqlite table Ii'm using this NSURL code to display an image. what I want to do is to insert a url from my database table in place of the static url shown in the code below:
Does anyone know how I should proceed?
NSURL *url = [NSURL URLWithString:@"http://www.nyapplecountry.com/images/photosvarieties/redrome04.jpg"];
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
[self.view addSubview:[[UIImageView alloc] initWithImage:image]];
[self.containerView addSubview:self.mainView];

I was thinking of something like:
NSString *urlAddress = [NSString stringWithFormat:@"%@", place.url];

where place.url is coming from my db table. I'm missing something though, not sure what.
thanks for any help

A: Is place.url a NSString object and the full URL to the image? Then it would be as simple as
NSURL *url = [NSURL URLWithString:place.url];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];

A: You can't do it that way. You have to read image from data base and initialize UIImage with that data.


text:
Q: Queue with linked list and counter in C I am implementing a queue with a linked list which is going to have data that will be send and received in the same program with simple commands and I want to add a counter to each data in the queue, values being new, pending or ack.  So do I store it in an array or is there any other way because the number of counters will be huge?
#define TOTALPACKETS 100
#define WINDOW   5
#define ACK      2
#define PENDING  1
#define NEW      0

typedef int Item ;
typedef struct node *link;
struct node{
    Item data;
    Item status;
    link next;
};

int QUEUEempty(link head){
    return head==NULL;
}

void QUEUEput(link *head, link *tail, Item data, Item status){
    if (*head==NULL){
                    (*tail)=(link)malloc(sizeof(node));
                    (*tail)->data=data;
                    (*tail)->next=NULL;
                (*tail)->status=NEW;
                    *head=*tail;
                    return;}
    (*tail)->next=(link)malloc(sizeof(node));
    *tail=(*tail)->next;
    (*tail)->data=data;
    (*tail)->next=NULL;
    (*tail)->status=NEW;
    return;
}

Item QUEUEget(link *head){
    Item data=(*head)->data;
    Item status
    link t=*head;
    *head=(*head)->next;
    free(t);
    return data;
}

A: I like to think I'm fairly good at reading between the lines and divining the hidden intention, but I'm not able to get a good idea of what you're after. I'd make this into comments except there are too many words to fit comfortably in comments and the formatting is very limited.  (It isn't really an answer — that's why it is CW.)
You talk about a 'counter' that has one of three values (NEW, PENDING, ACK).  That sounds more like a state or status than a counter.
Let's try some design; you can say where this is going wrong.  This assumes a non-intrusive queue design.
typedef struct Data Data;   /* This is the data that you're queueing - details TBS */

typedef struct QNode
{
    Data  *data;
    QNode *next;
    QNode *prev;
    ...possibly other data...status?
} QNode;

typedef struct Queue
{
    QNode *head;
    QNode *tail;
    ...possibly other data...counts?
} Queue;

extern int q_add(Queue *q, Data *d);    // Add datum d to queue per policy
extern int q_next(Queue *q, Data **dp); // Remove next datum from queue per policy

Now, there are at least two places where a system based on this outline could store a counter or state.  One place would inside struct Data, an as yet opaque structure type.  The other plausible place would be inside struct QNode.  You could keep tabs on how many nodes are in each state with summary counters in struct Queue too, if that was what you are after.
With this as a starting point, what are you after?  Everything is changeable at this point — but without something concrete to get going with, we're unable to help much more.

A: You already have the status "counter" in your nodes, but (as Jonathan Leffler suggested) let's call it just state or status.
In your ACK receive() of the Selective Repeat ARQ protocol implementation, there is the problem of accessing the node (not just the status, but also the data in case a retransmission is due) with the sequence number sent with the acknowledgement; we have to traverse the linked list to reach the right node, but during this traversal we can also free acknowledged nodes, so that's harmless.
Still, you could improve your data structure. We don't need an explicit state variable for every node, because states are strictly ordered. From head to tail of the list, first there are zero (or more only if you don't immediately free) ACK nodes, second there are zero or more PENDING nodes, and last there are zero or more NEW nodes. So, to maintain the state information, an index or pointer to the first NEW (and perhaps the first PENDING) node would suffice.


text:
Q: How to get the size of interactive viewer widget after the widget is scaled? How to get the size of interactive viewer widget after the widget is scaled. I am using translate of Matrix4, which I get from my transformationController, to go to end point of the widget(right or left) on a button touch, so want to stop at the end but interactive view is going infinite way. Any way to get the last offset or size of the canvas?
And without translate the pan and scaled is working fine with finite size.


text:
Q: Xpages: Search box for data table i have a DataTable on my Xpage. I´ve filled with JavaScript an array with elements from 4 Notes Databases, which i´ve returned to the Table to show it on the DataTable.
This works, but now i need a search (edit box with search button) to search and update the results in the DataTable.
Is this possible? I only found a solution for a datatable, which is directly bind to a view, and nothing for a "manually" filled DataTable.
This is my Datatable code , which includes the JS code to create the array
<xp:dataTable id="dataTable3" rows="990" var="coll2Test"
                style="width:70%" indexVar="idx">

                <xp:this.facets>
                    <xp:pager partialRefresh="true"
                        layout="Previous Group Next"
xp:key="header" id="pager8">
                    </xp:pager>
                </xp:this.facets>

                <xp:this.value><![CDATA[#{javascript:

var fa:NotesDatabase = session.getDatabase(@DbName()[0], "???????");
var faSh:NotesDatabase = session.getDatabase(@DbName()[0],"???????");
var faKb:NotesDatabase = session.getDatabase(@DbName()[0],"???????");
var fa20:NotesDatabase = session.getDatabase(@DbName()[0],"???????");

var vFa:NotesView = fa.getView("???????");
var vSh:NotesView = faSh.getView("???????");
var vKb:NotesView = faKb.getView("????????");
var v20:NotesView = fa20.getView("???????");

var doc:NotesDocument = vFa.getFirstDocument();
var docSh:NotesDocument = vSh.getFirstDocument();
var docKb:NotesDocument = vKb.getFirstDocument();
var doc20:NotesDocument = v20.getFirstDocument();

var faArr= new Array();

while(doc!= null) {

var eintrag = new Array();
eintrag.push(doc.getItemValue("Name"));
eintrag.push(doc.getItemValue("Description"));

faArr.push(eintrag)

doc = vFa.getNextDocument(doc);

}

while(docSh!= null) {

var eintrag = new Array();
eintrag.push(docSh.getItemValue("Name"));
eintrag.push(docSh.getItemValue("Description"));

faArr.push(eintrag)

docSh = vSh.getNextDocument(docSh);

}

.....
//another 2 while
...

return faArr;}]]></xp:this.value><xp:table>
                    <xp:tr>
                        <xp:td>
                            <xp:label
value="Suche:"     id="label14"

style="font-        weight:bold">
                            </xp:label>
                        </xp:td>
                        <xp:td>
                            <xp:inputText
id="inputText7"
                                value="#
{viewScope.searchView6}">

                            </xp:inputText>
                        </xp:td>
                        <xp:td>
                            <xp:button value="suchen"
                                id="button7">
                                <xp:eventHandler
event="onclick"

submit="true" refreshMode="complete" immediate="false"

save="true" id="eventHandler7">
                                </xp:eventHandler>
                            </xp:button>
                        </xp:td>
                    </xp:tr>
                </xp:table>

                <xp:column id="column6">
                    <xp:this.facets>
                        <xp:label id="label11"
xp:key="header"

style="color:rgb(0,128,255);font-weight:bold"
                            value="Name">

                        </xp:label>
                    </xp:this.facets>
                    <xp:text escape="false"
id="computedField5">

                        <xp:this.value><![CDATA[#
{coll2Test[0]}]]></xp:this.value>
                    </xp:text>
                </xp:column>
                <xp:column id="column7">
                    <xp:this.facets>
                        <xp:label id="label12"
xp:key="header"

style="color:rgb(0,128,255);font-weight:bold"
                            value="Description">
                        </xp:label>
                    </xp:this.facets>
                    <xp:text escape="true" id="computedField6">

                        <xp:this.value><![CDATA[#
{coll2Test[1]}]]></xp:this.value>
                    </xp:text>
                </xp:column>

            </xp:dataTable>

Regards
Stefan

A: Write your completely filled JavaScript array into a view scope variable e.g. viewScope.AllEntries at the beginning. Fill your DataTable with

*

*the complete array if no search string is entered.

*the values matching search string if user entered a search string

This way you only need to read the data once from your four views and just filter it later depending on search string.
Move your code to beforePageLoad event. Add at the top
if (viewScope.AllEntries) {
    return;
}

and replace the last line return faArr; with
viewScope.AllEntries = faArr;

This way you'll calculate faArr only once and store it in viewScope.AllEntries.
Replace your code in DataTable "value" with:
if (!viewScope.search) {
    return viewScope.AllEntries;
}
...create and return an array (walking through viewScope.AllEntries)
...which contains only elements with search string viewScope.search

The search field can be an edit field bound to a viewScope like viewScope.search. Trigger a partial refresh of DataTable when user clicks on search button.


text:
Q: Is there a way to route to multiple files in my views in Ruby on Rails I am making a website dedicated to flash and unity games to learn Ruby on Rails hands on and I wanted to know if there was a way to route to all the documents in a folder without entering them in the routes file one by one. I am not sure if I am just being blind, but I have been looking everywhere for an answer.
For example i have to enter:
Get 'game1', to: "games#game1"
In the routes file for an individual game, but I want to be able to add a entire library without having to enter them in one by one.

A: This is what variable segments are for. You should be using something like
get "games/:id" => "games#show"

and looking up the game by params[:id].

A: correct me if i'm wrong, but you have several files (games) into the games view folder and you want to route through a single action?
so, basically, in your routes.rb would have:
get "games/:game_number" => "games#show"

and then, on your games_controller.rb
def show
  # ...
  render "games/#{params[:game_number]}"
end

so, in this case, if you hit /games/first, it would render the view games/first.html.erb
this is not a good practice since the are several pitfalls through out, but, having that in mind, this should work if i got the right scenario :)


text:
Q: How to iterate through list of generic dictionary in C# I have a json object which is been converted to list of Dictionary. The json is as follows:
{
"DataList":
{"Non Fuel":
{
   "sn":"/DataXmlProduct/Customers/DataXml/Customer/DueDate",
   "ItemCode":"/DataXmlProduct/Customers/DataXml/Customer/InvoiceNo",
   "Qty":"/DataXmlProduct/Customers/DataXml/Customer/CustomerNo",
   "Amount":"DataXml/Customer/TotalCurrentCharges"
  },

  "Fuel":{
   "sn":"/DataXmlProduct/Customers/DataXml/Customer/InvoiceNo",
   "ItemCode":"/DataXmlProduct/Customers/DataXml/Customer/InvoiceNo",
   "Amount":"DataXml/Customer/TotalCurrentCharges"
  }
 }
}

The result is (Dictionary<string, object>), Here the value of each dictionary is again a dictionary and I need to dynamically iterate through each values of the dictionary and get the last key & value where the value is a Xpath and need to get the values from the xpath.
Kindly help me with a solution to iterate through the dictionary. It should be generic since the json format can vary based on user input.

A: Assuming that the actual values (such as the contents of fuel) come out as a KeyValuePair<string, object>, then you could do this with a recursive method:
public static void ParseData(object source)
{
    Dictionary<string, object> Dict;
    KeyValuePair<string, object> Kvp;
    if ((Dict = source as Dictionary<string,object>) != null)
    {
        foreach(var kvp in Dict)
        {
            Console.WriteLine(kvp.Key);
            ParseData(kvp.Value);
        }
    }
    elseif ((Kvp = source as KeyValuePair<string, object>) != null)
    {
        Console.WriteLine("{0}{1}", Kvp.Key, Kvp.Value);
    }
}

This makes an assumption or two, but that will iterate through all the data assuming its made of dictionaries and kvps.
Edit: If you've got an XPath and want to get a node then what you'll need to do is prepare an XMLDocument with the data in. You can use the code above to walk through the data to help you build an XMLDocument and then query the document with your XPath.

A: Here's the basic code for processing all the data:
static void IterateDictionary(Dictionary<string, object> dictionary)
    {
        foreach (var pair in dictionary)
        {
            System.Console.WriteLine("Processing key: " + pair.Key);
            object value = pair.Value;
            var subDictionary = value as Dictionary<string, object>;
            if (subDictionary != null)
            {
                // recursive call to process embedded dictionary
                // warning: stackoverflowexception might occur for insanely embedded data: dictionary in dictionary in dictionary in . etc
                IterateDictionary(subDictionary);
            }
            else
            {
                // process data
                System.Console.WriteLine("data: {0}", value);
            }
        }
    }

hope this helps

A: i'll suggest using Json.NET to serialize your objects, however, you've mentioned that the input is dynamic, but are the attributes standardized? Looking at your sample, there are several repeated fields. You can deserialize the json into your classes by doing
JsonConvert.DeserializeObject<YOUR_CUSTOM_OBJECT>


text:
Q: Python Pandas Data sampling/aggregation I have a huge comma separated datetime, unique_id dataset which looks as below.
datetime, unique_id
2016-09-01 19:50:01, bca8ca1c91d283212faaade44c6185956265cc09
2016-09-01 19:50:02, ddd20611d47597435412739db48b0cb04599e340
2016-09-01 19:50:10, 5b8776d7dc0b83f9bd9ad70a403a5f605e37d4d4
2016-09-01 19:50:14, 2b8a2d7179fe08f8c87d125ad5bc41b5eb79d06f
2016-09-01 19:50:20, 902c4428e08f4324a70a5a4bbfabb657c4a9ffc3
2016-09-01 19:50:23, bca8ca1c91d283212faaade44c6185956265cc09
2016-09-01 19:51:10, a2e6521c66e7207398ffe3d4e5bab449f75e616d
2016-09-01 19:51:11, a2e6521c66e7207398ffe3d4e5bab449f75e616d
2016-09-01 19:51:20, f7cfa02eeb3feed2a0f616185312925e4190c66b
2016-09-01 19:51:30, 0bb21868b55b832f1315438ccdb9c508cf37b8b4
2016-09-01 19:51:40, cb3cfe7bc2fa40d20db23ddc209d2062e10c2ce3
2016-09-01 19:51:50, 2b8a2d7179fe08f8c87d125ad5bc41b5eb79d06f
2016-09-01 19:51:55, 099ba09cd602f9d9bb20f5ebc195686dc133b464
2016-09-01 19:52:00, c300e6a54013ee56facab294e326aa523cd4c60a
2016-09-01 19:53:01, bca8ca1c91d283212faaade44c6185956265cc09
2016-09-01 19:53:04, 902c4428e08f4324a70a5a4bbfabb657c4a9ffc3
2016-09-01 19:53:10, 5b8776d7dc0b83f9bd9ad70a403a5f605e37d4d4
2016-09-01 19:53:11, 2b8a2d7179fe08f8c87d125ad5bc41b5eb79d06f
2016-09-01 19:53:17, bca8ca1c91d283212faaade44c6185956265cc09
2016-09-01 19:53:20, 0fe1560c790c78b960b66e7d7336dd76d2ea12cf
2016-09-01 19:53:40, ddd20611d47597435412739db48b0cb04599e340

Using Python Pandas, I would like to get count of unique ids per minute.
For ex.
datetime, count(unique_id)
2016-09-01 19:50:00, 5
2016-09-01 19:51:00, 6
2016-09-01 19:52:00, 1
2016-09-01 19:53:00, 6

I tried using pandas.DataFrame.resample but looks like that is not the way to approach this problem.
resampled_data = raw_df.set_index(pd.DatetimeIndex(raw_df["datetime"])).resample("1T")

A: You can set the datetime as index and use the pandas.TimeGrouper to create the group variable, which can group your data frame with specified frequency in time, and then count the number of unique ids:
import pandas as pd
df.set_index(pd.to_datetime(df.datetime)).groupby(pd.TimeGrouper(freq = "min"))['unique_id'].nunique()

#           datetime
#2016-09-01 19:50:00    5
#2016-09-01 19:51:00    6
#2016-09-01 19:52:00    1
#2016-09-01 19:53:00    6
#Freq: T, Name: unique_id, dtype: int64

A: I think you need specify Series - ['unique_id'] and add  Resampler.nunique:
resampled_data = raw_df.set_index(pd.DatetimeIndex(raw_df["datetime"]))
                       .resample("1T")['unique_id']
                       .nunique()
print (resampled_data)
2016-09-01 19:50:00    5
2016-09-01 19:51:00    6
2016-09-01 19:52:00    1
2016-09-01 19:53:00    6
Freq: T, Name: unique_id, dtype: int64


text:
Q: How to merge two single column csv files with linux commands I was wondering how to merge two single column csv files into one file where the resulting file will contain two columns.

file1.csv
   first_name
   chris
   ben
   jerry
file2.csv
   last_name
   smith
   white
   perry
result.csv
   first_name,last_name
   chris,smith
   ben,white
   jerry,perry
Thanks

A: You're looking for paste.

A: $ cat file1
John
Mary
$ cat file2
Smith
Jones
$ paste -d, file1 file2
John,Smith
Mary,Jones

The -d, argument is used to designate commas as the delimiter between columns


text:
Q: weird math problem involving representation We can write the number $384$ as $4\overline{2}4$ where the bar above the 2 denotes a negative digit, so that $4\overline{2}4$ means $4\times 100−2\times 10+4$. How could we write 1988 in this way?
what type of math is this? does it have a specific name?
if not, does anyone get the question?

A: This is the negadecimal number system, also known as base $-10$ ("negative ten"), assuming the bars are on every other digit and you never place them so there is a bar over the last digit.
Conversion from base ten can be done much like conversion into any other base: divide by the base, leaving a non-negative remainder, and the remainder gives one digit of the result. Repeat until done.
So for $1988,$ dividing by $-10$ with positive remainder:
$$1988=-198\times-10+8,$$
so the last digit is $8.$ Next we continue with the quotient, $-198$:
$$-198=20\times-10+2,$$
so the digit in the "$-10$s" place is $2.$
Next,
$$20=-2\times-10+0,$$
then
$$-2=1\times-10+8,$$
and finally
$$1=0\times-10+1.$$
Reading the remainders from last to first we have $1,8,0,2,8,$ which gives us the negadecimal number
$1\bar80\bar28.$

A: It's like a different base system.
We have $2\overline{1}9\overline{2}$ as the solution.
Alternatively we have $1\overline{8}0\overline{2}8$, which is much harder to find.

A: $384 = 3\times 100 + 8\times 10 + 4\times 1$
$=(3\times 100 + 8\times 10 + 4\times 1)+0$
$=(3\times 100 + 8\times 10 + 4\times 1)+100-100$
$=(3\times 100+100) +(8\times 10-100) + 4\times 1$
$=4\times 100 -2\times 10 + 4\times 1 = 4\overline{2}4$
In essence, what happened is that we take the tens-complement of the digit we wish to modify and increase the digit to its left by one.  If we wish to do this for multiple digits, its best to approach from right-to-left.
$1988=1\times 1000 + 9\times 100+8\times 10+8\times 1$
$ = 1\times 1000 + 9\times 100 + 8\times 10+8\times 1 + 100-100$
$= 1 \times 1000 + (9\times 100+100)+(8\times 10 - 100)+8\times 1$
$=2\times 1000+0\times 100-2\times 10+8\times 1$
$=2\times 1000+0\times 100-2\times 10+8\times 1+10000-10000$
$=1\times 10000 +(2\times 1000 - 10000)+0\times 100 - 2\times 10+8\times 1$
$=1\times 10000 - 8\times 1000 + 0\times 100 - 2\times 10 +8\times 1$
$=1\overline{8}0\overline{2}8$
With practice, one can do this without going through each step like I did above and arrive quickly at an answer.  E.g. rewriting $3334$ would be $1\overline{7}4\overline{7}4$.  Take the tens-complement of the digit you wish to change and increase the digit to its left by one.