text:
Q: Localized System.Windows.Media.Color name The standard color names are english names, ok. But my Application is german so I would like to have the color names in my ComboBox as german names. Instead of "Blue", "Yellow", etc. I would like to have "Blau", "Gelb", etc.
Is there a function that returns all localized names? Or is it that easy that I change the culture in this call?
<ObjectDataProvider MethodName="GetType"
                    ObjectType="{x:Type sys:Type}"
                    x:Key="colorsTypeOdp">
    <ObjectDataProvider.MethodParameters>
        <sys:String>System.Windows.Media.Colors, PresentationCore,
    Version=3.0.0.0, Culture=neutral,
    PublicKeyToken=31bf3856ad364e35</sys:String>
    </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>

A: I have found a useful table that gives me some Translations (english names and german ones) The table can be found here.
I will use the texts and a Converter to display the German color names.

A: As a follow-up to peetee's question and link to this German page about Netscape color names, I've built a small C# wrapper class that you can drop-into your project.
To use, simply call it something similar to:
string germanName = ColorNameGermanTranslator.GetGermanName(Color.Green);

and you get the German name back. It uses the English name as a fallback.

A: Sorry, the code snippet was gone  ... so here it is:
<ObjectDataProvider MethodName="GetType"
                    ObjectType="{x:Type sys:Type}"
                    x:Key="colorsTypeOdp">
    <ObjectDataProvider.MethodParameters>
        <sys:String>System.Windows.Media.Colors, PresentationCore,
    Version=3.0.0.0, Culture=neutral,
    PublicKeyToken=31bf3856ad364e35</sys:String>
    </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>

A: No, these are property names -- as much part of the code / class definition as the String.Length property -- not resources.  Property names aren't localised.


text:
Q: Page Progressbar My client wants to have a progressbar on initial page load. And the instant the page loads to hide it.
So I thought about it and come up with this.
var num = 0,
    progress = $('.progressbar'),
    interval = setInterval(function(){
        num++
        progress.text(num+'%')
    }, 100);

$(window).load(function(){
    clearInterval(interval);
    $({number: num}).animate({number: 100}, {
      duration: 1000,
      easing:'swing',
      step: function() {
          progress.text(Math.round(this.number)+"%");
      }
    })
})

Demo (I added a large image to show the loading)
The only thing I can come up in order to decrease the chance of the number reaching 100 before the dom load is to add a few if to check if the num is for example 50% and decrease the interval repeating value, and the same thing on 75% I guess, but I don't find it very smart.
So pretty much my question is - "Is there a smarter way to do this?"

A: Just an idea, I'm sure you've considered the jQuery progress bar.
I found this concept on Code Academy and made this FIDDLE.
JS
var mybar = $(".progressbar").progressbar({value: 1});

var progress = setInterval(function() {
                                       updateprog();
                                       }, 10
                          );

function updateprog ()
{
      var currentVal = $(".progressbar").progressbar("option", "value");
       var nextVal = currentVal + 1;
       if (nextVal > 100)
          {
           $(mybar).hide();
           clearInterval(progress);
           } else
          {
           $(".progressbar").progressbar({value: nextVal});
           }
}

I haven't styled anything, but that should be fairly straight-forward.

redpajama_set_name: RedPajamaStackExchange


text:
Q: APP rejected by reason 2.16 From Apple
2.16 - Multitasking Apps may only use background services for their intended purposes: VoIP, audio playback, location, task completion, local notifications, etc
detail
Your app uses the Location Background mode but does not include the required "battery use" disclaimer in your Application Description
last time my app is ok to submit,what should i do ?change the info.plist?

A: No you don't need to add it in your plist but you need to wirte "The continued use of GPS may decrease battery life" (like this) in your application meta data description in itunes connect app.


text:
Q: How many VLANs are too few and too many? We're currently running a netwok of 800+ PCs and 20+ servers, the network infrastucture is along the lines of Core Switch 10Gb-> Area Switch 2GB-> Local Switch 1GB-> Desktop.  All running 3Com equipment(1).
We have 3 Area switches for four areas (A, B ,C, D is merged with the core), each area switch will have between 10 and 20 local switches connected to these.  There is also a backup core switch, lesser powered but connected as the main core switch is.
We also have an IP phone system.  The Computers/servers and swicthes are on a 10.x ip range, the phones on a 192.168.x range.  Computers generally don't have to talk to each other except in computer labs, but they do need to be able to talk to most of our servers (AD, DNS, Exchange, File storage etc.)
When we set up, it was decided that we were to have 3 VLANs, one for Switches & Computers, one for Phones and one for server replication (this was against the 3Com engineers advice).  The network has been stable and working since this point(2), but we've now started to upgrade to SAN and Virtualisation environement.  Now splitting this new infrastructure into seperate VLANs makes sense, and re visting how our VLANS are set up seems sensible.
It's now being proposed that VLANs should be set up in a room by room basis, ie a computer lab with 5+ PCs should be it's own VLAN, but if we follow this model we'll be looking at least at 25 "new" VLANS, plus the VLANS for SAN/Virtual servers.  Which seems to me will add an excessive amount of administration, although I am quite happly to be proved wrong.
What would be best practice seem to suggest?  Is there a certain number of PCs that are advisable not to go over/below in a VLAN.
(1) The 3Com switches (3870 & 8800) route between VLANs differently to how some others do it, it doesn't require a seperate router as they are layer3.
(2) We do sometimes get high discard rates, or STP changes, and at time 3Com Network director report that switches are underload and slow to respond to pings, or a failed switch managing to take down the network (all phone & computer VLANS!, once, no idea why)

A: It sounds like somebody in your organization wants to create VLANs w/o understanding the reasons why you'd do it and the pros/cons associated therewith. It sounds like you need to do some measurement and come up with some real reasons for doing this before moving forward, at least with the insane "VLAN for a room" silliness.
You shouldn't start breaking an Ethernet LAN into VLANs unless you have good reasons to do it. The best two reasons are:

*

*Mitigating performance problems. Ethernet LANs can't scale indefinitely. Excessive broadcasts or flooding of frames to unknown destinations will limit their scale. Either of these conditions can be caused by making a single broadcast domain in an Ethernet LAN too big. Broadcast traffic is easy to understand, but flooding of frames to unknown destinations is a bit more obscure (so much so that none of the other posters here even mention it!). If you get so many devices that your switch MAC tables are overflowing switches will be forced to flood non-broadcast frames out all ports if the destination of the frame doesn't match any entries in the MAC table. If you have a large enough single broadcast domain in an Ethernet LAN with a traffic profile that hosts talk infrequently (that is, infrequently enough that their entries have aged out of the MAC tables on your switches) then you can also get excessive flooding of frames.

*A desire to limit / control traffic moving between hosts at layer 3 or above. You can do some hackery examining traffic at layer 2 (ala Linux ebtables) but this is difficult to manage (because rules are tied to MAC addresses and changing out NICs necessitates rule changes) can cause what appear to be really, really strange behaviors (doing transparent proxying of HTTP at layer 2, for example, is freaky and fun, but is utterly un-natural and can be very non-intuitive to troubleshoot), and is generally difficult to do at lower layers (because layer 2 tools are like sticks and rocks at dealing with layer 3+ concerns). If you want to control IP (or TCP, or UDP, etc) traffic between hosts, rather than attacking the problem at layer 2, you should subnet and stick firewalls / routers with ACLs between the subnets.
Bandwidth exhaustion problems (unless they're being caused by broadcast packets or flooding of frames) are not solved with VLANs typically. They happen because of a lack of physical connectivity (too few NICs on a server, too few ports in an aggregation group, the need to move up to a faster port speed) and can't be solved by subnetting or deploying VLANs since that won't increase the amount of bandwidth available.
If you don't have even something simple like MRTG running graphing per-port traffic statistics on your switches that's really your first order of business before you start potentially introducing bottlenecks with well-intentioned but uninformed VLAN segmentation. Raw byte counts are a good start, but you should follow it up with targeted sniffing to get more details about the traffic profiles.
Once you know how traffic moves around on your LAN you can begin to think about segmenting the LAN for performance reasons.
If you're really going to try and button down packet and stream-level access between VLANs be prepared to do a lot of legwork with application software and learning / reverse-engineering how it talks over the wire. Limiting access by hosts to servers can often be accomplished with filtering functionality on the servers. Limiting access on the wire can provide a false sense of security and lull administrators into a complacency where they think "Well, I don't need to configure the app. securely because the hosts that can talk to the app. are limited by 'the network'." I'd encourage you to audit the security of your server configuration before I'd start limiting host-to-host communication on the wire.
Typically you create VLANs in Ethernet and map IP subnets 1-to-1 onto them. You're going to need a LOT of IP subnets for what you're describing, and potentially a lot of routing table entries. Better plan those subnets with VLSM to summarize your routing table entries, eh?
(Yes, yes-- there are ways not to use a separate subnet for every VLAN, but sticking in a strictly "plain vanilla" world you'd create a VLAN, think up an IP subnet to use in the VLAN, assign some router an IP address in that VLAN, attach that router to the VLAN, either with a physical interface or a virtual subinterface on the router, connect some hosts to the VLAN and assign them IP addresses in the subnet you defined, and route their traffic in and out of the VLAN.)

A: VLANs are only really useful for restricting broadcast traffic. If something is going to do a lot of broadcasting, then separate it into its own VLAN, otherwise I wouldn't bother. You might want to have a virtualised duplication of a live system on the same network and want to use the same address range, then again, that might be worth a separate VLAN.

A: VLANs are good as an additional security level. I don't know how 3Com handles it but usually you can segment different functional groups into different VLANs (e.g. Accounting, WLAN, etc.). You can then control who has access to a particular VLAN.
I don't believe there is any significant performance loss if there are many computers in the same VLAN. I do find it impractical to segment LAN in a room by room basis, but again, I don't know how 3Com handles it. Usually the guideline is not size, but rather security or operation.
In effect I don't see any reason to even segment LAN into different VLANs if there are no security or operational gains.

A: Unless you have 25 test and development groups that regularly kill the network with broadcast floods, 25 per-room VLAN's are 24 too many.
Obviously your SAN needs its own VLAN and not the same VLAN as the virtual systems LAN and Internet access! This can all be done through a single ethernet port on the host system, so no worries there about splitting those functions.
If you have performance crap-outs, consider putting your Phone and SAN on separate network hardware, not just VLAN's.

A: There is always going to be broadcast traffic, whether it's name resolution broadcasts, ARP broadcasts, etc. The important thing is to monitor the amount of broadcast traffic. If it exceeds 3 - 5% of total traffic then it's a problem.
VLAN's are good for reducing the size of broadcast domains (as David stated) or for security, or for creating dedicated backup networks. They're not really meant as "management" domains. In addition, you'll add routing complexity and overhead to your network by implementing VLAN's.

A: Generally, you only want to consider using VLANs when you need to quarantine devices (such as an area where users can bring in their own laptops, or when you've got a critical server infrastructure that must be protected) or if your broadcast domain is too high.
Broadcast domains can typically be about 1000 devices large before you start to see issues on 100Mbit networks, though I'd bring that down to 250 devices if you're dealing with relatively noisy Windows areas.
For the most part, modern day networks don't need VLANs unless you're doing this quarantining (with appropriate firewalling using ACLs, of course) or broadcast limitation.

A: They're also useful for preventing DHCP broadcasts for reaching unwanted network devices.


text:
Q: css how do i fix a single nested div when scrolling the other layered/nested contents in a container? I have seen a number of interesting posts on the subject of fixed position elements, but I have a problem that I can't solve.
I have a number of nested divs inside a scrolling div container as in my example here

.bottombox
{
margin-top:0px;
margin-left:0px;
Position: absolute;
width: 200px;
height:200px;
overflow:auto;
background-color: darkblue;
}

.firstbox
{
margin-top:10px;
margin-left:10px;
width: 700px;
height:50px;
background-color: lightblue;
}

.secondbox
{
margin-top:20px;
margin-left:10px;
Position: absolute;
width: 700px;
height:50px;
background-color: brown;

}

.thirdbox
{
margin-top:30px;
margin-left:10px;
width: 100px;
height:100px;
/*Position: fixed;*/
background-color: white;
}

.topbox
{
margin-top:40px;
margin-left:10px;
width: 700px;
height:500px;
background-color: darkgray;
}

As you can see there are a number of "layers" which scroll together. The problem I have is that I want just the white box to stay fixed in relation to the bottom box which is in effect the container.
Can this be done with CSS? If not, what about Jquery to dynamically update its position?

A: I can't think of any way to do this in CSS, but here's a jquery solution:
http://jsfiddle.net/drHam/7/
$("#bottom").scroll(function(){
    var $this = $(this);
    $(".thirdbox").css("top",$this.scrollTop())
                  .css("left",$this.scrollLeft());

    $(".topbox").css("top", $this.scrollTop()*-1)
                .css("left",$this.scrollLeft()*-1);
});

A: I think this is not possible with pure CSS.
I worked out a solution with jquery, see updated fiddle:
var bottom = $("#bottom");
var third = $("#third");
var top = $("#top");

bottom.scroll(function() {
    third.css("left", bottom.scrollLeft());
    third.css("top", bottom.scrollTop());
    top.css("left", -bottom.scrollLeft());
    top.css("top", -bottom.scrollTop());
});


text:
Q: Optimize finding Min/Max value using Entity Framework LINQ only The way I normally find the Min/Max in the database  is using
var employeeWithMinSalary = employees.OrderBy(x=>x.Salary).First()
var employeeWithMaxSalary = employees.OrderByDescending(x=>x.Salary).First()

However, the performance is O(n * Log(n)).
Is there any other way to Optimize the performance to O(n) using Linq only? (No other libraries)

A: It's not necessary to sort a list to find the Min/Max value from a list. The best sorting algorithm has an average complexity of O(N*logN). Both  Max and Min operations shouldn't take more than O(N), even though the list is unsorted.
You can implement the solution posted here or implementing the following code:
   private static Employee MaxBySalary(List<Employee> employees)
    {
        Employee employee = null;
        employees.ForEach(x => employee = ( employee != null && employee.Salary > x.Salary) ? employee : x );
        return employee;
    }

    private static Employee MinBySalary(List<Employee> employees)
    {
        Employee employee = null;
        employees.ForEach(x => employee = (employee != null && employee.Salary < x.Salary) ? employee : x);
        return employee;
    }

Both approaches have O(N) complexity


text:
Q: FLTK Exif data from an image Is there a fltk class/function that deals with extracting exif data from an image? Is there code or any commands? Ive searched all over the internet, and could find nothing.

A: No, there is no such class in FLTK, and probably there will never be. Dealing with Exif data should be in another library that deals with image formarts, not a GUI toolkit.
What I would do if I were you is this: Link my FLTK application with Magick++ (http://www.imagemagick.org/Magick++/) and use ImageMagick C++ API to manipulate Exif data.


text:
Q: Orion Context Broker, how to enable CORS? Using jQuery/AJAX, I am testing the NGSI9 registerContext operation described here.
This NGSI9 operation works with the shared orion instance on
http://orion.lab.fi-ware.eu:1026/NGSI9/registerContext
but not when I try it with my own instance of the Orion Context Broker (orion-psb-image-R3.4) .
Using my own instance, I get 405 Method not allowed, because CORS is not enabled.
How to change the Same Origin Policy on my own instance?

A: Orion Context Broker doesn't include CORS related headers in the response (it has been identified as a future working item).
Thus, if you need CORS, you can implement it with a proxy between your client and Orion, that proxy including any CORS related header that your client may need.
EDIT: since version 0.22.0, orion supports CORS for GET operations with the -corsOrigin CLI parameter. Check documentation about it.
EDIT2: full CORS support including Preflight has been implemented in Orion for all NGSIv2 requests. It is now available in the master branch or in the official docker and soon in the 1.10.0 version (to be released by early December).


text:
Q: want to retrieve the value of specific row in which button was clicked. but i am getting the last one I have table so I want to retrieve key/value of specific row in which button was clicked.
componentDidMount() {
    let com = this;
    firebase
        .database()
        .ref()
        .child("bills")
        .once("value", snap => {
            let items = [];
            snap.forEach(childD => {
                items.push({
                    balance: childD.val().balance,
                    bill_num: childD.val().bill_num,
                    date: childD.val().date,
                    key: childD.val().key,
                    name: childD.val().name,
                    total: childD.val().total
                });
            });
            Array.prototype.push.apply(com.state.products, items);
            com.setState({
                products: com.state.products
            });
        });
}

open = e => {
    e.preventDefault();
    console.log("kal" + this.state.value);
};
handleChange=event=>{
    this.setState({value: event.target.value});
  }

render() {
    return (

                                Bill number
                                Name
                                Date
                                Total
                                Balance
                                Delete
                                Open bill

                            {console.log(this.state.products)}
                            {this.state.products.map((value, key) => (

                                    {value.bill_num}
                                    {value.name}
                                    {value.date}
                                    {value.total}
                                    {value.balance}

                                        <form onSubmit={this.returnOrder}>
                                            <input value={value.key} type="hidden" />
                                            <button className="btn btn-danger" type="submit">
                                                Return
                                            </button>
                                        </form>

                                        <form onSubmit={this.open}>
                                        <input value={value.key} onChange={this.handleChange} ref={ eKey => (this.inputeKey = eKey)} />

                                        <button className="btn btn-info" type="submit">
                                            Open
                                        </button>
                                        </form>

                            ))}

            ) : (
                <Printout
                    keya={{
                        key: this.props.keyas
                    }}
                />
            )}
    );
}
}

A: Typically, tables in React are made from several components: whole table, row and for example buttons in row. So in table you place array of rows. Each row has it's child buttons. So you can send props to RowButtons child with information about clicked row.


text:
Q: Finding a primary decomposition Let $k$ be a field, and $R=k[x,y]$.
I'm supposed to find two different minimal primary decompositions of the ideal $(x^2y, y^2x)$.
It's easy to see that one minimal primary decomposition is $(x)\cap(y)\cap(x^2, y^2)$.
My question: What's the second minimal primary decomposition of the above ideal?
EDIT: I've now added the minimality requirement to the question.

A: Since you suggest this is homework, I'll put this in the form of hints:
(1) Remember that the set of associated primes for a primary decomposition is unique. So you are looking for $\mathfrak{p} \cap \mathfrak{q} \cap \mathfrak{r}$ where $\sqrt{\mathfrak{p}} = (x)$, $\sqrt{\mathfrak{p}} = (y)$ and $\sqrt{\mathfrak{r}} = (x,y)$.
(2) Show that $\mathfrak{p}$ and $\mathfrak{q}$ must be $(x)$ and $(y)$. So the place where you have room to play is in choosing $\mathfrak{r}$.
At this point, I have trouble giving good general hints. The next two, which are far more helpful, will be put in ROT13.
(3) Lbh jvyy abg or noyr gb fbyir guvf ceboyrz vs lbh fgvpx gb vqrnyf trarengrq ol zbabzvnyf.
(4) Gur rknzcyr V sbhaq jnf nyfb trarengrq va qrterr gjb.

A: I'm a bit late with this but even so:
$$ \begin{align} (x^2 y, y^2 x) &= (x^2 y - y^2 x, y^2 x) \\
 &= (xy(x-y), y^2 x) \\
 &= (y) \cap (x(x-y), y^2x) \\
 &= (y) \cap (x) \cap (x-y, y^2)
\end{align}$$
It remains to be shown that $(x-y, y^2)$ is primary:
Let $r(I)$ denote the radical of $I$. Then $r((x-y, y^2)) = (x-y, y) = (x,y)$. To see that $(x,y)$ is maximal note that $k[x,y]/(x,y) \cong k$ is a field. We know that if $r(I)$ is maximal then $I$ is primary so we're done.


text:
Q: How to make EditText was exactly vertical? How to make EditText was exactly vertical ?
Thsi is my ScreenShot http://snag.gy/rJpZ4.jpg
This is my XML layout code
http://pastebin.com/QRNehrRV

A: Use layout_weight Property
Try this code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="0dp"
            android:padding="10dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="One"/>

        <EditText
            android:layout_width="0dp"
            android:padding="10dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>

        </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="0dp"
            android:padding="10dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Asdds"/>

        <EditText
            android:layout_width="0dp"
            android:padding="10dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="0dp"
            android:padding="10dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="KKssooasscasfas"/>

        <EditText
            android:layout_width="0dp"
            android:padding="10dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="0dp"
            android:padding="10dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Kasfas"/>

        <EditText
            android:layout_width="0dp"
            android:padding="10dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>

    </LinearLayout>

</LinearLayout>

A: Use Table layout.
Take this as reference forum.codecall.net/topic/70354-tablelayout-programatically/

A: try this
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
     >
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:orientation="horizontal"
    android:padding="10dp" >
    -

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginRight="10dp"
        android:orientation="vertical" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="first_name"
            android:layout_weight="1"
            android:textColor="@color/white"
            android:textSize="15dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="user_dob"
            android:textColor="@color/white"
            android:textSize="15dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="user_gender"
            android:layout_weight="1"
            android:textColor="@color/white"
            android:textSize="15dp" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/linear_layout_patient_detail_values"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="left"
            android:text="Name"
            android:textSize="15dp" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="left"
            android:text="12/22/1978"
            android:textSize="15dp" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="left"
            android:text="M"
            android:textSize="15dp" />

    </LinearLayout>

</LinearLayout>


text:
Q: How to call a polymorphic function which depends on multiple Typeclasses in Kotlin/Arrow I've created a function which is polymorphic in the Monad it needs to use, instead it depends on the typeclass instances that exists for this Monad. It looks like this:
fun <M> M.logic(...): Kind<M, String>
      where M: MonadReader<M, Dependency>,
            M: Effect<M> =
   fx.monad() {
      val dependency = ask().bind()
      val response = effect { ...using dependency here... }.bind()
      response
   }

I'm using the MonadReader to get a dependency, and I'm using Effect, well, for effects. Now I assumed, that all I need is to use some Monad Transformers to get to this constellation of a Monad "at the end of the world" (i.e. in main()). Something like ReaderT<ForIO, Dependency, Unit>.
However, I can't seem to create a suitable M (or any context) to call this method on. How can I call this method on an exact monad that has the necessary typeclass instances?

A: This is the code snippet you're after:
fun <M, F> M.logic(): Kind<F, String>
  where M: MonadReader<F, String>,
        M: Async<F> =
  fx.monad {
    val dependency = ask().bind()
    val response = effect { dependency }.bind()
    response
  }

object Transformer:
  Async<KleisliPartialOf<ForIO, String>> by ReaderT.async(IO.effect()),
  KleisliMonadReader<ForIO, String> by ReaderT.monadReader(IO.monad())

Note that Async is what you're after, not the poorly named Effect. And you need two generics, one for the composition and another for the content.
Transformer.run {
  logic()
}

The Async instance for Reader was added on January 2020, and will be available on the next release, either 0.10.5 or 0.11.0: https://github.com/arrow-kt/arrow/commit/6aaae6998de612eb0eec948697f1c477649230be


text:
Q: how to add count with username? hello everyone I am making a faucet list like Service
now I am just  wondering how would I display
their username with created and last updated list with their total faucets based on their username
I got a photo what I like it to look like and
I just don't have any
clue how to make it work :/
what I like it to look like

database table for users

database table for the list

the code
<?php
     $sql = "SELECT * FROM list  ";
     $result = mysqli_query($link, $sql);
     if( $result )
     while($user = mysqli_fetch_assoc($result)) {
    ?>

                Faucetlist
                Created
                Last updated
                faucets

            <?php echo $user["username"]; ?>
             <?php echo date('l jS F Y' , strtotime($user['Published']));?>
            <?php echo date('h:i A' , strtotime($user['last_update']));?>
             FAUCETS COUNT GO HERE

       <?php } ?>

A: change your query and follow this code
<?php
         $sql = "SELECT list.*,count(username) as faucet  FROM list  GROUP BY username";
         $result = mysqli_query($link, $sql);
         if( $result )
         while($user = mysqli_fetch_assoc($result)) {
        ?>

                    Faucetlist
                    Created
                    Last updated
                    faucets

                <?php echo $user["username"]; ?>
                 <?php echo date('l jS F Y' , strtotime($user['Published']));?>
                <?php echo date('h:i A' , strtotime($user['last_update']));?>
                 FAUCETS COUNT GO HERE <?php echo $user['faucet'];   ?>

           <?php } ?>


text:
Q: Connecting multiple constraints to a single outlet I have a bunch of objects, all equally spaced from each other. The constraints are set correctly for 3.5" screen, but for the 4" screen I want them farther apart (i.e. the distance between each object still the same, but larger).
I currently change constraints programmatically like this:
self.usernameVerticalSpace.constant = 256;

But if e.g. 8 constraints will be kept exactly the same as each other, but all increased at once, it seems like there should be a way to do that to one outlet, instead of 8 individual outlets. Is there a way to link all these constraints to one outlet, so I only have to change one value?

A: Have you heard about IBOutletCollection? When you link any object from IB to VC code, in popup window you can select IBOutletCollection Option.
Tell me if it is not useful or if more info needed

A: You can create an IBOutletCollection like this in code
@IBOutlet var constraintsCollection: [NSLayoutConstraint]!
Then click inside the small circle infront of the line just added and drag to link each constraint you want to add to the constraintsCollection one after the other in IB.

Once you have added one by one all the constraints to the Constraint Collection, it will contain all constraints like shown below


text:
Q: websocket endpoint fails in Tomcat 10 but not 9 I have moved up to Tomcat 10 and websocket endpoint no longer works/registers. It worked as expected in Tomcat 9, but fails in 10.  Per Websocket Server Endpoints not working on tomcat, I changed the imports to use Tomcat 10's jakarta packages/api's, but had no effect.  Trying to hit the websocket endpoint using Chrome + F12 (ex ws://localhost:8080/myapp/mywsendpoint) showed that nothing was listening.  It's as though it wasn't even registering as a ws listener in Tomcat 10.  All references to javax.xyz have been changed to jakarta.xyz, and the code compiles/builds
@ServerEndpoint(value = "/wscon")
public class WScon{
....removed code for brevity
Any help would be greatly appreciated.


text:
Q: SystemServerCAMSecurityRequired error when authenticating using Cognos I am using the Cognos TM1 10.1 API to connect to a server. The server uses Cognos for authentication which in turn uses integrated login to authenticate users against our instance of Active Directory. I've tried using TM1SystemServerConnect and TM1SystemServerConnectIntegratedLogin, but they both produce an error.
(note that I've used pseduo-code for simplicity - yes, I've verified all the handles, inputs, etc, are correct and accurate)
// Standard login
TM1V pLogin = TM1ValuePool( hUser );
TM1V hServerName = TM1ValString( pLogin, "server", 0 );
TM1V hUser = TM1ValString( pLogin, "userid", 0 );
TM1V hPassword = TM1ValString( pLogin, "password", 0 );
TM1SystemServerConnect( pLogin, hServerName, hUser, hPassword )

// Integrated Login
TM1V pLogin = TM1ValuePool( hUser );
TM1V hServerName = TM1ValString( pLogin, "server", 0 );
TM1V hServer = TM1SystemServerConnectIntegratedLogin( pLogin, hServerName );

The handle I get back from both (hServer) points to an error with code 199 and the message SystemServerCAMSecurityRequired. I've search through IBM's TM1 API Guide and I can't find a solution (or any documentation for this error message)... what's going on? The logs on the server show failed login attemtps, but provide no additional information.

A: The error is because the two documented login functions used above are specificaly for IntegratedSecurityMode 1, 2 and 3.
You've indicated that you are using Cognos to handle user authentication, which is either mode 4 or 5. There are two more-or-less "undocumented" functions for logging in to the server using Cognos authentication:

*

*TM1SystemServerConnectWithCAMNamespace

*TM1SystemServerConnectWithCAMPassport
Here's a sample, written in C++ (copied from here) which you can use a reference for connecting using Cognos authentication:
TM1V voServerName = TM1ValStringW( hPool, (TM1_UTF16_T *)pszServerName, 0 );

TM1V voPasswd = TM1ValStringEncryptW( hPool, (TM1_UTF16_T*)pszPassword, 0 );

TM1V vArray[3];
vArray[0] = TM1ValStringW( hPool, (TM1_UTF16_T*)szCAMNamespace, 0 );
vArray[1] = TM1ValStringW( hPool, (TM1_UTF16_T*)admin_login_name, 0 );
vArray[2] = voPasswd;

TM1V vCAMArgArr = TM1ValArray(hPool, vArray, 3);
TM1V vTmpServer =
    TM1SystemServerConnectWithCAMNamespace(hPool, voServerName, vCAMArgArr);


text:
Q: Inserting data into a column using switch case in SQL Server I need to use switch case in order to insert data into a column in database!
here is my code but its not working!
insert into fr(q)
values((select
            case
               when totalDue > 1000 then 'high'
               else 'Low'
            end as q
        from fr))

A: To make that a valid insert statement, take out the values () part of your code:
insert into fr (q)
  select
    case
      when totalDue > 1000
        then 'high'
      else 'Low'
      end as q
    from fr

Although I think you're probably trying to update the table instead of insert rows into it.
update fr
  set q = case
      when totalDue > 1000
        then 'high'
      else 'Low'
      end;


text:
Q: Passing value from JS to HTML and then using that value to pass back to JS I am running a JS function and at the end of the function I want to send a value through to my HTML to keep a memory of the last value used. I then want to call the JS function again and send the value that I passed to it last back through.
The reason I want to do this is so that I can make sure when the user clicks "New Card" that it won't be repeated. Any ideas on what I'm doing wrong here?
I have found items that show how to pass from one way to the other but that's it.

Your card of the day!

    <input type="hidden" name="currentCardNumber" id="currentCardNumber" />
    <button onclick="newCard(currentCardNumber)">New Card</button>

function newCard(currentCardNumber = 0) {
  const randomNumber = Math.floor(Math.random() * 4);
  console.log(currentCardNumber);
  if (randomNumber == currentCardNumber) {
    newCard(currentCardNumber);
  } else {
    document.getElementById("currentCardNumber").value = randomNumber;
    document.getElementById("cardImage").src = Object.values(
      cards[randomNumber]
    )[1];
    document.getElementById("cardName").innerHTML = Object.values(
      cards[randomNumber]
    )[0];
  }
}

A: I was able to figure out another way (probably a better option) to do what I was trying to do. I was able to get JS to get the value of what was in the HTML code by getting the .innerHTML attribute.
By doing this, I was able to compare the current value on the screen with the value that would be posted from the random draw. Then I had my function check to see if they matched and if so it would run the function again. My code is below (including the array of objects). Maybe there is a more efficient way to do this but It's definitely working out now.
HTML

Your card of the day!

    <button onclick="newCard()">New Card</button>

JS
const cards = [
  { blackSesame: "Black Sesame", image: "images/blacksesame.jpg" },
  { carrots: "Carrots", image: "images/carrots.jpg" },
  { cilantro: "Cilantro", image: "images/cilantro.jpg" },
  { papaya: "Papaya", image: "images/papaya.jpg" },
  { rosemary: "Rosemary", image: "images/rosemary.jpg" },
];

function newCard() {
  const randomNumber = Math.floor(Math.random() * 5);
  const currentCard = document.getElementById("cardName").innerHTML;

  if (currentCard == Object.values(cards[randomNumber])[0]) {
    newCard();
  } else {
    document.getElementById("cardImage").src = Object.values(
      cards[randomNumber]
    )[1];
    document.getElementById("cardName").innerHTML = Object.values(
      cards[randomNumber]
    )[0];
  }
}


text:
Q: joining results after making parallel calls using spring async I'm using spring @Async to make parallel calls to the same method/backend. Is there a clean way to join their results in a list? This is the pseudo code i came up with to make the calls/merge the result, but I'm not sure it's the cleanest way.
List<Future<String>> futureStringList = new ArrayList<Future<String>>();
for(each backend call){
           Future<String> futureString = backend.retrieve();
           futureStringList.add(futureString);
}

List<String> actualStringList = new ArrayList<String>();

    while(!futureStringList.isEmpty()){
           for(Future<String> futureString: futureStringList){
                          if(futureString.isDone()){
                                         actualStringList.add(futureString.get());
                                         futureStringList.remove(futureString);
                          }
           }
    }

A: Future.get() is a blocking call, so you can actually loop over your Future list and you know that, at the end of the loop, all your futures are finished.
List<Future<String>> futureStringList = new ArrayList<Future<String>>();
for(each backend call){
    Future<String> futureString = backend.retrieve();
    futureStringList.add(futureString);
}

List<String> actualStringList = new ArrayList<String>();
for (Future<String> stringFuture : futureStringList) {
  actualStringList.add(stringFuture.get()); // blocking call
}

// all your Strings are retrieved at this point


text:
Q: Why assigning a delegate to a local copy thread safe in C#, any code can prove it? I have been told that multicast delegate in C# is immutable.But this code below seems to prove it is not.
Action a = () => { };
Action b = a;
Console.WriteLine(ReferenceEquals(a, b));

It will display True instead of False. Here is another example:
public delegate void MyHandler();
public class Klass
{
    public event MyHandler onCreate;

    public void Create()
    {
        MyHandler handler = onCreate;
        if (handler != null)
        {
            handler();
        }

        Console.WriteLine(ReferenceEquals(handler, onCreate));
    }
}

This class will be invoked as below:
Klass k = new Klass();
k.onCreate += () => { };

k.Create();

Same as above it will display True,so how could it be thread safe if the local copy is the same reference as the orignal one?

A:
How could it be thread safe if the local copy is the same reference as the orignal one?

I think you may have misunderstood the meaning of immutability. This is how wikipedia defines it:

In object-oriented and functional programming, an immutable object is an object whose state cannot be modified after it is created. This is in contrast to a mutable object, which can be modified after it is created.

A reference assigment from variable a to b does not change the state of the delegate. Hence, multiple threads invoking the same delegate are guaranteed to be invoking the same constructed delegate. Note, this does not mean the underlying method referenced by that delegate is thread safe. Remember, delegates in C# are reference types and they are copied by value, which in their case is the address to the object held by in the GC heap, not the copy of the value itself. More on delegate thread safety in Are C# delegates thread-safe?

A: There are two concepts that make this pattern thread-safe.

*

*The delegate is immutable. Once it is created it will never change. That means you can use it in code and not have to worry about another thread changing it.

*Reference assignments are atomic. Copying the reference to a local variable prevents a race condition between one thread clearing out the multicast chain and the current thread assuming it will reference something other than null.

One possible confusion here is that an event works similar to a variables in that it holds a reference to the multicast delegate. When you do += or -= on it will construct a new multicast delegate and assign the newly created object to the event "variable". The delegate is still immutable so it will never change. It is the event that is not and can be changed by another thread.


text:
Q: How do I tell TextFieldParser to parse from a provided filesystem? I'm writing a method which validates csv-files. I'm also unit-testing, so I'm setting up a mock file system with mock csv-files using System.IO.Abstractions I want to use TextFieldParser to read through the csv-file, but I'm unsure how I tell it to read from the path in the IFileSystem (from System.IO.Abstractions) provided.
Basically, the code looks something like this:
    internal static bool ValidateCsvFile(IFileSystem fileSystem, string path)
    {
        var validated = false;
        using (var csvReader = new TextFieldParser(path))
        {
            //validation
        }
    }

And I want to know how I essentially tell the TextFieldParser to parse from a path using the filesystem provided, instead of using the local computer.

A: Found a solution myself. You have to set the using statement up like this:
        using (var csvReader = new TextFieldParser(fileSystem.FileInfo.FromFileName(path).OpenRead()))

This will let you read from the file in the mocked filesystem, or the local filesystem if you're running the program normally and it calls on a separate public method that calls on this using a new FileSystem (from system.io.abstractions). Basically like this:
    public static bool ValidateCsvFile(string path)
    {
        return ValidateCsvFile(new FileSystem(), path);
    }

Assuming a using System.IO.Abstractions in the .cs-file and no package conflicts.

A: One of the main rules of unit testing is it shouldn't ready any external files. I can understand you are trying to read mock file but that is still a file, it means your unit test is trying to read an external file which is a dependency and should be avoided.


text:
Q: How to print out columns instead of rows? alright so im making a program that prints out how many times the numbers 0-9 were input, its supposed to go on forever, until the user types a negative number, then its gonna stop the program and print out the result, heres my code so far:
import java.util.Scanner;

public class opg33 {
    public static void main(String args[]) {
        System.out.println(1 + ":" + "\t" + "Integer 0-9");
        Scanner keyboard = new Scanner(System.in);

        int[] a = new int[10];
        int counter = 0;
        int input;
        input = keyboard.nextInt();
        boolean exit = true;

        while (exit == true) {
            counter++;
            System.out.println((counter + 1) + ":" + "\t" + "Integer 0-9");
            if (input > -1 && input < 10) {
                a[input]++;
            }

            input = keyboard.nextInt();
            if (input < 0) {
                exit = false;
                for (int i = 0; i < a.length; i++) {
                    System.out.print(i + ":");
                    for (int n = 0; n < a[i]; n++)
                        System.out.print("x");
                    System.out.println();
                }
            }
        }
    }
}

as you can see this program works perfectly fine, just as I wanted it to! the only question I have, is, how can I make it print out vertically like a bar graph (columns), instead of horizontally? thanks in advance!

A: You mean something like...?
1:    Integer 0-9
1
2:    Integer 0-9
1
3:    Integer 0-9
2
4:    Integer 0-9
2
5:    Integer 0-9
2
6:    Integer 0-9
3
7:    Integer 0-9
3
8:    Integer 0-9
7
9:    Integer 0-9
8
10:    Integer 0-9
-1
       x
    x  x  x
    x  x  x           x  x
 0  1  2  3  4  5  6  7  8  9

The first thing you need to do is determine the max height of the chart...
// Calculate the required height...
/*
   All this loop does, is loops through the array "a"
   and finds the maximum value contained within,
   this is the largest number of times the user
   entered that value

   The loop itself is just an enhanced "for-next-loop",
   that is, it's a short cutted way of saying...

   for (int index = 0; index < a.length; index++) {
       int value = a[index];
       ...
   }
*/
int maxFrequency = 0;
for (int value : a) {
    // This is a really simply way to calculate the max value within
    // range, it just says, return me the value which is the larger
    // of two...
    maxFrequency = Math.max(value, maxFrequency);
}

Next, you need to print each row of the chart, starting at the top and moving to the bottom.  For each column, you need to determine if it has a value to be displayed within that row...
// This builds each row
for (int row = maxFrequency; row > 0; row--) {
    // This is used instead of String concatenation (String + String)
    // This is the preferred mechanism for doing String concatenation
    // in loops as it uses less memory and will generally be faster...
    StringBuilder sb = new StringBuilder(30);

    // We need to inspect each value in the array to determine
    // if we need to display something...
    // The basic idea is, we will only start displaying "x"
    // when the value in the array >= the row number...
    for (int value : a) {
        // This just appends each column value as
        // required, prefixing and suffixing it with spaces
        sb.append(" ");
        if (value >= row) {
            sb.append("x");
        } else {
            sb.append(" ");
        }
        sb.append(" ");
    }
    // Print the row...
    System.out.println(sb.toString());
}

And finally, you need to print the footer...
StringBuilder sb = new StringBuilder(30);
for (int i = 0; i < a.length; i++) {
    sb.append(" ").
            append(i).
            append(" ");
}
System.out.println(sb.toString());

The hows and why of StringBuilder
A book could be written on this subject, so the information provided here is just an overview...
StringBuilder should be used, especially, when concatenating Strings in loops,   basically because it reduces the number of temporary, short lived objects that are created and makes the process more efficient.
Normally the Java compiler will convert String concatenation to use StringBuilder internally, but because of the nature of loops, can't do so.  In your case, it's probably not all that important, but in long running programs which might iterate through the loop, hundreds, thousands or even millions of time, it becomes a performance bottleneck, so it is a good habit to form.
Internally, a StringBuilder is a self managed char array, this is not particular important, but it's nice to know.  When you use .append, the StringBuilder is taking the content, making space for it within it's internal buffer and writing out the content to it.  It might sound like that's introducing it's own overheads and to a certain extent it is (you can do things to imittergate these), but it's less then having to run a garbage collection cycle...
toString simply then converts the char array to a String object...
You can find more information at The StringBuilder Class


text:
Q: Wiremock queryParameters regex not working but does match outside wiremock I'm using java -jar wiremock-jre8-standalone-2.32.0.jar --verbose
Here is my mapping
{
   "priority":1,
   "request":{
      "method":"GET",
      "urlPath":"/api/arsys/v1/entry/CHG:Infrastructure%20Change",
      "queryParameters" : {
        "q": {
            "matches": "^.*?(?:\b|_)Infrastructure Change ID(?:\b|_).*?(?:\b|_)CRQ000000030315(?:\b|_).*?$"
        }
      }
   },
   "response":{
      "status":200,
      "headers":{
         "Content-Type":"application/json"
      },
      "bodyFileName": "/api/arsys/v1/entry/chginfrastructurechange/CRQ000000030315.json"
    }
}

I'm trying to match a GET with params ('Infrastructure Change ID' IN ("CRQ000000030315", "CRQ000000030316"))
The regex matches example here: https://regex101.com/r/oswkUE/1
The verbose out is:
[0:0:0:0:0:0:0:1] - GET /api/arsys/v1/entry/CHG:Infrastructure%20Change?q=(%27Infrastructure%20Change%20ID%27%20IN%20(%22CRQ000000030315%22,%20%22CRQ000000030316%22))

Authorization: [AR-JWT]
Accept: [*/*]
User-Agent: [PostmanRuntime/7.29.0]
Connection: [keep-alive]
Postman-Token: [50954490-5a26-4be0-a526-c61a6e409399]
Host: [localhost:8080]
Accept-Encoding: [gzip, deflate, br]
Content-Type: [application/json]

Matched response definition:
(no response definition configured)

Response:
HTTP/1.1 404
(no headers)

I know the issue is the regex matches because if I change it to .*CRQ000000030315.*
it returns the response, confirming everything else is good. However, I need to match on Infrastructure Change ID and then CRQ000000030315 anywhere in the param.
Cheers for your time.


text:
Q: NPM Pug is not working in my JS application I am trying to use pug in my node application since Jade is now deprecated and my app.js looks like this:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');

var app = express();

// tells which folder the template files will be in
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

app.get('/', function(req, res){
    res.render('index');
});

app.listen(3000);

console.log('Server is running on port 3000');

I created a views folder and inside that folder I have my index.pug file.
When I run the site in the browser, I do not see the hello world.
How can I use pug in my site?

A: your code is correct and perfectly working just give correct path on below line
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

if your view folder is inside public or in any other folder set path of that folder like this:
app.set('views', path.join(__dirname, './public/views'));
app.set('view engine', 'pug');

or remove all dependencies and reinstall them again
Or their might be fault in indentation in index.pug page
if it is not working change the function to this
app.get('/', function(req, res){
    res.send('hello world');
});


text:
Q: Filter out failed syscalls from strace log I can run strace on a command like sleep 1
and see what files it's accessing like this:
strace -e trace=file -o strace.log sleep 1

However, on my machine, many of the calls have a return value of -1
indicating that the file does not exist. For example:
$ grep '= -1 ENOENT' strace.log | head
access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
access("/etc/ld.so.preload", R_OK)      = -1 ENOENT (No such file or directory)
access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
open("/usr/lib/locale/locale-archive", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
open("/usr/lib/locale/en_US.UTF-8/LC_IDENTIFICATION", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
open("/usr/lib/locale/en_US.UTF-8/LC_MEASUREMENT", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
open("/usr/lib/locale/en_US.UTF-8/LC_TELEPHONE", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
open("/usr/lib/locale/en_US.UTF-8/LC_ADDRESS", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
open("/usr/lib/locale/en_US.UTF-8/LC_NAME", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
open("/usr/lib/locale/en_US.UTF-8/LC_PAPER", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)

I'm not really interested in the files that don't exist,
I want to know what files the process actually found and read from.
Aside from grep -v '=-1 ENOENT',
how can I reliably filter out failed calls?
Addendum
I was surprised to learn
that strace has had this feature in the works since 2002
in the form of the -z flag, which is an alias for -e status=successful,
fully functional since version 5.2
(2019-07-12),
also available as --successful-only since version 5.6 (2020-04-07).
Also available since version 5.2 is the complement of -z, the -Z flag,
which is an alias for -e status=failed,
available as --failed-only since version 5.6.
The -z flag was first added in a commit from 2002 and released in version 4.5.18 (2008-08-28),
bit it had never been documented because it was not working properly.
Relevant links:

*

*only seeing successful system calls
Sat Nov 2 23:07:23 UTC 2002

When using strace I  sometimes like to see the system calls
  which work (instead of all the system calls).
I've been porting this patch for years, it seems very useful.
With the -z option, you don't see opens on files which aren't there
  (very useful tracking down what a program actually does, instead of
  trying to do).

https://lists.strace.io/pipermail/strace-devel/2002-November/000232.html

*strace: -z option doesn't work properly
Date: Sun, 12 Jan 2003 09:33:01 UTC
https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=176376

*tracing only failing syscalls
Created: 2004-03-19
https://sourceforge.net/p/strace/feature-requests/3/

*[strace-4.15] Proposal: Output Staging for -z Option (print successful syscalls only) / Patch included
Tue Jan 17 09:35:54 UTC 2017
https://lists.strace.io/pipermail/strace-devel/2017-January/005941.html

*[PATCH v1] Implemented output staging for failed/successful syscalls
Wed Jan 18 16:01:20 UTC 2017
https://lists.strace.io/pipermail/strace-devel/2017-January/005950.html

*Fix -z option
Feb 28, 2018
https://github.com/strace/strace/issues/49

*[PATCH 0/3] Stage output for -z and new -Z options
Mon Apr 1 21:13:02 UTC 2019
https://lists.strace.io/pipermail/strace-devel/2019-April/008706.html

*strace -z flag
Mon Jun 10 05:29:19 UTC 2019
https://lists.strace.io/pipermail/strace-devel/2019-June/008808.html

A: Apart from post-processing the strace output, there isn't anything available to ignore failed system calls in strace. It wouldn't be too hard to add, look at the syscall_exiting_trace function in syscall.c.
If you'd rather pursue the post-processing angle, Ole Tange has already taken care of that for you in a more comprehensive way than you're likely to get here: the tracefile tool will run strace and filter out the information you're after in a nicely readable fashion. See List the files accessed by a program for details. Another answer to that question lists other possible approaches, including LoggedFS which I find very useful.
Another option is to use SystemTap; for example
#!/usr/bin/env stap

global stored_filename, stored_path

probe syscall.open {
  stored_filename = filename
}

probe syscall.open.return {
  if (execname() == "cat" && $return >= 0) {
    printf("opened %s\n", stored_filename)
  }
}

probe syscall.openat {
  stored_filename = filename
  stored_path = dfd_str
}

probe syscall.openat.return {
  if (execname() == "cat" && $return >= 0) {
    printf("opened %s in %s\n", stored_filename, stored_path)
  }
}

will show the name of any file successfully opened by any cat process.

A: Possible solution:
strace -e trace=file sleep 1 2>&1 | grep -v "= -1 ENOENT" > strace.log

strace by default prints to stderr so redirect it to stdout.

A: A slightly more reliable pattern (i.e. slightly less risk of skipping the wrong lines by accident) could be
| grep -v "= -1 ENOENT [(]No such file or directory[)]$"

I.e. copy-paste the end of line, "escaping" the brackets (which might otherwise be treated as special characters), and add the special character $ to the end which "anchors" the pattern to the end of the line.
I can't find any better option in man strace.  Quick and dirty text manipulation hacks are the Unix Way :-P.
It's almost certainly possible to do what you want with a custom gdb script.  However that's more work, and I don't have such a script prepared.
Another question references a tracefile script, which you would run with the -e option.  This is still implemented by parsing the output of strace, and so it does not appear to be entirely reliable either, but I guess it's possible you'd prefer it.  https://gitlab.com/ole.tange/tangetools/blob/master/tracefile/tracefile


text:
Q: Developing Azure .Net 4.0 Applications Presently .Net 4.0 is not supported on Azure.
This thread indicates that you will not be able to use .Net 4.0 with VS 2010 until it is supported in the cloud.
http://social.msdn.microsoft.com
I'd like a way to start developing Azure applications locally utilizing the new features of .Net 4.0.  I am fine with not being able to deploy these applications until Azure officially supports it.
From within the VS IDE; I tried replacing .Net 3.5 application references with newer .Net 4.0 references and Visual Studio crashes.
Does anyone have any suggestions?
Thanks,
Paul

A: An update to this old thread. .Net 4.0 has been supported since Azure SDK 1.2

A: Some features from .NET 4.0 can be added to your application through other means. For example, the recently-released Reactive Extensions for .NET 3.5 SP1 includes a back ported release of Parallel Extensions. And the Managed Extensibility Framework contains the Lazy class and Tuple struct. As long as you set "Copy Local" to true on any libraries that you add, your application should run (and deploy) successfully.
Obviously, these aren't all the features that are new in .NET 4.0, and not all of them will can be ported back to .NET 3.5 like these can.


text:
Q: Why is Ruby failing to convert CP-1252 to UTF-8? I have a CSV files saved from Excel which is CP-1252/Windows-1252. I tried the following, but it still comes out corrupted. Why?
csv_text = File.read(arg[:file], encoding: 'cp1252').encode('utf-8')
# csv_text = File.read(arg[:file], encoding: 'cp1252')
csv = CSV.parse csv_text, :headers => true
  csv.each do |row|
    # create model
    p model

The result
>rake import:csv["../file.csv"] | grep Brien
... name: "Oâ?TBrien ...

However it works in the console
> "O\x92Brien".force_encoding("cp1252").encode("utf-8")
=> "O'Brien"

I can open the CSV file in Notepad++, Encoding > Character Sets > Western European > Windows-1252, see the correct characters, then Encoding > Convert to UTF-8. However, there are many files an I want Ruby to handle this.
Similar: How to change the encoding during CSV parsing in Rails. But this doesn't explain why this is failing.
Ruby 2.4, Reference: https://ruby-doc.org/core-2.4.3/IO.html#method-c-read

A: Wow, it was caused by the shitty grep in DevKit.
>rake import:csv["../file.csv"]
... name: "O'Brien ...

>where grep
C:\DevKit2\bin\grep.exe

I also did not need the .encode('utf-8').
Let that be a lesson kids. Never take anything for granted. Trust no one!


text:
Q: Catching and sending events in python xlib For my window manager project, I'm grabbing all ButtonPress events(so I can focus the window underneath the mouse). If the window is already focused I would like to just pass the event along to the window.
Here's the offending function
def left_button(self, event):
    if event.detail == 1 and Configurator.display.get_input_focus().focus == event.window:
        print "Sending Window The Event"
        event.window.send_event(event)
    else:
        try:
            Utils.focus_window(event.window)
        except:
            return

The code doesn't fail or send any errors it just doesn't act the way I expect, or any different from the original function(everything after the else statement)
Have I simple forgotten something basic or am I going about this all wrong?


text:
Q: AngularJS: How to expose directive's method to nested directives, like ng-click? I've read the most of similar topics, but my question is still unanswered.
I hava  directive:
directive.repeatable = function () { return {
    restrict: 'A',
    scope: {
        data: '=repeatableData',
        add: '@'
    },
    controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {
        $scope.add = function() {
            console.log("ADD");
        }

    }]
}

I need to have an isolated scope and yet need to expose and add method to nested DOM elements:
<div repeatable repeatable-data="data">
    <div ng-repeat="item in data">
      {{ item }}
    </div>
    <button ng-click="add()">Add</button>
</div>

How can I access add() method of parent directive? Tried: $parent.add(), $scope.$parent.add(), add: '&add'. But I guess I just don't get it.
P.S. I cannot really access the data property of the repeatable directive, instead, both repeatable-data and item in data point to the same "model".

A: UPDATE
Check my other answer: Why I can't access the right scope?
If you really want the inner content to be part of the isolated scope you can do it like so:
app.directive('repeatable', function () {
  return {
    restrict: 'A',
    transclude: true,
    scope: {
        data: '=repeatableData',
        add: '@'
    },
    link: function(scope, elm, attr, ctrl, $transclude) {

      $transclude(scope, function(clone){
        elm.append(clone);
      });

      scope.add = function() {
          console.log("ADD");
      }

    }

  }
});


text:
Q: See more/Add more rows in table angular Ive googled so much, but I cant figure out what Im not getting. I search for the example in the image below, but I can only find how to extend one particular row in the table.
I want to add more individual rows to the table when the "see more" btn is clicked from the API. Am I searching for the wrong thing, since I cant be able to find anything, or any packages that supports this? If so, what is it called that I cant be able to understand? Im using Angular as framework
img of the table with the see more btn

A: Since I don't know what is your code I imagine you has a table with data and some like

  {{element.prop1}}
  {{element.prop2}}

Just can use slice pipe and a variable "page"
page:number=0 //<--declare variable in your .ts

  {{element.prop1}}
  {{element.prop2}}

  <td colspan="2" *ngIf="page*6<elements.length>
    <button (click)="page=page+1">more</button>

If you has a table with values (really you should use tables only to show tabulated data) you can has a variable "more"
    more=false; //<--declare variable in your .ts

      {{element.prop1}}

      {{element.prop2}}

    ....

        <button (click)="more=true">more</button>

    <ng-container *ngIf="more">

        {{element.prop3}}

        <button (click)="more=false">less</button>

   </ng-container>


text:
Q: Image not clickable on popup in selenium webdriver I have one popup which looks like as follow,
__________________
| Label 1      +<--this is  a plus img
|                |
| Label 2      + |
|________________|

I want to click that plus image, but when I am trying to do this getting one exception,
org.openqa.selenium.WebDriverException: unknown error: Element
...
 is not clickable at point (1012, 133). Other element would receive the click:
...

  (Session info: chrome=58.0.3029.96)
  (Driver info: chromedriver=2.27.440175 (9bc1d90b8bfa4dd181fbbf769a5eb5e575574320),platform=Linux 4.4.0-75-generic x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 72 milliseconds
Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
System info: host: 'PC-3', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '4.4.0-75-generic', java.version: '1.8.0_121'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.27.440175 (9bc1d90b8bfa4dd181fbbf769a5eb5e575574320), userDataDir=/tmp/.org.chromium.Chromium.5Z2sYt}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=58.0.3029.96, platform=LINUX, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=}]
Session ID: 2da36c1282dd134e5dec3c9024e86c48
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:216)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:168)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:638)
    at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:274)
    at org.openqa.selenium.remote.RemoteWebElement.click(RemoteWebElement.java:84)
    at com.trupublic.client.util.Thing.formShortcuts(Thing.java:240)
    at com.trupublic.client.restauranttapp.thing.MenuItemThingTest.testMenuItemThing(MenuItemThingTest.java:124)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

I have implemented my code as follow,
    Webelement popup = driver.findElement(By.className("popupMainVPanel_CCPopupView"))

//This popup contains a list of web elements which I am taking as follow,

    List<Webelement> popupWebElementList = popup.findElements(By.className("actionLabelHPanel"));

            String parentWindowHandler = driver.getWindowHandle(); // Store your parent window
            Thread.sleep(3000);
            switchToPopup();
            Thread.sleep(3000);

            for (WebElement element : popupWebElementList) {

                WebElement label1 = element.findElement(By.className("popupLabel"));
                Thread.sleep(3000);

                WebElement label1Img = element.findElement(By.className("popupImg"));
                Thread.sleep(3000);

                if (label1.getText().equals("Label1")
                        && label1Img.getAttribute("title").equals("Create Label1")) {
                    Thread.sleep(3000);
                    label1Img.click();// at this line i am getting exception
                }
            }

public void switchToPopUp() {
        try {

            String subWindowHandler = null;

            Set<String> handles = driver.getWindowHandles(); // get all window handles
            Iterator<String> iterator = handles.iterator();
            while (iterator.hasNext()) {
                subWindowHandler = iterator.next();
            }
            driver.switchTo().window(subWindowHandler); // switch to popup window perform operations on popup
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Exception Occured in createActionForThing() ", e);
        }
    }

I am able to get all webelements even though getting this exception.

A: As element is not receiving the click so you need to first move to the element using actions class, and then click the element.
   Actions act = new Actions(driver);
           act.moveToElement(label1Img).build().perform();
   label1Img.click();


text:
Q: Is it possible to define custom color palettes for re-use in Cytoscape There are many great color palettes built-in but I would like to be able to define my own palettes to keep a consistent look across various different sessions and graphs over time.
Re-defining the RGB color codes gets a bit tedious over time. I would think that it would be possible to define and save a color palette rather than styles? (I commonly use different styles for different visualizations but would ideally like to be able to use the same colors)

A: Great idea!! At this point, there is no capability to create custom palettes.  It would be relatively straightforward to write an app to do so, however, since the palette mechanism is extensible.  If you know somebody with Java expertise, I would be happy to get them started.  Probably no more than a 1-2 week effort, depending on how fancy you wanted to make the UI.  You might also submit this as a feature request and we'll put it on next year's Google Summer of Code list...
-- scooter


text:
Q: Supermartingale with vanishing drift Is a continuous supermartingale with vanishing drift already a martingale? In my concrete problem, I have a continuous nonnegative local martingale $ (X_t) $ on $ \left[0, T\right] $ which is bounded from below by 0 (and hence a supermartingale) and which in addition satisfies
$ sup_{t \in \left[0,T\right]} \mathbb{E} \left[ X_t^p \right] < + \infty$, for some $p > 1$. When I apply Ito, I find
$dX_t = 0 dt + H dW_t$,
where W is a Brownian motion and H is some predictable process. Now, I am wondering if
$(X_t)$ is in fact a true martingale (the reason is that I would like to apply the Doob inequality for martingales in $L^p$).
Thanks a lot for your help!
Simon

A: Take $dX_t= f(t)dt+ dW_t$ such that :
-$F(t)=\int_0^t f(s)ds$ is strictly decreasing (determisitic)
-$f(t)\to 0$ as $t\to \infty$
Then $X_t= F(t)+ W_t$ and as the sum of a martingale term (the Brownian motion) plus a deterministic supermartingale $F(t)$, $X$ it is a supermaringale with a drift term that goes to 0, and $X$ is not be a martingale (unless F is null).
For example $f(t)=-\frac{1}{(1+t)^2}$ gives $F(t)=\frac{1}{1+t}-1$ seems to work fine.
Best regards


text:
Q: How can I create a group with my project on GitHub and the FrontEnd and BackEnd associated to be repos of this group(project)? I'm building a web-app and I want to make a group with the name of the app to contain the two major part of a web site, the Frontend and Backend. How can I do this? Or maybe some suggestions !
I have read other question on this topic but neither explained in detail. Maybe we can find a more complete answer to help people that aren't familiar with GitHub.

A: Its not that much of a problem, you can do it in two ways. Either use:
1.GitHub (User Interface).
or
2.git bash (Command Line) (Preferred)
Firstly create a new repository and name it without spaces (use _ for a better naming)
Then You will have to add folders and files to it using GitHub.
link
Or you can make this empty repos and dont add any readme, gitignore or license, just create and follow these instructions:
GIT CLI TO ADD PROJECT FOLDERS
then, invite your group memebers as contributors to the project by clicking on settings in your repo, then click manage access. and invite contributors. this will send them an email to accept the invitation.


text:
Q: Button Menu Likes Evernote There are tutorial to create menu like this? (bottom right)

I need tutorial to create it.
Thank you, Regards!

A: This is not the appropriate question to be asked you should search by yourself on google(mainly github).
But you can use this library for this task "https://github.com/futuresimple/android-floating-action-button"


text:
Q: ADF:Read ADF logger log messages in web application I am developing an embedded tool in my ADF fusion web application which will read and display the log messages of weblogic server.I discovered one file named DefaultDomain.log in AppData\Roaming\JDeveloper\system11.1.1.7.40.67.80\DefaultDomain\servers\DefaultServer\logs folder which contains all the log messages.
Now I want to write some logic to read the contents of this file dynamically and display it through the tool(ADF Faces).Is it possible to read this log messages through my java application?
If yes how to get the log file name from the weblogic server.I think the name of the log file is configurable in the server.This application is to be installed in various environments like clustered environment and also in activation /passivisation on


text:
Q: How to hash the return string from WCF service to client I have a service that gets a card account number (16 digits). A website (MVC) will call that service then will return a card including the account number.
Since account number is a confidential information, I must only return the last four digits of card account number to the website but inside the service, the full account number must retain.
How can I do that?

A: Can you not do something like this in your service:
Have a Dictionary to store the hash of the card and the card number:
var cards = new Dictionary<int, string>();
var cardNumber = "1234123412341234"

cards.Add(cardNumber.GetHashCode(), cardNumber);

This is a simple solution, but there are so many unknowns: is your service stateless as it should, if so you need to persist the dictionary, but maybe because the right solution to this problem, would be to use some kind of caching systems, such as memcache.


text:
Q: TComboBox with Image in Firemonkey I have added a TImage to the style of TListBoxItem.
If I add to a TListBox, it works. If I add to a TComboBox, it doesn't works. I can't even change the height if the item in a TComboBox.
Here my sample code:
procedure TMainForm.FormCreate(Sender: TObject);
const
  BitmapFile : String = 'F:\testimage.png';
var
  ItemText : TText;
  ItemImage   : TImage;
  ListBoxItem : TListBoxItem;
  button : TButton;
begin

  ListBoxItem := TListBoxItem.Create(nil);
  ListBoxItem.Parent := CBoxHeadMenuLanguage;

  ListBoxItem.StyleLookup := 'ListBoxItemIconStyle';
  ListBoxItem.Height := 50; //just for test

  ItemText := ListBoxItem.FindStyleResource('text') as TText;
  if Assigned(ItemText) then ItemText.Text := 'Hello World!';

  ItemImage := ListBoxItem.FindStyleResource('image') as TImage;
  if Assigned(ItemImage) then If FileExists(BitmapFile) Then ItemImage.Bitmap.LoadFromFile(BitmapFile);
end;

A: You really shouldn't be doing styling stuff in FormCreate since styles are applied on an as-needed basis and can be removed and reapplied at any time.
Instead you'll need to use either OnApplyStyleLookup event or the ApplyStyle method. I recommend subclassing TListBox and using the latter and add a property to store the bitmap.
An outline class declaration would be:
type TBitmapLBItem = class(TListBoxItem)
  private
    FBitmap: TBitmap;
  protected
    procedure ApplyStyle;override;
  public
    property Bitmap: TBitmap read FBitmap write SetBitmap;
  end;

Use FindStyleResource etc both in ApplyStyle and SetBitmap (or create a shared method to do it).
And in FormCreate create items of your new class and set the Bitmap properties as appropriate.
As for the height problem, try setting the ItemHeight property of the combo box. If you want a variety of heights within the list you're probably out of luck.


text:
Q: For Google Chart, how to I determine the interval of a continuous h-axis with datetime format? Currently I am using Google Chart (Column Chart) to show the target quantity every hour for latest 48 hours. My code is like below:
var oChartOptions = {
    height:250,
    hAxis: {
      viewWindowMode:'explicit',
      viewWindow: {
        max: new Date()
        },
      format: "MM/dd h':00'",
      textStyle:{fontSize: 10},
      titleTextStyle: {
        color: 'red',"font-weight":"bold"
      },
      maxTextLines: 12
    }
  };

var nChart = new google.visualization.ColumnChart(nTarget);
var oChartData = new google.visualization.DataTable();
oChartData.addColumn('datetime','Time');
oChartData.addColumn('number','Quantity');
oChartData.addRows(aData);
nChart.draw(oChartData, oChartOptions);

Currently it works great, but for h-axis, it shows the label of time every 6 hours, and I want to shorten this interval from 6 to 2. After I tried a lot with the document, I still found no solution.

A: You can specify the tick interval with the last parameter (optional) of the chxr tag.
Here is an example :
chxr: 0,0,15,1

It will define a [0,15] interval on the first axis with a tick every one value.


text:
Q: rails devise after sign up not allowing access sign_in and sign_up page I am using rails4 and latest devise.
It seems after I signed up an user from devise, I could not access
/users/sign_in and
/users/sign_up

pages (all pages being redirected to root )
I have to clean up browser cookies to access these two pagae. Is there some setting I can turn this thing off. I was trying to testing I need to access these pages very often.

A: Once current_user is set via Devise, the RegistrationsController actions of sign_in and sign_up are no longer available – those actions can only be accessed by non-logged in users.
In both the default RegistrationsController and SessionsController, you'll see the following directive:
prepend_before_filter :require_no_authentication, :only => [ :new, :create ]

Basically, this prevents access to the new and create actions of both controllers by users who are already logged in. This makes sense: if a user is already logged in, why would he/she need to sign in or sign up?
If you'd like to override this default behavior, you can try overriding these controllers with the following:
`prepend_before_filter :require_no_authentication`, :only => :none

This declares that no actions should require_no_authentication as a precursor to access to the action in  question.


text:
Q: How to programmatically set a global (module) variable? I would like to define globals in a "programmatic" way.  Something similar to what I want to do would be:
definitions = {'a': 1, 'b': 2, 'c': 123.4}
for definition in definitions.items():
    exec("%s = %r" % definition)  # a = 1, etc.

Specifically, I want to create a module fundamentalconstants that contains variables that can be accessed as fundamentalconstants.electron_mass, etc., where all values are obtained through parsing a file (hence the need to do the assignments in a "programmatic" way).
Now, the exec solution above would work.  But I am a little bit uneasy with it, because I'm afraid that exec is not the cleanest way to achieve the goal of setting module globals.

A: Here is a better way to do it:
import sys
definitions = {'a': 1, 'b': 2, 'c': 123.4}
module = sys.modules[__name__]
for name, value in definitions.iteritems():
    setattr(module, name, value)

A: You can set globals in the dictionary returned by globals():
definitions = {'a': 1, 'b': 2, 'c': 123.4}
for name, value in definitions.items():
    globals()[name] = value

A: You're right, exec is usually a bad idea and it certainly isn't needed in this case.
Ned's answer is fine. Another possible way to do it if you're a module is to import yourself:
fundamentalconstants.py:
import fundamentalconstants

fundamentalconstants.life_meaning= 42

for line in open('constants.dat'):
    name, _, value= line.partition(':')
    setattr(fundamentalconstants, name, value)


text:
Q: python - crontab to run a script I'm fairly new to python and I'm trying to create a cronjob through a python script but I keep getting an error.  Any help would be greatly appreciated it to show me what I'm doing wrong?
thanks
python script
from crontab import CronTab

cron = CronTab(user=True)

job = cron.new(command='python /Users/<useraccount>/Desktop/my_script.py')
job.minute.on(2)
job.hour.on(12)

cron.write()

Errors:
Traceback (most recent call last):
  File "/Users/<useraccount>/Desktop/01-python-crontab.py", line 3, in <module>
    cron = CronTab(user=True)
TypeError: __init__() got an unexpected keyword argument 'user'

A: Here was the issues:
Error showed up:  TypeError: init() takes exactly 2 argument
documentaton: https://pypi.python.org/pypi/python-crontab helped to resolve the issue.
Reason:
1 - crontab was installed not python-crontab
Here's the completed code:
def main():
    from crontab import CronTab

    cron = CronTab(user=True)

    job = cron.new(command='python /opt/my_script.py')
    job.minute.on(2)
    job.hour.on(12)

    cron.write()

if __name__ == "__main__":
  main()

A: You may be using an old version of crontab (See - Documentation for 1.4.1 here) . You can either upgrade to latest version of python-crontab using -
pip install python-crontab --upgrade

Or download the 1.9.3 version from here and install it.
If you want to use the old version, you can pass in the username as the argument, Example -
cron = CronTab('<username>')


text:
Q: JqGrid id and rownumbers conflict I used Guriddo jqGrid JS - v5.0.0 - 2015-09-14
This is a example trouble
When I click id = 16 highlights rownum = 16 but id = 15 and etc...
Code:
    $("#jqGridEdit").jqGrid({
      url: '/brand/brandFormaQuery.php',
      cellurl:'/editData.php',
      mtype: 'POST',
      datatype: 'json',
      loadtext: "",
      page: 1,
      colModel: [
                    { label: 'id', name: 'id', key: true,hidden: false},
                    { label: 'Name', name: 'brandName',editable:true,hidden: true
                  }
      ],
    cellEdit: true,
    gridview: true,
    deepempty: true,
    gridview: true,
    headertitles: true,
    //autowidth: true,
    //shrinkToFit: false,
    viewsortcols : [true,'horizontal',true],
    width: 1270,
    height: 750,
    rowNum: 200,
    sortable: true,
    rownumbers: true,
    viewrecords: true,
    loadonce: true,
    caption: 'test',
    ignoreCase: true
    });
$('#jqGridEdit').jqGrid('filterToolbar',{searchOnEnter: true, defaultSearch: 'cn'});
   });

A: To analyse and to reproduce the problem one required to have the JSON data. It's important that it should be no id duplicates in the data returned from the server.
I recommend you additionally to try to use free jqGrid which is another fork of jqGrid. You can just use URLs described in the wiki article. Starting with publishing 4.7.1 version directly after 4.7, which changed license agreement, I started developing free jqGrid. Both forks will be developed independent. The version numbers have no relation with which version if newer. I prefer to use 4.*.* version numbers because I try to hold free jqGrid compatible with jqGrid 4.7/4.6 and some other 4.x versions.
If you would have the same problem with free jqGrid then I would suppose that you have some problem (like id duplicates) in the input data. You should use tools like Fiddler or Developer Tools of Internet Explorer or Google Chrome (press F12 to start the tools and choose Network tab) to make HTTP trace. The JSON data from the server response should be appended to the text of the question.
If you would have no problem with free jqGrid than some bug could exist in Guriddo jqGrid JS v5.0.0. You can report the problem to Guriddo. You should include JSON data which can be used to reproduce the problem in the bug report.


text:
Q: JPA EntityManagerFactory with Envers is not creating the context Please help me in setting up evnvers for my project. Below it my "entityManagerFactory" bean with Envers
Spring-Context.xml
<bean id="entityManagerFactory"
      class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
      depends-on="flyway">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" value="com.example.cns.*" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
    </property>
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.hbm2ddl.auto">validate</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>
            <!-- <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory</prop> -->
            <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
            <prop key="hibernate.cache.use_query_cache">true</prop>
            <prop key="hibernate.cache.use_second_level_cache">true</prop>

            <!-- Listeners for Hibernate Envers -->
            <prop key="hibernate.ejb.event.post-insert">
                org.hibernate.ejb.event.EJB3PostInsertEventListener,
                org.hibernate.envers.event.AuditEventListener
            </prop>
            <prop key="hibernate.ejb.event.post-update">
                org.hibernate.ejb.event.EJB3PostUpdateEventListener,
                org.hibernate.envers.event.AuditEventListener
            </prop>
            <prop key="hibernate.ejb.event.post-delete">
                org.hibernate.ejb.event.EJB3PostDeleteEventListener,
                org.hibernate.envers.event.AuditEventListener
            </prop>
            <prop key="hibernate.ejb.event.pre-collection-update">
                org.hibernate.envers.event.AuditEventListener
            </prop>
            <prop key="hibernate.ejb.event.pre-collection-remove">
                org.hibernate.envers.event.AuditEventListener
            </prop>
            <prop key="hibernate.ejb.event.post-collection-recreate">
                org.hibernate.envers.event.AuditEventListener
            </prop>

            <!-- Properties for Hibernate Envers -->
            <prop key="org.hibernate.envers.audit_table_suffix">_H</prop>
            <prop key="org.hibernate.envers.revision_field_name">AUDIT_REVISION</prop>
            <prop key="org.hibernate.envers.revision_type_field_name">ACTION_TYPE</prop>
            <prop key="org.hibernate.envers.audit_strategy">org.hibernate.envers.strategy.ValidityAuditStrategy</prop>
            <prop key="org.hibernate.envers.audit_strategy_validity_end_rev_field_name">AUDIT_REVISION_END</prop>
            <prop key="org.hibernate.envers.audit_strategy_validity_store_revend_timestamp">True</prop>
            <prop key="org.hibernate.envers.audit_strategy_validity_revend_timestamp_field_name">AUDIT_REVISION_END_TS</prop>

        </props>
    </property>
</bean>

Pom.xml
<spring.version>3.1.2.RELEASE</spring.version>

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-envers</artifactId>
    <version>4.2.1</version>
</dependency>

With above setting I am getting
SEVERE: Exception occurred when intialization
java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered?

Any help in resolving this is appreciated. Thanks
Mohan

A: You dont need the envers listeners to be defined for version 4.x
See http://docs.jboss.org/hibernate/core/4.0/devguide/en-US/html/ch15.html section 15.1
That might simplify your issue.

A: According the documentation Joss Docs

Important Unlike in previous versions, you no longer need to specify
  listeners in the Hibernate configuration file. Just putting the Envers
  jar on the classpath is enough - listeners will be registered
  automatically.


text:
Q: Qt - capturing internal qWarning or "failing makeCurrent()" error I'm running a QWebEngineView in Qt 5.12 on a linux machine with Wayland, where a bug in Qt (there are a few issues reported about this) causes the app to freeze rendering if the screen is disconnected and reconnected, or if it goes into sleep mode.
The app still runs fine, but no further rendering is done ant it's stuck at last frame. The only errors that are visible when running the app are:
[14:52:07.809] connector 87 disconnected
QOpenGLFunctions created with non-current context
QPaintDevice::metrics: Device has no metric information
QQuickWidget: Cannot render due to failing makeCurrent()
QQuickWidget: Cannot render due to failing makeCurrent()

This is the place in Qt that throws this warning:
// qtdeclarative/src/quickwidgets/qquickwidget.cpp
void QQuickWidgetPrivate::render(bool needsSync)
{
    if (!useSoftwareRenderer) {
#if QT_CONFIG(opengl)
        // createFramebufferObject() bails out when the size is empty. In this case
        // we cannot render either.
        if (!fbo)
            return;
        Q_ASSERT(context);
        if (!context->makeCurrent(offscreenSurface)) {
            qWarning("QQuickWidget: Cannot render due to failing makeCurrent()");
            return;
        }

I unfortunately cannot alter the Qt version on this device, so I'd like to know if there is any reliable way of detecting this situation from inside the app to do some proper crash/restart?
I couldn't find any way to capture qWarning messages from inside of Qt or anything like that, and the code that causes this doesn't look as it could emit any interesting signal.
As last resort, I could parse the output of my app and look for "Cannot render due to failing makeCurrent()" but I really don't like that I cannot detect it from my own app that rendering has frozen.
I could add QT_FATAL_WARNINGS environment variable, which causes the app to automatically crash upon any warning, but I'm kinda scared that there may be some non-fatal warnings that would cause unintentional crashes.

A: You can use qInstallMessageHandler to override the default logging mechanism. And in there, you can check the qWarning messages for the specific string you're looking for.
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QByteArray localMsg = msg.toLocal8Bit();
    const char *file = context.file ? context.file : "";
    const char *function = context.function ? context.function : "";
    switch (type) {
    case QtWarningMsg:
        fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);

        if (localMsg == theBadRenderError) {
            // Do something here
        }
        break;
    ...
    }
}

int main(int argc, char **argv)
{
    qInstallMessageHandler(myMessageOutput);
    QApplication app(argc, argv);
    ...
    return app.exec();
}


text:
Q: vnc doesn't work (connection successful, but I can't see any graphics) I'm trying to use VNC on a remote server of mine. My local machine and the remote machine are both running Ubuntu 18.04. There are no errors produced by any of the installation commands, but I just can't get anything graphical to appear.
Here are the steps I followed. On my remote machine inside a terminal after connecting with ssh:
sudo apt install -y xvfb
sudo apt install -y x11vnc
sudo touch /var/log/x11vnc.log
sudo chmod a+rw /var/log/x11vnc.log
/usr/bin/x11vnc -ncache 10 -ncache_cr -viewpasswd remote_view_only_pass -passwd some_pass123  -display :0 -forever -shared -logappend /var/log/x11vnc.log -bg -noipv6

I think all of these are working, however, I am not able to connect to this server and see graphical output on my local machine.The VNC client I am using is vinagre. I think most of the other ones are paid or only work on Windows/Mac (do I even need a 3rd party app, though?).
I open vinagre up, click connect, select ssh as the protocol, type in my ip address into the host space, enter my username, and hit connect. In the window, it looks like a regular terminal session, it prompts me for my password, I enter it, and this looks exactly like it usually does when I ssh in without graphics. I also try to enter the following into the terminal-looking vinagre window:
sudo apt install -y x11-apps
DISPLAY=:0 xeyes &

but nothing graphical pops up.

A: The tutorial I was following didn't mention that I had to set up a tunnel on my local machine:
ssh -L 5900:127.0.0.1:5900 -N root@1.2.3.4

which assumes my remote machine's ip is 1.2.3.4 and the username is root. Leave that running and then in another terminal on your local machine type
vncviewer localhost:5900
and use one of those two passwords in that command above, either remote_view_only_pass or some_pass123.


text:
Q: Combining UDP packets? Is there any benifit to combining several UDP packets into one as opposed to sending them all one right after the other? I know that if the large packet gets courrupted then i loose all of them, but is there possibly some upside to sending them all in one? such as a lower chance of the large one being lost?

A: That would be at the discretion of the sending application.
Note that your large packet is limited by the MTU of the underlying network. e.g. the theoretical size of a UDP packet is 64k, but an ethernet frame is only ~1500 bytes. So I suspect this is not a practical feature.

A: Generally networking channels will be limited on the rate of packets that can be sent per second.  Thus if you want to send millions of messages per second you generally want to combine into a smaller number of packets to run without major packet loss.
As an over generalisation, Windows doesn't like > 10,000 packets per second for UDP, but you can saturate a gigabit network with large MTU packets.

A:
Is there any benifit to combining several UDP packets into one as opposed to sending them all one right after the other?

One can save on UDP header which is 8 bytes per datagram hence reducing the amount of data sent over the wire. Just make sure you don't send more then MTU sans IP and UDP header sizes to avoid fragmenting on IP layer.
Also, the standard POSIX socket API requires one send/sendto/sendmsg() system call to send or receive one datagram, so by sending fewer datagrams one does fewer system call reducing the overall latency (an order of a few microseconds per call). Linux kernels starting from 3.0 provide sendmsg() and recvmmsg() functions to send and receive multiple datagrams in one system call.

I know that if the large packet gets courrupted then i loose all of the

True. However, if the protocol can't cope with UDP datagram loss at all it may not matter that much - as soon as one datagram is lost it's broken anyway.

A: It is important for situations where packet size is small (less than 100 byte). The IP/UDP header is at least 28 bytes.
Imagine you have streaming connection to a server, each packet contains 50 bytes and your software sends packets with rate 1000 packet per second.
The actual payload is 1000 * 50 bytes = 50000 bytes. Headers overhead 1000 * 28 = 28000 bytes Total bytes : 50000 + 28000 = 87000 ==> 87 KBps
Imagine you can combine each 3 UDP packets into one packet:
Headers overhead 1000 / 3 * 28 = 9333 Total bytes : 50000 + 9333 ===> 60 KBps
This -in some applications- saves good portion of the bandwidth.