text:
Q: Websocket client disconnects automatically after some time I am using websockets in my laravel project. I have opened a port by PHP that is 8000 and it is working fine. I am connecting to the port by following in in view file:
function WebSocketInit()
         {
            if ("WebSocket" in window)
            {
               // Let us open a web socket
               ws = new ReconnectingWebSocket("ws://xxx.xxx.xxx.xxx:8000");
            }
            else
            {
               // The browser doesn't support WebSocket
               alert("WebSocket NOT supported by your Browser!");
            }
         }
        WebSocketInit();
        ws.onopen = function(){
            console.log( "Connected." );
        };
        ws.onclose = function(){
            ws.refresh();
            console.log( "Disconnected." );
        };

It connects well first time but if I refresh my page then it disconnects and do not re-connect most of the time. Sometimes, it connects but takes few seconds. Any help will be appreciated.
Thanks in advance!


text:
Q: Customizing the blank screen before splash screen and videos not playing in full screen on phonegap I am building an app on phonegap that displays several links. A blank screen with the icon and title on the left top appears before the splash screen appears when I open the app. However I found online that it is normal in android but we can customize it. Is there any way I can customize it in phonegap and if so how?
When a user presses a link, it opens the link in an inappbrowser. Everything works accordingly on ios. However when it comes to android, if there are any videos in those links, they do not play on fullscreen but they do on ios. When I press the enlarge button, nothing happens. The video just keeps playing without enlarging on the android.
Below is my config.xml for android if it helps.
<preference name="orientation" value="portrait" />
    <preference name="fullscreen" value="true" />
    <preference name="target-device" value="universal" />

    <preference name="prerendered-icon" value="true" />
    <preference name="stay-in-webview" value="false" />

    <preference name="detect-data-types" value="true" />
    <preference name="exit-on-suspend" value="false" />
    <preference name="show-splash-screen-spinner" value="false" />
    <preference name="auto-hide-splash-screen" value="true" />
    <preference name="EnableViewportScale" value="true" />
    <preference name="MediaPlaybackRequiresUserAction" value="true" />
    <preference name="AllowInlineMediaPlayback" value="true" />
    <preference name="BackupWebStorage" value="local" />
    <preference name="TopActivityIndicator" value="gray" />
    <preference name="HideKeyboardFormAccessoryBar" value="false" />
    <preference name="android-minSdkVersion" value="15" />
    <preference name="android-targetSdkVersion" value="22" />

    <preference name="android-installLocation" value="auto" />
    <preference name="SplashScreenDelay" value="5000" />
    <preference name="ErrorUrl" value=""/>
    <preference name="BackgroundColor" value="0x000000"/>
    <preference name="KeepRunning" value="true"/>
    <preference name="DisallowOverscroll" value="true"/>
    <preference name="LoadingDialog" value=","/>
    <preference name="LoadUrlTimeoutValue" value="20000" />
    <preference name="disable-cursor" value="false" />

    <gap:platform name="android" />

    <feature name="http://api.phonegap.com/1.0/battery"/>
    <feature name="http://api.phonegap.com/1.0/geolocation"/>
    <feature name="http://api.phonegap.com/1.0/network"/>
    <feature name="http://api.phonegap.com/1.0/notification"/>
    <feature name="http://api.phonegap.com/1.0/geolocation"/>
    <feature name="http://api.phonegap.com/1.0/network"/>
    <gap:plugin name="org.apache.cordova.battery-status"  />
    <gap:plugin name="org.apache.cordova.device-motion"  />
    <gap:plugin name="org.apache.cordova.dialogs"  />
    <gap:plugin name="org.apache.cordova.geolocation"  />

    <gap:plugin name="org.apache.cordova.dialogs" />
    <gap:plugin name="org.apache.cordova.inappbrowser" />
    <gap:plugin name="org.apache.cordova.media"  />
    <gap:plugin name="org.apache.cordova.network-information"  />
    <gap:plugin name="org.apache.cordova.splashscreen"  />
    <gap:plugin name="org.apache.cordova.vibration"  />

    <icon src="res/icon/android/icon-36-ldpi.png" gap:platform="android" gap:density="ldpi" />
    <icon src="res/icon/android/icon-48-mdpi.png" gap:platform="android" gap:density="mdpi" />
    <icon src="res/icon/android/icon-72-hdpi.png" gap:platform="android" gap:density="hdpi" />
    <icon src="res/icon/android/icon-96-xhdpi.png" gap:platform="android" gap:density="xhdpi" />
    <icon src="res/icon/android/icon-xxhdpi.png" gap:platform="android" gap:density="xxhdpi" />
    <icon src="res/icon/android/icon-xxxhdpi.png" gap:platform="android" gap:density="xxxhdpi" />

    <icon src="icon.png" />

    <gap:splash src="res/screen/android/screen-ldpi-potrait.png" gap:platform="android" gap:density="ldpi" />
    <gap:splash src="res/screen/android/screen-mdpi-potrait.png" gap:platform="android" gap:density="mdpi" />
    <gap:splash src="res/screen/android/screen-hdpi-potrait.png" gap:platform="android" gap:density="hdpi" />
    <gap:splash src="res/screen/android/screen-xhdpi-potrait.png" gap:platform="android" gap:density="xhdpi" />
    <gap:splash src="res/screen/windows-phone/screen-portrait.png" gap:platform="winphone" />
    <access origin="*"/>

I have been trying to see where the problem is for the last two weeks but in vain. Any help is truly appreciated.

A: You could try this for the "blank screen that appears before the splash"
In the "platforms\android" folder under your project, open the AndroidManifest.xml and search for android:theme inside the <activity> tag that contains android:name="MainActivity" and change the default value (that is android:theme="@android:style/Theme.DeviceDefault.NoActionBar") to android:theme="@android:style/Theme.Translucent". Save the file and build your project again, the grey screen should desapear.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change WooCommerce checkout country field default option displayed label How would edit the default value on and existing array - have managed to edit the label using this but cannot get the options property to work using this:
add_filter( 'woocommerce_checkout_fields', 'custom_override_checkout_fields' );
function custom_override_checkout_fields( $fields ) {
    $fields['billing']['billing_country']['options value="default"'] = 'My new select prompt';
    $fields['billing']['billing_country']['label'] = 'Are you purchasing as a Company Y/N or from the UK?';

    return $fields;
}

A: To change WooCommerce country field default option displayed value in checkout page, you can use the following composite hook this way:
add_filter( 'woocommerce_form_field_country', 'filter_form_field_country', 10, 4 );
function filter_form_field_country( $field, $key, $args, $value ) {
    // Only in checkout page for "billing" city field
    if ( is_checkout() && 'billing_country' === $key ) {
        $search  = esc_html__( 'Select a country / region…', 'woocommerce' ); // String to search
        $replace = esc_html__( 'My new select prompt', 'woocommerce' ); // Replacement string
        $field   = str_replace( $search, $replace, $field );
    }
    return $field;
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.
Then you can keep on your question code the following:
add_filter( 'woocommerce_checkout_fields', 'custom_override_checkout_fields' );
function custom_override_checkout_fields( $fields ) {
    $fields['billing']['billing_country']['label'] = __('Are you purchasing as a Company Y/N or from the UK?', 'woocommerce');

    return $fields;
}


text:
Q: How can I make a Player only look in one direction? I am making a map for Minecraft and I want to make the Player only be able to face a certain wall.
Is there any way that I could do that?

A: You can achieve this with the  /tp repeating. For example:
/tp @p ~ ~ ~ 90 0

The ~ ~ ~ means that their x, y and z won't be changed, but their yaw (left/right) will be set to 90 and their pitch (up/down) to 0.
You will need to put this command in a repeating command block or some other form of clock.


text:
Q: Rails - how to render two identical forms but with different element IDs? I would like to have two almost identical forms on a single page and use a partial for generating both with a render call.
<%= render 'form_template', data: @categories_one %>
<%= render 'form_template', data: @categories_two %>

The problem lies in their only difference - both forms use f.collection_select to provide dropboxes with categories for the user.
<%= f.collection_select :category_id, data, :id, :name %>

which creates two different forms with identical IDs for the SELECT tag, breaking my forms, and I would like to avoid that. But how can I do that?

A: You can pass :namespace parameter to the form_for

A namespace for your form to ensure uniqueness of id attributes on form elements. The namespace attribute will be prefixed with underscore on the generated HTML id.

A: If you look at the documentation for collection_select, you'll see that its last argument is for HTML options. So you can do this:
<%= f.collection_select :category_id, data, :id, :name, {}, {:id => "different_css_id"} %>

Since you said this is called within a partial though, from your identical render calls, you can pass along a variable to toggle this behaviour.
# Render calls
<%= render 'form_template', data: @categories_one %>
<%= render 'form_template', data: @categories_one, :locals => {:use_other_id => true} %>

And then use that flag in your partial.


text:
Q: Only list name of EC2 using Powershell I set an a variable $ec2-instance = GetEC2Instance and this returns something like...
GroupNames    : {}
Groups        : {}
Instances     : {somekey}
OwnerId       : 11111111
RequesterId   :
ReservationId : r-111111111
What I'm trying to do is list just the name of the EC2 instance. I know, "name" is a tag but not sure how to capture in PowerShell.

A: Get-EC2Instance returns a list of Instances, you can iterate over that list and grab the value of the Name tag like this:
ForEach($i in (Get-EC2Instance).Instances) {
   ($i.Tags | ? { $_.Key -eq "Name"} | select -expand Value)
}


text:
Q: spivak calculus on manifold thm 1.11
I think the proof of thm 1.11 of spivak has little problem.
Please focus on the yellow highlight part. Actually M($a$,f,$\delta$) is only defined for  $a\in A$.
but in this proof, we don't have any guarantee  $y \in A$, actually, if  $y \notin A$ imply $y \in R^n-B$. so thm can be proven perfectly.
Please talk to me if there is any problem in my opinion.

A: $\{x: o_f(x) <\epsilon\}$ is an open subset of $A$ in the subspace topology (by the argument given in the book, restricting $y$ to points of $A$). Hence $\{x: o_f(x) \geq \epsilon\}$ is closed in $A$ which also implies it is closed in $\mathbb R$ because $A$ is closed in $\mathbb R$.


text:
Q: How to get headers for a POST request from aws lambda event object (in python) where the incoming request has empty body but info in headers This is with respect to google drive API integration where I have a Lambda python event code that gets triggered when I do . This is the push notification implentation of Google drive API.
In order to allow google drive push notification to call us, I have created the associated api gateway endpoint as webhook using their API. Now this lambda do gets triggered when I edit the file so this means that webhook is successful and google calls back the hook.
Google Drive sends HTTP POST messages to the webhook url once you do any change.
The following HTTP headers are returned with empty body to the lambda function:
{
        "Content-Type": "application/json; utf-8",
        "Content-Length": "5000",
        "X-Goog_Channel-ID": "05a349fd-c363-4d8c-9409-8b6f310b7379",
        "X-Goog-Channel-Token": "to66728b-21c7-4605-8445-d7a297b9ae7f",
        "X-Goog-Channel-Expiration": "Fri, 14 Oct 2016 20:05:58 GMT",
        "X-Goog-Resource-ID":  "SuIweVX_iBzKmM5PQVMbIDYFrr8",
        "X-Goog-Resource-URI": "https://www.googleapis.com/drive/v3/files/1QvVo67IJ3_o5g2tCyxpNA29JHx183-bOOblKMoSAGv4?acknowledgeAbuse=false&alt=json",
        "X-Goog-Resource-State":  "update",
        "X-Goog-Changed": "content,properties",
        "X-Goog-Message-Number": "480896"
}

However, the event object of lambda handler is empty. I assume that event object is the HTTP body and in my case the body is empty, so I have added custom mapping template in Integration Request (to retrieve headers) of the API Gateway POST method as the following:
#set($inputRoot = $input.path('$'))
{
  "Content-Type" : "$input.params('Content-Type')",
  "Content-Length" : "$input.params('Content-Length')",
  "X-Goog-Channel-ID" : "$input.params('X-Goog-Channel-ID')",
  "X-Goog-Channel-Token" : "$input.params('X-Goog-Channel-Token')",
  "X-Goog-Channel-Expiration" : "$input.params('X-Goog-Channel-Expiration')",
  "X-Goog-Resource-ID" : "$input.params('X-Goog-Resource-ID')",
  "X-Goog-Resource-URI" : "$input.params('X-Goog-Resource-URI')",
  "X-Goog-Resource-State" : "$input.params('X-Goog-Resource-State')",

      "X-Goog-Changed" : "$input.params('X-Goog-Changed')",
      "X-Goog-Message-Number" : "$input.params('X-Goog-Message-Number')",
      "body" : $input.json('$')
    }

But I am not sure how should I retrieve these headers from event object if at all they are getting received from google drive. Just logging the event object shows it as empty {}. What is the expected mapping if the above is incorrect?                                                                   Also, event['header-name'] is not even getting executed it seems as when I print
print 'Event header:{}'.format(event['header-name']) I don't even get Event header statement in the logs. So it means the line is not exceuted but the line above that is executed which is simple print statement like print 'Printing results' I am not sure why the code is not getting there or if there is an error.
Could you please guide me how we can retrieve headers using event object in python? And if all my steps above look correct or am I missing something?

A: I was able to get this working without any problem.  I can't tell from your post why your event object is empty.  My best guess is that you forgot to add the headers to the "HTTP Request Headers" section of the Method Request.
Here's my Lambda function:
from __future__ import print_function

import json

print('Loading function')

def lambda_handler(event, context):
    print("Received event: " + json.dumps(event, indent=2))

    print("Content-Type = " + event['Content-Type'])
    print("Content-Length = " + event['Content-Length'])
    print("X-Goog-Channel-ID = " + event['X-Goog-Channel-ID'])
    print("X-Goog-Channel-Token = " + event['X-Goog-Channel-Token'])
    print("X-Goog-Channel-Expiration = " + event['X-Goog-Channel-Expiration'])
    print("X-Goog-Resource-ID = " + event['X-Goog-Resource-ID'])
    print("X-Goog-Resource-URI = " + event['X-Goog-Resource-URI'])
    print("X-Goog-Resource-State = " + event['X-Goog-Resource-State'])
    print("X-Goog-Changed = " + event['X-Goog-Changed'])
    print("X-Goog-Message-Number = " + event['X-Goog-Message-Number'])
    print("body = " + event['body'])

    return {
        'statusCode': '200',
        'body': event['body'],
        'headers': {
            'Content-Type': 'application/json',
            'X-Goog-Channel-ID': event['X-Goog-Channel-ID'],
            'X-Goog-Channel-Token': event['X-Goog-Channel-Token'],
            'X-Goog-Channel-Expiration': event['X-Goog-Channel-Expiration'],
            'X-Goog-Resource-ID': event['X-Goog-Resource-ID'],
            'X-Goog-Resource-URI': event['X-Goog-Resource-URI'],
            'X-Goog-Resource-State': event['X-Goog-Resource-State'],
            'X-Goog-Changed': event['X-Goog-Changed'],
            'X-Goog-Message-Number': event['X-Goog-Message-Number'],
        }
    }

My mapping template is the same as yours.
Here's the return value from a test call, using the same input headers from your example:
{
  "body": "Test input body content",
  "headers": {
    "X-Goog-Resource-ID": "SuIweVX_iBzKmM5PQVMbIDYFrr8",
    "X-Goog-Channel-ID": "",
    "X-Goog-Resource-State": "update",
    "X-Goog-Changed": "content,properties",
    "X-Goog-Resource-URI": "https://www.googleapis.com/drive/v3/files/1QvVo67IJ3_o5g2tCyxpNA29JHx183-bOOblKMoSAGv4?acknowledgeAbuse=false&alt=json",
    "X-Goog-Message-Number": "480896",
    "X-Goog-Channel-Token": "to66728b-21c7-4605-8445-d7a297b9ae7f",
    "Content-Type": "application/json",
    "X-Goog-Channel-Expiration": "Fri, 14 Oct 2016 20:05:58 GMT"
  },
  "statusCode": "200"
}


text:
Q: Statistical distance between two matrices
*

*The statistical distance between two probability distributions can be
measured with $f$-divergences such as the KL-divergence.

*The statistical distance between two clusters can be measured with distance metrics.

How can the statistical distance between two matrices be measured? matrix $A\in \mathbb{R}^{n\times p}$ and matrix $B\in \mathbb{R}^{n\times p}$ have the same dimensions, but more interest in square and symmetric matrices, $n=p$.
A previous suggestion was the norm of the matrix-difference, but without much reasoning or proof of usage. The term 'distance matrix' was found, but not sure if that applies to this problem.

A: The natural matrix analogue for histograms or probabilty distributions are density matrices, i.e. symmetric, positive semi-definite matrices whose trace sums to $1$. They predominently occur in information theory and quantum mechanics. For these matrices plenty of the classical concepts can be defined in a similar fashion. The entropy of such a matrix, say $A$, goes under 'von Neumann entropy' and reads
\begin{equation}
S(A)=-\operatorname{tr}(A\log A).
\end{equation}
The quantum relative entropy between two density matrices $A$ and $B$ is given by
\begin{equation}
S(A|B)=-\operatorname{tr}(A\log B)-S(A)=\operatorname{tr}(A(\log A -\log B)).
\end{equation}
There do exist also Wasserstein distance concepts for such density matrices.


text:
Q: Strange error from Google API: initializeAutocomplete is not a function A screenshot is attached since I'm not even sure how to describe the error.

It claims initializeAutocomplete is not a function, yet the function clearly exists in my JS file and here it is...
let autocomplete

function initializeAutocomplete() {
  autocomplete = new google.maps.places.Autocomplete(addressInput, {
    types: ['geocode']
  })
  autocomplete.addListener('place_changed', parseAddress)
}

And here is the reference in my HTML file to the script.
<script src="https://maps.googleapis.com/maps/api/js?
v=3
&key=[confidential]
&libraries=places
&callback=initializeAutocomplete" async defer></script>

I'm at a loss, especially since this started happening out of nowhere. Does anybody know what's happening here?

A: You're using async and defer script attributes. Your script is probably loaded after the one calling the initializeAutocomplete function.


text:
Q: Beam / DataFlow ::ReadFromPubSub(id_label) :: Unexpected behavior Can someone clarify what's the purpose for id_label argument in ReafFromPubSub transform?
I'm using BigQuery sink, my understanding it acts like an insertId for BQ Streaming API, Tabledata: insertAll

A unique ID for each row. BigQuery uses this property to detect duplicate insertion requests on a best-effort basis. For more information, see data consistency.

However I don't see this expected behaviour.

*

*I'm publishing messages to Pub/Sub, each message with same attribute message_id value (this is intentional to test pipeline / BQ dedupe behaviour)

*My pipeline reads from pubs as follows
beam.io.gcp.pubsub.ReadFromPubSub(topic=TOPIC,
          subscription=None,
          id_label='message_id')
but still querying BQ, all messages get inserted. I expected, because each message published with same message_id value, BQ should have deduced those...
can someone clarify pls?
Thanks in advance!
Also, I notice DirectRunner keep throwing error when using this attribute,

NotImplementedError: DirectRunner: id_label is not supported for PubSub reads

I've to use DataflowRunner... is that expected as well?
Cheers!
UPDATE 1 : moved to DataflowRunner, and the pipeline seems to respect id_label argument during ReadFromPubSub(). However, the duplicate messages DO continue to get read into the pipeline sporadically.

*

*My publisher application, every 15 sec, publishes messages in following format (the publisher app code is here):
cid=141&message_id=2&evt_time={{DATE_TIME_AT_RUNTIME}}
notice, i'm passing same message_id value (='2') in message's attribute as well (this is intention to try, test deduce behaviour).

*

*my pipeline (running on Dataflow Runner, beam Python v2.11 SDK, pipeline code is here ), dumps following message to BQ. As you can see, multiple messages with same message_id get read into pipeline and emitted to sink. This usually happens, when I stop/restart my publisher application.

cid=141&message_id=2&evt_time=2019-03-17T09:31:15.792653Z
cid=141&message_id=2&evt_time=2019-03-17T09:30:00.767878Z
cid=141&message_id=2&evt_time=2019-03-17T09:28:30.747951Z
cid=141&message_id=2&evt_time=2019-03-17T09:22:30.668764Z
cid=141&message_id=2&evt_time=2019-03-17T09:21:00.646867Z
cid=141&message_id=2&evt_time=2019-03-17T09:19:45.630280Z
cid=141&message_id=2&evt_time=2019-03-17T09:12:05.466953Z
cid=141&message_id=2&evt_time=2019-03-17T09:10:42.956195Z
cid=141&message_id=2&evt_time=2019-03-17T09:01:42.816151Z

A: Those are different IDs. As explained here, every message published to a topic has a field named messageId that is guaranteed to be unique within the topic. Pub/Sub guarantees at-least-once delivery so a subscription can have duplicates (i.e. messages with the same messageId). Dataflow has exactly-once processing semantics because it uses that field to de-duplicate messages when reading from a subscription. This is independent of the sink, which does not need to be BigQuery.
Using id_label (or .withIdAttribute() in the Java SDK) we can force that messages are considered duplicate according to a different field that should be unique (such as order ID, customer ID, etc.). The input source will read the repeated messages only once, you won't see them increase the count of input elements in the pipeline. Keep in mind that the Direct Runner is intended for testing purposes only and does not offer the same guarantees in terms of checkpointing, de-duplication, etc. As an example refer to this comment. That's the most likely cause of why you are seeing them in the pipeline, also taking into account the NotImplementedError messages, so I'd suggest moving to Dataflow Runner.
On the other side, insertId is used, on a best-effort basis, to avoid duplicate rows when retrying streaming inserts in BigQuery. Using BigQueryIO it is created under the hood and can't be specified manually. In your case, if your N messages enter the pipeline and N are written to BigQuery, it is working as expected. If any had to be retried, the row had the same insertId and was, therefore, discarded.


text:
Q: Start .NET installation with VBScript and wait for completition Since I have to run my .NET app from an USB Stick, I need a way to check if .NET is installed.
I create this VBScript (in Win10) but it doesn't wait for the installer to finish, where I wrong
Option Explicit
Dim oShell
Dim value

On Error resume next

Set oShell = CreateObject("WScript.Shell")
value = oShell.RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\Release")

' check for .NET Framework 4.5.1 -> 378xxx

If ((Err.Number <> 0) Or (Clng(value) < 379000)) Then
    ' .NET 4.5.1 is not istalled....install it (and wait for completition)
    MsgBox("Install .NET")
    oShell.Run "NDP451-KB2858728-x86-x64-AllOS-ENU.exe", 1, True
End If

oShell.Exec("MyApp.exe")

A: If you really want your script to wait for the .NET Framework installer to complete, your another option should be a continuous loop.
Take a look at the following script:
Option Explicit
Dim oShell
Dim value
Dim PackageName

PackageName = "NDP451-KB2858728-x86-x64-AllOS-ENU.exe"

Function IsProcessRunning(StrProcess)
  Dim Process
  IsProcessRunning = False
  For Each Process in GetObject("winmgmts://.").InstancesOf("Win32_process")
    If UCase(Process.Name) = UCase(StrProcess) Then
    IsProcessRunning = True
    Exit Function
    End If
  Next
End Function

On Error Resume Next

Set oShell = CreateObject("WScript.Shell")
Value = oShell.RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\Release")

'Check for .NET Framework 4.5.1 -> 378xxx
If ((Err.Number <> 0) Or (Clng(Value) < 379000)) Then
'.NET 4.5.1 is not istalled....install it (and wait for completition)
  MsgBox("Installing .NET Framework 4.5.1...")
  oShell.Run """<< ONLY ABSOLUTE PATH TO YOUR PACKAGE FILE + BACKSLASH >>" + PackageName + "", 1, False
End If

Do
  WScript.Sleep 500
Loop Until IsProcessRunning(PackageName) = False

MsgBox ".NET Framework 4.5.1 has been installed successfully, Running MyApp..."
oShell.Exec("MyApp.exe")

This loop only uses 0 - 3 % of CPU resources and surely wait for the installer to complete or interrupt for any reason.
NOTE: This option will only work if main .NET Framework setup package is running as a background process until the installation completes or interrupts.
Here, as you are installing .NET Framework 4.5.1, this option should work.


text:
Q: CSS trouble: Float drops to another line (all browsers) I understand that a float drops to the next line if its parent container is not wide enough.
The site I'm working on is a Magento 1.7.2 install with a ThemeForest theme (Fortis). The expected problem started when I included Twitter bootstrap (I obviously did it at the top of the ).
My div.header is 960px wide. It contains:

*

*div.header-top which is working fine.

*h1.logo which floats left, and is narrower than it needs to be (currently 200px, should be 400px).

*div.header-left element which is currently empty, and has a left margin of 20px.

*div.header-right element which is 485px wide and floats right.

The problem is that if I make h1.logo any wider, the div.header-right will drop to the next line.
I should be able to make the div.header-left as wide as 455px without a problem. What am I missing?

A: Figured it out. Looks like the search bar on the top has a margin on the bottom and is pushing .header-right over to the left.
Right click and "Inspect Element" on the search field and you will see what I mean.
You will have to remove the margin or adjust the height on .header-top-search-wrapper.


text:
Q: Import data from ICS file to Google Calender I am generating ICS file dynamically and I want to import data from generated ICS file to Google event calendar every day using cron.
I tried to understand Calender API documentation, but no luck!! I don't understand how to configure composer and all that.
It would be very appreciated if someone can guide me easy way!!

A: Read your ICS file. Create a simple project in any language you are familiar with, incorporate Google Calendar V3 api in your project.
https://developers.google.com/google-apps/calendar/quickstart/dotnet, here you can get sample code.
I think this will help. Please read the sample and documentation before implementing.


text:
Q: Dynamics CRM 2013: Activity feed shows more than security role allows Dynamics CRM (relative) newbie here.
I have an activity feed set up on a users dashboard (I used the Personal Wall web resource).  If I look at the default posts for the Account view, everything is cool.
However, if I go and "follow" an Account when I look at my activity feed I can see other posts that relate to records that Account is involved with that are outside of my security role.  For example, that Account has several Case records.  My role has no permissions to Cases whatsoever, but there is the post in my activity feed.  If I click on the case I get a prvReadPriviledge error which is correct, but I don't want users to do this - I don't want these posts to show up in their feeds at all, even if the are following the account.
These posts do need to show up in the feeds for people working Cases, however (and their roles will have read/write to the Case entity).
I'm not sure what do here.. can you help?

A: I believe that this is what you're looking for it's from Microsoft's site.
"The activity feeds walls are web resources that can be embedded in dashboards in context with relevant grids and visualizations. For example, you can embed the msdyn_/PersonalWall.htm web resource into a dashboard with specifying the HideUserProfile parameter. The default is value 1 (or, true), to hide the user profile, to unhide, use the value 0 (or, false). For more information about how to use web resources in dashboards, see Analyze data with dashboards."


text:
Q: How to set install sample data during Magento 2 installation trough CLI? I am installing magento2 in a LEMP stack, trough composer and command line.
Follow is the code I am using to install:
bin/magento setup:install
--backend-frontname="adminlogin" \
--db-host="localhost" \
--db-name="magentodb" \
--db-user="magentouser" \
--db-password="magentouser@" \
--language="en_US" \
--currency="USD" \
--timezone="America/New_York" \
--use-rewrites=1 \
--use-secure=0 \
--base-url="http://www.newmagento.com" \
--base-url-secure="https://www.newmagento.com" \
--admin-user=adminuser \
--admin-password=admin123@ \
--admin-email=admin@newmagento.com \
--admin-firstname=admin \
--admin-lastname=user \
--cleanup-database

Is there any parameter to force magento to install sample data?

A: After your Magento installation in order to install sample data using the command line, enter the following command as the Magento file system owner:
php <your Magento install dir>/bin/magento sampledata:deploy
Source: http://devdocs.magento.com/guides/v2.0/install-gde/install/sample-data-before-composer.html


text:
Q: Jackson xml (de)serialization with custom boolean format I have xml file:
<?xml version="1.0" encoding="UTF-8"?>
<ADDRESSOBJECTS>
    <OBJECT ID="1802267" NAME="SomeName" ISACTIVE="1" />
</ADDRESSOBJECTS>

and correponding classes in kotlin:
@JacksonXmlRootElement(localName = "ADDRESSOBJECTS")
class AddressingObjectCollection {
    @JacksonXmlProperty(localName = "OBJECT")
    @JacksonXmlElementWrapper(useWrapping = false)
    open lateinit var objects: List<AddressingObject>
}

and
class AddressingObject : Serializable {
    @JacksonXmlProperty(isAttribute = true, localName = "ID")
    open var id: Long = 0

    @JacksonXmlProperty(isAttribute = true, localName = "NAME")
    open lateinit var name: String

    @JacksonXmlProperty(isAttribute = true, localName = "ISACTIVE")
    open var isActive: Boolean = false
}

when I try to deserialize I get error:
val deserialized = mapper.readValue(File(file).readText(), AddressingObjectCollection::class.java)

error:
Cannot deserialize value of type `boolean` from String "1": only "true"/"True"/"TRUE" or "false"/"False"/"FALSE" recognized

How to tell jackson to (de)serialize this format properly?

A: For this purpose I use Json attributes:
@JsonProperty("ISACTIVE")
@JacksonXmlProperty(isAttribute = true, localName = "ISACTIVE")
@JsonDeserialize(using = CustomBooleanDeserializer::class)
open var isActive: Boolean = false

And CustomBooleanDeserializer:
class CustomBooleanDeserializer : JsonDeserializer<Boolean>() {
    override fun deserialize(p: JsonParser?, ctxt: DeserializationContext?): Boolean {
        if (p?.currentTokenId() == JsonTokenId.ID_STRING){
            var text = p.text

            if (text == "1") return true
        }

        return false;
    }
}

It works for me.


text:
Q: Exception handling for Ajax requests in JSF using Omnifaces : always showing Status Code 200 instead of 500 we are currently adding a monitoring solution (Dynatrace) to our JSF web application. The monitoring solution checks for status codes that indicate an error to flag a problem in a user session. We are trying to use Omnifaces FullAjaxExceptionHander (see http://showcase.omnifaces.org/exceptionhandlers/FullAjaxExceptionHandler) to handle Ajax exception and render an error page. As you can see from the screen shot Omnifaces sets an error code of 500 but the status code on the POST shows up as 200 in Chrome. As Dynatrace doesn't see an error status code it does not flag this on the user session.
Any idea why the status code is not set on the response? I thought I saw it briefly come up with a status code of 500 on the POST in our system but now it is only showing 200 again. That's when I tried the example from the Omnifaces showcase and there I am only getting the 200 has well.

A: It's because it's technically a successful Ajax response. I.e. it has successfully delivered the error page content as part of <partial-response> in the Ajax response XML body.
If the Ajax response would have status 500, then JSF wouldn't have parsed the Ajax response XML at all, but instead invoked the onerror handler which in turn fires any registered custom client side code. This is where things get complicated as it by default doesn't render anything while the FullAjaxExceptionHandler really wants to utilize the existing JSF Ajax rendering logic.
Your best bet is to check if your monitoring service offers a Java based API to manually notify the error condition. And if so, then override one of the FullAjaxExceptionHandler methods to ping it. The shouldHandleExceptionRootCause() is a good candidate. There you can if necessary also perform an instanceof check on the exception to skip certain ones.
I'm not familiar with Dynatrace, but in case you're using NewRelic, this is how it would look like:
import com.newrelic.api.agent.NewRelic;

public class CustomExceptionHandler extends FullAjaxExceptionHandler {

    @Override
    protected boolean shouldHandleExceptionRootCause(FacesContext context, Throwable exception) {
        try {
            NewRelic.noticeError(exception);
        }
        catch (Exception e) {
            // Log a WARN line
        }

        return true;
    }
}

Finally create a custom ExceptionHandlerFactory for it and replace the FullAjaxExceptionHandlerFactory in faces-config.xml with it.


text:
Q: Bind Vita ORM using Ninject I am new to both Ninject and the Vita ORM (vita docs) and am just having issues coming up with a binding strategy for dependency injection and would really appreciate any help.
Firstly, my application in split into 3 layers, namely the data layer ( using Vita ORM so in essence it is a single EntityApp class similar to dbContext for EF), then I have a service layer with well defined interfaces ( and existing implementations using my current repository pattern using dapper.net ) and finally a simple MVC web application with controllers calling off to the service layer.
Currently I am using ninject constructor intection to inject the repo into the service and the service into the controller and scoping them accordingly. this works great because everything is interface driven and there is no shared context between services / repositories.
But now with the introduction of an "entity context" I need to create the context once in the app ( so singleton scope ) and then would in essence like to open a new session per request and pass that to any service layer objects that require it. Over and above this, the ORM needs to be initialized at application startup ( or I suppose it can be done lazily, but at app start would be better )
Here is some code generated by vita as to how to initialize the ORM
class Program {

public static MyEntityApp App;

static void Main(string[] args) {
  Console.WriteLine(" Sample application for VITA-generated model. ");
  Init();

  //Open session and run query
  var session = App.OpenSession();
  var query = from ent in session.EntitySet<IConnections>()  // just random entity
              // where ?condition?
              select ent;
  var entities = query.Take(5).ToList();

  Console.WriteLine("Loaded " + entities.Count + " entities.");
  foreach(var ent in entities)
    Console.WriteLine("  Entity: " + ent.ToString()); // change to smth more meaningful

  Console.WriteLine("Press any key ...");
  Console.ReadKey();
}

private static void Init() {

  App = new MyEntityApp();
  App.CacheSettings.AddCachedTypes(CacheType.FullSet /* , <fully cached entity types> */ );
  App.CacheSettings.AddCachedTypes(CacheType.Sparse /* , <sparsely cached entity types> */ );
  var connString = @".......";
  var driver = new Vita.Data.MsSql.MsSqlDbDriver();
  App.LogPath = "_appLog.log";
  var dbSettings = new DbSettings(driver, DbOptions.Default, connString, upgradeMode: DbUpgradeMode.Always);
  App.ConnectTo(dbSettings);
}

}

As you can see they initialize and set a static variable which has reference to the context container. As can also be seen by the above is that you need to call var session = App.OpenSession(); to work with the context, so I was hoping to create one session per request and then inject that session into the service object contructors.
So here is what I have done so far
/*Map the Vita ORM session into the request scope*/
kernel.Bind<MyEntities>().ToSelf().InSingletonScope();

I am assuming that will call the contructor, and inside there I have initialized the context correctly ( and this should also only be called once )
then in the service objects i want to do something like this
here is the service impl
private IEntitySession _Session { get; set; }

public VitaSettingsServiceImpl(IEntitySession Session)
{
    _Session = Session;
}

And here is my attempt at injecting that session object...
kernel.Bind<ISettingsService>().To<VitaSettingsServiceImpl>().InRequestScope().WithConstructorArgument("Session", [WANT TO CALL MYENTITIES.OpenSession() HERE]);

As you can see it is that last binding that is stumping me? how do I bind a contructor object param to a method call on an existing singleton bound object?
Like I said in the begining, I am VERY green at this and maybe I am going about it all wrong, but i have scoured the web and cant find any info regarding these to technologies being used together, so any help would be greatly appreciated

A: So for all the lonely souls trolling the web with similar issues, here is what I eventually cam up with :
        /*Map the Vita ORM session into the request scope*/
        kernel.Bind<SorbetEntities>().ToSelf().InSingletonScope();

        /*Map all the services to their respective implementations*/
        kernel.Bind<ISettingsService>().To<sorbet.Vita.VitaSettingsServiceImpl>().InRequestScope().WithConstructorArgument("Session", CreateVitaSession);

and then a static extension method to execute the method that will return my connection context
    private static object CreateVitaSession(IContext context)
    {
        return context.Kernel.Get<SorbetEntities>().OpenSession();
    }

And thats it. now i get a new connection context per request and I am a happy camper


text:
Q: Glew does not init I am using the following code to check for any error:
glfwInit();
glewExperimental = GL_TRUE;
if (glewInit() != 0)
{
    std::cout << "Failed to initialize GLEW" << std::endl;
    return -1;
}

I am using the non static version of Glew and I have included the .dll file in the Debug folder. I am using Visual Studio Community 2013. All other solutions suggested to set glewExperimental to GL_True or check the error checking, but I have done that and it is still does not work.

A: You don't have a GL context just by glfwInit(), so GLEW has nothing to work on. You must create a GL context and make it current to the thread, which for GLFW implies creating a window.


text:
Q: How to pass down variables to credential parameters in JenkinsFiles? I'm trying to write a JenkinsFile that automatically will reach to a git repo via ssh and perform some actions but I want to make the repo and ssh key use variables with the ssh id stored in Jenkins but I seem to be missing the Jenkins documentation for how to pass down variables to Jenkins Files as I'm not able to pass values down into the credentials key.  The variables being passed down to the sh commands resolve perfectly fine though...
Example Pipeline Below:
pipeline {
  parameters {
    string(name: 'SSH_priv', defaultValue: 'd4f19e34-7828-4215-8304-a2d1f87a2fba', description: 'SSH Credential with the private key added to Jenkins and the public key to the username stored in Git Server, this id can be found in the credential section of Jenkins post its creation.')
    string(name: 'REPO', defaultValue: 'git@--------------------')
  }
  stages {
    stage ('Output Variables'){
      // checks I can get these variables
      steps{
        sh("echo ${params.SSH_priv}")
        sh("echo ${params.REPO}")
      }
    }

stage('Do Something') {
      steps {
        // this below commented line, does not work.
        // sshagent (credentials: ['${params.SSH_priv}']){

        // this line does work
        sshagent (credentials: ['d4f19e34-7828-4215-8304-a2d1f87a2fba']){
          sh("git clone --mirror ${params.REPO} temp")
          dir("temp"){
            // start doing fancy stuff ...
            ....
            ....
          }
        }
      }
    }

The aim is a Pipeline that my fellow developers could call and will work with their own repos and own ssh id's that I'm not using.  When I try to run this with the SSH_priv parameter passing down the value I get the below failure in Jenkins.

The JenkinsFile works perfectly fine with the credential id hard-coded- as shown below:

A: So after testing different things a friend solved this in sub 5 minutes.  Quotation mark types matter in Groovy Script
Changing
sshagent (credentials: ['${params.SSH_lower}']){

To
sshagent (credentials: ["${params.SSH_lower}"]){

Solved the issue.

A: Better to use environment step in pipeline.
pipeline {
    agent any
    environment {
                AN_ACCESS_KEY = credentials('an_access_key_id')
            }
    stages {
        stage('Example') {
            steps {
                sh 'printenv'
            }
        }
    }
}

And credentials should exist in jenkins with id an_access_key_id
Take a look at official documentation here


text:
Q: Argument of type 'X' is not assignable to parameter of type 'Y" with NGRX I'm creating a people reducer...
However, we know that requests may very well fail and that is why I inserted in getInitialState() some properties such as data, error and loading.
The data is an object of type People to be able to enter the values of the specific person.
The error is an object of type RequestError if an error occurs in the request.
Finally, loading is the loading of requests.
The error that occurs is that it says that the RequestError interface is not signed in the People interface, which is obvious, because I am using the state as a base.

How do I do this implementation?
ERROR:
var error: RequestError
Argument of type 'RequestError' is not assignable to parameter of type 'People'.
  Type 'RequestError' is missing the following properties from type 'People': id, isMain, avatar, messagests(2345)

ACTIONS:
import { createAction, props } from '@ngrx/store';
import { RequestError } from '@shared/interfaces/request.interface';
import { People } from '@shared/interfaces/people.interface';

export const GET = createAction('[GET: USER/API] Get a people');

export const CREATE = createAction('[POST: USER/API] Create a new people', props<{ data: People }>());
export const CREATE_SUCCESS = createAction('[POST: USER/API] Successfully created person', props<{ data: People }>());
export const CREATE_FAIL = createAction('[POST: USER/API] Failed to create a new person', props<{ error: RequestError }>());

export const UPDATE = createAction('[PUT: USER/API] Update a people', props<{ id: string; changes: Partial<People> }>());
export const UPDATE_SUCCESS = createAction('[PUT: USER/API] Person updated with success', props<{ id: string; changes: Partial<People> }>());
export const UPDATE_FAIL = createAction('[PUT: USER/API] Person update failed', props<{ error: RequestError }>());

REDUCER:
import { EntityState, EntityAdapter, createEntityAdapter } from '@ngrx/entity';
import { Action, createReducer, on } from '@ngrx/store';
import { People } from '@shared/interfaces/people.interface';
import * as fromPeopleAction from './people.actions';

export interface State extends EntityState<People> {}

export const adapter: EntityAdapter<People> = createEntityAdapter<People>({
    selectId: (people: People) => people.id,
});

const INIT_STATE: State = adapter.getInitialState({
    data: null,
    error: null,
    loading: false,
});

const peopleReducer = createReducer(
    INIT_STATE,
    on(fromPeopleAction.CREATE, (state: State, { data }) => adapter.addOne(data, { ...state, loading: true })),
    on(fromPeopleAction.CREATE_SUCCESS, (state: State, { data }) => adapter.addOne(data, { ...state, loading: false })),
    on(fromPeopleAction.CREATE_FAIL, (state: State, { error }) => adapter.addOne(error, { ...state, loading: false }))
);

export function reducer(state: State | undefined, action: Action) {
    return peopleReducer(state, action);
}

A: As your chart shows, data property from State remains null, even when your CREATE action is successful, which means that the issue is with your action's props. Since your EntityAdapter is of type People, when you call the function adapter.addOne(), it is expecting params from type People. The way you modeled your State, data, error and loading are People's properties, which means that when you want to add or update any property, you need to wrap it inside of People class.
In summary you would have to change your CREATE_FAIL action's props to something similar as:
props<{ people: { error: RequestError } }>()

Or when you call adapter.addOne(), wrap it.
In case you already have the people state created on store and want to add an error, you can call adapter.updateOne() instead of addOne().


text:
Q: Center align HTML Elements, while adding new items from left I have a parent div containing an unknown number of smaller divs that are used like large icon-like buttons.  If a row of child divs is full, I would like them to have equal margins on each side (ie. centered), but if a row is not full I would like them to be filled in from the left side (but still in columns with the elements above).  Is there a way to do this with CSS?  Resizing the window should maintain the centering and add/remove columns as necessary.  All the child div widths are known.
Here's a crappy image of the behavior I'm trying for:

A: Just use float left, and items of the width (the original fiddle):

Cats

Cats

Cats

Cats

Cats

Cats

Cats

Cats

Cats

Cats

Cats

Cats

Cats

.container {
    overflow: auto;
}

.item {
    width: 50px;
    float: left;
    margin: 0 10px;
}

A: Okay I figured out a solution for this that both allows for equal margins and ALSO aligns divs left in the last row. The caveat is that it uses hidden elements, so the container is taller than the visible elements it contains.
Also it adds a bunch of extra markup to your code. If I thought of any other way to do this, I would do it differently. Sorry.
JSFiddle: https://jsfiddle.net/88qadmo3/2/

#container > div {
    margin: 10px;
    width: 100px;
    height: 100px;
}
.floatleft {
    background-color: red;
}

.invis {
    visibility: hidden;
}

#container {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    background-color: #DDDDDD;
}

.clearfix {
    clear: both;
}

A: You can do this by wrapping each of the child elements in an element and using CSS media queries to change the size of the wrappers. Then, just use % width on the wrappers based on what you want the column sizes to be.
When you run the example, shrink it to <400px so you can see it move from 6 columns to 3 (you'll need to run the code snippet on a full-page to see this).

.parent {
  border: 2px solid red;
}
.child {
  width: 100px;
  display: block;
  margin: 0 auto;
  border: 1px solid black;
}
.wrapper {
  display: inline-block;
  text-align: center;
  float: left;
  width: 16.66%;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.clear {
  clear: both;
}
@media (max-width: 800px) {
  .wrapper {
    width: 20%;
  }
}
@media (max-width: 600px) {
  .wrapper {
    width: 25%;
  }
}
@media (max-width: 400px) {
  .wrapper {
    width: 33.33%;
  }
}

1

2

3

4

5

6


text:
Q: how to convert simple string in to logical "if" validation statment in php I have a string from database ([INDEX]>0):[INDEX],0, Now I have a value of $index. How can i set that string in to IF condition in php like,
([INDEX]>0):[INDEX],0
$var='';
if($index>0){
 $var = $index;
} else {
 $var = 0;
}

there will also other conditions like
`[AGE] > 18:([AGE]-15)/1000`

 that will make validation like

$newage = 0;
if($age > 18){
  $newage = ($age-15)/1000
}

How can i manage it ?


text:
Q: Why does my fifo read return strings with weird characters in the middle? I am trying to pass logging statements to a daemon process via a named pipe. The statements contain the timestamp, the sender and the message. The messages are created just as they are supposed to but when I read them from the other end of the pipe, they sometimes have weird characters in the middle of the string such as Úèþ. I tried appending the '\0' to the end of each logging statement but it didn't have any effects. Below is the code of my pipe creation and the reading part:
char * fdfifo = "./fifo/myfifo";
    mkfifo(fdfifo, 0666);
    int fd = open(fdfifo,O_RDONLY);
    struct timeval timeout;
    timeout.tv_sec = 5;
    timeout.tv_usec = 0;
    logger(getpid(), pthread_self(), "logger started");
    while(1 && keepRunning){
        fd_set fds;
        FD_ZERO(&fds);
        FD_SET(fd, &fds);
        if(select(fd + 1, &fds, NULL, NULL, &timeout)<=0){
            logger(getpid(), pthread_self(), "stopping logger");
            close(fd);
            exit(EXIT_SUCCESS);
            break;
        }
        else{
            pthread_mutex_lock(&lock2);
            FILE *f = fopen("./log/log.log", "a");
            char concat_str[200];
            read(fd, concat_str, 200);
            fprintf(f, "%s\n", concat_str);
            fclose(f);
            pthread_mutex_unlock(&lock2);
        }
    }

And this is the part where I am writing to the pipe:
int startLoggerEnd(){
    readfifo = "./fifo/myfifo";
    mkfifo(readfifo, 0666);
    writedesc = open(readfifo,O_WRONLY);
    sleep(2);
    return 0;
}

int logger(pid_t pid, pthread_t tid, char *message){
    char tmp[100];
    char buff[20];
    char msg[200];
    struct tm *sTm;
    time_t now = time (0);
    sTm = gmtime (&now);
    strftime (buff, sizeof(buff), "%Y-%m-%d %H:%M:%S", sTm);
    sprintf(msg,"%s %s %d %s %d %s %s\n", get_timestamp(tmp), "process:", pid,
            "thread:",(unsigned) tid, "||", message);
    write(writedesc, msg, strlen(msg));
    return 0;
}

And few lines from the end of the logfile:
13:29:41:729 process: 14736 thread: 127881216 || moi
13:29:41:729 process: 14736 thread: 127881216 || moi
13:29:41:729 process: 14736 thread: 127881216 || moi
13:29:41:729 process: 14736 thread: 127881216 || moi
13:29:41:729 process: 14736 thread: 127881216 || moi
13:29:41:729 process: 14736 thread: 127881216 || moi
13:29:41:729 process: 14736 thread: 127881216 || moi
13:29:41:729 process: 14736 thread: 127881216 || moi
13:29:41:729 process: 14736 thread: 127881216 || moi
13:29:41:729 process: 14736 thread: 127881216 || moi
13:29:41:729 process: 14736 thread: 127881216 || moi
13:29:41:729 process: 14736 thread: 127881216 || moi
13:29:41:729 process: 14736 thread: 127881216 || moi
13:29:41:729 process: 14736 thread: 127881216 || moi
13:29:41:729 process: 14736 thread: 127881216 || moi
13:29:41:729 process: 14736 thread: 127881216 || moi
13:29:41:729 process: 14736 thread: 127881216 || moi
13:29:41:729 process: 14736 thread: 127881216 || moi
13:29:41:729 process: 14736 thread: 127881216 || moi
13:29:41:729 process: 14736 thread: 127881216 || moi
 process: 14736 thread: 127881216 || moi
13:29:41:729 process: 14736 thread: 127881216 || moi
13:29:

A: You are currently displaying an allocated slice of memory (str2).
However, you don't make sure that the portion of memory that you've requested is empty.
It may contains bytes of previous operations, resulting in a bad display.
The correct way to assure that you are not displaying previous bytes is to clean the memory before printing it.
char *str2 = calloc(strlen(msg) + 1, sizeof(char));
strcpy(str2, msg);
str2[strlen(msg)] = '\0'; // index start at 0, strlen start at 1
write(fd, str2, strlen(str2));
close(fd);

calloc will clean the memory allocated before returning it to you.
Also, be aware that this code suffers a major leak of memory, you doesn't even free the str2 that you have allocated.


text:
Q: Can I prevent a file from being created? We have a machine that runs VMware Server. It constantly creates a file called not_configured in /etc/vmware/, which somehow makes our virtual machines not able to be started.
I wondered if there was any reliable way to prevent this file from ever being created in the first place.
The file itself doesn't contain anything, so I don't want to create and write-protect it. It shouldn't be there in the first place.

A: You can make the directory read-only in some way: with unix permissions (chmod a-w), or with more stringent measures such as mounting a read-only filesystem at that spot. I don't think Linux offers a built-in way of preventing a single file from being created, without making the directory read-only as a whole. There is of course the multipurpose tool FUSE but I don't know of an existing FUSE filesystem that lets you create a file blacklist in this way.
You can try creating a dangling symbolic link, especially one pointing to a nonexistent file in a read-only directory. Depending on how the one program checks for the file existence and the other program tries to create the file, this may or may not work.
I'd recommend figuring out what program is creating that file and shutting it off. See How to determine which process is creating a file?

A: In short, if you have any Vmware products that you haven't uninstalled cleanly it would create such a problem that you describe.
Follow the instructions at this link, I have had success with them:
I have had the same problem, and after I have followed the above guide it solved.

A: The only standard way to do this is to remove the write permission from the directory.  This will, of course, prevent anything from creating files in this directory.

A: Not sure about VMWare Server flexibility in that area but assuming the /etc/vmware directory is allowed to be located on a remote file system  shared under NFS or CIFS, that would be an easy task by using an OS supporting DTrace at the file server side (Solaris, OpenIndiana, FreeBSD, MacOS/X, ...).
A simple so called destructive script could force or simulate a failure on any attempt to open the not_configured file.

A: I actually already do this.. you can make a listener in "watcher" or "incron" (I would use watcher, it's recursive) use that create trigger, write a script, wait 5 seconds (this is because all sorts of read only /tmp files can be "created" when a file is "created" - which you test for locked/read only and re pause if necessary) then in your script scan/move/delete any files in that folder you dislike..
NB: ensure your script is being intelligent for locked file/retry paradigm..


text:
Q: I am trying to make a registration form with JAVA, but I can't run my code I have this code and I can't get it to run. I'm new with JAVA. I was trying to make a login and registration form with JAVA swing, and I finished designing GUI part and I also connected the code with mySQL database. But I don't know why that I can't run the code. I tried debugging it, but can't find the bug. I am using eclipse and I also referenced mySQL jar.
Please let me know, if I'm doing anything wrong. Thank you for the help :)
package login_register_form;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.sql.*;
import javax.swing.JComboBox;

public class RegisterPage implements ActionListener{

JFrame frame;
String[] position = {"Admin", "Manager", "Assistant"};
JTextField firstName;
JTextField lastName;
JTextField userName;
JTextField email;
JPasswordField password;
JPasswordField confirmPW;
JButton registerButton;
JButton cancelButton;
JComboBox jobPosition = new JComboBox(position);

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                RegisterPage window = new RegisterPage();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application. Calling methods from constructor
 */
public RegisterPage() {
    createWindow();
    initialize();
    actionEvent();

}

/**
 * Create a main window
 */
public void createWindow() {
    frame = new JFrame();
    frame.setTitle("Registration Page");
    frame.getContentPane().setBackground(Color.GRAY);
    frame.setBounds(100, 100, 1113, 806);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {

    // panel: orange colored background
    JPanel panel = new JPanel();
    panel.setBackground(new Color(255,165,0,200));
    panel.setBounds(300, 150, 500, 472);
    frame.getContentPane().add(panel);
    panel.setLayout(null);

    // label: scaled background
    JLabel background = new JLabel("");
    background.setBounds(6, 6, 1100, 772);
    ImageIcon icon = new ImageIcon(this.getClass().getResource("/background.jpg"));
    Image img = icon.getImage();
    Image imgScale = img.getScaledInstance(background.getWidth(), background.getHeight(), Image.SCALE_SMOOTH);
    ImageIcon scaledIcon = new ImageIcon(imgScale);
    background.setIcon(scaledIcon);
    frame.getContentPane().add(background);

    // title: "Register Page"
    JLabel registerPage = new JLabel("Register Page");
    registerPage.setFont(new Font("Lucida Grande", Font.BOLD, 19));
    registerPage.setBounds(182, 40, 135, 29);
    panel.add(registerPage);

    // input: first name
    firstName = new JTextField();
    firstName.setBounds(145, 76, 210, 32);
    panel.add(firstName);
    firstName.setColumns(10);

    // input: last name
    lastName = new JTextField();
    lastName.setBounds(145, 120, 210, 32);
    panel.add(lastName);
    lastName.setColumns(10);

    // input: user name
    userName = new JTextField();
    userName.setBounds(145, 164, 210, 32);
    panel.add(userName);
    userName.setColumns(10);

    // input: password
    password = new JPasswordField();
    password.setBounds(145, 208, 210, 32);
    panel.add(password);

    // input: confirm password
    confirmPW = new JPasswordField();
    confirmPW.setBounds(145, 252, 210, 32);
    panel.add(confirmPW);

    // input: email
    email = new JTextField();
    email.setBounds(145, 296, 210, 32);
    panel.add(email);
    email.setColumns(10);

    // input: position
    jobPosition.setBounds(145, 340, 210, 32);
    panel.add(jobPosition);

    // button: cancel
    JButton cancelButton = new JButton("Cancel");
    cancelButton.setBounds(109, 400, 117, 40);
    panel.add(cancelButton);

    // button: register
    JButton registerButton = new JButton("Register");
    registerButton.setBounds(275, 400, 117, 40);
    panel.add(registerButton);

    // label: first name
    JLabel fName = new JLabel("First Name");
    fName.setBounds(36, 84, 85, 16);
    panel.add(fName);

    // label: last name
    JLabel lName = new JLabel("Last Name");
    lName.setBounds(36, 128, 85, 16);
    panel.add(lName);

    // label: user name
    JLabel uName = new JLabel("User Name");
    uName.setBounds(36, 172, 85, 16);
    panel.add(uName);

    // label: password
    JLabel pWord = new JLabel("Password");
    pWord.setBounds(36, 216, 85, 16);
    panel.add(pWord);

    // label: re-password
    JLabel cPW = new JLabel("Re-Password");
    cPW.setBounds(36, 260, 85, 16);
    panel.add(cPW);

    // label: email
    JLabel eMail = new JLabel("Email");
    eMail.setBounds(36, 304, 85, 16);
    panel.add(eMail);

    // label: position
    JLabel position = new JLabel("Position");
    position.setBounds(36, 347, 101, 16);
    panel.add(position);

}
public void actionEvent() {
    // Adding action listener to buttons
    registerButton.addActionListener(this);
    cancelButton.addActionListener(this);
}

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource()==registerButton) {
        try {
            //Creating Connection Object
            Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/myDatabase","root", "root");
            //Prepared Statement
            PreparedStatement Pstatement=connection.prepareStatement("insert into student value(?,?,?,?,?,?)");
            // Specifying the values of it's parameter
            Pstatement.setString(1, firstName.getText());
            Pstatement.setString(2, lastName.getText());
            Pstatement.setString(3, userName.getText());
            Pstatement.setString(4, password.getText());
            Pstatement.setString(5, confirmPW.getText());
            Pstatement.setString(6, email.getText());
            Pstatement.setString(7, jobPosition.getSelectedItem().toString());
            //Checking for the password match
            if (password.getText().equalsIgnoreCase(confirmPW.getText())) {
                // Executing query
                Pstatement.executeUpdate();
                JOptionPane.showMessageDialog(null, "Data Registered Successfully");
            } else {
            JOptionPane.showMessageDialog(null, "Password did not match");
            }

        } catch (SQLException e1) {
            e1.printStackTrace();
        }
    }
    if (e.getSource()==cancelButton) {
        // Clearing Fields
        firstName.setText("");
        lastName.setText("");
        userName.setText("");
        password.setText("");
        confirmPW.setText("");
        email.setText("");
        jobPosition.setSelectedItem("Admin");
    }
}

}


text:
Q: How to implement iAd correctly I am trying to get my banner ad to display but i receive the following error:
Property 'canDisplayBannerAds' not found on object of type 'ViewController *'
Thing you may need to know

*

*My app deployment target is iOS 6

Here is the code
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.canDisplayBannerAds = YES;
[Tramresult setNumberOfLines:0];

}

A: Add the iAd Framework to your build libraries.
Include this in your .h file
#import <iAd/iAd.h>

Include this in viewDidLoad of .m file.
self.canDisplayBannerAds = YES;


text:
Q: Refresh/Update Post/Product by POST Wordpress - Woocommerce I know that updating a wordpress post/producer can be done this way
$post = get_post(27087);
$post->post_content = "Some other content";
wp_update_post( $post );

The detail is that I have 3 plugins (one of them FACEBOOK) that update the content of the product when the UPDATE button of the product is clicked with the POST method of the form.
"I mean when you click update the product in the form Woocommerce"
Any idea how to create an api to refresh/update the product via the POST method of the update product form?
My goal is to activate the plugins that take action within the POST method when submitting the form.


text:
Q: Responsive bootstrap menu issues So my app has a primary menu and then once a user is logged in, a secondary menu. Works fine and looks fine with full size (first image shown). When my app hits its media queries as shown in code below, thats why things are getting messed up and despite my best efforts, I am having issues. Let me show images and then tell more of what is happening after.
So at full screen with user logged in, both menus show as:

But then when go to a tablet size of 768px in width, this is where the issues start. You can see that the drop down arrow not right for top menu, and secondary menu, no arrow at all. You can also see that the text that shows for the top menu has a bad z-index despite my updates and changes.

So my menu (outside of the angular injection for what shows) is mainly in the index.html for the top menu, then the secondary (as shown in the code) gets brought in via a partial.

            <button class="btn btn-success navbar-toggle" ng-click="navbarExpanded = !navbarExpanded">

            </button>

admin

benefits we offer

enrollment
`

forms

faq

IIAS merchant list

about us

contact us

log out

admin

products + services

about us
`

testimonials

careers

news

blog

contact us

log out

You can see in the div with the ng-include, I am calling the partial and that code is:

                Participants Home

                Benefits We Offer

                        Medical Flexible Spending Arrangement

                        Dependent Care Assistance Program

                        FSA vs. HSA Comparison

                Benefits & Info

                        Health Care FSA

                        Day Care FSA

                        Limited Health Care FSA

                        Health Savings Account (HSA)

                        GoNavia Commuter Benefits

                        Health Reimbursement Arrangement (HRA)

                        Direct Reimbursement Plan

                        COBRA

                Tools & Resources

                        Expenses

                        Navia Debit Card

                        MyNavia Mobile App

                        Tax Savings Calculator

                Tools & Resources

                        Expenses

                      Navia Benefits Debit Card

                        MyNavia Mobile App

                        FlexConnect

                        Online Claim Submission

                        Online Debit Card Substantiation

                        Tax Savings Calculator

                        Tutorial Videos

                        FAQ

                        Forms & Documents

And finally, with my over rides to bootstrap for color, font, etc..., my CSS is as (took out the media breakpoints as none were working as expected):
.navbar {
    background-color: #ffffff;
    height: 60px;
    color: #000000;
    font-size: 15px;
    font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', 'Arial', 'sans-serif';
    border: none;
    margin-bottom: 0px;
}

.navbarSecondary {
    background-color: #ab2328;
    height: 66px;
    color: #000000;
    padding-left: 0px;
}

.navbarSecondary > li.dropdown.open > ul {
    background-color: #2dccd3;
    color: #ffffff;
}

.navbar.navbarSecondary.navbar-inverse.ng-scope > div > div > div > ul > li > a:hover, .navbar.navbarSecondary.navbar-inverse.ng-scope > div > div > div > ul > li > a:active, .navbar.navbarSecondary.navbar-inverse.ng-scope > div > div > div > ul > li > a:focus {
    background-color: #68070b;
}

.navbarSecondary.navbar-inverse.ng-scope > div > div > div > ul > li > a {
    font-size: 20px;
    padding: 20px 25px 20px 25px;
    color: #ffffff;
}

#signOut {
    padding: 6px 10px;
    background-color: #ab2328;
    color: #ffffff;
    margin-top: 10px;
}

#signOut:hover, #signOut:active {
    background-color: #68070b;
}

.sub-menu {
    background-color: #2dccd3;
    padding-top: 18px;
    padding-bottom: 18px;
}

.sub-menu > li > a {
    color: #ffffff;
    font-size: 12px;
    line-height: 15.6px;
    padding: 8px 25px 8px 40px;
}

.sub-menu > li > a:hover {
    background-color: #24a4a9;
    color: #ffffff;
}

.navbar-inverse .navbar-nav > li >a {
    color: #2d3130;
}

.navbar-inverse .navbar-nav > li > a:hover, .navbar-inverse .navbar-nav > li > a:active {
    color: #ab2328;
}

I have tried asnd tried using chrome dev tools and setting media breakpoints to no avail to get this work. Am hoping some of you can chime and in give some help. Is much appreciated.


text:
Q: how to do popup's like facebook does in google chrome Say I have facebook open in one tab and am currently active in another. If I get a notification on facebook I get a weird popup from the browser. Here's a picture:

Google does these same types of notifications when you get IM's. My question is...  how do they do this?

A: They use Chrome's desktop notification feature.
Check out an example here:
Chrome desktop notification example
P.S: You have to allow a site to show you desktop notifications. You will get a prompt near the address bar in Chrome, the first time a site tries to show you desktop notification.


text:
Q: numpy/ndarrayobject.h: No such file or directory I am trying to compile a project using cmake. This is the relevant CMakeLists.txt code snippet.
set(PYTHON3_NUMPY_INCLUDE_DIRS=/usr/local/lib/python3.6/dist-packages/numpy/core/include/)
set(PYTHON_INCLUDE_DIRS ${PYTHON_INCLUDE_DIRS} /usr/local/lib/python3.6/dist-packages/numpy/core/include)
find_package(Python COMPONENTS Interpreter Development)
find_package(PythonLibs REQUIRED)
...
include_directories( ${PYTHON_INCLUDE_DIRS} )

To ensure that it is working properly, I print the relevant info
execute_process ( COMMAND ${PYTHON_EXECUTABLE} -c "import numpy; print(numpy.get_include())" OUTPUT_VARIABLE NUMPY_INCLUDE OUTPUT_STRIP_TRAILING_WHITESPACE)
message (STATUS "NUMPY_INCLUDE: " ${NUMPY_INCLUDE})

This is how I compile
cmake -DPYTHON_EXECUTABLE=/usr/bin/python3 .

Here is my output of cmake, the relevant bits.
-- Found Python: /usr/bin/python3.6 (found version "3.6.9") found components:  Interpreter Development
-- Found PythonLibs: /usr/lib/x86_64-linux-gnu/libpython3.6m.so (found version "3.6.9")
-- NUMPY_INCLUDE: /usr/local/lib/python3.6/dist-packages/numpy/core/include

So far everything is perfect and numpy is found.
However, on running make, I get the following
 fatal error: numpy/ndarrayobject.h: No such file or directory
 #include <numpy/ndarrayobject.h>

From what I can see I've covered all bases, yet I'm getting this error. What do I do?


text:
Q: Paint JLabel above another JLabel without JLayeredPane Here's my application structure :
one JFrame ---> which contain one Board1 (Board1 extends JPanel) ---> which contains some "Zone" (Zone extends JLabel with FlowLayout manager) ----> which contain some "Personnage" (extends JLabel)
First I create all my JLabels in the JPanel's class:
public class Board1 extends JPanel implements Board {
  private List<Zone> zones = new ArrayList<Zone>();
  private List<Personnage> personnages = new ArrayList<Personnage>();

  public Board1() {
    this.setLayout(null);
    zones.add(new Zone(1, false, true, null, "/zone1D1C.jpg", this));
    zones.add(new Zone(2, false, false, null, "/zone2D1C.jpg", this));
    zones.add(new Zone(3, false, false, null, "/zone3D1C.jpg", this));
    zones.add(new Zone(4, true, false, null, "/zone4D1C.jpg", this));
    zones.add(new Zone(5, false, false, null, "/zone5D1C.jpg", this));
    zones.add(new Zone(6, true, false, null, "/zone6D1C.jpg", this));
    zones.add(new Zone(7, true, false, null, "/zone7D1C.jpg", this));
    zones.add(new Zone(8, false, false, null, "/zone8D1C.jpg", this));
    personnages.add(new Survivant("Phil", zones.get(0), 3, "/phil.jpg"));
    for (Zone zone : zones) {
        this.add(zone);
        for (Personnage personnage : zone.getPersonnages()) {
            zone.add(personnage);
        }
    }
  }

  public void move_personnage(Zone zone) {
    running_personnage.moveZone(zone);
    zone.add(running_personnage);
    this.repaint();
  }

  public void try_add_personnage() {
    Personnage douglas = new Survivant("Douglas", zones.get(3), 3, "/douglas.jpg");
    zones.get(3).add(douglas);
    this.repaint();
  }
}

The constructor is working good, I see my "personnage" above the "zone".
move_personnage method is working too !!! It remove automatically the personnage from the previous zone.
The problem is when I'm running try_add_personnage method, there is no JLabel above the zone. However I checked that the method is called etc...
Whatever I do after the Board1 constructor, I can't add any kind of new visible Personnage above Zone.
I guess it's with paintComponent method or something like this, but I didn't find the solution.
I know that's possible with JLayeredPane but I don't want to use it because I will use a GridBagLayout manager for the board in the future.
I Hope I was understandable

A: I found the solution.
It was my repaint which wasn't enough, I had to make JPanel.revalidate(); and after JPanel.repaint();


text:
Q: Is the mean of a continuous random variable $X$ equal to its median? If we assume $X$ to be a normal distributed random variable, then we can prove than $\Bbb P(X<mean) = \Phi(0) = 0.5$. This is true for any symmetric distribution.
I'm not sure how to prove/disprove it for an asymmetric (around mean) PDF. We're basically trying to see if mean is always the $50\%$ percentile.

A: Let $X \sim \operatorname{Exp}(1)$. The mean is $$E[X]=1 ,$$
while the median is $\log(2)$.

A: Let $\mathsf{P}(X=-1)=\frac{n}{n+1}$ and $\mathsf{P}(X=n)=\frac1{n+1}$.
Then $\mathsf EX=0$ so:$$\mathsf{P}(X<\mathsf EX)=\frac{n}{n+1}$$
Look what happens for a large $n$.

A: Hint: take the density function $f(x) = 2x$ for $0\le x\le 1$ and $0$ otherwise. Can you calculate median and mean?


text:
Q: Angular2 SVG filter url I'm using Angular2 + D3 to create a chart.
I'd like to apply an svg filter to the bars in order to create a drop-shadow effect.
While the filter is created and the bars have a filter: url("#dropshadow") style applied, the shadow does not render.
Could this be due to Angulars single page and the url() not finding the filter? What would be the correct way to work around this issue?

A: I finally figured it out. The best solution seems to be to inject the Location via
import { Location } from '@angular/common';
...
constructor(private location: Location)

and then use it to specify the path for the url()
.style('filter', 'url(' + this.location.path() + '#drop-shadow)')

Now it works as expected.

A: In case some one arrives here and this isn't clear enough here is what i did for any url used in <svg> with Safari:
In my components i import Location
import { Location } from '@angular/common';

...
  constructor(private location: Location) {
  }

  url(id: string) {
    return `url(${this.location.path()}${id}`;
  }

}

Then use it in the inline <svg> tags as follows
[attr.filter]="url('#filter-11')"

[attr.clip-path]="url('#clip')"


text:
Q: How to put the link to the last created quiz in the email that will be sent to all users automatically? I could be able to let the web application sends automatic emails using Windows Task Scheduler. Now I want to put the link to last created quiz by admin in that email. How to do that? Should I add any column in the Quiz table in the database?
The table schema:
Employee Table: Username, Name, Job, Email
Quiz Table: QuizID, Title, Description
My code-behind:
protected void Page_Load(object sender, EventArgs e)
    {
        SmtpClient sc = new SmtpClient("mail address");
        MailMessage msg = null;

        try
        {
            msg = new MailMessage("xxxx@gmail.com",
                "yyyy@gmail.com", "Message from PSSP System",
                "This email sent by the PSSP system");

             sc.Send(msg);
        }

        catch (Exception ex)
        {
            throw ex;
        }

        finally
        {
            if (msg != null)
            {
                msg.Dispose();
            }
        }
    }

A: If I understand correctly, you want to send an email to someone(maybe your customer), inside the email body, you want to have a link, when user click the link it will navigate user to your quiz through browser, is it right?
If the above assumption is right, you don't need to add a new column.
assume the asp.net page which you display quiz is quiz.aspx
http://www.XXXX.com/quiz.aspx?quizId=XXX
Just add the above link in your email body.
in quiz.aspx. you can get the quizId by request["quizId"],then read the related quiz from your database and display.


text:
Q: img onclick need to disable in my page ther's a  label which on it's content i am basing
a decision such as hide an disable a cupple of controls.
there's a
<img src="images/Delete.png" alt="delete"
   style="height: 18px; width: 24px; cursor:pointer"
   onclick="deleteRow('<%=row["tId"] %>');" id="imgBut_dltRow" />

i would like to undersand how can i disable the click event *or the img/button response
like in :
if(document.getElementById("LBL_isManager").value != "")
disable click event / or totaly disable this "imgBut_dltRow"

i couldnt disable it from code behind cause it has <% %> c# tags so i could not make it runat="server" too .
only option is ask for the label value if it's not empty ("") then
block that event.
thanks a lot !

A: Try this - DEMO
document.getElementById("imgBut_dltRow").addEventListener("click", function(e) {
    if ( document.getElementById("LBL_isManager").value != "" ) {
        e.stopImmediatePropagation();
    }
}, false);


text:
Q: symfony 1.4 - inject current logged in user into Doctrine model I would like to inject, with full testability, the id of the current logged in user into a creator_id field of a Doctrine_Record class, without using the sfContext singleton. I found a couple of Doctrine behaviours like http://www.symfony-project.org/plugins/sfDoctrineActAsSignablePlugin, but they access the sfContext singleton in a listener or (in another example I found) in the save method of a subclass of Doctrine_Record.
I want to find a single entry point in the symfony controller, where I can inject the current logged in user and keep it till the end of the request.
How do I do?
Hope I have been clear enough.
EDIT:
As @jeremy suggested, I made a custom filter:
class userFilter extends sfFilter
{
  public function execute($filterChain)
  {
    $user = $this->getContext()->getUser();
    if ($user->isAuthenticated()) {
      $guard = $user->getGuardUser();
      Doctrine_Manager::getInstance()->setAttribute('logged_in_user', $guard->getId());
    }

    // Execute next filter
    $filterChain->execute();
  }
}

So now my tests and my tasks are sfContext free, I just have to set the proper user Id at some point before starting the interactions with the db:
Doctrine_Manager::getInstance()->setAttribute('logged_in_user', sfConfig::get('default_user'));

A: Great question! The use of sfContext everywhere is one of the uglier aspects of Symfony 1 and setting it on Doctrine_Manager sounds like a solid idea.
It's probably best to do this either in the configureDoctrine callback that happens in ProjectConfiguration (see below). I'm not 100% a user is present at this point, if it's not, your best bet is a custom filter (reference).
public function configureDoctrine(Doctrine_Manager $manager)
{
  $manager->setParam('user_id', sfContext::getInstance()->getUser()->getGuardUser()->getId());
}

A: Thanks for raising this question. I wrote the http://www.symfony-project.org/plugins/sfAuditablePlugin with this in mind. I basically externalized the method that returns the userId so you can get the userId from session, doctrine parameter or wherever you have it.
Here are the settings to configure the method that returns an array containing user_id and user_name
  # Retrieve User Array from custom implementation
      # [0] => (int)user_id; [1] => (string)user_name;
  getUserArray:
    class_name: Utility
    static_method_name: getUserAuditArray


text:
Q: What happens to locks on objects passed to other threads? I'm not quite sure how to word this, so I'll just paste my code and ask the question:
private void remoteAction_JobStatusUpdated(JobStatus status) {
    lock (status) {
        status.LastUpdatedTime = DateTime.Now;
        doForEachClient(c => c.OnJobStatusUpdated(status));
        OnJobStatusUpdated(status);
    }
}

private void doForEachClient(Action<IRemoteClient> task) {
    lock (clients) {
        foreach (KeyValuePair<RemoteClientId, IRemoteClient> entry in clients) {
            IRemoteClient clientProxy = entry.Value;
            RemoteClientId clientId = entry.Key;
            ThreadPool.QueueUserWorkItem(delegate {
                try {
                    task(clientProxy);
#pragma warning disable 168
                } catch (CommunicationException ex) {
#pragma warning restore 168
                    RemoveClient(clientId);
                }
            });
        }
    }
}

Assume that any other code which modifies the status object will acquire a lock on it first.
Since the status object is passed all the way through to multiple ThreadPool threads, and the call to ThreadPool.QueueUserWorkItem will complete before the actual tasks complete, am I ensuring that the same status object gets sent to all clients?
Put another way, when does the lock (status) statement "expire" or cause its lock to be released?

A: Locks don't expire. When a thread tries to pass the lock statement it can only do it if no other thread is executing inside a lock block having a lock on that particular object instance used in the lock statemement.
In your case it seems that you have a main thread executing. It will lock both the status and the clients instances before it spins of new tasks that are executed on seperate threads. If any code in the new threads want to acquire a lock on either status or clients it will have to wait until the main thread has released both locks by leaving both lock blocks. That happens when remoteAction_JobStatusUpdated returns.
You pass the status object to each worker thread and they are all free to do whatever they want to do with that object. The statement lock (status) in no way protects the status instance. However, if any of the threads tries to execute lock (status) they will block until the main thread releases the lock.
Using two separate object instances to lock can lead to deadlock. Assume one thread executes the following code:
lock (status) {
  ...
  lock (clients) {
    ...
  }

}
Another thread executes the following code where the locks are acquired in the reverse sequence:
lock (clients) {
  ...
  lock (status) {
    ...
  }

}
If the first thread manages to get the status first and the second the clients lock first they are deadlocked and both threads will no longer run.
In general I would advice you to encapsulate your shared state in a separate class and make access to it thread safe:
class State {

  readonly Object locker = new Object();

  public void ModifyState() {
    lock (this.locker) {
      ...
    }
  }

  public String AccessState() {
    lock (this.locker) {
      ...
      return ...
    }
  }

}

You can also mark you methods with the [MethodImpl(MethodImpl.Synchronized)] attribute, but it has its pitfalls as it will surround the method with a lock (this) which in general isn't recommended.
If you want to better understand what is going on behind the scenes of the lock statement you can read the Safe Thread Synchronization article in MSDN Magazine.

A: The locks certainly don't "expire" on their own, the lock will be valid until the closing brace of the lock(..){} statement.


text:
Q: override existing files in Downloads on GitHub Is there a way to override the file in the Downloads section on GitHub when uploading a file with the same filename? (e.g. via developer API or the ruby script, etc) The reason is that I want to keep track of the number of downloads. Thanks!

A: I havn't tried this but it's possible that you could replace the file on Amazon S3. I don't know if it will work or if it's a one-time upload token you get without the posibility to delete the file.
See the API documentation for uploading a file on Github (which includes using the amazon s3 rest api to upload the file):
http://developer.github.com/v3/repos/downloads/
And API documentation for deleing a file on amazon s3:
http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTObjectDELETE.html
And API documentation for putting a file on amazon s3:
http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTObjectPUT.html


text:
Q: What word can express a (fictional) transformation of a physical object into its artistic representation? I am looking for a word similar to, or perhaps a generalization of, petrification/petrify.  Whereas petrification involves a transformation of a physical object into a statue, the idea I have in mind is a transformation of a physical object into a two-dimensional projection of itself.  Another similar word is made up within the video game Luigi's Mansion, in which physical ghosts are turned into paintings of themselves via the Ghost Portrificationizer machine, but neither portrificationization nor portrification are real words.
A word that applies broadly to any type of artistic representation would also work, but the word should suggest that the object gets consumed in the process of creating the art, unlike most or all art in the real world, which merely creates an artistic copy of the physical object.
Here are the thesaurus searches I've tried, with no helpful results:
https://www.thesaurus.com/browse/petrify
https://www.thesaurus.com/browse/petrified

A: As there is no such actual action possible, you could consider some similar concepts from other fields. For example reduce or reduction as in Dimensionality Reduction

Dimensionality reduction, or dimension reduction, is the transformation of data from a high-dimensional space into a low-dimensional space

Alternatively, you can use common words and specify the exact meaning in context:

*

*Flatten

*Collapse

A: You could use realise/realize, realisation/realization in the sense of "to make real"
"The ghosts are realized as paintings."
OED

I. To give real existence to something.
1.a. transitive. To make real or actual; to convert (something imagined, planned, etc.) into real existence or fact; to bring (a scheme, ambition, etc.) to fruition. Formerly also: †to show the reality or truth of (a statement) (obsolete). Frequently in passive.
1957   A. E. Stevenson New Amer. III. ii. 104   We cannot produce overnight an abundance of modern, well-lighted school buildings with plenty of capable and devoted teachers, where every child is free to realize his best self.
2004   Manch. Evening News (Nexis) 17 Feb. (Business section) 14   Our expansion plans couldn't be realised without more funding.

And the common "He left home and realised his dreams."

A: I don't think you will find a "real" word that encapsulates that concept; consider coining one; portrify, like used in the game, seems like a reasonable option.
there is a vaguely related idea in 'The Picture of Dorian Gray', where a magic  portrait ages instead of the protagonist


text:
Q: Ubuntu Partition deleted and got i386 file not found error My query might be looking similar to others which are already posted here and in other forums. But i didn't see exact problem what i am facing.
Here we go,
My mistakes:

*

*Tried to install windows 8.1 on dual boot system.

*In a hurry, forgot to change the boot options. So directly installed from the DVD which installed the Win8.1 OS in C drive by default. (Original Win7 is located here)

*Tried to format the other drives from Win8.1 OS after OS installation.

*Again unfortunately Ubuntu grub/OS got deleted, which lead me to grub rescue promt with next reboot.

*Tried the steps as mentioned in this link. But again and again a mistake done. Not followed all the steps. When i successfully rebooted i didnt update the grub. So, after one more reboot, it went to again grub rescue mode.

*This time, the above steps didn't work. It is saying i386-pc/normal.mod not found.
Can any one help me to do clean OS installation with entire Hard disk format. (i want to format my all partitions and install the OS)
Thanks and Regards
Partha

A: Assuming that you want to remove all the partitions to install Ubuntu, the following steps would assist you:
1) Insert the Ubuntu installation disc in the drive and boot it.
2) At the partitioning screen, choose Something else.
3) At the below prompt, select every partition you see in the list and press the "-" (minus) button to remove the partitions.

Now choose the partitions wisely (I recommend following this for a better understanding at the partition table: How to use manual partitioning during installation? before proceeding)
The link states all the important stuff you might want to go through for A SUCCESSFUL installation.
Good lucK!


text:
Q: Python: Break statements for while blocks import random
def get_num ():
return random.randrange (999,9999)

print ("{}".format (get_num ()))

 def get_user_input():
   while True:
    user_input = input
    print("Please enter a four digit number")

   return user_input
   if False:
       print ("Length of string:" , len (str))

Here in this piece of coding I am trying to make a random 4 digit number which will tell user whether or not s/he has guessed the right number (essentially),
specifically though: It will tell the user (at the end of the game) if s/he has guessed certain digits correctly but not which position.
I want 'break' statement to be fitted into this which will separate the while block from the if False. How do I do this correctly? I have tried maany times but I have 4 problems:
1- I don't know where to insert the break
2- When I run the program it doesn't print the second print function.
3- When I run the program it doesn't tell me the length of the string so I don't know if the user is even enterring the correct number of digits.
4- How do I set a limit on python (i.e. how many goes a player can have before the game ends?

A: I guess you are new to programming and this may be one of your very first codes. It would be great if you start by learning syntax of programming language which you have decided to use as well as working of loops, return statements, etc. I personally preferred reading any basic programming language book. For your case, it would be any book of python which is for beginners. For the sake of completeness, i have added the below code which is probably not exactly what you asked for:
import random
def get_num():
    return random.randrange (999,9999)

def get_user_input():
    user_input = int(input())
    return user_input

while True:
    comp_num = get_num()
    print("The computer gave: {}".format(comp_num))

    print("Your turn:")
    user_num = get_user_input()

    if user_num == comp_num:
        print("Done it!")
        break
    else:
        print("No, it's different. Try again!")
        print()

In the above code, there are two functions and a while loop. One of the functions takes input from the user while the other generates a random number. The while loop is set to run for infinite iterations in case the user doesn't give the same input as the computer. As soon as the user gives the same input as the computer (which is displayed on the screen before he is asked to give input), the if condition evaluates to true, some things are printed and the break statement breaks the loop. And since, there is no further code, the program terminates


text:
Q: Give Active class for current page I have used a datapager for my listview. And I want if the user is on 2nd page the number 2nd should be highlighted. The datapager code is here
.pagination {
  font-family: 'signika_negativeRegular', sans-serif;
  font-size: 13px;
}
.pagination a,
.pagination strong {
  background: #fff;
  /* display: inline-block; */
  margin-right: 3px;
  padding: 4px 12px;
  text-decoration: none;
  line-height: 1.5em;
  /* -webkit-border-radius: 3px; */
  -moz-border-radius: 3px;
  /* border-radius: 3px; */
  border: 1px solid#ccc;
}
.pagination a:hover {
  background-color: red;
  color: #fff;
}
.pagination a:active {
  background: #ccc;
  padding: 4px 6px;
}
.pagination strong {
  border: 1px solid #ccc;
  font-size: 13px;
  color: #cf060d;
}

HTML:

  <asp:DataPager ID="dpNews" runat="server" PagedControlID="lstNews" PageSize="3">
    <Fields>
      <asp:NextPreviousPagerField ButtonType="Link" ShowFirstPageButton="false" ShowPreviousPageButton="true" ShowNextPageButton="false" />
      <asp:NumericPagerField ButtonType="Link" />
      <asp:NextPreviousPagerField ButtonType="Link" ShowNextPageButton="true" ShowLastPageButton="false" ShowPreviousPageButton="false" />
    </Fields>
  </asp:DataPager>

Please help

A: You can try adding a new css style and then you can use the  CurrentPageLabelCssClass property to assign the css class like givenbelow
.pagination
    {
        font-family: 'signika_negativeRegular' , sans-serif;
        font-size: 13px;
    }

    .pagination a, .pagination strong
    {
        background: #fff; /* display: inline-block; */
        margin-right: 3px;
        padding: 4px 12px;
        text-decoration: none;
        line-height: 1.5em; /* -webkit-border-radius: 3px; */
        -moz-border-radius: 3px; /* border-radius: 3px; */
        border: 1px solid#ccc;
    }

    .pagination a:hover
    {
        background-color: red;
        color: #fff;
    }

    .pagination a:active
    {
        background: #ccc;
        padding: 4px 6px;
    }

    .pagination strong
    {
        border: 1px solid #ccc;
        font-size: 13px;
        color: #cf060d;
    }

    .current-page
    {
        background-color: red;
        color: #fff;
    }

HTML:

    <asp:DataPager ID="dpNews" runat="server" PagedControlID="ListView1" PageSize="3">
        <Fields>
            <asp:NextPreviousPagerField ButtonType="Link" ShowFirstPageButton="false" ShowPreviousPageButton="true"
                ShowNextPageButton="false" />
            <asp:NumericPagerField ButtonType="Link" CurrentPageLabelCssClass="current-page" />
            <asp:NextPreviousPagerField ButtonType="Link" ShowNextPageButton="true" ShowLastPageButton="false"
                ShowPreviousPageButton="false" />
        </Fields>
    </asp:DataPager>

Hope it helps :)


text:
Q: Computing a weight relative to 2 bounds I am trying to crack a trivial-for-some-of-us math problem with no success. End product should be a nice and clean Excel formula.
We consider here a monthly consumption of cups of coffee in an office. Each stop in the table is distant from the preceding by 200 cups. (i.e. headings read 200, 400, 600, etc. cups a month). For each of these stops, I calculated packaging costs related to the level of consumption we consider.
Issue is when we consider an intermediate consumption value, say 720 cups / month. This falls between 2 columns in the table. 720 is closer to 800 than it is to 600. The formula I am looking for would therefore be something like:

w * (packaging cost related to 600 cups /month) + w' * (packaging costs related to 800 cups / month)
Where : w (w=200-120/200 in our example) and w' = 1-w

Can't do this elegantly without a series of 'if's'… What would you do?

A: In order to round A1 down to the closest product of 200, you can use this:
=ROUNDDOWN(A1 / 200, 0) * 200

Similarly, you can use ROUNDUP.
Then, in order to calculate your w, you can use the following formula:
= 200 - (A1 - ROUNDDOWN(A1 / 200, 0) * 200) / 200

And then you're a VLOOKUP away from finding the relevant prices by their location in your pricing table.

A: How about this:

Formula in cell D4
=VLOOKUP(D2,A2:B7,2,1)+((VLOOKUP(D2+200,A2:B7,2,1)-VLOOKUP(D2,A2:B7,2,1))/200)*(D2-VLOOKUP(D2,A2:B7,1,1))

So, an interpolation formula, takes the price for the nearest lowest value and adds the amount extra necessary...

A: EDIT #2
Presume you have following named ranges:

*

*Consumption being a list of consumption thresholds sorted ascending;

*Costs being a list of prices for each consumption threshold;

*Consumed being the quantity of actual consumption.

*Bound being the 200 units of increment in your example.

Based on the following assumptions:

*

*If the consumed quantity is closer to the lower bound, we will only use the price of the lower bound;

*If the consumed quantity is closer to the higher bound, we will calculate a weighted average price using the following equation:

Weighted Average Price (WAP) = w * p + w' * p'

Based on the price list provided above from my example,

If the consumed quantity is 720
w = (200-120)/200 = 0.4
w' = 1 - w = 0.6
p = 80 being the cost for quantity 600
p' = 100 being the cost for quantity 800
WAP = 0.4 * 80 + 0.6 * 100 = 92

Given the structure of the price equation, it can be re-written using SUMPRODUCT function as below:
WAP = SUMPRODUCT({w,w'},{p,p'})

To find the range of quantity weights {w,w'} from the above formula, you can use the following array formula which needs to be confirmed by pressing Ctrl+Shift+Enter:
{=ABS({0,1}-(Bound-MOD(Consumed,Bound))/Bound)}

Here MOD function is used to find out the residual quantity above 600 which is 120. The subtraction from {0,1} will return {-0.4,0.6}, then use ABS function to turn all values into positive.

To find the price range {p,p'}, you can use another array formula which also needs to be entered using Ctrl+Shift+Enter:
{=INDEX(Costs,N(IF(1,MATCH(MROUND(Consumed,Bound),Consumption,0)-IF(MOD(Consumed,Bound)<100,{0,0},{1,0}))))}

Here I used MROUND function as suggested by @JvdV to find the closest bound and then use INDEX+MATCH to return the corresponding prices. The IF function will return either {0,0} or {1,0} which will determine if the looked up prices are from two bounds or from the same bound, which is depended on if the consumed quantity is closer to higher or lower bound.

Lastly, combined the above two array formulas within the SUMPRODUCT function as shown below:
{=SUMPRODUCT(ABS({0,1}-(Bound-MOD(Consumed,Bound))/Bound)*INDEX(Costs,N(IF(1,MATCH(MROUND(Consumed,Bound),Consumption,0)-IF(MOD(Consumed,Bound)<100,{0,0},{1,0})))))}

It is also an array formula which needs to be confirmed by pressing Ctrl+Shift+Enter in the formula bar.

If I change the consumed quantity to 650, based on my first assumption, the price should be 80 as shown below:

A: Sorry for the late reply. Have been away for a while. I need to thoroughly read / test your suggestions but before anything would like to thank you all for your kind help on that matter. You really rock ;)
Julien.