text:
Q: Rationale to prefer local variables over instance variables? The codebase I'm working on frequently uses instance variables to share data between various trivial methods. The original developer is adamant that this adheres to the best practices stated in the Clean Code book by Uncle Bob/Robert Martin: "The first rule of functions is that they should be small." and "The ideal number of arguments for a function is
zero (niladic). (...) Arguments are hard. They take a lot of conceptual power."
An example:
public class SomeBusinessProcess {
  @Inject private Router router;
  @Inject private ServiceClient serviceClient;
  @Inject private CryptoService cryptoService;

  private byte[] encodedData;
  private EncryptionInfo encryptionInfo;
  private EncryptedObject payloadOfResponse;
  private URI destinationURI;

  public EncryptedResponse process(EncryptedRequest encryptedRequest) {
    checkNotNull(encryptedRequest);

    getEncodedData(encryptedRequest);
    getEncryptionInfo();
    getDestinationURI();
    passRequestToServiceClient();

    return cryptoService.encryptResponse(payloadOfResponse);
  }

  private void getEncodedData(EncryptedRequest encryptedRequest) {
    encodedData = cryptoService.decryptRequest(encryptedRequest, byte[].class);
  }

  private void getEncryptionInfo() {
    encryptionInfo = cryptoService.getEncryptionInfoForDefaultClient();
  }

  private void getDestinationURI() {
    destinationURI = router.getDestination().getUri();
  }

  private void passRequestToServiceClient() {
    payloadOfResponse = serviceClient.handle(destinationURI, encodedData, encryptionInfo);
  }
}

I would refactor that into the following using local variables:
public class SomeBusinessProcess {
  @Inject private Router router;
  @Inject private ServiceClient serviceClient;
  @Inject private CryptoService cryptoService;

  public EncryptedResponse process(EncryptedRequest encryptedRequest) {
    checkNotNull(encryptedRequest);

    byte[] encodedData = cryptoService.decryptRequest(encryptedRequest, byte[].class);
    EncryptionInfo encryptionInfo = cryptoService.getEncryptionInfoForDefaultClient();
    URI destinationURI = router.getDestination().getUri();
    EncryptedObject payloadOfResponse = serviceClient.handle(destinationURI, encodedData,
      encryptionInfo);

    return cryptoService.encryptResponse(payloadOfResponse);
  }
}

This is shorter, it eliminates the implicit data coupling between the various trivial methods and it limits the variable scopes to the minimum required. Yet despite these benefits I still cannot seem to convince the original developer that this refactoring is warranted, as it appears to contradict the practices of Uncle Bob mentioned above.
Hence my questions:
What is the objective, scientific rationale to favor local variables over instance variables? I can't quite seem to put my finger on it. My intuition tells me that hidden couplings are bad and that a narrow scope is better than a broad one. But what is the science to back this up?
And conversely, are there any downsides to this refactoring that I have possibly overlooked?

A: Discussing just process(...), your colleagues example is far more legible in the sense of business logic. Conversely your counter example takes more than a cursory glance to extract any meaning.
That being said, clean code is both legible and good quality - pushing local state out into a more global space is just high-level assembly, so a zero for quality.
public class SomeBusinessProcess {
  @Inject private Router router;
  @Inject private ServiceClient serviceClient;
  @Inject private CryptoService cryptoService;

  public EncryptedResponse process(EncryptedRequest request) {
    checkNotNull(encryptedRequest);

    return encryptResponse
      (routeTo
         ( destination()
         , requestData(request)
         , destinationEncryption()
         )
      );
  }

  private byte[] requestData(EncryptedRequest encryptedRequest) {
    return cryptoService.decryptRequest(encryptedRequest, byte[].class);
  }

  private EncryptionInfo destinationEncryption() {
    return cryptoService.getEncryptionInfoForDefaultClient();
  }

  private URI destination() {
    return router.getDestination().getUri();
  }

  private EncryptedObject routeTo(URI destinationURI, byte[] encodedData, EncryptionInfo encryptionInfo) {
    return serviceClient.handle(destinationURI, encodedData, encryptionInfo);
  }

  private void encryptResponse(EncryptedObject payloadOfResponse) {
    return cryptoService.encryptResponse(payloadOfResponse);
  }
}

This is a rendition that removes the need for variables at any scope. Yes the compiler will generate them but the important part is that it controls that so the code will be efficient. While also being relatively legible.
Just a point on naming. You want the shortest name that is meaningful and expands on the information already available. ie. destinationURI, the 'URI' is already known by the type signature.

A: The original code is using member variables like arguments. When he says to minimize the number of arguments, what he really means is to minimize the amount of data that the methods requires in order to function. Putting that data into member variables doesn't improve anything.

A: I would just remove these variables and private methods altogether. Here's my refactor:
public class SomeBusinessProcess {
  @Inject private Router router;
  @Inject private ServiceClient serviceClient;
  @Inject private CryptoService cryptoService;

  public EncryptedResponse process(EncryptedRequest encryptedRequest) {
    return cryptoService.encryptResponse(
        serviceClient.handle(router.getDestination().getUri(),
        cryptoService.decryptRequest(encryptedRequest, byte[].class),
        cryptoService.getEncryptionInfoForDefaultClient()));
  }
}

For private method, e.g.  router.getDestination().getUri() is clearer and more readable than getDestinationURI(). I would even just repeat that if I use the same line twice in the same class. To look at it another way, if there's a need for a getDestinationURI(), then it probably belongs in some other class, not in SomeBusinessProcess class.
For variables and properties, the common need for them is to hold values to be used later in time. If the class has no public interface for the properties, they probably shouldn't be properties. The worst kind of class properties use is probably for passing values between private methods by way of side effects.
Anyway, the class only needs to do process() and then the object will be thrown away, there's no need to keep any state in memory. Further refactor potential would be to take out the CryptoService out of that class.
Based on comments, I want to add this answer is based on real world practice. Indeed, in code review, the first thing that I'd pick out is to refactor the class and move out the encrypt/decrypt work. Once that's done, then I'd ask if the methods and variables are needed, are they named correctly and so on. The final code will probably closer to this:
public class SomeBusinessProcess {
  @Inject private Router router;
  @Inject private ServiceClient serviceClient;

  public Response process(Request request) {
    return serviceClient.handle(router.getDestination().getUri());
  }
}

With above code, I don't think it needs further refactor. As with the rules, I think it takes experience to know when and when not to apply them. Rules are not theories that are proven to work in all situations.
Code review on the other hand has real impact on how long before a piece of code can pass. My trick is to have less code and make it easy to understand. A variable name can be a point of discussion, if I can remove it reviewers wouldn't even need to think about it.

A: Other answers have already explained the benefits of local variables perfectly, so all that remains is this part of your question:

Yet despite these benefits I still cannot seem to convince the original developer that this refactoring is warranted, as it appears to contradict the practices of Uncle Bob mentioned above.

That should be easy. Simply point him to the following quote in Uncle Bob's Clean Code:

Have No Side Effects
Side effects are lies. Your function promises to do one thing, but it also does other hidden things. Sometimes it will make unexpected changes to the variables of its own class. Sometimes it will make them to the parameters passed into the function or to system globals. In either case they are devious and damaging mistruths that often result in strange temporal couplings and order dependencies.
(example omitted)
This side effect creates a temporal coupling. That is, checkPassword can only be called at certain times (in other words, when it is safe to initialize the session). If it is called out of order, session data may be inadvertently lost. Temporal couplings are confusing, especially when hidden as a side effect. If you must have a temporal coupling, you should make it clear in the name of the function. In this case we might rename the function checkPasswordAndInitializeSession, though that certainly violates "Do one thing."

That is, Uncle Bob doesn't just say that a function should take few arguments, he also says that functions should avoid interacting with non-local state whenever possible.

A: Flater's answer covers issues of scoping quite well, but I think that there's another issue here too.
Note that there's a difference between a function that processes data and a function that simply accesses data.
The former executes actual business logic, whereas the latter saves typing and perhaps adds safety by adding a simpler and more reusable interface.
In this case it seems that the data-access functions don't save typing, and aren't reused anywhere (or there would be other issues in removing them). So these functions simply shouldn't exist.
By keeping only the business logic in named functions, we get the best of both worlds (somewhere between Flater's answer and imel96's  answer):
public EncryptedResponse process(EncryptedRequest encryptedRequest) {

    byte[] requestData = decryptRequest(encryptedRequest);
    EncryptedObject responseData = handleRequest(router.getDestination().getUri(), requestData, cryptoService.getEncryptionInfoForDefaultClient());
    EncryptedResponse response = encryptResponse(responseData);

    return response;
}

// define: decryptRequest(), handleRequest(), encryptResponse()

A: "It contradicts what someone's uncle thinks" is NEVER a good argument. NEVER. Don't take wisdom from uncles, think for yourself.
That said, instance variables should be used to store information that is actually required to be stored permanently or semi-permanently. The information here isn't. It is very simple to live without the instance variables, so they can go.
Test: Write a documentation comment for each instance variable. Can you write anything that isn't completely pointless? And write a documentation comment to the four accessors. They are equally pointless.
Worst is, assume the way to decrypt changes, because you use a different cryptoService. Instead of having to change four lines of code, you have to replace four instance variables with different ones, four getters with different ones, and change four lines of code.
But of course the first version is preferable if you are paid by the line of code. 31 lines instead of 11 lines. Three times more lines to write, and to maintain forever, to read when you are debugging something, to adapt when changes are needed, to duplicate if you support a second cryptoService.
(Missed the important point that using local variables forces you to make the calls in the right order).

A: The first and most important thing: Uncle Bob seems to be like a preacher sometimes, but states that there are exceptions to his rules.
The whole idea of Clean Code is to improve readability and to avoid errors. There are several rules that are violating each other.
His argument on functions is that niladic functions are best, however that up to three parameters are acceptable. I personally think that 4 are also ok.
When instance variables are used, they should make a coherent class. That means, the variables should be used in many, if not all non-static methods.
Variables that are not used in many places of the class, should be moved.
I would neither consider the original nor the refactored version optimal, and @Flater stated already very well what can be done with return values. It improves readability and reduces errors to use return values.

A:
What is the objective, scientific rationale to favor local variables over instance variables?

Scope isn't a binary state, it's a gradient. You can rank these from largest to smallest:
Global > Class > Local (method) > Local (code block, e.g. if, for, ...)

Edit: what I call a "class scope" is what you mean by "instance variable". To my knowledge, those are synonymous, but I'm a C# dev, not a Java dev. For the sake of brevity, I've lumped all statics into the global category since statics are not the topic of the question.
The smaller the scope, the better. The rationale is that variables should live in the smallest scope possible. There are many benefits to this:

*

*It forces you to think about the current class' responsibility and helps you stick to SRP.

*It enables you to not have to avoid global naming conflicts, e.g. if two or more classes have a Name property, you're not forced to prefix them like FooName, BarName, ... Thus keeping your variable names as clean and terse as possible.

*It declutters the code by limiting the available variables (e.g. for Intellisense) to those that are contextually relevant.

*It enables some form of access control so your data can't be manipulated by some actor you don't know about (e.g. a different class developed by a colleague).

*It makes the code more readable as you ensure that the declaration of these variables tries to stay as close to the actual usage of these variables as is possible.

*Wantonly declaring variables in an overly wide scope is often indicative of a developer who doesn't quite grasp OOP or how to implement it. Seeing overly widely scoped variables acts as a red flag that there's probably something going wrong with the OOP approach (either with the developer in general or the codebase in specific).

*(Comment by Kevin) Using locals forces you to do things in the right order. In the original (class variable) code, you could wrongly move passRequestToServiceClient() to the top of the method, and it would still compile. With locals, you could only make that mistake if you passed an uninitialized variable, which is hopefully obvious enough that you don't actually do it.

Yet despite these benefits I still cannot seem to convince the original developer that this refactoring is warranted, as it appears to contradict the practices of Uncle Bob mentioned above.
And conversely, are there any downsides to this refactoring that I have possibly overlooked?

The issue here is that your argument for local variables is valid, but you've also made additional changes which are not correct and cause your suggested fix to fail the smell test.
While I understand your "no class variable" suggestion and there's merit to it, you've actually also removed the methods themselves, and that's a whole different ballgame. The methods should have stayed, and instead you should've altered them to return their value rather than store it in a class variable:
private byte[] getEncodedData() {
    return cryptoService.decryptRequest(encryptedRequest, byte[].class);
}

private EncryptionInfo getEncryptionInfo() {
    return cryptoService.getEncryptionInfoForDefaultClient();
}

// and so on...

I do agree with what you've done in the process method, but you should've been calling the private submethods rather than executing their bodies directly.
public EncryptedResponse process(EncryptedRequest encryptedRequest) {
    checkNotNull(encryptedRequest);

    byte[] encodedData = getEncodedData();
    EncryptionInfo encryptionInfo = getEncryptionInfo();

    //and so on...

    return cryptoService.encryptResponse(payloadOfResponse);
}

You'd want that extra layer of abstraction, especially when you run into methods that need to be reused several times. Even if you don't currently reuse your methods, it's still a matter of good practice to already create submethods where relevant, even if only to aid code readability.
Regardless of the local variable argument, I immediately noticed that your suggested fix is considerably less readable than the original. I do concede that wanton use of class variables also detracts from code readability, but not at first sight compared to you having stacked all the logic in a single (now long-winded) method.

A:
What is the objective, scientific rationale to favor local variables
  over instance variables? I can't quite seem to put my finger on it. My
  intuition tells me that hidden couplings are bad and that a narrow
  scope is better than a broad one. But what is the science to back this
  up?

Instance variables are for representing the properties of their host object, not for representing properties specific to threads of computation more narrowly scoped than the object itself.  Some of the reasons for drawing such a distinction that appear not to already have been covered revolve around concurrency and reentrancy.  If methods exchange data by setting the values of instance variables, then two concurrent threads can easily clobber each other's values for those instances variables, yielding intermittent, hard-to-find bugs.
Even one thread alone can encounter problems along those lines, because there is a high risk that a data exchange pattern relying on instance variables makes methods non-reentrant.  Similarly, if the same variables are used to convey data between different pairs of methods, then there is a risk that a single thread executing even a non-recursive chain of method invocations will run into bugs revolving around unexpected modifications of the instance variables involved.
In order to get reliably correct results in such a scenario, you need either to use separate variables to communicate between each pair of methods where one invokes the other, or else to have every method implementation take into account all the implementation details of all the other methods it invokes, whether directly or indirectly.  This is brittle, and it scales poorly.

A: Local variables reduce scope hence limits the ways in which the variables can be used and hence helps prevent certain classes of error, and improves readability.
Instance variable reduce the ways in which the function can be called which also helps reduce certain classes of error, and improves readability.
To say one is right and the other is wrong may well be a valid conclusion in any one particular case, but as general advice...
TL;DR: I think the reason you smell too much zeal is, there's too much zeal.

A: Despite the fact that methods starting with get... should not return void, the separation of levels of abstractions within the methods is given in the first solution. Although the second solution is more scoped it is still harder to reason about what is going on in the method. The assignments of local variables are not needed here. I would keep the method names and refactor the code to something like that:
public class SomeBusinessProcess {
  @Inject private Router router;
  @Inject private ServiceClient serviceClient;
  @Inject private CryptoService cryptoService;

  public EncryptedResponse process(EncryptedRequest encryptedRequest) {
    checkNotNull(encryptedRequest);

    return getEncryptedResponse(
            passRequestToServiceClient(getDestinationURI(), getEncodedData(encryptedRequest) getEncryptionInfo())
        );
  }

  private EncryptedResponse getEncryptedResponse(EncryptedObject encryptedObject) {
    return cryptoService.encryptResponse(encryptedObject);
  }

  private byte[] getEncodedData(EncryptedRequest encryptedRequest) {
    return cryptoService.decryptRequest(encryptedRequest, byte[].class);
  }

  private EncryptionInfo getEncryptionInfo() {
    return cryptoService.getEncryptionInfoForDefaultClient();
  }

  private URI getDestinationURI() {
    return router.getDestination().getUri();
  }

  private EncryptedObject passRequestToServiceClient(URI destinationURI, byte[] encodedData, EncryptionInfo encryptionInfo) {
    return serviceClient.handle(destinationURI, encodedData, encryptionInfo);
  }
}

A: Both things do the same and the performance differences are unnoticeable, so I don't think there's a scientific argument. It comes down to subjective preferences then.
And I too tend to like your way better than your colleague's. Why? Because I think it's easier to read and understand, despite what some book author says.
Both ways accomplish the same thing, but his way is more spread out. To read that code you need to shift back and forth between several functions and member variables. It's not all condensed in one place, you need to remember all that in your head to understand it. It's a much greater cognitive load.
In contrast, your approach packs everything much more densely, but no so as to make it impenetrable. You just read it line after line, and you don't need to memorize so much to  understand it.
However if he's used to code being laid out in such a fashion, I can imagine that for him it might be the other way round.


text:
Q: LDAP Query for all uniquemembers of a group I can accomplish this with memberOf but due to API constraints with Okta, this goes over our rate limit and is too slow for production use. I am trying to do this with uniqueMember as this supports indexing but I am having a real hard time getting this to query correctly.
Here is what I have and I believe the issue is how I am thinking of uniqueMember. I believe it is just an attribute for the groups but I don't know how to query a list of groups to get the uniqueMembers.
(&(objectClass=inetOrgPerson)(|(uniqueMember=CN=groupnamehere,ou=groups,dc=myorg,dc=okta,dc=com)
The memberof query that works
(&(objectClass=inetOrgPerson)(|(memberOf=CN=group1,ou=groups,dc=myorg,dc=okta,dc=com)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Oracle - How to find if the dates in a given list fall between a date range I have a list of dates.
The list will be passed as a java collection.
The list is dynamic. I want to check if the dates in the list fall between my startDate and endDate, without using a stored proc, preferably.
I can iterate through the list and execute the query for each startDate/endDate pair of the list.
But is it possible to avoid iteration and do it all in one statement?
Something like
select * from myTable
where <datesInList> between startDate and endDate;

Is there a way in Oracle to do this?

A: You could convert the array into a table with the TABLE function and then use it in a SQL query. For example:
DECLARE
  v_dates sys.ODCIDateList := sys.ODCIDateList(TO_DATE('01-01-2001','DD-MM-RRRR'),
                                               TO_DATE('01-02-2001','DD-MM-RRRR'),
                                               TO_DATE('01-03-2001','DD-MM-RRRR'),
                                               TO_DATE('01-04-2001','DD-MM-RRRR'));
  n NUMBER;
BEGIN
  SELECT COUNT(1)
  INTO n
  FROM TABLE(v_dates)
  WHERE COLUMN_VALUE NOT BETWEEN start_date AND end_date;

  IF n > 0 THEN
    dbms_output.put_line('There''s ' || n || ' dates out of the range');
  ELSE
    dbms_output.put_line('All dates are in the range');
  END IF;
END;


text:
Q: Batch file to copy files listed in a text file from source to destination keeping the folder structure I would like to create a batch file to copy files listed in a text file from a source folder to a destination folder. I checked this question but this doesn't copy the folders.
Right now I have the code below and it searches for the files in the list in the source folders but it then copies them to the destination folder but I get just the files, not the folders.
Destination Folder, and the File List reside under different paths:
File list:         W:\Parrot EN VO\Copylist.txt

DestinationFolder: W:\Parrot EN VO\VO4test

And File List points to files in different locations (sometimes the file names are the same but they are in different folders):
W:\Parrot EN VO\VO4_VO4b\Actor_A\file1.wav

W:\Parrot EN VO\VO4_VO4b\Actor_B\file1.wav

W:\Parrot EN VO\VO4_VO4b\Actor_B\file2.wav

W:\Parrot EN VO\VO4_VO4b\Actor_C\file1.wav

this is the code I have:
@echo off
for /f "tokens=* delims=" %%a in ('type "W:\Parrot EN VO\Copylist.txt"') do xcopy /hrkvy "%%a" "W:\Parrot EN VO\VO4test"

pause
Thanks!

A: I decided to start from scratch with a different approach and with help from another answer that I saw I managed to make it work:
@echo off

setlocal enabledelayedexpansion

set "source=input dir"
set "target=output dir"

for /f "tokens=* usebackq" %%A in ("file_list.txt") do (
set "FILE=%%A"
set "dest_file_full=%target%\!FILE:%source%=!"
set "dest_file_filename=%%~nxA"
call set "dest_file_dir=%%dest_file_full:!dest_file_filename!=%%"
if not exist "!dest_file_dir!" (
    md "!dest_file_dir!"
)
set "source_file_full=%source%\!FILE:%source%=!"
copy "!source_file_full!" "!dest_file_dir!"
)
pause


text:
Q: JSON Extract with IN statement, possible? This query works as expected.
SELECT DISTINCT JSON_UNQUOTE(JSON_EXTRACT(`colors` , '$."65"')) FROM color

Is it possible to do the same query but with an SQL IN statement as I'm trying to do below.
SELECT DISTINCT JSON_UNQUOTE(JSON_EXTRACT(`colors` , IN('$."65"','$."66"','$."67"','$."68"','$."69"'))) FROM color

I also want the result ordered by value ASC.

A: In 5.7 JSON_EXTRACT can accept more than 1 path element. Will this help to solve your problem?
SELECT DISTINCT JSON_UNQUOTE(JSON_EXTRACT(`colors` ,
 '$."65"',
 '$."66"',
 '$."67"',
 '$."68"',
 '$."69"'))
FROM color;


text:
Q: Decay overlaid with function I am trying to plot decay (1/r, 1/r^2 and 1/r^3) with my functions figure
My issue is that the decay lines are not near the function plots so it's difficult to see which decay line fits which function. I would like the decay lines to overlay the function.
I have tried subtracting a number from the 1/x function to shift it down but that did not work.
#load data from matlab
mat = loadmat('model01.mat')

#unpack data from matlab, one distance and velocities in 4 different directions
dist = mat['Dist_A_mm01']
distar = np.array(dist)
vpos = mat['Model_Posterior01_m']
vposar = np.array(vpos)
vant = mat['Model_Anterior01_m']
vantar = np.array(vant)
vleft = mat['Model_Left01_m']
vleftar = np.array(vleft)
vright = mat['Model_Right01_m']
vrightar = np.array(vright)

# transpose data

distar = np.transpose(distar)
vposar = np.transpose(vposar)
vantar = np.transpose(vantar)
vleftar = np.transpose(vleftar)
vrightar = np.transpose(vrightar)

#select numbers from array to plot (number in place 0 is 0 which gives an error when dividing by zero later)

dd = distar[1:50]

#plot the data from matlab in a log log graph

ax = plt.axes()
plt.loglog(distar,vposar)
plt.loglog(distar,vantar)
plt.loglog(distar,vleftar)
plt.loglog(distar,vrightar)
plt.loglog(dd,1/dd,dd,1/dd**2,dd,1/dd**3)
ax.set_title('Decay away from centroid')
ax.set_ylabel('Velocity in m/s')
ax.set_xlabel('mm')

plt.show()

Here is the mat file I am importing .mat file
I want the decay lines to be overlaid with the data so it's easy to see the decay of each line on the plot.

A: To shift the decay functions you need to multiply them with something smaller than one, not subtract, since log(A * 1 / x^2) = log(A) - 2 * log(x), i.e. by selecting appropriate values for A you can shift them up and down as you please. In practice this would look like this:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1, 10)
y = 1 / x**2
y2 = 0.1 * 1 / x**2

plt.loglog(x, y, label="1/x2")
plt.loglog(x, y2, label="A + 1/x2")
plt.legend()

If these lines are supposed to be just guides to the eye, that should suffice. Otherwise you should probably do a fit to your actual data.


text:
Q: Add more than one custom attribute to same column in the cart I have been trying for hours now to add more than one of the custom attributes from SimpleCarts cart to the same column (like a concatenation). The furthest I can get is below:
I have my cart column set up:
    cartColumns: [
    { attr: "name", label: "Name"},
    { attr: "pouch-one", label: "Content1"}, -- Custom Attribute One --
    { attr: "pouch-one-cost", label: "Content2"}, -- Custom Attribute Two --
    { view: "currency", attr: "price", label: "Price"},
    { view: "decrement", label: false},
    { attr: "quantity", label: "Qty"},
    { view: "increment", label: false},
    { view: "currency", attr: "total", label: "SubTotal" },
    { view: function(item, column){return item.quantity();}, attr: "custom" ,label: "Quantity"},
    { view: "remove", text: "Remove", label: "Remove Line Item"}
],

I am trying to add the above attribute into this column as well:
    { view: function(item, column){return item.pouch-one() + " $" + item.quantity()*item.pouch-one-price;}, attr: "custom" ,label: "Quantity"},

As for the display of the columns in the cart, i would be hiding them anyways with a display of none.
Everytime I have tried, I have only been able to get the default normal fields simpleCart has (ID, Price, Qty and so on) just not any custom Attributes.
Is there a place I should be adding these into as a default field for SimpleCart?
The reason for these fields is the customer wants a breakdown of the main price as it is a grouped product.
Any help would be greatly appreciated. Thank you.


text:
Q: Intent lost on BACK button even if I try startActivityForResult, saveInstanceState in FragmentPagerAdapter I have this navigation schema in my android application:

PrimaryActivity (... ListView onClick - sending <PrimaryUri> via
  intent...) >
  MasterActivity (TabLayout, ViewPager,
  FragmentPageAdapter) >
  FragmentA / FragmentB (...ListView onClick -
  sending <PrimaryUri> + <DetailUri> via intent...) > DetailActivity.

Now when I press BACK button in DetailActivity, MasterActivity gets destroyed and recreated again with new instances of Fragment A and B and Intent data (<PrimaryUri>) is lost.
I tried persisting <PrimaryUri> between Activies by this way:

*

*override onSaveInstanceState / onCreate(Bundle) in MasterActivity, but Bundle was always null even onSaveInstance saves the data

*start DetailActivity with getActivity().startActivityForResult(..., set resultIntent in DetailActivity and call setResult(OK, ResultCode > 0)
and read values in MasterActivity.onActivityResult... But
onActivityResult was never called

*start DetailActivity with startActivityForResult, ...dtto...FragmentB.onActivityResult... But onActivityResult is never
called

*checked manifest for wrong attributes

Now I really appreciate help for question: How to persist <PrimaryUri> in my application? I prefer to use intents and solve this strange behaviour. Some forum discussed errors in FragmentPageAdapter etc... Maybe I will refactor it for use of SharedPreferences if it will be quick solution...
EDIT: Some additional info:
In DetailActivity:
@Override
public void finish() {
    Intent resultIntent = new Intent();
    resultIntent.setData((Uri) getIntent().getParcelableExtra(FragmentB.MY_URI));
    setResult(Activity.RESULT_OK, resultIntent);
    super.finish();
}

In MasterActivity I have:
@Override  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
}

In FragmentB I have:
public void onItemSelected(Uri contentUri) {
    Intent intent = new Intent(getActivity(), DetailActivity.class);
    intent.putExtra(PRIMARY_URI, mUri);...
    startActivityForResult(intent, FragmentB.BACKTAG);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case (FragmentB.BACKTAG): {
            if (resultCode == Activity.RESULT_OK) {
                mUri = data.get...
            }
        }
        break;
    }
}

The strange behavior looks like:

*

*I press BACK button in DetailActivity >

*MasterActivity.onDestroy get called (why there?).. =

*WeakReference to FragmentB is null and new instance is created =

*onActivityResult of MasterActivity or FragmentB is never called.

I think that reason is that onDestroy appears while waiting for onActivityResult. But why it is called and why the MasterActivity isn't fully recreated to catch onActivityResult callback?

A: This was headache, but here I found the solution after 2 days of futile attempts. This has nothing to do with FragmentPageAdapter. I am lucky woman!

A: You were calling startActivityForResult in the fragments yes?
For your onActivityResult in the fragment to be called you first have to handle onActivityResult in the activity. Call the super.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
}

You should then be able to handle it in your fragment's onActivityResult.


text:
Q: How to check parameter is null in where clause in powershell I'm trying to write a PowerShell command but stucked on where clause. What i want to achieve is if parameters are not defined, where clause needs to ignore them. I tried this code but couldn't success.
I have parameters;
Param(
    [parameter(position=0)]
    [String]
        $JobName,
    [parameter(position=1)]
    [String]
        $JobID
)

And where clause which i tried and failed,
$Timerjob = Get-SPTimerJob | where { ($_.Id -eq $JobID) -or ($_.Title -eq $JobName) }

If $JobName or $JobID is null (or both of them), where clause should ignore them
how can i achieve this without writing multiple if clause?

A: Continuing from my comment:
To retrieve all Timer Jobs if both $JobName and $JobID are empty, you will need to add that condition to the Where-Object cmdlet:
$Timerjob = Get-SPTimerJob |Where-Object {
    (!$JobName -and !$JobID) -or ($_.Id -eq $JobID) -or ($_.Title -eq $JobName)
}

This means if both $JobName and $JobID are empty, the condition (!$JobName -and !$JobID) is $True. Any condition with the -or comparison operator won't be able to change that (to $false) causing the whole condition to be true in that matter and all Timer Jobs returned.
In case you would like to make a difference between an empty string filter and a parameter that isn't supplied, you would probably want to do something like this:
$Timerjob = Get-SPTimerJob |Where-Object {
    ($PSBoundParameters.ContainsKey('JobName') -and $PSBoundParameters.ContainsKey('JobID')) -or
    ($_.Id -eq $JobID) -or ($_.Title -eq $JobName)
}

In this case you would e.g. still be able to retrieve Time Jobs with an empty title (-JobName ''), if even possible.


text:
Q: Wait for a function to finish before proceeding to the next function I am a novice web developer, and am currently working on a web scraper project.
This is my code so far:
<?php

include('simple_html_dom.php');

$URLarray = array(); //empty array that stores list of all Video Page URLs

function getLinks()
{ // this function goes to every VidBlock on the page and add the URL to the array
    $html = file_get_html('https://www.myyouporn.com/');

    $outerBlocksArray = $html->find('h2[class="entry-title"]');

    foreach ($outerBlocksArray as $outerBlock) {

        $URLarray[] = $outerBlock->find('a', 0)->href;
    }
}

getLinks();  // WHAT I NEED IS --> THIS FUNCTION TO COMPLETE BEFORE MOVING AHEAD

print_r($URLarray);

?>

I'm using the simple-html-dom-parser library.
How do I make my PHP code to wait for the async function to complete, before moving further with the code.


text:
Q: не хватает yaml в php-fpm Для работы в связке nginx + php-fpm нужен модуль yaml.
Ставил через pecl install yaml. В конце установки вижу:
install ok: channel://pecl.php.net/yaml-1.2.0
configuration option "php_ini" is not set to php.ini location
You should add "extension=yaml.so" to php.ini

Сообщение явно говорит о том что я должен добавить в php.ini.
Я пытался добавить в /etc/php5/fpm/php.ini и перезапустил фмп. Не помогло.
Прошу помощи.

A: обратитесь через nginx к файлу с phpinfo() — в выдаче должны быть упомянуты используемые конфигурационные файлы и пути для поиска файлов:
<?php phpinfo() ?>

убедитесь, что нужный php.ini там упоминается, а файл yaml.so находится в одном из каталогов, где осуществляется поиск файлов.


text:
Q: How does downloads counted in ios Appstore If I re-install an app, will it be counted as a new download in ios Appstore ?? There show an iCloud sign. Is that shows download from my iCloud account ?? I have tried to check different guidelines in itunes and appstore and cannot find any answer. Please help . . . . . Thanks in advance

A: No it will not be counted as a new download, because when you download the app the second time apple uses your appstore account id to keep track of what you have downloaded previously.


text:
Q: Apache2 -> Tomcat Virtual Host I'm trying to set up an issue tracker on my server, running apache2.  However, the issue tracker (youtrack) runs in tomcat, so I am trying to set up a virtual host that will redirect to the tomcat server. This is what I've got:
#Tomcat
<VirtualHost *:80>
    ServerName issues.example.ca
    ServerAlias issues.example.*

    ProxyRequests Off
    <Proxy *>
        Order deny,allow
        Allow from all
    </Proxy>

    ProxyPass / http://www.example.com:8080/youtrack/
    ProxyPassReverse / http://www.example.com:8080/youtrack/
    ProxyPreserveHost On
    ProxyStatus On
    <Location />
        Order allow,deny
        Allow from all
    </Location>

    ErrorLog logs/issues.example.ca-error_log
    CustomLog logs/issues.example.ca-access_log common

</VirtualHost>

Now, I can see the youtrack login page, but without their CSS applied, and I can't log in. I poked around in the source and it turns out that it looks for all its resources in /youtrack which obviously doesnt exist because that means it would be looking in http://example.com:8080/youtrack/youtrack. How would I go about getting rid of this second youtrack path?  I have tried a rewrite, but I can't quite seem to get it right. Any help would be appreciated. Thanks!
EDIT: I maanged to do a rewrite like this:
RewriteRule ^.*/youtrack/(.*)$ /$1 [P,L]

And the site works, but now the problem is that the url reads issues.example.com/youtrack/stuff and I would like it to be issues.example.com/stuff. Any ideas?

A: You need to change URI on the server where YouTrack run from /youtrack to /.
This is only way to achieve what you need.
Then, replace
"ProxyPass / http://www.example.com:8080/youtrack/"
with
"ProxyPass / http://www.example.com:8080/"
etc...

A: In past, we use modjk to bridge Apache and Tomcat.
I didn't work on this configuration for years, so that maybe there are some newer method.


text:
Q: Should I use DisplayNameFor method in C# mvc or avoid it? In a View auto generated, I could see a couple of lines like:

        @Html.DisplayNameFor(model => model.RestarauntName)

I thought of writing something like this:

@{

                 @typeof(Tutorial.Models.RestarauntReview).GetProperty("RestarauntName").Name

        }

and it worked too!
So my guess is that the DisplayNameFor() method uses reflection to find the name of the corresponding property.
Here's something I break my head off.

*

*What is the cost of using reflection ?

*For smaller views that we want to be rendered quicky can we just type the name of the property ? (hardcoding ?)

A:
So my guess is that the DisplayNameFor() method uses reflection

Not directly, I suspect. It's more likely that is uses ModelMetaData (which no doubt uses reflection eventually if you follow the trail).

For smaller views that we want to be rendered quicky can we just type the name of the property ?

You can. It might be ok for a fairly small and unchanging project but I wouldn't necessarily recommend it.

What is the cost of using reflection ?

I think you'll find it to be insignificant for most purposes. It's one of those cases in which it's not a concern unless it becomes a concern (duck, recursion!).
The greater concern is: Is reflection the best way to achieve my goal? I think that's the question you should be asking. Reflection is great fun (I know) but it's also a bit hard to read and can be hard to debug. That's why it's probably best to avoid it if there is an alternative. In this case there is: ModelMetaData.
What I mean by that is: do try to use HTML Helpers, and if they don't quite do what you want then try to extend them and create your own. Try to fall in love with Display Templates and Editor Templates and use them in conjunction with ModelMetaData.
The problem with using reflection in the Razor View is that you're putting the wrong things in the view. Views should be stupid - meaning they shouldn't have any logic in them or really be 'doing much' of anything. You just pass the views data and they'll display it for you.
I asked the (slightly related) question Are HTML helpers worth using with complex markup? which you might find interesting.


text:
Q: What is the diffrence between canvas and form in j2me? Suppose you have one application and you are going to develop a game why choose canvas?
what can we do and what can we not do with form?Why Mobile games developed On canvas ????

A: Canvas is low level API.It is used for gaming,graphical process etc.It allows key events,etc
Form is high level API.It contains item like TextField,ImageItem,etc.

A: Canvas lets an application draw screens using the low-level user-interface API, and also receive key and pointer events directly. The shortcoming of Canvas is that it gives the application no control over when a canvas repaints itself - all it can do is request a repaint - or over how quickly key and pointer events get delivered to the canvas. This lack of control can cause action games and others that are speed-sensitive to feel sluggish and unresponsive. GameCanvas was designed specifically to fix these weak points.
Form is higher level API. Form contains an arbitrary mixture of items like choice group, command, text field, text, list and etc.
For more info see this articles,
GUI components based J2ME Applications.
J2ME Canvas sample to show games programming in J2ME.
Getting Started With the MIDP 2.0 Game API.


text:
Q: UISearchBar frame making x hard to press I have a UISearchBar in my UINavigationBar that also has a button in it. When you click the search field the button gets a bit larger to accommodate text and the search field gets smaller to make space for it.
Although this looks perfect as far as visual UI is concerned the x to clear the search field is almost unclickable.
I am setting the frame by doing
self.navigationController.navigationBar.bounds;

every time the size is meant to change. What should I use instead so that the search bar's x is clickable?
Cheers for any help

A: Well simple solution, I should be setting the bounds rather than the frame


text:
Q: How to create a filter that returns a forbidden result I want to create a web api filter that checks if the request header has the correct Api key.
If it doesn't, I want to return 403 response code and halt execution (forbidden action)
public class ApiPermission : ActionFilterAttribute
{
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

        }
}

Using the filterContext I know I can do something like:
filterContext.Result = new RedirectTo...

But how can I change the status code to 403 and just return a string and halt execution and stop processing other filters and the controller action?

A: If you don't want to throw an exception, you can instead return an HttpStatusCodeResult
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    if (filterContext.Result != null) return;   //Another filter has already returned a result so pass it on

    //Do your filtering

    filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Forbidden");
}

A: Looks like posted answers not Asp.Net Core 2.1 compatible. In core you can do something like that
filterContext.Result = new  ObjectResult(actionContext.ModelState)
{
    Value = null,
    StatusCode = StatusCodes.Status403Forbidden
};

Or maybe it'll be convenient to create class like BadRequest, but for 403 Code.
public class ForbiddenObjectResult : ObjectResult
{
    public ForbiddenObjectResult(object value)
            : base(value)
    {
        StatusCode = StatusCodes.Status403Forbidden;
    }
}

...

filterContext.Result = new ForbiddenObjectResult(filterContext.ModelState);

A: You can throw a HttpException which lets you pass any HTTP code and will halt execution (because its an exception)
throw new HttpException(403, "Forbidden");

Or look at Returning HTTP 403 in a WebAPI method which creates an ErrorResponse.
You may also want to consider moving this into an AuthorizationFilterAttribute, because you are checking the user's API Key to authorize them to perform the action.

A: In .NET core (I'm using 3.0), you can make sure code does not subsequently reach the controller action by using the following in the action filter:
 filterContext.Result = new StatusCodeResult(StatusCodes.Status403Forbidden);

A: Or you can return:
filterContext.Result = new ForbidResult();

A: you can throw HttpException :
 throw new HttpException(403, "Forbidden");

For more details, please visit ; http://msdn.microsoft.com/fr-fr/library/system.web.httpexception(v=vs.110).aspx


text:
Q: Remove Everyone Permissions and add Authenticate Users permissions to Net Share folders I have written a script to remove the Everyone permission and add the Authenticated Users permissions for the Net share.
But my script is removing it and adding the Authenticated Users, but it is only performing the action for the Root folders, not for the subfolder inside the root folder and I need to get that permission as an Inherited form parent.
And I just want to know like my script is excluding the shares which for ('Remote Admin' ,"Default share' , 'Remote IPC' , 'Printer Drivers'")
It would be great if someone can please help me achieve this...
$ScriptBlock = {
     "Executing on {0}" -f $env:COMPUTERNAME
     $ExclusionList = 'ADMIN\$','IPC\$' -join '|'
     $Shares = Get-SmbShare  | Where-Object -Property Name -notmatch $ExclusionList | Where-Object -Property Path -notmatch '^\w:\\$'
     "Analyzing these shares...."
     $Shares
     foreach ($Share in $Shares) {
         $Everyone = Get-SmbShareAccess $Share.Name | Where-Object -Property AccountName -eq Everyone
         if ($Everyone) {
             Revoke-SmbShareAccess $Share.Name -AccountName 'Everyone' -Force
             Grant-SmbShareAccess $Share.Name -AccountName 'Authenticated Users' -AccessRight FullControl -Force
             "Share {0} has been updated." -f $Share.Name
         }
     }
     "Complete"
 }

  $ComputerList = Get-Content "C:\users\a-lchandrakanthredd\Desktop\Test\Servers.txt"

  Invoke-Command -ComputerName $ComputerList -ScriptBlock $ScriptBlock

Thanks In Advance


text:
Q: Qt: Missing objects when loading from file using overloaded I/O operators and QDatastream I've created a list application as seen in this screenshot

I have a problem with the save/load functions. The text from the headers (QLineEdit) both gets saved and loaded normally. But when I try to save and load rows under the headers (user-defined class named "Row"), the QString from the QLineEdit-object loads with no characters.
I've checked that all stored elements are still there when i output them to the QDataStream and that only the QString belonging to QLineEdit-object of the Row-object is empty when It's supposed to input from the QDataStream at loading.
The headers is created when the program starts and the Row-objects is created when the user hits the add-button (the +-icon at the top) and are stored in private QList listOfRows.
// mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QObject>
#include <QFile>
#include <QLabel>
#include <QMessageBox>
#include "row.h"

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void on_actionNew_Row_triggered();
    void on_actionDelete_Rows_triggered();
    void on_actionSelect_All_triggered();
    void on_actionSave_triggered();
    void on_actionLoad_triggered();

    void on_actionShortcuts_triggered();

private:
    Ui::MainWindow *ui;
    QList<Row*> listOfRows;
    void AddHeaderRow();

    QLineEdit* headerOne;
    QLineEdit* headerTwo;
    QLineEdit* headerThree;
    QCheckBox* deleteAllSelect;
    QLabel* select;
};
#endif // MAINWINDOW_H

-
// mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "row.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    AddHeaderRow();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_actionNew_Row_triggered()
{
    // new row
    Row* newRow = new Row(this, listOfRows.size());
    listOfRows.push_back(newRow);
}

void MainWindow::on_actionDelete_Rows_triggered()
{
    // delete row
    if(listOfRows.size() != 0)
    {
        for(auto row : listOfRows)
        {
            if(row->isToDelete())
            {
                row->hide();
                listOfRows.removeOne(row);
            }
        }

        for(int i = 0; i < listOfRows.size(); i++)
        {
            listOfRows[i]->reAlign(i);
        }
    }
}

void MainWindow::on_actionSelect_All_triggered()
{
    if(deleteAllSelect->checkState())
    {
        for(auto row : listOfRows)
        {
            row->setStateCheckBoxDelete(true);
        }
    }else
    {
        for(auto row : listOfRows)
        {
            row->setStateCheckBoxDelete(false);
        }
    }
}

void MainWindow::AddHeaderRow()
{
    this->headerOne = new QLineEdit;
    this->headerTwo = new QLineEdit;
    this->headerThree = new QLineEdit;
    this->deleteAllSelect = new QCheckBox;
    this->select = new QLabel("Select");

    ui->horizontalLayout->addWidget(headerOne, 2, Qt::AlignHCenter);
    ui->horizontalLayout->addWidget(headerTwo, 2, Qt::AlignHCenter);
    ui->horizontalLayout->addWidget(headerThree, 3);
    ui->horizontalLayout->addWidget(select, 1, Qt::AlignHCenter);
}

void MainWindow::on_actionSave_triggered()
{
    QMessageBox msgBox;
    msgBox.setIcon(QMessageBox::Question);
    msgBox.setWindowIcon(MainWindow::windowIcon());
    msgBox.setWindowTitle("Save");
    msgBox.setText("Do you want to save your changes?");
    msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Cancel);
    msgBox.setDefaultButton(QMessageBox::Save);
    int ret = msgBox.exec();

    if(ret == QMessageBox::Save)
    {
        QString path = "rows.bin";
        QFile file(path);

        if (file.open(QIODevice::WriteOnly))
        {
            qDebug() << "File opened!";
            QDataStream out(&file);
            out << this->headerOne->text() << this->headerTwo->text() << this->headerThree->text();
            for(auto row : listOfRows)
            {
                out << row;
            }
            file.close();
        }
    }
}

void MainWindow::on_actionLoad_triggered()
{
    QString path = "rows.bin";
    QFile file(path);
    if(file.exists())
    {
      if (file.open(QIODevice::ReadOnly))
      {
         QDataStream in(&file);
         QString textOne;
         QString textTwo;
         QString textThree;
         in >> textOne >> textTwo >> textThree;
         this->headerOne->setText(textOne);
         this->headerTwo->setText(textTwo);
         this->headerThree->setText(textThree);
         while(!in.atEnd())
         {
             Row* tempRow = new Row(this);
             in >> tempRow;
             listOfRows.push_back(tempRow);
             qDebug() << "To file: " << tempRow->checkStateOne() << tempRow->checkStateTwo() << tempRow->textFromBox();
         }
         file.close();
         }
    }
}

void MainWindow::on_actionShortcuts_triggered()
{
    QMessageBox shortcuts;
    shortcuts.setWindowTitle("Shortcuts");
    shortcuts.setIcon(QMessageBox::Information);
    shortcuts.setWindowIcon(MainWindow::windowIcon());
    shortcuts.setText("New Row - Ctrl + N\n"
                      "Delete Selected - Ctrl + D\n"
                      "Save - Ctrl + S\n"
                      "Load - Ctrl + L\n");
    shortcuts.exec();
}

-
    // row.h
    #ifndef ROW_H
    #define ROW_H

    #include <QFrame>
    #include <QPainter>
    #include <QCheckBox>
    #include <QLineEdit>
    #include <QList>
    #include <QDebug>
    #include <QHBoxLayout>
    #include <QDataStream>

    class Row : public QFrame
    {
    Q_OBJECT

    static const int containerHeight = 40;

    public:
        Row(QWidget* parent = nullptr, int yPos = 0);
        ~Row() override;
        bool isToDelete() const;
        void reAlign(int);
        void setStateCheckBoxDelete(bool);
        bool checkStateOne() const;
        bool checkStateTwo() const;
        QString textFromBox() const;
        void setCheckStateOne(bool);
        void setCheckStateTwo(bool);
        void setTextToBox(QString);

    private:
        QWidget* parent;
        QCheckBox* checkBoxOne;
        QCheckBox* checkBoxTwo;
        QLineEdit* textBox;
        QCheckBox* checkBoxDelete;
    };

    QDataStream& operator<<(QDataStream&, Row&);
    QDataStream& operator>>(QDataStream&, Row*);

    #endif // ROW_H

-

// row.cpp
#include "row.h"

Row::Row(QWidget* parent, int yPos) : QFrame(parent)
{
    QHBoxLayout* layout = new QHBoxLayout();

    checkBoxOne = new QCheckBox(this);
    checkBoxTwo = new QCheckBox(this);
    textBox = new QLineEdit(this);
    checkBoxDelete = new QCheckBox(this);

    layout->addWidget(checkBoxOne, 2, Qt::Alignment(Qt::AlignHCenter));
    layout->addWidget(checkBoxTwo, 2, Qt::Alignment(Qt::AlignHCenter));
    layout->addWidget(textBox, 3);
    layout->addWidget(checkBoxDelete, 1, Qt::Alignment(Qt::AlignHCenter));

    this->parent = parent;
    this->setLayout(layout);
    this->resize(parent->size().width(), containerHeight);
    this->move(0, 50 + containerHeight * (1 + yPos));

    this->show();
}

Row::~Row()
{
    this->parent = nullptr;
    delete parent;
    delete checkBoxOne;
    delete checkBoxTwo;
    delete textBox;
    delete checkBoxDelete;
}

bool Row::isToDelete() const
{
    return checkBoxDelete->checkState();
}

void Row::reAlign(int yPos)
{
    this->move(0, 50 + containerHeight * (1 + yPos));
}

void Row::setStateCheckBoxDelete(bool check)
{
    this->checkBoxDelete->setCheckState(Qt::CheckState(check));
}

bool Row::checkStateOne() const
{
    return checkBoxOne->checkState();
}

bool Row::checkStateTwo() const
{
    return checkBoxTwo->checkState();
}

QString Row::textFromBox() const
{
    return textBox->text();
}

void Row::setCheckStateOne(bool check)
{
    this->checkBoxOne->setCheckState(Qt::CheckState(check));
}

void Row::setCheckStateTwo(bool check)
{
    this->checkBoxTwo->setCheckState(Qt::CheckState(check));
}

void Row::setTextToBox(QString text)
{
    this->textBox->setText(text);
}

QDataStream& operator<<(QDataStream& out, Row& row)
{
    out << row.checkStateOne();
    out << row.checkStateTwo();
    out << row.textFromBox();

    return out;
}

QDataStream& operator>>(QDataStream& in, Row* row)
{
    bool checkOne;
    bool checkTwo;
    QString text;
    in >> checkOne;
    in >> checkTwo;
    in >> text;

    row->setCheckStateOne(checkOne);
    row->setCheckStateTwo(checkTwo);
    row->setTextToBox(text);

    return in;
}

-
// main.cpp
#include "mainwindow.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

-
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>801</width>
    <height>600</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Monika's Awesome Widget</string>
  </property>
  <property name="windowIcon">
   <iconset>
    <normaloff>../MoniquesUnique/Icons/noun_Elephant_5119.svg</normaloff>../MoniquesUnique/Icons/noun_Elephant_5119.svg</iconset>
  </property>
  <widget class="QWidget" name="centralwidget">
   <widget class="QWidget" name="layoutWidget">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>0</y>
      <width>781</width>
      <height>31</height>
     </rect>
    </property>
    <layout class="QHBoxLayout" name="horizontalLayout"/>
   </widget>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>801</width>
     <height>26</height>
    </rect>
   </property>
   <widget class="QMenu" name="menuFile">
    <property name="title">
     <string>File</string>
    </property>
    <addaction name="actionSave"/>
    <addaction name="actionLoad"/>
   </widget>
   <widget class="QMenu" name="menuEdit">
    <property name="title">
     <string>Edit</string>
    </property>
    <addaction name="actionNew_Row"/>
    <addaction name="actionDelete_Rows"/>
   </widget>
   <widget class="QMenu" name="menuHelp">
    <property name="title">
     <string>Help</string>
    </property>
    <addaction name="actionShortcuts"/>
   </widget>
   <addaction name="menuFile"/>
   <addaction name="menuEdit"/>
   <addaction name="menuHelp"/>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
  <widget class="QToolBar" name="toolBar">
   <property name="windowTitle">
    <string>toolBar</string>
   </property>
   <attribute name="toolBarArea">
    <enum>TopToolBarArea</enum>
   </attribute>
   <attribute name="toolBarBreak">
    <bool>false</bool>
   </attribute>
   <addaction name="actionNew_Row"/>
   <addaction name="actionDelete_Rows"/>
   <addaction name="actionSave"/>
   <addaction name="actionLoad"/>
  </widget>
  <action name="actionNew_Row">
   <property name="icon">
    <iconset>
     <normaloff>../MoniquesUnique/Icons/plus-circle.svg</normaloff>../MoniquesUnique/Icons/plus-circle.svg</iconset>
   </property>
   <property name="text">
    <string>New Row</string>
   </property>
   <property name="shortcut">
    <string>Ctrl+N</string>
   </property>
  </action>
  <action name="actionDelete_Rows">
   <property name="icon">
    <iconset>
     <normaloff>../MoniquesUnique/Icons/delete.svg</normaloff>../MoniquesUnique/Icons/delete.svg</iconset>
   </property>
   <property name="text">
    <string>Delete Selected</string>
   </property>
   <property name="shortcut">
    <string>Ctrl+D</string>
   </property>
  </action>
  <action name="actionSave">
   <property name="icon">
    <iconset>
     <normaloff>../MoniquesUnique/Icons/save.svg</normaloff>../MoniquesUnique/Icons/save.svg</iconset>
   </property>
   <property name="text">
    <string>Save</string>
   </property>
   <property name="shortcut">
    <string>Ctrl+S</string>
   </property>
  </action>
  <action name="actionLoad">
   <property name="icon">
    <iconset>
     <normaloff>../MoniquesUnique/Icons/briefcase.svg</normaloff>../MoniquesUnique/Icons/briefcase.svg</iconset>
   </property>
   <property name="text">
    <string>Load</string>
   </property>
   <property name="shortcut">
    <string>Ctrl+L</string>
   </property>
  </action>
  <action name="actionShortcuts">
   <property name="icon">
    <iconset>
     <normaloff>../MoniquesUnique/Icons/info.svg</normaloff>../MoniquesUnique/Icons/info.svg</iconset>
   </property>
   <property name="text">
    <string>Shortcuts</string>
   </property>
  </action>
 </widget>
 <resources/>
 <connections/>
</ui>

A: You have to dereference your Row pointers while saving, because your << operator accepts a reference, not a pointer:
QDataStream& operator<<(QDataStream&, Row&); // also it would be better to accept "const Row&"

Edit inside void MainWindow::on_actionSave_triggered():
for(auto row : listOfRows)
{
    out << *row; // dereferenced here
}

and also seems your need to remove all existing rows while loading. Edit inside void MainWindow::on_actionLoad_triggered():
listOfRows.clear();

while (!in.atEnd())
{
    Row* tempRow = new Row(this, listOfRows.size());
    in >> tempRow;
    listOfRows.push_back(tempRow);

    qDebug() << "FROM file: " << tempRow->checkStateOne() << tempRow->checkStateTwo() << tempRow->textFromBox(); // Here was a typo: FROM file, not TO
}

Please also note:

*

*Your checkboxes are tri-state checkboxes, therefore may be you need to use setTristate(false) or save/load them as int, not as bool QCheckBox::setCheckState()

*May be you need to use some non-binary file for such data, for example XML or json

*See serialization libraries to facilitate and automate saving/loading structures & classes, such as cereal


text:
Q: eunit: How to test a simple process? I'm currently writing a test for a module that runs in a simple process started with spawn_link(?MODULE, init, [self()]).
In my eunit tests, I have a setup and teardown function defined and a set of test generators.
all_tests_test_() ->
    {inorder, {
        foreach,
        fun setup/0,
        fun teardown/1,
        [
            fun my_test/1
        ]}
    }.

The setup fun creates the process-under-test:
setup() ->
    {ok, Pid} = protocol:start_link(),
    process_flag(trap_exit,true),
    error_logger:info_msg("[~p] Setting up process ~p~n", [self(), Pid]),
    Pid.

The test looks like this:
my_test(Pid) ->
    [ fun() ->
            error_logger:info_msg("[~p] Sending to ~p~n", [self(), Pid]),
            Pid ! something,
            receive
                Msg -> ?assertMatch(expected_result, Msg)
            after
                500 -> ?assert(false)
            end
        end ].

Most of my modules are gen_server but for this I figured it'll be easier without all gen_server boilerplate code...
The output from the test looks like this:
=INFO REPORT==== 31-Mar-2014::21:20:12 ===
[<0.117.0>] Setting up process <0.122.0>

=INFO REPORT==== 31-Mar-2014::21:20:12 ===
[<0.124.0>] Sending to <0.122.0>

=INFO REPORT==== 31-Mar-2014::21:20:12 ===
[<0.122.0>] Sending expected_result to <0.117.0>
protocol_test: my_test...*failed*
in function protocol_test:'-my_test/1-fun-0-'/0 (test/protocol_test.erl, line 37)
**error:{assertion_failed,[{module,protocol_test},
                   {line,37},
                   {expression,"false"},
                   {expected,true},
                   {value,false}]}

From the Pids you can see that whatever process was running setup (117) was not the same that was running the test case (124). The process under test however is the same (122). This results in a failing test case because the receive never gets the message und runs into the timeout.
Is that the expected behaviour that a new process gets spawned by eunit to run the test case?
An generally, is there a better way to test a process or other asynchronous behaviour (like casts)? Or would you suggest to always use gen_server to have a synchronous interface?
Thanks!
[EDIT]
To clarify, how protocol knows about the process, this is the start_link/0 fun:
start_link() ->
    Pid = spawn_link(?MODULE, init, [self()]),
    {ok, Pid}.

The protocol ist tightly linked to the caller. If the either of them crashes I want the other one to die as well. I know I could use gen_server and supervisors and actually it did that in parts of the application, but for this module, I thought it was a bit over the top.

A: did you try:
all_tests_test_() ->
    {inorder, {
        foreach,
        local,
        fun setup/0,
        fun teardown/1,
        [
            fun my_test/1
        ]}
    }.

From the doc, it seems to be what you need.

A: simple solution
Just like in Pascal answer, adding the local flag to test description might solve some your problem, but it will probably cause you some additional problems in future, especially when you link yourself to created process.
testing processes
General practice in Erlang is that while process abstraction is crucial for writing (designing and thinking about) programs, it is not something that you would expose to user of your code (even if it is you). Instead expecting someone to send you message with proper data, you wrap it in function call
get_me_some_expected_result(Pid) ->
    Pid ! something,
    receive
         Msg ->
              Msg
    after 500
         timeouted
    end

and then test this function rather than receiving something "by hand".
To distinguish real timeout from received timeouted atom, one can use some pattern matching, and let it fail in case of error
get_me_some_expected_result(Pid) ->
    Pid ! something,
    receive
         Msg ->
              {ok, Msg}
    after 500
         timeouted
    end

in_my_test() ->
    {ok, ValueToBeTested} = get_me_some_expected_result().

In addition, since your process could receive many different messages in meantime, you can make sure that you receive what you think you receive with little pattern-matching and local reference
get_me_some_expected_result(Pid) ->
    Ref = make_ref(),
    Pid ! {something, Ref},
    receive
         {Ref, Msg} ->
              {ok, Msg}
    after 500
         timeouted
    end

And now receive will ignore (leave for leter) all messages that will not have same Reg that you send to your process.
major concern
One thing that I do not really understand, is how does process you are testing know where to send back received message?  Only logical solution would be getting pid of it's creator during initialization (call to self/0 inside protocol:start_link/0 function). But then our new process can communicate only with it's creator, which might not be something you expect, and which is not how tests are run.
So simplest solution would be sending "return address" with each call; which again could be done in our wrapping function.
get_me_some_expected_result(Pid) ->
    Ref = make_ref(),
    Pid ! {something, Ref, self()},
    receive
         {Ref, Msg} ->
              {ok, Msg}
    after 500
         timeouted
    end

Again, anyone who will use this get_me_some_expected_result/1 function will not have to worry about message passing, and testing such functions makes thing extremely easier.
Hope this helps at least a little.

A: Maybe it's simply because you are using the foreach EUnit fixture in place of the setup one.
There, try the setup fixture: the one that uses {setup, Setup, Cleanup, Tests} instead of {inorder, {foreach, …}}


text:
Q: NFA of language $1^*(001^*)^*$ My textbook has a problem -

Find NFA of language $1^*(001^*)^*$.

I have following question-
Suppose A is a language with regular expression $(001^*)^*$. Then will each occurrence of the expression within brackets has to be same? In other word, will $00100$ be accepted by A? (here first occurrence of $001^*$ is $001$, and second occurrence of $001^*$ is $00$).

A: Your language consists of all the words of the form $1^{n_0}001^{n_1} 001^{n_2}\dotsm 001^{n_k}$, where $n_0, n_1, \ldots, n_k$ are non-negative integers (possibly equal to $0$) and $k \geqslant 0$.
Hint. Show that your language is actually equal to $(00 + 1)^*$. Then prove it is accepted by an (incomplete) two-state deterministic automaton.


text:
Q: Remove "Continue Reading" Link From the Teaser Excerpt Only I want to remove the "Continue Reading" link from the teaser excerpt only and not from the automatic excerpt, which filter is easily available.
This is the original code; it's from the Showcase Template Page Template:
    <?php while ( have_posts() ) : the_post(); ?>

<?php
    if ( '' != get_the_content() )
        get_template_part( 'content', 'intro' );
?>

<?php endwhile; ?>

Here is the Intro:

    <?php the_content(); ?>
    <?php wp_link_pages( array( 'before' => '
' . __( 'Pages:', 'mytheme' ) . '', 'after' => '
' ) ); ?>
    <?php edit_post_link( __( 'Edit', 'mytheme' ), '', '' ); ?>

 -->

A: Change standard text for all excerpts:
function custom_excerpt_more($more) {
   global $post;
   $more_text = '...';
   return '… ID) . '">' . $more_text . '';
}
add_filter('excerpt_more', 'custom_excerpt_more');

Create your own excerpt function:
// Rafael Marques Excerpt Function ;)
function rm_excerpt($limit = null, $separator = null) {

    // Set standard words limit
    if (is_null($limit)){
        $excerpt = explode(' ', get_the_excerpt(), '15');
    } else {
        $excerpt = explode(' ', get_the_excerpt(), $limit);
    }

    // Set standard separator
    if (is_null($separator)){
        $separator = '...';
    }

    // Excerpt Generator
    if (count($excerpt)>=$limit) {
        array_pop($excerpt);
        $excerpt = implode(" ",$excerpt).$separator;
    } else {
        $excerpt = implode(" ",$excerpt);
    }
    $excerpt = preg_replace('`\[[^\]]*\]`','',$excerpt);
    echo $excerpt;
}

Use <?php rm_excerpt(); ?> when you want display custom excerpt. First value set words limit and second value set separator. Example: <?php rm_excerpt(10,' (...)'); ?>. To create separate link "read more", insert <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">Read More?

A: add_filter( 'the_content_more_link', 'wpsites_read_more_link' );
function wpsites_read_more_link() {
return '';
}

Add this to your functions file and it will remove the more link.
http://codex.wordpress.org/Customizing_the_Read_More

A: It sounds like you want to remove the "Continue Reading" teaser from the_content(). If so, this example from the Codex would be what you need:

Read More Techniques
The parameters within the template tag the_content() are as follows:
<?php the_content( $more_link_text , $strip_teaser ); ?>
The $more_link_text sets the link text like "Read More". The second
  one, $strip_teaser, sets whether or not the "more" link should be
  hidden (TRUE) or displayed (FALSE). The default is FALSE, which shows
  the link text.
To remove the teaser:
Change the_content(); in your index.php to (i.e., the second parameter controls this):
`the_content('',TRUE,'');`

Include  in the post text, immediately after the .

UPDATE
Based on your code, it looks like you have added the code in the wrong place. Without seeing your files, you probably need to go to content.php and look for the_content() and make the change there. I checked it on one of my themes that uses templates and it works fine. You should also read up more on templates, so you understand how they function. In short:
1 - Remove this text from your code:  if ( '' != get_the_content('',TRUE,'') )
2 - Go to content.php in your theme and find the_content() and change it to the_content('',TRUE,'')
3 - Add  as indicated above
This is if you are using  to manually setup the excerpts.

A: //.... get_the_content() .....//

Just edit this part like this: get_the_content("")
With this "" you will make content empty. So just you would have your content text without read more link :-)

A: I had to go into the wp-includes folder, inside the formatting.php file and edit line 3284 and change the default number of words to include in the excerpt to a huge number like so:
    $excerpt_length = apply_filters( 'excerpt_length', 550000000000000 );

The default is only 55


text:
Q: Redirecting to external page from django class based view I'm trying to redirect users based on the referer in the request header. Basically, if the referer is say https://www.google.com, I would like to send them to a page, not on my website. Otherwise, continue processing as usual.
Here is what I have so far
class ArticleAccess(TemplateView, SomeMixin):
    http_method_names = ['get']
    template_name = 'template.html'

    def dispatch(self, request, *args, **kwargs):
        return super(ArticleAccess, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):

        context = super(ArticleAccess, self).get_context_data(**kwargs)
        item = get_object_or_404(ClientItem.objects.using(self.get_site().name), id=kwargs['article_id'])

        if self.request.META.get('HTTP_REFERER') == 'https://www.google.com/':
            return redirect(item.item_url)

        context['id'] = item.id
        context['name'] = item.name
        context['html'] = item.description
        context['item_url'] = item.item_url

        return context

This just stays on the same page instead of redirecting. I have also tried HttpResponseRedirect, but to no avail

A: alecxe is correct.. you'd have to redirect from a method that is expected to return an HttpResponse.
get_context_data is not expected to return an HttpResponse and isn't ever returned by the view. It's always used to get a data dict to populate say a template. No matter what you return from this method, it will never override the response.
Therefore wherever you write this override, it needs to be in a place that is expected to return a response, such as get, post, dispatch.
The problem now is to determine how to get your object outside of the get_context_data method.

A: For debugging, I recommend you to start by just using a plain redirect('some_view') without conditions on your dispatch method so you can check if redirection is hit as expected and only then, go for conditions and anything else. @Yuji-tomita-tomita is just right! :) Django-pdb and ipdb are very nice tools.


text:
Q: Does LDAP (or any Ruby client library for LDAP) support batch calls? I'm thinking no, but hope to be corrected.
http://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol
i.e. i'm simply looking to a batch read of ~1000 users via one query, instead of making ~1000 separate queries.
Update:
Okay, it helps to read the spec:
https://www.rfc-editor.org/rfc/rfc2254
: )

A: Why batch?
(|(cn=user1)(cn=user2)(cn=user3)(cn=user4)(cn=user5)(cn=user6))

The LDAP filter string length can be looked at as unlimited for nearly all practical purposes.


text:
Q: Inequality for Stirling numbers of the second kind I stumbled upon the following inequality which, I believe, is true. I was able to prove it for small k, but I have no proof for the general case. Any help is welcome.

Let $n\geq k\geq 1$ then
$$\left(1+\frac{1}{n}\right)^k\cdot S(n+1,k+1)\,\ \geq
    \,\ \left(1+\frac{1}{k}\right)^n\cdot S(n,k)$$
where $S(n,k)$ is a Stirling number of second kind.

A: Let me prove a weaker inequality, the proof of which allows further improvements. Note that $S(n,k)=h_{n-k}(1,2,\dots,k)$, where $$h_t(x_1,\dots,x_k)=\sum_{a_1+\dots+a_k=t,a_i\geqslant 0} x_1^{a_1}\dots x_k^{a_k}$$ is a complete symmetric polynomial. Thus $$\frac{S(n+1,k+1)}{S(n,k)}=\frac{h_{n-k}(1,2,\dots,k+1)}{h_{n-k}(1,2,\dots,k)}=\frac{\sum(p_1+1)\dots (p_{n-k}+1)}{\sum p_1\dots p_{n-k}},$$
where summation is taken over $0\leqslant p_1\leqslant p_2\leqslant \dots \leqslant p_{n-k}\leqslant k$. For any such $(n-k)$-tuple we have
$$(p_1+1)\dots (p_{n-k}+1)\geqslant \left(1+\frac1k\right)^{n-k}p_1\dots p_{n-k},$$
summing up we get $$S(n+1,k+1)\geqslant \left(1+\frac1k\right)^{n-k} S(n,k),$$
this is worse than you need, but the inequality was not sharp enough. Roughly speaking, you need to prove that "in average" the ratio $(1+1/p_1)\dots (1+1/p_{n-k})$ grows as $(1+2/k)^{n-k}$, that corresponds to "average" $p_i\sim k/2$.


text:
Q: Width and height of tagged segments of photos in facebook-graph API I am trying to extract the tagged segments of my friend's facebook photos to train a facial recognition algorithm. Although https://developers.facebook.com/docs/reference/api/photo/ describes the x and y position of the tag in a photo, I don't know how to retrieve the width and height of the rectangle that appears when you hover over a face in a facebook photo. Is it possible to find out the width and height of the tagged face in the photo?

A: I was faced with the same situation. What I did was whip up a quick script in python and opencv2 for detecting faces using HAAR Cascades. This gives us rectangles aroud the detected faces. Since the x and y parameters of the tag represent the center of the tag, we look for the face-rectangle which surrounds the tag position. If multiple such rectangles are overlapping we could chose the one whose center is the closest to the tag position.

A: To my knowledge, grabbing the height and width of a tag box is not possible via the Facebook API.


text:
Q: What do you call someone who hates people with mental disabilities? What do you call someone who is hateful, discriminatory and bigoted against people with mental illness and further stigmatizes them by calling those with mental disabilities nutcases, psychos, freaks, mental, and all the rest?

A: Such people are called Ableists. What they practice is called ableism.
Definition of ableism is :

discrimination or prejudice against individuals with disabilities

Source : http://www.merriam-webster.com/dictionary/ableism

A: Mental illness has a long history of being sorely stigmatized, yet the terms for discrimination because of perceived mental illness are all comparatively new and poorly established.
One of the more exact terms in use is difficult to track with, for example, Google Ngrams, because of pre-existing but conflicting or simply discordant uses: 'mentalism' and the corresponding 'mentalist' are in contemporary use, but the words have a history of nonce uses, dating from the 1600s, and established uses, dating from the 1800s, that tend to militate against contemporary adoption of the 'mentalism/mentalist' terms for the purpose of naming the discrimination and discriminators against those with mental health problems.
Of the other terms I was able to discover, 'sanism' and the corresponding 'sanist' have the most exact denotation and the most currency for the given meaning. 'Sanism' does not appear in the OED Online, nor does the word appear in any of the dictionaries referenced at The Free Dictionary, but it does appear in the more agile online dictionaries. For example,

Discrimination and oppression against people who have, or who are labelled or perceived as having, a mental illness.

(From Wiktionary)
This term is also discussed in the current entry for 'mentalism' at Wikipedia:

While mentalism and sanism are used interchangeably, sanism is becoming predominant in certain circles, such as academics, those who identify as mad and mad advocates and in a socio-political context where sanism is gaining ground as a movement.1 The movement of sanism is an act of resistance among those who identify as mad, consumer survivors, and mental health advocates.2 In academia evidence of this movement can be found in the number of recent publications about sanism and social work practice.3

*

*Mad Matters: A Critical Reader in Canadian Mad Studies. Chapter 6: "Breaking open the bone": Storying, Sanism, and Mad Grief, Jennifer M. Poole and Jennifer Ward. Editors B. LeFrancois, R. Menzies and G. Reaume. Toronto: Canadian Scholars Press, 2013.

*Poole & Ward, 2013; Poole, 2011; Poole et al. 2012.

*Poole, 2011; Poole et al., 2012; Poole & Ward, 2013.

Another extant term is 'ableist', a generic term denoting discrimination against people with disabilities. It lacks specificity, but may be generally useful:

Discrimination in favour of able-bodied people; prejudice against or disregard of the needs of disabled people.

["ableism, n.". OED Online. December 2015. Oxford University Press. http://www.oed.com/view/Entry/240190?redirectedFrom=ableism (accessed December 09, 2015).]
The OED Online, which, generally speaking, has (lexicographical) reflexes like bread dough, gives quotes for the term 'ableist' dating from 1981. 'Sanism', on the other hand, is tracked in the current Wikipedia entry through a secondary source to its earlier coinage in the 1960s for a legal case:

The term "sanism" was coined by Morton Birnbaum during his work representing Edward Stephens, a mental health patient, in a legal case in the 1960s.4 Birnbaum was a physician, lawyer and mental health advocate who helped establish a constitutional right to treatment for psychiatric patients along with safeguards against involuntary commitment.

*"Sanism in Theory and Practice", May 9/10, 2011. Richard Ingram, Centre for the Study of Gender, Social Inequities and Mental Health. Simon Fraser University, Canada.

The foregoing considerations suggest that, for specific uses, 'sanism' has the most contemporary acceptance and might be the best choice overall for a term denoting 'discrimination against people with mental disabilities'.

A: A eugenist is an advocate of eugenic measures.

"eugenic" is a set of beliefs and practices that aims at
  improving the genetic quality of the human population. It is
  considered to be a violation of basic human rights, because eugenists
  are/were determined to wipe away all human beings deemed "unfit,"
  preserving only those who conformed to a "non disabled" stereotype.

However, "eugenist" is not exactly the hate of disabled people. It is the feeling that their number shall be reduced by all means, from sterilization to euthanasia.


text:
Q: Rewarded Video Ads - setting amount and type of reward I implemented showing rewarded video according to this guide. When a reward video ad has triggered a reward then onRewarded(RewardItem reward) is called.
Where and how I can set the information about the reward that RewardItem contains (the amount of credit and the type the credit) ?

A: Just to share what I've found. Reward amount and reward item can be set during creation of a rewarded video ad unit. Here are instructions on how to create such ad unit and more information about rewarded video ad units.


text:
Q: HTML File Input Angularjs Select same File only fires ones I've made a Angular directive to warp the a file upload input.
directive('ngFile', function () {
    return {
        link: function (scope, element, attrs) {
            var button = element.find('button[data-fileInputButton]');
            var inputElement = element.find('input[type="file"]');

            var updateModel = function (evt) {
                scope.$apply(function () {
                    scope.files = evt.target.files;
                    if (scope.startUpload) {
                        scope.startUpload();
                    }

                    evtl.target.files = [];
                });
            }

            inputElement.bind('change', updateModel);

            button.click(function () {
                var input = element.find('input[type="file"]');
                input.click();
            });
        }
    }
});

When I click and select a file, everything is OK. However, when I select the file again, the event is not fired. It is only fired when I select another file. Why is this happening?

A: The change is listening to the value and not to the files.
you need to do:
evt.target.value = "";

Good luck :)


text:
Q: Error installing tables via pip I'm tying to install tables as follows (I have no sudo permissions):
pip install --user tables

And I get the following error:
Command /usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-build-pWg1M_/tables/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-mOibUT-record/install-record.txt --single-version-externally-managed --compile --user failed with error code 1 in /tmp/pip-build-pWg1M_/tables Storing debug log for failure in /home/hudson/pg/fkgm22/.pip/pip.log

I can install other packages with this method, but not tables... any idea?
Thanks

A: You can check the log pip has mentioned at /home/hudson/pg/fkgm22/.pip/pip.log to see what went wrong. I guess you will get a much more detailed error message which you can try to analyse.


text:
Q: Why local changes would be overwritten by merge? I have next local changes:
diff --git a/lib/Art.pm b/lib/Art.pm
index c8fd249..4bd479f 100644
--- a/lib/Art.pm
+++ b/lib/Art.pm
@@ -61,6 +61,7 @@ sub startup {

     $self->hook( around_action  =>  \&Art::Controller::_log_request        );
+    $self->hook( around_action  =>  \&Art::Controller::_store_referral     );
     $self->hook( around_action  =>  \&Art::Controller::_json_as_urlencoded );
     $self->hook( after_dispatch =>  \&Art::Controller::_mail_exception     );
     # NOTICE: before_render is called even before rendering included template

And has next changes in the stash:
diff --git a/lib/Art.pm b/lib/Art.pm
index 0dde0ec..cff11c9 100644
--- a/lib/Art.pm
+++ b/lib/Art.pm
@@ -32,6 +32,7 @@ sub startup {
     push @{ $self->plugins->namespaces }, __PACKAGE__ .'::Plugin';
     $self->plugin( Config =>  { file => 'conf/' .$self->moniker .'.conf' } );
     $self->plugin( 'TagHelpers::FetchPanel' );
+    $self->plugin( 'UserReferral',  key => 'r' );

     # default_page is used in redirections. Redirect to site root by default

As you can see these changes are not overlap.
Why I get this error when try to apply this stash?
error: Your local changes to the following files would be overwritten by merge:
    lib/Art.pm

Is there a way to apply this patch without this error?

A:
Is there a way to apply this patch without this error?

You are getting this error because, as the error message says, you have local changes to the file lib/Art.pm which would be overwritten by the merge.  So, the first thing you should do is commit your local changes via:
git add lib/Art.pm
# and commit any other work you want
git commit -m 'local changes to Art.pm'

After this, you can apply the stash via:
git stash apply

Note that you still may get merge conflicts here.  If you do, it just means that Git was being cautious and did not want to assume which final version of Art.pm it should use.  In the event of conflicts, this file would be peppered with conflict markers looking like <<<< and ====.  Resolve the conflicts, and make another commit to finish applying the stash.


text:
Q: How to use my PC Chrome as a mobile chrome permanently? I use the Chrome in my laptop with Windows 7 OS, and the Chrome on Windows provides a Device Mode(shortcut is F12) so that it can simulate a specific mobile device to get and display a Web page in a Chrome tab as follow.

However, such Device Mode is only limited on a single Chrome tab, so when you close the tab and open a new one, the new tab get and show the web page as normal, not as in the Device Mode.
So my question is How to set the Device Mode permanently, and when I open a new tab in the Chrome, it runs on Device Mode by default. Is there any method or plug-in can help me to achieve it?

A: I believe that this is not applicable as Google created that mode for inspection purposes only not for navigating or viewing.
So you will need a smartphone simulator like the one which is provided by Android SDK or the IOS simulator which comes with XCODE on mac, or you can use a real smartphone of course, and you can inspect on it via your PC using ADOBE Edge Inspect extension on chrome.

A: Chrome inspector mode is designed with testing in mind, and isn't intended for regular browser use. You might try a device simulator tool, like what's included in Xcode or Eclipse IDE.
Hope this helps.

A: I think this is something what you are looking for
Google chrome plugin

A: You can open devtool automatically with chrome switches, so i suppose that you can reach your goal with the correct one... our only problem is that chrome's switches are thousands... that's the documentation, good reading :D (unofficial documentation here)


text:
Q: How to Understand Code on zyBooks Ch. 4 Program: Drawing a half arrow This program outputs a downwards facing arrow composed of a rectangle and a right triangle. The arrow dimensions are defined by user specified arrow base height, arrow base width, and arrow head width.
(1) Modify the given program to use a loop to output an arrow base of height arrowBaseHeight. (1 pt)
(2) Modify the given program to use a loop to output an arrow base of width arrowBaseWidth. Use a nested loop in which the inner loop draws the *'s, and the outer loop iterates a number of times equal to the height of the arrow base. (1 pt)
(3) Modify the given program to use a loop to output an arrow head of width arrowHeadWidth. Use a nested loop in which the inner loop draws the *'s, and the outer loop iterates a number of times equal to the height of the arrow head. (2 pts)
(4) Modify the given program to only accept an arrow head width that is larger than the arrow base width. Use a loop to continue prompting the user for an arrow head width until the value is larger than the arrow base width. (1 pt)
These are what it is wanting to me to do i just dont understand here is the code it starts with
#include <stdio.h>

int main(void) {
    int arrowBaseHeight;
    int arrowBaseWidth;
    int arrowHeadWidth;

    printf("Enter arrow base height:\n");
    scanf("%d", &arrowBaseHeight);

    printf("Enter arrow base width:\n");
    scanf("%d", &arrowBaseWidth);

    printf("Enter arrow head width:\n");
    scanf("%d", &arrowHeadWidth);
    printf("\n");

    // Draw arrow base (height = 3, width = 2)
    printf( "**\n");
    printf( "**\n");
    printf( "**\n");

    // Draw arrow head (width = 4)
    printf( "****\n");
    printf( "***\n");
    printf( "**\n");
    printf( "*\n");

    return 0;
}

What Zybooks wants it too look like minus the blue

A: print ('Enter arrow base height:')
arrow_base_height = int(input())

print ('Enter arrow base width:')
arrow_base_width = int(input())

print ('Enter arrow head width:')
arrow_head_width = int(input())

while arrow_head_width <= arrow_base_width:
    print ('Enter arrow head width:')
    arrow_head_width = int(input())
print('')

for base_height in range(arrow_base_height):
  for base_width in range(arrow_base_width):
    print('*', end='')
  print('')

for head_width in range(arrow_head_width):
  for head in range(arrow_head_width - head_width):
    print('*', end='')
  print('')


text:
Q: Is each Javascript function of a webpage supposed to be defined in its own separate .js file? I'm creating a website as a personal project to learn my way around the DOM and javascript. After several hours of annoyance, I discovered that if I comment out a portion of my HTML ("Animated Landing Page" in the HTML below) that has a javascript function (the btnEnter.addEventListener sequence in the JS) tied to it, anything after that function in my .js file ceases to work (such as the test.addEventListener sequence in the JS). Am I supposed to be separating my javascript functions into their own individual files? At the moment, I want to stick with javascript solutions, as I'd like to grasp the details of javascript before moving on to jQuery. I've included my HTML and JS below:
HTML
<!DOCTYPE html>

<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>My Webpage</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<link rel="stylesheet" type="text/css" href="MyStyle.css">

    <button id="entry-btn">Enter</button>

Banner

Home

Page 1

Page 2

Page 3

HOME

PAGE1

PAGE2

PAGE3

JS
var btnEnter = document.getElementById("entry-btn");
var test = document.getElementById("link1");

btnEnter.addEventListener("click", coverFadeOut);

test.addEventListener("click", testFunc);

function coverFadeOut() {
    var coverimg = document.getElementById("cover-image");
    coverimg.classList.toggle("fadeout");
    coverimg.addEventListener("transitionend", setTimeout(coverHide, 1000), false);
}

function coverHide() {
    var coverimg = document.getElementById("cover-image");
    coverimg.classList.toggle("hide");
}

function testFunc(){
    alert("Test");
}

To clarify, I'm asking why my testFunc is not working when I comment out the HTML section "Animated Landing Page"?

A: When you select an element you need to make sure it's not undefined before doing something with it. Your javascript will break if you try to access a method or property on undefined (in this case the method addEventListener).
var btnEnter = document.getElementById("entry-btn");
var test = document.getElementById("link1");

if (btnEnter) {
    btnEnter.addEventListener("click", coverFadeOut);
}

if (test) {
    test.addEventListener("click", testFunc);
}

A: Welcome to the Wonderful World of JavaScript!
I'd suggest hitting F12 in your browser and taking advantage of your browser's console and developer tools. They'll show you any exceptions that occur when your code runs. In your case, commenting out that button will cause one: by removing entry-btn from your page's markup, the code that adds an event listener to it will fail as document.getElementById("entry-btn") will return null.
var btnEnter = document.getElementById("entry-btn"); // Uh oh! This is gone! document.getElementById returns null.
btnEnter.addEventListener("click", coverFadeOut);    // btnEnter is null. I can't add a listener to it!

There's no need to add each function to a separate file. You just have to make sure that you're debugging while you're trying things out. (Incidentally, when it comes to grouping related files and functionality, you'd want to give the JavaScript Module Pattern or ES2015 modules a Google; they're the preferred way of keeping related pieces of code together).

A: The short answer is no, it's not necessary to separate each js function into different files, but for big applications it is convenient, it favour code reuse, testing, etc
This is broad topic and depends greatly on team conventions, best practices and design patterns.
For example, the way I see it, javascript functions must be separated following concepts souch as encapsulation and abstraction, i.e: modules should have only one reason of change and must handle specific responsibilities.
You can decide to separate your functions into modules (aka: separate js files) following this concept. So for example, you can have a navigation file handling all functions specific to navigation, and other modules abstracting another aspects of functionality.
Hope it helped!


text:
Q: Value based Page split in a SSRS Report with Multiple Tablixes I have a SSRS Report which have multiple tablixes as shown below

This report is having multi-value parameters.  the output of this report is shown as below

Now I need to do a page split on this report based column value loan_id. Records with Loan_ID 1 come in the first page, Records with loan_id 2 come in 2nd page of the report...etc. As below
expected output :

To do this,  I have added a Rowgroup on both tablixes with value loan_id.  Then In pagesplit properties of group I ticked 'split using each instance of group'
But when the Report runs I didn't get the desired result. i got output as below
First page of the report

Tablix 1 data ends here and Tablix 2 begins in 4 th page

I figured out the issue because ssrs processing first tablix entirely  then start with next tablix. But I need both of the tablixes processing at the same time.
Pls help...

A: You can set the PageBreak to occur based on an expression. In your row group properties set the BreakLocation to End. Set the Disabled property to an expression like this:
    =IIf(Fields!loan_id.Value = Previous(Fields!loan_id.Value), True, False)

In other words, you will get a page break each time an loan ID is different than the previous one.


text:
Q: How to apply multi classes to an element/ combine conditional static classes I want to apply multiple css classes to one element. How do I do it? One conditional and one static.
  <p
    class={current === 'overview' ? 'selected' : '' // here I want to add another class named foo}
    on:click={() => (current = 'overview')}
  >

A: To make life easier you can use the class: directive
<p class="foo" class:selected={current === 'overview'}>

A: Separate by whitespace according to HTML standard class="{current === 'overview' ? 'selected' : ''} foo"


text:
Q: Firebase won't send push notifications to all live iOS app users Perhaps a silly questions, but here it goes.
We are using Firebase to send out our notifications for an iOS app. When we send notifications, it appears that not all live, iOS app users are receiving the notifications.
We have targeted all users who has installed the app, but it appears that minorities aren't receiving the notification.
The notification works are all development phones without any issues.
Has anyone else experienced this and if so, why are some live iOS app users not receiving our notification sends?

A: Basically if your development devices are receiving the PN's then you are using development Push certificates from your Push Notification Server. You need to have your production ones installed in order to send. You also have to ship production ones with the app. Very easy to get them from Apples developer site and install them just the same as the dev ones.
Otherwise like I said in the comments get very familiar with TN2265