text:
Q: XCode SubProject configuration due to working needs, I need to integrate an xcodeproj into my existing project as subproject.
The structure of my two projects is the following
Structure of the two projects
What is the best practice to integrate (no cocoapods) the subProject into my main project?
I have done the following steps as you can see from the picture below:
Integration Steps

*

*I have copied the folder and all the files to my MainProject
folder.

*In XCode I have added files to MainProject and then I have choose
the "SubProject.xcodeproj" and I can see the structure in the
project navigator.

*I have added into the "Search Header Path" the following sentence:
"${SRCROOT}/../SubProject" with recursive search.

I am not be able to import into my main project the header of the sub project. How can I solve my situation? What I am missing?

A: Is not clear what you mean with "Integrate a sub project". What to you want achieve? A single target or every project should build a different binary?
First of all I would suggest you to put both project in the same folder, in your example they are both inside the Desktop folder so this is ok.
As second step you should create a workspace, and add both project to this workspace. There is no need of moving folders around, just drag the project icon inside xCode, just below the workspace icon.


text:
Q: In sending a soap message "manually" I get AddressingNone error with WCF I'm trying to send through a SOAP message (that I've extracted) to my WCF service without using the WCF client infrastructure.
Without using my production messages (and code), I've been able to setup a dummy version of the same problem (thanks to the WF_WCF_Samples).
So the contract looks like this:
[ServiceContract(Namespace="http://Microsoft.Samples.UsingUsing")]
public interface ICalculator
{
    [OperationContract]
    double Add(double n1, double n2);
    [OperationContract]
    double Subtract(double n1, double n2);
    [OperationContract]
    double Multiply(double n1, double n2);
    [OperationContract]
    double Divide(double n1, double n2);
}

Looking at the SOAP message that the actual WCF client sends I get this in the WCF Tracing:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Header>
        <To s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://localhost:56852/service.svc</To>
        <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://Microsoft.Samples.UsingUsing/ICalculator/Divide</Action>
    </s:Header>
    <s:Body>
        <Divide xmlns="http://Microsoft.Samples.UsingUsing">
            <n1>0</n1>
            <n2>0</n2>
        </Divide>
    </s:Body>
</s:Envelope>

And that is from the working call.
However, if I try to do it I get the following exception that gets logged in the WCF tracing:

Addressing Version 'AddressingNone (http://schemas.microsoft.com/ws/2005/05/addressing/none)' does not support adding WS-Addressing headers.

I've tried something like SoapUI and even Httpie to send an XML file:

So I get back an HTTP error 400 - Bad request.
I am currently using the basicHttp(s)Binding WCF binding.
I've tried messing with the bindings but nothing is working. Any thoughts?

A: I was stunned that WCF actually added the following header in the SOAP message when I looked at the WCF tracing (on the service side, not the client side):
<To s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://localhost:56852/service.svc</To>
<Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://Microsoft.Samples.UsingUsing/ICalculator/Divide</Action>

When I took it out, my request went through without a problem.

In setting up something like Wireshark I managed to see that the actual message didn't contain this header. Somewhere WCF was adding that in the SOAP header during tracing. But sending that through was invalid. The HTTP Soap Action header is sufficient.

redpajama_set_name: RedPajamaStackExchange


text:
Q: running time of longest non-decreasing segment in an array I have a method in java that finds the longest non-decreasing segment in an array.
The method works, however, as part of the assignment, I need to find the running time of size n elements using the method in terms of O(f(n))(i.e upper bound) and Ω(g(n))(i.e lower bound). Can someone help me?
thanks in advance!!
    public int maxAscent(int A[])
    {
int num = 0;
int count = 1;
int i;
for(i = 0; i < A.length-1; i++)
    if(A[i] <= A[i+1])
        count++;
    else
    {
        if(count > num)
            num = count;
        count = 1;
    }
if(count > num)
    num = count;
return num;

}

A: The upper and lower bound, as well as the Big O have to do with the loops.  The questions to ask are which loops do you have in your code? How many times does each loop run in the worst case and best case scenarios? If a loop contains another loop, you multiply their best cases and their worst cases.
For your particular program, there is one loop, and it goes from 0 to n-1.  There is no early out so your best case, worst case, and average case all have the same value.
That would be "n" operations, so O(n), Ω(n) and ø(n).


text:
Q: How to presents javascript code with variable in executeScript method? I am implementing selenium script, by executing javascript code with method executeScript. In which getting issue with single(') and Double quotes(") while passing variable.
Not Working:
js.executeScript("return document.querySelector('input[value=\" '"+group_name+"' \"]').value;").toString();

Working with static value:
js.executeScript("return document.querySelector('input[value=\" DemoTest \"]').value;").toString();

Here ('input[value=\" '"+group_name+"' \"]')  group_name variable is covered by Java variable quotes,
So By technically its 3 Quotes which need to pass
 1. Before return statement " "
 2. On querySelector ''
 3. Passing variable value to querySelector " "
Please Note: DOM only accepts if it has been passed through different Quotes with inner strings 2 and 3.
Here I am getting SyntaxError from DOM: Its says SyntaxError : missing ) after argument list
So How can I pass variable in such a way where DOM accepts it with required syntax.

A: Try to use below code:
js.executeScript("return document.querySelector('input[value=\"' + arguments[0] + '\"]').value;", group_name).toString();


text:
Q: How could I change this dependency for Android custom shadow view? I was using the following dependency, but I am not going to use it anymore as I have noticed that it is deprecated: dependency I was using
As you can see, the About of this depencency, says the following:

Deprecated because of the performance not fine. Android custom shadow
view, can replace your CardView

I am trying to replace what I was using from that dependency for the Android custom shadow view as the dependency About says, but I don´t know how could I do it.
This is what I was using:
<com.loopeer.shadow.ShadowView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginStart="14dp"
                android:layout_marginEnd="14dp"
                android:layout_weight="1"
                android:elevation="@dimen/shel"
                app:cornerRadiusTL="@dimen/hol"
                app:cornerRadiusTR="@dimen/car"
                app:shadowMarginLeft="@dimen/shadow"
                app:shadowMarginRight="@dimen/margn"
                app:shadowRadius="@dimen/radius">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:visibility="visible">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/sign_stp"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="3dp"
                        android:padding="6dp"
                        android:text="@string/sign"
                        android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
                        android:textColor="@color/red" />

                </LinearLayout>
            </LinearLayout>
            </com.loopeer.shadow.ShadowView>

Also I had made the following function to show card view:
public void showCardView() {

        Animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                LinearLayout.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        LinearLayout.startAnimation(Animation);

    }

In the main.activity.java the above function is run:
showCardView();


text:
Q: View is rendered before user type is loaded from firestore So I'm building an Ionic - Angular app that have an hospital patient submit a request to the nurse stuff and the nurse stuff can see their assigned requests (based on the room that assigned to the patient submitting the request). A nurse can see all requests and a patient can see only his/her requests. I have a function in the auth.service.ts that is called (setUserType() ) once a user is logged in manually or if it is an auto login(token is stored and found) and fetch the user type and name once it finished authentication.
The problem is, in the my-requests.page.ts in NgOnInit I call a function in the requests service that run a query to fetch all requests(if it is a nurse) or to fetch only the user's requests(if it is a patient) based on the user type I assigned once login/auto login occured. This field is unassigned once the my-requests.page.html is rendered and I can't seem to find a way to make it render only after I have the user type information.
setUserType() function:
    let userId: string;
    this.userIdObservable.subscribe(x => {
      userId = x;
    });
    const userQuery = this.firestore.doc<Users>(`added-users/${userId}`);
    userQuery.valueChanges().subscribe(x => {
      this._userType = x.type;
      this._userName = x.name;
    });

My requests ngOnInit function:
      ngOnInit() {
    this.segment.value = 'progress';
    this.requestSubscription = this.requestsService
      .loadRequests()
      .subscribe(requests => {
        this.requestsList = requests;
      });
  }

Now all the auth functions -
Auth page Authenticate function:
    authenticate(email: string, password: string) {
    this.isLoading = true;
    this.loadingCtrl
      .create({
        keyboardClose: true,
        message: 'Logging in...'
      })
      .then(loadingEl => {
        loadingEl.present();
        let authObs: Observable<AuthResponseData>;
        if (this.isLogin) {
          authObs = this.authService.login(email, password);
        } else {
          authObs = this.authService.signup(email, password);
        }
        authObs.subscribe(resData => {
          console.log(resData);
          this.isLoading = false;
          loadingEl.dismiss();
          this.authService.setUserType();
          this.router.navigateByUrl('/requests/tabs/add-requests');
        }, errRes => {
          loadingEl.dismiss();
          const code = errRes.error.error.message;
          let message = 'Could not sign you up, please try again.';
          if (code === 'EMAIL_EXISTS') {
            message = 'This Id exists already!';
          } else if (code === 'EMAIL_NOT_FOUND') {
            message = 'No such user.';
          } else if (code === 'INVALID_PASSWORD') {
            message = 'Could not log you in, please try again.';
          }
          this.showAlert(message);
        });
      });
  }

Auth service login function:

      login(email: string, password: string) {
    return this.http
      .post<AuthResponseData>(
        `https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=${
          environment.firebaseAPIKey
        }`,
        { email: email, password: password, returnSecureToken: true }
      )
      .pipe(tap(this.setUserData.bind(this)));
  }

Auth service autologin function:
    autoLogin() {
    return from(Plugins.Storage.get({ key: 'authData' })).pipe(
      map(storedData => {
        if (!storedData || !storedData.value) {
          return null;
        }
        const parsedData = JSON.parse(storedData.value) as {
          token: string;
          tokenExpirationDate: string;
          userId: string;
          email: string;
        };
        const expirationTime = new Date(parsedData.tokenExpirationDate);
        if (expirationTime <= new Date()) {
          return null;
        }
        const user = new User(
          parsedData.userId,
          parsedData.email,
          parsedData.token,
          expirationTime
        );
        return user;
      }),
      tap(user => {
        if (user) {
          this._user.next(user);
          this.setUserType();
        }
      }),
      map(user => {
        return !!user;
      })
    );
  }

A: This is how you can do you dont have to include it in any module cli will do that for you.

import {Component, Injectable, OnInit} from '@angular/core';
import {BehaviorSubject} from 'rxjs';
import {FormGroup} from '@angular/forms';

@Injectable({
  providedIn: 'root'
})
export class UserStateService {
  private user = new BehaviorSubject({
    isLoggedIn: false,
    userType: null
  });

  constructor() {
  }

  setUser(user) {
    this.user.next(user);
  }

  getUser() {
    return this.user;
  }
}

// my request

@Component({
  selector: 'request-component',
  templateUrl: './request-component.html'
})
export class RequestComponent implements OnInit {
  constructor(private userStateService: UserStateService) {}

  ngOnInit(): void {
    this.userStateService
      .getUser()
      .subscribe(
      ((val: {isLoggedIn: boolean, userType: any}) => {
        // calll you service
      }));
  }
}

// in your auto login or login you call setter

this.userStateService.setUser({isLoggedIn: true, userType: 'data from login'});


text:
Q: Specifying android permissions through gradle I have:
product flavors {
    a { }
    b { }
}

buildTypes {
    1 { }
    2 { }
    releaseTest { }
}

Now I have a specific Manifest file I want to add to Flavor b & buildType Test, without putting it in the product Flavor b folder (I want it to be only going into androidTest, and I don't want to put it into the Flavor b folder as I may want it in flavor A as well but not in flavor B, while cutting builds, etc). Specifically all that's going to be in the manifest folder is a couple of permissions.
Is there a way to do this?


text:
Q: Mongoose: what's the differences between Model.create and Collection.insert I want do a batch insert job in MongoDB and I found two ways in mongoose:
One way is use insert:
dataArr = [
   {
       id: "",
       name: ""
   }
   {
       id: "",
       name: ""
   }
]

Collection.insert(dataArr)

and another way is Model.create:
Model.create(dataArr)

both could complete the batch insert job, but what's the difference between them?
Which one is more  efficiency?

A: In Mongoose, there is Model.create and Collection.insert (the latter isn't strictly part of Mongoose, but of the underlying MongoDB driver).
According to the Mongoose developer, they are basically the same when called with an array of documents, although looking at the code makes me think that there are subtle differences (warning: I haven't looked at the code that well so I might be mistaken about the following):

*

*using Model.create will call any validators/hooks declared on your schema;

*Model.create does a .save for each document in the array, resulting in N database calls (where N is the number of documents in the array); Collection.insert performs one large database call;

A: according to what i've read, Collection.insert is a function of mongoDB driver it's much faster when inserting big amounts of data like millions or such at the cost that it bypasses mongoose validations.
handle with care

A: They loosely mean the same thing. You can use either of them.

A: checking the documentation for insertMany, apparently it's faster that create as  it only sends one operation to the server, rather than one for each document.
insertMany documentation, one thing to note is that insertMany does not trigger save middleware, while on the other hand, create does.


text: Q: How often does the FBI choose to investigate me? Sometimes, almost randomly, almost seemingly when I get to high amounts of income does the FBI choose to investigate me, and I really don't like losing assets and cash value when the spinner lands on the wrong tile.  Is it possible to predict in advance or know when the FBI is coming so I can liquidate what current funds I have in either the political investment tree, the financial investment tree, or the last tree?


text:
Q: primefaces commandlink wont show modal dialog hello I have a commandLink that executes a method in my baking bean, that method calls an ejb that builds a string and place it as an attribute of the bean (with getters and setters), after executing that method should raise a modal dialog to only display the value of that attribute but it does not, I see the method that builds the chain runs but does not lift the dialogue, this is my code:
xhtml:
<ui:composition>

<h:form id="headerForm">

<h:outputText styleClass="titleHeader" value="#{loginBean.entityName}" />

<h:commandLink onComplete="PF('dlg').show(); return false;" type="button" ajax="false" action="#                {xxxxBean.createString}">
<h:outputText value="Contact" />
</h:commandLink>

</h:form>

<h:outputText value="#{xxxxBean.stringBuild}" />

</ui:composition>

Backing bean:
@ManagedBean
@SuppressWarnings("serial")
public class XxxxBean implements Serializable{

private String stringBuild;
private someBeanRemote ejb;

public XxxxBean() {
// TODO Auto-generated constructor stub
try{
ejb = EjbConsumer.getRemoteEjb();
}catch(Exception e){
e.printStackTrace();
}

}

public void createString(){
List<someObject> list = ejb.findAllActiveObjects(Constants.TOP);
String temp = "";
if( list!=null && list.size() > 0 ){
for(int i=0; i < list.size(); i++){
temp += list.get(i).getName() + "
";
}

this.stringBuild= temp;
}

System.out.println(this.stringBuild);

}

public void setStringBuild(String stringBuild) {
this.stringBuild= stringBuild;
}

public String getStringBuild() {
return stringBuild;
}

}

thanks in advance!!!

A: You are using ajax=false with oncomplete
oncomplete: Client side callback to execute when ajax request is completed.
Change to:

that is default ajax = true and everything should work


text:
Q: Categorize objects in different lists depending on a property I'm having a problem in categorizing objects in different lists using the interest property.
I have a list of users objects as List, my user class looks like the following:
class User {
    private int id;
    private String name;
    private String interest;
    //constructors, getters & setters etc...
}

I'm trying to display users depending on a certain interest, but I feel like there's an easier way to do this other than what I've tried.
And I need the interest list to be dynamic other than using a fixed set of elements in a switch, And also I don't know if there is a better and more efficient way without having to use 3 lists a list for each interest.
Here's what I've done so far:
List<User> javaInterestList;
List<User> javascriptInterestList;
List<User> cInterestList;

public void category(List<User> unfilteredList) {
    for (User u : unfilteredList) {
        String interest = u.getInterest().toLowerCase();
        switch (interest) {
        case "java":
            javaInterestList.add(u);
            break;
        case "c":
            cInterestList.add(u);
            break;
        case "javascript":
            javascriptInterestList.add(u);
            break;
        }
    }
}

The problem in the above that I'm restricted to only 3 interests, Is there any way to solve this problem and a better, cleaner way to do it?

A: The thing to think about here is not the mechanism of filtering, rather the used data-structure.
In such a situation, you are allocating different type of users with a certain interest (key). Which is a perfect use case for maps.
I think you just need to use a map for the following situation.

The problem in the above that I'm restricted to only 3 interests, Is there any way to solve this problem

Of course you can categorize as many interests as you desire, take a look at the following method:
public static Map<String,List<User>> category(List<User> unfilteredList){
        Map<String,List<User>> result = new HashMap<>();
        for(User u :unfilteredList){
            String inerest = u.getInterest();
            if(result.containsKey(u.getInterest())){
                List<User> users = new ArrayList<>(result.get(inerest));
                users.add(u);
                result.put(inerest, users);
            }else{
                List<User> users = new ArrayList<>();
                users.add(u);
                result.put(inerest, users);
            }
        }
        return result;
    }

Is there a better, cleaner way to do it?

Yes, using Java 8 Streams you can easily rewrite the above in only one line of code:
public static  Map<String,List<User>> category(List<User> unfilteredList){
        return unfilteredList.stream().collect(Collectors.groupingBy(u -> u.getInterest()));
    }

A: this is a perfect opportunity to use a groupingBy collector.
Map<String, List<User>> resultSet =
           unfilteredList.stream().collect(
                  Collectors.groupingBy(u -> u.getInterest().toLowerCase());

now you can retrieve the list of users for a given key by doing:
List<User> java = resultSet.get("java");
List<User> c = resultSet.get("c");
List<User> javascript = resultSet.get("javascript");


text:
Q: Some example using SubProtocolWebSocketHandler and stompSubProtocolHandler? I can't find examples of use of stompSubProtocolHandler and SubProtocolWebSocketHandler?
I need extend this SubProtocolWebSocketHandler class?
private static class ProducerStompSessionHandler2 extends SubProtocolWebSocketHandler {

        public ProducerStompSessionHandler2(MessageChannel clientInboundChannel,
                SubscribableChannel clientOutboundChannel) {
            super(clientInboundChannel, clientOutboundChannel);
            // TODO Auto-generated constructor stub
        }

    }

I'm using a handler for a Sockjs java client that extend of StompSessionHandlerAdapter and is working. I can connect, subscribe and send messages:
private static class ProducerStompSessionHandler extends StompSessionHandlerAdapter {
     ...
}
But I see another user telling that there are two implementacions: SubProtocolWebSocketHandler and stompSubProtocolHandler.
https://stackoverflow.com/a/28306539/6243317
These are implementation of Java Websocket over STOMP clients? how use? advantages? why use this implementation?

A: To answer your main question in the title, I think this sample by Spring would be useful to you. The stompSubProtocolHandler is more server side in the sample, but I assume the logic will be the same for client.


text:
Q: Determining time complexity of recursive function I have written a recursive function which computes Catalan Numbers.
The recursion formula is .
My code:
def catalan(n): # We call this function. To my opinion it is more elegant.
    d = dict()
    return catalan_rec(n,d)

def catalan_rec(n,d):
    if n == 0:
        result = 1
    elif n in d: return d[n]
    else:
        result = 0
        for i in range(n):
            result += catalan_rec(i,d)*catalan_rec(n-i-1,d)
        d[n] = result
    return result

Now, it is obvious that the recursion depth is O(n). I am not sure what is the time complexity of this algorithem. The recursion tree has O(n) nodes and in any node (except leaves) we make two calls. Any call is O(1) as we only check if we already have the result in the dictionary, hence the time complexity is O(n).
Is my reasoning correct?
And by the way, is there an option to write non recursive algorithm that runs in time complexity which is better than O(n^2)?
Thanks!

A: Not sure if this is what you want, but according to that page you could write the function to compute the catalan number in O(n) like this:
def catalan(n):
    num, div = 1, 1
    for x in range(n + 2, 2*n + 1):
        num *= x
    for x in range(2, n + 1):
        div *= x
    return num / div


text:
Q: Deleting incremental snapshots before occasional full backup Google Cloud Compute Engine Regarding snapshots on Google Cloud Compute Engine, I have some questions I could not find answers to in the documentations:

*

*We do have a two-hourly frequency for some of our disks. The documentation says that at not defined times, a full image of the disk is captured. In case I do not need to restore anything from before the latest full image, does this mean that all previous snapshots to the new full image could be deleted?

*If so, how do I identify the snapshots that can be deleted?

*Or: Is there even a way to accomplish this task automatically (e.g. something like "delete all prior incremental images after latest full image"?)

A: Let me provide you some links to the documentation that could answer your questions:

*

*Accordingly to the documentation Working with persistent disk snapshots:

Compute Engine uses incremental snapshots so that each snapshot contains only the data that has changed since the previous snapshot.

on the other hand, as it was admitted by @Peter Sonntag,  accordingly to the documentation Use existing snapshots as a baseline for subsequent snapshots:

Important: Snapshots are incremental by default to avoid billing you for redundant data, to minimize use of storage space, and to decrease snapshot creation latency. However, to ensure the reliability of snapshot history, a snapshot might occasionally capture a full image of the disk.

*Accordingly to the documentation Snapshot deletion:

When you delete a snapshot, Compute Engine immediately marks the
snapshot as DELETED in the system. If the snapshot has no dependent
snapshots, it is deleted outright. However, if the snapshot does have
dependent snapshots:

*

*Any data that is required for restoring other snapshots is moved into the next snapshot, increasing its size.

*Any data that is not required for restoring other snapshots is deleted. This lowers the total size of all your snapshots.

*The next snapshot no longer references the snapshot marked for deletion, and instead references the snapshot before it.

*To automate deletion of the snapshots of you can use Snapshot retention policy:

A snapshot retention policy defines how long you want to keep your snapshots.
If you choose to set up a snapshot retention policy, you must do so as part of your snapshot schedule.


text:
Q: How to repeat a test with pytest after every other test? I have few test cases as described below. But i want to repeat test1() after every other test case. how can i achieve this?
@pytest.mark.test1()
@pytest.mark.parametrize(a,b,c)
def test_test1():
   ......
   ......

@pytest.mark.test2()
def test_test2():
   ......
   ......

@pytest.mark.test3()
def test_test3():
   ......
   ......

run test1() again

A: You can modify the list of tests to be executed by implementing the pytest_collection_modifyitems hook. Example: In your root dir, create a file named conftest.py and add the hook to it:
def pytest_collection_modifyitems(session, config, items):
    test1s = [item for item in items if item.function.__name__ == 'test_test1']
    items.extend(test1s)

Now the test_test1 will be appended to the list of already collected tests, being executed twice:
$ pytest -v
============================= test session starts =============================
platform darwin -- Python 3.6.3, pytest-3.4.0, py-1.5.2, pluggy-0.6.0 -- /Users/hoefling/.virtualenvs/stackoverflow/bin/python
cachedir: .pytest_cache
rootdir: /Users/hoefling/projects/private/stackoverflow/so-49213392, inifile:
plugins: celery-4.1.0, forked-0.2, cov-2.5.1, asyncio-0.8.0, xdist-1.22.0, mock-1.6.3, hypothesis-3.44.4
collected 5 items

test_spam.py::test_test1[a] PASSED                                      [ 12%]
test_spam.py::test_test1[b] PASSED                                      [ 25%]
test_spam.py::test_test1[c] PASSED                                      [ 37%]
test_spam.py::test_test2 PASSED                                         [ 50%]
test_spam.py::test_test3 PASSED                                         [ 62%]
test_spam.py::test_test1[a] PASSED                                      [ 62%]
test_spam.py::test_test1[b] PASSED                                      [ 62%]
test_spam.py::test_test1[c] PASSED                                      [ 62%]

========================== 8 passed in 0.02 seconds ===========================

A more elegant solution would be using a custom marker, let's name it my_repeat:
@pytest.mark.my_repeat
@pytest.mark.parametrize(a,b,c)
def test_test1():
    ...

Adapted hook in conftest.py:
def pytest_collection_modifyitems(session, config, items):
    repeats = [item for item in items if item.get_marker('my_repeat')]
    items.extend(repeats)


text:
Q: Machine Learning - Features selection and Modeling (Connection between samples) I am new to Machine Learning, and I have got several questions with my data now.
Let's say I have X samples, Y features and I also have the connection between x1 and x2 (e.g. the interaction count)
As most of the tutorial of Machine Learning start with labels specifically labelled at the sample itself...
I would like to ask how I should build the model? I want to have a model that it can predict two specific samples to see how high the interaction counts would be.
Giving me a direction/ keywords to learn would be good enough, thanks!

A: I have got others suggestion for the approach:
Formulate the problem as z=f(x1,x2), i.e. label depends on tuple of sample. if a dataset of ((x1,x2)=>z) is prepared, it can then be used to train regression, decision trees or networks.


text:
Q: How to add htaccess rewrite rule in Joomla I use Joomla 1.5.22 and mod_rewrite with nice links. But I would like to add also a redirection like this:
RewriteRule ^mail /squirrelmail
So if Someone enters www.mypage.com/mail he will be redirected to www.mypage.com/squirrelmail
How to update Joomla's .htaccess file in order for this to work? For now, if I use this Rule, it shows a Joomla 404 Error

A: In your .htaccess find, and AFTER the following statement:
RewriteEngine On

ADD the following line
RewriteRule ^mail$ /squirrelmail [R=301,L]


text:
Q: Adding elements in a Bash array to print them later I am adding elements on an array (Add a new element to an array without specifying the index in Bash) but I am getting an unexpected result. I suppose I am doing something wrong when adding elements in the array and/or when iterating the array to print its values.
Code:
for name in $(cat list.txt); do
    host $name.$DOMAIN | grep "has address" | cut -d" " -f4
done

for name in $(cat list.txt); do
    echo "."
    IPS+=(`host $name.$DOMAIN | grep "has address" | cut -d" " -f4`)
    echo ${#IPS[@]}
done

for ip in $IPS; do
    echo "IP: $ip"
done

Output:
12.210.145.45
67.20.71.219
75.58.197.10
31.70.88.22
.
1
.
3
.
4
.
4
.
4
IP: 12.210.145.45

Expected output:
Output:
12.210.145.45
67.20.71.219
75.58.197.10
31.70.88.22
.
1
.
2
.
3
.
4
IP: 12.210.145.45
IP: 67.20.71.219
IP: 75.58.197.10
IP: 31.70.88.22

A: To iterate over an array, use
for ip in "${IPS[@]}" ; do

See PARAMETERS in man bash.


text:
Q: Different styling on background in html  I would like to style some <option> elements inside a <select> element in some unique ways, dynamically. This goes beyond the simple working examples of the "background-color" CSS; I'm trying to find ways where I don't have to keep resources but could generate styles dynamically such as adding some gradient or image from data-uri to the background.
Well, so far, no gradients are working and neither does data-uri  with background or background-image.
Besides perhaps backgrounds, what other ways can option elements be styled to make it looks like there's extra stuff in there but that doesn't rely on a static resource?

A: In general you cannot style a select element or an option element. The select element itself is a "replaced element" which is OS-dependent and not part of the HTML/browser. It cannot be styled via CSS.
However you can use replacement plug-ins/libraries that look like a select element but are actually composed of regular HTML elements in which the style can be changed.


text:
Q: After shutting down laptop from ubuntu 16.04 it getting hot I am new to ubuntu 16.04. It is dual booted with windows 10.
After installing ubuntu 16.04 i fetch a problem that if i shut down my laptop from ubuntu it getting hot though it is shut down.Now i am helpless and need help to solve this problem. How to fix this problem?
My laptop model is HP pavilion 15-AB203Tx

A: first test that the suspend functionality works without closing the lid
systemctl suspend

you should see the system suspend , it should wake up when you press a key or move the mouse.
then try hibernating without closing the lid
systemctl hibernate

If both of those work and your laptop isn't getting hot then it would seem like the lid sensor is either faulty or not being setup properly.
If either of these don't work then it would seem your problem is that its not actually suspending or hibernating when you close the lid, maybe you have some services running that won't suspend, an external monitor or an experimental hardware driver.
Work your way through this guide if its not suspending or hibernating
https://wiki.ubuntu.com/DebuggingKernelSuspend


text:
Q: Can't type anything when using getchar() in this program I am studying "The C Programming Language, 2nd Ed." by Brian Kernighan and Dennis Ritchie. I was on Exercise 1-19 of the book. The question asks to define a function reverse(s) which reverses a character string a. And we have to write a program which reverses it's input one at a time.
//This program is working on online compiler but not here
#include <stdio.h>

void reverse(char s[]);

int main(void) {
    int h = 0; // sort of automatic variable just to
               // keep storing characters in current line
    char s[200];
    char c;

    for (int i = 0; i < 1000; i++)
        s[i] = '\0';
    while ((c = getchar()) != EOF) {
        if (c != '\n') {
            s[h++] = c;
        } else {
            s[h++] = c;
            h = 0;
            reverse(s);
            for (int i = 0; i < 1000; i++)
                s[i] = '\0';
        }
    }
}

void reverse(char s[]) {
    int i = 200;
    while(i >= 0)
        if(s[i--] != '\0')
            putchar(s[i]);
    printf("\n");
}

So when I run this code with gcc on my system, I don't get any errors while compiling, but I can't type any input for some reason. However, the program runs correctly when I use an online C compiler.

A: void reverse(char s[]) {
    int i = 200;
    while(i >= 0)
        if(s[i--] != '\0')
            putchar(s[i]);
    printf("\n");
}

if you postdecrement your string index, you are first using value at 200 position, which is invalid (it's one position out of the array) so you are doing bad.  To do it properly, you need to predecrement it, as in:
void reverse(char s[]) {
    int i = 200;
    while(i >= 0)
        if(s[--i] != '\0')
            putchar(s[i]);
    printf("\n");
}

but there's still an error... as you pass a null terminated string, you cannot be sure of what there is in the array after the null.... (can be another null?) so you have to search for the null from the beginning of the string (and this is good, because the most of the time you will feed the routine short strings, and now you don't depend on the array size, which you assumed by a constant 200.  One good way to do it is with the strlen() function, as in:
void reverse(char s[]) {
    int i = strlen(s);
    while(i >= 0) /* ??? see below */
        if(s[--i] != '\0')
            putchar(s[i]);
    printf("\n");
}

and then, the test you do is not necessary at all (you already found the leftmost null):
void reverse(char s[]) {
    int i = strlen(s);
    while(i >= 0) /* still more below VVV */
            putchar(s[--i]);
    printf("\n");
}

... and there's still a little mistake... you have to stop when i <= 0 and not when i < 0 as you are predecrementing now:
void reverse(char s[]) {
    int i = strlen(s);
    while(i > 0) /* here!! */
            putchar(s[--i]);
    printf("\n");
}


text:
Q: Blazor: OnSubmit: How to access form input values and show ValidationMessage? I know that when using OnSubmit for handling form submission (instead of OnValidSubmit and OnInvalidSubmit) we are responsible for ensuring that the form is valid (via calling EditContext.Validate() method);
Consider the following sample code:
<EditForm Model=@Person OnSubmit=@FormSubmitted>
  <DataAnnotationsValidator/>
  <ValidationSummary/>

    Name
    <InputText @bind-Value=Person.Name class="form-control" id="Name" />
    <ValidationMessage For="() => Person.Name"/>

  <input type="submit" class="btn btn-primary" value="Save"/>
</EditForm>

Now suppose we are in the FormSubmitted function:
My questions are:

*

*How can we access the value of the inputs of the from? (in the code above, accessing the value of the InputText with the id: "Name") (is data-binding the only way?)

*Since we are responsible for validating the form, the only way to show the ValidationMessage is to call EditContext.Validate() method (if form is indeed invalid) or we can decide and have control over which ValidationMessage to show up?

A: The issue you are facing is due to the fact that by the time EditContext.Validate returns, Validation has taken place, and validation messages are being displayed. Unfortunately, you can't do anything about it, especially because you cannot access and manipulate the ValidationMessageStore object where those messages are stored. Steve Anderson has told me that such feature will be provided, if more people (in addition to me) ask for it. I told him that this feature is very important... it was a couple of months ago, and you are not the first person to show that this feature is essential. You may go to github, and post an issue, requesting this feature made available.
However, If you think you can't live with all the validation messages displayed at the same time ( some folks may say that it is desirable ), I guess you can do that implementing the ValidationMessage component to display only content you desire.
If I were you, I wouldn't do that. It's usually more desirable to display messages for all the fields that need to be filled, and I guess that when users click on the submit button, they usually fill most of the fields.
Hope this helps...

A: 1) yes model binding is the way to go
2) the validation message itself comes from the dataannotations in the data model


text:
Q: Make Windows 7/8 to use different partitions for system data and user/program data Is there the way to mount partition as /Users, while first one mounted as root (where /Windows folder lives)?
I want to be able to make backup image of system excepting all user/program data (like saves in game, photos, program settings, et cetera).
But there is another folder - /ProgramData, which I don't want to store in backup. So I need to make another partition for it?
In the internet I found solution, that makes /Users and /ProgamData to live in another "drive". And it has disadvantage, because some programs has hardcoded path to C:/Users or C:/ProgramData.


text:
Q: expand users table with django I'm using the authentication that ships with django, and as such, it comes with its own SQL table. I have a few more attributes I'd like to use with the User model that are custom to my app such as a user photo or a random user blob where users can type in notes.
what's the best way of extending the existing user table that ships with django's authentication/authorization modeling to allow for my custom fields?

A: Please see my (and others) answer to this question:

A: The other way to handle this is to do table inheritance on the User model and develop your own derived EnhancedUser model.  Typically a custom wrapper backend is also written to make sure the auth subsystem returns the EnhancedUser model as well.
There's a very good blog post answer here.


text:
Q: Find value in row header sum corresponding column I am seeking to sum values in one column in one sheet based on a value in a second sheet.

*

*In Sheet A, B3 = "JD".

*In Sheet B, there is a column specifically marked "JD".

I want a formula that will find the column in sheet B that is named the value in B3 (JD), and return the sum for all values in that column.
I know it should be simple but cannot figure it out!

A: Use this
=SUM(INDEX(SheetB!$A:$Z,0,MATCH(B3,SheetB!$1:$1,0)))


text:
Q: How to plot "voltage drop" across a specific component in LTSpice?
In the above circuit I can only be able to plot |Vr1+Vc1| = V1 in green plot and Vc1 in blue plot. I use the voltage probe in LTSpice and click on the lines to obtain the plots. If I click on the line between V1 and R1 it plots |Vr1+Vr2| = V1. If I click on the line between R1 and C1 it plots Vc1.
Is there a way to see also Vr1 (the voltage drop only accross R1) along with the others?

A: Click on the left side of the component (cursor will be a red probe before, then turning gray), drag over the component to the right (cursor will be a black probe), then release the mouse button.
Now the graph shows something like V(N002,N003) which is the voltage between those nodes. If you know the node names you can also manually enter these expressions into the graph view, or move things around or do calculations there.


text:
Q: Call .reg File from Access I want to call a .reg file from AutoExec Macro in Access so that once the Access application opens an ODBC registry is installed.
The following is the code I write to create a function. I call the function in the AutoExec Macro. But when I run this, the ODBC registry is not installed into the machine.
Public Function ImportReg()
    CreateObject("WScript.Shell").Run "%WinDir%\Regedit.exe /s R:\database2007\Testing\Test_Tool_ODBC.reg"
End Function

I tested the .reg file. If I double click, it works well and an ODBC registry is installed. That's why I think the problem may be the code.
I will be grateful if any help. Thank you very much!


text:
Q: NTFS Permissions I'm running ubuntu 13.10 x86_64 and I have modified /etc/fstab to mount my NTFS HDD with permissions but I'm getting some permissions errors because the owner is "root" instead of my user.
Thanks in advance
P.S: I had no problems doing this in Ubuntu 13.04 32bits
EDIT:
fstab content:
#/etc/fstab: static file system information.

#Use 'blkid' to print the universally unique identifier for a
#device; this may be used with UUID= as a more robust way to name devices
#that works even if disks are added and removed. See fstab(5).

#<file system> <mount point>   <type>  <options>       <dump>  <pass>
#/ was on /dev/sda5 during installation
UUID=3e857b61-2d2b-469a-a3eb-de1cf4d5130a /               ext4    errors=remount-ro 0
#/home was on /dev/sda7 during installation
#UUID=14887804-6799-443e-955f-6b2872cd441a /home           ext4    defaults        0       2
#swap was on /dev/sda6 during installation
#UUID=2da59282-61ee-40d2-821b-2042ff556748 none            swap    sw              0       0
#UUID=4A1499C11499B085 /media/ivykoko/269Gb ntfs umask=0000,utf8 0 0

A: To mount the drive with your user as the owner add the uid option.
Type id in the terminal to get your user ID from the output: uid=####.
Then add that option to fstab so your new entry will look like:
UUID=4A1499C11499B085 /media/ivykoko/269Gb ntfs umask=0000,utf8,uid=#### 0 0
Where #### is your actual uid.
Then unmount and remount the drive.


text:
Q: Merge one website into another website on same domain in Magento1.9.2.4 [Multiwebsite] I have Multi-website domain , which has 4 website with one store in each.
Likewise Site Structure-
Domain : example.com

Website                Store

example.com             UK
example.com/fr          FR
outlet.example.com      UK
outlet.example.com/fr   FR

Now I want to merge website-

outlet.example.com (UK) into example.com (UK)

and

outlet.example.com/fr (FR) into example.com (UK).

So -

*

*Which Entities among below,I need to move and HOW can I move each of
them  ?

*

*customer,

*orders,

*promotions,

*categories,

*products,

*newsletter subscribers etc.

*What changes it would require at backend or at code level as well ?


text:
Q: Does this DXF file contain geolocation data? I'm new to autocad and have been sent a file with polylines which I need to plot on a map.
However I cannot see that the file contains any geolocation data to plot it accurately.
The GeoLocation tab does not appear and reading the AutoCad knowledge base, I suspect that the file does not contain any location data.
Can someone download the file and confirm this or if I'm missing something?

A: You can load this into QGIS okay - it has 3 point features and 12 line features. The coordinate system is undefined, so exactly where on the planet the features live can't be determined. The bounding box of the coordinates is xMin,yMin 325880.38,6409376.11 : xMax,yMax 651934.19,12818724.96 - which isn't lat-long.
The ogrinfo command will tell you most of this:
$ ogrinfo -so -al testpoly.dxf
INFO: Open of `testpoly.dxf'
      using driver `DXF' successful.

Layer name: entities
Geometry: Unknown (any)
Feature Count: 15
Extent: (325880.382876, 6409376.107868) - (651934.193204, 12818724.956451)
Layer SRS WKT:
(unknown)
Layer: String (0.0)
SubClasses: String (0.0)
ExtendedEntity: String (0.0)
Linetype: String (0.0)
EntityHandle: String (0.0)
Text: String (0.0)

Without the -so (summary) flag you'll even get the coordinates and attributes of each feature:
$ ogrinfo -al testpoly.dxf
INFO: Open of `testpoly.dxf'
      using driver `DXF' successful.

Layer name: entities
Geometry: Unknown (any)
Feature Count: 15
Extent: (325880.382876, 6409376.107868) - (651934.193204, 12818724.956451)
Layer SRS WKT:
(unknown)
Layer: String (0.0)
SubClasses: String (0.0)
ExtendedEntity: String (0.0)
Linetype: String (0.0)
EntityHandle: String (0.0)
Text: String (0.0)
OGRFeature(entities):0
  Layer (String) = Gunnilse dagvatten_arc
  SubClasses (String) = AcDbEntity:AcDbBlockReference
  ExtendedEntity (String) = (null)
  Linetype (String) = (null)
  EntityHandle (String) = 29
  Text (String) = (null)
  Style = PEN(c:#7fff7f)
  LINESTRING (651870.29291189997457 12818660.791532900184393 2,651869.138874100055546 12818665.608888300135732 2,651868.297324900049716 12818669.17193860001862 2,651867.79771399998572 12818671.234730100259185 2,651867.36775169998873 12818675.153996299952269 2,651867.851822299999185 12818677.184894200414419 2,651868.40745499997865 12818680.869133699685335 2,651868.819348299992271 12818683.458861399441957 2,651869.270946800010279 12818686.965924400836229 2,651870.653307599946856 12818705.297845300287008 2,651870.880679300054908 12818708.077216699719429 2,651870.458569 12818712.177779801189899 2,651870.37601609993726 12818714.970561100170016 2,651870.643554799957201 12818718.677922200411558 2,651870.940263499971479 12818721.080252200365067 2,651871.33599349996075 12818723.296622600406408 2,651871.504200200084597 12818724.95645060017705 2)
[ etc etc ]


text:
Q: Is there a name for a matrix with all zeros on its diagonal? Consider a matrix having only zeros on its diagonal, i.e.
\begin{bmatrix}
0 & a & b \\
c & 0 & d \\
e & f & 0 \\
\end{bmatrix}
Has such type of matrices a name?

A: Actually there is a name for this kind of matrix
It is called Hollow Matrix

A: Perhaps a zero-diagonal-matrix?

A: These are co-diagonal matrices according to Low Rank Co-Diagonal Matrices and Ramsey Graphs by Vince Grolmusz..


text:
Q: How to CSS button back to top in footer How to create button back to top. In image, button in the middle content and footer and this have 2 circle as border.

A: this should get you started
http://jsfiddle.net/g1axjn1b/
There are a lot of different ways to do this, without knowing the exact scope of the project I just put together some very basic stuff and I'm sure someone else can answer you more thoroughly, but I want to explain what I did and what you need.
You are trying to create a link to the top of the page. There are some really great ways to do this in Javascript, which I will not cover.
What you need is an anchor at the top with a name, we specify this with
 which will go at the very top of your page. The "button" which takes your page back to the top will be a horizontal reference anchor. .
The other thing you were looking to do was style it. This can probably be achieved in more ways than you can imagine, but the way that I approached it was to create two div's which surround your character/src/ whatever you decided to use for it. I recommend fontawesome's up arrow  after including font-awesome.io on your page of course.
You want two div's which can either be styled together or separately, depending on what you're working with, it's probably more applicable to style them separately, but regardless the code you're looking for will be similar. You want your div's to posses two properties. Border which is defined with three attributes, size, style, color. it looks like this border:1px solid black; and the other property you'd be interested in would be border-radius which accepts up to 4 parameters, one for each corner starting at the top right if I'm not mistaken. If you're circles are in fact circles, you'll be able to set the value to 50%, like this border-radius:50%;.
I hope this helped. The last thing I wanted to mention is that it looked like you had some margin or padding in your picture, so don't forget to add those. They are set top, right, bottom, left; or top-bottom, left-right; or top, right-left, bottom; or top-right-left-bottom;

A: You can use onclick to do this.

        #style your position in this div


text:
Q: PostgreSQL - Creating a CDR-like View/Table from a Simple Agent States Table I have a table I am trying to work with as such:

Timestamp
Agent
State

2022/11/10 05:00:01
Steve
In Call

2022/11/10 06:00:01
Steve
Waiting

2022/11/10 05:00:01
Jack
In Call

2022/11/10 05:30:01
Jack
Waiting

2022/11/10 07:00:01
Steve
In Call

Basically, We have agents in a call centre, and whenever they change state, a record of the state, and the timestamps that the change occured, as well as the agents name is recorded into a DB. In order to work with this data in PowerBI, I need to change how it is displayed.
What i need to do is get this data into a view like follows:

Starttime
Endtime
Agent
State
Duration (s)

2022/11/10 05:00:01
2022/11/10 06:00:01
Steve
In Call
3600

2022/11/10 05:00:01
2022/11/10 05:30:01
Jack
In Call
1800

2022/11/10 06:00:01
2022/11/10 07:00:01
Steve
Waiting
3600

So using the data in the first table (we know the end times as when that agent changes to the next status, we can use that as the end time for the previous status), Im trying to get a new table or view, presenting the data with:

*

*Their Name

*Start and end time of the state

*the state

*The duration in seconds they were in that state

Im having a bit of trouble working out in my head how to do this for all of the agents and data. Can anyone provide me some guidance as to where I can start?

A:
What i need to do is get this data into a view like follows:

sure. The order may not be exact order. Change the order use order by clause as your wish.
setup test:
begin;
create temp table call(log_Timestamp timestamp,Agent text,  State text);
insert into call values
('2022/11/10 05:00:01',     'Steve'     ,'In Call')
,('2022/11/10 06:00:01',    'Steve'     ,'Waiting')
,('2022/11/10 05:00:01',    'Jack'  ,'In Call')
,('2022/11/10 05:30:01',    'Jack'  ,'Waiting')
,('2022/11/10 07:00:01',    'Steve'     ,'In Call');
commit;

query:
CREATE VIEW call_view AS
WITH cte AS (
    SELECT
        c1.log_Timestamp AS start,
        lead(c1.log_Timestamp) OVER (PARTITION BY Agent ORDER BY log_Timestamp),
        EXTRACT(EPOCH FROM (lead(c1.log_Timestamp) OVER (PARTITION BY Agent ORDER BY log_Timestamp) - c1.log_Timestamp)),
        Agent,
        state
    FROM CALL c1 ORDER BY Agent,
    log_Timestamp
)
SELECT
    *
FROM
    cte
WHERE
    lead IS NOT NULL;


text:
Q: Is representation theory in QM a real physical thing or just a mathematical tool? I was studying group theory and representation theory in Quantum Mechanics and I really don't understand yet if it is just a mathematical tool of seen the operators as a representation of a group action, or if it is really conected to the physical reallity. I guess Representation Theory is not the only thing that botters me in this sense, because every time I learn some deeper math in a physical theory I have the feeling that I am only using an abstract tool that happens to help me in my problem.

A: All of physics is not real. The universe is real. Physics is a mathematical model of the universe.
We see patterns of behavior in the universe. The purpose of physics is to describe those patterns. So the mathematical tools of physics are chosen to match the behavior. We call these the laws of physics.
Physicists use the laws to predict the behavior of the universe. Then they do experiments to confirm the predictions. Physicists quickly get used to the correspondence between the laws and the behavior. They begin to think of the laws and the behavior as the same thing. That is, when they think of the behavior described by Newton's $2^{nd}$ law, they thing of $F = ma$. This is a mathematical statement with two vectors and a number. But physicists think of this as the same thing. Force is a vector. Mass is a number.
So you are right. Representation theory is an abstract tool that helps describe the universe. But it is also connected to the physical reality.
This way of thinking dates back to Galileo, who first connected systematic mathematics to the behavior of the universe. Later Newton greatly expanded this ideas and transformed physics from philosophy to science.
Before this, it was not possible to think precisely about the behavior. Before this, people thought like Aristotle. He said rocks come to rest because it is the nature of rocks (things with lots of earth in them) to be at rest. The rock might move as it rolls down a hill, but soon the nature of the rock asserts itself. On the other hand, it is the nature of things like stars and planets (things with lots of fire in them) to move. You can see the advantage math brings.


text:
Q: vba vlookup/index match from another workbook with multiple worksheets where name and number of worksheet is variable Objective: trying to perform index match/vlookup from workbook 2 to workbook 1
Backgrounds:

*

*VBA must be coded on workbook 3 due to workbook 1 & 2 are browsed by user.

*workbook 1 is always with one sheet  only where sheetname = "sheet 1"

*workbook 2 would contain multiple worksheets where worksheets name and number of worksheets is variable

Below code is OK to copy data from 1ST sheet of workbook 2 to workbook 1.
What should be done so I could copy data from all the worksheets of workbook2 to workbook 1?
here is my code:
 Sub datacopy()

  'prompt user to select 1st workbook
 N = Application.GetOpenFilename _
 (Title:="Please choose OTS offline template file", _
 FileFilter:="Excel Files *.xls*; *.csv (*.xls*; *.csv),")
 Set twb = Workbooks.Open(N)

 If N = False Then
 MsgBox "No file selected. Please click run again and select file",
 vbExclamation, "Sorry!"
 Exit Sub
 Else
 End If

  'prompt user to select 2nd workbook
 R = Application.GetOpenFilename _
 (Title:="Please choose WIP information file", _
 FileFilter:="Excel Files *.xls*; *.csv (*.xls*; *.csv),")
 Set extwbk = Workbooks.Open(R)
 If R = False Then
 MsgBox "No file selected. Please click run again and select file.",
 vbExclamation, "Sorry!"
 Exit Sub
 Else
 End If

 Dim Row As Long
 Dim Clm As Long

extwbk.Sheets(1).Activate

table1 = twb.Sheets("Sheet1").Range("A1:A5") 'lookup value in 1st workbook
table2 = extwbk.activesheet.Range("A2:D5") ' DataRange of vlookup array table in 2nd workbook

Row = twb.Sheets("Sheet1").Range("B2").Row
Clm = twb.Sheets("Sheet1").Range("B2").Column
On Error Resume Next

For Each cl In table1
twb.Sheets("Sheet1").Cells(Row, Clm)
Application.WorksheetFunction.VLookup(cl, table2, 3, False)

Row = Row + 1
Next cl

extwbk.Close SaveChanges:=False

twb.Close SaveChanges:=True
MsgBox "Done"

End Sub

A: To reach all sheet in Workbook2, do this:
Dim wbk1 as Workbook, wbk2 as Workbook
Dim sh1 as Worksheet, sh2 as Worksheet
Dim rTarget as Range

Set wbk1 = <name of workbook1>
Set sh1 = wbk1.Sheets("Sheet1")
Set wbk2 = <name of workbook2>

for each sh2 in wbk2
   Set r = sh2.Range("A1:F300")
   Set rTarget = sh1.Range(<Set the top left cell of the desired target>
   r.Copy Destination:=sh1.rTarget
   <do everything else what you want>
next sh2

You need to change the target range loop by loop in order not to overwrite the previous copy.


text:
Q: CosmosDB Emulator: The value for one of the HTTP headers is not in the correct format I am writing/debugging an Azure Function with the Azure Storage Emulator on my local machine. Unfortunately, I'm not quite sure which API(s) I should use or the correct URLs for the storage. My code looks like this:
CosmosClient client = new CosmosClient(storageURL, authKeyString);
Database db = client.GetDatabase("devstoreaccount1");
container = db.GetContainer("leaderboard");
ItemResponse<StoredScore> resp = await container.CreateItemAsync<StoredScore>(newScore);

The inputs to the function are:
storageURL = "http://127.0.0.1:10002"
authKeyString = "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw=="

On the last line of the code above, I get an exception:
DocDBTrace Warning: 0 : initializeTask failed Microsoft.Azure.Documents.DocumentClientException: <?xml version="1.0" encoding="utf-8" standalone="yes"?>
<error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
  InvalidHeaderValue
  <message xml:lang="en-US">The value for one of the HTTP headers is not in the correct format.
RequestId:ed82efd8-6cb8-4a2e-a793-16a38b3c8f2a
Time:2019-12-20T20:07:19.9539313Z</message>
</error>
RequestUri: http://127.0.0.1:10002/;
RequestMethod: GET;
Header: x-ms-version Length: 10;
Header: User-Agent Length: 98;
Header: x-ms-date Length: 29;
Header: Authorization Length: 84;
, Request URI: /, RequestStats: , SDK: Windows/10.0.16299 cosmos-netstandard-sdk/3.4.2
   at Microsoft.Azure.Cosmos.GatewayStoreClient.ParseResponseAsync(HttpResponseMessage responseMessage, JsonSerializerSettings serializerSettings, DocumentServiceRequest request)
   at Microsoft.Azure.Cosmos.GatewayAccountReader.GetDatabaseAccountAsync(Uri serviceEndpoint)
   at Microsoft.Azure.Cosmos.Routing.GlobalEndpointManager.GetDatabaseAccountFromAnyLocationsAsync(Uri defaultEndpoint, IList`1 locations, Func`2 getDatabaseAccountFn)
   at Microsoft.Azure.Cosmos.GatewayAccountReader.InitializeReaderAsync()
   at Microsoft.Azure.Cosmos.CosmosAccountServiceConfiguration.InitializeAsync()
   at Microsoft.Azure.Cosmos.DocumentClient.InitializeGatewayConfigurationReaderAsync()
   at Microsoft.Azure.Cosmos.DocumentClient.GetInitializationTaskAsync(IStoreClientFactory storeClientFactory)
   at Microsoft.Azure.Cosmos.DocumentClient.EnsureValidClientAsync()
DocDBTrace Error: 0 : DocumentClientException with status code BadRequest, message: <?xml version="1.0" encoding="utf-8" standalone="yes"?>
<error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
  InvalidHeaderValue
  <message xml:lang="en-US">The value for one of the HTTP headers is not in the correct format.
RequestId:67e1f70a-c9c8-4aed-892c-964e8ff0f0e1
Time:2019-12-20T20:11:28.0006476Z</message>
</error>
RequestUri: http://127.0.0.1:10002/;
RequestMethod: GET;
Header: x-ms-version Length: 10;
Header: User-Agent Length: 98;
Header: x-ms-date Length: 29;
Header: Authorization Length: 82;
, inner exception: null, and response headers: {
"Server": "Microsoft-HTTPAPI/2.0",
"x-ms-request-id": "67e1f70a-c9c8-4aed-892c-964e8ff0f0e1",
"Date": "Fri, 20 Dec 2019 20:11:27 GMT",
}
DocDBTrace Information: 0 : Fail to reach global gateway http://127.0.0.1:10002/, Microsoft.Azure.Documents.DocumentClientException: <?xml version="1.0" encoding="utf-8" standalone="yes"?>
<error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
  InvalidHeaderValue
  <message xml:lang="en-US">The value for one of the HTTP headers is not in the correct format.
RequestId:67e1f70a-c9c8-4aed-892c-964e8ff0f0e1
Time:2019-12-20T20:11:28.0006476Z</message>
</error>
RequestUri: http://127.0.0.1:10002/;
RequestMethod: GET;
Header: x-ms-version Length: 10;
Header: User-Agent Length: 98;
Header: x-ms-date Length: 29;
Header: Authorization Length: 82;
, Request URI: /, RequestStats: , SDK: Windows/10.0.16299 cosmos-netstandard-sdk/3.4.2
   at Microsoft.Azure.Cosmos.GatewayStoreClient.ParseResponseAsync(HttpResponseMessage responseMessage, JsonSerializerSettings serializerSettings, DocumentServiceRequest request)
   at Microsoft.Azure.Cosmos.GatewayAccountReader.GetDatabaseAccountAsync(Uri serviceEndpoint)
   at Microsoft.Azure.Cosmos.Routing.GlobalEndpointManager.GetDatabaseAccountFromAnyLocationsAsync(Uri defaultEndpoint, IList`1 locations, Func`2 getDatabaseAccountFn)
Exception thrown: 'Microsoft.Azure.Documents.DocumentClientException' in System.Private.CoreLib.dll

The Azure Storage Emulator is running and I can manipulate it in Storage Explorer.
Can anyone help me figure out what I've done wrong? Am I using the 'best' API for this?

A: Based on your code, you want to use cosmosdb to store your StoredScore data. If so , you should use CosmosDB emulator on your side instead of storage Emulator.
Pls follow steps below to make your code work :

*

*Install and run CosmosDB emulator

*Create a cosmos db with a collection on your local :

In this case , my cosmos db name is localdb and my container name is localcontainer
You can find your cosmosdb host and key here :

3.Create a http trigged Azure function in VS locally, this is my code below :
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.Azure.Cosmos;

namespace cosmostest
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            CosmosClient client = new CosmosClient("https://localhost:8081/", "<your key here>");
            Database db = client.GetDatabase("<your local db name>");
            Container container = db.GetContainer("<your local container name>");
            var newScore = new StoredScore() { id ="1", name ="stan", score =100 };
            ItemResponse<StoredScore> resp = await container.CreateItemAsync<StoredScore>(newScore);
            return new OkObjectResult(resp.StatusCode);
        }
    }

    public class StoredScore
    {

        public string id { get; set; }
        public string name { get; set; }
        public int score { get; set; }
    }

}

Run the function and trigger it, if you get "201" as response, your data has been saved into you local cosmos DB successfully :

Data in local cosmos DB:

Hope it helps.


text:
Q: flash actionscript access filesystem without air? Is there any workaround to allow actionscript3 write to file system without adobe air?
The reason is because, in order to use adobe air, each of the web visitors will need to install add-on air run-time and that is tedious. Most of the users will have flash plug-in and not Adobe Air.

A: This is possible in Flash 10.
Take a look at the FileReference class, specifically the save method.
There are certain limitations imposed for security's sake, of course.
The write can only be initiated by user interaction (e.g. a button click), and it will always pop up the host OS's File Save dialog box prompting the user to choose a location (or cancel).


text:
Q: Confidence intervals relating to non-parametric data I have a question relating to computing confidence intervals that doesn't seem to be correct for my data. I have sales data on a test group and control group that looks something like this (note - the numbers have been made up just to show the kind of data I have):
Date        Group1 Control (Group1 - Control) Standardized(Group1 - Control)
X-Jan-20XX  123.5     187.2   (123.5-187.2)       -0.05
X           200.9     97.8
.            .         .          .                 .
.            .         .          .                 .
.            .         .          .                 .
Xn           Yn        Tn         Dn                Sn

I then compute the 95% confidence intervals on the standardized(group1 - control) using the standard method (shown below) to identify the line where we can safely assume the data should fall under.

The problem I have is shown through the image below, as you can see majority of the data falls outside of the confidence interval. It must be noted that my data is not normally distributed, however, when I standardize my data I get mean 0 and standard deviation of 1. Can someone help with solutions on this issue?
What I am suspicious of is the fact that my initial raw data is not normally distributed whilst the methods implemented are for normally distributed data. I believe this is why there are many data points that are not captured under the normal distribution. If this seems to be the problem, can someone suggest solutions?!?
Thanks!

A: You mix up the standard-deviation of your data, and the standard-deviation of the mean of your data. The confidence interval you mention is for the mean of your data, and it is not an interval where you "can safely assume the data should fall under". It is - in loose tersms - the interval where you "can safely assume that the mean of your data falls under".
 While the mean of your data sample is a single fixed number, it is subject to uncertainty. This is because it is estimated from a finite amount of datapoints. The mean of the distribution that underlies the datapoints might in fact be (slightly) different. If you estimated the mean from a finite sample, and if your data is normally distributed, then you can compute the uncertainty of your mean via the formula $\sigma/\sqrt{N}$, and with this you can construct confidence intervals. This does however not mean that a certain fraction of your datapoints lie withing that confidence interval. If $N$ goes towards infinity, your confidence interval gets smaller and smaller - meaning that a smaller and smaller fraction of points lies within the confidence interval. The confidence interval tells you something else: if you redo your whole experiment (gather new data), and for each experiment compute the mean of your datapoints, how many of these means would lie within that confidence interval.


text:
Q: Scenario of huge SQL Server Database backup I use SQL Server and have a huge database with large compressed backup size (about 250 GB).
The backup scenario of this database is:
Create full backup at the first day of each month.
Create Differential backup daily exclusive first day of each month.

also I use mirror backup in order to copy my backup file to another server.
Total time that need to create full backup is about 3 hour.
I look for a better scenario to create small backup size and copy faster than now.
In this database I have 2 filegroups (ArchiveFG and PRIMARY). The size of ArchiveFG is 200 GB, also this file group is read-only filegroup.
I don't know that can I use following scenario?
create full backup from ArchiveFG filegroup (One time).
create full backup from PRIMARY filegroup the first day of each month.
create differential backup from PRIMARY filegroup daily exclusive first day of each month.

And how can I restore backup with above scenario.
Thanks in advance

A: What you're looking to do is called a "piecemeal restore" and is pretty complicated. Here's a small pull quote from the MSDN article:

Every piecemeal restore starts with an initial restore sequence called the partial-restore sequence. Minimally, the partial-restore sequence restores and recovers the primary filegroup and, under the simple recovery model, all read/write filegroups.

I'm assuming that your database is in simple recovery since you didn't mention any log backup schedule. So, if you ever need to restore your archive filegroup, you'll end up restoring the entire database.
If I were you, I'd try tuning your backup before going this route. For instance, try taking the mirroring out of the backup command note the time difference. You can always copy it to the secondary location after the full backup completes.
But, if you're looking to proceed with the piecemeal restore solution, the actual syntax isn't that bad:
restore database [yourDB]
filegroup = 'PRIMARY'
from disk = '\\path\\to\\full_backup.bak'
with partial, norecovery;

restore database [yourDB]
filegroup = 'PRIMARY'
from disk = '\\path\\to\\diff_backup.bak'
with partial, recovery;

restore database [yourDB]
filegroup = 'ArchiveFG'
from disk = '\\path\\to\\archive.bak'
with recovery;


text:
Q: Batch file name string concatenation this problem has been bothering me for hours. I hope someone could help shed some light. Basically, I am trying to scan through all the files (of a specific type) in a folder (there are no subfolder inside, so no need to worry this case), get those files' name, and concatenate all into one string for example, if a folder has two files,
a.xml, b.xml and c.xml, I want to get a string looks like
-a a.xml -a b.xml -a c.xml
Below is my code.
copy *.xml C:\FTP
setLocal Enabledelayedexpansion
set "directory=C:\temp"
set "attachment= "
set "a= -a "
for %%n in (%directory% *.xml) DO (
set "attachment=!attachment! %a% %directory%\%%n "
echo.%attachment%
)
setlocal disabledelayedexpansion
echo.%attachment%

The output is shown in this image  http://imgur.com/vpUUe05
the problem I have is that first,
all echoes in the for loop prints out nothing. as shown in those blank lines.
the final string I want,i.e. attachment, contains an initial substring of
-a C:\temp\C:temp.

This is actually not a file. the final string I want should be one that is without this substring, only those behind it. By the way, if there is no file inside the folder, I want the string "attachment" to just an empty string like "".  Can anyone help me? Thanks a lot!

A: Inside your for loop you show the value of %attachment%, so that value is NOT updated in each iteration; you must use delayed expansion to do so.
The set of values in for command is: (%directory% *.xml) that is, the value C:\temp and all files with .xml extension, that I assumed is none in current directory. After that, you use this value in %a% %directory%\%%n expression, so the result is -a C:\temp\C:\temp. I think there is not a point here.
If you want not the folder value in the list, just don't insert it and use %~NXn modifier in the for replaceable parameter.
Below is the correct code:
copy *.xml C:\FTP
setLocal Enabledelayedexpansion
set "directory=C:\temp"
set "attachment= "
set "a= -a "
for %%n in ("%directory%\*.xml") DO (
set "attachment=!attachment! %a% %%~NXn "
echo.!attachment!
)
setlocal disabledelayedexpansion
echo.%attachment%


text:
Q: Parse Timestamp String with Quarter to Python datetime I am searching for a way to parse a rather unusual timestamp string to a Python datetime object. The problem here is, that this string includes the corresponding quarter, which seems not to be supported by the datetime.strptime function. The format of the string is as follows: YYYY/qq/mm/dd/HH/MM e.g 1970/Q1/01/01/00/00. I am searching for a function, which is allows me to parse string in such a format, including a validity check, if the quarter is correct for the date.

A:
Question: Datetime String with Quarter to Python datetime

This implements  a OOP solution which extends Python datetime with a directive: %Q.
Possible values: Q1|Q2|Q3|Q4, for example:
data_string = '1970/Q1/01/01/00/00'
#              '%Y/%Q/%m/%d/%H/%M'

Note: This depends on the module _strptime class TimeRE and may fail if the internal implementation changes!

from datetime import datetime

class Qdatetime(datetime):
    re_compile = None

    @classmethod
    def _strptime(cls):
        import _strptime
        _class = _strptime.TimeRE

        if not 'strptime_compile' in _class.__dict__:
            setattr(_class, 'strptime_compile', getattr(_class, 'compile'))
            setattr(_class, 'compile', cls.compile)

    def compile(self, format):
        import _strptime
        self = _strptime._TimeRE_cache

        # Add directive %Q
        if not 'Q' in self:
            self.update({'Q': r"(?P<Q>Q[1-4])"})

        Qdatetime.re_compile = self.strptime_compile(format)
        return Qdatetime.re_compile

    def validate(self, quarter):
        # 1970, 1, 1 is the lowest date used in timestamp
        month = [1, 4, 7, 10][quarter - 1]
        day = [31, 30, 30, 31][quarter - 1]
        q_start = datetime(self.year, month, 1).timestamp()
        q_end = datetime(self.year, month + 2, day).timestamp()
        dtt = self.timestamp()
        return dtt >= q_start and dtt<= q_end

    @property
    def quarter(self): return self._quarter
    @quarter.setter
    def quarter(self, data):
        found_dict = Qdatetime.re_compile.match(data).groupdict()
        self._quarter = int(found_dict['Q'][1])

    @property
    def datetime(self):
        return datetime(self.year, self.month, self.day,
                        hour=self.hour, minute=self.minute, second=self.second)

    def __str__(self):
        return 'Q{} {}'.format(self.quarter, super().__str__())

    @classmethod
    def strptime(cls, data_string, _format):
        cls._strptime()

        dt = super().strptime(data_string, _format)
        dt.quarter = data_string

        if not dt.validate(dt.quarter):
            raise ValueError("time data '{}' does not match quarter 'Q{}'"\
                     .format(data_string, dt.quarter))
        return dt

Usage:

for data_string in ['1970/Q1/01/01/00/00',
                    '1970/Q3/12/31/00/00',
                    '1970/Q2/05/05/00/00',
                    '1970/Q3/07/01/00/00',
                    '1970/Q4/12/31/00/00',
                   ]:
    try:
        d = Qdatetime.strptime(data_string, '%Y/%Q/%m/%d/%H/%M')
    except ValueError as e:
        print(e)
    else:
        print(d, d.datetime)

Output:
Q1 1970-01-01 00:00:00 1970-01-01 00:00:00
time data '1970/Q3/12/31/00/00' does not match quarter 'Q3'
Q2 1970-05-05 00:00:00 1970-05-05 00:00:00
Q3 1970-07-01 00:00:00 1970-07-01 00:00:00
Q4 1970-12-31 00:00:00 1970-12-31 00:00:00

Tested with Python: 3.6 - verified with Python 3.8 source


text:
Q: In horizontal scroll view the image centers by it's own. I need it to be centercropped Currently the layout looks this way:
https://cdn.pbrd.co/images/2IYgIygCi.png
I want it to look this way BUT the image to be horizontally scrollable:
https://cdn.pbrd.co/images/2IYsV5rzd.png
                <LinearLayout
                android:id="@+id/definition4_layout"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <HorizontalScrollView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="3">

                <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="160dp"
                        android:layout_weight="3"
                        android:scaleType="centerCrop"
                    android:src="@drawable/plsquadron" />
                </HorizontalScrollView>

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="10dp"
                    android:layout_weight="2"
                    android:text="@string/definition4_1"
                    android:textColor="@android:color/black" />

            </LinearLayout>

For some reason it automatically centers the image. What's the solution?


text:
Q: Amplified Sound in another room I was sitting in my room with my door open, because I have a cooler in my room that has a lot of noise when turned on. I was watching a video on my phone, but because of the noise from the cooler, I couldnt hear it and I had to increase the volume. However, my brother comes from the adjacent room and tells me he can hear the sounds from my phone very clearly and loudly, although his door was closed. I cant seem to understand this phenomenon. How can he hear sounds from my phone clearly, when I myself cant hear it clearly due to the cooler?

A: Several reasons are at work here, as follows.
First, if the cooler fan is closest to you, then you will be bothered by it more than your brother, who is farther away.
Second, the noise made by a cooler fan is well-blocked by walls and doors, whereas music and speech is less-well blocked.
Third, random noise (as from a cooler fan) is fundamentally less bothersome than speech and music, to which your hearing "software" is far more sensitive.
A practical application of these effects is called masking, where the sound system speakers in a busy, open office are fed a random whoosh noise which renders speech in an adjacent cubicle inaudible to you. In fact, after several days in such an office, you get used to the whoosh noise coming from the speakers and you stop hearing it altogether. The office seems to your ears to be perfectly quiet, even though it is not!


text:
Q: Vue/Vuefire: Ok, I can open a modal, save a image file to firebase, but can't get it to view without a refresh Lots of pieces, got them all working except one!
I can open a modal window, do a firebase image upload (with the correct call back to make sure the upload worked), save the image to firebase storage (using vuefire). And close the modal.
The image DOES NOT show up until I do a manual refresh, then displays fine. Also if the image has been cached, it works OK. Just can't figure out why I can't view the new image without that manual refresh.
CODE
HTML to Display image: edit.vue
<div>
    <img :src="showPhoto()" id="showPhoto" name="showPhoto" />
</div>

VUE code to populate html and open modal
    showModal: function() {
        this.$modal.show('save')
      },
      showPhoto: function () {

        const photoName = this.residentObj['photo']

        console.log('photoName', photoName)

        if (photoName) {

          const gsReference = storage.refFromURL('gs://connect-the-dots-ef09c.appspot.com/images/' + this.$route.params.id +
          '/' + photoName).getDownloadURL().then(function(url) {

            var img = document.getElementById('showPhoto')
            img.src = url
          })
        }
      }

Save uploaded image close modal, go back the parent page. I can push a new route, but that has no effect even though the image has changed.
save.vue
 methods: {
    onFileChange(e) {
      const file = e.target.files[0];

      const storageRef = firebase.storage().ref('images/' + this.$route.params.id + '/' + file.name);

   residentsRef.child(this.$route.params.id).update({photo:file.name});

    storageRef.put(file).then(function(result) {

    alert("OK, file uploaded!")

// this has no effect, and probably dont want to refresh the entire page this the "img src"
 // this.$router.push({name: 'edit', params: { id: this.$route.params.id }});

    }});

    this.closeModal ()

    });

Summary: I can save an image to firebase using vue/vuefire, but can't view the new image unless I do a manual refresh. A cached image works fine.
Thanks for any tips.


text:
Q: specific response to specific clients while making requests at the same time to the server Is there any way to get responses to a specific client when another client has a different request at the same time to the same server?
This is code snippet for an exchange server. The given function is present in a library named "ccxt", this function "exchange.fetchMarkets()" has an API which requests to a third party server which is an exchange server like 'bitfinex', 'crex24', 'binance', etc. The issue I am facing is when one client is requesting for an exchange like 'crex24' at the same time when another client is requesting for different exchange like 'binance', they are getting the same response as the function calls for the last recent exchange.
I want it to give responses according to the client's requests independent of each other.
this one is controller function:
const ccxt = require("ccxt");

exports.fetchMarkets = function(req, res){

  let API = req.params.exchangeId;
  let exchange = new ccxt[API]();

  if (exchange.has["fetchMarkets"]) {
    try{
        var markets = await exchange.fetchMarkets();
        res.send(markets)
    }catch (err) {
          let error = String(err);
          res.send({ failed: error });
    }
  }else{
    res.send({loadMarkets : "not available"})
  }
}

This is end point for the server request:
app.route('/markets/:exchangeId')
    .get(exchange.fetchMarkets)

Here you can find the ccxt library: https://github.com/ccxt/ccxt/wiki/Manual and can be included in the project by "npm install ccxt"

A: I don't see why the code you mentioned wouldn't work the way you are expecting it to work. I created a small app and it is working as expected. You can check here
https://repl.it/repls/IllfatedStrangeRepo
I am hitting four different request with different ids and I am getting different response.
Hope it clear the doubts.


text:
Q: store characters in character pointer I have a thread which parses incomming characters/bytes one by one.
I would like to store the sequence of bytes in a byte pointer, and in the end when the sequence of "\r\n" is found it should print the full message out.
unsigned char byte;
unsigned char *bytes = NULL;

while (true){              // thread which is running on the side
    byte = get();          // gets 1 byte from I/O
    bytes = byte;          //
    *bytes++;
    if (byte == 'x'){      // for now instead of "\r\n" i use the char 'x'
        printf( "Your message: %s", bytes);
        bytes = NULL;        //  or {0}?
    }
}

A: You should define bytes as array with size of max message length not a pointer.
unsigned char byte, i;
unsigned char arr[10];   // 10 for example
i=0;
while (true){
    byte = get();
    arr[i] = byte;
    i++;
    if (byte == 'x'){
        printf( "Your message: %s", arr);
    }
}

When you define bytes as a pointer, it points to nothing and writing to it may erase other data in your program, you can make it array or allocate space for it in run time using malloc

A: Your Code
unsigned char byte;
unsigned char *bytes = NULL;

while (true){

Nothing wrong here, but some things must be cleared:

*

*
*

*Did you alloc memory for your bytes buffer? That is, using malloc() family functions?

*

*If so, did you check malloc() return and made sure the pointer is ok?

*

*Did you include stdbool.h to use true and false?

Moving on...
byte = get();
bytes = byte;
*bytes++;

*

*

*I'm assuming get() returns an unsigned char, since you didn't give the code.

*

*Problem: bytes = byte. You're assigning an unsigned char to an unsigned char *. That's bad because unsigned char * is expecting a memory address (aka pointer) and you're giving it a character (which translates into a really bad memory address, cause you're giving addresses up to 255, which your program isn't allowed to access), and your compiler certainly complained about that assignment...

*

**byte++ has two "problems" (not being really problems): one, you don't need the * (dereferencing) operator to just increment the pointer reference, you could've done byte++; two, it was shorter and easier to understand if you switched this line and the previous one (bytes = byte) to *bytes++ = byte. If you don't know what this statement does, I suggest reading up on operator precedence and assignment operators.

Then we have...
if (byte == 'x'){
    printf( "Your message: %s", bytes);
    bytes = NULL;
}

*

*

*if's alright.

*

*printf() is messed up because you've been incrementing your bytes pointer the whole time while you were get()ting those characters. This means that the current location pointed by bytes is the end of your string (or message). To correct this, you can do one of two things: one, have a counter on the number of bytes read and then use that to decrement the bytes pointer and get the correct address; or two, use a secondary auxiliary pointer (which I prefer, cause it's easier to understand).

*

*bytes = NULL. If you did malloc() for your bytes buffer, here you're destroying that reference, because you're making an assignment that effectively changes the address to which the pointer points to to NULL. Anyway, what you need to clear that buffer is memset(). Read more about it in the manual.

*

*Another subtle (but serious) problem is the end of string character, which you forgot to put in that string altogether. Without it, printf() will start printing really weired things past your message until a Segmentation Fault or the like happens. To do that, you can use your already incremented bytes pointer and do *bytes = 0x0 or *bytes = '\0'. The NULL terminating byte is used in a string so that functions know where the string ends. Without it, it would be really hard to manipulate strings.

Code
    unsigned char byte;
    unsigned char *bytes = NULL;
    unsigned char *bytes_aux;

    bytes = malloc(500);
    if (!bytes) return;
    bytes_aux = bytes;

    while (true) {  /* could use while(1)... */
        byte = get();
        *bytes++ = byte;
        if (byte == 'x') {
            *(bytes - 1) = 0x0;
            bytes = bytes_aux;
            printf("Your message: %s\n", bytes);
            memset(bytes, 0, 500);
        }
    }

*

*

*if ((*bytes++ = get()) == 'x') is a compound version of the three byte = get(); *bytes++ = byte; if (byte == 'x'). Refer to that assignment link I told you about! This is a neat way of writing it and will make you look super cool at parties!

*

**(bytes - 1) = 0x0; The -1 bit is to exclude the x character which was saved in the string. With one step we exclude the x and set the NULL terminating byte.

*

*bytes = bytes_aux; This restores bytes default state - now it correctly points to the beginning of the message.

*

*memset(bytes, 0, 500) The function I told you about to reset your string.

*

*Using memset is not necessary in this particular case. Every loop repetition we're saving characters from the beginning of the bytes buffer forward. Then, we set a NULL terminating byte and restore it's original position, effectively overwriting all other data. The NULL byte will take care of preventing printf() from printing whatever lies after the end of the current message. So the memset() part can be skipped and precious CPU time saved!

*

*Somewhere when you get out of that loop (if you do), remember to free() the bytes pointer! You don't want that memory leaking...


text:
Q: Shadow stack implementation on x86_64 In Control Flow Integrity, a protected shadow stack is implemented using x86 segments via LDT. But in x86_64 segmentation is disabled. Is there any other mechanism available which can be used to implement a protected stack on x86_64?
Edit
Found a recent paper which describes several alternatives.

A: I think the idea for 32-bit CFI is to set a limit on DS/ES/SS, and put the shadow stack outside that, so it can only be corrupted by instructions with a gs: segment override prefix.
This only works in compat mode (32-bit user-space) on x86-64, because CS/DS/ES/SS have fixed base=0 and no limit when the CPU is in long mode.
FS and GS can have a non-zero base even in long mode, but even if you could set a limit on those segments, it's the opposite of what you need.  (That would protect regular memory from instructions with a gs prefix, instead of the other way around.)  Fun fact: @MichaelPetch says most CPUs don't support a limit on those segments in long mode anyway.

For the Linux x32 ABI (32-bit pointers in long mode), you could put the shadow stack outside the low 4GiB of virtual address space.  Normal compiler-generated code always takes care to truncate pointers to 32-bit.  The current default code-gen strategy (-maddress-mode=short) is to use address-size prefixes on every instruction with a memory operand, except rsp, which is assumed to always be zero-extended.
This leads to a lot of wasted address-size prefixes, but it means that code compiled for x32 by current gcc will definitely truncate pointers to 32-bit, even when there's UB, making it impossible for compiler-generated code to load/store outside the low 4GiB of address space.

I don't think long mode has any general way to make a region of virtual address space accessible only with some kind of special instruction, either a prefix or something else.  So if you're defending against normal code using 64-bit operand-size, there are no options that replace segment tricks with baseline x86-64.  You'd have to map / unmap the shadow stack, which would be unusably slow.
There are several other technologies for enforcing / checking control flow these days.  Intel's CET (Control-flow Enforcement Technology) gives hardware support for various stuff, including a shadow stack.  Grsecurity published a review / critique of it.  Their conclusion starts with "In summary, Intel's CET is mainly a hardware implementation of Microsoft's weak CFI implementation with the addition of a shadow stack."  IDK if this review is accurate.  Grsecurity does produce a competing product (which they acknowledge), so there might be some bias.  I'm sure CET is better than nothing.
See also https://github.com/huku-/research/wiki/Intel-CPU-security-features for a list of x86 (or maybe specifically Intel) CPU features that assist security in general (like MPX bounds checking), not just control-flow.


text:
Q: Django url mapping: regular expression In Django, I would like to use the regular expression:
url(r'^(?P<arg1>\w+)/(?P<arg2>\w*)/$', ...)

to match the following two requests:
http://localhost:8000/someApp/showData/
http://localhost:8000/someApp/showData/addRecord/

It doesn't work for the first request. How should I do it?

A: Add the preceding / before the second capturing group plus the second capturing group into a non-capturing group and make it as optional by adding ? after the whole non-capturing group.
^(?P<arg1>\w+)(?:/(?P<arg2>\w*))?/$

OR
Make the preceding / character before the second non-capturing group as optional.
^(?P<arg1>\w+)/?(?P<arg2>\w*)/$

A: I would suggest you to use two urlconf lines instead of one, one with one param and the other with both, both pointing to the same view which has the second argument optional. Something like:
# urls.py
urlpatterns = patterns("",
    url(r"^(?P<arg1>\w+)/(?P<arg2>\w+)/$", yourview, name="yourview_with_arg1_arg2"),
    url(r"^(?P<arg1>\w+)/$", yourview, name="yourview_with_arg1"
)

# views.py
def yourview(arg1, arg2=None):
    pass # etc

This way your intentions are much clearer to anyone seeing your code later, and it's easier to extract some of the functionality into a separate view if necessary.


text:
Q: Create a setter for a local variable in a Javascript object I have the following code
var loyaltyObject = (function () {
  var data = null, vm, getLoyaltyUrl;

  function getData() {
    $.ajax({
      type: 'POST',
      url: getLoyaltyUrl,
      contentType: 'application/json; charset=utf-8',
      dataType: 'json',
      success: function (resp) {
        data = resp;
      },
      error: function (resp) {
        console.log('Error fetching offers!');
        console.log(resp);
      }// error(resp)
    });// $.ajax()
  }

...

  vm = {
    getData: getData,
    getLoyaltyUrl: getLoyaltyUrl
  };

  return vm;
}());

on document.ready I call
function Init() {
    window.loyaltyObject.getLoyaltyUrl = '@Url.Action("GetLoyaltyData", "Orders")';
    window.loyaltyObject.getData();
}

window.loyaltyObject.getLoyaltyUrl  is indeed the url but the internal getLoyaltyUrl is still undefined.
I read the following return a variable as a property about setting up a getter, but how would I perform a setter, what is the this or value I would be setting?
Also would it be comparable on most browsers?

A: You are assigning the value to vm.getLoyaltyUrl not to the private variable getLoyaltyUrl. That variable has no inheritance from the object vm so it never ever gets defined in your code
Just change:
url: getLoyaltyUrl

to
url: vm.getLoyaltyUrl

Simplified example

var loyaltyObject = (function () {
  var data = null, vm;

  function getData() {
   // switched out the ajax for a simple console.log()
   console.log(vm.getLoyaltyUrl)
  }

  vm = {
    getData: getData,
    getLoyaltyUrl: null
  };

  return vm;
}());
// following is exactly what you have
function Init() {
    window.loyaltyObject.getLoyaltyUrl = '@Url.Action("GetLoyaltyData", "Orders")';
    window.loyaltyObject.getData();
}

Init()

A:
but how would I perform a setter, what is the this or value I would be setting?

You would simply assign to the variable getLoyaltyUrl:
vm = {
  // ...
  set getLoyaltyUrl(value) {
    getLoyaltyUrl = value;
  },
}

You wouldn't use this in your case. value is the value assigned to the property.

A: I don't think there's any need for a custom property here. But you can look into Object.defineProperty or it's Reflect counterpart to change objects properties on the fly.
Object.defineProperty(obj, 'getLoyaltyUrl', {
    set: (value) => {
        // do something here, better be worth it.
    },
    get: () => {}
})