text:
Q: When iterating an NSMutableArray, how to delete one object then insert multiple objects? For example, if we have an instance of NSMutableArray, with 10 objects in it. When iterating over it, we found that we have to delete object a[2] and a[8], and then insert 3 objects at a[2] and 4 objects at a[8] continuously, how to do that at lowest time cost?
Any idea will be thankful!

A: Edit :  As @trojanfoe pointed out, it's nice to add that you should never edit an array while iterating it. This is true for many collection classes in many different languages; not just NSMutableArray & Objective-C. Doing so can easily leads to out-of-bounds index.

For your question, let's do it in two iteration.
First, we want to save the indexes we want to delete, so we will iterate on the sourceArray.
NSMutableArray * indexesToRemove = [NSMutableArray array];

[sourceArray enumerateObjectsUsingBlock:^(NSNumber * obj, NSUInteger idx, BOOL * _Nonnull stop) {
    if (obj.integerValue%2 == 1) {
        // Insert at first position
        [indexesToRemove insertObject:@(idx) atIndex:0];
    }
}];

It's important to save the index in an array and not a set, since you want to insert objects later. Also, add the new items at the beginning of the array is important, so you will iterate from the biggest index to the smallest, and will not have to shift the indexes according to the previously added items.
Now, you can, in a new iteration (this time on the index array), delete the items and add the new ones according to the indexes you saved :
[indexesToRemove enumerateObjectsUsingBlock:^(NSNumber * obj, NSUInteger idx, BOOL * _Nonnull stop) {

    NSUInteger indexToRemove = obj.unsignedIntegerValue;

    // Delete the item from the source array
    [sourceArray removeObjectAtIndex:indexToRemove];

    // Create the items you want to insert, do whatever you want in this method :]
    NSArray * itemsToAdd = [self generateElementsToAddAtIndex:indexToRemove];

    // Create the indexSet according to the start index and the number of objects you want to insert
    NSIndexSet * indexSet = [NSMutableIndexSet indexSetWithIndexesInRange:NSMakeRange(indexToRemove, itemsToAdd.count)];

    // Insert the objects
    [sourceArray insertObjects:itemsToAdd atIndexes:indexSet];
}];

A: [myMutableArray replaceObjectAtIndex:2 withObject:"5"];
will it work ?

A: First you have to delete object then use below line of code to insert multiple objects:
NSMutableOrderedSet *orderedSet = [[NSMutableOrderedSet alloc] init];
[orderedSet insertObjects:@[@"Eezy", @"Tutorials"] atIndexes:
                       [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, 2)]];
NSLog(@"Result: %@", orderedSet);

Refer below reference link:
http://ios.eezytutorials.com/nsmutableorderedset-by-example.php#.VwIJIhN95fg

A: For such a small array and so many operations, I consider replacing the array with a new one a good option - for performance as well as clarity.


text:
Q: How to specify a value for each bit of the reg in Verilog? I want to declare a reg of 8 bits and set the value for each one of the bits separately (based on another "counter" reg) inside an always block using Verilog.
Here is what I thought:
module readvalue (
    button_1,
    button_2,
    value,
    counter);

    input button_1;
    input button_2;
    output value;
    output counter;
    reg [7:0] value;
    reg [7:0] counter = 8'd0;
    always@(posedge button_1 or posedge button_2)
    begin
        if(button_1)
        begin
            [counter]value <= 1'b0;
            counter <= counter + 8'd1;
        end
        else if(button_2)
        begin
            [counter]value <= 1'b1;
            counter <= counter + 8'd1;
        end
    end
endmodule

The idea behind the code is that when button_1 is pressed, 1 is stored in a particular bit of value and when button_2 is pressed, 0 is stored. I have a higher module in the hierarchy to make readvalue stop when counter is equal to 8 in decimal.
The code, as expected, gives me the following errors:
Error (10170): Verilog HDL syntax error at calculator.v(17) near text: "[";  expecting "end". Check for and fix any syntax errors that appear immediately before or at the specified keyword. The Intel FPGA Knowledge Database contains many articles with specific details on how to resolve this error. Visit the Knowledge Database at https://www.altera.com/support/support-resources/knowledge-base/search.html and search for this specific error message number.

Error (10170): Verilog HDL syntax error at calculator.v(22) near text: "[";  expecting "end". Check for and fix any syntax errors that appear immediately before or at the specified keyword. The Intel FPGA Knowledge Database contains many articles with specific details on how to resolve this error. Visit the Knowledge Database at https://www.altera.com/support/support-resources/knowledge-base/search.html and search for this specific error message number.

How can we put it to work?
I am using Intel's Quartus Premium Lite Edition 18.1 (with the latest update pack) on Ubuntu 18.04 with the default configuration. If I have not been clear or you need more information, just comment and I will provide.
I am a beginner on Verilog so, sorry for such a simple doubt.
EDIT 1: button_1 and button_2 are never going to have a posedge at the same time (or even in the same second) in my implementation.

A: First, you need to put the index after the register name, like
value[counter]

not
[counter]value

However, I'm not sure if using a variable as an index into a register will be simulable and synthesizable.
If not, you could use something like
always@(posedge button_1 or posedge button_2)
    begin
        if(button_1)
        begin
            value <= value & ~(8'b1 << counter);
            counter <= counter + 8'd1;
        end
        else if(button_2)
        begin
            value <= value | (8'b1 << counter);
            counter <= counter + 8'd1;
        end
    end

However you should also be aware that this is likely not synthesizable because you are trying to make logic that is edge-sensitive to two different signals and if you consider all the subtleties, the actual logic in your FPGA or CPLD doesn't do that. You can probably make an SR latch, but that doesn't work exactly like your code because it will behave differently if, for example, button_1 is still asserted when the rising edge of button_2 arrives.
The usual way to code these things for an FPGA is to have a clock available that runs much faster than you expect button_1 and button_2 events to arrive, and use that to clock logic that detects edges on the input signals and responds to them.
For example (sorry, code not tested),
reg b1d; b2d; // delayed button signals

always @(posedge clk) begin
    b1d <= button_1;   // Notice: non-blocking assignment
    b2d <= button_2;
    if (button_1 & ~b1d) begin
        // A rising edge on button 1 happened
        // ...
    end
    else if (button_2 & ~b2d) begin
        // ...
    end
end

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trouble with Parent/Child in OpenGL I am currently using C code in Codeblocks for OpenGL and I am having trouble making objects operating independently. In my case I have separate fingers and each one seems to be reliant on the previous finger coding and I cannot seem to figure out why exactly. I think I have gone wrong with my Push and Pop but not sure where. Any help would be appreciated.
This is the important part of the code
glClear (GL_COLOR_BUFFER_BIT);
glPushMatrix();

glTranslatef(-1.0, 0.0, 0.0);
glRotatef((GLfloat) shoulder, 0.0, 0.0, 1.0);
glTranslatef(1.0, 0.0, 0.0);
glPushMatrix();
glScalef(2.0, 0.4, 1.0);
glutWireCube(1.0);
glPopMatrix();

glTranslatef(1.0, 0.0, 0.0);
glRotatef((GLfloat) elbow, 1.0, 0.0, 1.0);
glTranslatef(1.0, 0.0, 0.0);
glPushMatrix();
glScalef(2.0, 0.4, 1.0);
glutWireCube(1.0);
glPopMatrix();

glTranslatef (1.0, 0.0, 0.0);
glRotatef ((GLfloat) finger, 0.0, 0.0, 1.0);
glTranslatef (0.25, 0.0, 0.0);
glPushMatrix();
glScalef(0.5, 0.1, 0.1);
glutSolidCube(1.0);
glPopMatrix();

glTranslatef (0.25, 0.0, 0.0);
glRotatef ((GLfloat) fingerjoint, 0.0, 0.0, 1.0);
glTranslatef (0.25, 0.0, 0.0);
glPushMatrix();
glScalef(0.5, 0.1, 0.1);
glutSolidCube(1.0);
glPopMatrix();

//need to make finger2 not reliant on fingerjoint
glTranslatef (-0.75, 0.0, 0.0);
glRotatef ((GLfloat) finger2, 0.0, 0.0, 1.0);
glTranslatef (0.25, 0.0, 0.25);
glPushMatrix();
glScalef(0.5, 0.1, 0.1);
glutWireCube(1.0);
glPopMatrix();

glTranslatef (0.25, 0.0, 0.0);
glRotatef ((GLfloat) finger2joint, 0.0, 0.0, 1.0);
glTranslatef (0.25, 0.0, 0.0);
glPushMatrix();
glScalef(0.5, 0.1, 0.1);
glutWireCube(1.0);
glPopMatrix();

//need to make finger3 not reliant on previous fingerjoints
glTranslatef (-0.75, 0.0, 0.0);
glRotatef ((GLfloat) finger3, 0.0, 0.0, 1.0);
glTranslatef (0.25, 0.0, -0.5);
glPushMatrix();
glScalef(0.5, 0.1, 0.1);
glutWireCube(1.0);
glPopMatrix();

glTranslatef (0.25, 0.0, 0.0);
glRotatef ((GLfloat) finger3joint, 0.0, 0.0, 1.0);
glTranslatef (0.25, 0.0, 0.0);
glPushMatrix();
glScalef(0.5, 0.1, 0.1);
glutWireCube(1.0);
glPopMatrix();

glPopMatrix();
glutSwapBuffers();


text:
Q: GenericDTO and JSF I am currently reading Adam Bien´s book "Java EE Patterns: Rethinking Best Practices".
In chapter "Transfer Object and Data Transfer Object" on page 273 he introduces a generic DTO.
See also: http://www.adam-bien.com/roller/abien/entry/no_duplication_no_decoupling_the
A genericDTO does not follow the bean conventions.
I was wondering how to use generic DTO together with JSF.
JSF if not dynamically used (build components on the flight) makes use of java-beans to bind values to UI-Components (for example #{beanA.beanB.myValue}).
A genric DTO does not provide individual getters for attributes or relations.
Instead i would have to call getters with a string parameter.
So accessing it via #{beanA.beanB.myValue} is not possible in JSF (1.2).
Is it possbile to use the genric DTO pattern together with JSF?
Regards,
Max

A: I have not read the entirety of Adam's article, so can not comment on when using this pattern is appropriate. However, EL-expressions do support maps with the . or [] operators, i.e. if you have:
@Named
public class MyBean {
    private Map<String, Object> attributes;

    public Map<String, Object> getAttributes() {
        return attributes;
    }
}

you can use
#{myBean.attributes.name}

or
#{myBean.attributes['name']}

to get or set the map entry with key "name".


text:
Q: Cronbach's alpha vs. Average Item-Sum correlation? I have heard that Cronbach's alpha is used to measure reliability of a test (to check if a set of items/question are measuring the same construct). How does the Cronbach's alpha compare with the average of Item-Sum correlation or the Item-(Sum minus Item) correlation of all the items?
I have a set of testing items and I am interested in understanding if they are measuring different concepts/constructs or are measuring the same construct.

A: The standardized alpha coefficient is more intuitive so let's start there:
$$\alpha_{standardized}=\frac{K\bar{r}}{1+(K-1)\bar{r}}$$
where $K$ is the number of items and $\bar{r}$ is the mean of the non-redundant correlations between items.
The non-standardized alpha coefficient just needs a few changes to the denominator.
$$\alpha=\frac{K\bar{c}}{\bar{v}+(K-1)\bar{c}}$$
where $K$ is the number of items, $\bar{v}$ is the average variance of each item, and $\bar{c}$ is the mean of the non-redundant covariances between  items.
Here is some sample data in subject-by-item format (with four items A, B, C, and D):

A   B   C   D
-------------
5   5   5   5
3   1   3   1
5   5   5   5
3   1   3   1
5   5   4   5
1   2   3   3
3   1   1   1
1   1   1   3
3   3   4   4
1   3   1   1
5   5   5   5
1   1   1   1
1   1   1   1
1   1   1   1
3   3   4   3
1   3   3   4
4   4   5   5
5   5   5   5
5   3   3   3
3   2   3   3
5   3   5   5
3   3   3   4
1   1   1   1
1   1   1   1
1   1   3   3
3   3   3   1
3   3   1   1
3   3   1   1
3   3   2   5

To calculate the standardized alpha, we need the inter-item correlations ($r$):
$r_{AB}=.776$
$r_{AC}=.756$
$r_{AD}=.630$
$r_{BC}=.730$
$r_{BD}=.750$
$r_{CD}=.810$
Which makes for a mean inter-item correlation of $\bar{r}=.742$.
$$\alpha_{standardized}=\frac{4(.742)}{1+(4-1).742}=.920$$
To calculate alpha, we need the variances ($v$) and covariances ($c$):
$v_A=2.433$
$v_B=2.101$
$v_C=2.384$
$v_D=2.933$
$c_{AB}=1.754$
$c_{AC}=1.820$
$c_{AD}=1.683$
$c_{BC}=1.633$
$c_{BD}=1.861$
$c_{CD}=2.142$
which makes for a mean variance of $\bar{v}=2.463$ and mean covariance of $\bar{c}=1.816$.
$$\alpha=\frac{4(1.816)}{2.463+(4-1)1.816}=.918$$
Now let's compare these results to your idea of the average item-sum correlation.
$$S=A+B+C+D$$
$r_{AS}=.877$
$r_{BS}=.901$
$r_{CS}=.919$
$r_{DS}=.895$
which makes for a mean item-sum correlation of $\bar{r}_{XS}=.898$.
So your result is similar to but lower than the alpha coefficient(s). Perhaps someone else who is better at algebra than I am can put together an equation for calculating one from the other.


text:
Q: How to populate an append only long text data type field I use a form to update/insert a database in Access 2016.
I found Access has an option to record version of a field value change if data type of this field is long text and append only property is set to yes. I decided to concat all the values of a single record and save to this long text (history) field.
Now I have added an invisible textbox control to that form. The value of this field i.e. "history"  will be populated when an event occurs (on unload from form current record) and that invisible textbox control value is set running a function.
So now I need to know which event should I address to populate history field?
I tried several events but all say conflict!

A: This seems like a last changed date kind of problem. I have has success with using the form's before update event for this. E.g.:
Private Sub Form_BeforeUpdate(Cancel As Integer)
    With Me
        .LastChangedDate = Now()
    End With
End Sub

If you are having trouble accessing the history from the control you could set a vba variable to it using the Current event of the form. Be careful, the Current Event fires for many reasons and the code has to defend itself from running except when you want.
I frequently test many conditions and switch settings so the Current event does not crash or worse. Trial and error needed.
For example, you could record the key of the record whose history you have saved for later and test to see if it has changed before saving it again. Also, I make sure that initialization of the OPEN and LOAD events are complete along with any other initialization necessary before I allow the Current event to do anything significant.
Good luck.


text:
Q: Opencart customization: server-side script for rating I've added a custom table into the Opencart database, where I have a field/column, called average_rating (value = null to 5).
In my (custom) template (.tpl file) I've added a code to get and show the rating of current record from database.
Here is the code within .tpl file:

  <?php echo $entry_average_rating; ?>

      <input type="hidden" name="average_rating" value="<?php echo $average_rating; ?>" id="input-average_rating" />

        <?php for ($i = 0; $i < $average_rating; $i++) { ?>
          <div class="rating_hover" id="<?php echo 'r' . ($i+1) ?>" title="<?php echo $i+1 ?>" data-toggle="tooltip">

        <?php } ?>

        <?php for ($i = $average_rating; $i <= 4; $i++) { ?>
          <div class="rating_normal" id="<?php echo 'r' . ($i+1) ?>" title="<?php echo $i+1 ?>" data-toggle="tooltip">

        <?php } ?>

For the blue-stars, I use .rating_hover class, for the grey-ones: .rating_normal class (see the picture below).

All this stuff works fine. But now I want to do something I have no experience with and I would appreciate any tip concerning my question.
Question: When a mouse pointer is over a grey star, it must become blue, like the ones before it. And when clicked on a star, my hidden input must get the value of title attribute of the clicked div-element. I wouldn't like to write a client-side Javascript to do this. Could somebody give a tip on how to do this with JSON or AJAX... or somehow please?
I mean: something like this:
$('div[id=\'r*\']').onmouseover({
    // for (i=$average_rating; i<=[current_id]; i++) {
    // ??? document.getElementById('r[i]').style.ClassName = 'someclass';
});

Javascript-alternative works fine, but I still have problems with JSON-script:
This is how javascript works:
Inside every div-element I added following commands:
 <div ... onclick="rOnClick(<?php echo ($i+1) ?>);" onmouseover="rOnMouseOver(<?php echo ($i+1) ?>);" onmouseout="rOnMouseOut(<?php echo ($i+1) ?>);" ... >

And my Javascript functions are now, as follows:

A: Please add another css class 'rating' in all rating divs. Also you will be needed to add a different class 'rated' for existing/clicked rated value. Then add following script:
$('.rating').hover(
     // Handles the mouseover
  function() {
    $(this).prevAll().andSelf().addClass('rating_over');
    $(this).nextAll().removeClass('rating_normal');
   },
    // Handles the mouseout
   function() {
     $(this).prevAll().andSelf().removeClass('ratings_over');
     $('.rated').addClass('ratings_over'); // back to rated one

   }
);

$('.rating').bind('click', function() {
   $('.rating').removeClass('rated');
   $(this).addClass('rated');
   $('#input-average_rating').val($(this).attr('title'));

});


text:
Q: Odoo version 13: Email digests & KPI's I am trying to create a new KPI in the Digests model to show the number of new customers created per week. (Unfortunately, this functionality is not well documented).
As documented, I have created two fields in the digest model:
x_studio_kpi_new_customers (Boolean)
x_studio_kpi_new_customers_value (Integer)
The value is
for record in self:
    start, end, company = record._get_kpi_compute_parameters()
    record.x_studio_kpi_new_customers_value = sum(self.env['res.partner'].search([
            ('x_studio_when', '>=', start),
            ('x_studio_when', '<', end)
    ]).mapped('x_studio_counter'))

x_studio_counter is just the value 1 in all records
x_studio_when is the record creation date (have also tried with a datetime field)
I have also tried the code below:
for record in self:
    start, end, company = record._get_kpi_compute_parameters()
    new_customers = self.env['res.partner'].search_count([('x_studio_when', '>=', start), ('x_studio_when', '<', end)])
    record['x_studio_kpi_new_customers_value'] = new_customers

I keep getting 0.
Any help will be appreciated.

A: In order to build your customized digest, follow these steps:

*

*You may want to add new computed fields with Odoo Studio:
You must create 2 fields on the digest object:

*

*first create a boolean field called kpi_myfield and display it in the KPI's tab;

*then create a computed field called kpi_myfield_value that will compute your customized KPI.
Create below "compute_kpis_actions" method and after that digest mail able to view count.
def compute_kpis_actions(self, company, user):
        res = super(Digest, self).compute_kpis_actions(company, user)
        res['x_studio_kpi_new_customers'] = 'your_module_name.your_action_name&menu_id=%s' % self.env.ref(your_module_name.your_menu_name').id
        return res


text:
Q: Python: scan file for substring, save position, then return to it I'm writing a script that needs to scan a file until it finds the line at which a substring occurs, save the position of the beginning of that line, then return to it later.  I'm very new to python, so I've not had much success yet.  Here is my current code:
with open("test.txt") as f:
pos = 0
line = f.readline()
while line:
    if "That is not dead" in line:
        pos = f.tell() - len(line.encode('utf-8'))
        # pos = f.tell()

    line = f.readline()

f.seek(pos)
str = f.readline()
print(str)

With test.txt:
That is not dead
Which can eternal lie
Till through strange aeons
Even Death may die

Sphinx of black quartz, judge my vow!

Here's the output:
hat is not dead

[newline character]

I realized that my original pos = f.tell() gave me the position of the end of the line rather than the beginning, and I found this answer detailing how to get the byte length of a string, but using this cuts off the first character.  Using utf-16 or utf-16-le gives ValueError: negative seek position -18 or ValueError: negative seek position -16, respectively.  I tried to use the solution from this answer, using this code:
with open("ctest.txt") as f:
pos = 0
line = f.readline()
while line:
    if "That is not dead" in line:
        print(line)
        f.seek(-len(line), 1)
        zz = f.readline()
        print(zz)
    line = f.readline()

f.seek(pos)
str = f.readline()
print(str)

which gives io.UnsupportedOperation: can't do nonzero cur-relative seeks at f.seek(-len(line), 1)
Can someone please point out where I'm going wrong?

A: Stefan Papp suggested saving the position before the line was read, a simple solution that I failed to consider.  An adjusted version:
with open("test.txt") as f:
pos = 0
tempPos = 0
line = f.readline()
while line:
    if "That is not" in line:
        pos = tempPos

    tempPos = f.tell()
    line = f.readline()

f.seek(pos)
str = f.readline()
print(str)

With the correct output:
That is not dead
[newline character]

Thanks, Stefan.  I guess I was too deep into my issue to think clearly about it.
If there's a better way to iterate through the file than what I've done, I'd be interested to know, but this seems to work.


text:
Q: Numerical integration of $\int_0^{2\pi}\frac{dx}{3+\sin x}$ We know that numerical integration using end points is first order, trapezoid and mid-piont rules second order, and Simpson's rule fourth order. However, with $\int_0^{2\pi}\frac{dx}{3+\sin x}$, we have the following errors:
n   Left point              Right point             Trapezoid               Mid-point               Simpson
1   2.02200572599407E-2     2.02200572599406E-2     2.02200572599406E-2     2.02200572599407E-2     2.02200572599407E-2
2   2.02200572599407E-2     2.02200572599406E-2     2.02200572599406E-2     -2.14466094067260E-2    -7.55772051783715E-3
3   1.80370579205280E-5     1.80370579205280E-5     1.80370579205280E-5     1.80370579205280E-5     1.80370579204725E-5
4   -6.13276073392621E-4    -6.13276073392621E-4    -6.13276073392621E-4    6.12214122685750E-4     2.03717390659608E-4
5   1.56304432175070E-8     1.56304432175070E-8     1.56304432175070E-8     1.56304432175070E-8     1.56304432175070E-8
6   1.80370579205280E-5     1.80370579205280E-5     1.80370579205280E-5     -1.80379781545281E-5    -6.01296612956492E-6
7   1.35448319227294E-11    1.35448319227294E-11    1.35448319227294E-11    1.35449429450318E-11    1.35449429450318E-11
8   -5.30975353407737E-7    -5.30975353463248E-7    -5.30975353407737E-7    5.30974556545161E-7     1.76991253264536E-7
9   1.20459198171829E-14    1.19904086659517E-14    1.20459198171829E-14    1.19904086659517E-14    1.20459198171829E-14
10  1.56304431619958E-8     1.56304431619958E-8     1.56304431619958E-8     -1.56304434395516E-8    -5.21014786869500E-9

Simpson is surprised. Why are the end points over-performing? Another interesting fact is that the errors are not converging steadily but rather in an oscillating manner. Is there any explanation for this?


text:
Q: How to unpack an array into different arguments on method call I would like to know if it is possible to unpack an Object array into separate Object on method call which accepts vargs. This question is similar to this one.
I have a code like:
public class Test {
    public static Object doWork(Object... objects){
        System.out.println(objects.length);
        return objects;
    }

    public static void main(String[] args){
        Object res = doWork("one", "two");
        res = doWork("three", res);
    }
}

I would like to unpack the res object in the second call so it would receive an object array with length 3 instead of length 2 as now (where the second position is an Object array of length 2, having then all three arguments).
Is even that possible in Java?

More detailed:
By doing
Object res = doWork("one", "two");
res = doWork("three", res);

the second call gets called as:
doWork( Object[ "three", Object[ "one", "two" ] ] )

where i would like:
doWork(Object[ "one", "two", "three" ] )

I know this can be achieved by doing:
public static void main(String[] args){
res = doWork("one", "two");
    List<Object> los = Arrays.asList(res);
    los = new ArrayList<>(los);     // Can't modify an underlying array
    los.add("three");
    res = doWork(los.toArray());
}

But I'm looking for something like the unpack Lua built in function or the Python way described in the previously mentioned SO question.

Both answers given by @chancea and @Cyrille-ka are good and also solve the problem. One of the facts that might be a good idea to take into account is if the signature of the method can be modified.
@cyrille-ka answer respects the function's signature, whereas @chancea does not. However I think in most cases one can just write asimple wrapper function to another one, so that shouldn't be a problem.
On the other hand @chancea's way might be easier to use while programing (there no possible mistake of forgetting to call the unpack function).

A: Well, there is no syntactic sugar à la Python or Lua for that in Java, but you can create your own unpack method:
@SafeVarargs
public static <E> Object[] unpack(E... objects) {
    List<Object> list = new ArrayList<Object>();
    for (Object object : objects) {
        if (object instanceof Object[]) {
            list.addAll(Arrays.asList((Object[]) object));
        }
        else{
            list.add(object);
        }
    }

    return list.toArray(new Object[list.size()]);
}

This will returns an array containing all the input elements, unpacked.
Then you can call it in your main method:
res = doWork(unpack("three", res));

The reason I make this method generic is that you can call it with, for example, a String[] array, without generating a warning. For some reason, the Java compiler thinks that this method has a chance of "polluting the heap", but it is not the case, that's why I added a @SafeVarargs annotation.

A: This does not implement the Unpack solution, instead it goes about it by making an overload method as I said in my comment.  I do not know if this at all what you wanted, but I got it to work and I felt like I would post this for reference.
public class Test {
    public static Object doWork(Object... objects){
        System.out.println(objects.length);
        return objects;
    }

    // this is the method that will concatenate the arrays for you
    public static Object doWork(Object[] objects1, Object... objects2){
        System.out.println(objects1.length + "+" + objects2.length);
        Object[] retval = new Object[objects1.length+objects2.length];
        System.arraycopy(objects1, 0, retval, 0, objects1.length);
        System.arraycopy(objects2, 0, retval, objects1.length, objects2.length);
        return retval;
    }

    public static void main(String[] args){
        Object res = doWork("one", "two");
        res = doWork((Object[])res, "three");
        Object[] res2 = (Object[])res; // = {one, two, three}
    }
}

A: Try to return as an array of Object instead. Then concatenate "three" at the end of the returned array.


text:
Q: SSH remote takes too much time to connect My local is Windows 10 and host is Linux (AWS EMR).
Using key based authentication.
I need to connect to linux machine for my dev work. Every time I connect to remote, it looks like it setups the VS Code Server everytime and it takes a lot of time each time I connect.
How can I prevent VS Code to setup itself each time I connect?
what it shows when connecting to remote
Thanks in advance!

A: I figured out something. It was a .ssh/config file issue on host system.
I reverted it to vanilla (bare minimum configs) and it was smooth after that.


text:
Q: Php length of cyrillic string doubles its value Hello here it is the problem:
when i get to the $_POST latin string strilen() works perfectly, but when i get cyrillic string strlen() doubles its value here is the code:
$word = $_POST['word'];
echo strlen($word) . '<br>'; //input: abc -> returns 3, input: абв -> returns 6
var_dump($word); //input: abc -> returns string 'abc' (length=3), input: абв -> returns string 'абв' (length=6)

Do you have some ideas?!

A: Try mb_strlen() if you're dealing with multi-byte characters.
http://php.net/manual/en/function.mb-strlen.php

A: strlen does not double anything, it simply reports what the situation is. Specifically, it reports how many bytes -- and not how many characters -- make up the string. That is because strlen does not have any knowledge of what a "character" is, and blindly assumes that 1 byte = 1 character. Therefore we say that "strlen is not multibyte-aware".
In your case, it seems that the browser submits UTF-8 encoded data to the server. In UTF-8, cyrillic is two bytes per character.
If you want to find out the number of characters in the string, use the multibyte-aware mb_strlen:
echo mb_strlen($word, 'UTF-8');

A: if you want to get length in the terms of characters (not bytes) use a multi-byte version of strlen: mb_strlen: http://php.net/manual/en/function.mb-strlen.php


text:
Q: how can i search Controls in flow Layout panel? In my flow layout panel it load pic and name in user control.
I try this, which is working fine
foreach (DataRow row in dt.Rows)
{
    byte[] data = (byte[])row["Image"];
    pic = new PictureBox();
    pic.Width = 150;
    pic.Height = 150;
    pic.BackgroundImageLayout = ImageLayout.Stretch;
    pic.BorderStyle = BorderStyle.FixedSingle;
    string type = row.Table.Columns.Contains("liquidPriceId") ? "liquidPrice" : "itemMaster";
    string tag = row.Table.Columns.Contains("liquidPriceId") ? row["liquidPriceId"].ToString() : row["itemMasterId"].ToString();
    MemoryStream ms = new MemoryStream(data);
    pic.BackgroundImage = new Bitmap(ms);

    Label name = new Label();
    name.Text = row["Name"].ToString();
    name.BackColor = Color.FromArgb(45, 66, 91);
    pic.Controls.Add(name);
    flp.Controls.Add(pic);
}

THEN in my search text change I try this, my problem is I don't know how to get the name for filtering
foreach (Control c in flowLayoutPanel3.Controls)

how to get inside  c of my pic and name values ?
private void txtSearchBox_TextChanged(object sender, EventArgs e)
{
    string searchValue = txtSearchBox.Text;

    try
    {
        if (txtSearchBox.Text.Length > 0)
        {
            string compareTo = String.Concat("*", txtSearchBox.Text.ToLower(), "*");

            foreach (Control c in flowLayoutPanel3.Controls)
            {
                c.Visible =(c.Name.ToLower() == compareTo); // c.Name is empty how can i get name ?
            }
        }
        else
        {
            foreach (Control c in flowLayoutPanel3.Controls)
            {
                c.Visible = true;
            }
        }
    }
}

A: It's not clear from the code and text provided, but it seems that what you might need is to set the Name property of the control(s) you create in the first code snippet. Something like this:
//...
pic = new PictureBox();
pic.Name = "My Picture";
// ...

I would also change the comparison from this:
c.Visible =(c.Name.ToLower() == compareTo);

to this:
c.Visible = c.Name.StartsWith(compareTo, StringComparison.CurrentCultureIgnoreCase);

A: When you create the PictureBox control, I would make the Name property the same as the Text property of the Label:
name.Text = row["Name"].ToString();
pic.Name = name.Text;

But, you are adding * to the beginning and end of your search string.  So do you want a match if the search value is contained anywhere within the Name property?
If yes, then you could just use String.Contains():
string compareTo = txtSearchBox.Text.Trim().ToLower();
foreach (Control c in flowLayoutPanel3.Controls)
{
    c.Visible = c.Name.ToLower().Contains(compareTo);
}


text:
Q: gspread and oauth2client usage I was trying to use oauth2client and gspread to operate on googlesheet but the problem i have is that when using oauth2client, it requires a field of scope. I have no idea what the scope is. The following is the code of the use of oauth2client.
import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope = ['https://spreadsheets.google.com/feeds']

credentials = ServiceAccountCredentials.from_json_keyfile_name('gspread-april-2cd … ba4.json', scope)

gc = gspread.authorize(credentials)

wks = gc.open("Where is the money Lebowski?").sheet1

A: The OAuth scopes express the permissions you request users to authorize for your app.
The one you used is the only available scope to authorize your request when using Google Sheets API v3.
https://spreadsheets.google.com/feeds

While if you used the Google Sheets API v4, you can now use either of these two scopes:
https://www.googleapis.com/auth/spreadsheets.readonly

that allows read-only access to the user's sheets and their properties and
https://www.googleapis.com/auth/spreadsheets

that allows read/write access to the user's sheets and their properties.


text:
Q: How to import a function I wrote in python I wrote a function and saved it in a different directory.
If I want to call the function in the script I'm currently at.  How do I tell Python the location of this directory?  I've read some article like this one http://tinyurl.com/q2mmlh3
but I really don't understand how to solve my problem.
Please explain to me how to import morbo_function_lib.py into euler_04.py
the location of the script I currently working at
/home/morbo/document/python/euler/euler_04.py
below is the location of the function I wish to import from
/home/morbo/document/python/python_script/morbo_function_lib.py
I am running Python 2.X on Ubuntu 14.04.  And I am using Geany to write Python code.
I must apologize because this seem to be a repeated question on the forum but due to my limited knowledge.  I can't seem to locate the proper answer to my question.
Thank you very much for the time spent

A: Common used approach for this with good explanation are provided here
How to import a module given the full path?

A: By default only the current directory and the Python library path are used (https://docs.python.org/2/tutorial/modules.html#the-module-search-path); anyway, you can use the "imp" (https://docs.python.org/2/library/imp.html):
import imp

foo = imp.load_source('module.name', '/home/morbo/document/python/python_script/morbo_function_lib.py')


text:
Q: (Next 12.2) Chaining Middleware I am looking to chain middleware in a nextJS project, on the latest NextJS version with the stable Middleware API. Here's an example snippet of my middleware.ts file.
Both of these will return a NextResponse object, how can I go about chaining them so the cookies are added first then passed along to find redirects?
I suppose I'll have to extend the API of the second middleware to take in the response and use it's contents or pass it along. Does anyone have a good example for how to go about this?
export const middleware = (req: NextRequest): NextResponse | undefined => {
  addCookieMiddleware(req);
  findRedirectsMiddleware(req);

// How to return a singular NextResponse object with the cookie attached and the correct URL to redirect?
}

A: I'm trying to chain as well.
The docs say you can chain https://nextjs.org/docs/api-reference/next/server#static-methods

next() - Returns a NextResponse that will continue the middleware chain

Here is the source code for v12.2.2 (current at the time of writing)
https://github.com/vercel/next.js/blob/689626c6a4d509fe04aaf82c9971a5928669bcf4/packages/next/server/web/spec-extension/response.ts#L64
static next(init?: ResponseInit) {
  const headers = new Headers(init?.headers)
  headers.set('x-middleware-next', '1')
  return new NextResponse(null, { ...init, headers })
}

If it does chain, I think it has to do something with the x-middleware-next header it is setting. I looked through the source code and I still could not determine how to chain.
The other interesting thing is next() returns a new NextResponse ,but, next() is a static method.
Since next() is static, you cannot call twice.
This does not work, response will be undefined.
const response = NextResponse.next()
response.next({
  headers: {
    'a-test': Math.random().toString(),
  },
})

What I'm doing for now:
You set cookies by calling next() and using the public cookie property and use Map operations.
const response = NextResponse.next()
response.cookies.set('a-test', Math.random().toString())

You set headers by calling next() and passing in an object with a headers object within.
const response = NextResponse
response.next({
  headers: {
    'a-test': Math.random().toString(),
  },
})

I first thought was to use const response = new NextResponse but that did not work, response would always be undefined. You have to use const response = NextResponse
Since you can only call next() once, the best thing I could do was call the headers function first where calling next() is required, and then calling the function that sets the cookies.
// middleware.js
import { NextResponse } from 'next/server'

const setHeaders = (response) => {
  return response.next({
    headers: {
      'a-test': Math.random().toString(),
    },
  }
}

const setCookies = (response) => {
  response.cookies.set('a-test', Math.random().toString())
  return response
}

export async function middleware(request) {
  // Limitation in config matcher, requires me to exclude here
  if (request.nextUrl.pathname.startsWith('/_next')) {
    return NextResponse.next()
  }

  let response = NextResponse
  response = setHeaders(response)
  response = setCookies(response)
  return response
}

Hope this helps!


text:
Q: How can i call a web-component with a script call I developed a web app with react and i want to embed it in another website, although i embedded it in the website through an iframe, there is a code below about it.
<iframe src="https://mapbox-project.netlify.app/" frameborder="0" height="560" width="100%"></iframe>

But, due to iframes limitations, i want to be able to embed it through a script call like this instead?
I don't know if this might help to understand what I'm trying to achieve here.. https://blog.jenyay.com/web-ui-widget/
  <script src="https://mapbox-project.netlify.app/"></script>

But i really do not know how to go about it.

A: That's not possible. The only ways to embed another page is via an iframe, actual frames (if anyone still remembers them), or using embed. Script tags are for executing javascript code, but a page is not javascript code. Some web applications/APIs offer a JSONP variant for embedding where you can indeed call them via a script tag, e.g., but that would need to be enabled by the embedded application and requires additional work.


text:
Q: front end workflow tools and NODE.JS as a example

*

*Package Manager (BOWER,GULP)

*JavaScript Task Runner(GRUNT)

*Web Scaffolding tool (Yeoman)

why theses type of front end workflow tools ONLY AVAILABLE IN NODEJS not any other language.

A: Bower,Gulp,Grunt,yoeman etc are npm packages. There are similar packages in other  languages. Here are some.
Front end package managers using bower repo
bowerphp - A PHP implementation of Bower.
django-bower - python django
bower-ruby - use bower in ruby
Build tools
phing -based on apache ant, taskphp - task runner inspired from grunt and gulp, bldr - php
rake ,capistrano - ruby (Capistrano tasks behave slightly differently than rake tasks and their hookable nature separates them from rake tasks.)
fabric - python
This is what I understood from your question. You can always use these npm packages along with other languages also.eg yoeman with php


text:
Q: apply function to a subset of a variable length I have got a list
list = Row[{#}] & /@ Range[100]

and I want to apply function f to the following elements:
sublist = Row[{5 #}] & /@ Range[20]

It is easy when I specify indexes I want to transform. For instance,
MapAt[f, list, {{1}, {5}}]

works OK. As soon as I create a new list and use it as "Part":
h = Row[{5 #}] & /@ Range[20];
MapAt[f, list, h]

it fails. I suppose that the crux of the problem is using # simultaneously in two arrays - list and h, but I am new to Mathematica and can't figure it out. Is there any way to work with arrays of arbitrary length?

A: MapAt needs a plain list, not items wrapped in Row.  If you omit Row from h it works.  Note your function f is applied to Row[{5}], not just {5}.  Are you sure you need to use Row at all?


text:
Q: Changing background-image in CSS with JQuery I am creating a simple slider who is just fading a picture over an other. The problem is that the background change only works in the dreamweaver preview but not in the browser.
loop = setInterval(function(){
    $("#slider").css("background-image" , "url(/slider" + x + ".jpg)");
    $("#slider > img").fadeOut(2);
    $("#slider > img#" + y).fadeIn(3000);
}, 4000)

So it basicly looks like this: Set the background, fade the old pic away, fade the new pic over the background, do it again.
But I can't see why it won't set the background or won't display it at least.

A: You need to change the src attribute of the image like this: $("#slider > img").attr('src', y);.
Please check this jsfiddle.


text:
Q: Unexpected Output using Struct Array in C So I have a struct, and within that struct I have a array of chars that is meant to store a phone number. Format being xxxxxxxxxx (with x being a digit from 0-9). Then, I'm running a for loop to format the display of those ten digits while printing.
 #include <stdio.h>

void clear(void);

struct Student {
    int idNumber;
    char firstName[25];
    char lastName[25];
    char cellNumber[15];
    char grade, grade2;
    char semester[11], semester2[11];
    char course[10], course2[10];
};

int main() {

    struct Student studentArr[2];

    for (int x = 0; x < 2; x++){

        printf("For student %d...\n", x+1);
        printf("Enter student number: \n");
        scanf("%d", &studentArr[x].idNumber);
        printf("%d", studentArr[x].idNumber);
        printf("Enter student's first name: \n");
        scanf("%s", studentArr[x].firstName);
        printf("%s", studentArr[x].firstName);
        printf("Enter student's last name: \n");
        scanf("%s", studentArr[x].lastName);
        printf("%s", studentArr[x].lastName);
        printf("Enter student's cell number: \n");
        scanf("%s", studentArr[x].cellNumber);
        printf("%c", &studentArr[x].cellNumber[1]);
        printf("(");
        //print("%s", studentArr[x].cellNumber);
        for(int i = 0; i < 3; i++) {
            printf("%s", &studentArr[x].cellNumber[i]);}
        printf(")");
        for(int i = 3; i < 6; i++){
            printf("%s", &studentArr[x].cellNumber[i]);}
        printf("-");
        for(int i = 6; i < 10; i++){
            printf("%s", &studentArr[x].cellNumber[i]);}
        printf("Enter course %d: \n", x+1);
        scanf("%s", studentArr[x].course);
        printf("%s", studentArr[x].course);
        printf("Enter semster for course %d: \n", x+1);
        scanf("%s", studentArr[x].semester);
        printf("%s", studentArr[x].semester);
        printf("Enter letter grade for course %d: \n", x+1);
        scanf("%s", studentArr[x].grade);
        printf("%s", studentArr[x].grade);
        clear();

    }

}

void clear(void) {

    while(getchar() != '\n');
}

Here is the output:

As you can see, the output for the phone number is completely messed up, also I'm ending up with a segmentation fault. Any help or advice is completely appreciated.
FWIW, I'm a novice so don't be too harsh :)
EDIT: Switched the %s to %c and now am getting this output and not prompt for user entry:
Letters instead of numbers

A: I understand being a new user. You should, however, review StackOverflow's How to ask? guidelines to understand what you should do prior to posting a question on StackOverflow. However, in the interest of helping out a new user of SO:
You should ensure your compiler warnings are on. If you didn't get warnings, then you should ensure you're using a good compiler like Clang.
When I compiled your code, I got these errors:
$cc phone.c -o phone
phone.c:34:22: warning: format specifies type 'int' but the argument has type 'char *' [-Wformat]
        printf("%c", &studentArr[x].cellNumber[1]);
                ~~   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
                %s
phone.c:52:21: warning: format specifies type 'char *' but the argument has type 'int' [-Wformat]
        scanf("%s", studentArr[x].grade);
               ~~   ^~~~~~~~~~~~~~~~~~~
phone.c:53:22: warning: format specifies type 'char *' but the argument has type 'char' [-Wformat]
        printf("%s", studentArr[x].grade);
                ~~   ^~~~~~~~~~~~~~~~~~~
                %c
3 warnings generated.

These clue you in to what mistakes you may have made.
In this case, you got a little confused between characters and strings, along with some other issues.

*

*Fixing your character/string issues:
You made the error of passing a pointer to a character where you  should've just passed the char itself. To fix this, you should delete the ampersand, changing this:
printf("%c", &studentArr[x].cellNumber[i]);

to this:
printf("%c", studentArr[x].cellNumber[i]);

for each of your three lines.

*You also probably want to print a '1' first, not the index 1 of the phone string (otherwise input 5555555555 outputs 5(555)555-5555).
So, change this:
printf("%c", &studentArr[x].cellNumber[1]);

to this:
printf("%c", '1');    // or printf("1");

After you do #1 and #2, you will get output like this:
gregEnter student's last name:
schmit
schmitEnter student's cell number:
6306089561
1(630)608-9561Enter course 1:

*There are still errors in your code. From here, you should compile and inspect warnings, and then search for the errors you get, as they are well documented.

A: You are printing cell number using &. Do not use & to print value at address. & Is used to print address only.


text:
Q: Ubuntu 20.04 boot failure after editing system files on a iMac I'm a life-long Windows PC guy (boo hiss) whose friend was getting rid of a 2010 27-inch iMac (as the hard drive had failed). I took it from him and I figured I could use it as way to learn Linux. I bought an SSD and replaced the HD. Then I installed Ubuntu as a single install, deleting the Mac OS recovery partition in the process (which I now understand was a mistake).
Ubuntu 20.04 installed with no hiccups. Interestingly, when it boots I get nothing for 5 seconds, then the too-loud Mac start-up sound (more boo hiss), then a white screen for 10 seconds, then a black screen for 30 seconds, then the scrolling Ubuntu text starts. I gather this is normal for an old iMac running Ubuntu, but have no experience.
Anyway, I found a popular YouTube, 50 Things to Do After installing Ubuntu 20.04, and started to follow these guidelines.  After finishing his 11th step yesterday, I shut the computer down for the evening. Some of his steps include decreasing the swap use by editing /etc/sysctl.conf and reducing SSD writes by editing fstab. I followed the instructions carefully.
This morning I started to continue the remaining steps from the YouTube video, but I could not get the machine to boot! I have tried Ctrl+C while booting and putting in a bootable flash drive, but neither have allowed me to boot from the flash drive or get to the Ubuntu GRUB boot loader.
Messages I am seeing include but are not limited to:
Failed to start Login Service
Failed to start Modem Manager
Failed to start Hostname Service
Failed to start Service for snap application
Failed to start Network Name Resolution
Failed to start Snap Daemon
Here is a screenshot of the boot errors:


text:
Q: custom email event receiver doesn't accept .msg file attachments Environment is Sharepoint 2010. The issue I'm running into is essentially the one that occurred here: http://social.technet.microsoft.com/Forums/en-US/sharepointadmin/thread/f74ca4cb-44fe-4918-b206-b6616458a524
except that I am running a custom email event receiver instead of the native SharePoint one.
The section that handles the attachments happens here:
foreach (SPEmailAttachment attachment in emailMessage.Attachments)
{
    byte[] attachmentArray = new byte[attachment.ContentStream.Length];
    attachment.ContentStream.Read(attachmentArray, 0, (int)attachment.ContentStream.Length);
    item.Attachments.Add(fileName, attachmentArray);
}

This code works fine for every attachment that I've tried, with the exception of .msg files. When any kind of .msg file is attached to an incoming email, no attachments appear and my event receiver logs an error that there were special characters that are not allowed in a file name. Even the most harmlessly named files like "a.msg" gives this error. Has anyone run into this problem with email attachments for an incoming email enabled list?

A: If anyone else comes across this issue, the fix is quite simple. Emails with other emails as attachments do not have a filename but rather the file name is stored as a header. See my code snippet below for how to access the filename.
string fileName = attachment.FileName;
if (fileName == null)
{
    if (string.Equals(attachment.ContentType, "message/rfc822", StringComparison.OrdinalIgnoreCase))
    {
        fileName = new SPEmailMessage(attachment.ContentStream, (string)null).Headers["subject"] + ".eml";
    }
}


text:
Q: com.android.camera.NEW_PICTURE is deprecated for all apps Android N? I have used com.android.camera.NEW_PICTURE & android.hardware.action.NEW_PICTURE to check whether an image is captured or not in my app.
But it's getting warning com.android.camera.NEW_PICTURE is deprecated for all apps starting with the Android N release to target SDK
How can I resolve it? Can any one help me for Android N.
My code is
 **<receiver android:name=".receiver.CameraReceiver"
           android:enabled="true">
 <intent-filter android:priority="10000">
 <action android:name="android.intent.action.CAMERA_BUTTON" />
 <action android:name="com.android.camera.NEW_PICTURE" />
 <action android:name="android.hardware.action.NEW_PICTURE" />
 <category android:name="android.intent.category.DEFAULT" />
 <data android:mimeType="image/*" />
 </intent-filter>
 </receiver>**

Thanks.

A: The Documentation states that it's deprecated in Android N. Relevant part of the docs:
In Android N this broadcast was removed, and applications are recommended to use JobInfo.Builder.addTriggerContentUri(JobInfo.TriggerContentUri) instead.
In Android O this broadcast has been brought back, but only for registered receivers. Apps that are actively running can again listen to the broadcast if they want an immediate clear signal about a picture being taken, however anything doing heavy work (or needing to be launched) as a result of this should still use JobScheduler.


text:
Q: In related Contacts list it shows account field instead of contact fields I am seeing some discrepancies with related list page layout deployment.
The columns are shown in Contact related list on custom object page layout changes when deployed to the instance.
Columns in the Contact-related list are:

*

*Name

*Account Name

*Description(custom field on Contact)

The metadata file also shows these columns but when this layout gets deployed to the environment the Description (custom field on Contact) is changed to Account:Description (custom field on Account). After deployment when I retrieve meta.xml file for page layout from the instance, it didn't show any "Description" field in that.
Contact Related List
Meta.xml file which I have deployed

Meta.xml file retrieved after deployment


text:
Q: Correct application of Leibniz Rule Consider the following integral
$$I = \int^b_af[x[t];c]dt$$
where $a,b$ and $c$ are scalers and $x[t]$ is a function of $t$. I want to know $\frac{\partial I}{\partial x}$.
If I apply Leibniz Rule, I get
$$\frac{\partial I}{\partial x} = \int^b_a\frac{\partial f}{\partial x}dt$$
I feel this is an incorrect application of the rule, since $x$ is a function of $t$.
Alternatively, I can think of re-defining $f$ as $g = f[x+\epsilon;c]$, where for $\epsilon = 0$ we have the original function. Now if I apply Leibniz Rule by differentiating with respect to $\epsilon$ (and then evaluate the derivative at $\epsilon = 0$), I get,
$$\frac{\partial I}{\partial  \epsilon} = \int^b_a\frac{\partial g}{\partial x}|_{\epsilon=0}  dt$$
Questions:

*

*Am I correct in saying that my first method is incorrect?

*If the alternative method is correct, does it correctly capture $\frac{\partial I}{\partial x}$?

Edit:
It might help to explain what I was thinking of when I wrote the question:
Suppose $x$ represents monetary values at different points of time ($t$) and $f$ is a function of $x$. $I$ is adding $f$ from $t=a$ to $t=b$. I would like to calculate, how the sum ($I$) changes if the entire sequence $x$, say, goes up or down.


text:
Q: How to make discord bot randomly skip a response This might sound like a weird one but I was wondering how to make a discord bot randomly skip a response when a person says one of the keywords that bot will respond to? I was thinking adding NULL to the array would work but it does. Adding skip() doesn't seem to work either. I'm just not sure how to do this. Thanks for all the help in advance.
var array = ['test', 'test2'];

const messages = ['what kind of test?', NULL];

client.on('message', function(message) {
    if (array.includes(message.content)) {
        setTimeout(function(){message.channel.send(messages[Math.floor(Math.random() * messages.length)]);}, 3000);
    }
});

A: You could do something simple like using Math.random() with a variable that you can adjust based on your desired response rate.
Math.random will return a pseudo-random number between 0 and less than 1. Whenever the random number is greater than your response rate you can use return to exit the function. This isn't the most precise way to guarantee the exact response rate specified but it should be good enough for something like this.
const matches = ['test', 'test2'];
const messages = ['what kind of test?', 'Some other response'];
const responseRate = 0.7;

client.on('message', function(message) {
    if (matches.includes(message.content)) {
         if(Math.random() > responseRate) return;
         setTimeout(function(){message.channel.send(messages[Math.floor(Math.random() * messages.length)]);}, 3000);
    }
});


text:
Q: Crashing Pointer Array C++ Code::Blocks, Win7, C++
Hi, I'm creating an overview project for myself, and an integral part includes doing an Exchange Sort in descending order. I've created a simple trial run to test the concept.
Embarrassingly enough, I can't get past creating the array without the project crashing. This only happens when I create the array with pointers (My project's arrays are pointers, which is why I need this to work). The code compiles fine, but when I run it, I get a Window's notification that "ArrayTest.exe has stopped working"
When I print out each dereferenced value, I get:
"The original order: 1 13 5 7 2 "
When I print out each value's address, I get:
"The original order: 0x28ff08 0x28ffc4 0x760c8cd5 0x6aadab61 0xfffffffe "
The last address showed up when using an array length of 6, and crashes as well. Am I blind to a simple error in my code, or is this a hardware issue?
//filename ArrayTest
#include <iostream>

using namespace std;

int main()
{
    int *j[5];
    (*j)[0] = 1;
    (*j)[1] = 13;
    (*j)[2] = 5;
    (*j)[3] = 7;
    (*j)[4] = 2;

    cout << "The original order: ";
    for (int i = 0; i < 5; i++)
    {
        cout << (*j)[i] << " ";
    }

     return 0;
}

A: Consider int *j[5]; carefully. This is an array of pointers.
Those pointers are not pointing to memory that you own.
So the behaviour on dereferencing them is undefined.
Trivial fix: use int j[5]; instead, and j[0] = 1 etc.
When analysing code problems consider these numbers as approximating the probability of the error location:

99.0% - your code
0.9% - the standard library
0.09% - the compiler
0.009% - the operating system
0.001% - the hardware

A: If you want a pointer on array, you have to use this syntax
int array[5];
int (*j)[5] = &array;

(*j)[0] = 42;

A: So, firstly, the correct syntax is int j[5]; but that's C, not C++.
use std::array - actual C++ and with compile-time checking.

A: You're allocating an array of 5 pointers to int, not an array of 5 integers. Try to init the array like this: int j[5];
Your code writes your values 1, 13, 5, 7, 2 to the dereferenced pointers in your pointer array. Since they are uninitialized, they contain garbage and thus you're writing to random addresses in memory, which leads to the crash.


text:
Q: Condtitional Validation rules in Yii I have a problem in custom validation rules in Yii. I have some fields like day1s, day1e, day2s, day2e etc. I want to check whether these attributes have the same value stored in my db or not before creating a new record. And also check for different userid. If a value already exists I want to generate an error and prompt the user to change the value. I figured to do something like this:
 array('day1s, day1e, day2s etc','unique','message'=>'day1s is already exist, please change'),

This kinda work but I want to modify it. The default value of this is "00:00" and if I put this rule then every time I will go and create a new record it generates the error, except the first time. I want to ignore that when day1s==00:00. And also if the user changes(in my occasion the user is SchoolID). I'm having trouble wrapping around my head on how to do that. Thanks in advance!

A: Add allowEmpty in rule:
array('day1s, day1e, day2s etc','unique','message'=>'day1s is already exist, please change', 'allowEmpty'=>true),

In controller before validation add this code:
if($model->day1s == "00:00") {
   $model->day1s = '';
}

A: Sorry for being so late to answer. In controller you mean in my action Create?Before $model->save?I tried that but it doesn't seem to work. I figured to make a function in my model like this:
public function unique() {
 if ($this->day1s == "00:00" || $this->day1s == "0:00") {

       $this->day1s='';//here it seems to work for the 00:00
 } else {
     //but my rule gets ignored now for any other values. What can I add here to make it work?
 }

Also sorry for posting an answer instead of editing my question.
I figured it out eventually: my rules are like this:
array('day1s,day1e, day2s, day2e, day3s, day3e, day4s, day4e, day5s, day5e, day6s, day6e, day7s, day7e','unique','message'=>'This already exist, please change', 'allowEmpty'=>true,
                 'criteria' => array(
                 'condition' => 'schoolid=:schoolid',
                 'params' => array(':schoolid' => $this->schoolid))
               ),

and my controller is like this:
if ($model->day1s == "00:00" || $model->day1s == "0:00") {
    $model->day1s='';//for custom validation rule 'unique'
                    }
if ($model->day1e == "00:00" || $model->day1e == "0:00") {
                            $model->day1e='';
                    }
 .....
 if($model->validate()){
        if($model->save())
                    $this->redirect('admin');}
    }

Thanks again for your help!


text:
Q: Error when trying to update values in database I have the following c#/Query:
TrackDuration =TimeSpan.Parse( Request.Form["TrackDuration"].ToString());
string InsertQuery = string.Format("UPDATE tblTracks SET  TrackLength={0}, TrackDuration='{1}', TrackName='{2}',TrackDescription='{3}',TrackMap='{4}',DifficultLevel={5},OverallHeight={6},IsCircular='{7}', ForBeginners='{8}',StartPoint='{9}',ParkingPlace='{10}',SeasonOfYear={11},TrackLocation={12}, Images='{13}' WHERE UserID={14}",
                                                                      TrackLength, TrackDuration, TrackName, TrackDescription, TrackMap, DifficultID, OverallHeight, IsCircular, ForBeginners, StartPoint, ParkingPlace, SeasonID, AreaID, ImageList, UserID);

But I got this error message:

Syntax error in UPDATE statement
Syntax error (missing operator) in query expression

I realy tried to solve this, but I can't.
How can I fix this problem?
Update:
This is the value of the Query:
UPDATE tblTracks SET  TrackLength=35, TrackDuration='02:30:00', TrackName='45',TrackDescription='
sometext.

',TrackMap='f',DifficultLevel=3,OverallHeight=450,IsCircular='true', ForBeginners='false',StartPoint='
קיבוץיסעור

',ParkingPlace='
כניסה לקיבוץ יסעור

',SeasonOfYear=1,TrackLocation=3, Images='' WHERE UserID=1

The sql values types are:
TrackLength = number ; TrackDuration = date/time ; TrackName= string ;TrackDescription= string; TrackMap = string; DifficultLevel=number;OverallHeight=number;IsCircular=true/false;ForBeginners=true/false;
StartPoint=string; ParkingPlace=string; SeasonOfYear=number; TrackLocation=number;Images=string

A: '02:30:00'  is not a correct value for datetime DB field, AFAIK. The default format is controlled by date format setting.
Additionally, '20130412' should work in any case, but for datetime field. You need to format the TrackDuration correctly or use CAST/CONVERT. As TimeSpan doesn't contain date part (it represents a duration and not a point in time), you can only make it up (e.g. prepend "20100101") but that is an awful hack.
The proper solution is to use the correct DB field type.
'02:30:00' might work if the field was of time type. Please read some more about time types in SQL Server.
Even better, why don't you use plain integer for the duration in seconds? The duration is not a date anyway.
The much bigger issue is that you are concatenating strings to set the command text, which opens you for SQL injection attack. If I name the racing track a';DROP TABLE tblTracks;-- your database is toast:
UPDATE tblTracks SET TrackLength=35,
                     TrackDuration='02:30:00',
                     TrackName='a';DROP TABLE tblTracks;-- ...


text:
Q: How can my first while loop be done after going to my second loop So if I input numbers that are not equal to 28,29,30,31 (for example days of the month) I want my first while loop to be done after the second loop. If you don't get my poor english try to run this code. I hope that will help. Thank you.
import java.util.Scanner;

public class Padilla8 {

    public static void main (String args []) {

        int nd, day;

        Scanner in = new Scanner (System.in);

        System.out.print ("Please input number of days: \t");
        nd = in.nextInt ();

        System.out.print ("1 - Monday\n2 - Tuesday\n3 - Wednesday\n4 - "
                + "Thursday\n5 - Friday\n6 - Saturday\n7 - Sunday\n");
        System.out.print ("Enter the corresponding number on what "
                + "day you want the month will start:\t");
        day = in.nextInt ();

        while (nd < 28 || nd > 31) {
            System.out.print ("Months are from 28 days to 31 days only.");
            System.out.print (" Please input number of days:\t");
            nd = in.nextInt ();
        }

        while (day < 1 || day > 7) {
            System.out.print ("Please read.");
            System.out.print ("1 - Monday\n2 - Tuesday\n3 - Wednesday\n4 - "
                    + "Thursday\n5 - Friday\n6 - Saturday\n7 - Sunday\n");
            System.out.print ("Enter the corresponding number on what day "
                    + "you want the month will start:\t");
            day = in.nextInt ();
        }
    }
}

A: please use flags in loop condition .
while (day < 1 || day > 7 && flag) {
}


text:
Q: Benchmarking System performance of Python System I'm looking at using inotify to watch about 200,000 directories for new files. On creation, the script watching will process the file and then it will be removed. Because it is part of a more compex system with many processes, I want to benchmark this and get system performance statistics on cpu, memory, disk, etc while the tests are run.
I'm planning on running the inotify script as a daemon and having a second script generating test files in several of the directories (randomly selected before the test).
I'm after suggestions for the best way to benchmark the performance of something like this, especially the impact it has on the Linux server it's running on.

A: I would try and remove as many other processes as possible in order to get a repeatable benchmark.  For example, I would set up a separate, dedicated server with an NFS mount to the directories.  This server would only run inotify and the Python script.  For simple server measurements, I would use top or ps to monitor CPU and memory.
The real test is how quickly your script "drains" the directories, which depends entirely on your process.  You could profile the script and see where it's spending the time.


text:
Q: Setting asynchronous value to a variable not working First take a look at the code
AsyncStorage.getItem("CartItem").then(val => console.log(val))

When I run it, it logs this array of objects
[{"id":"6084844531f6aa1a980272e6","name":"Garlic","price":300,"qty":10,"totalPrice":3000,"image":"Some image"}]

I need that value which is returning from AsyncStorage to be assigned to a global variable like this
var cart
AsyncStorage.getItem("CartItem"). then(val => cart = val)
console.log(cart)

But the cart variable doesn't affect it logs undefined
It's a function in react-native not a component, so please don't say store the val to state
Any help will be appreciated, thanks in advance

A: The call made to AsyncStorage is obviously async. then block would be executed when the AsyncStorage get the value retrieved. Currently your system is busy in retrieving value but it goes to the next line before the value retrieves.
Following code should work
 var cart = await AsyncStorage.getItem("CartItem")


text:
Q: how to get particular information in particular variable from table import requests
from bs4 import BeautifulSoup

url = "https://www.reuters.com/finance/stocks/company-officers/MPAPss.BO"
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
table = soup.find('table', {'class': 'dataTable'})
for row in table.find_all("tr"):
    for col in row.find_all("td"):
        print(col.text)

it prints the all information simultaneously(name,year and designation) i want to store name in name section using
name = col[0].text

but it gives the the error how i solve this?

A: >>> for row in table.find_all("tr"):
...     cols = row.find_all("td")
...     if not cols:
...         continue
...     name, year, des = filter(None, [col.text.strip() for col in cols])
...     print (f'Name: {name}, Year: {year}, Des: {des}')
...
Name: K. Ratna Prabha, Year: 2014, Des: Non-Executive Chairman of the Board
Name: Mohan Kulkarni, Year: 2012, Des: Compliance Officer, Company Secretary
Name: Naveen Singh, Year: 2014, Des: Managing Director, Executive Director
Name: B. Khanna, Year: 2014, Des: Non-Executive Director - Nominee of BIFR
Name: V. Rammohan, Year: 2013, Des: Non-Executive Director - Nominee of IFCI
Name: Aravind Shrivastava, Year: 2013, Des: Non-Executive Director
Name: M. Lakshminarayana, Year: 2009, Des: Non-Executive Independent Director
Name: C. Okaly, Year: 2010, Des: Non-Executive Independent Director
Name: S. Parameswarappa, Year: 1996, Des: Non-Executive Independent Director
Name: C. Shivashankar, Year: 1995, Des: Non-Executive Independent Director
>>>

A: This is another way you might wanna give atry:
import requests
from bs4 import BeautifulSoup

url = "https://www.reuters.com/finance/stocks/company-officers/MPAPss.BO"

response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
table = soup.find('table', {'class': 'dataTable'})
for row in table.find_all("tr")[1::1]:
    col = row.find_all("td")
    name = col[0].get_text(strip=True)
    year = col[2].get_text(strip=True)
    position = col[3].get_text(strip=True)
    print("Name: {} Year: {} Position: {}".format(name,year,position))

Output:
Name: K. Ratna Prabha Year: 2014 Position: Non-Executive Chairman of the Board
Name: Mohan Kulkarni Year: 2012 Position: Compliance Officer, Company Secretary
Name: Naveen Singh Year: 2014 Position: Managing Director, Executive Director
Name: B. Khanna Year: 2014 Position: Non-Executive Director - Nominee of BIFR
Name: V. Rammohan Year: 2013 Position: Non-Executive Director - Nominee of IFCI
Name: Aravind Shrivastava Year: 2013 Position: Non-Executive Director
Name: M. Lakshminarayana Year: 2009 Position: Non-Executive Independent Director
Name: C. Okaly Year: 2010 Position: Non-Executive Independent Director
Name: S. Parameswarappa Year: 1996 Position: Non-Executive Independent Director
Name: C. Shivashankar Year: 1995 Position: Non-Executive Independent Director


text:
Q: R: (kind of) log axis, i.e. axis with (...-10^1,0,10^1,...) , displaying negative values I have a data-set containing many small (~100), but some bigger (~106) values as well. But the few big points (Which are not that important, but shouldn't be left out) stretch the whole axis.
For positive values i'd use log="y"...
But now, i'd love to get an axis like "...-102, -101, 0, 101, 102...".
Is there a(n easy) possibility to do this?
Do i have to loop through my data set, mapping all negative numbers x to -log(|x|)?   And what to do with the y-axis afterwards?


text:
Q: How to create a list of lists by combining lists of strings of a column with python? I have a column in my dataset consisting of lists of strings like below:
column
['tablet', 'mobile', 'man']
['people', 'house']
. . .
['people', 'computer']
['computer', 'laptop']
How can I get a list of lists with the elements of this column? I want the output like this:
[['tablet', 'mobile', 'man'],['people', 'house'],. . .,['people', 'computer'],['computer', 'laptop']]

A: Use ast.literal_eval for convert strings lists in list comprehension:
import ast

L = [ast.literal_eval(x) for x in df["column"]]
print (L)
[['tablet', 'mobile', 'man'], ['people', 'house'],
 ['people', 'computer'], ['computer', 'laptop']]

A: If you df is like
                      column
0  ['tablet', 'mobile, man']
1        ['people', 'house']
2      ['people, 'computer']
3     ['computer', 'laptop']

You can get the list by calling the column with tolist()
df["column"].tolist()

Output:
[['tablet', 'mobile', 'man'], ['people', 'house'], ['people', 'computer'], ['computer', 'laptop']]

A: import pandas as pd

result_list = []

df = pd.read_csv("file_name")
series_1 = df.loc[::, "column_name"]

for s in series_1:
    list1 = s.strip("[]").replace(" ", "").replace("'", "").split(",")
    result_list.append(s)

print(result_list)


text:
Q: Check if session exists inside blade template - Laravel Currently I have the below code in one of my vanilla php files
<?php

if (isset($_SESSION['qwick'])) {
    include "checkout-lin.php";
} else {
    include "checkout-nlin.php";
}

?>

How can I do the same in laravel. I have created 2 files in my includes folder named loggedinclude.blade.php and notloggedinclude.blade and I now want to add them in a page checkstatus.blade.php
Also I'm able to set a session like this
$vars = [
    "email" => $email,
    "password" => $password,
    "firstname" => $row['firstName'],
    "lastname" => $row['lastName'],
    "id" => $row['id']
];

session()->put('blog', $vars);

From the above code, I'm creating an array then putting the array in a session called blog thereby setting the a session called blog. and now I want to be able to check if a session named blog has been set. blog then has variable email etc
FYI;
my first question is checking for session exist in blade
my second question is checking for named session exist in controller
The documentation only has code for checking session items
if ($request->session()->has('users')) {
    //
}

A: you can use this way for Laravel :
In your Controller or Route function:
$request->session()->flash('your_session', 'your message');

and in Resource/Views/your_blade_file.blade.php
@if (session()->has('your_session'))
    anything ...
@endif

A: @if(session()->has('qwick'))
    @include('includes.loggedinclude')
@else
    @include('notloggedinclude.loggedinclude')
@endif

Documentation about blade can be found here.
Session documentation can be found here.

A: Try the below Code Snippet.
@if(session->has('qwick'))
 @include('includes.loggedinclude checkout-lin')
@else
  @include('checkout-nlin')
@endif

Reference:
Laravel Session variables in Blade @if
http://laravel-recipes.com/recipes/90/including-a-blade-template-within-another-template
If statements in blade templating?

A: The better way to check out the user is logged inside the controller. Checking user log in in view section may be break the MVC rule.
Thanks.
If you must need you can try this
@if(session->get('qwick'))
@include("includes.loggedinclude")
@else
@include("notloggedinclude.loggedinclude")
@endif


text:
Q: JMeter not recording for .NET application My application is developed in .NET, It has one scenario where after 4 steps(Pages) registration will happen. Jmeter is not recording the last step, where as it is able to record the first three steps.
Step 1. Fill the form click on next
Step 2 Input some data and click on next
Step 3. Upload some document and click next
Step 4. Fill the last page and click on "Submit" button
After 4th step, one new pop-up window will display having registration number
If I am trying to do the same without using JMeter, application is behaving ok. Jmeter version is 2.9

A: You should first upgrade to jmeter 2.11.
If it still does not work, in recorder switch to java implementation instead of HttpClient.


text:
Q: Hello world example not working in react.js I have installed React.js using the following command:
create-react-app my-app

now i open my command line and i execute the following command:
npm start

The App opens in my browser at the following URL:
http://localhost:3000/

Now i go to the public/src/app.js folder and change the code from the following:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return (

Welcome to React

          Why did you do ??

    );
  }
}

export default App;

To the following:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

ReactDOM.render(

Hello, world!
,
  document.getElementById('root')
);

export default App;

But i get the following error. Why ?

Failed to compile
./src/App.js
  Line 5:   'ReactDOM' is not defined  no-undef
  Line 10:  'App' is not defined       no-undef

Search for the keywords to learn more about each error.

A: The errors are pretty self-explanatory:

Line 5:   'ReactDOM' is not defined  no-undef

You are using ReactDOM.render, but you're not importing it, so it's not defined.
Also, you probably don't want to use it at all, because it's already being called in another file (src/index.js).

Line 10:  'App' is not defined       no-undef

The original code declared a class App and exported it. You removed the class declaration, but you kept the export, which references the now non-existent class App.

A: You have to add this:
import ReactDOM from 'react-dom';

and delete export default App;

A: you are not importing React-DOM,
jsut add
import ReactDOM from 'react-dom';

A: I have describe this example to understand

For Example: App.js

import React, { Component } from 'react';
import ReactDOM from 'react-dom';  // Step 1: import ReactDOM
import logo from './logo.svg';
import './App.css';

ReactDOM.render(

Hello, world!
,
  document.getElementById('root')
);

// export default App;// Step 2 :- This line is comment

I hope 'Hello world' example is working in React.js.


text:
Q: jquery toggle the votes like stackoverflow
Possible Duplicate:
jQuery voting system

i have this voting jquery script, which works fine, but i want the option for the user to toggle the vote, just like stackoverflow, so basically
you can vote up by clicking up arrow
   increase vote by 1
   if they click again on the picture(arrow up)
   minus 1 from the vote

my jquery script:
$(document).ready(function() {
    $('.statuses').delegate('.vote_up', 'click', function(e) {

        //stop event
        e.preventDefault();
       //get the id
        var the_id = $(this).closest('.message').attr('id').split('_').pop();
        //the main ajax request
        $.ajax({
            context: this,
            type: "POST",
              // Make sure "this" in the callback refers to the element clicked

            data: "action=vote_up&id=" + the_id,
            url: "ajax/votes.php",
            success: function (msg) {
                  // Not sure where your vote_count is. See the HTML for my placement
                $(this).siblings("span.vote_count").html(msg).fadeIn();
                  // get the child  and set its src
                $(this).children("img").attr("src", "img/uparrowActive.png");
            }
        });
    });
});

html code:
0

i was thinking what was the best way to do this thanks :))


text:
Q: C++: no matching constructor for initialization / candidate constructor not viable: requires single argument, but no arguments were provided I am trying to implement a linked list in C++ and don't know how to fix the error given below. I would greatly appreciate any help with debugging and, more importantly, an explanation of any underlying concepts that I don't understood regarding this error. Thanks.
Here is my error:
linkedList.cpp:19:23: error: no matching constructor for initialization of 'NodeType'
        newnode = new NodeType;
                      ^
./linkedList.h:10:9: note: candidate constructor not viable: requires single argument 'str', but no arguments
      were provided
        NodeType(const std::string str);
        ^
./linkedList.h:4:7: note: candidate constructor (the implicit copy constructor) not viable: requires 1
      argument, but 0 were provided
class NodeType
      ^
linkedList.cpp:54:29: error: no matching constructor for initialization of 'NodeType'
    NodeType* newnode = new NodeType;
                            ^
./linkedList.h:10:9: note: candidate constructor not viable: requires single argument 'str', but no arguments
      were provided
        NodeType(const std::string str);
        ^
./linkedList.h:4:7: note: candidate constructor (the implicit copy constructor) not viable: requires 1
      argument, but 0 were provided
class NodeType
      ^

Here is my NodeType class in my linkedList.h file:
  3 // define the node class
  4 class NodeType
  5 {
  6     private:
  7         std::string value;
  8         NodeType* next;
  9     public:
 10         NodeType(std::string str);
 11     friend class LinkedList;
 12 };

Here is the method in the linkedList.cpp file for the first error:
 10 LinkedList::LinkedList(const LinkedList& src)
 11 {
 12     head = NULL;
 13     NodeType* srccur; //node that is currently in src
 14     srccur = src.head;
 15
 16     NodeType* pre = NULL; //predecessor of the new node
 17     while (srccur != NULL) // have not finished yet
 18     {   NodeType* newnode;
 19         newnode = new NodeType;
 20         if (newnode == NULL) //dynamic allocation failed
 21             { cout << "Memory allocation error" << endl;
 22                 exit(1);
 23             }
 24
 25     newnode->value = srccur->value;
 26
 27     if (pre == NULL)    //the new node becomes the 1st node
 28         head = newnode;
 29     else    // the new node is attached to the end
 30         pre->next = newnode;
 31
 32     newnode->next = NULL;
 33
 34     pre = newnode;
 35     srccur = srccur->next;
 36     }
 37 };

Here is the method in the linkedList.cpp file for the second error:
 53 bool LinkedList::insertFirst(string v){
 54     NodeType* newnode = new NodeType;
 55
 56     if (newnode == NULL) // dynamic allocation failed
 57     {
 58         return false;
 59     }
 60
 61     newnode->value = v;
 62     newnode->next = head;
 63
 64     head = newnode;
 65
 66     return true;
 67 };

A: Very simple. Look at your constructor for NodeType (linkedList.h, line 10). It requires a single string. Yet, when you create new instances of NodeType (linkedList.cpp, line 18, line 54), you are calling the constructor without any arguments.
The proper way to do this would be...
NodeType* newnode = new NodeType("Some string.");

If you want that string argument in the constructor to be optional, you can do so by changing the constructor's header prototype to be...
NodeType(std::string str="Some default value");

Also, you could overload your constructor, having one for no arguments, one accepting a string, and so on.

Just so you know, that was a very basic principle. If you are a student (officially or unofficially), you'll want to review C++ Object Oriented Programming, specifically "Constructors".


text:
Q: How to send message via GMail in Spring Application I try to make integration with GMail on Java and stuck with this issue: according to this documentation  page everything works fine until it deployed to AWS in Docker image.
After creation client_id and client_secret, run first time Gmail integration from sample it  ask me to confirm my gmail account and then creates StoredCredential file.
After all manipulations it works fine locally without any additional confirmations. But the thing is that when Spring app runs in docker it can't read files as File object but only in resource stream format, but Google library ask set directory as a File:
...
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
                .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH))) // THIS LINE
                .setAccessType("offline")
                .build();
...

I realize that nothing works and start making workaround with temporary files and directories, but this not work properly because, how I understand, Google obtain path to stored creds and watch at condition of it and if something changes it ask for confirmation. I don't have any desires to watch in logs of Docker and every time confirm my account for google each time when it see that something changes.
How can I manage this problem?


text:
Q: Use Akita Store with Apollo Client I have developed a small GraphQl API and I am now using it as a React project as I start.
I used to use Akita Store (now Elf) as a store and wondered if it was still relevant to use it with an Apollo customer.
Akita Store has interests.
The Apollo client also allows to manage the local state, but is it also interesting?


text:
Q: Powershell Import-Csv New-AdUser skip if user exists I have a fully functional script to import and create AD Users, but I would like to skip from attempting to create Users that are already in AD.
Import-Module ActiveDirectory

$CsvPath = "C:\Shares\Users.csv"
$CsvTest = Test-Path $CsvPath

Import-Csv $CsvPath | ForEach-Object {
Get-AdUser $_.sAMAccountName
}

Import-Csv $CsvPath | ForEach-Object {
New-ADUser -Name $_.Name -UserPrincipalName $_.userPrincipalName -SamAccountName $_.sAMAccountName -DisplayName $_.DisplayName -GivenName $_.GivenName -Surname $_.Surname -AccountPassword (ConvertTo-SecureString $_.Password  -AsPlainText -force)  -Enabled $true -ChangePasswordAtLogon $true

{

Catch [Microsoft.ActiveDirectory.Management.Commands.NewADUser]

}
    $_."sAMAccountName";  "already exists"
    }

A: Something like this without relying on exceptions would be better:
Import-Module ActiveDirectory

$csvPath = "C:\Shares\Users.csv"

if (Test-Path $csvPath)
{
    $newUsers = Import-Csv $csvPath
    $existingUsers = Get-ADGroupMember "Domain Users"

    foreach ($newUser in $newUsers)
    {
        if (($existingUsers | Where-Object { $_.sAMAccountName -eq $newUser.sAMAccountName }) -eq $null)
        {
            $user = New-ADUser -Name $newUser.Name -UserPrincipalName $newUser.userPrincipalName -SamAccountName $newUser.sAMAccountName -DisplayName $newUser.DisplayName -GivenName $newUser.GivenName -Surname $newUser.Surname -AccountPassword (ConvertTo-SecureString $newUser.Password -AsPlainText -Force) -Enabled $true -ChangePasswordAtLogon $true
        }
    }
}

Personally I prefer to use the Quest AD Module for Powershell as it avoids exceptions by returning $null when an object doesn't exist.


text:
Q: Dynamic subdomains for woocommerce affiliate sales but NO multisite. Is that possible? I've got a woocommerce installation that sells things.  We want to offer affiliates to sell our products with their own url, ie mysite.thebasesite.com.  Basically, the way that it works is that a visitor would hit the above url and I have written a plugin that extracts the "mysite" segment, does an API call to an API to get the affiliate information and then uses that information to customize some things in the header, set a cookie/session object later used to store affiliate information in the woocommerce order.  All the above works when I hardcode the url segment into the plugins.
My problem is getting wordpress to maintain the subdomain in the url throughout the session.  First, if I visit mysite.thebasesite.com, it immediately forwards me to thebasesite.com.  Not sure why.  Second, all the urls in wordpress are absolute, which I think I can get around, but still annoying.  Third, all the emails from the site (particularly orders and whatnot) will have links from thebasesite.com and not mysite.thebbasesite.com.  I can likely get around this too, but I'm wondering if I'm barking up the wrong tree here.
I have no aversion to using multisite but I don't think that will work because all the content (products, themes, plugins, content) is all the same for each site AND there could be thousands of affiliates and therefor thousands of subdomains.  I'm starting to think that this is just something that is going to be impossible with woocommerce and wordpress.

A: It's as possible/impossible as you have time/budget for. It seems achievable to me, given that I'm assuming you're a for-profit organisation and this is generating you revenue somehow, but you might end up hacking some Wordpress internals at some point.
It's a broad and subjective question, which is not ideally suited to this stackexchange, but a couple of ideas below which are not 'solutions' just things worth considering.
1 - Use URL rewriting to make the subdomain a parameter passed to a single domain
Using e.g. the below mod_rewrite rules, taken from [here][1], you could perhaps solve some of your problem by getting the subdomain into a parameter you can easily work with in code.
The below htaccess (or something like it) would assume that you actually only have a single website at e.g. domain.com and a visit to affiliate123.example.com/foo/bar.php would actually appear to the server as example.com/foo/bar.php?sub=affiliate123.
If you make sure that all the URLs on your site are rendered relative to the domain (i.e. your URLs are '/foo/bar/baz.jpg' rather than 'https://www.example.com/foo/bar/baz.jpg') then the browser will consider them to be URLs in the current domain and you have a lot less stuff to worry about.
You'd then need to do some coding in order to be able to map this parameter in your URL that gives you the subdomain to lookup theme components, etc.
This probably has various issues that you'd have to figure out, like what happens if a plugin messes with your sub URL parameter or some other URL construction corner cases.
RewriteEngine on
RewriteCond %{QUERY_STRING} !^sub=
RewriteCond %{HTTP_HOST} ^(?!www\.)(.+)\.domain\.com$
RewriteRule ^(/?)$ $1?sub=%1

2 - What do you do when the affiliate wants to put some content on their page
Occurs to me that it's quite possible that an affiliate or someone in your organisation might have the requirement where they want some content specific to one of the affiliates to be posted only on that affiliate's page. I'd suggest you either allow for that now or make it clear that it's going to be impossible. If this is a possible future requirement, it makes Multisite a potentially much better option because of the ability to allow each affiliate to manage their own content.
3 Management tools
Seems like you definitely need to look into management tools that are going to let you manage a large number of similar sites from e.g. a centralised 'control panel' or set of scripts that you write. There are tools with plugins out there that let you manage many sites from a single dashboard. This could meet a bunch of your requirements. (This also mentioned by @TonyDjukic while I was drafting this answer)
Hope some of that helps you figure out which way to go.
[1]: https://stackoverflow.com/questions/42263265/how-to-rewrite-subdomain-and-subsubdomain-into-a-parameter


text:
Q: Encoding video on H.263 to send over RTP I'm developing an application to send video over RTP to a client that can play only H.263 (1996) and H263+ (1998).
To do this i've encoded the video using libav following these steps: (this is only part of the code)
av_register_all();
avformat_network_init();
Fmt = av_guess_format("rtp", NULL, NULL);
...
st = add_video_stream(FmtCtx, CODEC_ID_H263);
...
avio_open(&FmtCtx->pb, rtp_url, URL_WRONLY)

To finally enter a loop where i encode the video, the problem is that the stream generated by this program is encoded in H.263-2000 (or H.263++) which the other side cannot undertand, even though i use CODEC_ID_H263 or CODEC_ID_H263P in the initialization the same thing happens.
Is it possible to encode in those old H.263 versions using libav? i havent managed to do it not even using ffmpeg commands. The stream is always h.263-2000 (PT=96)


text:
Q: Cannot write to boot disk, asks authentication Problem
Suddenly, after rebooting a Snow Leopard Mac Pro (2009), I cannot copy to the main disk, or even move one of its files, without having Mac OS X asking for authentication.
Once I type the password in the dialog box, the copy is made, but this is not acceptable nor usable in the long term. I even think most apps won't like it...

I'm talking about copying a file from the Desktop to somewhere else on the same disk, the one the system has booted on...!
History
2 x Mac Pro 2009, one has Mac OS X 10.6 Snow Leopard working properly, the second one has nothing.
I used Copy Carbon Cloner to make a clone of the first Mac on another disk then installed the copy in the second machine.
It worked for some time! Then, on this second Mac, I added another disk in bay 3 and things started to go south. I think the disk in bay 3 was faulty.
So I stopped the machine, removed the faulty disk from bay 3, and rebooted. And here the authentication problem on the main disk appeared.
What has been done
I've booted from another system partition on another disk then used Disk Utility to repair the disk and to repair permissions. No errors were detected.
I researched other answers to similar questions but they are all about using an NTFS disk, and this is not my case at all, I'm talking about a standard HFS+ Mac OS X disk that suddenly is in this "read only" mode.
Other info
If I add another disk with Yosemite installed, I can boot on it and I can copy/move/write anything on the Yosemite disk and on the Snow Leopard one.
But I absolutely need to have the Snow Leopard one also working (because of obsolete apps we still need) and rebooting again on it, the problem is still here.
TL;DR
In a 2009 Mac Pro, a cloned Snow Leopard disk asks for authentication for any file operation.
In the same Mac Pro, a Yosemite disk works properly and does not suffer from this issue, I can move files on the Yosemite disk and on the Snow Leopard disk.
Back on the Snow leopard one: the authentication problem is still here, for all disks in the machine.
Result of operations asked in comments
Asked by seaturtle:
cd ~; ls -ale | grep -e '^ [0-9]*:' -B 1 | grep -v '^--$'

drwxr-xr-x@ 15 lollipopmusic  staff    510 17 oct 16:40 .
 0: group:everyone deny delete
drwx------@ 30 lollipopmusic  staff   1020 17 oct 16:43 Desktop
 0: group:everyone deny delete
drwx------@ 35 lollipopmusic  staff   1190 17 oct 16:10 Documents
 0: group:everyone deny delete
drwx------@  5 lollipopmusic  staff    170  1 jui  2010 Downloads
 0: group:everyone deny delete
drwx------@ 32 lollipopmusic  staff   1088 24 avr  2012 Library
 0: group:everyone deny delete
drwx------@  3 lollipopmusic  staff    102 27 mai  2010 Movies
 0: group:everyone deny delete
drwx------@  6 lollipopmusic  staff    204 22 fév  2011 Music
 0: group:everyone deny delete
drwx------@  4 lollipopmusic  staff    136 27 mai  2010 Pictures
 0: group:everyone deny delete
drwxr-xr-x@  5 lollipopmusic  staff    170 27 mai  2010 Public
 0: group:everyone deny delete
drwxr-xr-x@  5 lollipopmusic  staff    170 27 mai  2010 Sites
 0: group:everyone deny delete

and:
total 32
drwxr-xr-x@ 15 lollipopmusic  staff    510 17 oct 16:40 .
 0: group:everyone deny delete
drwxr-xr-x@  6 root           admin    204  1 fév  2011 ..
-rw-------@  1 lollipopmusic  staff      5 27 mai  2010 .CFUserTextEncoding
-rw-r--r--@  1 lollipopmusic  staff  15364 17 oct 16:11 .DS_Store
drwx------   4 lollipopmusic  staff    136 17 oct 16:43 .Trash
drwx------@ 30 lollipopmusic  staff   1020 17 oct 16:43 Desktop
 0: group:everyone deny delete
drwx------@ 35 lollipopmusic  staff   1190 17 oct 16:10 Documents
 0: group:everyone deny delete
drwx------@  5 lollipopmusic  staff    170  1 jui  2010 Downloads
 0: group:everyone deny delete
drwx------@ 32 lollipopmusic  staff   1088 24 avr  2012 Library
 0: group:everyone deny delete
drwx------@  3 lollipopmusic  staff    102 27 mai  2010 Movies
 0: group:everyone deny delete
drwx------@  6 lollipopmusic  staff    204 22 fév  2011 Music
 0: group:everyone deny delete
drwx------@  4 lollipopmusic  staff    136 27 mai  2010 Pictures
 0: group:everyone deny delete
drwxr-xr-x@  5 lollipopmusic  staff    170 27 mai  2010 Public
 0: group:everyone deny delete
drwxr-xr-x   3 lollipopmusic  staff    102 17 oct 16:11 RECUPS
drwxr-xr-x@  5 lollipopmusic  staff    170 27 mai  2010 Sites
 0: group:everyone deny delete

Asked by klanomath:
sudo ls -lae /

drwxrwxr-x@ 30 root           wheel         1088 17 oct 16:43 .
drwxrwxr-x@ 30 root           wheel         1088 17 oct 16:43 ..
-rw-r--r--@  1 lollipopmusic  admin        12292 17 oct 17:04 .DS_Store
drwx------@  5 _unknown       _unknown       170 12 oct 15:07 .Spotlight-V100
d-wx-wx-wt@  2 _unknown       _unknown        68 17 oct 17:04 .Trashes
-rw-r--r--@  1 _unknown       _unknown         0 12 oct 15:07 .com.apple.timemachine.donotpresent
----------@  1 root           admin            0  5 oct  2009 .file
drwx------@  8 _unknown       _unknown       272 17 oct 17:04 .fseventsd
-rw-------@  1 root           wheel        65536 12 oct 16:20 .hotfiles.btree
drwxr-xr-x@  2 root           wheel           68 18 mai  2009 .vol
drwxrwxr-x@ 49 root           admin         1666  2 jan  2012 Applications
 0: group:everyone deny delete
lrwxr-xr-x   1 root           admin           60 13 sep  2016 Guides de l'utilisateur et informations -> /Library/Documentation/User Guides and Information.localized
drwxrwxr-t@ 55 root           admin         1870  1 jui  2010 Library
 0: group:everyone deny delete
drwxr-xr-x@  2 root           wheel           68  5 oct  2009 Network
drwxr-xr-x@  5 root           wheel          170  7 fév  2011 System
drwxr-xr-x@  6 root           admin          204  1 fév  2011 Users
drwxrwxrwt@  5 root           admin          170 17 oct 17:35 Volumes
 0: group:everyone deny add_file,add_subdirectory,directory_inherit,only_inherit
drwxr-xr-x@ 39 root           wheel         1326  4 nov  2009 bin
dr-xr-xr-x   3 root           wheel         4259 17 oct 17:05 dev
lrwxr-xr-x@  1 root           wheel           11 13 sep  2016 etc -> private/etc
dr-xr-xr-x   2 root           wheel            1 17 oct 17:05 home
-rw-r--r--@  1 root           wheel     18676624  4 nov  2009 mach_kernel
dr-xr-xr-x   2 root           wheel            1 17 oct 17:05 net
drwxr-xr-x@  6 root           wheel          204  4 nov  2009 private
drwxr-xr-x@ 64 root           wheel         2176  4 nov  2009 sbin
lrwxr-xr-x@  1 root           wheel           11 13 sep  2016 tmp -> private/tmp
drwxr-xr-x@ 11 root           wheel          374 27 mai  2010 usr
lrwxr-xr-x@  1 root           wheel           11 13 sep  2016 var -> private/var

and:
sudo ls -lae ~/

drwx------@  30 lollipopmusic  staff      1020 17 oct 16:43 .
 0: group:everyone deny delete
drwxr-xr-x@  15 lollipopmusic  staff       510 17 oct 16:40 ..
 0: group:everyone deny delete

A: Do this instead:
Open Finder, find your drive, typically named "Macintosh HD"(but in your case "MAC106"), select it, press Command (⌘) + I on your keyboard, in the window that opens, scroll to the bottom, if the text next to your username is "read and write", this isn't the solution, but if the text is "Read Only", do this:
Click the padlock, type your credentials, click the "Read Only" tag next to your username, click on "Read & Write", click on the padlock, and done.

A: Before you do this, always make sure you have a recent backup!
Is your problem only at the root level, or in every folder?
If it's in every folder try this solution, it'll remake all file permissions: launch the Terminal from /Applications/Utilities/, type this command: sudo chmod -RN ~/Desktop, press enter, type your password, and press enter again. Wait for the command to finish (it can take some time).
If this makes you able use your desktop as Read/Write, you can try doing this sudo chmod -RN /, it'll do the same but for the whole disk instead.
Before you do this, always make sure you have a recent backup!