text:
Q: HttpWebRequest POST in c# I have an Api that allows users to be inserted into the database. I am trying requesting the Api in a windows forms application but keep getting System.Net.WebException: 'The remote server returned an error: (403) Forbidden.'I am relatively new to Api requests. Can anyone see what I am doing incorrectly, thanks.
Customer class:
public class Customer
    {
        public int StoreCustomerID { get; set; }
        // Actaul customer from store ID
        public string Number { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
        public string Address { get; set; }
        public string Email { get; set; }
        public string City { get; set; }
        public string Region { get; set; }
        public string Country { get; set; }
        public string MobilePhone { get; set; }
        public System.DateTime DOB { get; set; }
        public string Phone { get; set; }
        //public User Credentials { get; set; }
        public string DeviceToken { get; set; }
        //public CustomerCard Details { get; set; }
        public string Gender { get; set; }
        public bool IsError { get; set; }
        public string ErrorMessage { get; set; }
        //Public Property StoreNumber As Integer

            public string Token { get; set; }
            public bool Authenticated { get; set; }
            public string SecretKey { get; set; }

    }

ApiRequest class:
private void button1_Click(object sender, EventArgs e)
        {

            Customer cust = new Customer();
            InsertUpdateCustomer(cust, "http://Example.com");
        }

        public static Customer InsertUpdateCustomer(Customer MyCustomer, string ServerAddress)
        {

            //Dim PostData As New CardInfo With {.CardNumber = CardNumber, .Reference = Reference, .SaleDate = DateTime.Now, .SaleTotalAmount = Amount, .StoreNumber = StoreNumber, .TransactionTypeID = Transaction}

            //Customer Res = new Customer();
            string webAddr = ServerAddress + "/api/Customer/Insert";

            WebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";
            httpWebRequest.Headers.Add("X-Giftworx-App", "Posworx");
            httpWebRequest.Timeout = 4000;

            MyCustomer.Name = "Janice";
            MyCustomer.Surname = "Alexander";
            MyCustomer.Email = "j@example.com";
            MyCustomer.MobilePhone = "0314011828";
            MyCustomer.Gender = "Female";
            MyCustomer.DOB = DateTime.Now;
            MyCustomer.Token = "wMq0cZ4iN7uOnJdrSdYITQcWHQ9VYgiLCosN7Rj9MSdqmZKSTuHCb08jeO/wlp3bCoK/sbEwwvjlZUeQdj8p5w==";
            MyCustomer.SecretKey = "jdghe45";
            MyCustomer.Authenticated = true;

            try
            {
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {

                    string jsonstring;

                    MemoryStream stream1 = new MemoryStream();

                    //Serialize the Record object to a memory stream using DataContractJsonSerializer.
                    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Customer));
                    ser.WriteObject(stream1, MyCustomer);

                    stream1.Position = 0;

                    StreamReader sr = new StreamReader(stream1);

                    jsonstring = sr.ReadToEnd();

                    Debug.WriteLine("JSON form of Insert Loyaltyworx Update Customer object: ");
                    Debug.WriteLine(JObject.Parse(jsonstring));

                    streamWriter.Write(jsonstring);
                    streamWriter.Flush();
                }
            }
            catch (Exception ex)
            {
                return null;
            }

            try
            {
                HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                if (httpResponse.StatusCode == HttpStatusCode.OK)
                {
                    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                    {
                        string result = streamReader.ReadToEnd();
                        Console.WriteLine(JObject.Parse(result));

                        Customer MyResult = JsonConvert.DeserializeObject<Customer>(result);

                        Debug.WriteLine(JObject.Parse(result));

                        return MyResult;

                    }
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {

                return null;
            }

        }

A: You can convert your data in to a json string  as below
 Customer cust = new Customer();
 var json = new JavaScriptSerializer().Serialize(cust );
 JObject json2 = JObject.Parse(json);

and then you can make a call like this.
 string webAddr = ServerAddress + "/api/Customer/Insert";
 HttpClient client = new HttpClient();
 HttpResponseMessage response = client.PostAsJsonAsync(webAddr , json2).Result;

A: Make sure you are lunching your app as administrator and check that the firewall/antivirus is not blocking.


text:
Q: What is the meaning of Ajax Status 8 in IE? In our web application accessed via IE11, sometimes we see a strange response for some Ajax Requests and the code/status is 0x8 highlighted in red color in the "Developer Tools" (F12 Network Requests) of IE Browser.

In the console we can see this message:

What is the potential cause for this and how to troubleshoot further?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Method not found: 'Void System.Data.Entity.DbModelBuilder.RegisterEntityType(System.Type)' I'm using EntityFramework but in some cases I get this Exception:
threw an exception.", inner exception: "Method not found: 'Void System.Data.Entity.DbModelBuilder.RegisterEntityType(System.Type)'.

Why is this exception is happening?
As I found out, this exception is happening when system expected to have EF 6.1.3, but the referenced EF is 6.0.0.
As I updated my EF via nuget, it worked. The problem is in some cases I can not found any 6.0.0
For example I'm using a 3rd party component (XAF) which have a designer in Visual Studio.
The designer cannot load because of this exception. The EF in my project is 6.1.3 but I don't know how it uses 6.0.0
Question 1: Why and when is this exception happening?

A: This exception probably is happening because of the different versions of loaded assemblies. If XAF referencies the 6.0.0 version in it's metadata, and your project doesn't, the compiler will load the 6.0.0 version to bin folder.
You can try overload the assembly version in you application configuration file (app.config), using something like this:
<configuration>
    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0-6.0.0" newVersion="6.1.3" />
            </dependentAssembly>
        </assemblyBinding>
    </runtime>
</configuration>

A: I had same problem and change version of EF in all app.config and web.config files to correct version. like this in app.config of my DataLayer prject:
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.1.3.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>

and also manage my NuGet packages to all of projects use same version.


text:
Q: javascript prototype object 1.
function MyConstructor() {}
var myobject = new MyConstructor();
MyConstructor.prototype = {protest:"maizere"};

[ myobject instanceof MyConstructor,     // false !
myobject.constructor == MyConstructor, // true !
myobject instanceof Object ]           // true
console.log(myobject.protest)          //undefined

This proves that myobject does not inherit properties and method from MyConstructor prototype anymore.
But see next code below:
2.
function MyConstructor() {}
var myobject = new MyConstructor();
MyConstructor.prototype.protest= "Maizere";//Do this line gets hoisted?or something else

[ myobject instanceof MyConstructor,     // true!
myobject.constructor == MyConstructor, // true !
myobject instanceof Object ]           // true
console.log(myobject.protest)          //Maizere

Why is this happening?what is the exact definition of internal prototype?This also  proves even after the instantiation of the object , proto is  refering to MyConstructor prototype.If so than why the first(1.) code not referring to MyConstructor prototype?
since the property is being added after the instantiation of an object in the second code and the internal prototype of the object receives it ,this means we can change the prototype properties later and still see the effect in the instance .But same definition is not working when prototype properties is replaced in the first code?

A: I might be wrong with this but it looks like when you do:
MyConstructor.prototype = {protest:"maizere"};

You're overriding your prototype with an anonymous object definition, thus when you just add a new property like:
MyConstructor.prototype.protest= {"Maizere"};

Your class keeps its prototype and it works like a charm.

A: MyConstructor.prototype = overwrites the entire prototype object.

The instanceof operator tests whether an object has in its prototype chain the prototype property of a constructor

http://jsfiddle.net/ExplosionPIlls/xtqhp/
function MyConstructor () {}
MyConstructor.prototype = {'xyz': 'zyx'};
//true
console.log((new MyConstructor) instanceof MyConstructor);

function MyConstructor2 () {}
var mc2 = new MyConstructor2;
MyConstructor2.prototype = {'xyz': 'zyx'};
//false
console.log(mc2 instanceof MyConstructor2);

By the way, MyConstructor.prototype.protest = {"Maizere"}; is not valid syntax.

A: So, this is one of the reasons I have this article bookmarked:
Constructors Considered Mildly Confusing
Basically, what's happening in the first block of code is that you're overwriting MyConstructor's prototype object with a new object.  Whereas, in the second block, you're adding a property to the existing prototype object.


text:
Q: How can I change database values in Javascript code, but not allow the user to change (or access) database values in the Javascript console? Okay, so I'm creating a web app.
The web app basically is a game, in which you have a number of points. You get more points by answering addition questions correctly.
I'm using Firebase Real-time Database to save the users' score. This is the code I'm running whenever the user answers a question correctly: (document.getElementById("score").innerText is the current score)
var user = firebase.auth().currentUser;
firebase.database().ref('users/' + user.uid).set({
   score: parseInt(document.getElementById("score").innerText) + 2,
}).catch(function(error) {
   console.log(error);
});

So that works fine. But, I found out, that a user could take that code, and put it in the console and gain infinite points.
So how would I go about fixing this? This is my current database rules if that needs to be changed:
{
  "rules": {
    ".read": true,
    ".write": true
  }
}

My more generalized question is

How can I change database values in Javascript code, but not allow the user to change (or access) database values in the Javascript console?

I looked into https://firebase.google.com/docs/database/security/securing-data and couldn't find anything helpful. I think I need to change something in the database rules.
UPDATE: The best solution suggested so far was to use Cloud Functions in Firebase.

A: You'll have to put the logic that deals with the database in backend code that can't be tampered with.  Cloud Functions is the typical choice for that, if you're already working with Firebase.
At I/O 2017 I gave a talk about writing a turn based game that's immune to cheating by putting all the core logic on the backend with Cloud Functions.  The details are slightly out of date, but the principles remain the same.


text:
Q: How to query documents which contains a sent parameter in Firestore? I am using the new Cloud Firestore in Android.
So I am facing this issue in firestore.
I want to query a document, which contains an id in their array fields.
for example, I have a document with a field in firestore containing an array of integers like this:

So when I have an id 66940, I can get the document and other documents which contains the id, without returning other documents which don't contain the id 66940.

Other than this approach, I can also use the id (66940) to search it in the document id. My documents id format is like this:
- 66940_88123
- 12323_66940
The idea is, to return documents which contain 66940 in their ID.
I've read about a solution here, but I don't really understand how to implement it.

A: This is a common question, so we have posted some documentation on how to work with arrays in Cloud Firestore:
https://firebase.google.com/docs/firestore/solutions/arrays
In short, if you want to query for array membership it's better to store your data as a map of booleans.
So instead of this:
{
  name: "sam",
  userGgIds: [12345, 67890]
}

You want this:
{
  name: "sam",
  userGgIds: {
    12345: true,
    67890: true
  }
}

Then you can do this query to search for documents that contain the ID "12345"
db.collection("users").where("userGgIds.12345", "==", true).get()


text:
Q: Forward PTR request if not found I am attempting to find a way to forward PTR request, if not found in local master zones. I'm transitioning a network from one domain (and dns servers) to another, which is easy for A records - but a mess for PTR, as ips haven't changed.
How can I set up bind to forward PTR lookup request to another server, only if not found in the local zones (E.G 0.0.10.in-addr.arpa)?

A: Basically, no. This is a common question for BIND but this software has no mechanism for that. Either it is authoritative for the zone (and have all the possible data) or it isn't (and it forwards).


text:
Q: Save the selected value of a drop down in global variable How can I save the value of a selected dropdown in a global variable in MVC.I have to save the changed value in a variable named "no_of_days" whenever the value is changed.
@{
    Layout = null;
    string no_of_days = "6";
}

      <select id="no_of_days" class="ms-Dropdown-select">
         <option value="6" class="ms-Dropdown-item " selected="selected">last 6 months</option>
          <option value="7" class="ms-Dropdown-item">last 7 months</option>
                <option value="8" class="ms-Dropdown-item">last 8 months</option>
                <option value="9" class="ms-Dropdown-item">last 9 months</option>
                <option value="10" class="ms-Dropdown-item">last 10 months</option>
                <option value="11" class="ms-Dropdown-item">last 11 months</option>
                <option value="12" class="ms-Dropdown-item">last year</option>
       </select>

I am not able to get any value in @no_of_days variable. I want to do a Ajax.ActionLink call so I need the real-time value of @no_of_days


text:
Q: UITableView after prepareForReuse - all the data in Cell disappear I have a TableView with customCell, that has next properties:
@interface CustomTableViewCell : UITableViewCell

@property (weak, nonatomic) IBOutlet UIImageView *image;
@property (weak, nonatomic) IBOutlet UILabel *nameOfImage;
@property (weak, nonatomic) IBOutlet UIButton *start;
@property (weak, nonatomic) IBOutlet UIButton *stop;
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@property (weak, nonatomic) IBOutlet UILabel *realProgressStatus;

In table view - when user press start button - an image is downloaded, as well as progressView with realProgressStatus reflects current situation. At this stage everything works perfect, but when scroll table view and return back to the cell - that was already fulfilled with data - all info disappeared(except the nameOfImage, I set it separately).
I implemented next method in my CustomTableViewCell class:
 -(void)prepareForReuse
{
    [super prepareForReuse];

    self.progressView.progress = 0.1;
    self.realProgressStatus.text = @"";
    self.image.image = [UIImage imageNamed:@"placeholder"];
}

I implemented new property NSMutableSet self.tagsOfCells, where I save number of cells where images where already downloaded.
I tried to make changes in TableView method but effect is the same :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* PlaceholderCellIdentifier = @"Cell";
    CustomTableViewCell *customCell = [tableView dequeueReusableCellWithIdentifier:PlaceholderCellIdentifier forIndexPath:indexPath];
    customCell.delegate = self;
    customCell.cellIndex = indexPath.row;
    if (!customCell)
    {
        customCell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                                reuseIdentifier:@"cell"];
    }
    else
    {
           NSNumber *myNum = [NSNumber numberWithInteger:indexPath.row];

        if (![self.tagsOfCells containsObject:myNum])
        {
            NSLog(@"Row: %ld",(long)indexPath.row);
            UIImage *img = [UIImage imageNamed:@"placeholder"];
            customCell.realProgressStatus.text = @"";
            customCell.progressView.progress = 0.1;
            customCell.image.image = img;
            [customCell setNeedsLayout];
        }
    }

    if ( indexPath.row % 2 == 0 )
        customCell.backgroundColor = [UIColor grayColor];
    else
        customCell.backgroundColor = [UIColor darkGrayColor];

    customCell.nameOfImage.text = self.names[indexPath.row];
    return customCell;
}

EDIT:
I populate self.tagsOfCells in one of methods during downloading images, here is the method:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    self.customCell.realProgressStatus.text = @"Downloaded";

    UIImage *img = [UIImage imageWithData:self.imageData];
    self.customCell.image.image = img;
    self.customCell.tag = self.selectedCell;
    [self.savedImages setObject:img forKey:self.customCell.nameOfImage.text];
    NSNumber *myNum = [NSNumber numberWithInteger:self.selectedCell];
    [self.tagsOfCells addObject:myNum];

}

Thanks in advance for any help or advice.

A: Content-related actions shouldn't occur in the prepareForReuse function.
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewCell_Class/#//apple_ref/occ/instm/UITableViewCell/prepareForReuse

If a UITableViewCell object is reusable—that is, it has a reuse identifier—this method is invoked just before the object is returned from the UITableView method dequeueReusableCellWithIdentifier:. For performance reasons, you should only reset attributes of the cell that are not related to content, for example, alpha, editing, and selection state. The table view's delegate in tableView:cellForRowAtIndexPath: should always reset all content when reusing a cell. If the cell object does not have an associated reuse identifier, this method is not called. If you override this method, you must be sure to invoke the superclass implementation.

Edited
Alfie is right, prepareForReuse isn't invoked after returning from cellForRowAtIndexPath
First thing I would try is edit the code
if (!customCell)
{
    customCell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                            reuseIdentifier:@"cell"];
}
else
{
       NSNumber *myNum = [NSNumber numberWithInteger:indexPath.row];

    if (![self.tagsOfCells containsObject:myNum])
    {
        NSLog(@"Row: %ld",(long)indexPath.row);
        UIImage *img = [UIImage imageNamed:@"placeholder"];
        customCell.realProgressStatus.text = @"";
        customCell.progressView.progress = 0.1;
        customCell.image.image = img;
        [customCell setNeedsLayout];
    }
}

to the following
if (!customCell)
{
    customCell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                            reuseIdentifier:@"cell"];
}

NSNumber *myNum = [NSNumber numberWithInteger:indexPath.row];

if (![self.tagsOfCells containsObject:myNum])
{
    NSLog(@"Row: %ld",(long)indexPath.row);
    UIImage *img = [UIImage imageNamed:@"placeholder"];
    customCell.realProgressStatus.text = @"";
    customCell.progressView.progress = 0.1;
    customCell.image.image = img;
    [customCell setNeedsLayout];
}

This really isn't an expensive operation and it's better to have this logic in a single place. Especially since you got rid of prepareForReuse, this should be changed.
The reason when you scroll away, and then come back to not find your data is cellForRowAtIndexPath is being called again, which results in the default data overriding the new data you just added.
You would want to have an underlying data structure and retrieve data from there.

What I would do:
For instances, you can keep a mutable list as such
NSMutableArray* tableData = [[NSMutableArray alloc] init];

add image data for each row to the array
[tableData add:imageData];

and then display it add cellForRowAtIndexPath
customCell.image.image = [tableData objectAtIndex:[indexPath row]];

This would be the normal practice for populating a UITableView with data. This way, even if you scroll away tableData would remain the same, resulting in consistent data.
Note
I would also call new data asynchronously using NSURLSession from within the cell if I had to implement this. Just a suggestion=)

A: I don't think this has anything to do with your use of prepareForReuse. A couple things look fishy.

*

*You're setting the delegate and cellIndex properties on your cell before you know whether it's nil or not. If it's nil then these properties will never be set.

*I also don't think you need the else clause in there. The logic that it wraps doesn't have anything to do with whether a cell could be dequeued. it has to do with configuring a non-nil cell.

*A missing piece from your question is where do you populate the tagsOfCells object? That code is important. If you're not setting the tag in cellForRowAtIndexPath it seems like your data will get out of sync and this will cause your cell to be misconfigured.
Try the following code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* PlaceholderCellIdentifier = @"Cell";
    CustomTableViewCell *customCell = [tableView dequeueReusableCellWithIdentifier:PlaceholderCellIdentifier forIndexPath:indexPath];
    if (!customCell)
    {
        customCell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                            reuseIdentifier:@"cell"];
    }

    NSNumber *myNum = [NSNumber numberWithInteger:indexPath.row];

    if (![self.tagsOfCells containsObject:myNum])
    {
        NSLog(@"Row: %ld",(long)indexPath.row);
        UIImage *img = [UIImage imageNamed:@"placeholder"];
        customCell.realProgressStatus.text = @"";
        customCell.progressView.progress = 0.1;
        customCell.image.image = img;
        [customCell setNeedsLayout];
    }

    customCell.delegate = self;
    customCell.cellIndex = indexPath.row;
    customCell.nameOfImage.text = self.names[indexPath.row];

    if (indexPath.row % 2 == 0)
    {
        customCell.backgroundColor = [UIColor grayColor];
    }
    else
    {
        customCell.backgroundColor = [UIColor darkGrayColor];
    }

    return customCell;
}

Edit
Regarding info in another answer here. prepareForReuse is not being called after you configure your cell. It's being called when you invoke dequeueReusableCell and hence before you configure your cell. I don't believe prepareForReuse is the problem.

A: It looks like you are not using interface builder's prototype cells so you are using the wrong dequeue reusable cell method. The correct one in your situation does not have an index path param e.g.
CustomTableViewCell *customCell = [tableView dequeueReusableCellWithIdentifier:PlaceholderCellIdentifier];

And as the others said you need to move your 2 lines of initialization after you alloc init your custom cell because it's nil before then. Eg you need to dequeue the cell and if nil create one. Then set your params on the cell now you have a valid instance.


text:
Q: cannot be used as a JSX component Its return type string | Element is not a valid JSX element Type 'string' is not assignable to type 'Element | null' I created a react function  EventDateTooltip:
import React from 'react';
import { endOfDay, isToday, isTomorrow, isYesterday } from 'date-fns';
import { useTranslation } from 'react-i18next';
import I18nWrapper from '../i18n-wrapper';
import DateFormater from '../formaters/date-formater';

 const EventDateTooltip = ({ date }: { date: string }) => {
 const { t } = useTranslation();
 const dateTooltip = endOfDay(new Date(date));
  if (isTomorrow(dateTooltip)) return t('tooltip.event.date.tomorrow');
  if (isYesterday(dateTooltip)) return t('tooltip.event.date.yesterday');
  if (isToday(dateTooltip)) return t('tooltip.event.date.today');

 return (
   <>
  <span key={date.toString()}>
    <I18nWrapper translateKey="tooltip.event.date.the" />{' '}
    <DateFormater dateToFomat={date} formater="full-date" />
  </span>
</>
  );
};

export default EventDateTooltip;

this function return a text and a translated date.
when I call this function on another component:
 <EventDateTooltip date={props.event.endDate}></EventDateTooltip>;

the call returns the following error message:
Its return type 'string | Element' is not a valid JSX element.
   Type 'string' is not assignable to type 'Element | null'.  TS2786

has anyone got the following message ?

A: As stated in this answer, currently TypeScript's React types do not allow you to return a string from a React component and include that in a component tree.
You can wrap your strings with fragments to avoid the error:
// [...]
  if (isTomorrow(dateTooltip)) return <>t('tooltip.event.date.tomorrow')</>;
  if (isYesterday(dateTooltip)) return <>t('tooltip.event.date.yesterday')</>;
  if (isToday(dateTooltip)) return <>t('tooltip.event.date.today')</>;
// [...]


text:
Q: How to find all factors of a number for a given number range How can I find all the existing factors between two number?
for example all the factors of 5 that are between 10 and 1000.
One thing I can think of is like this:

function getFactors(factor, numbers) {
  let factors = new Array()

  for (var i = numbers[0] ; i <= numbers[1] ; i++) {
    if (i % factor == 0) factors.push(i)
  }

  return factors
}

console.log(getFactors(5, [50, 100]))

But the problem is that I have a big number range ([0, 10000]) and a small factor 0.01. so I think doing this using my solution will be too much in terms of performance (i need to do this check every tick).
so I was wondering what is the better way to do this?

A: You can achieve same thing without checking for every number between numbers[0] & numbers[1]. What you need basically is to get every multiple of factor between numbers[0] & numbers[1]. Below code does it:
function getFactors(factor, numbers) {
  let factors = new Array();
  let start = numbers[0]/factor;
  let end = numbers[1]/factor;
  for(var i=start; i<= end; i++) {
    factors.push(factor*i);
  }

  return factors
}
console.log(getFactors(5,[50,100]))
//[50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]


text:
Q: Python asyncio function call inside loop I have a server and client where multiple clients will be connecting to multiple server and does something. I want to make client connection to server async.
clients = [1,2,3]
for c in clients:
  connect_to_server()

right now the above code connects to server but waits for first iteration to be executed and then second.
how to make it async function call to connect_to_server() method so that second iteration will not wait for first to be executed ?
And which function has to be async either connect_to_server or for loop function and which has to be awaiting ?

def connect_to_server(client_id):
    print(client_id)
    time.sleep(3)

async def main():
    clients = [1, 2, 3, 4]
    for client in clients:
       await connect_to_server(client)

asyncio.run(main())

A: Here wrap the code you want to be async in an async function,
import asyncio

async def main():

    clients = [1,2,3]

    for c in clients:
        await connect_to_server()

asyncio.run(main())

Explaination : here asyncio calls your async "MAIN" function and "AWAIT" in the function makes the process proceed to the next iteration without waiting for connect_to_server() function to finish !


text:
Q: HTML5 Remove previous drawn object in canvas I have a polygon object (say a car) drawn inside a HTML5 canvas with help of methods moveTo and lineTo. I want to repeatedly draw that object at different positions in the canvas (simulating a moving object). My problem is that the previous drawn object is not getting cleared. Instead, multiple images are drawn on the canvas. How can I fix this issue?

A: You have to clear the canvas at the start of every draw frame
context.clearRect(0, 0, canvas.width, canvas.height);

A: Canvases are just arrays of pixels, they know nothing of the shapes you have drawn.
There are animation tricks that used to be used on bitmapped displays (e.g. "xor drawing") that can be used to remove the old shape before you draw the new one, but on modern machines it's generally far simpler (and perfectly fast) to just erase the canvas and start again for each frame.
Given your comments to other answers, I'd suggest just using two Canvases - one for the static background and one for the car.   If the background image is static it could even be an <img> element instead of a Canvas.
If the car image is static you could also just draw that once, and then use CSS positioning to set its position relative to the background for each frame.

A: suppose your shape is car then you first have to assign a new graphic like:
car.graphics = new createjs.Graphics();

car.graphics
            .setStrokeStyle(1)
            .beginStroke("#000000")
            .moveTo()
            .lineTo()
            .lineTo()


text:
Q: track points using kalman filter in opencv c How to draw random points using kalman filter algorithm with opencv c++ code. I have tried with mouse function now instead of mouse function i want random points to be generated and the kalman filter to track all the random points. Here is the mouse function:
struct mouse_info_struct { int x,y; };
struct mouse_info_struct mouse_info = {-1,-1}, last_mouse;
  vector<Point> mousev,kalmanv;

  void on_mouse(int event, int x, int y, int flags, void* param)

  {
    last_mouse = mouse_info;
    mouse_info.x = x;
    mouse_info.y = y;
  }

A: Replace the x and y coordinates of your mouse points by the result of a call to cv::RNG::uniform() or cv::RNG::gaussian(), depending on what kind of random distribution you want. See the doc here.


text:
Q: Android Studio AssertionError while building project I've been fighting with Android Studio and Gradle all day.  My project originally was created in Eclipse, then migrated to IntelliJ, and now Android studio.  It has the old project structure for example.  I ended up following through Google's migration guide for how to convert the project to a Gradle structure.  After much pain I was able to get Gradle installed and successfully built my project by calling gradle buildDebug.
I'm trying to get it so that I can click the Run button in Android Studio and get the behavior it previously had (build the project, load onto device, open on device).  I also need to get back interactive debugging.  Whenever I try to click the button it does nothing and eventually grays itself out.  I notice it throws an AssertionError with this stacktrace:
null
java.lang.AssertionError
    at com.android.tools.idea.gradle.invoker.GradleTasksExecutor.invokeGradleTasks(GradleTasksExecutor.java:229)
    at com.android.tools.idea.gradle.invoker.GradleTasksExecutor.run(GradleTasksExecutor.java:184)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$TaskRunnable.run(ProgressManagerImpl.java:464)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$2.run(ProgressManagerImpl.java:178)
    at com.intellij.openapi.progress.ProgressManager.executeProcessUnderProgress(ProgressManager.java:209)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:212)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.runProcess(ProgressManagerImpl.java:171)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$8.run(ProgressManagerImpl.java:373)
    at com.intellij.openapi.application.impl.ApplicationImpl$8.run(ApplicationImpl.java:435)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)
    at com.intellij.openapi.application.impl.ApplicationImpl$1$1.run(ApplicationImpl.java:152)

I have seen other posts for AssertionError but not for this line.  Right now I'm building with a custom shell script I made to execute Gradle and fire off the ADB command.  I'd really like this integrated with Android Studio though.  Any ideas?  Is this just a bug?  Is there a way to launch interactive debugging with Android Studio using adb and the command line?  If I had that option I probably wouldn't care so much.  Thanks.
Using Android Studio 0.4.0 and Gradle 1.9

A: Try my solution here and see if it works for you:
android studio 0.4.2: Gradle project sync failed error
Do you have JAVA_HOME and GRADLE_HOME env variables set up correctly ? (ie pointing to the correct locations?)
Do you get the same error if you create a new project ?


text:
Q: useEffect tries to read property of object before the state was updated in React I am cascading data to my components with createContext() in React. In this I have an API call, where I'm fetching two different arrays of objects, mapping over them, and creating a final set of data like:
const [organizationData, setOrganizationData] = useState([
    {
        id: "",
        orgName: "",
        street: "",
        city: ""
    }
])

const organizationFunction = async () => {
    try {
        const data = await axios
        .get(
            API_URL + `organizations/${someUniqueId}`
        )
        .then(res => {
            const masterData = res.data.master
            const contactData = res.data.contact
            const combinedData = masterData.map((item, i) => Object.assign({}, item, contactData[i]))
            setOrganizationData(combinedData)
        })
        setOrgLoading(true)
    } catch (e) {
        alert(e)
    }
}

Then I send the data to children
<AuthContext.Provider organizationData={organizationData}>
    {children}
</AuthContext.Provider>

Now, when I try to access this data from one of the children, specifically to populate the inputs of a form with the data from the database, with the help of useEffect when the component is mount, it crashes because in the beginning organizationData is undefined, just the empty object I have defined upfront, so it tries to read organizationData.orgName and breaks with Cannot read property 'orgName' of undefined.
If I console.log(organizationData) in the Context component, the output is
[{…}]
0: {id: "", orgName: "", street: "", city: ""}

(1) [{…}]
0: {id: 12, orgName: "MyOrganization", street: "Skalitzerstr. 31", city: "Berlin"}

So the first output is empty and then the state updates.
I have tried to short circuit when adding data to my form in my child component but that is not working, it still crashes with Cannot read property 'orgName' of undefined.
useEffect(() => {
    setFillingData({
      ...fillingData,
      orgName: organizationData.orgName || "",
      ...
  })
}

Any idea what exactly is wrong here, and how can I avoid exporting organizationData before the state was updated and the data/object created?
Thanks!

A: You can add organizationData in dependency array of useEffect
useEffect(() => {
  if(organizationData){
    setFillingData({
      ...fillingData,
      orgName: organizationData.orgName || "",
      ...
   })
  }
}, [organizationData])


text:
Q: Efficient NumPy way of rolling nanstd I have a 1-D NumPy array where I create a rolling window and then compute the np.nanstd:
import numpy as np

def rolling_window(a, window):
    a = np.asarray(a)
    shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
    strides = a.strides + (a.strides[-1],)

    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)

if __name__ == "__main__":
    n = 100_000_000
    nan_indices = np.random.choice(np.arange(n), size=1000, replace=False)
    T = np.random.rand(n)
    T[nan_indices] = np.nan
    m = 50
    np.nanstd(rolling_window(T, m), axis=T.ndim)

However, I noticed that not only is this extremely time consuming, it also uses a lot of memory. Is there a way to improve both the memory and speed performance (Numba is an option)?

A: NumPy vectorized
After grueling through the math, here's what I ended up with few np.convolve and some masking to get a vectorized NumPy solution -
def nanstd(a, W):
    k = np.ones(W, dtype=int)
    m = ~np.isnan(a)
    a0 = np.where(m, a,0)

    n = np.convolve(m,k,'valid')
    c1 = np.convolve(a0, k,'valid')
    f2 = c1**2
    p2 = f2/n**2
    f1 = np.convolve((a0**2)*m,k,'valid')+n*p2
    out = np.sqrt((f1 - (2/n)*f2)/n)
    return out

*

*Complete Explanation is at the end of this post.

Pandas equivalent
Here's the equivalent pandas version, which isn't too bad on performance -
import pandas as pd

def pdroll(T,m):
    return pd.Series(T).rolling(m).std(ddof=0).values[m-1:]

Benchmarking
Using benchit package (few benchmarking tools packaged together; disclaimer: I am its author) to benchmark proposed solutions.
def setup(n):
    nan_indices = np.random.choice(np.arange(n), size=10, replace=False)
    T = np.random.rand(n)
    T[nan_indices] = np.nan
    return T

import benchit
f = {'rolling': lambda T,m: np.nanstd(rolling_window(T, m), axis=T.ndim),
     'pdroll': pdroll, 'conv':nanstd}
in_={(n,w):(setup(n),w) for n in 10**np.arange(2,6) for w in [5,10,20,50,80,100]}
t = benchit.timings(f, in_, multivar=True)
t.plot(logx=True, sp_ncols=2, save='timings.png', dpi=200)

NumPy one is good on smaller window sizes, while pandas is better on larger ones.

NumPy vectorized : Explanation on NumPy version nanstd
Basically, np.nanstd is computing std ignoring NaNs. Now, std can be computed based on mean.
Thus, for an array a with no NaNs, it would be :
np.sqrt(np.mean((a-np.mean(a))**2))   # (1)

Let's prove it :
In [43]: a = np.arange(1,6).astype(float)

In [44]: np.nanstd(a)
Out[44]: 1.4142135623730951

In [45]: np.sqrt(np.mean((a-np.mean(a))**2))
Out[45]: 1.4142135623730951

Now, let's say, we have a NaN in it :
In [46]: a[2] = np.nan

In [47]: a
Out[47]: array([ 1.,  2., nan,  4.,  5.])

The std with nanstd would be :
In [48]: np.nanstd(a)
Out[48]: 1.5811388300841898

Let's figure out the equivalent one based on (1).
Let's start with (a-np.mean(a))**2.
This one : ?
In [72]: (a-np.mean(a))**2
Out[72]: array([nan, nan, nan, nan, nan])

No!
This one : ?
In [73]: (a0 - np.sum(a0)/n)**2
Out[73]: array([4., 1., 9., 1., 4.])

No! Because a is :
In [76]: a
Out[76]: array([ 1.,  2., nan,  4.,  5.])

We need to make the NaN position one 0.
This one : ?
In [75]: m*((a0 - np.sum(a0)/n)**2)
Out[75]: array([4., 1., 0., 1., 4.])

Yes!
Then, what's np.mean((a-np.mean(a))**2)? It would be, sum of those in [75] divided by n :
In [77]: np.sum(m*((a0-np.sum(a0)/n)**2))/n
Out[77]: 2.5

Hence, the final std value :
In [78]: np.sqrt(np.sum(m*((a0-np.sum(a0)/n)**2))/n)
Out[78]: 1.5811388300841898

Summarizing :
In [55]: m = ~np.isnan(a)       # (2)
    ...: a0 = np.where(m, a,0)
    ...: n = m.sum()
    ...: out0 = np.sqrt(np.sum(m*((a0-np.sum(a0)/n)**2))/n)

In [56]: out0
Out[56]: 1.5811388300841898

Next part is incorporating the sliding nature. So, we need to do (2) in a sliding nature. So, the first two steps remains.
Hence, it starts off with :
m = ~np.isnan(a)
a0 = np.where(m, a,0)

But the last two would change, let's see how.
Let's focus on the final step to compute out0. We have :
m*((a0-np.sum(a0)/n)**2)

Then, we compute the summation :
np.sum(m*((a0-np.sum(a0)/n)**2))

We have : (a-b)**2 = a**2 + b**2 - 2*a*b. So, earlier step becomes
np.sum(m*(a0**2 + (np.sum(a0)/n)**2 - 2*a0*np.sum(a0)/n))

Further re-arranging leads to :
np.sum(m*(a0**2 + (np.sum(a0)/n)**2) - np.sum(2*a0*np.sum(a0)/n))

np.sum(m*(a0**2 + (np.sum(a0)/n)**2)) - np.sum(2*a0*np.sum(a0)/n)

np.sum(m*(a0**2 + (np.sum(a0)/n)**2)) - 2*np.sum(a0*np.sum(a0))/n

np.sum(m*(a0**2 + (np.sum(a0)/n)**2)) - (2/n)*np.sum(a0*np.sum(a0)) # (3)

Let's focus on the first two parts for the summation.
Also, let's take a sample case to make things concrete. We will setup two datasets - One for the complete array setup and another a windowed version of the complete one.
Setup :
#=========================== 1. Complete setup
a = np.arange(1,10).astype(float)
a[[2,5]] = np.nan

W = 5
k = np.ones(W, dtype=int)
m_comp = ~np.isnan(a)
a0_comp = np.where(m_comp, a,0)

n_comp = np.convolve(m_comp,k,'valid')
c1 = np.convolve(a0_comp, k,'valid')
c2 = np.convolve((a0_comp**2)*m_comp,k,'valid')

#=========================== 2. Windowed setup
a1 = np.arange(1,6).astype(float)
a1[2] = np.nan
m = ~np.isnan(a1)
a0 = np.where(m, a1,0)
n = m.sum()
out0 = np.sqrt(np.sum(m*((a0-np.sum(a0)/n)**2))/n)

From windowed setup, we have :
In [51]: np.sum(m*(a0**2 + (np.sum(a0)/n)**2))
Out[51]: 82.0

In [52]: np.sum(m*(a0**2) + m*((np.sum(a0)/n)**2))
Out[52]: 82.0

In [53]: np.sum(m*(a0**2)) + np.sum(m*((np.sum(a0)/n)**2))
Out[53]: 82.0

First summation part :
In [86]: np.sum(m*(a0**2))
Out[86]: 46.0

# complete setup version :
In [87]: c2
Out[87]: array([ 46.,  45.,  90., 154., 219.])

Second summation part :
In [54]: np.sum(m*((np.sum(a0)/n)**2))
Out[54]: 36.0

# complete setup version :
In [55]: n_comp*(c1/n_comp)**2
Out[55]:
array([ 36.        ,  40.33333333,  85.33333333, 144.        ,
       210.25      ])

The remaining piece of puzzle fromn (3) is :
In [79]: (2/n)*np.sum(a0*np.sum(a0))
Out[79]: 72.0

Let's focus on the meat of it :
In [80]: np.sum(a0*np.sum(a0))
Out[80]: 144.0

On the complete setup, it would correspond to :
In [81]: c1**2
Out[81]: array([144., 121., 256., 576., 841.])

Thus, for the entire remaining piece :
In [82]: (2/n)*np.sum(a0*np.sum(a0))
Out[82]: 72.0

# complete setup version :
In [83]: (2/n_comp)*c1**2
Out[83]:
array([ 72.        ,  80.66666667, 170.66666667, 288.        ,
       420.5       ])

Hence, (3) and its complete version counterpart would be :
In [89]: np.sum(m*(a0**2 + (np.sum(a0)/n)**2)) - (2/n)*np.sum(a0*np.sum(a0))
Out[89]: 10.0

In [90]: c2 + n_comp*(c1/n_comp)**2 - (2/n_comp)*c1**2
Out[90]: array([10.        ,  4.66666667,  4.66666667, 10.        ,  8.75      ])

To get the final std values, we need to divide by the count of valid ones per window and then apply sqrt :
In [99]: np.sqrt((c2 + n_comp*(c1/n_comp)**2 - (2/n_comp)*c1**2)/n_comp)
Out[99]: array([1.58113883, 1.24721913, 1.24721913, 1.58113883, 1.47901995])

Hence, with some cleanup, we end up with the final nanstd version.


text:
Q: Convergence in $L^1 \cap L^2$ I am very confused about the following:
Assume we have a sequence of functions $f_n \in$$L^1 \cap L^2 (\mathbb{R}^n)$. Then is it true that if this sequence is Cauchy both in $L^1$ and $L^2$, two limits coincide as a function in $L^1 \cap L^2$?
To make the question more general, lets say we have a space $X$ with two Hausdorff topologies. If a sequence of points which has a unique limit in both topologies, when is it guaranteed that two limits coincide?

A: A set $X$ can have two metrics $d$ and $d'$ (and thus Hausdorff topologies) and a sequence $(x_n)$ so that the limits $x$ and $x'$ are different.
For example, take $X=[0,1]$ and let $d$ be the usual metric.
Let $f:X\to X$ be the bijection that interchanges $0$ and $1$ but fixes all other points.
Let $d'(a,b)=d(f(a),f(b))$.
If $x_n=1/n$, then the limit points are $x=0$ and $x'=1$.
A similar argument by swapping points works for more general topological spaces as well, so there seems to be no way to guarantee a common limit without any compatibility assumptions between the two topologies.


text:
Q: Google Chrome Extensions Interacting With Secure Website There is a third-party google chrome extension that has been written to interact with my website.   It automatically logs a client computer into my website and then submits information to a particular page on my website.
Once this client computer is logged into my secure website, is there a way for this Chrome extension to extract information from other pages that would only be visible when a user is logged into my website?

A: Yes, chrome extensions have full access to everything you are doing in the browser while the extension is enabled.


text:
Q: API Calls bombs in loop when object not found My code is erroring out when the object "@odata.nextLink" is not found in the JSON. I thought the while loop was supposed to account for this? I apologize if this is rudimentary but this is my first python project, so i dont know the stuffs yet.
Also, for what it is worth, the api results are quite limited, there now "total pages" value I can extract

# Import Python ODBC module
import pyodbc
import requests
import json
import sys

cnxn = pyodbc.connect(driver="{ODBC Driver 17 for SQL Server}",server="theplacewherethedatais",database="oneofthosedbthings",uid="u",pwd="pw")
cursor = cnxn.cursor()

storedProc = "exec GetGroupsAndCompanies"

for irow in cursor.execute(storedProc):

    strObj = str(irow[0])
    strGrp = str(irow[1])
    print(strObj+" "+strGrp)
    response = requests.get(irow[2], timeout=300000, auth=('u', 'pw')).json()
    data = response["value"]
    while response["@odata.nextLink"]:
        response = requests.get(response["@odata.nextLink"], timeout=300000, auth=('u', 'pw')).json()
        data.extend(response["value"])

cnxn.commit()
cnxn.close()

A: You can use the in keyword to test if a key is present:
while "@odata.nextLink" in response:


text:
Q: installing rails rake conflicts with usr/bin/rake After using command "$ sudo gem install rails", an error occurred saying "rake's executable "rake" conflicts with /usr/bin/rake". I have searched errors regarding this install and can't find any solutions. Please Help!

A: All I can recommend is try to setup your environment for development or production on a non-sudo-user base.
A great tool I prefer and use for managing multiple rubies and gems is rvm
The best place for up-to-date-how-to-start-with-rails is the RailsApps Project


text:
Q: How to change a block texture but not the item? i changed the texture of the chest of minecraft so it is invisible for a map of mine, but as the item is the block itself it is invisible in the inventory as well, i searched and there is no chest in the item textures folder, is it possible to create a item.chest file ?

A: Blocks in Minecraft are made out of voxels with individual sides.
The stone block texture is flat. In order to put it in 3D space, it has to be manipulated somehow.

It is mapped to a voxel by setting each face to the texture. (Stone uses a random rotation, but that's irrelevant). This image is used as both the block in-game and the item model.

Blocks like the chest and hopper are more complex, as they don't fill the whole block and have unique sides.
The block is flattened out, and stitched together by hard-coded constraints. This is like when you have a piece of paper that you can fold out into a cube, but without the glue tabs and with image manipulation instead of folds.

As I said earlier, the mapped voxel is what is used for the item model. This means it will look the same in your inventory as it does when placed. So if you want to place an invisible block, the item has to be invisible too.
TL;DR - No, you can't make an 'item.chest' file.


text:
Q: Выполнение команд в окне программы Linux.
bash.
У меня имеется программа #1, при запуске которой открывается консоль самой программы #1. В программе #1 можно вводить свои команды, но основные команды терминала работать не будут. Также и наоборот.
Теперь я хочу сделать программу #2 на bash, которая могла бы выполнять команды в программе #1. Если я создаю простую программу #2 где она выполняет например команду help, то она выполняет ее в основном терминале, а не в программе #1. Дело в том, что у программы #1 нет открытого кода и мне нужно придумать обходной путь.


text:
Q: exact fetch returns more than requested number of rows in a triger execution I am creating a trigger for auto_generating prod_id from prod_summery
the given table is
PROD_ID CHAR(8 BYTE)    No      1
PRODUCT_TITLE   VARCHAR2(30 BYTE)   No      2
PRODUCT_SUMMERY VARCHAR2(150 BYTE)  No      3
INTEREST_TYPE   CHAR(1 BYTE)    No      4
INTEREST_RATE   NUMBER(4,2) No      5
SECURITY_REQD   CHAR(1 BYTE)    No      6
MIN_LOAN_AMT    NUMBER(11,2)    No      7
MAX_LOAN_AMT    NUMBER(11,2)    No      8
TERM_MIN    INTERVAL YEAR(2) TO MONTH   No      9
TERM_MAX    INTERVAL YEAR(2) TO MONTH   No      10
REPAYMENT_FREQUENCY INTERVAL YEAR(2) TO MONTH   No      11
REPAYMENT_AMT   NUMBER(11,2)    No      12
EARLY_REPAY_ALLOWED CHAR(1 BYTE)    No      13
MIN_AGE_LIMIT   NUMBER(2,0) No      14
MAX_AGE_LIMIT   NUMBER(2,0) No      15
RESIDENT    RESIDENT_VARRAY No      16
PROD_START_DT   DATE    Yes     17
PROD_END_DT DATE    Yes     18
PROD_STATUS CHAR(1 BYTE)    No      19

Trigger
create or replace TRIGGER LOAN_PROD_ID_TR1
    BEFORE INSERT ON LOAN_PROD_TAB
   for each row
    DECLARE
      v_length number(2):=LENGTH(:NEW.PRODUCT_SUMMERY)-
         LENGTH(REPLACE(:NEW.PRODUCT_SUMMERY,' ',' '))+1;
         V_W2 VARCHAR2(10);
        V_W3 VARCHAR2(10);
     V_W4 VARCHAR2(10);
      V_W5 VARCHAR2(10);
V_W6 VARCHAR2(10);
 V_CON VARCHAR2(10);
V_CON1 VARCHAR2(10);
V_CON2 VARCHAR2(10);
BEGIN
 IF v_length=1 THEN
 SELECT 'CBIS'||LPAD(:NEW.PRODUCT_SUMMERY,4) INTO :NEW.PROD_ID FROM
 LOAN_PROD_TAB;
  ELSIF v_length=2 THEN
  V_W2:=SUBSTR(REGEXP_SUBSTR(:NEW.PRODUCT_SUMMERY,'(\S*)(\s)',1,2),1,2);
  V_W3:=SUBSTR(REGEXP_SUBSTR(:NEW.PRODUCT_SUMMERY,'(\S*)'),1,2);
    SELECT 'CBIS'||LPAD(V_W2,4,V_W3) INTO :NEW.PROD_ID FROM LOAN_PROD_TAB;
    ELSIF v_length=3 THEN
  V_W2:=SUBSTR(REGEXP_SUBSTR(:NEW.PRODUCT_SUMMERY,'(\S*)($)'),1,1);
   V_W3:=SUBSTR(REGEXP_SUBSTR(:NEW.PRODUCT_SUMMERY,'(\S*)(\s)',1,2),1,2);
   V_W4:=SUBSTR(REGEXP_SUBSTR(:NEW.PRODUCT_SUMMERY,'(\S*)'),1,2);
    V_CON:=CONCAT(V_W3,V_W2);
   SELECT 'CBIS'||LPAD(V_W4,4,V_CON) INTO :NEW.PROD_ID FROM LOAN_PROD_TAB;
   ELSIF v_length=4 THEN
    V_W2:=SUBSTR(REGEXP_SUBSTR(:NEW.PRODUCT_SUMMERY,'(\S*)'),1,1);
     V_W3:=SUBSTR(REGEXP_SUBSTR(:NEW.PRODUCT_SUMMERY,'(\S*)(\s)',1,2),1,1);
   V_W4:=SUBSTR(REGEXP_SUBSTR(:NEW.PRODUCT_SUMMERY,'(\S*)(\s)',1,3),1,1);
   V_W5:=SUBSTR(REGEXP_SUBSTR(:NEW.PRODUCT_SUMMERY,'(\S*)($)'),1,1);
    V_CON:=CONCAT(V_W2,V_W3);
      V_CON1:=CONCAT(V_W4,V_W5);
    V_CON2:=CONCAT(V_CON,V_CON1);
    SELECT 'CBIS'||LPAD(V_CON2,4) INTO :NEW.PROD_ID FROM LOAN_PROD_TAB;
        ELSE
        V_W2:=SUBSTR(REGEXP_SUBSTR(:NEW.PRODUCT_SUMMERY,'(\S*)'),1,1);
         V_W3:=SUBSTR(REGEXP_SUBSTR(:NEW.PRODUCT_SUMMERY,'(\S*)(\s)',1,2),1,1);
         V_W4:=SUBSTR(REGEXP_SUBSTR(:NEW.PRODUCT_SUMMERY,'(\S*)(\s)',1,3),1,1);
      V_W5:=SUBSTR(REGEXP_SUBSTR(:NEW.PRODUCT_SUMMERY,'(\S*)(\s)',1,4),1,1);
      V_CON:=CONCAT(V_W2,V_W3);
    V_CON1:=CONCAT(V_W4,V_W5);
    V_CON2:=CONCAT(V_CON,V_CON1);
         SELECT 'CBIS'||LPAD(V_CON2,4) INTO :NEW.PROD_ID FROM LOAN_PROD_TAB;
         END  IF;
     END;

A: your error is caused by the select statements, e.g.
SELECT 'CBIS'||LPAD(:NEW.PRODUCT_SUMMERY,4) INTO :NEW.PROD_ID
FROM LOAN_PROD_TAB;

if there is more than one record in the table you will get an error as you are selecting everything from the table.
You shouldn't need to do a select here, you should be able to just do
:NEW.PROD := 'CBIS'||LPAD(:NEW.PRODUCT_SUMMERY,4);

A: TOO-MANY-ROWS is returned by one of SELECT statements. Basically, no wonder - none of them contains the WHERE clause.
On the other hand, I think that you shouldn't use SELECT at all; trigger is on LOAN_PROD_TAB, and you're selecting from it - that leads to a mutating table error. Instead, you should rewrite them (example based on your first SELECT) into
   :NEW.prod_id := 'CBIS' || LPAD (:NEW.PRODUCT_SUMMERY, 4);

Oh, yes - one more thing: for your own sake, learn how to properly format code. Using such an unreadable mess is a nightmare.


text:
Q: How can read Random Access Fıle? I have this characters ("abcdef") in a file.
I want to separate these letters in 3-digit format as follows:
1-2-3.term of this phrase = abc
2-3-4.term of this phrase = bcd
3-4-5.term of this phrase = cde
4-5-6.term of this phrase = def

I wrote this code but started reading in reverse (result is "def" but I want "abc" ).
#include <stdio.h>

int main(void) {

   FILE *fp;
   char ch;
   int num=3;
   long length;

   fp = fopen("test.txt", "r");
   if (fp == NULL) {
      puts("cannot open this file");
   }

   fseek(fp, 0, SEEK_SET);
   length = ftell(fp);
   fseek(fp, (length-num), SEEK_END);

   do {
      ch = fgetc(fp);
      putchar(ch);
   } while (ch != EOF);

   fclose(fp);
   return(0);
}

How can I fix this?


text:
Q: Fast writing to file - Sometimes the file is empty Modification
After some investigation I can reproduce my problem with this test code. The problem is unrelated to thread but to fast writing :
public static void main(String[] args) {
    String text = "Testing fast writing in file";
    for (int i = 0 ; i < 100000 ; i++) {
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter(new File("temp.txt")));
            bw.write(text);
        } catch(Throwable t) { // Ensure there is no throwable for the test
            System.err.println(t.getMessage());
        } finally {
            if(bw != null) {
                try {
                    bw.close();
                } catch (IOException ioe) {
                    System.err.println(ioe.getMessage());
                }
            }
        }
    }
}

Opening with Notepad++ at different times, I've sometime an empty file.
What would be the best way to avoid this ?

ORIGINAL QUESTION
I'm analyzing a problem where multiple Threads (can go up to 60) are writing on the same file using JAXB Marshaller. Note that the myObject is shared between Threads.
Here is the original code:
Marshaller m = jaxbContext.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(myObject, myFile);

The problem is that sometimes when I take a look at the file, it's empty (myObject is never empty nor null). This file allow us to resume some job later if the service crashes.
Thinking the marshalling process could be long I first wrote in a Buffer and then write to the file :
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(8192);
marshaller.marshal(myObject, outputStream);
String result = outputStream.toString();
if (result != null && !result.isEmpty()) {
  BufferedWriter bw = null;
  try {
    bw = new BufferedWriter(new FileWriter(myFile));
    bw.write(result);
    bw.flush(); // I know close() should do that, but I tried too
  } catch(IOException ioe) {
    ...
  } finally {
    ... close the bw
  }

problem still there. So I also tried to add synchronized to the method (the only one used to write to the file) but I've got the same problem.
Finally I also tried to keep a static boolean to know if I'm in a writing process:
if (!processing) {
  processing = true;
  try {
  Marshaller marshaller = jaxbContext.createMarshaller();
  ...
  ... close file writer
  processing = false;
}

Same behaviour, what would be the best way to avoid having an empty file ? I'm a bit puzzled on that now.

A: I think you are misinterpreting the use of the FileWriter. In the example shown, you write with multiple threads at the same time in the same file, but the way the FileWriter works is that it resets the content of the file unless you explicitly tell it to append.
FileWriter fw = new FileWriter(new File("temp.txt"), true);

If you don't want to append you need to make sure that only one thread is writing to the file. Also inspecting the file which seems empty might just happen to be at the same time that the file get cleared before the writer starts to do his it's job.

A: Here is what I came with for the moment :
Write in a temp file, once it's done rename it.
The final file is always filled.
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(myObject, myFileTmp);

if (myFileTmp.exists() && myFileTmp.length() > 0) {
  myFile.delete();
  myFileTmp.renameTo(myFile);
}

I then modified the code to make only one thread write to the file.


text:
Q: Dephi read registry on Windown 7 x64 I have value in registry (Windows 7 x64):
[HKEY_CLASSES_ROOT\.html]
@="ChromeHTML"

Then i read via my ServiceApplication on Delphi 7:
Reg := TRegistry.Create(KEY_ALL_ACCESS or KEY_WOW64_32KEY);
  try
    Reg.RootKey := HKEY_CLASSES_ROOT;

    Reg.OpenKey('.html', False);
    Default := Reg.ReadString('');

I have got htmlfile in my Default variable.
How can i get correct value?
ps: Same code in destop application reads correct value.

A: HKEY_CLASSES_ROOT is a merged view of the HKEY_LOCAL_MACHINE\Software\Classes and HKEY_CURRENT_USER\Software\Classes keys, where a value present in HKCU has priority over a corresponding value present in HKLM.  By default, a service does not run in the same user account as a desktop app does.  So, for the user account that the service is actually running as, either htmlfile exists in that user's HKCU key, or no value exists in HKCU but htmlfile does exist in the HKLM key instead.
In order for the service to see the same data that the desktop app sees, the service has to access the Registry as the same user.  You need to either:

*

*configure the service in the SCM to run as that user account.

*have the service dynamically impersonate the user account using ImpersonateLoggedOnUser() or similar function, then open that user's HKEY_CLASSES_ROOT key normally.

*have the service dynamically obtain a token to the user account, such as from LogonUser() or OpenProcessToken(), then use the LoadUserProfile() and RegOpenUserClassesRoot() functions to access that user's HKEY_CLASSES_ROOT key.


text:
Q: Search a book name by using prefix in less complexity java Problem statement:
Consider a library which has millions of books. Thousands of books are being added and removed each minute. The Problem is to find all the books available by using a prefix (given as input) with minimum time and space complexity in java.
Example,
Books - {'abcd','abda','aaqe','abc'}

input: ab

output: 3 // because there are 3 book names starting with 'ab'

input: abc

output: 2

input: a

output: 4

This can be done using just loops but as I said before this needs to be done in minimum time and space complexity in java.
Thanks in advance
Update - Since everyone asked me to at least try and write my own code, I am updating this. This problem was given to me in an interview. I tried this using a hashmap and it convinced the interviewer but I'm still thinking that there are some good data structures or algorithms for this purpose.
I'm not asking anyone to solve this by writing code for me. I'm just asking an idea on which data structure to use for minimum complexity since I'm still learning data structures and algorithms.
Sorry if this is a stupid question.
Thank you

A: You can use the data structure called Trie to achieve the same.
I found this to be useful as it is concise and explains what a trie is and how it is different from other Data Structures.
You can also refer to other sources online to get a better understanding of Trie.


text:
Q: Cannot find 'System Type' in 'menuconfig' I ran menuconfig on my jetson AGX Xavier but I cannot find the System Type in it. I also have a Tegra K1 on which I can find the system type successfully.
What I want to do is to disable cache L1 (I-cache and D-cache), and it is supposed to be under the System Type in the menuconfig while I can't find it.
I also attached the pic of what I got.

And this is the 'System Type' that I got on my TK1 board.

But I cannot find it on Jetson AGX Xavier board.
Thank you so much for your help!


text:
Q: How to send an email to yourself, from react frontend I know this sounds very similar to other questions, but it's a little more confusing. The person I'm making the website for wants to make an ordering system, in which you pick your product, then when you click the order button, it sends an email to him. I've tried using an 'a' tag with a href of mailto, but that opens your mail system, which isn't what I want.
If any of you guys have used J-lab test prep, at the end of your session, you can email your results to your teacher with the click of a button, without opening your mail client.
Edit:
I realized I probably need a server for that to host the email, does anyone know how to make that type of back-end?
Thanks in advance!


text:
Q: Command prompt within another widget I have a GUI with label and entry widgets on a frame widget. I want to add a command prompt.to the frame through which the user can submit commands. I know about using the cmd module to create a prompt in the python shell, but I want the prompt to be part of my GUI window. Is there a way to 'embed' a command prompt in a canvas for example? Right now I am using Cmd.init(self) and cmdloop to start a prompt in python shell...
Just to clarify further, I would like the shell to run from within my GUI window (e.g. inside a canvas), and not as its own window. Is that possible?

A: The cmd module was made for terminals, where there's just one textual "widget" used for both input and output. This is not really suited for a GUI.
Here's an idea (inspired by web frameworks like Pyramid) that works better:
Have a read-only widget for the output, and a separate widget for the command entry.
When the user presses Enter, copy the command to the output box (prefixing with '>>>' and '...' as necessary), run the command (using compile_command and run_code from the code module, with redirecting sys.stdout to a StringIO that gets appended to the output), and then append the output in the output box.


text:
Q: Python if else micro-optimization In pondering optimization of code, I was wondering which was more expensive in python:
if x:
    d = 1
else:
    d = 2

or
d = 2
if x:
    d = 1

Any thoughts?  I like the reduced line count in the second but wondered if reassignment was more costly than the condition switching.

A: You should probably benchmark this, but there's also a third form that uses the ternary operator:
d = 1 if x else 2

A: Don't ponder, don't wonder, measure -- with timeit at the shell command line (by far the best, simplest way to use it!). Python 2.5.4 on Mac OSX 10.5 on a laptop...:
$ python -mtimeit -s'x=0' 'if x: d=1' 'else: d=2'
10000000 loops, best of 3: 0.0748 usec per loop
$ python -mtimeit -s'x=1' 'if x: d=1' 'else: d=2'
10000000 loops, best of 3: 0.0685 usec per loop
$ python -mtimeit -s'x=0' 'd=2' 'if x: d=1'
10000000 loops, best of 3: 0.0734 usec per loop
$ python -mtimeit -s'x=1' 'd=2' 'if x: d=1'
10000000 loops, best of 3: 0.101 usec per loop

so you see: the "just-if" form can save 1.4 nanoseconds when x is false, but costs 40.2 nanoseconds when x is true, compared with the "if/else" form; so, in a micro-optimization context, you should use the former only if x is 30 times more likely to be false than true, or thereabouts.  Also:
$ python -mtimeit -s'x=0' 'd=1 if x else 2'
10000000 loops, best of 3: 0.0736 usec per loop
$ python -mtimeit -s'x=1' 'd=1 if x else 2'
10000000 loops, best of 3: 0.076 usec per loop

...the ternary operator of the if/else has its own miniscule pluses and minuses.
When the differences are as tiny as this, you should measure repeatedly, establish what the noise level is, and ensure you're not taking differences "in the noise" as significant.  For example, to compare statement vs expression if/else in the "x is true" case, repeat each a few times:
$ python -mtimeit -s'x=1' 'd=1 if x else 2'
10000000 loops, best of 3: 0.076 usec per loop
$ python -mtimeit -s'x=1' 'd=1 if x else 2'
10000000 loops, best of 3: 0.0749 usec per loop
$ python -mtimeit -s'x=1' 'd=1 if x else 2'
10000000 loops, best of 3: 0.0742 usec per loop
$ python -mtimeit -s'x=1' 'd=1 if x else 2'
10000000 loops, best of 3: 0.0749 usec per loop
$ python -mtimeit -s'x=1' 'd=1 if x else 2'
10000000 loops, best of 3: 0.0745 usec per loop

now you can state that the expression forms takes (on this machine and versions of key software) 74.2 to 76.0 nanoseconds -- the range is much more expressive than any single number would be.  And similarly:
$ python -mtimeit -s'x=1' 'if x: d=1' 'else: d=2'
10000000 loops, best of 3: 0.0688 usec per loop
$ python -mtimeit -s'x=1' 'if x: d=1' 'else: d=2'
10000000 loops, best of 3: 0.0681 usec per loop
$ python -mtimeit -s'x=1' 'if x: d=1' 'else: d=2'
10000000 loops, best of 3: 0.0687 usec per loop
$ python -mtimeit -s'x=1' 'if x: d=1' 'else: d=2'
10000000 loops, best of 3: 0.0679 usec per loop
$ python -mtimeit -s'x=1' 'if x: d=1' 'else: d=2'
10000000 loops, best of 3: 0.0692 usec per loop

now you can state confidently that the statement form takes (under identical conditions) 67.9 to 69.2 nanoseconds; so its advantage, for x true, wrt the expression form, is 4.8 to 8.1 nanoseconds (it's quite fair to restrict this latter interval estimation to 6.3 to 6.8 nanoseconds, comparing min/min and max/max instead of min/max and max/min as the wider, more prudential estimate does).
How much time and energy is worth devoting to such microscopic differences, once you've realized for any given care that they are microscopic, is, of course, a different issue.

A: The second one should obviously be more expensive, it does the same operations if x is false and twice the assignments if x is true.
Assumption: assignment is more expensive in python than a conditional jump, which makes sense since its interpreted and it has to read a run time hash to get the new value then upload it in the same hash.

A: I would argue that the one that is most readable is the most optimized (for readability at least).
The if...else construct makes it clear that you are dealing with an either/or case.
The assignment construct might make more sense if (d==2) is the usual value and your if tests for an unusual case.  This construct becomes less clear if your assignment gets moved away from the if.
In this simple example it doesn't really matter.  For more complex code, I would almost always optimize for readability, even at the expense of a few CPU cycles.


text:
Q: pyCharm: append(int) flagged correctly or not? I've recently switchedfrom using a text editor to the PyCharm IDE, and while a minimal example is fine:
def temp():
    a_list = [[], []]
    value = int(5)
    a_list[1].append(value)
    print(a_list)

However for this function:
# replays is parsed json data. cache is a caching class for player stats
def team_average_ratings(replays, cache):
    """returns an array containing a dict of the average rating of the green and red teams"""
    team_ratings = []
    for battle in replays:
        teams = [[], []]
        std = battle.get('std')
        for player in std.get('vehicles').values():
            name = player.get('name')
            cached_player = cache.cached_player(name)
            if cached_player:
                rating = int(cached_player.get('global_rating'))
                team_num = player.get('team') - 1 # 1-indexed -> 0-indexed
                if name == std.get('playerName'):
                    # note player's team and eliminate them from the calculation
                    replay_team = team_num
                else:
                    teams[team_num].append(rating)
        team_ratings.append({'green': mean(teams[replay_team]),
                             'red': mean(teams[1 - replay_team])})
    return team_ratings

The IDE flags the line:

This can be rectified by modifying the line to read:
list(teams[team_num]).append(rating)

however when editing the line, the IDE correctly identifies that teams[team_num] is a list.
The code works correctly when run by the interpreter.
Is this a case of my doing something particularly obtuse, or is there a problem with the parser in the IDE?


text:
Q: Método para comprobar si una tabla esta vacia ¿Alguien podría decirme como puedo verificar si una tabla de la bd de mi app esta vacía?
Mi idea es llamar a un método dentro de un if y que compruebe si esta vacía o no y me devuelva un tipo de dato booleano.
if(checkDataBaseInf("cartera")==true){
  //Si existen datos perfecto
}
else{
  //Si no existen datos tareas a realizar.....
}

public boolean checkDataBase(String Database_path){
  //Ha esta parte me refiero con mi consulta del post
}

Clase que se encarga de la creación de la tabla:
public class CarteraSQLiteOpenHelper extends SQLiteOpenHelper {

public CarteraSQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, name, factory, version);
}

@Override
public void onCreate(SQLiteDatabase db) {
    //Se ejecuta las sentencias SQL de creación de las tablas
    String query = "CREATE TABLE CARTERA (id_cartera INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, saldo INTEGER);";
    db.execSQL(query);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    //En caso de cambio de version se ejecutaria esta bloque de codigo
    db.execSQL("DROP TABLE IF EXISTS CARTERA;");
    db.execSQL("CREATE TABLE CARTERA (id_cartera INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, saldo INTEGER);");
}

//Metodo que me permite abrir la tabla
public void abrirBDCartera() {
    this.getWritableDatabase();
}

//Metodo que me permite cerrar la tabla
public void cerrarBDCartera() {
    this.close();
}

//Metodo que me permite realizar insert en la tabla
public void insertarCartera(int saldo) {
    ContentValues valores = new ContentValues();
    valores.put("saldo", saldo);
    this.getWritableDatabase().insert("cartera", null, valores);
}

//Metodo que me permite realizar update en la tabla
public void modificarCartera(int saldo) {
    ContentValues valores = new ContentValues();
    valores.put("saldo", saldo);
    this.getWritableDatabase().update("cartera", valores, "id_cartera = ?", new String[]{"1"});
}
}

Hasta el momento he realizado esto:
    private boolean checkDataBaseInf(String Database_path){
    SQLiteDatabase checkDB = null;
    int count = 0;

    try {
        checkDB = SQLiteDatabase.openDatabase(Database_path, null, SQLiteDatabase.OPEN_READONLY);
        Cursor cursor = checkDB.rawQuery("SELECT count(*) FROM " + Database_path, null);

        try {
            if (cursor != null)
                if (cursor.getCount() > 0) {
                    cursor.moveToFirst();
                    count = cursor.getInt(0);
                }
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
        }

    } catch (SQLiteException e){
        Toast.makeText(getApplicationContext(), "NO BD2", Toast.LENGTH_LONG).show();
        return false;
    }

    if(count>0) {
        return false;
    }
    else {
        return true;
    }
}

¿Podria gestionarlo así?

A: Para comprobar si la tabla está vacía te sobraría con hacer una consulta para ver cuantos elementos tiene esa tabla.
A continuación te dejaré un ejemplo de consulta:
SELECT count(*) FROM tabla

Y un ejemplo de función:
public boolean checkEmpty(String tabla){
    int count = 0;
    CarteraSQLiteOpenHelper mDbHelper = new CarteraSQLiteOpenHelper(getContext());

    SQLiteDatabase db = mDbHelper.getWritableDatabase();

    Cursor cursor = db.rawQuery("SELECT count(*) FROM " + tabla, null);

    try {
        if(cursor != null)
            if(cursor.getCount() > 0){
                cursor.moveToFirst();
                count = cursor.getInt(0);
            }
    }finally {
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }
    }

    if(count>0)
       return false;
    else
       return true;
}

Otra alternativa sería la de utilizar la función queryNumEntries de la clase DatabaseUtils de la siguiente forma:
public boolean checkEmpty(SQLiteDatabase db, String tabla){
        return DatabaseUtils.queryNumEntries(db, tabla) == 0;
}

EDIT: échale un ojo a la documentación de Android sobre cómo guardar datos en BD o a este otro manual en el que te ponen ejemplos de cómo manejar las BD


text:
Q: A sufficient condition for a relaxation of Lipschitz continuity I am interested in a property that, I believe, is closely related to Lipschitz continuity. Lipschitz continuity is defined as:

Given two metric spaces $(X, d_X)$ and $(Y, d_Y)$, where $d_X$ denotes the
metric on the set $X$ and $d_Y$ is the metric on set $Y$, a function $f: X\rightarrow Y$ is called Lipschitz continuous if there exists a real constant $K \geq 0$
such that, for all $x_1$ and $x_2$ in $X$,
$d_{Y}(f(x_{1}),f(x_{2}))\leq Kd_{X}(x_{1},x_{2}).$

I focus on the case $K=1$ in which case $f$ is called a metric map and I take this relaxation:

$d_{Y}(f(x_{1}),f(x_{2}))\leq d_{X}(x_{1},x_{2}) + \varepsilon$

for a $\varepsilon \geq 0$.
I am interested in the condition:
$D_{X,Y}(x, f(x)) \leq \varepsilon$, for $D$ a metric between spaces $X$ and $Y$ and $\varepsilon\geq 0$. I'm assuming that the metric $D$ exists, for example, when $X=Y$.
That is, we are limiting where $f$ can send $x$.
I believe that this property would imply my relaxation of Lipschitz. For example, if we assume $d = D = d_Y = d_Y$, by the triangle inequality:
$d(f(x_{1}),f(x_{2}))\leq d(f(x_{1}), x_1) + d(x_2,f(x_{2})) + d(x_2,x_1)\leq 2\,\varepsilon + d(x_2,x_1).$
I am trying to find more information related to this.


text:
Q: How can I smoothly switch between a presentation and another data source? In the next couple of weeks, I'll be giving a lot of presentations using PowerPoint on Windows. Problem is, a lot of the data I want to cover doesn't belong in a PowerPoint slide. I'll be doing product demos, showing web pages, that kind of stuff. While I could record it as a video, it won't feel right, and it won't demo as well.
What I want to do is to achieve the look that Steve Jobs has during Apple keynotes, where he smoothly fades from the presentation to a demo screen and back. Jobs does this by having two different laptops and a video mux. I don't have that luxury: I've just got a single laptop.
Is there any application that allows you to smoothly fade out a window (in this case, PowerPoint) to achieve a similar effect? Or perhaps some hidden feature inside PowerPoint that covers this scenario? If not, is there some equivalent strategy that will have the same effect?

A: I've often wondered about the best way of doing this and so far I've found virtual desktops are probably the best way to go. I've used Dexpot which has plenty of customiseable options, supporting up to 20 virtual desktops. Have a prowerpoint on one desktop, fullscreen website on another, video in another. All it takes is a ctrl and 1 keystroke to switch to desktop 1, ctrl and 2 to switch to 2, and so on. It cuts in stright away, I don't know if there is an option to fade per se, but there are some trainsitions to play with.

A: If you only need to show slides and demo webapps you might be able to use Compiz with a Linux LiveCD (e.g. a recent Ubuntu). Compiz' Application Switcher should already be pretty close to what you want.
During the presentation I would then use one full screen program showing your PDF slides, and another one running your browser. You can prepare different pages in tabs and switch your browser to fullscreen hiding any tab bar.

A: A smoother and native solution on Windows is by creating a new desktop by using the task view shortcut.
Then open Powerpoint in fullscreen in a desktop, and have your browser open in another.
If you don't have the task view visible in your taskbar, you can activate by right-clicking on the taskbar and going to its settings.

A: You may want to look at Vitruawin. I'm not sure if they have the smooth transitions though. It tries to implement the linux multiple-desktop idea on windows.

A: ALT-TAB works nicely, even between full-screened web pages and other applications.  There's no transition, but if you do it quickly it looks just like a slide changing.
Command-TAB works on the Mac too in Keynote if you enable the preference setting "Slideshow -> Allow Mission Control".


text:
Q: How to set Storyboard.TargetProperty in C#? I am developing wpf application in C#. The following xaml code is working fine for me.
<VisualStateManager.VisualStateGroups>
    <VisualStateGroup x:Name="VisualStateGroup">
        <VisualState x:Name="DefaultVisualState">
            <Storyboard/>
        </VisualState>
        <VisualState x:Name="FocusVisualState">
            <Storyboard>
                <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" Storyboard.TargetName="CircleEllipse1">
                    <EasingColorKeyFrame KeyTime="0" Value="#FF0004FF"/>
                </ColorAnimationUsingKeyFrames>
                <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(TextElement.Background).(SolidColorBrush.Color)" Storyboard.TargetName="TextBlock1">
                    <EasingColorKeyFrame KeyTime="0" Value="#FFBCB0B0"/>
                </ColorAnimationUsingKeyFrames>
            </Storyboard>
        </VisualState>
    </VisualStateGroup>
</VisualStateManager.VisualStateGroups>

The same code I have written in C#
EasingColorKeyFrame easingColorKeyFrameObj = new EasingColorKeyFrame();
easingColorKeyFrameObj.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(1));
easingColorKeyFrameObj.Value = Colors.Red;
ColorAnimationUsingKeyFrames colorAnimationUsingKeyFramesObj = new ColorAnimationUsingKeyFrames();
colorAnimationUsingKeyFramesObj.KeyFrames.Add(easingColorKeyFrameObj);
Storyboard.SetTargetName(colorAnimationUsingKeyFramesObj, "CircleEllipse1");
Storyboard.SetTargetProperty(
    colorAnimationUsingKeyFramesObj, new PropertyPath("Color"));

Storyboard myStoryboard = new Storyboard();
myStoryboard.Children.Add(colorAnimationUsingKeyFramesObj);

myStoryboard.Begin(this, true);

In the above code how should I set the Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)" and Storyboard.TargetProperty="(TextElement.Background).(SolidColorBrush.Color)" in C#

A: You need to specify it as a string
private void AnimateColor(string ellipseName, Color ellipseColor, string textBlockName, Color textBlockColor)
            {
                EasingColorKeyFrame easingColorKeyFrameEllipseObj = new EasingColorKeyFrame();
                easingColorKeyFrameEllipseObj.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(12));
                easingColorKeyFrameEllipseObj.Value = ellipseColor;

                ColorAnimationUsingKeyFrames colorAnimationUsingKeyFramesEllipseObj = new ColorAnimationUsingKeyFrames();
                Storyboard.SetTargetName(colorAnimationUsingKeyFramesEllipseObj, ellipseName);
                Storyboard.SetTargetProperty(
                    colorAnimationUsingKeyFramesEllipseObj, new PropertyPath("(Shape.Fill).(SolidColorBrush.Color)"));
                colorAnimationUsingKeyFramesEllipseObj.KeyFrames.Add(easingColorKeyFrameEllipseObj);

                EasingColorKeyFrame easingColorKeyFrameTextBlockObj = new EasingColorKeyFrame();
                easingColorKeyFrameTextBlockObj.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(12));
                easingColorKeyFrameTextBlockObj.Value = textBlockColor;

                ColorAnimationUsingKeyFrames colorAnimationUsingKeyFramesTextBlockObj = new ColorAnimationUsingKeyFrames();
                Storyboard.SetTargetName(colorAnimationUsingKeyFramesTextBlockObj, textBlockName);
                Storyboard.SetTargetProperty(
                    colorAnimationUsingKeyFramesTextBlockObj, new PropertyPath("(TextElement.Background).(SolidColorBrush.Color)"));
                colorAnimationUsingKeyFramesTextBlockObj.KeyFrames.Add(easingColorKeyFrameTextBlockObj);

                Storyboard storyboard = new Storyboard();

                storyboard.Children.Add(colorAnimationUsingKeyFramesEllipseObj);
                storyboard.Children.Add(colorAnimationUsingKeyFramesTextBlockObj);

                storyboard.Begin(this, true);
            }


text:
Q: Проблема доработки скомпилированного js У меня есть скомпилированный js файл, где вместе пару библиотек, а так же некоторый пользовательский скрипт. Изначально сайт был одностраничный, а теперь я дорабатываю ещё несколько страниц.
В консоли возникает ошибка о том, что некоторые элементы на моих страницах не найдены и код перестаёт работать.
Можно было бы к моим страницам не подключать этот файл, а делать всё в другом, но я собираюсь вёрстку в дальнейшем натягивать на WP.
Подскажите, какие могут быть решения?

A: У вас в коде есть строки, которые ищут элемент на странице, ошибка возникает в том, что элемент не удалось найти и в таком случае скрипт перестает работать. Добавьте дополнительные проверки на undefined и всё будет работать.


text:
Q: Calculating the Min of Date from the related list I am having one big task and from the last 2 weeks I am working on to solve it but without any result. Please help me out to solve this puzzle.
So we are having one object Entity group, which is the collection of all the Accounts. In Accounts, we are having multiple Invoices and Now the requirement is that we have tomake 4 fields in Account and 2 in Entity group, all with the Date field.

*

*First invoice = we are calculating the Min of Signing Date of all the Invoices of the Account.

*First invoice as product client = Min of Signing date of all the invoices of the Account where Invoices have Contract and in the Contract having one field Contract service provided = which is not blank or its not 'currency account'
4 and 5 we will see after
Now if we go to the Entity group, we have to make another 2 fields (Date), and having one or multiple Account related lists.

*First invoice Account group = min of the first invoices from the Accounts related list

*First invoice as product client AG = min of the first invoice of the Accounts where contract cervice provided is not blank or 'currency account' from the Account related list.
Now if we go back to the Account object:
We still need to make another 2 fields:

*

*First invoice Account group = here we should take the value from the Entity group via lookup maybe

*First invoice as product client AG = here also we should take the value from the Entity group via lookup I guess.

If the Account dont have the Entity group selected than the First invoice Account group and first invoice as product client AG should take the value from the own Account, First invoice account group from the First invoice field and the First invoice as Product client AG from the First Invoice as Product client.
I have make one screenshot from Account

The below screenshot is from Entity group

The classes I have created are:
1. For the first invoice
 global class BatchCalcFirstInvoice implements Database.Batchable<sObject>,Schedulable {

    String query = ' SELECT id,(SELECT Date_Invoice__c FROm Invoices__r WHERE Date_iNVOICE__C!=null ORDER BY Date_Invoice__c ASC LIMIT 1),First_Invoice__c FROM Account';

  global BatchCalcFirstInvoice() {

  }

  global Database.QueryLocator start(Database.BatchableContext BC) {
    return Database.getQueryLocator(query);
  }

  global void execute(Database.BatchableContext BC, List<sObject> scope) {
    List<Account> toUpdate = New List <Account> ();
    for(Account A: (List<Account>) scope) {
      if(!A.Invoices__r.isEmpty()){
        A.First_Invoice__c = A.Invoices__r[0].Date_Invoice__c;
        toUpdate.add(A);
            }
            if(A.Invoices__r.isEmpty()){
                A.First_Invoice__c=null;
                toUpdate.add(A);
            }
    }
    update toUpdate;
  }

  global void finish(Database.BatchableContext BC) {

  }
    public void execute(SchedulableContext context) {
        Database.executeBatch(this);
    }

}

*for first invoice product client
global class BatchFirstInvoiceasProductClient implements Database.Batchable,Schedulable {
    string conServiceProvided = '%CURRENCY ACCOUNTS%';

    String query = 'SELECT Id,(SELECT id, Contract_Service_Provided__c, Date_Invoice__c From Invoices__r WHERE Contract_Service_Provided__c != null and (Not Contract_Service_Provided__c LIKE : conServiceProvided) ORDER BY Date_Invoice__c ASC LIMIT 1) FROM Account';

    global BatchFirstInvoiceasProductClient() {

    }

    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<sObject> scope) {
        List<Account> toUpdate = New List <Account> ();
        for(Account A: (List<Account>) scope) {
            if(!A.Invoices__r.isEmpty()){
                A.First_Invoice_as_Product_Client__c = A.Invoices__r[0].Date_Invoice__c;
                toUpdate.add(A);
            }
        }
        update toUpdate;
    }
    global void finish(Database.BatchableContext bc){

    }

    global void execute(SchedulableContext sc) {
        BatchFirstInvoiceasProductClient batchable = new BatchFirstInvoiceasProductClient();
        Database.executeBatch(batchable, 50);
    }
}

Now the rest of the code I am missing from entity group, please help me out how to find the min of first invoice of all the related accounts from the Entity group object.


text:
Q: Discord.js Join and Leave Events not working i am trying to make a bot with some new tricks i figured out but the events arent working.
When someone Joins or Leaves, it doesn't event log it in the console.
index.js:
const config = require('./config.js');

const {Client} = require('discord.js');
const client = new Client();

const utils = require('./utils.js');

let prefix = config.prefix;

client.on('ready', () => {
    utils.ready(client);
    utils.registerEvents(client);
});

client.on("message", message => {
    utils.onMessage(client, message, prefix);
})

client.login(config.token);

utils.js:
const fs = require("fs");
const eventHandler = require('./eventHandler.js');

module.exports.ready = async (client) => {
    console.log("--------------------");
    console.log("Name: " + client.user.username);
    console.log("ID: " + client.user.id)
    console.log("--------------------");
    client.user.setActivity("Team INSTINCT BETA", {"type": "STREAMING", "url": "https://twitch.tv/hanyaku"});
}

module.exports.onMessage = async (client, message, prefix) => {
    let raw = message.content.slice(prefix.length).split(" ");
    let cmd = raw[0];
    let rawArgs = raw.join(" ");
    let args = rawArgs.slice(cmd.length).split(" ");

    if(message.content.startsWith(prefix))
    {
        fs.exists(`./commands/${cmd}.js`,function(exists){
            let cmdFile = require(`./commands/${cmd}.js`);
            cmdFile.run(client, message, args);
        });
    }
}

module.exports.registerEvents = async (client) => {
    eventHandler.register(client,'guildMemberAdd');
    eventHandler.register(client,'guildMemberRemove');
}

eventHandler.js:
module.exports.register = async (client, eventName) => {
    eval(`${eventName}(client);`);
}

function guildMemberAdd(client)
{
    client.on('guildMemberAdd', member => {
        let eventFile = require(`./commands/guildMemberAdd.js`);
        eventFile.run(client, member);
    });
    console.log("Event guildMemberAdd Registriert");
}

function guildMemberRemove(client)
{
    client.on('guildMemberRemove', member => {
        let eventFile = require(`./commands/guildMemberRemove.js`);
        eventFile.run(client, member);
    });
    console.log("Event guildMemberRemove Registriert");
}

guildMemberAdd.js:
const { Client, Collection, MessageEmbed, MessageAttachment } = require('discord.js');
const fs = require("fs");
const Canvas = require('canvas');

const fetch = require("node-fetch");

module.exports.run = async (client, member) => {
    console.log('Member Joined');
    let channel = client.channels.cache.get('776942211798532106');

    let { user } = member;

    var name = user.tag;

    let embed = new MessageEmbed()
    .setTitle('Welcome')
    .setDescription('Have a nice time, ' + name)
    channel.send(embed);

}

I guess the error is in the eventHandler.js or in the guildMember.js
I hope to get help.
Greetings
-Hanyaku

A: I think you need to enable SERVER MEMBERS INTENT.
Go to discord dev portal and in bot section there will be SERVER MEMBERS INTENT option, enable it.


text:
Q: Dynamics CRM Workflow: Verifying that Item is assigned to a User (vs. Team) Before Sending Notification I have reviewed all the past questions as well as scoured google results, but I can't find a good answer to this.
In our MS Dynamics CRM 2016 Cloud implementation, we have added email notifications to the owner of a Lead, or Opportunity, based on certain events.  Sometimes the owner is a Team, and in those cases, we want to avoid sending to the team (it causes the workflow to get stuck in "waiting for retry based on error").
I added a qualification to all the workflows to say: If OwningUser.PrimaryEmail Contains Data ...
My theory was that if a user were associated with the Owner field, this would pass (all of our users have primary emails except service accounts), and if a team were associated, it would fail.  However, that is not happening - it is still trying to send the email and failing.
I was concerned that it could be an issue if no user were assigned and the system tried to reference a null value.
However, I can't see another way to do this and no one I've talked to seems to know either.

A: Try adding a condition like this. This should hopefully tell you if the owner is populated with a team record, if not then you are safe to send the email.


text:
Q: read_excel cannot able to read xls(MS excel 5.0/95 Workbook) while can be read with saving as .xlsx I am really learner in this R, Python area and faced some problem that read_xls cannot read .xls(MS excel 5.0/95 Workbook) but only my R studio shows a 0x0 tibble.
I tried to make a reprex but it showed me as below so did not understand 'path' does not exist while I can see the result in my trial so I copied both cases.
So this problematic file can be read only if I saved it as .xlsx. I can do with this way as a workaround but I want to use original file so that my code can be automatic and work within my code without effort outside like saving as .xlsx.
This problematic xls file can be found from the link while it is .zip file so should be extracted for trial and can be check file type as MS excel 5.0/95 Workbook only if you go to the save menu.
--reprex trial--
library(readxl)
read_excel("tdocList_3GU_2017-05-19_18h25.xls")
#> Error: path does not exist: 'tdocList_3GU_2017-05-19_18h25.xls'
read_excel("tdocList_3GU_2017-05-19_18h25_xlsx.xlsx")
#> Error: path does not exist: 'tdocList_3GU_2017-05-19_18h25_xlsx.xlsx'

--my trial--
library(readxl)
read_excel("tdocList_3GU_2017-05-19_18h25.xls")

A tibble: 0 x 0
read_excel("tdocList_3GU_2017-05-19_18h25_xlsx.xlsx")

A tibble: 2,159 x 32
tdocList_3GU_2017-05-19_18h25_xlsx.xlsx

Tdoc Title Source Contact Contact ID Type Type supplemen~ For Abstract Secretary Rema~ `Agenda item so~
1 R2-1~ Agen~ Chair~ Richar~ 14160 agen~ NA Appr~ NA NA NA
2 R2-1~ RAN2~ ETSI Juha K~ 21609 repo~ NA Appr~ NA NA NA
3 R2-1~ LS o~ CT1 Jaehyu~ 44912 LS in NA Acti~ NA NA NA
4 R2-1~ LS o~ CT1 Lena C~ 38080 LS in NA Info~ NA NA NA
5 R2-1~ Repl~ CT1 Mikael~ 40034 LS in NA Info~ NA NA NA
6 R2-1~ Repl~ CT1 Chen-h~ 57105 LS in NA Info~ NA NA NA
7 R2-1~ Repl~ CT1 Jennif~ 43418 LS in NA Acti~ NA NA NA
8 R2-1~ LS o~ CT1 Chen-h~ 57105 LS in NA Acti~ Offline~ NA NA
9 R2-1~ Resp~ RAN1 Albert~ 63913 LS in NA Acti~ NA NA NA
10 R2-1~ LS o~ RAN1 Alexey~ 46112 LS in NA Acti~ NA NA NA
... with 2,149 more rows, and 21 more variables: Agenda item , Agenda item description , TDoc sort order within agenda item<dbl>,TDoc Status<chr>,Reservation date<dttm>, Uploaded <dttm>,Is revision of<chr>,Revised to<chr>, Rel <chr>, Specification <chr>, Version <chr>,Related WIs<chr>, CR <chr>,CR revision<chr>,CR category<chr>,TSG CR Pack<lgl>,Reply to<chr>, LS_To <chr>, LS_Cc <chr>,Original LS<chr>,Reply in
file download link as I cannot find where I can upload my test file

A: There is probably no solution to this in R, other than converting to a more recent excel format. Neither readxl or xlsx handle excel formats as old as this.


text:
Q: Object creation and destruction order in C++ I wrote a simple program to learn more about the order of creating and destructing objects in C++ (using Visual Studio 2015). Here it is:
#include <iostream>
#include <string>

using namespace std;

class A
{
public:
    A(string name)
        : name(name)
    {
        cout << "A(" << name << ")::constructor()" << endl;
    }
    ~A()
    {
        cout << "A(" << name << ")::destructor()" << endl;
    }
private:
    string name;
};

class C
{
public:
    C(string name, A a)
        : name(name), a(a)
    {
        cout << "C(" << name << ")::constructor()" << endl;
    }
    ~C()
    {
        cout << "C(" << name << ")::destructor()" << endl;
    }
private:
    string name;
    A a;
};

class B
{
public:
    B(string name)
        : name(name)
    {
        cout << "B(" << name << ")::constructor()" << endl;
    }
    ~B()
    {
        cout << "B(" << name << ")::destructor()" << endl;
    }
private:
    string name;
    A a1{"a1"};
    A a2{"a2"};
    C c1{"c1", a1};
    A a3{"a3"};
};

int main()
{
    B b("b1");
    return 0;
}

The output surprised me a little bit (the a1s):
A(a1)::constructor()
A(a2)::constructor()
C(c1)::constructor()
A(a1)::destructor()
A(a3)::constructor()
B(b1)::constructor()
B(b1)::destructor()
A(a3)::destructor()
C(c1)::destructor()
A(a1)::destructor()
A(a2)::destructor()
A(a1)::destructor()

To learn more about what was going on I added information about the instances of objects:
    A(string name)
        : name(name)
    {
        cout << "A(" << name << ")::constructor(), this = " << this << endl;
    }
    ~A()
    {
        cout << "A(" << name << ")::destructor(), this = " << this << endl;
    }

The result was even more surprising:
A(a1)::constructor(), this = 0039FB28
A(a2)::constructor(), this = 0039FB44
C(c1)::constructor()
A(a1)::destructor(), this = 0039F8A8
A(a3)::constructor(), this = 0039FB98
B(b1)::constructor()
B(b1)::destructor()
A(a3)::destructor(), this = 0039FB98
C(c1)::destructor()
A(a1)::destructor(), this = 0039FB7C
A(a2)::destructor(), this = 0039FB44
A(a1)::destructor(), this = 0039FB28

Namely, why is a1's constructor only called once and destructor 3 times? I'm passing a by value so obviously at least 1 temporary object is created but please explain to me when and how many A instances are created and destroyed?

A: As already noted in the comments, objects of type A are also constructed via copy-construction when you pass them as arguments by value. In order to see this you can add a copy-constructor on your own:
A(const A& other)
: name(other.name)
{
    cout << "A(" << name << ")::copy-constructor(), this = " << this << endl;
}

Sample output:
A(a1)::constructor(), this = 0xbff3512c
A(a2)::constructor(), this = 0xbff35130
A(a1)::copy-constructor(), this = 0xbff350e8
A(a1)::copy-constructor(), this = 0xbff35138
C(c1)::constructor()
A(a1)::destructor(), this = 0xbff350e8
A(a3)::constructor(), this = 0xbff3513c
B(b1)::constructor()
B(b1)::destructor()
A(a3)::destructor(), this = 0xbff3513c
C(c1)::destructor()
A(a1)::destructor(), this = 0xbff35138
A(a2)::destructor(), this = 0xbff35130
A(a1)::destructor(), this = 0xbff3512c

Try it online
As you can see, one copy-construction happens when you pass a1 as parameter to the constructor of c1 and a second one happens when this constructor initializes its member a. The temporary copy is destructed immediately afterwards while the member is destructed when c is destructed.
Edit:
Here you can read the exact rules when a copy-constructor is created.
In order to not create a default copy-constructor it is not sufficient to provide any user-defined constructor, it needs to be a copy/move-constructor.
Edit2:
Taken from C++14 standard (12.8 Copying and moving class objects):

7 If the class definition does not explicitly declare a copy constructor, one is declared implicitly. If the class definition declares a move constructor or move assignment operator, the implicitly declared copy constructor is defined as deleted; otherwise, it is defined as defaulted (8.4). The latter case is deprecated if the class has a user-declared copy assignment operator or a user-declared destructor.


text:
Q: Merge query: set map and 'created' property upon creation I'm trying to create a user if it doesn't already exist, then know whether creation occurred or not.
This syntax always perform the second set:
MERGE (n:User {email: {email}})
ON CREATE n
  SET n = {user}
  SET n.created = timestamp()
WITH n WHERE n.created = timestamp()
RETURN n

I'm guessing the second set isn't actually part of the ON CREATE clause, like so:
MERGE (n:User {email: {email}})
ON CREATE n
  SET n = {user}
SET n.created = timestamp()
WITH n WHERE n.created = timestamp()
RETURN n

However, the alternate syntax of multiple sets results in "Error: expected valid query body":
MERGE (n:User {email: {email}})
ON CREATE n
  SET n = {user}, n.created = timestamp()
WITH n WHERE n.created = timestamp()
RETURN n

As a workaround I've decided to pass the created time-stamp in with the user map, but is there a way to accomplish this?  Is it working as intended or is there a bug here, maybe?

A: That last one should work IMO--can you make a github issue? We'll see what the neo guys say, but I think it should be ok to have comma separated sets.
As an alternative, you can do multiple ON CREATEs:
MERGE (n:User {email: {email}})
ON CREATE n
  SET n = {user}
ON CREATE n
  SET n.created = timestamp()
WITH n WHERE n.created = timestamp()
RETURN n