text:
Q: What does "! in C/C++ means What does !<number> in c means. For example !-2 or !3?
cout << !-2;

Output:
0

cout << !3;

Output:
0

A: ! is the logical negation operator. From the C Standard (6.5.3.3 Unary arithmetic operators)

5 The result of the logical negation operator ! is 0 if the value of
  its operand compares unequal to 0, 1 if the value of its operand
  compares equal to 0. The result has type int. The expression !E is
  equivalent to (0==E).

And from the C++ Standard (8.3.1 Unary operator)

9 The operand of the logical negation operator ! is contextually
  converted to bool (Clause 7); its value is true if the converted
  operand is false and false otherwise. The type of the result is bool.

So, for example, this expression
cout << !-2;

according to the C quote is equivalent to
cout << ( 0 == -2 );

In C the result of the operator has the type int while in C++ the result of the operator has the type bool.
Pay attention to that in C++ you may use the alternative token not. For example the above statement can be rewritten like
cout << not -2;

In C you can include the header <iso646.h> and use the macro not as an alternative record for the operator !.
And one more trick. If for example you want from a C function to return an integer expression preliminary converting it either exactly to 1 or to 0 you can write for example
return !!expression;

That is if expression is not equal to 0 then the first applying of the operator ! converts the expression to 0 and the second applying the operator ! converts the result expression to 1.
It is the same as if to write
return expression == 0 ? 0 : 1;

but more compact.

A: It's called a "logical not". The expression evaluates to false if the operand is nonzero and true if the operand is zero. Applying logical not to negative zero also returns true.

A: Unary operator ! is the logical negiation (i.e. NOT) operator. When the operand is true, the result is false  and when the operand is false, the result is true. Integers operand is implicitly converted to bool value. Zero is false and all other numbers are true.


text:
Q: apply user defined function to a list of lists in python I have a list of lists in which I want to return the contents of strings within each list that match specific keywords.
THIS IS ORIGINAL LIST:
list_orig = [['summary of the', 'cold weather', 'bother me over high'], ['what is in a name?', 'reveals a lot', 'juniper relationship']]

WANT TO APPLY THIS KEYWORD SEARCH:
keywords = ['summary', 'indicates','suggesting', 'relationship', 'reveals']

RESULT DESIRED:
list_refine = [['summary of the'], ['reveals a lot', 'juniper relationship']]

So far, i have the code to apply to a single list but I don't know how to look that over all the lists.
HERE IS CODE FOR ONE LIST:
string1 = list_orig
substr1 = keywords

def Filter(string, substr):
    return [str for str in string if
             any(sub in str for sub in substr)]

print(Filter(string1, substr1))

HERE IS RESULT FOR 1 LIST:
['summary of the']

I researched so many ways to loop over the lists of lists. Here is 1 attempt.
for item in string3:
     new.append([])
     for item in items:
        item = Filter(string1, substr1)
        new[-1].append(item)
item

just got a blank list
Thanks everyone! Appreciate it :)

A: You can use a for loop to iterate over the list and another for loop to iterate over the items and keywords like this,
list_orig = [['summary of the', 'cold weather', 'bother me over high'], ['what is in a name?', 'reveals a lot', 'juniper relationship']]

keywords = ['summary', 'indicates','suggesting', 'relationship', 'reveals']

list_refine = []

for l_inner in list_orig:
    l_out = []
    for item in l_inner:
        for word in keywords:
            if word in item:
                l_out.append(item)
    list_refine.append(l_out)
print(list_refine) # [['summary of the'], ['reveals a lot', 'juniper relationship']]

A: Here is an alternative solution without explicit loops
list_orig = [['summary of the', 'cold weather', 'bother me over high'], ['what is in a name?', 'reveals a lot', 'juniper relationship']]

def contains_keyword(sentence):
    keywords = ['summary', 'indicates','suggesting', 'relationship', 'reveals']
    return any([(kw in sentence) for kw in keywords])

list_refine = [
    (sentence for sentence in lst if contains_keyword(sentence))
    for lst in list_orig
]

redpajama_set_name: RedPajamaStackExchange


text:
Q: UWP Project: how to attach a drop shadow (Microsoft.Toolkit.Uwp.UI.AttachedShadowBase) to a UIElement in CODE Right, I have been using the old approach of doing DropShadows (ElementCompositionPreview...) in code.
That approach is marked DEPRECATED.
Using the new AttachedDropShadow is fine in XAML, but what about in C# code? I do not see any documentation on how to use this helper in straight C#. I want to attach it to a UIElement.
Any help?


text:
Q: Slow scroll on UITableView images I'm displaying lots of images loaded directly from my app (not downloaded). My table view is slow when I scroll it the first time. It becomes smooth after all my cell has been displayed. I don't really know why.
I have an array of UIImage that I'm loading in the viewDidLoad. Then in my tableview delegate I just get the image at a given index path and set it to an UIImageView of my cell.
Do you know how I can improve performances ?

A: just to share I have fixed and it worked very well Steps I followed.
1) Set the performSelectorInBAckground function with Cell as parameter passed that holds the scroll view or uiview to put many iamges.
2) In the background function load the image stored from application bundle or local file using imagewithContents of file.
3) Set the image to the imageView using this code.
    //// Start of optimisation - for iamges to load dynamically in cell with delay , make sure you call this function in performSelectorinBackground./////

    //Setting nil if any for safety
    imageViewItem.image = nil;

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);

    dispatch_async(queue, ^{
        UIImage *image = // Load from file or Bundle as you want

        dispatch_sync(dispatch_get_main_queue(), ^{

            //Set the image to image view not, wither cell.imageview or [cell add subviw:imageview later ]
            [imageViewItem setImage:image];
            [imageViewItem setNeedsLayout];
        });
    });

    //// End of optimisation/////

This will load all images dynamically and also scroll the table view quite smoothly than previous slow and jerky behaviour.
All the best

A: You can read the answer I have just submitted here:
Loading image from CoreData at cellForRowAtIndexPath slows down scrolling
The basic idea is to use Grand Central Despatch to move your table-view-image-getting code to a separate thread, filling in your cells back on the main thread as the images become available. Your scrolling will be super-smooth even if there's a delay loading the images into memory from the filesystem.

A: What I understand from your question is that your images are all set to go and that they are loaded into RAM (stored in an array which is populated in viewDidLoad). In this case, I would want to see the exact code in cellForRowAtIndexPath in order to help out. My instinct tells me that something is being done there that shouldn't be done on the main thread (as He Was suggests). The thing is - if it's only a fetch from an NSArray (worst case O(log(n))), you shouldn't be seeing a performance hit.
I know you're not downloading the images but I would still recommend to do ANY non-UI operation on a background thread. I wrote something that might help you out.


text:
Q: How to solve a particular initial-boundary value problem I have the following initial-boundary value problem
$$\begin{cases}\dfrac{\partial^2 u_1}{\partial x^2}=A_{11}\dfrac{\partial u_1}{\partial t}+A_{12}\dfrac{\partial u_2}{\partial t}\\\dfrac{\partial^2 u_2}{\partial x^2}=A_{21}\dfrac{\partial u_1}{\partial t}+A_{22}\dfrac{\partial u_2}{\partial t}\end{cases}$$
with $A_{12}=A_{21}$
Initial conditions
$$u_1(x,0)=c_1\\u_2(x,0)=c_2$$
for each $x$ such that $0<x<L$
Boundary conditions
$$u_1(0,t)=0\\u_2(L,t)=0\\\frac{\partial u_1}{\partial x}(L,t)=0\\\frac{\partial u_2}{\partial x}(0,t)=0$$
for each $t$ such that $t>0$
What I tried.
First I tried to solve the uncoupled system when $A_{12}=A_{21}=0$, to gain some knowledge. I found by separation of variables and using Fourier Series the following solution $\left(\text{with }\omega_m=\dfrac{(2m+1)\pi}{2L}\right)$:
$$
u_1(x,t)=\sum_{m=0}^\infty\frac{2 c_1}{\omega_m L}
  \exp\left({-\frac{\omega_m^2}{A_{11}}t}\right)\sin(\omega_m x)\\
u_2(x,t)=\sum_{m=0}^\infty(-1)^m\frac{2 c_2}{\omega_m L}
  \exp\left({-\frac{\omega_m^2}{A_{22}}t}\right)\cos(\omega_m x)
$$
Next, I tried to uncouple the original equations, by defining $u_i=P_{ij}v_j$, and found
$$
\frac{\partial^2 v_1}{\partial x^2}=
  \lambda_1\frac{\partial v_1}{\partial t}\\
\frac{\partial^2 v_2}{\partial x^2}=
  \lambda_2\frac{\partial v_2}{\partial t}
$$
where $\lambda_i$ are the eigenvalues of $A$, and the columns of $P$ are the eigenvectors.
By separation of variables I found
$$
v_i(x,t)=\exp\left(-\frac{\mu_i^2}{\lambda_i}t\right)\left(D_i^{+}\cos(\mu_i x)+D_i^{-}\sin(\mu_i x)\right)
$$
where the $\mu_i$ are positive constants to be fixed by the initial-boundary conditions.
The boundary conditions become
$$
u_1(0,t)=P_{11}v_1(0,t)+P_{12}v_2(0,t)=0\\
u_2(L,t)=P_{21}v_1(L,t)+P_{22}v_2(L,t)=0\\
\frac{\partial u_1}{\partial x}(L,t)
  =P_{11}\frac{\partial v_1}{\partial x}(L,t)
  +P_{12}\frac{\partial v_2}{\partial x}(L,t)=0\\
\frac{\partial u_2}{\partial x}(0,t)
  =P_{21}\frac{\partial v_1}{\partial x}(0,t)
  +P_{22}\frac{\partial v_2}{\partial x}(0,t)=0
$$
Writing down explicitly this system, it can be regarded as an algebraic homogeneous linear system in the $4$ unknown $D_i^\pm$, whose coefficients depend on $t$ and on the $\mu_i$. It should have a solution other than the trivial one, and this for each $t>0$.
Is this the right direction and where to go from here?
Is there a completely different approach I am missing?


text:
Q: How to run code on Android Studio with an Android API lower than 20? I'm writing the code for an app on Android Studio and when I try to run or debug the code, I'm not allowed and a message pops up saying "Instant run is not supported on devices with API levels 20 or lower". I'm using a Samsung Note 5 so it's not too old and I really don't know much about API levels. What should I do to run the code? Thanks.

A: You can disable Instant Run:
Android Studio -> Preferences -> Build, Execution, Deployment -> Instant Run and uncheck the box next to Enable Instant Run.
Please refer this link for more information: https://developer.android.com/studio/run/index.html

A: you can use android studio emulator or genymotion emulator to setup API level more than 20
here is a list of Android API levels
https://en.wikipedia.org/wiki/Android_version_history

A: just use emulator that bellow 20.
you can use default android studio emulator, or genymotion or any android emulator.
and 1 more thing is when you run ur apps dont use instant run.
but first you have to set ur api bellow 20 too.

A: First you have to connect your Android-device to the PC and have activated the Debugging mode. Don't deactivate the screen of your smartphone, but let it be activated and accessible.
If you had recently an error in your Android-Studio, then invalidate the cache and restart android studio. If you restart Android-Studio, wait at the beginning for Android-Studio to be done with all its processes in the background. After having started Android-Studio, go to the terminal and enter the following lines.
sudo apt-get install android-tools-adb

Then start server with
sudo adb start-server

It's essential, that you use "sudo". When starting server, then you'll get a question on your smartphone concerning the connection attempt. Check the checkbox and accept the connection. If you don't use the "sudo" keyword, then you'll get that error message.
If you've done everything properly, then you can click on the debug-sign and select your device as shown in the popup-list.
This is how it worked for me.


text:
Q: Compute the unix timestamp for the previous midnight How can you, in Java, compute the unix timestamp truncated to midnight?
PHP examples show making strings and then parsing them back.  There has to be a cleaner way to do it in Java than that, surely?

A: Unix timestamp starts from midnight UTC so we can do the following
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
long unixTimeStamp = c.getTimeInMillis() / 1000;

A: For unix timestamps you can create function like this:
public long getMidnightTimestamp(long timestamp)
{
    return timestamp - timestamp % 86400; // 24 * 60 * 60 sec in one day
}

And use it like this:
long currentTimestamp =  System.currentTimeMillis() / 1000;
long todayMidnightTimestamp = getMidnightTimestamp(currentTimestamp);

A: Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.set(Calendar.HOUR,0);
c.set(Calendar.MINUTE,0);
c.set(Calendar.SECOND,0);
c.set(Calendar.MILLISECOND,0);

long midnightUnixTimestamp = c.getTime().getTime()/1000;


text:
Q: How can I fix this JSON file? I want to create a JSON file which consists in this format: for each course name there are some categories and for each category there are some other details. My JSON file looks like:
[
   {
      "$id":"1",
      "name":"Business"{
      "cat":"CuberSecurity"{
         "img":"img3_1.jpg",
      "cat_kurs":"7-course specialization",
      "txt":"Rice University"
      },
    "cat":"Google Cloud Platform for Systems Operations"{
       "img":"img3_2.jpg",
      "cat_kurs":"6-course specialization",
      "txt":"University of California"
    }
      }
   },
   {
      "$id":"2",
      "name":"Computer Science"{

      "cat":"Fundamentals of Computing"{
      "img":"img3_1.jpg",
      "cat_kurs":"7-course specialization",
      "txt":"Rice University"
      },
      "cat":"Data Structures and algorithms"{
      "img":"img3_2.jpg",
      "cat_kurs":"6-course specialization",
      "txt":"University of California"
      },
      "cat":"Probabilistic Graphical Models"{
       "img":"img3_3.jpg",
      "cat_kurs":"3-course specialization",
      "txt":"Stanford University"
      },
      "cat":"Bioinformatics"{
      "img":"img3_4.jpg",
      "cat_kurs":"7-course specialization",
      "txt":"University of California"
      },
      "cat":"Algorithms"{
      "img":"img3_5.jpg",
      "cat_kurs":"4-course specialization",
      "txt":"Stanford University"
      }
    }
  }
]

I have seen it in an editor and I know it is full of mistakes. Please give me any idea how can I correct it.

A: I would recommend starting out with only a couple of lines and expanding it if the synxtax is correct, there are a lot of sites that can help you with this. Just google json online validator.
edit: small example:
[{
    "$id": "1",
    "name": "Business",
    "cat":
    [{
        "cname": "CyberSecurity",
        "img": "img3_1.jpg",
        "cat_kurs": "7-course specialization",
        "txt": "Rice University"
    }, {
        "cname": "Google Cloud Platform for Systems Operations",
        "img": "img3_2.jpg",
        "cat_kurs": "6-course specialization",
        "txt": "University of California"
    }]
}]

A: I think you should use a JSON validator when you are trying to create a JSON structure, is it really useful.
I fixed your JSON here:
[
   {
      "$id":"1",
      "name":"Business",
      "cat":[
         {
            "name":"CuberSecurity",
            "img":"img3_1.jpg",
            "cat_kurs":"7-course specialization",
            "txt":"Rice University"
         },
         {
            "name":"Google Cloud Platform for Systems Operations",
            "img":"img3_2.jpg",
            "cat_kurs":"6-course specialization",
            "txt":"University of California"
         }
      ]
   },
   {
      "$id":"2",
      "name":"Computer Science",
      "cat":[
         {
            "name":"Fundamentals of Computing",
            "img":"img3_1.jpg",
            "cat_kurs":"7-course specialization",
            "txt":"Rice University"
         },
         {
            "name":"Data Structures and algorithms",
            "img":"img3_2.jpg",
            "cat_kurs":"6-course specialization",
            "txt":"University of California"
         },
         {
            "name":"Probabilistic Graphical Models",
            "img":"img3_3.jpg",
            "cat_kurs":"3-course specialization",
            "txt":"Stanford University"
         },
         {
            "name":"Bioinformatics",
            "img":"img3_4.jpg",
            "cat_kurs":"7-course specialization",
            "txt":"University of California"
         },
         {
            "name":"Algorithms",
            "img":"img3_5.jpg",
            "cat_kurs":"4-course specialization",
            "txt":"Stanford University"
         }
      ]
   }
]

A: I have another small example, a little different.
{
  "courses": [
    {
      "id": "1",
      "categories": [
        {
          "cat_id": "1",
          "name": "Advanced Science",
          "date": "1234"
        },
        {
          "cat_id": "2",
          "name": "Advanced Math",
          "date": "1234"
        },
        {
          "cat_id": "3",
          "name": "Advanced History",
          "date": "1234"
        }
      ]
    },
    {
      "id": "2",
      "categories": [
        {
          "cat_id": "1",
          "name": "Advanced Science",
          "date": "1234"
        },
        {
          "cat_id": "2",
          "name": "Advanced Math",
          "date": "1234"
        },
        {
          "cat_id": "3",
          "name": "Advanced History",
          "date": "1234"
        }
      ]
    }
  ]
}


text:
Q: LWC as QuickAction in Salesforce I have made a quick action in lightning web component and want ot make that compponent available for quick action. I havenot found any guide or documentation regarding this. Can you please suggest on how to make the lwc available for quick action.

A: LWC can be directly used as a quick action. This is a pilot feature, available in the Spring '21 release.
https://help.salesforce.com/articleView?id=release-notes.rn_lwc_action.htm&type=5&release=230

A: [EDIT] Starting the Summer '21 release, you be able to use lightning web components directly as a Quick Action as described here.
You'll just need to set the myComponent.js-meta.xml metadata file accordingly:
<?xml version="1.0" encoding="UTF-8" ?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
   <apiVersion>52.0</apiVersion>
   <isExposed>true</isExposed>
   <targets>
       <target>lightning__RecordAction</target>
   </targets>
    <targetConfigs>
   <targetConfig targets="lightning__RecordAction">
     <actionType>Action</actionType>
   </targetConfig>
 </targetConfigs>
</LightningComponentBundle>

The original answer is still valid for some use cases where Lightning web components are not supported yet, like Global Actions. [/EDIT]
Original answer:
This is not supported yet. You can have a look to what's supported and what's not here.
What you can do is wrap your Lightning web component in an Aura component:
<aura:component implements="force:lightningQuickAction">
    <c:myLwc></c:myLwc>
<aura:component>

If you need to send events like force:closeQuickAction, you'll have to first send an event to the enclosing Aura component, so that it could fire this action. More on this here.

A: Now it's possible with Summer 21 release. Here is the link to release note.
https://releasenotes.docs.salesforce.com/en-us/summer21/release-notes/rn_lwc_quick_actions.htm?edition=&impact=

A: STEPS:

*

*create one action from set up and override that with aura
component

*create an aura component and place LWC inside of it

*in LWC i am using data service concept to load a record and update
that record.

here in below example i am updating two fields when they click on approve button.
note: this particular example not getting any data from UI we just changing the existing field values to another values inside java script file by data service concpet
Aura UI:
<aura:component
  implements="force:lightningQuickActionWithoutHeader,force:hasRecordId"
>
  <c:jJ_SFASampleRequestApproveLWC
    recordId="{!v.recordId}"
    onclose="{!c.closeQA}"
  ></c:jJ_SFASampleRequestApproveLWC>
</aura:component>

JS:
({
  closeQA : function(component, event, helper) {
    $A.get("e.force:closeQuickAction").fire();
  }
})

LWC UI:
<template>
  <template if:true={profilenamebool}>
    <template if:true={orderstatusbool}>

        Are you sure you want to approve this Sample Request?

        <lightning-button-group>
          <lightning-button
            label="Approve"
            onclick={approvehandler}
          ></lightning-button>
          <lightning-button
            label="Cancel"
            onclick={closeQuickAction}
          ></lightning-button>
        </lightning-button-group>

    </template>
    <template if:false={orderstatusbool}>

        Order is not in Pending Approval Status!

    </template>
  </template>
  <template if:false={profilenamebool}>

      You can not perform this operation

  </template>
</template>

LWC JS UI:
import { LightningElement, api, wire } from 'lwc'
import { ShowToastEvent } from 'lightning/platformShowToastEvent'
import {
  getRecord,
  getFieldValue,
  getFieldDisplayValue,
  updateRecord,
} from 'lightning/uiRecordApi'

import SAMREQID from '@salesforce/schema/Inventory_Order_vod__c.Id'
import ORDERSTATUS_FIELD from '@salesforce/schema/Inventory_Order_vod__c.Order_Status_vod__c'
import APPROVED_FIELD from '@salesforce/schema/Inventory_Order_vod__c.Approved_vod__c'
import USER_ID from '@salesforce/user/Id' // this is how you will retrieve the USER ID of current in user.
import USERPROFILENAME_FIELD from '@salesforce/schema/user.Profile.Name'

export default class JJ_SFASampleRequestApproveLWC extends LightningElement {
  @api recordId
  userid = USER_ID
  orderstatus
  approved
  userprofilename
  profilenamebool
  orderstatusbool

  @wire(getRecord, { recordId: '$userid', fields: [USERPROFILENAME_FIELD] })
  userdetails({ error, data }) {
    if (data) {
      this.userprofilename = getFieldValue(data, USERPROFILENAME_FIELD)

      if (
        this.userprofilename === 'JNJ Sampling Administrator' ||
        this.userprofilename === 'System Administrator'
      ) {
        this.profilenamebool = true
      } else {
        this.profilenamebool = false
      }
    } else if (error) {
      this.error = error
      console.error('Error ', this.error)
    }
  }

  @wire(getRecord, {
    recordId: '$recordId',
    fields: [ORDERSTATUS_FIELD, APPROVED_FIELD],
  })
  wiredRecord({ error, data }) {
    if (data) {
      this.orderstatus = getFieldDisplayValue(data, ORDERSTATUS_FIELD)
      this.approved = getFieldValue(data, APPROVED_FIELD)

      if (this.orderstatus === 'Pending Approval') {
        this.orderstatusbool = true
      } else {
        this.orderstatusbool = false
      }
    } else if (error) {
      this.error = error
      console.error('Error ', this.error)
    }
  }

  approvehandler() {
    if (
      this.userprofilename === 'JNJ Sampling Administrator' ||
      this.userprofilename === 'System Administrator'
    ) {
      if (this.orderstatus === 'Pending Approval') {
        this.orderstatusbool = true

        const fields = {
          [SAMREQID.fieldApiName]: this.recordId,
          [ORDERSTATUS_FIELD.fieldApiName]: 'submitted',
          [APPROVED_FIELD.fieldApiName]: true,
        }

        updateRecord({ fields })
          .then(() => {
            this.dispatchEvent(
              new ShowToastEvent({
                title: 'Success',
                message:
                  'Approved the Pending for Approval Inventory Order records successfully!',
                variant: 'success',
              })
            )
          })
          .catch((error) => {
            this.dispatchEvent(
              new ShowToastEvent({
                title: 'Error updating record',
                message: error.body.message,
                variant: 'error',
              })
            )
          })
          .finally(() => {
            this.closeQuickAction()
          })
      }
    }
  }

  closeQuickAction() {
    const closeQA = new CustomEvent('close')
    this.dispatchEvent(closeQA)
  }
}

LWC - META DATA
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
  <apiVersion>49.0</apiVersion>
  <isExposed>true</isExposed>
  <targets>
    <target>lightning__AppPage</target>
    <target>lightning__RecordPage</target>
    <target>lightning__HomePage</target>
    <target>lightning__UtilityBar</target>
  </targets>
</LightningComponentBundle>


text:
Q: smooth images whlie translation in android I am trying to translate an image from one position to another while user drags that image, the image is moving but it's not moving accurate and it's just jumping, please help me because I am new to android. Below is my XML File and followed by java code. Thank you..
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >

 <ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="230dp"
    android:layout_marginTop="100dp"
    android:layout_marginRight="400dp"
    android:layout_marginBottom="100dp"
    android:background="#000000"
    android:src="@drawable/desert" />

 <ImageView
    android:id="@+id/imageView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/imageView1"
    android:layout_alignTop="@+id/imageView1"
    android:layout_alignRight="@+id/imageView1"
    android:layout_alignBottom="@+id/imageView1"
    android:layout_margin="10dp"
    android:layout_toRightOf="@+id/imageView1"
    android:src="@drawable/logo" />

<ListView
    android:id="@android:id/list"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="800dp" >
</ListView>

</RelativeLayout>

Java File
public class Display extends ListActivity implements OnTouchListener
{
ArrayList<String> listimages;
ListView images;
ImageView imgback,imgfront;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.display);
    images=(ListView) findViewById(android.R.id.list);
    listimages=new ArrayList<String>();
    listimages.add("/Pictures/Chrysanthemum.jpg");
    listimages.add("/Pictures/Koala.jpg");
    setListAdapter(new listAdapter(getApplicationContext(), listimages));

    imgback=(ImageView) findViewById(R.id.imageView1);
    imgfront=(ImageView) findViewById(R.id.imageView2);
    //imgback.setImageBitmap("From Camera");

    //Matrix mat=new Matrix();

}

@Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
    super.onListItemClick(l, v, position, id);
Toast.makeText(getApplicationContext(), "Image:    "+String.valueOf(position)+"

    Clicked", Toast.LENGTH_LONG).show();
    if(position==0)
    {
    imgfront.setImageBitmap(getbitmap("/sdcard/Pictures

             /Koala.jpg"));
        imgfront.setOnTouchListener(this);
    }
    else if(position==1)
    {
        imgfront.setImageBitmap(getbitmap("/sdcard/Pictures

             /Chrysanthemum.jpg"));
    }
}

public Bitmap getbitmap(String path)
{
    Bitmap bitmap=BitmapFactory.decodeFile(path);
    return bitmap;
}

@Override
public boolean onTouch(View arg0, MotionEvent arg1)
{
    Toast.makeText(getApplicationContext(), "Touch Event Occured",

     Toast.LENGTH_LONG).show();
    Toast.makeText(getApplicationContext(), "x value:

    "+String.valueOf(arg1.getX())+" Y value: "+String.valueOf(arg1.getY()),

      Toast.LENGTH_LONG).show();

    imgfront.setTranslationX(arg1.getX());
    imgfront.setTranslationY(arg1.getY());

    return true;
}

 }

A: use
imgfront.setTranslationX((arg1.getRawX() - imgfront.getWidth())/2);
imgfront.setTranslationY((arg1.getRawY() - imgfront.getHeight())/2);


text:
Q: Data-structure to be store in array
where GF : Grand father
      f1,f2,f3 : Father
      c1,c2,c3  : children
Q1. How to store this data structure in an array
Q2. Using above array , how to access all child elements ,ONLY?

A: I think this does it
#include <iostream>
using namespace std;

struct Father
    {
        char* Child1;
        char* Child2;
        char* Child3;
    };

struct Grandfather
{
    Father Father1 ;
    Father Father2;
    Father Father3;
};

const int MAXARRAYSIZE = 20;
Grandfather Grandfathers[MAXARRAYSIZE];

int main()
{
    Grandfathers[0].Father1.Child1 = "The smart";
    Grandfathers[0].Father1.Child2 = "the brave";
    Grandfathers[0].Father1.Child3 = "the free";

    Grandfathers[0].Father2.Child1 = "The good";
    Grandfathers[0].Father2.Child2 = "the bad";
    Grandfathers[0].Father2.Child3 = "the ugly";

    Grandfathers[0].Father3.Child1 = "The boy";
    Grandfathers[0].Father3.Child2 = "the girl";
    Grandfathers[0].Father3.Child3 = "the other boy";

    //To print the children
    int CurrentArraySize = 1; //i can be changed with user input to accomodate more users for example, if there are 3 elements to the Grandfathers array i.e 3 different trees change CurrentArraySize to 3
    for(int i = 0; i < CurrentArraySize; i++)
    {
        cout<<"Children under Father1 are : "<<Grandfathers[i].Father1.Child1<<", "<<Grandfathers[i].Father1.Child2<<" and "<<Grandfathers[i].Father1.Child3<<endl;
        cout<<"Children under Father2 are : "<<Grandfathers[i].Father2.Child1<<", "<<Grandfathers[i].Father2.Child2<<" and "<<Grandfathers[i].Father2.Child3<<endl;
        cout<<"Children under Father3 are : "<<Grandfathers[i].Father3.Child1<<", "<<Grandfathers[i].Father3.Child2<<" and "<<Grandfathers[i].Father3.Child3<<endl;

    }
    system("pause");
}


text:
Q: Transform translate caused element to loose width Parent div is absolute, child div contains iframe. I want iframe to expand. I have managed to achieve this by setting child to fixed position.
However, what is causing a problem is that I have some transform translate on parent div and this causes iframe to loose width again. I cannot modify or remove this translate which is complicated (like transform: translate(836.152px, 253.619px) translateZ(9999px) rotate(0deg))
Demo here:
http://jsfiddle.net/5bk6dn7y/1/
Everything works well if you remove translate, but again I cannot modify or remove this.
One fix it to add:
iframe {
  width: 1000%;
}

but this is not a solution because on small screen, it will not automatically shrink to max screen width.
Full code, use jsfiddle instead because this snippet wont play youtube in iframe.

#a {
  position: absolute;
  background: red;
  top: 50px;
  transform:translateX(10px);
}

#b {
  position: fixed;
  width: 100%;
  background: blue;
  max-width: 400px;
}

iframe {
  width: 100%;
  height: 200px;
}


text:
Q: how to handle interrupts in qnx? /*kernel calls attach the interrupt function handler to the hardware interrupt specified by intr(i.e irq) */
  // InterruptAttach() : Attach an interrupt handler to an interrupt source
  // interrupt source is handler1 for this example
 void ConfigureISR(void)   //void *ISR (void *arg)
  {

/*  the software must tell the OS that it wishes to associate the ISR with a particular source of //interrupts. On x86 platforms, there are generally 16 hardware Interrupt Request lines (IRQs) */
  StartInterruptTime = GetTimeStamp();   //startTime of the interrupt

  volatile int irq = 7;   //0 : A clock that runs at the resolution set by ClockPeriod()

  ThreadCtl (_NTO_TCTL_IO, NULL);  // enables the hardware interrupt
  id1 = InterruptAttach(irq, &ISR, NULL, 0, 0);    // ISR is the interrupt service routine

  //sleep(20);

  }
int main ()
{
ConfigureISR();
return 1;
}

I created a interrupt handler on the server side to handle the interrupt from the client side. but the above code is breaking at the interrupt attach function call. could someone tell me why is it breaking ?? Is it the right way to handle interrupts in user application.


text:
Q: Leopard Mail app keyboard shortcut I've recently switched to Chrome for developing and have thus started using the build-in Developer Tools instead of my previously preferred Firebug workflow. Just today I found a keyboard shortcut (Command-Shift-I) that jumps straight to Inspect Element rather than just opening the Developer Tools like Command-Option-I does.
The problem I'm having is that this shortcut also opens the Mail app, which I do not use. I've looked in the Keyboard Shortcuts preferences and I don't see the aforementioned shortcut anywhere. Anybody know where I can disable this shortcut?

A: Command + Shift + C  Will open up the inspector, and let you click an object to Inspect.
https://superuser.com/questions/175529/google-chrome-keyboard-shortcut-to-view-resources-inspect-element

A: hotkeys for Chrome on Mac OS X (from here):

*

*Command ⌘ + Option ⌥ + I to open Developer Tools

*Command ⌘ + Option ⌥ + J to open Developer Tools and bring focus to the Console.

*Command ⌘ +  Shift ⇧ + C to toggle Inspect Element mode.


text:
Q: How to get link from Array level? How to get object reference(link) from object array(levelArray)? F.e., levelArray has created object "Level1" under index 1, and I need to change variables in that object. How to do it?
public class LevelEditorScreen implements Screen {

    final Drop game;
    private Batch batch;
    private Array<Level> levelArray;
    private int levelCount;

    private void createLevel(int lvlCount) {
        levelCount += 1;
        lvlCount = levelCount;
        levelArray.add(new Level());

    }
}

A: If you know the index you can use get(int index) method.
levelArray.get(0); //This will return object of index 0

If you don't know the index, but you know that some variable is set to specific value you can do this to get desired object:
In this example Level has variable String name
for(Level level : levelArray) {
    if(level.name.equals("Awesome level")) {
        //We found desired level!
    }
}


text:
Q: Model value is getting null when form post I populate my model and pass that model to view from action method. with for loop in view I generate radio button based on model.
just see this code. here I populate my model manually and pass to view from action method.
[HttpGet]
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            var student = new StudentModel
            {
                FirstName = "Rion",
                LastName = "Gomes",

                //I think the best way to populate this list is to call a service here.
                Sex = new List<Sex>
                {
                    new Sex{ID="1" , Type = "Male"},
                    new Sex{ID="2" , Type = "Female"}
                }
            };

            return View(student);
        }

based on Sex property I generate no of radio button in loop and when I select any radio button and click on form submit then form data properly deserialize to my model in action method but when I am checking the sex property then I saw it is showing null value. I am new in mvc and not being able to understand why my sex property is getting null when form submit to action.
here is my full code and please tell me where I am making mistake. thanks
controller code
public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            var student = new StudentModel
            {
                FirstName = "Rion",
                LastName = "Gomes",

                //I think the best way to populate this list is to call a service here.
                Sex = new List<Sex>
                {
                    new Sex{ID="1" , Type = "Male"},
                    new Sex{ID="2" , Type = "Female"}
                }
            };

            return View(student);
        }

        [HttpPost]
        public ActionResult Index(StudentModel model)
        {
            if (ModelState.IsValid)
            {
                //TODO: Save your model and redirect
            }

            //Call the same service to initialize your model again (cause we didn't post the list of sexs)
            return View(model);
        }
        public ActionResult About()
        {
            return View();
        }
    }

model code
public class StudentModel
    {
        [Required(ErrorMessage = "First Name Required")] // textboxes will show
        [Display(Name = "First Name :")]
        [StringLength(5, ErrorMessage = "First Name cannot be longer than 5 characters.")]
        public string FirstName { get; set; }

        [Required(ErrorMessage = "Last Name Required")] // textboxes will show
        [Display(Name = "Last Name :")]
        [StringLength(5, ErrorMessage = "Last Name cannot be longer than 5 characters.")]
        public string LastName { get; set; }

        public List<Sex> Sex { get; set; }
      }

    public class Sex
    {
        public string ID { get; set; }
        public string Type { get; set; }
    }

here is my view code.
@model MvcRadioButton.Models.StudentModel
@{
    ViewBag.Title = "Home Page";
}
@using(Html.BeginForm())
{

        @Html.LabelFor(model => model.FirstName)
        @Html.EditorFor(model => model.FirstName)
        @Html.ValidationMessageFor(model => model.FirstName)

        @Html.LabelFor(model => model.LastName)
        @Html.EditorFor(model => model.LastName)
        @Html.ValidationMessageFor(model => model.LastName)

    foreach (var Sex in Model.Sex)
    {

                @Html.RadioButtonFor(model => model.Sex, Sex.ID, new { @id = ("sex" + Sex.ID) })
                @*@Html.Label("Sex", sex.Type)*@
                @Html.Label("sex" + Sex.ID, Sex.Type)

    }
   <input type="submit" value="Submit" />
}

also guide me how could I set validation on my sex property. if anyone try to submit form without selecting any radio button then a message will display. thanks please guide that where I am making mistake.

A: you are only posting student model make a view model
like here
public class StudentDetailViewModel
    {
        public Student Student { get; set; }
        public Sex Sex { get; set; }
    }

and use this model in your index method to pass values to view also change name of model in view like following
StudentDetailViewModel studentvm = new StudentDetailViewModel();
studentvm.Student.firstname = -----------;
studentvm.Sex.Type = ----------;
return View(studentvm);
@model MvcRadioButton.Models.StudentDetailViewModel

on submit also post viewmodel to your post method


text:
Q: .NET MVC - build complex List I'm sorry if I don't quite know how to word this.  I know how I would do this in PHP but not .net MVC.
In short, I need to grab categories from multiple tables.  I know in PHP I would do something like build a new object, then add an array to the object.  For example, I need to be able to build something so I can return it to the view and iterate through it.  So something like:
categoryType1
    subcategoryType1 (also has ID, name, description)
        subsubCategoryType1 (also has ID, name, description)
        subsubCategoryType2 (also has ID, name, description)
        subsubCategoryType3 (also has ID, name, description)
    subcategoryType2 (also has ID, name, description)
        subsubCategoryType1 (also has ID, name, description)
        subsubCategoryType2 (also has ID, name, description)
        subsubCategoryType3 (also has ID, name, description)
categoryType2
    subcategoryType1 (also has ID, name, description)
        subsubCategoryType1 (also has ID, name, description)
        subsubCategoryType2 (also has ID, name, description)
        subsubCategoryType3 (also has ID, name, description)
    subcategoryType2 (also has ID, name, description)
        subsubCategoryType1 (also has ID, name, description)
        subsubCategoryType2 (also has ID, name, description)
        subsubCategoryType3 (also has ID, name, description)

Right now, I have one less level, so it looks like this:
In the model:
public class LayoutViewModel
{
    public int ID { get; set; }
    public string Category { get; set; }
    public IEnumerable<string> OutcomeType { get; set; }
    public string Identifier { get; set; }
}

In the controller:
public PartialViewResult _Sidebar()
    {
        var category1 = db.Category1.Where(oa => oa.Category != "")
            .GroupBy(oa => oa.Category).Select(oa => new LayoutViewModel
            {
                Category = oa.Key,
                Identifier = oa.Key.Replace(" ", "-").ToString(),
                SubCategory = oa.Select(y => y.SubCategory).Distinct()
            });
        return PartialView("_Sidebar", category1);
    }

But the above example is only one.  I need to do this multiple times but still return all of them together as one object (list?) to the view.


text:
Q: Pasar valor de @Html.Checkbox vía @Ajax.ActionLink ASP. NET MVC Tengo 3 ActionLinks y un checkbox en un Razor:

Ordenar por:

        @Ajax.ActionLink("Nombre", "Index", "Productos", new { orderby = "name", pagenumber = 0, category = @ViewBag.Category, keywords = @ViewBag.Keywords, orderType = ""}, new AjaxOptions { LoadingElementId = "loading-container", HttpMethod = "POST", UpdateTargetId = "contenedor-catalogo", OnSuccess = "loadImages()" }, new { @class = "btn " + ((ViewBag.OrderBy != null && ViewBag.OrderBy != "" && ViewBag.OrderBy != "name") ? defaultType : selectedType) + " btn-xs js-data-order btn-order _default", @data_order_id = "name" })

        @Ajax.ActionLink("Categoría", "Index", "Productos", new { orderby = "category", pagenumber = 0, category = @ViewBag.Category, keywords = @ViewBag.Keywords, orderType = "" }, new AjaxOptions { LoadingElementId = "loading-container", HttpMethod = "POST", UpdateTargetId = "contenedor-catalogo", OnSuccess = "loadImages()" }, new { @class = "btn " + ((ViewBag.OrderBy == null) ? defaultType : (ViewBag.OrderBy == "category") ? selectedType : defaultType) + " btn-xs js-data-order btn-order", @data_order_id = "category" })

        @Ajax.ActionLink("Precio", "Index", "Productos", new { orderby = "price", pagenumber = 0, category = @ViewBag.Category, keywords = @ViewBag.Keywords, orderType = "" }, new AjaxOptions { LoadingElementId = "loading-container", HttpMethod = "POST", UpdateTargetId = "contenedor-catalogo", OnSuccess = "loadImages()" }, new { @class = "btn " + ((ViewBag.OrderBy == null) ? defaultType : (ViewBag.OrderBy == "price") ? selectedType : defaultType) + " btn-xs js-data-order btn-order", @data_order_id = "price" })

        @Html.CheckBox("MostrarImagen", true, new { @onchange = "OnValueChanged();" })
        <input id="MostrarImagen" name="MostrarImagen" value="false" type="checkbox" style="display:none" />

lo que quiero hacer es que cuando presione el actionlink se mande el estado actual del checkbox (si esta seleccionado o no),
este es mi actionresult:
public ActionResult Index(int ? PageNumber, string OrderBy, string category, string keywords, string orderType, bool MostrarImagen = true)
    {//codigo...}

ya intente hacerlo con viewbag, viewdata y TempData, el problema que tengo es que como se manda a llamar una vista parcial y los actionlinks y el checkbox no pertenecen a esa vista parcial cuando llega el viewbag, viewdata o tempdata llegan vacíos, lo cual provoca que cuando se llega al actionresult se ponga por defecto el true siempre que selecciona alguno, o tal vez esté equivocado y no sea ese el motivo (buscando es lo que me dieron a entender), entonces necesito ayuda para poder pasar el estado actual del checkbox, alguna idea de como pueda lograr esto?
Editado:
Antes que nada mencionare que los actionlinks y el checkbox están en una vista llamada Index y el cuerpo en un partialview llamado _Catalogos, en el Index tengo el código mencionado antes (el primero) y en medio de index tengo esto:

    @Html.Partial("_Catalogo")

@* Contenedor que incluye Loader 1 y el componente para mostrar los mensajes de error. *@

Ocurrío un error al obtener la información.

Donde se observa que llamo a la partialview _Catalogo.
No puedo usar los viewbag ni sus parecidos por esto:
Cuando se seleccionan los actionlinks en mi actionresult tengo que si es llamado por un ajax (Request.IsAjaxRequest) se manda a llamar solo la vista parcial que es _Catalogo, entonces tengo entendido que los viewbag solo funcionan en la primera vista que se toca después de salir del actionresult por lo tanto si pongo en el actionlink el parámetro "MostrarImagen = @ViewBag.MostrarImagen" el viewbag está vacío, entonces no se si lo estoy usando mal o algo.
Gracias.


text:
Q: Can't specify Cobertura datafile location for server running under Ant? I have an Ant build script that instruments some jar files, starts some servers using those jars files and then runs an integration test suite of junit tests against them.
I want to capture the cobertura.ser file from each server in a separate file.
The servers need to have their working directory set so they can pick up config files. It's a requirement of the system that the classpath must not be used to pick up these files.
Setting the net.sourceforge.cobertura.datafile system property allows the datafile to be set, and this works ok, until the "dir" property is set on the ant java task. Once dir is set, the server starts correctly, the test suite runs OK, but when the server shuts down no data file is written.
Here's a fragment of the build.xml:
<parallel>
    <daemons>
        <java fork="true" dir="src\main\resources\conf\my.server" classname="my.Server">
            <sysproperty key="net.sourceforge.cobertura.datafile" file="target\cobertura.ser" />
            <classpath>
            ...
            </classpath>
            <arg value="-server" />
        </java>

        ...more servers...

        ...run junit tests...

    </daemons>
</parallel>

A: The answer is to not run the servers as daemons. We were doing this so that the servers were automatically shut down when the junit task had completed, but in reality, the Cobertura instrumentation wasn't picking up the fact that the servers were shutting down and so never wrote out the various cobertura.ser files.
The solution was to remove the daemons task, and to add an explicit server shutdown mechanism which we could call from Ant once the tests were complete.


text:
Q: format.js generate 406 Not Acceptable error
Possible Duplicate:
Weird "406 not acceptable" error

following code generate a 406 Not Acceptable error.
What can be wrong with my code?
  def remote_create
    @photo = Photo.new(params[:photo])

    respond_to do |format|
      if @photo.save
        # add @photo's thumbnail to last import tag
        format.js {
          render :update do |page|
            page.insert_html :bottom, 'polaroids' , :partial    => 'polaroid', :locals => {:photo => @photo}
          end
        }
      else
        format.html
      end
    end
  end

Started POST "/photos/remote_create" for 127.0.0.1 at 2010-03-14 14:02:08
  Processing by PhotosController#remote_create as HTML
  Parameters: {"photo"=>{"photo"=>#<File:/var/folders/BT/BTpdsWBkF6myaI-sl3+1NU+++TI/-Tmp-/RackMultipart20100314-285-1y9eq1x-0>, "name"=>"4204497503_a0c43c561d.jpg"}}
  SQL (0.6ms)  INSERT INTO "photos" ("created_at", "filename", "height", "name", "photo_content_type", "photo_file_name", "photo_file_size", "photo_updated_at", "size", "updated_at", "width") VALUES ('2010-03-14 13:02:08.449499', NULL, NULL, '4204497503_a0c43c561d.jpg', 'application/octet-stream', '4204497503_a0c43c561d.jpg', 136710, '2010-03-14 13:02:08.446370', NULL, '2010-03-14 13:02:08.449499', NULL)
[paperclip] Saving attachments.
[paperclip] saving /Users/denisjacquemin/Documents/code/projects/photos/public/system/photos/224/original/4204497503_a0c43c561d.jpg
Completed in 101ms with 406

here is the request header
Host    localhost:3000
User-Agent  Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6
Accept  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip,deflate
Accept-Charset  ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive  115
Connection  keep-alive
Content-Type    multipart/form-data; boundary=AJAX-----------------------1268573300187
Referer http://localhost:3000/photos/
Content-Length  2058592
Cookie  remember_token=ea5af5a7c9a38d72bfd07756754af682a5d16cac; _photos_session=BAh7ByIQX2NzcmZfdG9rZW4iMW1yTUo3RkhzRlhPUXhsa0ptdDAyaUpDcXlTdlU0OHk2WHJhUzBzMmVQV1k9Ig9zZXNzaW9uX2lkIiViNzc0MGI2ZGMyYWNlNjEzZWEwYjVhM2U1Njg1MWE3YQ%3D%3D--1af96dbdbef595c48121e4f5c16298cadeef5b2a

A: I found the solution, when I build the ajax request, I need to set the following header parameter
xhr.setRequestHeader("Accept", "text/javascript");

before setting this parameter, the request header was
Accept  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

and now the request header looks like this
Accept  text/javascript

works fine now
UPDATE for goo:
Here is the full code, the setRequestHeader is in the send function
hope it helps
In my view
<%= link_to 'upload all', '/photos/remote_create', :remote => true, :method => 'POST', :multipart => 'droppedItems', :id => 'upload', :class => 'awesome small green' %>

In rails.js function handleRemote(element)
else if (element.readAttribute('multipart') != null) {
  url    = element.readAttribute('data-url') || element.readAttribute('href');
  var uploader = new Uploader(null, $(element.readAttribute('multipart')));
  uploader.sendFiles(url);
  return;
}

In a js utility file
sendFiles : function(url) {
    try {
      this.filesToUpload.forEach(function(file, index, all) {
          send(file, url);
      });
    } catch(e) {
        alert('send Error: ' + e);
    }
}

function send(file, url) {
    try {
        var xhr = new XMLHttpRequest;

        var boundary    = generateBoundary();

        var contentType = "multipart/form-data; boundary=" + boundary;

        xhr.upload.addEventListener("loadstart", (function(e){
            $('progress_'+file.name).update('0%');
        }), false);

        xhr.upload.addEventListener("progress", (function(e) {
              if (e.lengthComputable) {
                  var percentage = Math.round((e.loaded * 100) / e.total);
                  $('progress_'+file.name).update(percentage + '%');
              }
        }), false);

        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4) {
                eval(xhr.responseText || '');
            }
        };

        xhr.open("POST", url, true);

        xhr.setRequestHeader("Content-Type", contentType);
        xhr.setRequestHeader("Accept", "text/javascript");

        var CRLF  = "\r\n";
        var request = "--" + boundary  + CRLF;

        request += 'Content-Disposition: form-data; ';
        request += 'name="' + 'photo[name]' + '"' + CRLF + CRLF;
        request += file.name + CRLF;

        request += "--" + boundary + CRLF;

        request += 'Content-Disposition: form-data; ';
        request += 'name="' + 'photo[photo]' + '"; ';
        request += 'filename="'+ file.fileName + '"' + CRLF;

        request += "Content-Type: application/octet-stream" + CRLF + CRLF;
        request += file.value + CRLF;
        request+= "--" + boundary + "--" + CRLF;

        xhr.sendAsBinary(request);

    } catch(e) {
        alert('send Error: ' + e);
    }
}

A: Are you setting a specific format (like if using jQuery, something like {format: 'raw'}), or setting the request header mime type (search for setRequestHeader)?
Easiest way to find out would be to use Firebug and look at what your request looks like.
Other thing to try, does the same error occur with another browser?


text:
Q: Is it possible to use 2 Heartbeat nics in SQL Failover Cluster ? (One for local servers, one for DR servers) We have a 6 servers MSSQL Failover-cluster setup, 3 servers on each datacenter, where all 6 servers use a vlan set on a Cross-datacenter network for the heartbeat.
So in case this line fails between the two datacenters - even the local servers are not able to reach each other's heartbeat, and the the cluster goes down.
Is it possible to add a secondary NIC for heartbeat for the local servers, so that each 3 servers located on the same DS will be able to contact their local partner and the cluster will still be up ?
does such design makes sense ? is there a different solution for a cross-datacenter setup ? at the moment we have a cluster failure each time the network between the two DS goes down.
thanks !


text:
Q: Game of Life, Calculate neighbors Java for homework we have to program Conway's Game of Life in Java.
But I have a problem to calculate the number of neighbors correctly.
We have to use a class Cell which represents the cells in our 2 dimensional field.
All alive cells should be saved in a LinkedHashSet.
The problem that comes up is that too much possible alive cells are saved and that i got duplicate cells in my population set.
My code to calculate the neighbors and the next generation is:
public void next() {
   generations++;
   // used to save possible alive cells
   Set<Cell> nextGen = new LinkedHashSet<Cell>();
   int col;
   int row;
   int count;
   for( int i = 0; i < grid.length; i++ ) {
      for( int j = 0; j < grid[ 0 ].length; j++ ) {
         grid[ i ][ j ].setNeighbours( 0 );
      }
   }
   for( Cell e : population ) { // calculate number of neighbors
      col = e.getCol();
      row = e.getRow();
      count = 0;

      for( int i = row - 1;
           i >= 0 && i < ( row + 2 ) && i < grid.length;
           i++ )  {
         for( int j = col - 1;
              j >= 0 && j < ( col + 2 ) && j < grid[ 0 ].length;
              j++ ) {
            count = grid[ i ][ j ].getNeighbours() + 1;
            if( i == row && j == col )
            {
               count--;
            }
            grid[ i ][ j ].setNeighbours( count );
            nextGen.add( grid[ i ][ j ] );

         }
      }
   }
   for( Cell e : population )
   { // check if all alive cells stay alive
      switch( e.getNeighbours() )
      {
      case 3:
      break;
      case 2:
      break;
      default:
         e.setAlive( false );
         population.remove( e );
      break;
      }
   }
   // check which cells get alive
   for( Cell e : nextGen ) {
      if( e.getNeighbours() == 3 ) {
         e.setAlive( true );
         population.add( e );
      }
      else if( e.getNeighbours() == 2 ) {
         /* */
      }
      else
      {
         e.setAlive( false );
      }
   }
}

A: This line doesn't seem correct:
count = grid[i][j].getNeighbours() + 1;

Shouldn't you be counting alive neighbours? Like this:
if (grid[i][j].isAlive()) count++;

You should be counting Cell e's neighbours. So remove this line
grid[i][j].setNeighbours(count);

and add this line after the i, j loops:
e.setNeighbours(count);


text:
Q: How do I get the differences between two string arrays in C#? How to compare two array string using C#.net?
Eg:
string[] com1 = { "COM6", "COM7" };
string[] com2 = { "COM6", "COM7","COM8" };

Here com1 and com2 are Array string.
Result:
COM8.
How to achieve this?

A: I think this the shortest way to solve this
foreach (string com in com2 )
{
    if (!com1.Contains(com))
    {
        MessageBox.Show(com);
    }
}

A: Sounds like you want everything in array2 except what's in array1:
var onlyInArray2 = array2.Except(array1);

Of course, if you also wanted to know what was only in array1 you could use:
var onlyInArray1 = array1.Except(array2);

(This all requires .NET 3.5 or higher, or an alternative LINQ to Objects implementation such as LINQBridge.)
I'm assuming that order isn't important when computing differences - Except is a set-based operator, so assumes that you're regarding the collections as sets.
Note that Except just returns an IEnumerable<T> - if you want the results as arrays, you'll need to call ToArray:
var onlyInArray2 = array2.Except(array1).ToArray();
var onlyInArray1 = array1.Except(array2).ToArray();

If you want the symmetric difference, i.e. you only care about which values are in a single array, rather than which array they came from, you could use:
var onlyInOneArray = array1.Union(array2).Except(array1.Intersect(array2));

or you could use HashSet directly:
var set = new HashSet<string>(array1);
// This modifies the set...
set.SymmetricExceptWith(array2);

In all of these, the resulting order is undefined, although in practice Except will preserve the original order of the first argument. While this is strictly speaking an implementation detail, I think it's very unlikely to change.
Like the other set-based operators in LINQ, Except will only return any element once - so if COM8 appeared twice in array2, it would only appear once in the result.

A: If you want everything that's in one list but not both, in a single expression, you could use Union, Intersect and Except:
var inOnlyOneArray = array1.Union(array2).Except(array1.Intersect(array2));

A: Using the Linq Except extension:
IEnumerable<string> result = com2.Except(com1);
// result: { "COM8" }

A: You could use IEnumerable.Except.

A: As others have already said, the Except extension method is definitely the way to go here. I will add, however, that it looks like you might want some control over how the comparisons are made; if 'COM8' refers to a serial port identifier, then you'd want to perform a case-insensitive comparison:
var result = com2.Except(com1, StringComparer.OrdinalIgnoreCase);


text:
Q: How to install a network of four nodes in Substrate i have tested Substrate and had some tutorials, now i want install a small network of four nodes.
The problem is that i have no tutorials and no idea how to installa four nodes in four different machines and connect them.
Have some tuts or could you help me?
Thanks in advance

A: You can find a tutorial on setting up a network of multiple Substrate chains in our Substrate Developer Hub:
https://substrate.dev/docs/en/tutorials/start-a-private-network-with-substrate


text:
Q: Hyper-V W10 (Host) Ubuntu 18.04 (Guest): Why does enhanced session mode not work? I have installed Ubuntu 18.04 as a guest system on a Windows 10 host system using Hyper-V and I want to use the guest system in full-screen mode. To resize the screen as far as I have learned I need to run the guest system in enhanced session mode.
If I am connecting to the guest system it neither lets me choose the screen size nor activate the Enhanced Session Mode.
Enhanced Session Mode (User) and Enhanced Session Mode Policy (Server) are activated under the Hyper-V Settings.
I have also tried to deactivate the RemoteFX setting -> no changes
Guest services are activated -> no changes
As far as I have learned Ubuntu 18.04 LTS should already support the enhanced session mode.

A: It fails when the auto login is enabled on Ubuntu. I disabled the auto login and it worked. Also make sure you enter your user name lowercase even if it has caps.

A: As @Guenther Schmitz stated, this feature is part of Windows 10 Update 1803, in order to try it, you need at least build 17063 (as stated here).
If you "only" want to increase your guest screensize, you might want to try setting the videomode. Careful that you remove any RemoteFX 3D Hardware. This way you can achieve 1920x1080.

A: This functionality comes with Windows 10 Update 1803

A: I had the same problem yesterday with 19.04, tried all of the workarounds I could find in the internet and nothing helped. if I used 800x600 resolution everything worked "perfectly", when I tried full screen, it would kick me out... then I installed 18.04 LTS and everything just worked....

A: I have found this guide, which helped me to activate the Enhanced Session Mode: https://www.tenforums.com/virtualization/107147-guide-how-run-ubuntu-18-04-enhanced-mode-hyper-v.html
However, I am not able to connect to the VM using xorg because it always gives me the error "Video remoting was disconnected" and only the options to Reconnect or Exit.


text:
Q: Damn-Small-Linux telnet server freezes I'm using Damn Small Linux (or "DSL") (which is based "non-purely" on Debian - I have access to apt-get) in a Virtual Machine.
I installed telnet server (telnetd + xinetd).
I'm also running another Virtual Machine, this time with installed telnet client in it (Linux distribution AntiX).
When I'm connecting with telnet from AntiX to DSL, I'm prompted about login+password, which is ok.
But then, when I log-in it's just shows a message and then freezes. By "freezes" I mean:

*

*I can type anything I want, but when I press ENTER the commands are not executed. Instead the cursor just moves to the next line.

*The line "dsl@dsl$ " (which prompts for entering a command) does not show.

*In the server side (DSL) the windows flash (close) when the login happens.

It seems like some process is running, but the problem is that it never stops. I have to type "Ctrl+C" to stop it and continue with the command line.
Here is a screenshot when it freezes:
There is also a warning in DSL's site which says that if you install the wrong application via apt-get, then you can break something, "for Instance the X server"? Could this be X server?
My questions are:

*

*Can I find out which process is running? I'm intended here only to try and make it not start again.

*Can I make this process not start upon telnet connection?

Logging in with root also reproduces the error.

A: According to this wiki page about /home/dsl/.bash_profile, the default contents of this file check if you are logging in from ssh, and if not it uses the command startx to start the X11 graphics server:
#!/bin/bash
export IRCNICK=DSL
SSH=`env | grep SSH_CONNECTION`
RUNLEVEL=`runlevel|cut -f2 -d' '`
if [ -z "$SSH" ]; then
   if [ $RUNLEVEL -eq 5 ]; then
       startx
   fi
fi

So when you login from telnet, ssh is not detected, and you are probably doing startx and running X11.  The simplest solution is for you to edit this file to make the command a comment, : startx, or somehow detect your telnet connection. Telnet doesn't usually set any special environment variables. You could perhaps use the command tty to see that you are on a pseudo-tty instead of a real console. Eg after the SSH= line add:
case `tty` in
/dev/pts*) SSH=telnet ;;
esac

For a user different to dsl such as root, you need to look in its home directory to see if it is different to /home/dsl, and check out both .profile and .bash_profile. Find the directory with eg:
awk -F: '$1=="root"{print $6}' /etc/passwd


text:
Q: How to call a JavaScript function in HTML on load JavaScript code I am trying to get to call from the HTML.
var ClassList = new Array ["Bio1300","csci12"];

function ClassMenu(ClassList) {
  return (ClassList.toString);
};

This is the HTML code I am trying to call the JavaScript function inside of on the load of the page.
<li>
  <script type="text/javascript" src="JavaScript InProg.js">
    function ClassMenu() {
      console.log(ClassList.toString);
    }
  </script>
</li>

Please help. I have many other functions I am trying to call in this manner that are both arrays and contain mathematical calculations.

A: There are a few issues with the code snippet you've provided. Firstly, it's considered a best practice to add your <script> tags inside the <head> of the document or at the end of the document when loading JavaScript files. Secondly, your source reference is incorrect. Assuming the JavaScript file InProg.js is at the same directory level as your HTML file, you could change your script link to something like this:
<script src="InProg.js"></script>

Once you've ammended how you're loading the JavaScript file into your page, you can simply make a call to the function inside another <script> tag from anywhere on the page, like so:
<script>ClassMenu(params);</script>

Also, I'd recommend adding the console.log statement to the function you're calling.
Hopefully this helps.


text:
Q: row_number() expression question in SQL Presto Sample table:

object_id
event_time
event_type
event_subtype
stage

1
2022-10-01
create
name, stage
A

1
2022-10-02
update
stage
B

1
2022-10-03
update
stage
C

1
2022-10-04
update
stage
A

2
2022-10-01
create
name, stage
A

2
2022-10-02
update
stage
C

2
2022-10-03
update
stage
A

2
2022-10-04
update
stage
B

2
2022-10-05
update
stage
C

2
2022-10-06
update
stage
A

So what I need is a column that numbers the rows based on the stage - after an object_id reaches stage C, the row number of the same object_id should be incremented. It'd look like this:

object_id
event_time
event_type
event_subtype
stage
row_number

1
2022-10-01
create
name, stage
A
1

1
2022-10-02
update
stage
B
1

1
2022-10-03
update
stage
C
1

1
2022-10-04
update
stage
A
2

2
2022-10-01
create
name, stage
A
1

2
2022-10-02
update
stage
C
1

2
2022-10-03
update
stage
A
2

2
2022-10-04
update
stage
B
2

2
2022-10-05
update
stage
C
2

2
2022-10-06
update
stage
A
3

The table must be ordered by object_id, event_time. I'm having troublle writing the window function that does this, this is what I've tried:
row_number() over (partition by object_id, stage order by event_time)

It just doesn't work for all cases. Also I'm having a hard time understanding how this would work when I'm not defining stage = C as the delimiter anywhere. Any ideas?
Thanks!

A: I would suggest using rolling sum based on previous value of stage:
-- sample data
with dataset(object_id, event_time, event_type, event_subtype, stage) as (
    values    (1, '2022-10-01', 'create',   'name, stage', 'A'),
    (1, '2022-10-02', 'update', 'stage', 'B'),
    (1, '2022-10-03', 'update', 'stage', 'C'),
    (1, '2022-10-04', 'update', 'stage', 'A'),
    (2, '2022-10-01', 'create', 'name, stage',' A'),
    (2, '2022-10-02', 'update', 'stage', 'C'),
    (2, '2022-10-03', 'update', 'stage', 'A'),
    (2, '2022-10-04', 'update', 'stage', 'B'),
    (2, '2022-10-05', 'update', 'stage', 'C'),
    (2, '2022-10-06', 'update', 'stage', 'A')
)

-- query
select object_id,
       event_time,
       event_type,
       event_subtype,
       stage,
       1 + sum(counter) over (partition by object_id order by event_time) as num
from (select *,
             if(lag(stage) over (partition by object_id order by event_time) = 'C', 1, 0) counter
      from dataset);

Output:

object_id
event_time
event_type
event_subtype
stage
num

1
2022-10-01
create
name, stage
A
1

1
2022-10-02
update
stage
B
1

1
2022-10-03
update
stage
C
1

1
2022-10-04
update
stage
A
2

2
2022-10-01
create
name, stage
A
1

2
2022-10-02
update
stage
C
1

2
2022-10-03
update
stage
A
2

2
2022-10-04
update
stage
B
2

2
2022-10-05
update
stage
C
2

2
2022-10-06
update
stage
A
3

A: It is not the problem of the row_number to give you the final "correct" order.
for you mist use the ORDER BY
SELECT
"object_id", "event_time", "event_type", "event_subtype", "stage",
ROW_NUMBER() OVER(PARTITION BY "object_id","stage" ORDER BY "event_time") rn
  FROM tab1
  ORDER BY "object_id",rn,"stage"

object_id
event_time
event_type
event_subtype
stage
rn

1
2022-10-01
create
name, stage
A
1

1
2022-10-02
update
stage
B
1

1
2022-10-03
update
stage
C
1

1
2022-10-04
update
stage
A
2

2
2022-10-01
create
name, stage
A
1

2
2022-10-04
update
stage
B
1

2
2022-10-02
update
stage
C
1

2
2022-10-03
update
stage
A
2

2
2022-10-05
update
stage
C
2

2
2022-10-06
update
stage
A
3


text:
Q: Changing Value of a hidden field I am trying to be able to change the value of a hidden field from multiple combo boxes.
Here is the example, I want to generate the value of the hidden field name="myNumbers" with the three previous select elements delimited by |.
How can I do this? with jQuery changing the .val() or with .attr() or maybe with a simple variable in PHP?
<select name="element1">
  <option value="">Select One</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option selected value="3">3</option>
  <option value="4">4</option>
</select>
<select name="element2">
  <option selected value="">Select One</option>
  <option value="1">1</option>
  <option selected value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select>
<select name="element2">
  <option selected value="">Select One</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option selected value="4">4</option>
</select>

<input type="hidden" name="myNumbers" value="3|2|4">

A: This will do what you want...
$(function(){
  var str = $('element1').val() + '|' + $('element2').val() + '|' + $('element3').val()
  $("[name='myNumbers']").val(str)
})

EDIT
A more complete solution that will iterate over every select element on the page
$(function(){
    $('select').change(function(e){
        var myNumbers = [];
        $('select').each(function(){
          myNumbers.push($(this).val());
        })
        $("[name='myNumbers']").val(myNumbers.join('|'));
    });
});

A: You have to have an onChange function for each drop down that calls updateMyNumbers function
function updateMyNumbers() {
   $("#myNumbers#").val(("#element1").val() +"|"+("#element2").val()+"|"+("#element3").val());
}

A: You would have to use javascript as php is run server-side, so before the page is loaded or after it has been submitted.
In text: You would have to capture the change events of the select boxes, generate your string and put that string in the hidden element.
Untested code:
$("select").change(function(){
  var desired_value = $("[name='element1']").val() + "|" + $("[name='element2']").val() + "|" + $("[name='element3']").val();
  $("[name='myNumbers']").val(desired_value);
});

A: var select = document.getElementById('#element1');
var index = select.selectedIndex;

With this code, you can build the string for the hidden input

A: If you are wanting to set it once at the time the page is loaded, it would make sense to do it in php (see answers above).
If you want to do it whenever a user changes one of the selects, then you would want to use javascript (jQuery is one good way) to do that in response to an onChange event for any of those selects.
If you just want to do it when the form is submitted, you could also just use javascript (perhaps jQuery in particular) to do it as part of a general form validation for the onsubmit event.
If you want it to happen just prior to using the form values to store something in your database, again you would do it in php once the user has selected things and hit Submit.  But then you really don't need the hidden value at all, you can just create it in php after you have the form submitted.

A: Here it is http://jsfiddle.net/fuhQx/


text:
Q: Java 8: pass method reference to another method I make myself familiar with Java 8's so called method references.
Two questions:
1) I want to println uppercased values. How can I pass the result of String::toUpperCase to println? For example this block of code doesn't compile:
List<String> food = Arrays.asList("apple", "banana", "mango", "orange", "ice");
food.forEach(System.out.println(String::toUpperCase));

2) Is there something similar to anonymous function parameters (_) like is Scala?

A: What you want to do is to combine a function with a consumer.
You can do it this way:
food.stream().map(String::toUpperCase).forEach(System.out::println);

Alternatively you can use a lambda expression:
food.forEach(x->System.out.println(x.toUpperCase()));

Besides these straight-forward approaches, you can combine functions to create a new function but not a function with a consumer, however, with the following quirky code you can do it:
Function<String,String>     f0=String::toUpperCase;
food.forEach(f0.andThen(" "::concat).andThen(System.out::append)::apply);

This get even uglier if you try to inline the first expression for a one-liner…


text:
Q: Javascript - Convert Name:ItemName/Value:ItemValue Objects to Regular ItemName:ItemValue JSON I have JSON data that looks like this:
[{"name":"age","value":31},
{"name":"height (inches)","value":62},
{"name":"location","value":"Boston, MA"},
{"name":"gender","value":"male"}]

I need it to look like this instead:
[{"age": 31},
{"height (inches)": 62},
{"location": "Boston, MA"},
{"gender": "male"}]

This is for a jQuery web app. How would I go about this conversion? Not picky about how it gets done, just having trouble finding an existing solution. Thanks!

A: This should do the trick:

a = [{"name":"age","value":31},
     {"name":"height (inches)","value":62},
     {"name":"location","value":"Boston, MA"},
     {"name":"gender","value":"male"}];

b = a.map(function(item){
  var res = {};
  res[item.name] = item.value;
  return res;
});

console.log(b);

A:

var jsonData = [{"name":"age","value":31},
{"name":"height (inches)","value":62},
{"name":"location","value":"Boston, MA"},
{"name":"gender","value":"male"}];

var newObj = [];
jsonData.forEach(function(d){
    var obj = {};
    obj[d.name] = d.value;
    newObj.push(obj)
});
console.log(JSON.stringify(newObj))

A: Parse your JSON string, then iterate and build a string as show here:
var s = [{"name":"age","value":31},{"name":"height(inches)","value":62},{"name":"location","value":"Boston, MA"},{"name":"gender","value":"male"}];

var h='[';
for(var i = 0; i<s.length; i++){
  h+='{"'+s[i].name+'":"' + s[i].value + '"}'
  if(i!=s.length-1){
    h+=','
  }
}
h+=']';
h=JSON.parse(h);


text:
Q: How to Create Live connection between Amazon Redshift and Amazon RDS (MySQL) I have a transaction table in MySQL which get updated almost every second. The table has about 20 million records and counting. I have been running queries directly on this table in my app development which has been having serious impact on performance especially when I have to call some queries using aggregate functions.
I want to connect the MYSQL to Amazon Redshift.
The problem is I want my connection to Redshift to be live. ie. Get Redshift updated with every insert in my tales in mysql.

*

*How do I create the live connection to Amazon Redshift?

*Is there any other way I can manage data without using Amazon Redshift?

A: In order to create a live connection from MySQL to Redshift you need to choose an appropriate database replication method. Among all existing methods, the Change Data Capture (CDC) is the most suitable for your case.
In this method, after a dump of the initial state of the database, the log of each database operation is continuously streamed and loaded into the data warehouse, and consolidated on a schedule (configurable) and the biggest advantage is that it enables near real-time replication.
A tool that I had a good experience with is Alooma, it can support near real time connection between Amazon Redshift and MySQL data base.


text:
Q: collectionReference Issue with copying Rest API data to Azure SQL DB When I copy Rest API data to Azure SQL, there is weird issue. If I use ADF V2 Copy Wizard to generate the pipeline, it can insert 3 following records into my Azure SQL DB table.
taskId taskName error error_description
1 abc success success
2 cde success success
3 efg sucess success
If I do any tiny modification like modifying the pipeline description on this pipeline, after that, if I run the updated pipeline, it can only copies following 1 record into the azure sql table.
taskId taskName error error_description
null null success success
note:
Rest API returned data format is as followings:
{
    "data": [
        {
            "taskId": 1,
            "taskName": "abc"
        },
        {
            "taskId": 2,
            "taskName": "efg"
        },
        {
            "taskId": 3,
            "taskName": "ggg"
        }
    ],
    "error": "success",
    "error_Description": "successful"
}

The pipeline json code is as followings:
{
    "name": "pipeline3",
    "properties": {
        "activities": [
            {
                "name": "Copy_v9u",
                "type": "Copy",
                "policy": {
                    "timeout": "7.00:00:00",
                    "retry": 0,
                    "retryIntervalInSeconds": 30,
                    "secureOutput": false,
                    "secureInput": false
                },
                "userProperties": [
                    {
                        "name": "Source",
                        "value": "api/getTask"
                    },
                    {
                        "name": "Destination",
                        "value": "[abc].[table1]"
                    }
                ],
                "typeProperties": {
                    "source": {
                        "type": "RestSource",
                        "httpRequestTimeout": "00:01:40",
                        "requestInterval": "00.00:00:00.010"
                    },
                    "sink": {
                        "type": "AzureSqlSink",
                        "preCopyScript": "truncate table abc.table1"
                    },
                    "enableStaging": false,
                    "translator": {
                        "type": "TabularTranslator",
                        "mappings": [
                            {
                                "source": {
                                    "path": "taskId"
                                },
                                "sink": {
                                    "name": "taskId",
                                    "type": "Int32"
                                }
                            },
                            {
                                "source": {
                                    "path": "taskName"
                                },
                                "sink": {
                                    "name": "taskName",
                                    "type": "String"
                                }
                            },
                            {
                                "source": {
                                    "path": "$.error"
                                },
                                "sink": {
                                    "name": "error",
                                    "type": "String"
                                }
                            },
                            {
                                "source": {
                                    "path": "$.error_Description"
                                },
                                "sink": {
                                    "name": "error_Description",
                                    "type": "String"
                                }
                            }
                        ]
                    }
                },
                "inputs": [
                    {
                        "referenceName": "SourceDataset_v9u",
                        "type": "DatasetReference"
                    }
                ],
                "outputs": [
                    {
                        "referenceName": "DestinationDataset_v9u",
                        "type": "DatasetReference"
                    }
                ]
            }
        ]
    },
    "type": "Microsoft.DataFactory/factories/pipelines"
}

On the mapping of the copy activity, I checked the "Collection Reference" since the "data"on json result contains the array data.
I think it is caused by current ADF doesn't save collectionReference on the json file and once I republish it, the collectionReference information is lost somehow. My previous project is working file, I compared the pipeline json file, I found previous one uses "schemaMapping" instead of "mappings" and previous one contains "collectionReference", however current one doesn't contains "collectionReference". Please see following code for 3 months' ago pipeline copying Rest API to sql db:
"translator": {
                        "type": "TabularTranslator",
                        "schemaMapping": {
                            "$.count": "count",
                            "$.next": "next",
                            "$.previous": "previous",
                            "product_id": "product_id",
                            "product_name": "product_name",
                            "city": "city",
                            "country": "country"
                        },
                        "collectionReference": "$.results"
                  }

The pipeline should still copy 3 records into the table after I did these tiny modification. In addition, is there any reason the "collectionReference" no longer appears in the json file of the pipeline? How the pipeline knows which node has array collections?
Can you please advise the solution to resolve this issue?

A: Thanks for reporting this issue. The 'collectionReference' property indeed got lost after republishing the pipeline. The fix for this issue will be rolled out to product at the end of this week. Please feel free to create pipeline from Copy wizard as a workaround. Thanks.
Also, as you can see, we previously used "schemaMapping" to describe mapping relationship between source and sink. Now it's replaced by "mappings". Both of them are working and it is not the cause of the issue you met.
The useful doc link for you: https://learn.microsoft.com/en-us/azure/data-factory/copy-activity-schema-and-type-mapping


text:
Q: Trace WPF System.Windows.ResourceDictionary warning Resource not found I get below error on output window. I can't find what is the problem?

System.Windows.ResourceDictionary Warning: 9 : Resource not found;
  ResourceKey='17' System.Windows.ResourceDictionary Warning: 9 :
  Resource not found; ResourceKey='#FF000000';
  ResourceKey.HashCode='51639504';
  ResourceKey.Type='System.Windows.Media.SolidColorBrush'
  System.Windows.ResourceDictionary Warning: 9 : Resource not found;
  ResourceKey='17' System.Windows.ResourceDictionary Warning: 9 :
  Resource not found; ResourceKey='#FF000000';
  ResourceKey.HashCode='51639504';
  ResourceKey.Type='System.Windows.Media.SolidColorBrush'
  System.Windows.ResourceDictionary Warning: 9 : Resource not found;
  ResourceKey='17'

How to find what's error???

A: If you are familiar with WinDBG you can break the process execution into the debugger on debug output and examine the callstack.
To do so in WinDBG, attach to your process and go to Debug->Event filters
Find a line that says "Debugee output" and click on it
On the right click "Enabled" under execution
Type g in the command line to run the debugger and when it breaks on the correct output, use kb to print unmanaged callstack or
.loadby sos clr
!clrstack
to print managed callstack

A: I suggest to search your entire solution for a string like {StaticResource 17}, {DynamicResource 17} or {x:Static 17}. You cannot trace something like that. There's some faulty xaml you have to fix.


text:
Q: Dask scheduler limit (fps) On https://distributed.dask.org/en/latest/actors.html#motivation I read the scheduler can coordinate about 4000 tasks per second.
Is this really the upper limit of the scheduler, or can it be increased somehow?
I'm asking for a use case where I have a Dask distributed computing graph, processing image data. Images are processed frame by frame, so I assume every frame counts as (at least) 1 task?
So can I deduct that the upper limit of a Dask cluster is 4000 frames per second?
Thanks for any help/info/workaround!

A:
Is this really the upper limit of the scheduler

Today, yes.

so I assume every frame counts as (at least) 1 task?

Not necessarily, you can organize things in many ways.  Most Dask collections like Dask array, Dask dataframe, and Dask bag, will automatically batch things for you.
See https://docs.dask.org/en/latest/best-practices.html#avoid-very-large-graphs


text:
Q: How do I construct the cake when using Scalaxb to connect to a SOAP service? I've read the documentation, but what I need to know is:
I'm not using a fictitious stock quote service (with an imaginary wsdl file). I'm using a different service with a different name.
Where, among the thousands and thousands of lines of code that have been generated, will I find the Scala trait(s) that I need to put together that correspond to this line in the documentation's example:
val service = (new stockquote.StockQuoteSoap12Bindings with scalaxb.SoapClients with scalaxb.DispatchHttpClients {}).service

Now, you might be thinking "Why not just search for Soap12Bindings in the generated code"? Good idea - but that turns up 0 results.

A: The example in the documentation is outdated, or too specific. (The documentation is also internally inconsistent and inconsistent with the actual filenames output with scalaxb.)
First, search for SoapBindings instead of Soap12Bindings to find the service-specific trait (the first trait).
Then, instead of scalaxb.SoapClients, use scalaxb.Soap11Clients.


text:
Q: Understanding memoization in Python I would like to understand memoization in Python better. In an online class I am taking, the following example is provided:
def memoize(func):
    memo_dict = {}
    def wrapper(*args):
        if args not in memo_dict:
            memo_dict[args] = func(*args)
        return memo_dict[args]
    return wrapper

@memoize
def find_divisors_memo(n):
    divisors = []
    for i in range(1, n+1):
        if n % i == 0:
            divisors.append(i)
    return divisors

I am trying to find the numerical values stored in memo_dict after running a few examples, e.g.:
find_divisors_memo(100000009)
find_divisors_memo(100000008)

I do:
for x,y in memo_dict.items():
        print(x,y)

and it says: NameError: name 'memo_dict' is not defined.

A: If you want to have a look at the dict for the purpose of understanding memoization, you can add a few print statements:
def memoize(func):
    memo_dict = {}
    def wrapper(*args):
        if args not in memo_dict:
            memo_dict[args] = func(*args)
        else:
            print('using cached value')
        print(memo_dict.items())
        return memo_dict[args]
    return wrapper

@memoize
def find_divisors_memo(n):
    print('function called')
    divisors = []
    for i in range(1, n+1):
        if n % i == 0:
            divisors.append(i)
    return divisors

Now you can see the items of the dict in every function call.
Also, you'll see how memoization works: If you call the function with a specific parameter for the first time, the function is actually called. If you call it a second time with the same parameter, it does not actually call the function (which could be a very computation-intensive function), but instead uses the cached value from the dict.
If you want to use caching in a real project, I recommend functools.lru_cache. Also, there are other cache implementations available in a (non-stdlib) library named cachetools.


text:
Q: Mouse hover on element http://www.franchising.com/  ---> Mouse over on (Franchises A-Z) ---> need to click Q
I have tried with the following
WebElement we1=driver.findElement(By.cssSelector("a[href='/franchises/']"));

WebElement we2=driver.findElement(By.cssSelector("a[href='/franchises/q.html']"));

String js = "arguments[0].style.height='auto'; arguments[0].style.visibility='visible';";

((JavascriptExecutor) driver).executeScript(js, we2); // I have used the script since the we2 is not visible

Actions builder=new Actions(driver);
builder.moveToElement(we1).perform();
Thread.sleep(5000);
we2.click();

could any one try and share me the code... Still I'm getting "ElementNotVisibleException"

A: With firefoxdriver, a lot would depend on what version of driver you are using and what version of Firefox you have on your system since native support would differ based on that.
Following works on Chrome :
WebElement link1 = driver.findElementByLinkText("Franchises A-Z");
Actions action = new Actions(driver);
action.moveToElement(link1).click(driver.findElementByXPath("//a[contains(@href,'franchises/b')]")).perform();

A: Before going in to the code i just want to you to ensure the version of Selenium server you are using. Please make it to the updated version of 2.28.x
Code:
    driver = new FirefoxDriver();
    driver.get("http://www.franchising.com/franchises/");
    Thread.sleep(5000);
    WebElement element=driver.findElement(By.xpath("//tr[3]/td/table/tbody/tr/td[4]/a"));
    Actions builder = new Actions(driver);
    builder.moveToElement(element).build().perform();
    Thread.sleep(5000);

it works fine for me. Try this code. I hope this will work.


text:
Q: User's profile is not creating I am building a BlogApp and I am tried to register user Today BUT it shows

AttributeError: 'User' object has no attribute 'encode'

This was working before few days but when i tried today then it is keep showing.
When i python manage.py createsuperuser in terminal then same error is showing.
Full Traceback
Traceback (most recent call last):
  File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\app\users\views.py", line 10, in signup_view
    user = form.save()
  File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\forms.py", line 131, in save
    user.save()
  File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save
    super().save(*args, **kwargs)
  File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 727, in save
    force_update=force_update, update_fields=update_fields)
  File "C:\DELL\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 776, in save_base
    update_fields=update_fields, raw=raw, using=using,
  File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\django\dispatch\dispatcher.py", line 182, in send
    for receiver in self._live_receivers(sender)
  File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\django\dispatch\dispatcher.py", line 182, in <listcomp>
    for receiver in self._live_receivers(sender)
  File "D:\app\mains\models.py", line 264, in post_save_create_profile
    Profile.objects.create(user=instance)
  File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 453, in create
    obj.save(force_insert=True, using=self.db)
  File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 727, in save
    force_update=force_update, update_fields=update_fields)
  File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 765, in save_base
    force_update, using, update_fields,
  File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 868, in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
  File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\base.py", line 908, in _do_insert
    using=using, raw=raw,
  File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 1270, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1415, in execute_sql
    for sql, params in self.as_sql():
  File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1360, in as_sql
    for obj in self.query.objs
  File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1360, in <listcomp>
    for obj in self.query.objs
  File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1359, in <listcomp>
    [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
  File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1310, in pre_save_val
    return field.pre_save(obj, add=True)
  File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\autoslug\fields.py", line 276, in pre_save
    slug = self.slugify(value)
  File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\autoslug\utils.py", line 34, in slugify
    return django_slugify(unidecode(value))
  File "C:\Users\AppData\Local\Programs\Python\Python37\lib\site-packages\unidecode\__init__.py", line 48, in unidecode_expect_ascii
    bytestring = string.encode('ASCII')
AttributeError: 'User' object has no attribute 'encode'

users/views.py
def signup_view(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            login(request, user)
            return redirect('mains:home')
    else:
        form = SignUpForm()
    return render(request, 'registration/signup.html', {'form': form})

models.py
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True)
    full_name = models.CharField(max_length=100,default='')
    email = models.EmailField(max_length=60,default='')
@receiver(post_save,sender=User)
def post_save_create_pro(sender,instance,created,**kwargs):
    if created:
        Profile.objects.create(user=instance)

forms.py
class SignUpForm(UserCreationForm):
    password1 = forms.CharField(widget=forms.PasswordInput())
    username = forms.CharField(help_text=False)

    class Meta:
        model = User
        fields = (
            'username',
        )

In error in browser it is showing this with form.save() highlighted.

When i click on register then this error is raising . When i check in admin then user is created BUT profile is not created, BUT it should show me User has no object Profile BUT it is showing something different.
Any help would be much Appreciated.
Thank You in Advance.

A: You are creating profile but not saving it. Try it.
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True)
    full_name = models.CharField(max_length=100,default='')
    email = models.EmailField(max_length=60,default='')
@receiver(post_save,sender=User)
def post_save_create_pro(sender,instance,created,**kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

A: I create a New Virtual Environment and It Worked.
What was the Problem :-
Not 100 % Sure BUT i think i was adding a middleware of a library which was
not installed in virtual environment


text:
Q: Request_Content in agentcontext empty when receiving a large XML I have a java agent in IBM Domino which processes a XML content which is being received by HTTP POST. Now it seems that if the XML content is larger than aprox. 1180 lines, the agent is not processing the POST(XML) content. When I Perform a:
System.out.println(agentContext.getDocumentContext().getItemValueString("REQUEST_CONTENT"));

Then it returns empty.
Is there a maximum limit and if you could point me a workaround that would be great.

A: From this technote:

If the POST data is less than 64 KB -  Use REQUEST_CONTENT to access
  the POST data.
If the POST data is greater than 64 KB -  Use REQUEST_CONTENT_000 to
  access the first 6 4KB chunk, REQUEST_CONTENT_001 to access the second
  64 KB chunk, REQUEST_CONTENT_002 to access the third 64 KB chunk, and
  so on.
A developer can use the NotesDocument.HasItem("REQUEST_CONTENT") call
  to test for the presence of the REQUEST_CONTENT field. If it exists,
  then there was less than 64 KB of POST data.

A: I use something like this:
private String getRequestContent(Document document) throws Exception {
    String returnObject = "";

    try {
        if (document.hasItem("Request_Content")) {
            returnObject = document.getItemValueString("Request_Content");
        }
        else {
            if (document.hasItem("Request_Content_000")) {
                for (int i = 0; i < 100; i++) {
                    String fieldName = "Request_Content_" + String.format("%03d", i);
                    returnObject += document.getItemValueString(fieldName);
                }
            }
            else {
                throw new Exception("Request_Content fields not found");
            }
        }
    }
    catch (Exception e) {
        throw new Exception("could not retrieve the Content from the Request", e);
    }

    return returnObject;

}


text:
Q: Can a FSBL load another FSBL? I am currently exploring the bootloader world.
However I asked myself if it is possible for a first stage bootloader to load and run another first stage bootloader. (lets say it lays on a FAT partition)
If so what would be the preferred way?
If not why?

A: Just be sure to:

*

*Load the new FSBL in the proper segment.
This usually means 0000:7c00 that in turns imply that you have to overwrite your current bootloader.
You can relocate a routine (that you cared to make position independent) that could be as simple as setting ds:si, es:di and cx for a (slow) rep movsb/w/d.

*Set the registers properly.
The BIOS hands control to the FSBL with definite register values (see section 6.5.1 of the relative specifications), you have to save those values (even to fixed memory locations) and restore them.
Some bootloaders could be additional constrains for a successful chainload.