text:
Q: How to programmatically determine maximum and minimum limit of int data in C? I am attempting exercise 2.1 of K&R. The exercise reads:

Write a program to determine the ranges of char, short, int, and long variables, both signed and unsigned, by printing appropriate values from standard headers and by direct computation. Harder if you compute them: determine the ranges of the various floating-point types.

Printing the values of constants in the standards headers is easy, just like this (only integer shown for example):
printf("Integral Ranges (from constants)\n");
printf("int max: %d\n", INT_MAX);
printf("int min: %d\n", INT_MIN);
printf("unsigned int max: %u\n", UINT_MAX);

However, I want to determine the limits programmatically.
I tried this code which seems like it should work but it actually goes into an infinite loop and gets stuck there:
printf("Integral Ranges (determined programmatically)\n");

int i_max = 0;

while ((i_max + 1) > i_max) {
        ++i_max;
}

printf("int max: %d\n", i_max);

Why is this getting stuck in a loop? It would seem that when an integer overflows it jumps from 2147483647 to -2147483648. The incremented value is obviously smaller than the previous value so the loop should end, but it doesn't.

A: Ok, I was about to write a comment but it got too long...
Are you allowed to use sizeof?
If true, then there is an easy way to find the max value for any type:
For example, I'll find the maximum value for an integer:
Definition: INT_MAX = (1 << 31) - 1 for 32-bit integer (2^31 - 1)
The previous definition overflows if we use integers to compute int max, so, it has to be adapted properly:
INT_MAX = (1 << 31) - 1
        = ((1 << 30) * 2) - 1
        = ((1 << 30) - 1) * 2 + 2) - 1
        = ((1 << 30) - 1) * 2) + 1

And using sizeof:
INT_MAX = ((1 << (sizeof(int)*8 - 2) - 1) * 2) + 1

You can do the same for any signed/unsigned type by just reading the rules for each type.

A: So it actually wasn't getting stuck in an infinite loop. C code is usually so fast that I assume it's broken if it doesn't complete immediately.
It did eventually return the correct answer after I let it run for about 10 seconds. Turns out that 2,147,483,647 increments takes quite a few cycles to complete.
I should also note that I compiled with cc -O0 to disable optimizations, so this wasn't the problem.
A faster solution might look something like this:
int i_max = 0;
int step_size = 256;

while ((i_max + step_size) > i_max) {
    i_max += step_size;
}

while ((i_max + 1) > i_max) {
    ++i_max;
}

printf("int max: %d\n", i_max);

However, as signed overflow is undefined behavior, probably it is a terrible idea to ever try to programmatically guess this in practice. Better to use INT_MAX.

A: The simplest I could come up with is:
signed int max_signed_int = ~(1 << ((sizeof(int) * 8) -1));
signed int min_signed_int =  (1 << ((sizeof(int) * 8) -1));
unsigned int max_unsigned_int = ~0U;
unsigned int min_unsigned_int = 0U;

In my system:
// max_signed_int = 2147483647
// min_signed_int = -2147483648
// max_unsigned_int = 4294967295
// min_unsigned_int = 0

A: Assuming a two's complement processor, use unsigned math:
unsigned ... smax, smin;
    smax = ((unsigned ...)0 - (unsigned ...)1) / (unsigned ...) 2;
    smin = ~smax;

A: As it has been pointed here in other solutions, trying to overflow an integer in C is undefined behaviour, but, at least in this case, I think you can get an valid answer, even from the U.B. thing:
The case is tha if you increment a value and compare the new value with the last, you always get a greater value, except on an overflow (in this case you'll get a value lesser or equal ---you don't have more values greater, that's the case in an overflow) So you can try at least:
int i_old = 0, i = 0;
while (++i > i_old)
    i_old = i;
printf("MAX_INT guess: %d\n", i_old);

After this loop, you will have got the expected overflow, and old_i will store the last valid number.  Of course, in case you go down, you'll have to use this snippet of code:
int i_old = 0, i = 0;
while (--i < i_old)
    i_old = i;
printf("MIN_INT guess: %d\n", i_old);

Of course, U.B. can even mean program stopping run (in this case, you'll have to put traces, to get at least the last value printed)
By the way, in the ancient times of K&R, integers used to be 16bit wide, a value easily accessible by counting up (easier than now, try 64bit integers overflow from 0 up)

A: I would use the properties of two's complement to compute the values.
unsigned int uint_max = ~0U;
signed int int_max = uint_max >> 1;
signed int int_min1 = (-int_max - 1);
signed int int_min2 = ~int_max;

2^3 is 1000. 2^3 - 1 is 0111. 2^4 - 1 is 1111.
w is the length in bits of your data type.
uint_max is 2^w - 1, or 111...111. This effect is achieved by using ~0U.
int_max is 2^(w-1) - 1, or 0111...111. This effect can be achieved by bitshifting uint_max 1 bit to the right. Since uint_max is an unsigned value, the logical shift is applied by the >> operator, means it adds in leading zeroes instead of extending the sign bit.
int_min is -2^(w-1), or 100...000. In two's complement, the most significant bit has a negative weight!
This is how to visualize the first expression for computing int_min1:
...
011...111   int_max          +2^(w-1) - 1
100...000   (-int_max - 1)   -2^(w-1)      == -2^(w-1) + 1 - 1
100...001   -int_max         -2^(w-1) + 1  == -(+2^(w-1) - 1)
...

Adding 1 would be moving down, and subtracting 1 would be moving up. First we negate int_max in order to generate a valid int value, then we subtract 1 to get int_min. We can't just negate (int_max + 1) because that would exceed int_max itself, the biggest int value.
Depending on which version of C or C++ you are using, the expression -(int_max + 1) would either become a signed 64-bit integer, keeping the signedness but sacrificing the original bit width, or it would become an unsigned 32-bit integer, keeping the original bit width but sacrificing the signedness. We need to declare int_min programatically in this roundabout way to keep it a valid int value.
If that's a bit (or byte) too complicated for you, you can just do ~int_max, observing that int_max is 011...111 and int_min is 100...000.
Keep in mind that these techniques I've mentioned here can be used for any bit width w of an integer data type. They can be used for char, short, int, long, and also long long. Keep in mind that integer literals are almost always 32-bits by default, so you may have to cast the 0U to the data type with the appropriate bit width before bitwise NOTing it. But other than that, these techniques are based on the fundamental mathematical principles of two's complement integer representation. That said, they won't work if your computer uses a different way of representing integers, for example ones' complement or most-significant sign-bit.

A: The assignment says that "printing appropriate values from standard headers" is allowed, and in the real world, that is what you would do.  As your prof wrote, direct computation is harder, and why make things harder for its own sake when you're working on another interesting problem and you just want the result?  Look up the constants in <limits.h>, for example, INT_MIN and INT_MAX.
Since this is homework and you want to solve it yourself, here are some hints.
The language standard technically allows any of three different representations for signed numbers: two's-complement, one's-complement and sign-and-magnitude.  Sure, every computer made in the last fifty years has used two's-complement (with the partial exception of legacy code for certain Unisys mainframes), but if you really want to language-lawyer, you could compute the smallest number for each of the three possible representations and find the minimum by comparing them.
Attempting to find the answer by overflowing or underflowing a signed value does not work!  This is undefined behavior!  You may in theory, but not in practice, increment an unsigned value of the same width, convert to the corresponding signed type, and compare to the result of casting the previous or next unsigned value.  For 32-bit long, this might just be tolerable; it will not scale to a machine where long is 64 bits wide.
You want to use the bitwise operators, particularly ~ and <<, to calculate the largest and smallest value for every type.  Note: CHAR_BITS * sizeof(x) gives you the number of bits in x, and left-shifting 0x01UL by one fewer than that, then casting to the desired type, sets the highest bit.
For floating-point values, the only portable way is to use the constants in <math.h>; floating-point values might or might not be able to represent positive and negative infinity, are not constrained to use any particular format.  That said, if your compiler supports the optional Annex G of the C11 standard, which specifies IEC 60559 complex arithmetic, then dividing a nonzero floating-point number by zero will be defined as producing infinity, which does allow you to "compute" infinity and negative infinity.  If so, the implementation will #define __STDC_IEC_559_COMPLEX__ as 1.
If you detect that infinity is not supported on your implementation, for instance by checking whether INFINITY and -INFINITY are infinities, you would want to use HUGE_VAL and -HUGE_VAL instead.

A: #include <stdio.h>

int main() {
    int n = 1;
    while(n>0) {
     n=n<<1;
    }
    int int_min = n;
    int int_max = -(n+1);
    printf("int_min is: %d\n",int_min);
    printf("int_max is: %d\n", int_max);

    return 0;
}

A:     unsigned long LMAX=(unsigned long)-1L;
    long SLMAX=LMAX/2;
    long SLMIN=-SLMAX-1;

If you don't have yhe L suffix just use a variable or cast to signed before castong to unsigned.
For long long:
    unsigned long long LLMAX=(unsigned long long)-1LL;


text:
Q: UnauthorizedAccessException on comPort.Open() when using usb Bluetooth dongle I have an unity/c# app which utilizes com ports to comunicate with a custom bluetooth device. The connection with serial ports works fine when using a stock/inbilt/OE bluetooth device in any computer I tested. When using a usb bluetooth adapter(BT dongle you plug into a usb port), I get an UnauthorizedAccessException when calling serialPort.Open().
The dongle finds my bluetooth device in win , I can see the outgoing serial port name. Have tryed making a plain WindowsFormsApp to figure out timings and delays but it is the same. No matter what I do  there is the same exception on .Open() method.
The simplified code would goes like:
SerialPort serialPort = new SerialPort(@"\\.\COM3" , 9600);
serialPort.Open();

I have seen and am not dupicating:
why is access to com port denied?
Access to the port is denied with USB Bluetooth adapter
It's just that they dont solve anything.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Не работает нахождение факториала Python Не могу понять, почему не работает нахождение факториала, сижу туплю. При положительном вводе выводит 0, при отрицательном и 0 выводит введённое число. Версия - 3.10.4
val = int( input('Введите число: ') )
result = val

while val > 0:
    val -= 1
    result *= val

print(result)

A: while val > 1:
    ...

В конце (когда val = 1) вы делаете val -= 1 и получается, что val = 0. Тогда result * 0 = 0


text:
Q: Adding counts from one dataframe to another dataframe on corresponding row I would like to count the number of record in dataframe2 and add the count to the corresponding rows in dataframe1.
The first one (df1)

Road
RoadNo
Count

A
1
0

A
2
0

B
1
0

B
2
0

The second one (df2)

Road
RoadNo

A
1

A
1

A
1

A
2

A
2

B
1

The expected output is to count the number of records in dataframe2 and add that number to the corresponding Road and RoadNo rows in dataframe1.
Expected Output:

Road
RoadNo
Count

A
1
3

A
2
2

B
1
1

B
2
0

Is there a function in Pandas or Python that can help me with this operation? Do I need to create two tables in the database and execute the SQL query to perform this operation? Many Thanks!

A: You could first count the values from df2 for all Road and RoadNo pairs and then join the resulting data frame to df1:

df1 = pd.DataFrame(data={"Road":["A", "A", "B", "B"],   "RoadNo": [1, 2, 1, 2], "Count":[0, 0, 0, 0]})

df2 = pd.DataFrame(data={"Road":["A", "A", "A", "A", "A", "B"], "RoadNo": [1, 1, 1, 2, 2, 1]})

merge_df = df2.value_counts(["Road", "RoadNo"]).reset_index().rename(columns={0: "Count"})
expected_df = pd.merge(left=df1.drop(columns=["Count"]), right=merge_df, on=["Road", "RoadNo"], how="left").fillna(0).astype({"Count": "int32"})
expected_df

---------------------------------
    Road RoadNo Count
0   A    1      3
1   A    2      2
2   B    1      1
3   B    2      0
---------------------------------


text:
Q: mysql optimization - copy or serialized old rows Suppose i have a simple table with this columns:
|    id      |    user_id    |   order_id |
About 1,000,000 rows is inserted to this table per month and as it is clear relation between user_id and order_id is 1 to M.
The records in the last month needed for accounting issues and the others  is just for showing order histories to the users.To archive records before last past month,i have two options in my mind:
first,create a similar table and each month copy old records to it.so it will  get bigger and bigger each month according to growth of orders.
second,create a table like below:
|    id      |    user_id    |   order_idssss |
and each month, for each row to be inserted to this table,if there exist user_id,just update order_ids and add new order_id to the end of order_ids.
in this solution number of rows in the table will be get bigger according to user growth ratio.
suppose for each solution we have an index on user_id.
.
Now question is which one is more optimized for SELECT all order_ids per user in case of load on server.
the first one has much more records than the second one,but in the second one some programming language is needed to split order_ids.

A: The first choice is the better choice from among the two you have shown. With respect, I should say your second choice is a terrible idea.
MySQL (with all SQL dbms systems) is excellent at handling very large numbers of rows of uniformly laid out (that is, normalized) data.
But, your best choice is to do nothing except create appropriate indexes to make it easy to look up order history by date or by user.  Leave all your data in this table and optimize lookup instead.
Until this table contains at least fifty million rows (at least four years' worth of data), the time you spend reprogramming your system to allow it to be split into a current and an archive version will be far more costly than just keeping it together.
If you want help figuring out which indexes you need, you should ask another question showing your queries. It's not clear from this question how you look up orders by date.

A: In a 1:many relationship, don't make an extra table.  Instead have the user_id be a column in the Orders table.  Furthermore, this is likely to help performance:
PRIMARY KEY(user_id, order_id),
INDEX(order_id)

Is a "month" a calendar month?  Or "30 days ago until now"?
If it is a calendar month, consider PARTITION BY RANGE(TO_DAYS(datetime)) and have an ever-increasing list of monthly partitions.  However, do not create future months in advance; create them just before they are needed.  More details: http://mysql.rjweb.org/doc.php/partitionmaint
Note: This would require adding datetime to the end of the PK.
At 4 years' worth of data (48 partitions), it will be time to rethink things.  (I recommend not going much beyond that number of partitions.)
Read about "transportable tablespaces".  This may become part of your "archiving" process.
Use InnoDB.
With that partitioning, either of these becomes reasonably efficient:
WHERE user_id = 123
  AND datetime > CURDATE() - INTERVAL 30 DAY

WHERE user_id = 123
  AND datetime >= '2017-11-01'  -- or whichever start-of-month you need

Each of the above will hit at most one non-empty partition more than the number of months desired.
If you want to discuss this more, please provide SHOW CREATE TABLE (in any variation), plus some of the important SELECTs.


text:
Q: SQL State : 90057, Message : Constraint "PRIMARY KEY | UNIQUE (USERNAME)" not found; SQL statement: I am using h2 in memory DB, I have small spring boot application.
When trying to run test I am getting error:
java.lang.IllegalStateException: Failed to load ApplicationContext

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.internal.command.DbMigrate$FlywayMigrateException: Migration V1.0.1__create_authorities_table.sql failed
-----------------------------------------------------
SQL State  : 90057
Error Code : 90057
Message    : Constraint "PRIMARY KEY | UNIQUE (USERNAME)" not found; SQL statement:

So it says that Flyway can't build it.
I have only two sql files:
V1.0.0__create_user_table.sql
CREATE TABLE users
(
    id IDENTITY PRIMARY KEY,
    username            VARCHAR(50) NOT NULL,
    password        VARCHAR(68) NOT NULL,
    enabled BOOLEAN NOT NULL
);

and V1.0.1__create_authorities_table.sql:
CREATE TABLE authorities (
                             username VARCHAR(50) NOT NULL,
                             authority VARCHAR(50) NOT NULL,
                             FOREIGN KEY (username) REFERENCES users(username)
);

CREATE UNIQUE INDEX ix_auth_username on authorities (username,authority);

I see that Flyway doesn't like FOREIGN KEY (username) REFERENCES users(username) so I also tried with ALTER TABLE authorities ADD FOREIGN KEY (username) REFERENCES users(username) but still doesn't work. I checked that when I just remove adding FOREIGN KEY then tests are green - no errors.
Seems like both ways from this: https://stackoverflow.com/a/41515905/4952262 are failing for me - what am I doing wrong here?

A: Referential constraints may reference only unique sets of columns, a primary key or unique constraint on them is required, so you need to create a unique constraint on users(username) to allow references to this column from referential constraints.
You can simply add an inline constraint to definition of this column:
CREATE TABLE users
(
    …
    username            VARCHAR(50) NOT NULL UNIQUE,
    …

It will be better to remove username column from authorities table and add something like user_id BIGINT REFERENCES users(id) instead of it, however, duplication of long values between tables isn't a good practice.


text:
Q: How can I extract several sets of pixel coordinates (u, v) from an image and store them in a matrix? For example, if I were to use the following code for a photo in my MATLAB path:
imtool('Vision.bmp')

the following figure would load:
MATLAB Image with Pixel Coordinates in Bottom Left Corner
Based on where I hover my mouse on this image, the pixel coordinates in the bottom left corner change. I want to be able to extract the coordinates from this image and store them in a matrix, so that later on I can extract the same data - from the image I specified - using this newly created matrix.
Fair warning, I've just started to learn to code.


text:
Q: ObjectiveC+SDWebImageView : Error Domain=NSURLErrorDomain Code=400 "The operation couldn't be completed. (NSURLErrorDomain error 400.)" I've gotten a secured image URL from the server as follows:
https://jointeffort-dev-test.s3.amazonaws.com/11316b6e-9824-418a-869e-ca4c1a453145.jpg?AWSAccessKeyId=AKIAJITHUU5FSWYPBZIA&Expires=1454576763&Signature=KogwFiMdpB%2B5scNI0MkDin7jTmE%3D

I'm trying to load image view with that url using the SDWebImageView i got the following error
Error Domain=NSURLErrorDomain Code=400 "The operation couldn't be completed. (NSURLErrorDomain error 400.)"
I can able to load the images from normal imageURLs but i could n't load this kind of url which is having AccessKeyId like the above url.
Can anyone help me please.. Thanks in advance.
I have tried the following codes.. but i did nt get image on image view (URL is working fine)
Code 1:
[imageView sd_setImageWithURL:[NSURL URLWithString:imageURL] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL)
    {
        if (error)
        {
            NSLog(@"error and image url  %@, %@",error,imageURL);
        }
        else
        {
            NSLog(@"image success = %@",image);
        }
    }];

Code 2:
[imageView sd_setImageWithURL:[NSURL URLWithString:imageURL]
                 placeholderImage:[UIImage imageNamed:@"placeholder"]
                          options:SDWebImageRefreshCached];

A: Please use SDWebImageRetryFailed for options when you set image.
I've also faced this issue. This error suggest that Access is Denied for that image.
This is because, you are not able to access the image from amazon server, OR image itself is not exists on server.
You can also inform your server team to send the exact image URL from amazon server.


text:
Q: What does flash.discard do? What's the difference from flash.clear()? I haven't found any documentation on flash.discard(). What does it do?

A: After looking at the code, this is what I understand:

*

*The Flash data is ultimately for storing data between requests.

*Since Play is stateless, that state is saved in a session cookie, which is send to the client and send back with the next request.

*The data Map is the data that comes from the client via the cookie.

*The out Map is the data that the Play app writes to the Flash instance.

*If the data changed, the data in the out Map is used to build the content of the cookie to send back to the client.

So from this, I would say, that flash.discard() is used to throw away everything that would go to the client, and flash.clear() is used to throw away everything that came from the client...

A: That's a good question. While I don't know the answer either, the source code at github should help:
https://github.com/playframework/play/blob/master/framework/src/play/mvc/Scope.java
A quick glance shows the Scope keeps two hashmaps, one named data and other named out.
They both store the same information. But the flash.clear() is acting upon data and flash.discard() is acting upon out... Funny...
Better call both, just in case =)


text:
Q: Create an array of text fields using data from a database and use the values from the fields to do calculate I would like to fetch items and item prices from database and use it to create an array of input fields for quantity and amount. Then use Jquery to automatically fetch the values of quantity as I type and multiply it by the price to display the amount in the amounts field for each item.
At the same time, the totals value (which is sum of all amounts) should also be displayed.
This is restricted to only the items that have been checked (selected).

        Material Name
        Quantity
        Unit Price
        Amount
        Currency

    <?php
    foreach($database_result as $value){
    ?>

            <input type="checkbox" name="checkboxes[]" value="<?php echo $row['price']."".$row['item_name'] ?>">

        <?php echo $row['item_name'] ?>

            <input name="qnty[]" id="qnty">

            <input name="price" class="form-control" value="<?php echo $row['price']) ?>" id="price">

            <input name="total_amount[]" class="text form-control" readonly="readonly" id="total_amount">

      <?php } ?>

        Total Amount

A: First thing is the inputs should have different ids.
Now, you can use onchange event to call a function when input value changes. You can use plain javascript for that. Here's an example:

<input name="qnty[]" onchange="updatePrice('1')" id="qnty1">
<input name="price" value="1" onchange="updatePrice('1')" id="price1">
<input name="total_amount[]" id="total1">

The 1 corresponds to row number, so you would need to change your PHP code so it has a row number (can be just a simple $i=1; before the loop and $i++; in the end of every loop iteration).


text:
Q: Same hardware cluster If I have two databases and views in one in which both databases are JOIN'ed or UNION'ed is this an issue for for GCSql? This feature according to MySQL only requires that both databases remain within the same hardware cluster.
I am not totally clear on what constitutes a hardware cluster, but how does that relate to google SQL instances, etc?

A: Each Google Cloud SQL instances has a single MySQL instance at any one time. The data is replicated to multiple locations when that single MySQL instance writes it to persistent storage -- this means that the instance can failover to a new location if there is a problem.
There isn't any hardware clustering in the sense used here.


text:
Q: Calculate time difference between current and future time I want to calculate time difference in milliseconds from current time of a day(11 am , 1 october,2012) and time at midnight for the same day (11 pm 59 m 59s , 1 october , 2012.
I have tried this
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.SECOND, 59);
    cal.add(Calendar.HOUR, 23);
    cal.add(Calendar.MINUTE, 59);
        cal.getTime().getTime() - today.getTime();

here today is the current date.
But when i print long values of cal and today , the time difference if of 86400 approx one day.

A: You can set your date to newly created Calendar instance..
And then compare it with current instance using getTimeInMillis()
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.DATE, 1);
cal.set(Calendar.MONTH, 9);
cal.set(Calendar.YEAR, 2012);

long difference = cal.getTimeInMillis() - Calendar.getInstance().getTimeInMillis();

A: Use cal.set() instead of cal.add()
Calendar cal = Calendar.getInstance();
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.HOUR, 23);
cal.set(Calendar.MINUTE, 59);

long diff = cal.getTime().getTime() - today.getTime();


text:
Q: Why it shows the error: Error: Target container is not a DOM element, when creating a ReactDOM.createPortal() and pass a const variable On a tutorial about ReactJS and context API, I was trying to render a Modal class by creating a const inside a class extended by React.Component
import React from 'react';
import ReactDOM from 'react-dom';
import './style.scss';
import { AppContext } from '../../context/appContext';

class Modal extends React.Component {
    render() {
        const node = (

modal

        );

        return ReactDOM.createPortal(node, document.getElementById('modal'));
    }
}

Modal.contextType = AppContext;

export default Modal;

And using this class on a layout class also extended of React.Component and using the ReactDOM by
import Modal from '../modal';
<Modal />

But when I tried to render it, it gave me the error that the const node I created, it's not a DOM element, also on the tutorial I followed to do this, he hasn't any error.
Error: Target container is not a DOM element.
createPortal$$1 [as createPortal]
> 17 |         return ReactDOM.createPortal(node, document.getElementById('modal'));
View compiled
▶ 16 stack frames were collapsed.


text:
Q: Where do chrome/chromium store search keywords? I've setup a number of special search keywords, such as "yt" so I can type "yt foo" in the URL bar and have it search youtube for "foo". Unlike just about everything else, chrome and chromium don't sync these with your google account. I'd like to setup syncing for these myself, but grepping through ~/.config/chromium I can't find any reference to the keyword searches I've setup. I assume they're stored in binary format somewhere... any way to extract them, save them, and be able to import them on another box later? I see a sqlite3 database in there so I figure it might be doable.

A: The Chrome search keywords are stored in the Web Data SQLite file inside the User Data folder. The exact path depends on the OS you are using:
macOS
~/Library/Application Support/Google/Chrome/Default/Web Data

Windows XP
C:\Documents and Settings\<username>\Local Settings\Application Data\Google\Chrome\User Data\Default\Web Data

Windows Vista / 7 / 10
C:\Users\<username>\AppData\Local\Google\Chrome\User Data\Default\Web Data

Linux
~/.config/google-chrome/Default/Web Data

A: Inside that Web Data SQLite database file, the table keywords has the list of search keywords.
You can edit it using anything that can use SQLite databases (e.g. by hand in Microsoft Access with an SQLite ODBC plugin, scripting a solution with Python's sqlite3 module, etc.)
Unfortunately, Chrome keeps the file locked while it is running, so I don't think an automatic sync solution outside of Chrome would be possible.
If you really want the whole skinny on Chrome's Web Data database, you could comb through that part of the Chromium source code for hints.


text:
Q: Remove top line of output PowerShell I am trying to get the session ID but the below output is giving me the ID column name. If I use match it gives me the correct value as the output doesn't seem to have the column names in.
How do I remove the top line so I can just get the IDs value?
$sessionID = ( (quser | Where-Object { $_ -notmatch 'username' } ) -split ' +')[3]

logoff $sessionID

A: Assuming that your usernames contain no spaces (if they did, it would be highly unusual):
To get the ID of the first user session listed by quser:
(-split (quser)[1])[2]

To get all user-session IDs:
quser | Select-Object -Skip 1 | ForEach-Object { (-split $_)[2] }

Cast to [int] (...) / [int[]] (...) if you want the extracted IDs to be numbers.

As for what you tried:
The only immediate problem with your approach was use of index [3] instead of [2] - since array indices are 0-based, [2] is needed to retrieve the 3rd element, which is the Id field.
However, instead of using a -match operation to skip the header line, it is easier to simply skip the first line, as shown above:

*

*(quser)[1] returns the second line only, i.e. the first data line.

*Similarly, Select-Object -Skip 1 skips the first input object, i.e. the header line (PowerShell streams the (stdout) output from external programs line by line).
The unary form of the -split operator, as used at the top, is a convenient way to split by nonempty runs of whitespace (ignoring leading and trailing whitespace).


text:
Q: Linq IEnumerable to entity cast error Please refer to my following code. An exception error occurs at the return value.
Unable to cast object of type 'System.Data.Objects.ObjectQuery1[VB$AnonymousType_23[System.String,System.String,System.String]]' to type 'System.Collections.Generic.List`1[MyEntities.stk_cust]'.
Public Function GetCustomerProdListToGrid() As List(Of stk_cust)
        Dim result = From s In Db.stk_cust
             Group Join d In Db.s_armaster On d.dbcode Equals s.dbcode Into stk_ar = Group
             From d In stk_ar.DefaultIfEmpty()
             Order By s.stk_code, s.dbcode Ascending
             Select s.stk_code, s.dbcode, d.name
   Return result
 End Function

I've tried the following method at select section but error turns out the same
Select New With {.stk_code = s.stk_code,
        .dbcode = s.dbcode,
        .name = d.name
  }

Any help is highly appreciated.

A: If you want to return a List(Of stk_cust) you need to create instances of stk_cust instead of using an anonymous type. Presuming that those are the properties:
....
Select New stk_cust() With {
      .stk_code = s.stk_code,
      .dbcode = s.dbcode,
      .name = d.name
}

Return result.ToList()

Maybe you could also select the object  directly without needing to create a new one:
Dim result = From s In Db.stk_cust
             Group Join d In Db.s_armaster On d.dbcode Equals s.dbcode Into stk_ar = Group
             From d In stk_ar.DefaultIfEmpty()
             Order By s.stk_code, s.dbcode Ascending
             Select s
Return result.ToList()


text:
Q: Unable to install GCC using anaconda This is output of the command conda install gcc:
    Solving environment: failed

PackagesNotFoundError: The following packages are not available from current channels:

  - gcc-6

A: I had to install two conda packages to fix this issue:
$ conda install gcc_linux-64
$ conda install gxx_linux-64

A: I'm not sure how exactly the packages relate, but I needed to install the gcc package to resolve some sort of load error. Given that gcc didn't produce any results, I ran a quick
$ conda search gcc

Which yielded, among other things, gcc_linux-64. After
$ conda install gcc_linux-64

My issue went away, despite the fact that which gcc still pointed to the system install ♂


text:
Q: How to get files under Code tab in a job using AzureML python SDK I'm trying to access the files/artifacts located in the code tab under an AzureML job. When using the azureml.core.run.Run class, the only methods suitable could be get_file_names() and download_files but they only list files under the Outputs + logs tab.
Is there a workaround to do this?

A: From Designer we can export the code. For Automl we could see the image as show below. you can use the run.download_files.


text:
Q: Small bug in geometry.sty Complete

Top Left Corner

Top Right Corner

Bottom Left Corner

Bottom Right Corner

\documentclass[dvipsnames,dvips,cmyk]{minimal}
\usepackage{xcolor,calc}
\usepackage[%
paperwidth=30mm,
paperheight=30mm,
textwidth=25mm,
textheight=25mm,
showframe]{geometry}
\setlength{\fboxsep}{5mm}
\setlength{\fboxrule}{5mm}
\usepackage{lipsum}
\begin{document}
\topskip0pt%
\noindent\color{red}\fbox{\parbox{\textwidth-2\fboxsep-2\fboxrule}{\color{green}\rule{5mm}{5mm}}}
\end{document}

EDIT 1:
Questions:

*

*These asymmetric frame rules are intentionally made or bugs?

*\textwidth equals to the horizontal distance between inner edges of the frame rules or outer edges of the frame rules?

EDIT 2:

*I think the frame enclosing the text content is created partially/separately using 4 rules rather than using \fbox (with \fboxsep set to zero, of course). Can it be changed to use \fbox ?

*If we use PSTrick's terminology in this discussion,  I think the box enclosing the text content used dimen=inner, right? If it is right, then the \textwidth is measured as the horizontal distance between the inner edges of the box. Please kindly confirm whether or not my understanding is correct?

EDIT 3:
Except for the "asymmetric frame rules" produced by geometry.sty, my diagram below reproduce it with some annotations.
The frame produced by geometry.sty seems to expand outward. Thus, the \textwidth equals to horizontal distance between the inner edges of this frame.
Note: scale in mm.

This bug still exists.

A: I'd say that the behaviour seen is a bug in geometry. LaTeX's \fbox also has to use four rules to achieve the effect, but these do join up correctly. So I'd report the issue to the author of geometry and see what he says.
On framing around \textwidth, the frame should be 'outside' of the material (i.e. the TeX box containing the material should actually have a width of \textwidth plus twice the width of the rule used). Again, this is certainly what \fbox does.

A: TeX always thinks in boxes. The reference point is the current point, which is at the start at the very left of each line. When TeX draws a fbox, it draws a vertical bar of width \fboxsep and increases the currentpoint with this value. Then it draws two horizontal rules each of a boxwidth of 0, the reason why the current point isn't increased. Then it inserts a space of \fboxsep which is the same as moving the current point to the right. Then the box contents is inserted and the current point is increased with the width of the box contents. Now the \fboxsepis added again, also with increasing the current point. And now the right vertical bar is drawn and the current point again increased by \fboxrule. The next box, if there is one, starts with its left side at the current point. See also slide 32ff of http://userpages.fu-berlin.de/~latex/PSTricks/DANTE2006.pdf. It is in german, but easy to see, what I mean by setting boxes.

A: I cannot say, that I understand your problem. But here is a slightly changed code, which gives me an expected result:
\documentclass[cmyk]{minimal}
\usepackage{xcolor,calc}
\usepackage[%
paperwidth=30mm,
paperheight=30mm,
textwidth=25mm,
textheight=25mm,
showframe]{geometry}
\setlength{\fboxsep}{5mm}
\setlength{\fboxrule}{5mm}
\begin{document}
\noindent\color{red}\fbox{%
%  \parbox{\linewidth-2\fboxsep-2\fboxrule}{%
  \color{green}\rule{5mm}{5mm}%
%  }
}
\end{document}


text:
Q: Adding variable to df after creatng by mutating I am new to R and have a dummy question.
I want ot creat a numerical variable based on string variable.
the main factor is called icd10
icd10 <- c("v860", "x45", 'C150', 'NA')
df <- data.frame(icd10)
I want to creat a new varaivle called main.
I want to have result like this:
icd10 main
1  v860    2
2   x45    2
3  C150    1
4    NA    NA
I used the following command:
df %>%
mutate(df, main=ifelse(grepl("C", icd10 ) , 1 , 2))
1- It wokrs. But do not know how to fix NA in the new variable.
2-Wben I get the table or print it deosn't show up.
It gives the follwing results:

print(df)
icd10
1  v860
2   x45
3  C150
4    NA

table(df$can2)
< table of extent 0 >

Thanks for help
KZ
I am expecting a quick and easy solution from community


text:
Q: CSOM: WorkflowInteropService is returned null I'm trying to run SP2010 workflow in SP2013 portal and stuck on the nullable interop service...
The following powershell script returns $interopService.ServerObjectIsNull == false, but when it's run in my other test environment it always returns true. Any ideas on the causes and what can I check?
$spContext = new-object Microsoft.SharePoint.Client.ClientContext("http://portal")
$web = $spContext.Web
$spContext.Load($web)
$spContext.ExecuteQuery()
$wfMngr = New-Object Microsoft.SharePoint.Client.WorkflowServices.WorkflowServicesManager($spcontext, $web)
$interopService  = $wfMngr.GetWorkflowInteropService()
$spcontext.ExecuteQuery()
$interopService.ServerObjectIsNull


text:
Q: Is there an easy way to have Powershell always show the actual value? These things drive me nuts:

Is there an easy way to have Powershell just show me the empty string and the list with an empty string in it?

A: For a while I am maintaining a ConvertTo-Expression which converts an (complex) object into a PowerShell expression which eventually can be used to rebuild most objects. It might useful in situations as comparing test results but also to reveal objects. For details see: readme.
Source and installation
The ConvertTo-Expression script can be installed from the PowerShell Gallery:
Install-Script -Name ConvertTo-Expression

As it concerns a standalone script, installation isn't really required. If you don't have administrator rights, you might just download the script (or copy it) to the required location. You might than simply invoke the script using PowerShell dot sourcing:
. .\ConvertTo-Expression.ps1

Example
The following command outputs the same expression as used to build the object:
$Object = [Ordered]@{
    'Null' = $Null
    'EmptyString' = ''
    'EmptyArray' = @()
    'SingleItem' = ,''
    'EmptyHashtable' = @{}
}
ConvertTo-Expression $Object

Note the comment from @Mathias there's no functional difference between "one string" and "an array of one string", the pipeline consumes 1 string either way. PowerShell is not node which is described here: PowerShell enumerate an array that contains only one inner array. Some objects might be really different than you expect.
See also: Save hash table in PowerShell object notation (PSON)

A: This is PowerShell, not Node. So it's not JavaScript or JSON. Also, PowerShell is not Bash or CMD any other regular text-based shell. PowerShell works with objects. .NET objects, in particular. And how objects are represented as text is ... quite a matter of taste. How to represent null? Of course: nothing. How to represent an empty string? Nothing, either. An empty array ... you get my point.
All pipeline output is by default send to Out-Default. In general, the way objects are represented can be controlled by format files: about_Format.ps1xml and about_Types.ps1xml. From PowerShell 6 upwards, the default formats are compiled into the source code, but you can extend them. How you do so, depends on your personal taste. Some options were already mentioned ConvertTo-Json "", ConvertTo-Json @("")), but this would be veryyy JSON-specific.
tl;dr Don't care too much about how objects are represented textually. As you see, there are many possible ways to do so, and also some others. Just make sure your scripts are always object-oriented.

A: You mean like Python's repr() function? A serialization? "Give me a canonical representation of the object that, when property evaluated, will return an object of the type originally passed?" No, that's not possible unless you write it yourself or you serialize it to XML, JSON, or similar. That's what the *-CliXml and ConvertTo-*/ConvertFrom-* commands are for.
On Powershell 7:
PS C:\> ''.Split(',') | ConvertTo-Json -Compress -AsArray
[""]
PS C:\> '1,2,3,,5'.Split(',') | ConvertTo-Json -Compress -AsArray
["1","2","3","","5"]

The closest would be the ToString() common method. However, that's intended for formatting output and typecasting, not canonical representations or serializations. Not every object even has a string representation that can be converted back into that object. The language isn't designed with that in mind. It's based on C#, a compiled language that favors binary serializations. Javascript requires essentially everything to have a string serialization in order to fulfill it's original design. Python, too, has string representations as fundamental to it's design which is why the repr() function is foundational for serialization and introspection and so on.
C# and .Net go the other way. In a .Net application, if you want to specify a literal empty string you're encouraged to use String.Empty ([String]::Empty in Powershell) because it's easier to see that it's explicit. Why would you ever want a compiled application to tell the user how the canonical representation of an object in memory? You see why that's not a useful thing for C# even if it might be for Powershell?


text:
Q: Copy workbook one by one into archive folder I used the below code which perfectly does its job of picking up all the files and moving them into Archive folder. However, I am looking for files to be picked up one by one get the date into Target workbook and move it to archive folder and this process goes on till the last workbook. I have used the below code to copy the data and have called the Sub routine to perform the Archive.
But it moves all the file at once into Archive folder in the first iteration.
Sub Test()
    Dim xWb As Workbook
    Dim xToBook As Workbook
    Dim xStrPath As String
    Dim xFileDialog As FileDialog
    Dim xFile As String
    Dim xFiles As New Collection
    Dim I As Long
    Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
    xFileDialog.AllowMultiSelect = False
    xFileDialog.Title = "Select a folder [Kutools for Excel]"
    If xFileDialog.Show = -1 Then
        xStrPath = xFileDialog.SelectedItems(1)
    End If
    If xStrPath = "" Then Exit Sub
    If Right(xStrPath, 1) <> "\" Then xStrPath = xStrPath & "\"
    xFile = Dir(xStrPath & "*.xlsx")
    If xFile = "" Then
        MsgBox "No files found", vbInformation, "Kutools for Excel"
        Exit Sub
    End If
    Do While xFile <> ""
        xFiles.Add xFile, xFile
        xFile = Dir()
    Loop
    Set xToBook = ThisWorkbook
    If xFiles.Count > 0 Then
        For I = 1 To xFiles.Count
            Set xWb = Workbooks.Open(xStrPath & xFiles.Item(I))
            xWb.Worksheets(1).Copy after:=xToBook.Sheets(xToBook.Sheets.Count)
            On Error Resume Next
            ActiveSheet.Name = xWb.Name
            On Error GoTo 0
            xWb.Close False
            '**Call MoveFiles_3**
        Next I
    End If
End Sub

Sub MoveFiles_3()
    Dim fso As Object, d As String, ext, x
    Dim srcPath As String, destPath As String, srcFile As String
    srcPath = "C:\Users\userfolder\Desktop\Test Macro\"
    destPath = "C:\Users\userfolder\Desktop\Archive Test\"
    Set fso = CreateObject("Scripting.FileSystemObject")
    ext = Array("*.xlsx")
    MsgBox Dir(srcPath)
    For Each x In ext
        d = Dir(srcPath & x)
        Do While d <> ""
            srcFile = srcPath & d
            fso.CopyFile srcFile, destPath & d
            Kill srcFile
        d = Dir
        Loop
    Next x
    MsgBox "done"
End Sub

A: Try below code.  I add two lines in your Test and MoveFiles_3 is needless.
Sub Test()
    Dim xWb As Workbook
    Dim xToBook As Workbook
    Dim xStrPath As String
    Dim xFileDialog As FileDialog
    Dim xFile As String
    Dim xFiles As New Collection
    Dim I As Long
    Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
    xFileDialog.AllowMultiSelect = False
    xFileDialog.Title = "Select a folder [Kutools for Excel]"
    If xFileDialog.Show = -1 Then
        xStrPath = xFileDialog.SelectedItems(1)
    End If
    If xStrPath = "" Then Exit Sub
    If Right(xStrPath, 1) <> "\" Then xStrPath = xStrPath & "\"
    xFile = Dir(xStrPath & "*.xlsx")
    If xFile = "" Then
        MsgBox "No files found", vbInformation, "Kutools for Excel"
        Exit Sub
    End If
    Do While xFile <> ""
        xFiles.Add xFile, xFile
        xFile = Dir()
    Loop
    Set xToBook = ThisWorkbook
    If xFiles.Count > 0 Then
        For I = 1 To xFiles.Count
            Set xWb = Workbooks.Open(xStrPath & xFiles.Item(I))
            xWb.Worksheets(1).Copy after:=xToBook.Sheets(xToBook.Sheets.Count)
            On Error Resume Next
            ActiveSheet.Name = xWb.Name
            On Error GoTo 0
            xWb.Close False

            Name xStrPath & xFiles.Item(I) As "C:\Users\userfolder\Desktop\Archive Test\" & xFiles.Item(I) ' new added'
            Kill xStrPath & xFiles.Item(I) ' new added'
        Next I
    End If
End Sub


text:
Q: Disable next steps in array but still have previous indexes accessible I am rendering some navigation steps in React and am mapping through an array. Currently I have a isDisabled prop as a boolean that will take pointer events away if the condition is met. I want to be able to have previous links/steps in the array be accessible but have future steps disabled. All my logic seems to get some of them working but usually will skip one. I've tried something like
isDisabled = i > (i + stepLength - 1) % stepLength

where stepLength is just the length of the array (which is 4). All questions I've seen answered have just been for the immediate next or previous step and doesn't account for multiple previous or future indexes in the array.


text:
Q: Is $\mathbb{Z}[\frac{1}{p}]$ a projective $\mathbb{Z}$-module, where $p$ is a fixed prime? Is $\mathbb{Z}[\frac{1}{p}]=\{\sum_{i=0}^n \frac{a_i}{p^i} : a_i\in \mathbb{Z},  n \in \mathbb{N}\cup\{0\}\}$ projective for any fixed prime $p$?
I don't know how you would go about proving this. Can we simple say $\{1, p^{-1}, p^{-2}, \dots \}$ is a basis so that $\mathbb{Z}[\frac{1}{p}]$ is free over $\mathbb{Z}$?

A: A projective $\mathbb Z$-module is in particular a submodule of some free $\mathbb Z$-module $\mathbb Z^{(I)}$.
But a non-zero element of a free $\mathbb Z$-module can only be divided by finitely many integers, while any element of $\mathbb Z[\frac 1p]$ can be divided by the infinitely many  $p^r \: (r\in \mathbb N)$.

A: No. If it were projective, it would actually free, and no two elements of $\mathbf Z\biggl[\dfrac1p\biggr]$ are linearly independent.
Indeed two elements can be written as $x=\dfrac a{p^r}$,  $y=\dfrac b{p^s}$ and
$$bp^r\cdot x-ap^s\cdot y=0.$$
Thus if  $\mathbf Z\biggl[\dfrac1p\biggr]$ is free, it has rank $1$, so that   $\mathbf Z\biggl[\dfrac1p\biggr]=\mathbf Z$, and  $p$ is a unit in $\mathbf Z$. That would be great news.
Edit: The same kind of argument shows no ring of fractions of an integral domain $R$ can be a free $R$-module.


text:
Q: FOL and Conjuctive Normal Form Conversion I see the CNF from following firs order logic:
$ \forall x [ \forall y [ \neg A(y) \vee B(x,y) \Rightarrow  [ \neg \forall y B(y,x) ] ] $
is equivalent to :
$ (A(f(x)) \vee \neg B(g(x),x)) \wedge (\neg B (x,f(x)) \vee \neg B(g(x),x))   $
How this CNF is calculated? i.e: how convert above the FOL sentence to above CNF?
Thanks to all.

A: Assuming that the correct formula is :

$∀x[∀y[¬A(y)∨B(x,y)]⇒[¬∀yB(y,x)]]$ --- (*)

we have that $p \Rightarrow q$ is equivalent to $\lnot p \lor q$; thus (*) is :

$∀x[\lnot ∀y[¬A(y)∨B(x,y)] \lor [¬∀yB(y,x)]]$

i.e. :

$∀x[\exists y \lnot (¬A(y)∨B(x,y)) \lor \exists z (\lnot B(z,x))]$

i.e. to :

$\forall x \exists y \exists z [\lnot (¬A(y)∨B(x,y)) \lor \lnot B(z,x)]$.

Now we apply De Morgan to the left disjunct to get :

$\forall x \exists y \exists z [(A(y) \land \lnot B(x,y)) \lor \lnot B(z,x)]$

and ditribute the right disjunct :

$\forall x \exists y \exists z [(A(y) \lor \lnot B(z,x)) \land (\lnot B(x,y) \lor \lnot B(z,x))]$ ---(§).

The final step is to introduce skolem functions to get rid of existential quantifiers, i.e. remove every existential quantifier in the prefix replacing the corresponding variable with a new $n$-ary function symbol (the so-called "skolem function") where $n$ is the number of universal quantifiers preceding the existential one to be removed.
In the prefix of (§) we have the first existential quantifier : $\exists y$ and the second one : $\exists z$; both are preceded by a single universal quantifier : $\forall x$.
Thus, we need two unary skolem functions $f(x)$ and $g(x)$; they will replace variables $y$ and $z$ respectively, now free after the removal of the leading existential quantifiers, getting :

$\forall x [(A(f(x)) \lor \lnot B(g(x),x)) \land (\lnot B(x,f(x)) \lor \lnot B(g(x),x))]$


text:
Q: comparison operator is not working in twig
*

*problem in comparing dates  in twig.

*case  if event is ongoing or is about to begin within 7 days.
twig code
 {% set  event_startdate=data.detailes.data.event.event_startdate|date("d-m-Y")%}
 {% set  event_enddate=data.detailes.data.event.event_enddate|date("d-m-Y") %}
 {% set upcoming_days =daysdiff(event_startdate)|date('d-m-y') %}
 {% set stdate= "now"|date('d-m-y') %}

   {% if event_startdate >stdate and event_startdate < upcoming_days  %}

 // condition true
     {% else %}
      // condition false
    {%endif %}

acmextension.php (custom function)
 public function daysdiff($date)
{

$date = date('Y-m-d', strtotime($date. ' + 7 days'));

return $date;
}

*

*date are as follows :
  14-11-2015(event startdate) ,17-06-15(current date) and 21-11-15(7 days addded in startdate).

problem

*

*compare operators is not working in twig.

A: try to not convert the dates to string with twigs date filter
e.g
 {% set upcoming_days =daysdiff(event_startdate) %}

instead of
 {% set upcoming_days =daysdiff(event_startdate)|date("d.m.y") %}


text:
Q: HTML onclick append textbox value to link I have a textbox with id main_category_lan1 as below.
<input type="text" name="main_category_lan1" id="main_category_lan1" Value="Hello">

And I have a link in the same page as below.
 Translator

I want to append the textbox value to the "Onclick link" while clicking the link...
Expected output onclick is ,
 Translator

A: You forgot the closing parenthesis in your onclick attribute. Also, did you mean to use window.open() instead of popup()? This works:
 Translator

http://jsfiddle.net/AXWr8/

A: Try
function openLink() {
    window.open('http://translate.google.com/#en/ta/' +
      document.getElementById('main_category_lan1').value);
}

Translator


text:
Q: MySQL "ALTER IGNORE TABLE" Error In Syntax I am trying to run the query:
ALTER IGNORE TABLE test_table DROP PRIMARY KEY, ADD PRIMARY KEY(id);

test_table is just a temporary table I'm using for testing purposes, and id is a column in it.
The query works fine without the "IGNORE" key word, but when I add it I get the error message:

"Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IGNORE TABLE test_table ADD PRIMARY KEY(id)' at line 1"

How do I fix this? Or how can I run that query and ignore any errors that might occur? Thanks!

A: As of MySQL 5.7.4, the IGNORE clause for ALTER TABLE is removed and its use produces an error. Please check your version


text:
Q: KeyError while trying to create a list from existing list using len() function I am trying to create a list to calculate the number of prices in each list of list.
With the following code:
print data['OtherBids']

I got the following output:

[[0.074, 0.073, 0.072, 0.03, 0.029, 0.024, 0.021, 0.02], [0.02, 0.02, 0.015], [0.026, 0.026, 0.02, 0.02, 0.02, 0.015], [0.021, 0.021, 0.02, 0.017], [0.077, 0.076, 0.074, 0.055, 0.045, 0.021], [0.053, 0.052, 0.051, 0.023, 0.022], [0.016, 0.016]]

Based on a cursory view of the data, we can see that there are 8 elements in the 1st list, 3 in the 2nd list, 6 in the 3rd list and so on ... However, when I tried to using a while loop to generate the data, it returned the following error:
data['number'][a] = len(data['OtherBids'][a])
KeyError: 'number'

and the code that lead to the above error are:
a = 0
b = len(data['OtherBids'])

while a <= b - 1:
    for i in data['OtherBids']:
        data['number'][a] = len(data['OtherBids'][a]).get
    a = a + 1

Anybody know how I should fix it?

A: Your data has no "number" key:
a = 0
b = len(data['OtherBids'])
# add this line
data['number'] = dict()

while a <= b - 1:
    for i in data['OtherBids']:
        # seems to be mistype: len(data['OtherBids'][a]).get
        # I removed .get
        data['number'][a] = len(data['OtherBids'][a])
    a = a + 1

UPD
I found your code too complicated
More pythonic version:
data['number'] = {}
for i, item in enumerate(data['OtherBids']):
    data['number'][i] = len(item)

Inline version:
data['number'] = {i:len(item) for i,item in enumerate(data['OtherBids'])}


text:
Q: Get value from deserialised JSON I have a JSON string which looks like this:
jsonstring = {"XX":["Blah blah"]}

I need to get the 'Blah blah' into a string variable. How do I do this?
Tried doing it this way, but all that returned was '{', so that's not working.
string result = (String)JSON.deserialize(jsonstring, String.Class);

A: Use the JSON.deserializeUntyped to get an Object and you can typecast it further into a Map .
You can then easily start reading the object with key and typecasting it further.
String jsonstring = '{"XX":["Blah blah"]}';

Map<String, Object> m = (Map<String, Object>)JSON.deserializeUntyped(jsonstring);

System.debug((List<Object>)m.get('XX'));

for(Object o : (List<Object>)m.get('XX')) {
   system.debug((String) o);
}


text:
Q: decimal separator in woocommerce to be a comma I have a woocommerce shop in which I have set up my prices (in settings) to have the decimal separator to be a comma instead of a dot (EURO system).
The problem is in the code I need to add. There is this part:
$price_excl_vat = wc_get_price_excluding_tax( $product ); // Unit price excluding VAT

and this
<?php echo $items_string;

where it returns the prices with a dot.
Any tips on how to make it give the prices with a comma?

A: You can use the function number_format( $price_excl_vat, 2, ',', ' ' ); to format your price with the decimal separator set as comma.
http://php.net/manual/en/function.number-format.php
You could also use the woocommerce function wc_price( $price_excl_vat, array( 'decimal_separator' => ',' ) );. This function wil return a formatted price with a currency symbol and the decimal separator set as comma.
http://woocommerce.wp-a2z.org/oik_api/wc_price/


text:
Q: Why does UIIndicator not move away? I use UIActivityIndicator in my app. I have written code for it as follows:
-(void)startSpinner {

    spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    spinner.hidden = NO;
    spinner.frame = CGRectMake(137, 160, 50, 50);
    [spinner setHidesWhenStopped:YES];
    [self.view addSubview:spinner];
    [self.view bringSubviewToFront:spinner];
    [spinner startAnimating];
}

I call this method on the UIButton's action event
and to remove indicator I write the code as follows:
-(void)stopSpinner {

    [spinner stopAnimating];
    [spinner removeFromSuperview];
    [spinner release];
}

on click on the button indicator appears but when I call -(void)stopSpinner method in view
willAppear the indicator does not disapppear.
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self stopSpinner];

}

even I debug the code and I found that control also goes to the stopSpinner();
I can't understand what is the problem.
plz help...

A: You might have potential leak in startSpinner because you always create UIActivityIndicatorView without releasing it. Change your method like this:
-(void)startSpinner {
    if (spinner){
        [spinner removeFromSuperview];
        [spinner release]; spinner = nil;
    }
    spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    spinner.frame = CGRectMake(137, 160, 50, 50);
    [spinner setHidesWhenStopped:YES];
    [self.view addSubview:spinner];
    [spinner startAnimating];
}

For stopping animation assign stopSpinner for another UIButton action. Cos viewWillAppear will fired early then you tap on any button.
ps. maybe you mean viewWillDisappear?


text:
Q: Numerous Hidden Files show on SdFat library ls() My goal is to be able to navigate through a file system on an SD card and pick out certain file types and display them to the user. When I execute sd.ls(LS_R) on the SdFat library, it shows lots of hidden files. I can deal with most of them fine, but some of them give me headaches. Since the library uses the 8.3 naming convention, it truncates the file/folder names that are too long and replaces it with a "~". This is a problem because then, I cannot distinguish between files/folders that are visible and files/folders that are hidden. Are there any known ways to solve this issue?
Here's my code:
#include <SdFat.h>

const uint8_t chipSelect = 10;

SdFat sd;
SdFile file;

void setup()
{
    Serial.begin(9600);
    while (!Serial) {} // wait for Leonardo
    delay(1000);

    if (!sd.begin(chipSelect, SPI_HALF_SPEED)) sd.initErrorHalt();

    sd.ls(LS_R);
    while(1);
}

void loop() {}

Here is my "visible" file system:
Folder1/
    test3.txt
    test4.txt
Folder2/
BearsOutside/
test1.txt
test2.txt
LongFilename.txt

And here is the output:
FOLDER1/
  TEST4.TXT
  TEST3.TXT
TEST2.TXT
~1.TRA
TEST1.TXT
TRASHE~1/
SPOTLI~1/
  STORE-V2/
    F8D581~1/
      PSID.DB
      TM~1.SNO
      TM~1.LIO
      LIO~1.CRE
      TMP.CAB
      CA~1.CRE
      INDEXS~1
      ~1.IND
      ~~2.IND
      ~~~3.IND
      ~~~~4.IND
      ~~~~~5.IND
      ~~~~~~34.IND
      ~~~~~~37.IND
      ~~~~~~40.IND
      ~~~~~~43.IND
      ~~~~~~46.IND
      ~~~~~~48.IND
      ~1.DIR
      LIVE~~~4.IND
      LIVE~~2.IND
      LIVE~~~3.IND
      LIVE~~~5.IND
      LIVE~~66.IND
      LIVE~~69.IND
      LIVE~~73.IND
      LIVE~1.SHA
      LIVE~~79.IND
      LIVE~1.DIR
      LIVE0D~1.SHA
      STORE.DB
      STOR~1.DB
      REVERS~1
      TMPSPO~1.STA
      PERMST~1
      STORE_~1
      JOURNA~1.LIV/
      JOURNA~2.LIV/
        RETIRE.3
      JOURNA~3.LIV/
        RETIRE.4
      JOURNA~4.LIV/
      JOURNA~1.ASS/
      JOURNA~2.ASS/
      JOURNA~1.HEA/
      JOURNA~1.MIG/
      JOURNA~2.MIG/
      JOURNA~1
      JOURNA~1.SCA/
        RETIRE.11
      REVERS~1.SHA
      ~1.SHA
      SHUTDO~1
      JOURNA~1.REP/
      CA~1.MOD
      LIVE~155.IND
      LIVE~158.IND
      0DIREC~1.SHA
      ~~~~~166.SHA
      LIVE~169.IND
      LIVE~172.IND
      LIVE~175.IND
      LIVE~178.IND
      LIVE~181.IND
      LIVE~184.IND
      LIVE~1.IND
      LIVE~190.IND
      LIVE~194.SHA
      STOR~1.UPD
      REVERS~1.UPD
      LIVE~202.IND
      TMPSPO~1.LOC
      LIVE~208.IND
      LIVE~211.IND
      LIVE~215.IND
      LIVE~218.SHA
      LIVE~~2.DIR
      LIVE1D~1.SHA
      LIVE~264.SHA
      LIVE~267.IND
      LIVE~270.IND
      LIVE~274.IND
      LIVE~277.IND
      LIVE~~~3.DIR
      LIVE~~2.SHA
      LIVE~~~3.SHA
      LIVE~~~4.SHA
      LIVE~~~5.SHA
      LIVE~296.SHA
      LIVE~300.SHA
      LIVE2D~1.SHA
      LIVE~308.SHA
      LIVE~327.IND
  STORE-V1/
    VOLUME~1.PLI
  VOLUME~1.PLI
FOLDER2/
BEARSO~1/
LONGFI~1.TXT

So my issue is, how do I distinguish between BEARSO~1/ [BearsOutside], which is not hidden, and SPOTLI~1/, which IS hidden?

A: These files are created automatically by the Mac OSX system... Is it an option for you not to plug the SD card on any Mac? This would solve your problem... ;-)
You could also try to remove them with the Terminal on Mac.

A: unfortunately some of the primitive functions are not directly available with the
SdFat sd;

object. Hence precluding the use of the "ls" function. The following code should accomplish what you want. It passes the sd objects current file to the pointer a directory entry object of pointer p. which then can have its attributes tested to see if they are hidden or other.
Note there is a method to test if a directory entry is long name. However, I do not believe the entry is caching the long name itself.
The below does compile. And 99.5 of it is from working code that I use. I have added the attribute and long file name detection, so it should work.
void ListFiles2(uint8_t flags) {
  // This code is just copied from SdFile.cpp in the SDFat library
  // and tweaked to print to the serial output in html!
  dir_t p;

  sd.vwd()->rewind();
  Serial.println();
  while (sd.vwd()->readDir(&p) > 0) {
    // done if past last used entry
    if (p.name[0] == DIR_NAME_FREE) break;

    // skip deleted entry and entries for . and  ..
    if (p.name[0] == DIR_NAME_DELETED || p.name[0] == '.') continue;

    // only list subdirectories and files
    if (!DIR_IS_FILE_OR_SUBDIR(&p)) continue;

    if ((p.attributes & DIR_ATT_HIDDEN) != DIR_ATT_HIDDEN) continue;

    // print any indent spaces
    Serial.print(F("  "));
    for (uint8_t i = 0; i < 11; i++) {
      if (p.name[i] == ' ') continue;
      if (i == 8) {
        Serial.print('.');
      }
      Serial.print((char)p.name[i]);
    }
    Serial.print(F(" "));

    // print file name with possible blank fill
    for (uint8_t i = 0; i < 11; i++) {
      if (p.name[i] == ' ') continue;
      if (i == 8) {
        Serial.print('.');
      }
      Serial.print((char)p.name[i]);
      if (DIR_IS_LONG_NAME(&p)) {
        Serial.print(F(" long fn"));
      }
    }

    if (DIR_IS_SUBDIR(&p)) {
      Serial.print('/');
    }

    // print modify date/time if requested
    if (flags & LS_DATE) {
      sd.vwd()->printFatDate(p.lastWriteDate);
      Serial.print(' ');
      sd.vwd()->printFatTime(p.lastWriteTime);
    }
    // print size if requested
    if (!DIR_IS_SUBDIR(&p) && (flags & LS_SIZE)) {
      Serial.print(' ');
      Serial.print(p.fileSize);
    }
    Serial.println();
  }
  Serial.println();
}

A: This is a very old question, but it comes up high in google search so I'll provide some updated information:
As of the time of this writing (Fall 2020) a major upgrade to SdFat exists. SdFat-2.0 has been available for several years and even though it continues to be labeled as beta.8 (and is referred to in the ReadMe as an "early beta") there are relatively few known issues and it is in production use at many sites.
I was initially hesitant to adopt it, but it provides so much needed new functionality that eventually I gritted my teeth and took it on. It has turned out to be very easy to integrate and very stable.
SdFat-2.0 includes robust support for ExFat volumes, long filenames, and preallocation of file clusters with a mechanism to guarantee non-blocking writes to the SD card. This solves the long-standing problem with occasional blocking long write latency that used to interfere with data-logging on SD cards. For ExFat volumes, the data size calculation for final truncation of the preallocated file space is handled automatically.
SdFat-2.0 supports multiple cards even if they are running on different busses or different bus types. I have a device with three SD cards, one addressed by SDIO and two running on different SPI busses, and I can copy files around without difficulty.
AFAIK there are only two incompatibilities with the older arduino <sd.h> library on which so many other libraries take a dependency:
SDFat-2.0 uses a new syntax for begin(), passing a config object that tells how your SD card is wired and how it should be addressed.
SdFat-2.0 doesn't support the older file.name() function because that was set up for 8.3 filenames. Instead you get the long filename by passing a const char* that points to somewhere the filename can be stored. You need the full filename in order to open a file, but if you are OK to stick with 8.3 filenames then you could just create a wrapper that implements a simple parameterless begin() along with the old name() function. That would make everything completely compatible with sd.h and avoid any #ifdef patching of libraries.
That's really the only compatibility issues I've found, and I haven't personally encountered any bugs.  You can find the github project here: github.com/greiman/SdFat-beta


text:
Q: c# Find Out Which Method or Class or Object Creates so many threads I have an server application that needs to run 24x7. The clients connecting to the server hang-up after a few days. We just learned that the server (through the memory dump) generated 800+ threads! On some situations, it would reach to 100+! I know this is really so much and must 'probably' be the cause of calls from the clients not getting serviced.
0:000> !threads -live
ThreadCount:      809
UnstartedThread:  790
BackgroundThread: 14
PendingThread:    790
DeadThread:       1
Hosted Runtime:   no
                                   PreEmptive   GC Alloc                Lock
       ID  OSID ThreadOBJ    State GC           Context       Domain   Count APT Exception
   0    1   d4c 012be0a0   2006020 Enabled  00000000:00000000 012b7310     0 STA
   2    2   d54 012c9dd0      b220 Enabled  00000000:00000000 012b7310     0 MTA (Finalizer)
   3    3   d60 0131a0c0   100a220 Enabled  00000000:00000000 012b7310     0 MTA (Threadpool Worker)
   4    4   d64 01331ef0      b220 Enabled  00000000:00000000 012b7310     0 MTA
   6    6   d70 01337348   1000220 Enabled  00000000:00000000 012b7310     0 Ukn (Threadpool Worker)
   7    7   d8c 0133f100   2000220 Enabled  00000000:00000000 012b7310     0 Ukn
   9    a   f90 06c2c948   2000220 Enabled  00000000:00000000 012b7310     0 Ukn
  10    b   9a8 06c33f48   200b020 Enabled  00000000:00000000 012b7310     0 MTA
  11    c   584 06c34450   200b020 Enabled  00000000:00000000 012b7310     0 MTA
  12    d   5f4 06c35758   200b020 Enabled  00000000:00000000 012b7310     0 MTA
  13   12   970 06ca6d08   2000220 Enabled  00000000:00000000 012b7310     0 Ukn
  14    e  1254 06ca8b38   2000220 Enabled  00000000:00000000 012b7310     0 Ukn
  15   13  12f0 06ca9548   2000220 Enabled  00000000:00000000 012b7310     0 Ukn
  16    5  10ec 06ca7210   2000220 Enabled  00000000:00000000 012b7310     0 Ukn
  17    f  1d90 06cac290   a009220 Enabled  259e45ac:259e4fe8 012b7310     0 MTA (Threadpool Completion Port)
  19   19  1124 06ca7718   8009220 Enabled  258f90c4:258fafe8 012b7310     0 MTA (Threadpool Completion Port)
  20    8  1394 06ca9040   2000220 Enabled  00000000:00000000 012b7310     0 Ukn
  22  322  21d4 13698f50   2000220 Enabled  259e6394:259e6fe8 012b7310     0 Ukn

The server codes is composed of thousands of lines of codes. Is there an easy tool to check which object generated that much thread?


text:
Q: Laravel validation unique rule reflection class exception I'm trying to setup a unique rule for an email address field and I'm running into a ReflectionException because the validation table name is being cast into a class. Looking at the documentation this should just cast it to the table however..
Laravel version is: 5.7.
The validation rules are like this:
$this->validate($request, [
    'email' => 'unique:users',
    'password' => 'same:password_confirmation'
]);

Where $this is the Controller, I've also tried using the Illuminate\Http\Request; same result.
The stacktrace that I get is the following:
ReflectionException thrown with message "Class users does not exist"

Stacktrace:
#65 ReflectionException in /var/www/vendor/laravel-doctrine/orm/src/IlluminateRegistry.php:362
#64 ReflectionClass:__construct in /var/www/vendor/laravel-doctrine/orm/src/IlluminateRegistry.php:362
#63 LaravelDoctrine\ORM\IlluminateRegistry:getManagerForClass in /var/www/vendor/laravel-doctrine/orm/src/Validation/DoctrinePresenceVerifier.php:137
#62 LaravelDoctrine\ORM\Validation\DoctrinePresenceVerifier:getEntityManager in /var/www/vendor/laravel-doctrine/orm/src/Validation/DoctrinePresenceVerifier.php:93
#61 LaravelDoctrine\ORM\Validation\DoctrinePresenceVerifier:select in /var/www/vendor/laravel-doctrine/orm/src/Validation/DoctrinePresenceVerifier.php:46
#60 LaravelDoctrine\ORM\Validation\DoctrinePresenceVerifier:getCount in /var/www/vendor/laravel/framework/src/Illuminate/Validation/Concerns/ValidatesAttributes.php:687
#59 Illuminate\Validation\Validator:validateUnique in /var/www/vendor/laravel/framework/src/Illuminate/Validation/Validator.php:373
#58 Illuminate\Validation\Validator:validateAttribute in /var/www/vendor/laravel/framework/src/Illuminate/Validation/Validator.php:268
#57 Illuminate\Validation\Validator:passes in /var/www/vendor/laravel/framework/src/Illuminate/Validation/Validator.php:293
#56 Illuminate\Validation\Validator:fails in /var/www/vendor/laravel/framework/src/Illuminate/Validation/Validator.php:305
#55 Illuminate\Validation\Validator:validate in /var/www/vendor/laravel/framework/src/Illuminate/Foundation/Validation/ValidatesRequests.php:47
#54 App\Http\Controllers\Controller:validate in /var/www/app/Http/Controllers/SignUpController.php:74
#53 App\Http\Controllers\SignUpController:memberSignUp in /var/www/vendor/laravel/framework/src/Illuminate/Routing/Controller.php:54
#52 call_user_func_array in /var/www/vendor/laravel/framework/src/Illuminate/Routing/Controller.php:54
#51 Illuminate\Routing\Controller:callAction in /var/www/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php:45
#50 Illuminate\Routing\ControllerDispatcher:dispatch in /var/www/vendor/laravel/framework/src/Illuminate/Routing/Route.php:212
#49 Illuminate\Routing\Route:runController in /var/www/vendor/laravel/framework/src/Illuminate/Routing/Route.php:169
#48 Illuminate\Routing\Route:run in /var/www/vendor/laravel/framework/src/Illuminate/Routing/Router.php:679
#47 Illuminate\Routing\Router:Illuminate\Routing\{closure} in /var/www/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:30
#46 Illuminate\Routing\Pipeline:Illuminate\Routing\{closure} in /var/www/app/Http/Middleware/BoxMiddleware.php:28
#45 App\Http\Middleware\BoxMiddleware:handle in /var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:151
#44 Illuminate\Pipeline\Pipeline:Illuminate\Pipeline\{closure} in /var/www/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53
#43 Illuminate\Routing\Pipeline:Illuminate\Routing\{closure} in /var/www/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php:41
#42 Illuminate\Routing\Middleware\SubstituteBindings:handle in /var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:151
#41 Illuminate\Pipeline\Pipeline:Illuminate\Pipeline\{closure} in /var/www/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53
#40 Illuminate\Routing\Pipeline:Illuminate\Routing\{closure} in /var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php:75
#39 Illuminate\Foundation\Http\Middleware\VerifyCsrfToken:handle in /var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:151
#38 Illuminate\Pipeline\Pipeline:Illuminate\Pipeline\{closure} in /var/www/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53
#37 Illuminate\Routing\Pipeline:Illuminate\Routing\{closure} in /var/www/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php:49
#36 Illuminate\View\Middleware\ShareErrorsFromSession:handle in /var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:151
#35 Illuminate\Pipeline\Pipeline:Illuminate\Pipeline\{closure} in /var/www/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53
#34 Illuminate\Routing\Pipeline:Illuminate\Routing\{closure} in /var/www/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php:63
#33 Illuminate\Session\Middleware\StartSession:handle in /var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:151
#32 Illuminate\Pipeline\Pipeline:Illuminate\Pipeline\{closure} in /var/www/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53
#31 Illuminate\Routing\Pipeline:Illuminate\Routing\{closure} in /var/www/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse.php:37
#30 Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse:handle in /var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:151
#29 Illuminate\Pipeline\Pipeline:Illuminate\Pipeline\{closure} in /var/www/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53
#28 Illuminate\Routing\Pipeline:Illuminate\Routing\{closure} in /var/www/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php:66
#27 Illuminate\Cookie\Middleware\EncryptCookies:handle in /var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:151
#26 Illuminate\Pipeline\Pipeline:Illuminate\Pipeline\{closure} in /var/www/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53
#25 Illuminate\Routing\Pipeline:Illuminate\Routing\{closure} in /var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:104
#24 Illuminate\Pipeline\Pipeline:then in /var/www/vendor/laravel/framework/src/Illuminate/Routing/Router.php:681
#23 Illuminate\Routing\Router:runRouteWithinStack in /var/www/vendor/laravel/framework/src/Illuminate/Routing/Router.php:656
#22 Illuminate\Routing\Router:runRoute in /var/www/vendor/laravel/framework/src/Illuminate/Routing/Router.php:622
#21 Illuminate\Routing\Router:dispatchToRoute in /var/www/vendor/laravel/framework/src/Illuminate/Routing/Router.php:611
#20 Illuminate\Routing\Router:dispatch in /var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php:176
#19 Illuminate\Foundation\Http\Kernel:Illuminate\Foundation\Http\{closure} in /var/www/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:30
#18 Illuminate\Routing\Pipeline:Illuminate\Routing\{closure} in /var/www/vendor/fideloper/proxy/src/TrustProxies.php:57
#17 Fideloper\Proxy\TrustProxies:handle in /var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:151
#16 Illuminate\Pipeline\Pipeline:Illuminate\Pipeline\{closure} in /var/www/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53
#15 Illuminate\Routing\Pipeline:Illuminate\Routing\{closure} in /var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php:31
#14 Illuminate\Foundation\Http\Middleware\TransformsRequest:handle in /var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:151
#13 Illuminate\Pipeline\Pipeline:Illuminate\Pipeline\{closure} in /var/www/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53
#12 Illuminate\Routing\Pipeline:Illuminate\Routing\{closure} in /var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php:31
#11 Illuminate\Foundation\Http\Middleware\TransformsRequest:handle in /var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:151
#10 Illuminate\Pipeline\Pipeline:Illuminate\Pipeline\{closure} in /var/www/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53
#9 Illuminate\Routing\Pipeline:Illuminate\Routing\{closure} in /var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php:27
#8 Illuminate\Foundation\Http\Middleware\ValidatePostSize:handle in /var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:151
#7 Illuminate\Pipeline\Pipeline:Illuminate\Pipeline\{closure} in /var/www/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53
#6 Illuminate\Routing\Pipeline:Illuminate\Routing\{closure} in /var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php:62
#5 Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode:handle in /var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:151
#4 Illuminate\Pipeline\Pipeline:Illuminate\Pipeline\{closure} in /var/www/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php:53
#3 Illuminate\Routing\Pipeline:Illuminate\Routing\{closure} in /var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php:104
#2 Illuminate\Pipeline\Pipeline:then in /var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php:151
#1 Illuminate\Foundation\Http\Kernel:sendRequestThroughRouter in /var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php:116
#0 Illuminate\Foundation\Http\Kernel:handle in /var/www/public/index.php:55

I might just be overlooking something, however after one hour of debugging I decided to post a question. Thanks! :)

A: In type of using laravel-doctrine, the validation accept two parameter:
As Documentation Says:
/**
 * Store a new blog post.
 *
 * @param  Request  $request
 * @return Response
 */
public function store(Request $request)
{
    $this->validate($request, [
        'username' => 'required|unique:App\User,username',
    ]);
}

therefore in your case:
$this->validate($request, [
        'email' => 'required|unique:App\User,email',
    ]);

A: What fixed my issue was the following:
I still had a part of the laravel-doctrine/orm left in my vendor folder probably because I removed the dependency but never ran composer to reflect those changes. Therefore running composer install fixed my issue!


text:
Q: Why when I tried to insert some values in the table with python the output it's none? I have this code
import MySQLdb
db = MySQLdb.connect("localhost", "root", "password", "db_name")
cursor = db.cursor()

cursor.execute("INSERT INTO directedEdges (`originLbl`, `targetLbl`) VALUES
              ('user1@enron.com', 'user2@enron.com' )")
data = cursor.fetchone()
print data

but when I execute this script the output is None and and I can't insert the values in the db. Why ?
In a first moment I thought it was a problem whit db connection, but if I execute
import MySQLdb
db = MySQLdb.connect("localhost", "root", "password", "db_name")
cursor = db.cursor()
cursor.execute("SELECT * FROM directedEdges")
data = cursor.fetchone()
print data

I see the content of the table directedEdges.
Thanks

A: You issued the cursor.fetchone() command immediately after inserting into the database. You don't have any queried data like that. You need to have queried some data before using fetchone(). Try this:
import MySQLdb
db = MySQLdb.connect("localhost", "root", "password", "db_name")
cursor = db.cursor()

cursor.execute("INSERT INTO directedEdges (`originLbl`, `targetLbl`) VALUES
              ('user1@enron.com', 'user2@enron.com' )")
# Commit your insert
db.commit()

# Query for data
cursor.execute("SELECT * FROM directedEdges")

data = cursor.fetchone()
print data


text:
Q: Updating column by calculation in cassandra I am trying to add a new column in cassandra table to aid in some client side operations. The table is already there, and it has data in it. The primary key is a bigint.
The idea is to add a column on the table that would create domains of the primary key.
So the new column here is a int that must have the value of the <primary-key % 10>, which will give me 10 possible values for the new column, such as 10 pages based on the last digit of the primary key.
The primary key is named idx and the new column is called idx_page.
One idea was to add the new 'idx_page' column as CLUSTERING column, but this didnt seem to work, using an ALTER TABLE statement. IF this is supposed to work, then I am probably doing something wrong with my cql statement for altering the table.
Next thing I tried was to add new column, then add an index on that, because eventually client side will need to do SELECT based on the value of that column in order to fetch all rows that have a specific value on the new column. This worked fine.
Regardless of whether idx_page would be a clustering column or a plain column with index on it, there are still 2 issues to solve:

*

*existing rows have a NULL "value" on the new column (which was expected)

*I have to figure out the best way that when a new row is inserted, the new column will be assigned with a value that is calculated based on primary key, preferably not by changing all the client side code to do this manually.

I guess I could get around both issues by using cassandra FUNCTIONS and AGGREGATES ?
Ideally I would like to be able to call some function manually once, in order to update all existing rows, and assign a value to idx_page, which is always calculated by (idx % 10).
Then upon INSERT, I would like to have the same logic run automatically so that idx_page gets a value at the insertion phase.
I am not sure how to proceed with this, or even if I am on the right path with UDF/UDA.
Any comments or advice please.
Alex

A: You can build a custom function to accomplish this.
https://docs.datastax.com/en/cql/3.3/cql/cql_using/useCreateUDF.html
CREATE FUNCTION IF NOT EXISTS moduluo (input bigint)
   CALLED ON NULL INPUT
   RETURNS int
   LANGUAGE java AS '
     return input % 10;
     ';


text:
Q: How can I make a Switch component async await for successful response before changing value? The default flow of a switch will toggle the value as soon as it is pressed.
I want to execute the following logic

*

*Press switch

*Don't change the value yet

*Open alert box

*If ok, send post request to toggle database value

*On successful response, allow the switch value to change

I can get the successful response and update the switch, but as soon as I press the switch the value toggles twice and I want to pause this behaviour until there is a successful response. Tried async await, tried wrapping the switch in a touchablewithout feedback... now need some help
<Switch
   value={this._getSwitchValue(id)}
   onValueChange={() => this._toggleSwitch(id)}
/>

  /**
   * Toggle the Switch - Send post request to database
   */
  _toggleSwitch (id) {
    Alert.alert('Notice!', 'Do you really want to change this setting?',
    [
      { text: "OK", onPress: () => this.props.toggleSettingsSwitch(id, this.props.token) },
      { text: "Cancel", onPress: () => console.log("cancel pressed")}
    ],
    { cancelable: true }
  )}

A: Change the Switch value inside the function that makes the request.
toggleSettingsSwitch = async (value) => {

  const response = await this.changeSettingsRequest(); // making a call

  // here add a check, if request was successful change switch value
  // if (response.ok) {
  // this.setState({ switchValue: value });
  //}

};

_toggleSwitch = (value) => {
  Alert.alert(
    'Notice!',
    'Do you really want to change this setting?',
    [
      {
        text: 'OK',
        onPress: () => {
          this.toggleSettingsSwitch(value);
        },
      },
      { text: 'Cancel', onPress: () => console.log('cancel pressed') },
    ],
    { cancelable: true }
  );
};

<Switch
  onValueChange={this._toggleSwitch}
  value={this.state.switchValue}/>

snack example

A: I know this is an old question, but for people still looking for an answer to this, try: react-native-switch-pro
Another alternative is to create your own async-supporting switch-like component, here's an example on snack: Custom Async Switch

A: You can just have another variable loading and ignore calls, if it is true
_toggleSwitch = async (value) => {
  if (this.loading) {
     return;
  }
  this.loading = true;

  try {
     ...
  } finally {
     this.loading = false;
  }
};

You can even put it in React state and make it part of UI interaction (hiding Switch if it's in loading state and presenting some kind of animation)
I would just optimistically update UI state and inform user in case of an error, that way UI would feel more responsive.


text:
Q: asp.net mvc url routing (disable access to /index and query string Suppose we have the following controller code and default to Home/Index and i have a domain www.abc.com.
How to i configure to make www.abc.com/home and www.abc.com/home/index as 404 page
 public HomeController : Controller {
        public ActionResult Index() {
        }
    }

Also suppose I have controller like this, I assume that user can access it following way. www.abc.com/home/index/1 or using query string www.abc.com/home/index/?id = 1. I would like to display 404 page for this url: www.abc.com/home/index/?id = 1. How can this be done?
public HomeController : Controller {
        public ActionResult Index(string id) {
        }
    }

A: In your RouteConfig.RegisterRoutes method, this will make /home and /home/index show a 404:
routes.MapRoute(
    name: "Home",
    url: "",
    defaults: new { controller = "Home", action = "Index" });

and this route will allow /home/index/1 but will 404 for /home/index/?id=1:
routes.MapRoute(
    name: "Home",
    url: "home/index/{id}",
    defaults: new { controller = "Home", action = "Index" });

This is pretty basic routing in ASP.NET MVC. I recommend reading some of documentation that's out there for more information.
http://msdn.microsoft.com/en-us/library/vstudio/cc668201(v=vs.100).aspx


text:
Q: Execute procedure owned by a schema in sys I have a schema called test, and it has a procedure called doAProcedure('varA'). Inside the procedure it calls a function funcA that belongs to schema test.
CREATE OR REPLACE PROCEDURE doAProcedure(tabname varchar2) AUTHID CURRENT_USER AS ....

If I log in to the db as test, I am able to complete execute doAProcedure('valA');
However, I want to support executing the procedure as SYS as well. if I execute the following command as sys, it is complaining that function funcA is not declared. execute test.doAProcedure('varA'); Not sure what needs to be fixed.

A: Problem is in: AUTHID CURRENT_USER
This means that the current user must also be authorized to execute code inside the procedure.
Fix 1: Remove this part and leave only:
CREATE OR REPLACE PROCEDURE doAProcedure(tabname varchar2) AS

Fix 2: Grant execute to function funcA for SYS
grant execute on test.funcA to sys;

A: This is test case; everything works OK when connected as the owner:
SQL> connect scott/tiger@pdb1
Connected.
SQL> create or replace function f_test return number is
  2  begin
  3    return 1;
  4  end;
  5  /

Function created.

SQL> create or replace procedure p_test authid current_user is
  2  begin
  3    dbms_output.put_line('Function returned ' || f_test);
  4  end;
  5  /

Procedure created.

SQL> set serveroutput on
SQL> exec p_test
Function returned 1

PL/SQL procedure successfully completed.

SQL>

Let's connect as SYS and try again:
SQL> connect sys@pdb1 as sysdba
Enter password:
Connected.
SQL> exec scott.p_test
BEGIN scott.p_test; END;

*
ERROR at line 1:
ORA-06598: insufficient INHERIT PRIVILEGES privilege
ORA-06512: at "SCOTT.P_TEST", line 1
ORA-06512: at line 1

SQL>

As you said, it won't work.
"Problem" is in Oracle 12c or later, with new security feature (see inherit privileges).
What to do? A little grant (still connected as SYS):
SQL> grant inherit privileges on user sys to scott;

Grant succeeded.

SQL> exec scott.p_test
Function returned 1

PL/SQL procedure successfully completed.

SQL>

Now it works.


text:
Q: Job queue for PHP and C# scripts I'm looking for best solution to run tasks (performed by C# and PHP scripts) which are sharing same dataset. Execution time of this script varies from 5 min - 10 min. Scripts are placed on different servers and return results to main server.
I need to run PHP script right after C# script gets the job done. Right now, I might use one PHP script on main server with file_get_contents() and call another PHP script that uses exec() to run .exe and waits for response.
After that I'll run second PHP task script. I saw multiple solutions for this, like Gearman and RabbitMQ.
I would like to know which solution is best for this kind of simple problem, and avoid using file_get_contents().

A: RabbitMQ, Gearman and other queueing solutions won't prevent you fro using file_get_contents(). They will allow you to write that code so that it runs somewhere else... a separate process, or even on a different server. But your code is still going to do what it needs to do, to read a file and execute another process.


text:
Q: Substrate genesis blocks not matching I am currently doing this tutorial. When I am following it as described and execute the alice and bob nodes both on the same machine it works as expected: the nodes are connecting and are creating and finalizing blocks. Now I want to get the same done but over the internet and on different machines. So I execute the bootnode on my PC and the other node on my Laptop. I compiled both from the same code and also forwarded the ports in my router. So now I expect the same behavior as when I am running both on my local machine. So when I execute them I see network traffic printed in both consoles but the bob node prints a warning: Bootnode with peer id '12D3KooWEyoppNCUx8Yx66oV9fJnriXwCcXwDDUA2kj6vnc6iDEp' is on a different chain (our genesis: 0xbfbd…3144 theirs: 0x8859…14c4) and they are not connected (Idle 0 peers).
So from the warning I conclude they have not the same genesis blocks which is obviously necessary to run as a blockchain. But from my understanding the joining node should copy the current state of the chain from the bootnode. How can I change bobs part to use alices state of the chain?
Both machines are running rust version 1.50.0
Thanks for your help!

A: Rust compilations are not deterministic, thus the exact same code for the exact same blockchain compiled on two computers will unfortunately not have the same genesis hash. (Specifically because part of the genesis of that chain is the Wasm Runtime blob, which is compiled non-deterministically with Rust).
You need to create a chainspec file to use for all other nodes. Note that you want to generate this on one computer, and pass the file to other nodes (don't re-generate it, as the genesis code will differ, as you ran into) before you then start other nodes using the correct chainspec and manually specifying boot nodes.


text:
Q: R: Compare data.table and pass variable while respecting key I have two data.tables:
original <- data.frame(id = c(rep("RE01",5),rep("RE02",5)),date.time = head(seq.POSIXt(as.POSIXct("2015-11-01 01:00:00"),as.POSIXct("2015-11-05 01:00:00"),60*60*10),10))
compare <- data.frame(id = c("RE01","RE02"),seq = c(1,2),start = as.POSIXct(c("2015-11-01 20:00:00","2015-11-04 08:00:00")),end = as.POSIXct(c("2015-11-02 08:00:00","2015-11-04 20:00:00")))
setDT(original)
setDT(compare)

I would like to check the date in each row of original and see if it lies between the start and finish dates of compare whilst respecting the id. If it does lie between the two elements, a variable should be passed to original (compare$diff.seq). The output should look like this:
    original
     id           date.time diff.seq
1  RE01 2015-11-01 01:00:00       NA
2  RE01 2015-11-01 11:00:00       NA
3  RE01 2015-11-01 21:00:00        1
4  RE01 2015-11-02 07:00:00        1
5  RE01 2015-11-02 17:00:00       NA
6  RE02 2015-11-03 03:00:00       NA
7  RE02 2015-11-03 13:00:00       NA
8  RE02 2015-11-03 23:00:00       NA
9  RE02 2015-11-04 09:00:00        2
10 RE02 2015-11-04 19:00:00        2

I've been reading the manual and SO for hours and trying "on", "by" and so on.. without any success. Can anybody point me in the right direction?

A: As said in the comments, this is very straight forward using data.table::foverlaps
You basically have to create an additional column in the original data set in order to set join boundaries, then key the two data sets by the columns you want to join on and then simply run forverlas and select the desired columns
original[, end := date.time]
setkey(original, id, date.time, end)
setkey(compare, id, start, end)
foverlaps(original, compare)[, .(id, date.time, seq)]
#       id           date.time seq
#  1: RE01 2015-11-01 01:00:00  NA
#  2: RE01 2015-11-01 11:00:00  NA
#  3: RE01 2015-11-01 21:00:00   1
#  4: RE01 2015-11-02 07:00:00   1
#  5: RE01 2015-11-02 17:00:00  NA
#  6: RE02 2015-11-03 03:00:00  NA
#  7: RE02 2015-11-03 13:00:00  NA
#  8: RE02 2015-11-03 23:00:00  NA
#  9: RE02 2015-11-04 09:00:00   2
# 10: RE02 2015-11-04 19:00:00   2

Alternatively, you can run foverlaps the other way around and then just update the original data set by reference while selecting the correct rows to update
indx <- foverlaps(compare, original, which = TRUE)
original[indx$yid, diff.seq := indx$xid]
original
#       id           date.time                 end diff.seq
#  1: RE01 2015-11-01 01:00:00 2015-11-01 01:00:00       NA
#  2: RE01 2015-11-01 11:00:00 2015-11-01 11:00:00       NA
#  3: RE01 2015-11-01 21:00:00 2015-11-01 21:00:00        1
#  4: RE01 2015-11-02 07:00:00 2015-11-02 07:00:00        1
#  5: RE01 2015-11-02 17:00:00 2015-11-02 17:00:00       NA
#  6: RE02 2015-11-03 03:00:00 2015-11-03 03:00:00       NA
#  7: RE02 2015-11-03 13:00:00 2015-11-03 13:00:00       NA
#  8: RE02 2015-11-03 23:00:00 2015-11-03 23:00:00       NA
#  9: RE02 2015-11-04 09:00:00 2015-11-04 09:00:00        2
# 10: RE02 2015-11-04 19:00:00 2015-11-04 19:00:00        2


text:
Q: Issue Launching Grails project to cloudfoundry I am having a problem launching my (grails) project to cloud foundry.  I have already launched with cf-push, but I keep getting this error
I/O error: Connection reset; nested exception is java.net.SocketException: Connection reset

when I run cf-update.
I also cannot see my log files with cf-crashlogs. I get this in the terminal window:
grails> cf-crashlogs
|   Checking for available resources:.....

And if I try to access the page I get a 404 Not Found page.
Did I completely miss something?  has anyone else seen this or know how fix this issue?

A: please check which version of the cf grails plugin were you using. try listing the plugin updates with this command:
grails list-plugin-updates

after that try to get cloud foundry connection info by:
grails cf-info

i suppose you know how to configure the login info, all the configure properties are listed here: http://grails-plugins.github.com/grails-cloud-foundry/docs/manual/guide/3%20Configuration.html
to access your app log, the most commonly used command is
grails cf-logs [destination] [--appname] [--instance] [--stderr] [--stdout] [--startup]

hope that helps.

A: I was trying to test Cloud Foundry long time ago. Don't remember but also had some issues which I couldn't overcome using default tool.
However then I used the Cloud Foundry Integration.
As I mentioned it was some time ago, so I won't help with the details, but the plugin worked as expected and I was able to deploy. Maybe you will success with it too :)


text:
Q: Creating Rich Text Templates I need to create a Rich Text Formatted (RTF) Template File I can pass data through which generates the RAW rich text (that can then be saved).

*

*I see a TON of HTML editors...I don't want that.

*I need something to create the actual RTF...raw!

*I will save that raw RTF as a template

Having a hard time finding something.  Thanks
FOR EXAMPLE:
I need the raw RTF for a template...I DO NOT want HTML
{\rtf1\ansi\ansicpg1252\uc1\deff0{\fonttbl
{\f0\fnil\fcharset0\fprq2 Arial;}
{\f1\fswiss\fcharset0\fprq2 Tahoma;}
{\f2\froman\fcharset2\fprq2 Symbol;}}
{\colortbl;}
{\stylesheet{\s0\itap0\nowidctlpar\f0\fs24 [Normal];}{\*\cs10\additive Default Paragraph Font;}}
{\*\generator TX_RTF32 19.0.542.500;}
\paperw7315\paperh15840\margl0\margt0\margr0\margb0\deftab1134\widowctrl\lytexcttp\formshade\sectd
\headery720\footery720\pgwsxn7315\pghsxn15840\marglsxn0\margtsxn0\margrsxn0\margbsxn0\pgbrdropt32\pard\itap0\nowidctlpar\plain\f1\fs20 MED BILL INV#  28989293\par }

A: Sorry... Your question is not very clear...
What about:
richTextBox1.SaveFile(filename.rtf);

If you open that file with Notepad you'll see something like:
{\rtf1\ansi\ansicpg1252\deff0\deflang1040{\fonttbl{\f0\fnil\fcharset0 Microsoft Sans Serif;}}
\viewkind4\uc1\pard\b\i\f0\fs36\par
}