text:
Q: Functions of random variables problem Random variable $X$ has uniform distribution on ($0,1$). The question is to find the distribution of $U=|X-1/3|$.
So, by using the definition of continuous variables, I got to the equation $Fx(u+1/3)-Fx(-u+1/3)$, and that is correct.
Now, I don't understand how to subtract these two functions, since one is non-zero on the interval $(-1/3,2/3)$ and the other on the interval $(-2/3,1/3)$.
The answer in the book is $2u$ on ($0,1/3$), $u+1/3$ on ($1/3,2/3$), and $1$ after that.

A: It is immediate that $U$ takes values in $[0,\frac23)$ almost surely.
This leads to $F_U(u)=0$ if $u<0$ and $F_U(u)=1$ if $u\geq\frac23$.
After this preparation it is time to look at $u\in[0,\frac23)$.
If $u\in[0,\frac13)$ then: $$F_U(u)=F_X(u+\frac13)-F_X(-u+\frac13)=(u+\frac13)-(-u+\frac13)=2u$$
If $u\in[\frac13,\frac23)$ then: $$F_U(u)=F_X(u+\frac13)-F_X(-u+\frac13)=(u+\frac13)-0=u+\frac13$$


text:
Q: Оптимизация запроса where group by Имею запрос
SELECT DATE_FORMAT(dl.`date_col`, '%Y-%m-%d') AS dateF
FROM table_name dl
WHERE dl.`date_col` BETWEEN '2016-01-01' AND '2017-12-01'
GROUP BY date(dateF)
ORDER BY dateF;

Время работы 0.735. Как его можно оптимизировать? Пробовал подобный запрос
SELECT DATE_FORMAT(dl.`date_col`, '%Y-%m-%d') as dateF
FROM table_name dl
GROUP BY date(dateF)
HAVING dl.`date_col` BETWEEN '2016-01-01' AND '2017-12-01'
ORDER BY dateF;

Время получилось 0.657, но все таки не хорошо пихать в having, то что должно быть в where. explain-ы для запросов соответственно:
'1', 'SIMPLE', 'dl', 'index', NULL, 'uid', '9', NULL, '767882',
'Using where; Using index; Using temporary; Using filesort' (where)

'1', 'SIMPLE', 'dl', 'index', NULL, 'uid', '9', NULL, '767883',
'Using index; Using temporary; Using filesort'  (having)

База MyISAM. Структура таблицы:
'CREATE TABLE `table_name` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date_col` datetime NOT NULL DEFAULT \'0000-00-00 00:00:00\',
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`))

A: Возможное решение по "оптимизации" запроса путём переопределения данных:
-- добавить поле с датой
ALTER TABLE table_name ADD COLUMN only_date_col DATE;
-- пересчитать его значения
UPDATE table_name SET only_date_col = DATE(date_col);
-- проиндексировать поле
CREATE INDEX idx_only_date ON table_name (only_date_col);
-- создать триггеры, обновляющие поле при вставке/изменении данных
CREATE TRIGGER bi_table_name ON table_name BEFORE INSERT
    FOR EACH ROW SET NEW.only_date_col = DATE(NEW.date_col);
CREATE TRIGGER bu_table_name ON table_name BEFORE UPDATE
    FOR EACH ROW SET NEW.only_date_col = DATE(NEW.date_col);

Соответственно запрос трансформируется в
SELECT DATE_FORMAT(only_date_col, '%Y-%m-%d') AS dateF, COUNT(*) AS cnt
FROM table_name
WHERE only_date_col BETWEEN '2016-01-01' AND '2017-12-01'
GROUP BY only_date_col;

При возникновении подозрений на несогласованность данных (или в процедуре обслуживания БД) - запускать запрос пересчёта значений UPDATE для согласования данных в поле only_date_col.
ВАЖНО! Следует понимать, что данное изменение ухудшит производительность большинства других запросов (если они, как и оптимизируемый запрос, не используют часть даты из поля даты-времени - тогда переписывание их на использование добавленного поля может улучшить их выполнение), а также увеличит расход дискового пространства.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to combine two byte arrays I have two byte arrays and I am wondering how I would go about adding one to the other or combining them to form a new byte array.

A: I think it is best approach,
public static byte[] addAll(final byte[] array1, byte[] array2) {
    byte[] joinedArray = Arrays.copyOf(array1, array1.length + array2.length);
    System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
    return joinedArray;
}

A: You can do this by using Apace common lang package (org.apache.commons.lang.ArrayUtils class ). You need to do the following
byte[] concatBytes = ArrayUtils.addAll(one,two);

A: The simplest method (inline, assuming a and b are two given arrays):
byte[] c = (new String(a, cch) + new String(b, cch)).getBytes(cch);

This, of course, works with more than two summands and uses a concatenation charset, defined somewhere in your code:
static final java.nio.charset.Charset cch = java.nio.charset.StandardCharsets.ISO_8859_1;

Or, in more simple form, without this charset:
byte[] c = (new String(a, "l1") + new String(b, "l1")).getBytes("l1");

But you need to suppress UnsupportedEncodingException which is unlikely to be thrown.

The fastest method:
public static byte[] concat(byte[] a, byte[] b) {
    int lenA = a.length;
    int lenB = b.length;
    byte[] c = Arrays.copyOf(a, lenA + lenB);
    System.arraycopy(b, 0, c, lenA, lenB);
    return c;
}

A: String temp = passwordSalt;
byte[] byteSalt = temp.getBytes();
int start = 32;
for (int i = 0; i < byteData.length; i ++)
{
    byteData[start + i] = byteSalt[i];
}

The problem with your code here is that the variable i that is being used to index the arrays is going past both the byteSalt array and the byteData array.  So, Make sure that byteData is dimensioned to be at least the maximum length of the passwordSalt string plus 32.  What will correct it is replacing the following line:
for (int i = 0; i < byteData.length; i ++)

with:
for (int i = 0; i < byteSalt.length; i ++)

A: You're just trying to concatenate the two byte arrays?
byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();
byte[] combined = new byte[one.length + two.length];

for (int i = 0; i < combined.length; ++i)
{
    combined[i] = i < one.length ? one[i] : two[i - one.length];
}

Or you could use System.arraycopy:
byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();
byte[] combined = new byte[one.length + two.length];

System.arraycopy(one,0,combined,0         ,one.length);
System.arraycopy(two,0,combined,one.length,two.length);

Or you could just use a List to do the work:
byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();

List<Byte> list = new ArrayList<Byte>(Arrays.<Byte>asList(one));
list.addAll(Arrays.<Byte>asList(two));

byte[] combined = list.toArray(new byte[list.size()]);

Or you could simply use ByteBuffer with the advantage of adding many arrays.
byte[] allByteArray = new byte[one.length + two.length + three.length];

ByteBuffer buff = ByteBuffer.wrap(allByteArray);
buff.put(one);
buff.put(two);
buff.put(three);

byte[] combined = buff.array();

A: Assuming your byteData array is biger than 32 + byteSalt.length()...you're going to it's length, not byteSalt.length. You're trying to copy from beyond the array end.

A: I've used this code which works quite well just do appendData and either pass a single byte with an array, or two arrays to combine them :
protected byte[] appendData(byte firstObject,byte[] secondObject){
    byte[] byteArray= {firstObject};
    return appendData(byteArray,secondObject);
}

protected byte[] appendData(byte[] firstObject,byte secondByte){
    byte[] byteArray= {secondByte};
    return appendData(firstObject,byteArray);
}

protected byte[] appendData(byte[] firstObject,byte[] secondObject){
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream( );
    try {
        if (firstObject!=null && firstObject.length!=0)
            outputStream.write(firstObject);
        if (secondObject!=null && secondObject.length!=0)
            outputStream.write(secondObject);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return outputStream.toByteArray();
}


text:
Q: Are there any Laravel framework conditions that might truncate a model table during a test? I've encountered a mysterious error while testing my Laravel app: a model instance that's just been created is not found inside the middleware after I call postJson method.
The test class StoreEventControllerTest extends Laravel's TestCase, which is using LazilyRefreshesDatabase. I've tried removing it form the TestCase and also added RefreshDatabase, to no avail.
I've tried debugging the test, but still couldn't figure out what's going on:
Test debugging step #1: A model instance's been created

Test debugging step #2: The recently created model is not found!

Route is configured in routes/api.php:
Route::post('stores/{key}/receive-payload', StoreEventController::class)
    ->middleware('event.signature')
    ->name('stores.receive-payload');

The middleware event.signature handle method:
public function handle(Request $request, Closure $next)
{
    $key = $request->route('key');
    $sourceName = $request->get('source');

    if (!$key || !$sourceName) {
        abort(401);
    }

    /** @var EventStore $store */
    if (!$store = EventStore::find($key)) {
        abort(401);
    }

    /** @var EventStoreSource $source */
    if (!$source = $store->sources()->where('name', $sourceName)->first()) {
        abort(401);
    }

    $providedSignature = $this->getProvidedSignature($request, $source);

    if (!$providedSignature) {
        abort(401);
    }

    if (!$this->checkSignature($providedSignature, $request, $store, $source)) {
        abort(401);
    }

    // Bind the event store to the request so that it can be used in the controller
    app()->instance(EventStoreSource::class, $source);

    return $next($request);
}

And here is a relevant excerpt from model EventStore:
use App\Models\Concerns\UsesUuidKey;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;

class EventStore extends Model
{
    use HasFactory;

    use UsesUuidKey;

namespace App\Models\Concerns;

use Illuminate\Support\Str;

trait UsesUuidKey
{
    public function initializeUsesUuidKey()
    {
        $this->setKeyType('string');

        $this->setIncrementing(false);
    }

    public static function bootUsesUuidKey()
    {
        static::creating(fn ($model) => $model->setUuidKey());
    }

    protected function setUuidKey()
    {
        $keyName = $this->getKeyName();

        if (blank($this->getAttribute($keyName))) {
            $this->setAttribute($keyName, Str::uuid());
        }
    }
}

The table event_stores structure:
+--------------+---------------------+------+-----+---------+-------+
| Field        | Type                | Null | Key | Default | Extra |
+--------------+---------------------+------+-----+---------+-------+
| id           | varchar(191)        | NO   | PRI | NULL    |       |
| team_id      | bigint(20) unsigned | YES  | MUL | NULL    |       |
| name         | varchar(191)        | NO   |     | NULL    |       |
| secret       | text                | NO   |     | NULL    |       |
| created_at   | timestamp           | YES  |     | NULL    |       |
| updated_at   | timestamp           | YES  |     | NULL    |       |
| activated_at | timestamp           | YES  |     | NULL    |       |
| config       | json                | YES  |     | NULL    |       |
| sources      | json                | YES  |     | NULL    |       |
+--------------+---------------------+------+-----+---------+-------+

Here's some extra commands I ran on the debug console during the test, which demonstrate the database connection doesn't change during the whole process:

Edit: I've added the table description.
Edit 2: Added a screenshot of the debug console after running commands to print the DB connection name.


text:
Q: Is there anybody did install properly aws-cli v2(x86_64; zipped) on Raspberry pi 3(ARM)? Is there anybody to try to put aws-cliv2 into raspberry pi?
I've got an err msg below which expresses an exec format error.

[my env]
(uname on my Raspberry Pi3)
Linux raspberrypi 4.19.97-v7+ #1294 SMP Thu XXX XX XX:XX:XX GMT 2020 armv7l GNU/Linux
[err msg]
pi@raspberrypi:~/XX/cdkContainer $ sudo ./aws/install
./aws/install: 78: ./aws/install: /XX/cdkContainer/aws/dist/aws: Exec format error
You can now run: /usr/local/bin/aws --version
pi@raspberrypi:~/XX/cdkContainer $ aws --version
bash: /usr/local/bin/aws: cannot execute binary file: Exec format error

I've just referred to an aws doc on the web site:
However, It doesn't work on my Raspberry Pi 3.

A: Same here..AWS Cli 2.0 docu page reports ARM, but only for 64 bit architecture, so you cannot use in raspbian.
The only solution I found is to install aws-cli version 1 using pip.
python3 -m pip install aws-cli

Everything works.

A: aws-cli v2 only supports 64-bit ARM, and your Raspberry Pi is presumably 32-bit, so it looks like what you're asking is simply impossible. The older aws-cli v1 does support Raspberry Pi though.
There is an open issue on Github where a dev confirmed the issue, but they currently have no fix planned.

A: The issue you are facing I think as others mentioned is that you are perhaps running the 64-bit aws-cli version. I ran into this issue on my linux machine running an arm processor. The easiest solution was installing the linux arm version instead (see: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html).
If you already have a 64-bit version installed, you can just delete the 64-bit file, download the arm version and re-run the installation with an update flag:
sudo ./aws/install --update
Hope this helps anyone.


text:
Q: ios parse _user pointer equal to user id? I have a table with a column which is pinter to _User. I want to check one string is equal to the user id I have in my table.

In this example I want to check if iSMSxjAnvJ is equal to user column.
Here is my code:
PFQuery *query2 =  [PFQuery queryWithClassName:@"Friends"];
[query2 whereKey:@"user" equalTo:self.friendID];

[query2 findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
           for (PFObject *friendRecord in objects) {
                        // do something with a single example object here.
           }
}];

But I get this error:
[Error]: pointer field user needs a pointer value (Code: 102, Version: 1.7.5)

I need to change this pointer value to string type to do comparison. One way is to query my user table and get string value. Is there any better way?

A: The operand of equalTo: for a pointer column is a PFObject, either a complete object or an empty PFObject with just an objectId (a "pointer" in parse world).  In other words, say you have a a real PFUser object...
PFUser *friend = // imagine you have this somehow.

To test whether a Friend instance's user is friend, just say...
PFQuery *query2 =  [PFQuery queryWithClassName:@"Friends"];
[query2 whereKey:@"user" equalTo:friend];

But what if you don't have a object?  Like the name friendId implies, what if you only have an objectId string?  Two answers:
Short answer: Make the objectId into a pointer...
PFUser *friendPointer = [PFUser objectWithoutDataWithClassName:@"_User" objectId:self.friendID];
PFQuery *query2 =  [PFQuery queryWithClassName:@"Friends"];
[query2 whereKey:@"user" equalTo:friendPointer];

Long answer: starts with a question: why do you have only the object id, why don't you have a real object?  Change the friendId (string) column on self to a friend column (pointer to _User).  Then...
// put a column called friend on self. Make it a pointer to _User
PFUser *friend = self.friend;  // we imagined this before, now its real!
PFQuery *query2 =  [PFQuery queryWithClassName:@"Friends"];
[query2 whereKey:@"user" equalTo:friend];


text:
Q: Using iPhone Gyrometer in a Moving Car I've been trying to determine how the iPhone Gyrometer can be used for a driver safety app and I Have been very confused about it.  I know that the Gyrometer in the phone can measure changes and rotations of the phone itself, but can it be used to measure changes that take place while the phone is in a moving car?
For example, would it still be able to provide the rotation rates if it's not the phone being moved but rather the phone is stationary in a moving car?

A: The gyroscope is a physical device (albeit at a minuscule level) that observes the same physical law as a toy gyroscope does by spinning — conservation of momentum.
It'll therefore recognise any changes within its inertial frame.
So, subject to precision, it'll recognise any turning that you, as a human being, recognise. It'll spot the rotational part of any force that you can feel.
For example, if the car you're in is driving smoothly in a straight line, it should pick up very little. If the car brakes abruptly such that the rear elevates relative to the front, it'll pick that up. If you performed doughnuts (safety tip: don't), it should continuously spot orientation changes for the entire period.


text:
Q: How to continue looping while the condition is false I want my program to do the certain code only if the actors variable is <=5 && >0
else I want to go back and ask different question again:
System.out.println("\nEnter actors number(max.5): ");

        int actorsNumber = scanner.nextInt();
        scanner.nextLine();

        if (actorsNumber <= 5 && actorsnumber>0) {
            for (int i = 1; i <= actorsNumber; i++) {
                System.out.println("\nEnter name and surname of the " + i + " actor: ");
                String[] parts2 = scanner.nextLine().split("\\s+");
                String actName = parts2[0];
                String actSurname = parts2[1];
                actorName.add(actName);
                actorSurname.add(actSurname);
            }

        }

So when the condition is false for example actors number = 7 then I want to tell the user: "Enter the valid actors number(1-5)" and do the for loop again if the actorsnumber is 1-5 instead ask again "Enter the valid actors number(1-5)"

A:     while(!scanner.nextLine().equals("quit")) {
        if (actorsNumber <= 5 && actorsnumber>0) {
            for (int i = 1; i <= actorsNumber; i++) {
                System.out.println("\nEnter name and surname of the " + i + "    actor: ");
                String[] parts2 = scanner.nextLine().split("\\s+");
                String actName = parts2[0];
                String actSurname = parts2[1];
                actorName.add(actName);
                actorSurname.add(actSurname);
            }

         }
     }

Or something like that, point is, use a while loop on the scanner.

A: As @apexlol stated, your code should be in a loop. However, do-while loop is more convenient than while loop since that way, the loop executes at least once no matter what.

A: You need to ask user to enter number in a loop. The condition of the loop will be the condition of your if. Then after exiting the loop (which means user enter a correct number), enter your for loop.
This will look like that :
int actorsNumber = -1; //force a wrong value at the beginning
while(actorsNumber < 1 || actorsNumber > 5) {
    //Ask user to enter a number between 1 and 5
    //store this number in actorsNumber
}
//As we exited the while-loop, actorsNumber is between 1 and 5
//Put your for-loop here


text:
Q: Export csv file from scrapy (not via command line) I successfully tried to export my items into a csv file from the command line like:
   scrapy crawl spiderName -o filename.csv

My question is:
What is the easiest solution to do the same in the code? I need this as i extract the filename from another file.
End scenario should be, that i call
  scrapy crawl spiderName

and it writes the items into filename.csv

A: There an updated way to save your file in scrapy which is using "FEEDS"
class mySpider(scrapy.Spider):
    name = "myProject"
    custom_settings = {
    "FEEDS":{"fileName.csv":{"format":"csv"}},
    }

A: Why not use an item pipeline?
WriteToCsv.py
   import csv
   from YOUR_PROJECT_NAME_HERE import settings

   def write_to_csv(item):
       writer = csv.writer(open(settings.csv_file_path, 'a'), lineterminator='\n')
       writer.writerow([item[key] for key in item.keys()])

   class WriteToCsv(object):
        def process_item(self, item, spider):
            write_to_csv(item)
            return item

settings.py
   ITEM_PIPELINES = { 'project.pipelines_path.WriteToCsv.WriteToCsv' : A_NUMBER_HIGHER_THAN_ALL_OTHER_PIPELINES}
   csv_file_path = PATH_TO_CSV

If you wanted items to be written to separate csv for separate spiders you could give your spider a CSV_PATH field. Then in your pipeline use your spiders field instead of path from setttigs.
This works I tested it in my project.
HTH
http://doc.scrapy.org/en/latest/topics/item-pipeline.html

A: That's what Feed Exports are for:
http://doc.scrapy.org/en/latest/topics/feed-exports.html

One of the most frequently required features when implementing scrapers is being able to store the scraped data properly and, quite often, that means generating a "export file" with the scraped data (commonly called "export feed") to be consumed by other systems.
Scrapy provides this functionality out of the box with the Feed Exports, which allows you to generate a feed with the scraped items, using multiple serialization formats and storage backends.

A: Up-to-date answer is:
Use build-in exporter. You can set filename as key. Config may look like:
filename = 'export'
class mySpider(scrapy.Spider):
  custom_settings = {
    'FEEDS': {
      f'{filename}.csv': {
        'format': 'csv',
        'overwrite': True
      }
    }
  }

Documentation:  https://docs.scrapy.org/en/latest/topics/feed-exports.html#std-setting-FEEDS


text:
Q: XSLT: Populating child node content repeating with parent node elemnts i am trying to transform XML from one form into another form using XSLT.
I have input XML as
<Employee>
<Emp>
    <EMPID>123</EMPID>
    <NAME>James</NAME>
    <Sequence>1</Sequence>
    <JOBS>
        <COMPANY>ABC</COMPANY>
        <DESIGNATION>Developer</DESIGNATION>
    </JOBS>
    <JOBS>
        <COMPANY>DEF</COMPANY>
        <DESIGNATION>Tester</DESIGNATION>
    </JOBS>
</Emp>
<Emp>
    <EMPID>456</EMPID>
    <NAME>Clark</NAME>
    <Sequence>2</Sequence>
    <JOBS>
        <COMPANY>GHT</COMPANY>
        <DESIGNATION>QA Lead</DESIGNATION>
    </JOBS>
    <JOBS>
        <COMPANY>Levor</COMPANY>
        <DESIGNATION>Project Lead</DESIGNATION>
    </JOBS>
</Emp>
</Employee>

I want to transform into (Desired Output)
<Employee>
<Emp>
    <EMPID>123</EMPID>
    <NAME>James</NAME>
    <Sequence>1</Sequence>
    <JOBS>
        <COMPANY>ABC</COMPANY>
        <DESIGNATION>Developer</DESIGNATION>
    </JOBS>
</Emp>
<Emp>
    <EMPID>123</EMPID>
    <NAME>James</NAME>
    <Sequence>1</Sequence>
    <JOBS>
        <COMPANY>DEF</COMPANY>
        <DESIGNATION>Tester</DESIGNATION>
    </JOBS>
</Emp>
<Emp>
    <EMPID>456</EMPID>
    <NAME>Clark</NAME>
    <Sequence>2</Sequence>
    <JOBS>
        <COMPANY>GHT</COMPANY>
        <DESIGNATION>QA Lead</DESIGNATION>
    </JOBS>
</Emp>
<Emp>
    <EMPID>456</EMPID>
    <NAME>Clark</NAME>
    <Sequence>2</Sequence>
    <JOBS>
        <COMPANY>Levor</COMPANY>
        <DESIGNATION>Project Lead</DESIGNATION>
    </JOBS>
</Emp>
</Employee>

I have tried this below XSLT and different trails it didnt work, can you please help me to correct this XSLT to get desire output
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="Employee">
    <xsl:element name="Employee">
        <xsl:for-each select="Employee">
            <xsl:sort select="Sequence"/>
            <xsl:element name="Emp">
                <xsl:copy-of select="EMPID"/>
                <xsl:copy-of select="NAME"/>
                <xsl:copy-of select="Sequence"/>
                <xsl:for-each select="child::JOBS">
                    <xsl:copy-of select="COMPANY"/>
                    <xsl:copy-of select="DESIGNATION"/>
                </xsl:for-each>
            </xsl:element>
        </xsl:for-each>
    </xsl:element>
</xsl:template>
</xsl:stylesheet>

Please help me?

Added:
Thank you for the quick response, but i forgot to add a case here that JOBS aggregate wont be available for all Employees like below
<Employee>
<Emp>
    <EMPID>123</EMPID>
    <NAME>James</NAME>
    <Sequence>1</Sequence>
    <JOBS>
        <COMPANY>ABC</COMPANY>
        <DESIGNATION>Developer</DESIGNATION>
    </JOBS>
    <JOBS>
        <COMPANY>DEF</COMPANY>
        <DESIGNATION>Tester</DESIGNATION>
    </JOBS>
</Emp>
<Emp>
    <EMPID>789</EMPID>
    <NAME>Anderson</NAME>
    <Sequence>3</Sequence>
</Emp>
<Emp>
    <EMPID>456</EMPID>
    <NAME>Clark</NAME>
    <Sequence>2</Sequence>
    <JOBS>
        <COMPANY>GHT</COMPANY>
        <DESIGNATION>QA Lead</DESIGNATION>
    </JOBS>
    <JOBS>
        <COMPANY>Levor</COMPANY>
        <DESIGNATION>Project Lead</DESIGNATION>
    </JOBS>
</Emp>
</Employee>

So here Anderson doesn't have emp, and result should be like this
<Employee>
<Emp>
    <EMPID>123</EMPID>
    <NAME>James</NAME>
    <Sequence>1</Sequence>
    <JOBS>
        <COMPANY>ABC</COMPANY>
        <DESIGNATION>Developer</DESIGNATION>
    </JOBS>
</Emp>
<Emp>
    <EMPID>123</EMPID>
    <NAME>James</NAME>
    <Sequence>1</Sequence>
    <JOBS>
        <COMPANY>DEF</COMPANY>
        <DESIGNATION>Tester</DESIGNATION>
    </JOBS>
</Emp>
<Emp>
    <EMPID>456</EMPID>
    <NAME>Clark</NAME>
    <Sequence>2</Sequence>
    <JOBS>
        <COMPANY>GHT</COMPANY>
        <DESIGNATION>QA Lead</DESIGNATION>
    </JOBS>
</Emp>
<Emp>
    <EMPID>456</EMPID>
    <NAME>Clark</NAME>
    <Sequence>2</Sequence>
    <JOBS>
        <COMPANY>Levor</COMPANY>
        <DESIGNATION>Project Lead</DESIGNATION>
    </JOBS>
</Emp>
<Emp>
    <EMPID>789</EMPID>
    <NAME>Anderson</NAME>
    <Sequence>3</Sequence>
</Emp>
</Employee>

Can you please help me here?

A: Edited in response to clarification:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/Employee">
    <xsl:copy>
        <xsl:apply-templates select="Emp">
            <xsl:sort select="Sequence"/>
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template>

<xsl:template match="Emp[not(JOBS)]">
     <xsl:copy-of select="."/>
</xsl:template>

<xsl:template match="Emp">
    <xsl:apply-templates select="JOBS"/>
</xsl:template>

<xsl:template match="JOBS">
    <Emp>
        <xsl:copy-of select="../EMPID | ../NAME | ../Sequence | ."/>
    </Emp>
</xsl:template>

</xsl:stylesheet>


text:
Q: Removing unused months on ggplot I have a dataframe that only lists months from October to April. When I plot this data on a line graph, it includes the unused months as well. I would only like to show the months that are listed in the data so there is no unused space on the plot.
The code I am using for the plot
gplot(df,aes(GAME_DATE,DEF_RATING)) +
   geom_line(aes(y=rollmean(df$DEF_RATING,9, na.pad = TRUE))) +
   geom_line(aes(y=rollmean(df$OFF_RATING,9,na.pad = TRUE)),color='steelblue')

Sample data
    GAME_DATE OFF_RATING DEF_RATING
       <dttm>      <dbl>      <dbl>
 1 2017-04-12      106.1      113.1
 2 2017-04-10      107.1      100.8
 3 2017-04-08      104.4      105.1
 4 2017-04-06      116.1      105.9
 5 2017-04-04      116.9      116.0

A: ggplot2 doesn't allow broken axes because such axes can be misleading. However, if you still want to proceed with this, you can simulate a broken axis with faceting. To do this, create a grouping variable to mark each "island" where data is present with a unique group code and then facet by those group codes.
Also, the data should be converted to long format before plotting, so that you can get two separate colored lines with a single call to geom_line. Mapping a column to color inside aes will also automatically generate a legend.
Here's an example with fake data:
library(tidyverse)

# Fake data
set.seed(2)
dat = data.frame(x=1950:2000,
                 y1=c(cumsum(rnorm(30)), rep(NA,10), cumsum(rnorm(11))),
                 y2=c(cumsum(rnorm(30)), rep(NA,10), cumsum(rnorm(11))))

dat %>%
  # Convert to long format
  gather(key, value, y1:y2) %>%
  # Add the grouping variable
  group_by(key) %>%
  mutate(group=c(0, cumsum(diff(as.integer(is.na(value)))!=0))) %>%
  # Remove missing values
  filter(!is.na(value)) %>%
  ggplot(aes(x, value, colour=key)) +
    geom_line() +
    scale_x_continuous(breaks=seq(1950,2000,10), expand=c(0,0.1)) +
    facet_grid(. ~ group, scales="free_x", space="free_x") +
    theme(strip.background=element_blank(),
          strip.text=element_blank())

A: You can try to delimiting x-axis with "scale_x_date()" for your present dates like this:
gplot(df,aes(GAME_DATE,DEF_RATING)) +
geom_line(aes(y=rollmean(df$DEF_RATING,9, na.pad = TRUE))) +
geom_line(aes(y=rollmean(df$OFF_RATING,9,na.pad = TRUE)),color='steelblue') +
scale_x_date(date_labels="%b",breaks=seq(min(df$GAME_DATE),max(df$GAME_DATE), "1 month"))


text:
Q: parse lua script and connect with C++ codes I am not sure whether it is suitable to ask this question here, but I will try to explain my question as clearly as possible.
I have a machine to control. Basic operation functions (e.g. move, open doors, wait for commands, etc.), interfaces, etc are all writen in C++, and we need to write some service scripts in lua. The pseudo codes of service scripts are like:
 * define the service name and give some description
 * declare the task address
 * declare the input and output class name
 * list the input plugin files
 * define a "run" function
   -- publish the machine state
   -- initialize the machine
   -- wait for commands
   -- call the "service" function
   -- wait for stop command
 * define a "service" function
   -- set the service state to be true
   -- move the car to destination
   -- open the door for a while
   -- close the door
 * after the service is finished, send a "finish" flag to the center handler.

In this pseudo code, we have 2 functions, and lines started with "--" are usually basic operation functions written in C++ or functions defined in other lua plugin files.
I have written very simple C++ code and Lua script before and connected them. But they are just like pass a table of numbers from C++ to lua, use functions in lua to calculate the sum/factorial/sqaure... and then pass the result back to C++ and print out. In such exercises, I just used functions such as    lua_State *L;
    L = luaL_newstate();
    luaL_openlibs();
        luaL_loadfile();
        lua_pcall();
        lua_tostring();
        lua_tonumber();
        ......
But now I need to handle such a complicated lua script and C++ code system. I think simply doing what I used to do is not enough....I was wondering whether there is a specific way to parse the lua script, get value of each component (task address, function, etc..) and save them in C++ code, then probably it will be easier for me to connect the extracted component to existing C++ functions....
Or is this possible: just return everything (including values, functions, etc...) from lua in the form of table, then I write a C++ code to read the table and save the values, and then I connect the extracted items to existing C++ functions....
I am not sure whether I make my question clearly...I am newbie in Lua and I think there is a large deal of greatness of Lua that I haven't found..I know people say that Lua is a light and fast language and I want to make the most of it. If you understand my question and have better ideas to solve my problem, I will be more than happy to learn!

A: In this case I would not just stick to Lua, but rather prepare some Domain Specific Language. In example you provided there is informal syntax of your language that will need formal record.
You will need to define tokens (atoms of your language) and then grammar rules (how to build services out of those tokens). Something that will look more or less like:
%tokens {
    NUMBER = [0-9]+
    NAME = [A-Z]+
    STRING = \"[^\"]\"
}

%rules {
    script: service
          | service script

    service: "def" NAME "doc" STRING "address" NUMBER io body

    io: //and much more here
}

There is lots of tools that can convert that formal definition into parser, or interpreter.
As a C++ developer you might like Bison/Flex. This is Compiler Compiler written in C, it compiles files that contains mixed C/C++ codes with definition of tokens and rules.
If you do not need to write your parser in C++ then I will recommend you to use ANTLR which is IMO simpler to use.

A: You should look into the ability of the lua API to receive C functions directly into the environment when they are pushed as function pointers:
lua_pushcfunction(L, func);

where func has signature:
int func(lua_State * L);

Using this mechanism, you can make an API to control the doors and such from the scripts, and it will be very natural for the lua scripter to control it. That will be much better than having lua compute a bunch of tables that encode what should happen, I think.


text:
Q: Binding in Flex: How to make a variable automatically update when another variable is changed? I know that it is possible to make a parameter of a component depend on a variable, provided that variable contains the [Bindable] tag. This means that updating the value of the Bindable variable automatically updates the component.
Is it possible to make another variable depend on a Bindable variable?
In the example below I have a variable btnClicked that is bound. When btnClicked is changed by the function btnClick() being called, the text in the TextArea is updated as expected.
I would like to be able to make another variable, btnText, be updated when btnClicked is updated. I do not know how to communicate this dependency. In the code below the value of btnText is initially "clickMe" as expected. However, when btnClicked changes, the text on the button does not update to "unclickMe".
<fx:Script>
    <![CDATA[
        [Bindable]
        public var btnClicked:Boolean = false;

        public function btnClick():void{
            btnClicked = !btnClicked;
        }

        [Bindable]
        public function get btnText():String{
            return btnClicked?"unclickMe":"clickMe";
        }
    ]]>
</fx:Script>

<s:Button click="btnClick()" label="{btnText}"/>

<s:TextArea y="50" text="{btnClicked?'Button is clicked':'Button is unclicked'}"/>

How can I change the code above so that btnText automatically updates when btnClicked is changed?
Would it be possible to have an arbitrarily long chain of connected variables each of which updates when the previous one updates?

A: You can also use a ChangeWatcher to detect when your bindable property is updated :
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx" creationComplete="init(event)">

    <fx:Script>
        <![CDATA[

            import mx.binding.utils.ChangeWatcher;
            import mx.events.FlexEvent;

            public var watcher:ChangeWatcher;

            [Bindable]
            public var btnClicked:Boolean = false;
            [Bindable]
            public var btnText:String = 'clickMe';

            protected function btnClick():void {
                btnClicked = !btnClicked;
            }

            protected function init(event:FlexEvent):void
            {
                watcher = ChangeWatcher.watch(this, 'btnClicked', watcherListener);
            }

            protected function watcherListener(event:Event):void {
                btnText = btnClicked ? 'unclickMe' : 'clickMe';
            }

        ]]>
    </fx:Script>

    <s:Button x="303" y="30" label="{btnText}" click="btnClick()"/>
    <s:TextArea x="303" id="txt" y="96" text="{btnClicked ? 'Button is clicked' : 'Button is unclicked'}"/>

</s:Application>

Hope that can help.

A: In this case, all you have to do is update your btnClick function to dispatch a PropertyChangeEvent:
public function btnClick():void{
    btnClicked = !btnClicked;
    dispatchEvent(new PropertyChangeEvent(PropertyChangeEvent.PROPERTY_CHANGE));
}

This works because of the way [Bindable] works - see What does [Bindable] mean in actionscript? for a nice explanation.
Using the Bindable metadata tag and Binding to functions, Objects, and Arrays are good resources for background reading, too.
Edit:  Don't forget the import statement!
import mx.events.PropertyChangeEvent;

Flash Builder will insert the import statement for you if you ctrl-space while typing PropertyChangeEvent.

A: I have found a solution, but if someone has a cleaner solution that makes use of in built Flex features please post it.
The following code updates the value of btnText each time the value of btnClicked is changed. It does this by having a setter function for btnClicked that explicitly calls function updateBtnText. See this explanation for more information about how getters and setters allow you to call other functions any time a variable is read or written.
<fx:Script>
    <![CDATA[
        private var _btnClicked:Boolean = false;

        [Bindable]
        public function get btnClicked():Boolean{
            return _btnClicked;
        }

        public function set btnClicked(newBtnClicked:Boolean):void{
            _btnClicked = newBtnClicked;
            updateBtnText();
        }

        private function updateBtnText():void{
            btnText = btnClicked?"unclickMe":"clickMe";
        }

        public function btnClick():void{
            btnClicked = !btnClicked;
        }

        [Bindable]
        public var btnText:String = btnClicked?"unclickMe":"clickMe";

    ]]>
</fx:Script>

<s:Button click="btnClick()" label="{btnText}"/>

<s:TextArea y="50" text="{btnClicked?'Button is clicked':'Button is unclicked'}"/>


text:
Q: Matplotlib in Sublime Text 3 I've recently started using sublimetext 3, the plt.show() function doesn't seem to work when run within sublimetext.
I have create the following script:
import matplotlib.pyplot as plt
year = [1950, 1970, 1990, 2010]
pop = [2.519, 3.692, 5.263, 6.972]
plt.plot(year, pop)
plt.show()

Running this with IDLE generates a plot, however using sublimetext no output is generated.
I use the following build system
{
    "cmd": ["/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6", "-u", "$file"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python",
    "shell": true
}

If someone can please tell me what i am doing wrong, because i don't see any build errors but i still don't see any graph.
If someone could please help in this regard - Thanks

A: Sublime is great, but doesn't do well with certain things (eg, input() and Kivy displays, among other things).
Try using another IDE such as Spyder. (Your sample code renders just fine for me.)

A: For Windows: I recently had a problem loading a map on the screen. After many tries, I got a simple solution...running the python program by the cmd prompt. This way, the map just popped up on my screen. I still using sublime text becouse for me is the better editor, very light and fast.

A: Mostly, you are not using Sublime Text 3.0
You can Download 3.0 version then download the package (For Mac, Press Command+Shift+P -->Package Control: Install Package)
It will definitely work after that. Here is the graph plotted using your code.Plot Image


text:
Q: Planning: To split or not to split logic into separate controllers I'm planning out a web application using Laravel for the server side structure. The main goal of the application is to display a form that will allow the user to enter in Parent/Guardian and related Student information. The additional goals will be to allow administrators to log in and look up Parent/Guardian and Student data that has been submitted.
At the simplest, I feel like I could do this by using one controller for "Form" that facilitates the display of the form, the submission of the form data, and the showing of the stored data.
Thinking forward though, it seems like it would be beneficial to have the logic for the Parent/Guardians and the Students in separate resourceful controllers to make it easier/clearer to access and work with the logic per entity. If I did it this way though, it seems like I would need a third controller for the Form that would then call out to methods in the Parent/Guardian and Student controllers separately.
What would be the best way of approaching this structure? I want to go for the "pass the salt" or "just program what you need now" approach, but I know that I'll need more refined access to Parent/Guardians and Student data in the near future. My goal is to minimize the amount of refactoring by planning well at the beginning.
Any suggestions or insight would be appreciated.
Thanks!


text:
Q: How to use shared resource file between projects in one solution? I have a problem with resource files.
I have a solution with two projects. The first project contains ImageResource.resx file with the images that I use. Every Form in this project can access this file from the designer. But I can see in the designer ImageResource.resx file to use it from second project (Reference to second project is present).
I have added the ImageResource.resx file as a link to my second project. And I saw it in the designer! But when I use an image from this resource in the second project Visual Studio modified my original file (It sets the namespaces, and other..) and my solution breaks. Also Visual Studio tells me that ImageResource.resx is present in two dll's first_project.dll and second_project.dll
Can anybody help me with How to correctly use shared resources between projects?

A: *

*The correct way to share resources is to create a global shared project. Create a new Project with the name Resources:

*Next we must add some resources (such as icons) to the project. Do this as usual. Go to the projects setting, select tab Resources and Add Existing File… to the project. We can see that the icon is added to the project and was copied to the local folder:

*Next step consists of adding this icon to the other project(s). Note the important difference, you need to add this icon as a link!
Adding as a link avoids the resource duplication. Create a new Project within the same solution and name it e.g. Main. Create some folder in this new project, naming it Resources (the logical name for our purpose). Then right click on this folder, select Add Existing Item… and choose the image file from the shared project folder. Make sure to use Add As Link here! If done correctly the icon of the newly added file will look slightly different (see below):

Added resource's icon must look like this

*Now we must set the Build Action for this file to None. For this select the file and go to the Properties Window. There choose None for Build Action. We need to do this to avoid embedding this icon into the assembly:

*Finally we need to add the linked files to the Resources of the corresponding project. Open the project Properties for the project where we just added the files. Choose the Resource tab and drag the linked file there:

These are the five simple steps you must perform to share icons between projects. You might ask "What are the benefits of this?" The benefits are:

*

*We store resources in one place, and

*It is easy to replace an icon with a new one.

A: This didn't work for me and I found another (VS2015+) approach.
 See https://stackoverflow.com/a/45471284/4151626
In short, the shared project is directly included into the peripheral project.  Thus, even though the IDE does not support <Resource> elements in the shared project.  <Resource> elements can be added to the shared project, via a text editor.  They are then incorporated into the peripheral project during the build.
(Apologies for the hyper-link.  I would just repost the answer for clarity, but the stackoverflow editors crack down on this, deleting duplicate answers to save you from ???.)

A: Can you use a symbolic link to share the file into multiple folders?
windows:
mklink linked_location\ImageResource.resx original_location\ImageResource.resx

C:\Users\preet>mklink
Creates a symbolic link.

MKLINK [[/D] | [/H] | [/J]] Link Target

        /D      Creates a directory symbolic link.  Default is a file
                symbolic link.
        /H      Creates a hard link instead of a symbolic link.
        /J      Creates a Directory Junction.
        Link    specifies the new symbolic link name.
        Target  specifies the path (relative or absolute) that the new link
                refers to.

A: If a resource file is really shared between projects, you should put it in a shared project.
Solution 'Sample'
   Project Sample.Data
   Project Sample.Business
   Project Sample.UI
   Project Sample.Resource   //shared resources are put in a shared project

A: You can't see the resource if it is not public, and it is default set to "Friend". You can set the "Access Modifier" in the Visual Designer (upper right-hand corner).


text:
Q: Fast checking if a string can be converted to float or int in python I need to convert all strings in a large array to int or float types, if they can be converted. Usually, people suggest try-except or regex approach (like in Checking if a string can be converted to float in Python), but it turns out to be very slow.
The question is: how to write that code the fastest way possible?
I found that there is .isdigit() method of a string. Is there something like that for floats?
Here is the current (slow) code.
    result = []
    for line in lines:
        resline = []
        for item in line:
            try:
                resline.append(int(item))
            except:
                try:
                    resline.append(float(item))
                except:
                    resline.append(item)
        result.append(resline)
    return np.array(result)

There is also some evidence (https://stackoverflow.com/a/2356970/3642151) that regex approach is even slower.

A: Your return value shows you are using NumPy. Therefore, you should be using np.loadtxt or np.genfromtxt (with the dtype=None parameter) to load the lines into a NumPy array.
The dtype=None parameter will automatically detect if the string can be converted to a float or int.
np.loadtxt is faster and requires less memory than np.genfromtxt, but requires you to specify the dtype -- there is no dtype=None automatic-dtype-detection option. See Joe Kington's post for a comparsion.
If you find loading the CSV using np.loadtxt or np.genfromtxt is still too slow, then using Panda's read_csv function is much much faster, but (of course) would require you to install Pandas first, and the result would be a Pandas DataFrame, not a NumPy array. DataFrames have many nice features (and can be converted into NumPy arrays), so you may find this to be an advantage not only in terms of loading speed but also for data manipulation.

By the way, if you don't specify the dtype in the call
np.array(data)

then np.array uses a single dtype for all the data. If your data contains both ints and floats, then np.array will return an array with a float dtype:
In [91]: np.array([[1, 2.0]]).dtype
Out[91]: dtype('float64')

Even worse, if your data contains numbers and strings, np.array(data) will return an array of string dtype:
In [92]: np.array([[1, 2.0, 'Hi']]).dtype
Out[92]: dtype('S32')

So all the hard work you go through checking which strings are ints or floats gets destroyed in the very last line.
np.genfromtxt(..., dtype=None) gets around this problem by returning a structured array (one with heterogenous dtype).

A: Try profiling your Python script, you'll find out that try... except, float or int are not the most time consuming calls in your script.
import random
import string
import cProfile

def profile_str2float(calls):
    for x in xrange(calls):
        str2float(random_str(100))

def str2float(string):
    try:
        return float(string)
    except ValueError:
        return None

def random_str(length):
    return ''.join(random.choice(string.lowercase) for x in xrange(length))

cProfile.run('profile_str2float(10**5)', sort='cumtime')

Running this script I get the following results:
         40400003 function calls in 14.721 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000   14.721   14.721 <string>:1(<module>)
        1    0.126    0.126   14.721   14.721 str2float.py:5(profile_str2float)
   100000    0.111    0.000   14.352    0.000 str2float.py:15(random_str)
   100000    1.413    0.000   14.241    0.000 {method 'join' of 'str' objects}
 10100000    4.393    0.000   12.829    0.000 str2float.py:16(<genexpr>)
 10000000    7.115    0.000    8.435    0.000 random.py:271(choice)
 10000000    0.760    0.000    0.760    0.000 {method 'random' of '_random.Random' objects}
 10000000    0.559    0.000    0.559    0.000 {len}
   100000    0.242    0.000    0.242    0.000 str2float.py:9(str2float)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

As you can see from the Cumulative Time stat, str2float function is not consuming much CPU time, in 100.000 calls it barely uses 250ms.

A: All generalizations are false (irony intended).  One cannot say that try: except: is always faster than regex or vice versa.  In your case, regex is not overkill and would be much faster than the try: except: method.  However, based on our discussions in the comments section of your question, I went ahead and implemented a C library that efficiently performs this conversion (since I see this question a lot on SO); the library is called fastnumbers.  Below are timing tests using your try: except: method, using regex, and using fastnumbers.

from __future__ import print_function
import timeit

prep_code = '''\
import random
import string
x = [''.join(random.sample(string.ascii_letters, 7)) for _ in range(10)]
y = [str(random.randint(0, 1000)) for _ in range(10)]
z = [str(random.random()) for _ in range(10)]
'''

try_method = '''\
def converter_try(vals):
    resline = []
    for item in vals:
        try:
            resline.append(int(item))
        except ValueError:
            try:
                resline.append(float(item))
            except ValueError:
                resline.append(item)

'''

re_method = '''\
import re
int_match = re.compile(r'[+-]?\d+$').match
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def converter_re(vals):
    resline = []
    for item in vals:
        if int_match(item):
            resline.append(int(item))
        elif float_match(item):
            resline.append(float(item))
        else:
            resline.append(item)

'''

fn_method = '''\
from fastnumbers import fast_real
def converter_fn(vals):
    resline = []
    for item in vals:
        resline.append(fast_real(item))

'''

print('Try with non-number strings', timeit.timeit('converter_try(x)', prep_code+try_method), 'seconds')
print('Try with integer strings', timeit.timeit('converter_try(y)', prep_code+try_method), 'seconds')
print('Try with float strings', timeit.timeit('converter_try(z)', prep_code+try_method), 'seconds')
print()
print('Regex with non-number strings', timeit.timeit('converter_re(x)', prep_code+re_method), 'seconds')
print('Regex with integer strings', timeit.timeit('converter_re(y)', prep_code+re_method), 'seconds')
print('Regex with float strings', timeit.timeit('converter_re(z)', prep_code+re_method), 'seconds')
print()
print('fastnumbers with non-number strings', timeit.timeit('converter_fn(x)', prep_code+fn_method), 'seconds')
print('fastnumbers with integer strings', timeit.timeit('converter_fn(y)', prep_code+fn_method), 'seconds')
print('fastnumbers with float strings', timeit.timeit('converter_fn(z)', prep_code+fn_method), 'seconds')
print()

The output looks like this on my machine:
Try with non-number strings 55.1374599934 seconds
Try with integer strings 11.8999788761 seconds
Try with float strings 41.8258318901 seconds

Regex with non-number strings 11.5976541042 seconds
Regex with integer strings 18.1302199364 seconds
Regex with float strings 19.1559209824 seconds

fastnumbers with non-number strings 4.02173805237 seconds
fastnumbers with integer strings 4.21903610229 seconds
fastnumbers with float strings 4.96900391579 seconds

A few things are pretty clear

*

*try: except: is very slow for non-numeric input; regex beats that handily

*try: except: becomes more efficient if exceptions don't need to be raised

*fastnumbers beats the pants off both in all cases

So, if you don't want to use fastnumbers, you need to assess if you are more likely to encounter invalid strings or valid strings, and base your algorithm choice on that.


text:
Q: on refresh full calendar adds duplicate events On the first load of the page, it shows a single event per day, but on the second load (or refresh of the page) it adds a duplicate event on the same day in the full calendar.
Here is my code:
var CalendarView = Backbone.View.extend({

    el : '#calendar-box',
    initialize : function() {
    // TODO for instance: more instances, Event Bus bindings... only once.
    this.calendarModel = new CalendarModel();
    $('#calendar-box').hide();
    var date = new Date();
    var d = date.getDate();
    var m = date.getMonth();
    var y = date.getFullYear();

    this.calendarModel.fetch({
        success : function(model, response, options) {
            $.unblockUI();
           var count=0;
            var eventsList=[];
            model.attributes.result.forEach(function(){
                eventsList.push({
                    id: model.attributes.result[count].eventId,
                    title:model.attributes.result[count].title,
                    start: new Date(model.attributes.result[count].startDate),
                    end: new Date(model.attributes.result[count].endDate),
                    attorneyName: model.attributes.result[count].attorneyName,
                    codeLitOrg: model.attributes.result[count].codeLitOrg,
                    balance: model.attributes.result[count].balance,
                    litCode: model.attributes.result[count].litCode
                });
                count++;
            });
            if (!_.isEmpty(eventsList)){
                    $('#calendar').fullCalendar({
                        editable: true,
                        events: eventsList,
                        eventMouseover: function(event, jsEvent, view) {
                            var info = event.title+'\nBK/LIT: '+event.codeLitOrg+'\nBalance: '+event.balance
                            +'\nAttorney: '+event.attorneyName+'\nLitCode: '+event.litCode;
                            $(jsEvent.target).attr('title', info);
                        },
                        theme: false,
                        height:575,
                        weekMode:'liquid',
                        header: {
                            left: 'prev,next today',
                            center: 'title',
                            right: 'month,agendaWeek,agendaDay'
                        },
                    });
            }
        },
        error : function(model, xhr, options) {
            $.unblockUI();
        }
    });

    $.eventBus.on('calendarModalLoaded',function(){
        if (!($('.fc-border-separate').html())){
            $('#calendar').fullCalendar('today');
        }
    });
    },
    render : function() {
        // TODO for instance, bindings elements after ready in DOM.
        $('#calendar').fullCalendar('today');
        return this;
    },
    events : {
        'click a.op-attorney-info' : 'onAttorneyInfo',
        'click .go-back-link' : 'goBack'
    },

    goBack: function(){
        $('#calendar-box, .content-box').toggle();
        //$('.content-box').toggle();
        //$('.go-back-link').hide();
    },

    onAttorneyInfo : function(ev) {
    // TODO for instance, fetch attorney's model
    }
});

return CalendarView;
});

I have tried $('#calendar').fullCalendar('removeEvents'), but it is also not working.
Please help me out.


text:
Q: Always getting java.io.FileNotFoundException and requiring 'REFRESH TABLE tableName' when querying Hive and transforming data I run a scheduled process which queries a table in Hive using sparkSQL and does some transformations and then counting the rows in the dataset:
val dataset       = this.query_hive(sql_statement)
val result_interm = this.transformation_step1(dataset)
val result        = this.transformation_step2(result_interm)
println(result.count())

The issue I have is the table in Hive, which gets updated rather frequently, and whenever its getting updated while the spark job is running, I get Spark java.io.FileNotFoundException, invalidate the cache in Spark by running REFRESH TABLE table error message from Spark. My question: is there a way I can prevent this?

A: You could try following options:

*

*Run REFRESH TABLE right before using some transformations.

*Write some try-finally code section where you will emulate some kind of retry logic.

*Actually, third option I was not able to test, but you could try to create the table that updates frequently as MANAGED table and then create another EXTERNAL table which will point to location with the MANAGED table, in this way it could read the old values and do not crush on java.io.FileNotFoundException
Hope this could help.


text:
Q: How to create PRIMARY KEY in VIEW that uses OUTER JOIN I have created view that must use FULL OUTER JOIN.
I want to use this view in EDMX with DbFirst approach.
But the EDMX is generating next warning:

        <!--Errors Found During Generation:
warning 6013: The table/view 'MyView' does not have a primary key defined and no valid primary key could be inferred. This table/view has been excluded. To use the entity, you will need to review your schema, add the correct keys, and uncomment it.

I tried to solve this by adding

CREATE UNIQUE CLUSTERED INDEX PK_MyView ON [dbo].[MyView] (Id)

But Sql says:

Cannot create index on view "dbo.MyView" because it uses a LEFT, RIGHT, or FULL OUTER join, and no OUTER joins are allowed in indexed views. Consider using an INNER join instead.

Is there a way to add view without PK to edmx or add PK to the view.

A: You are creating an Indexed View and there are restrictions on the type of joins you can do in an Indexed view. Mainly, you can only perform an inner join. All other types of joins are not allowed.
There is a work-around to this limitation, which you can read about here to see if it's appropriate in your situation. It's not a particularly attractive work-around though.
You generally don't need to index views unless you intend to use the indexed view to aggregate data, which is what indexed views are primarily useful for. Otherwise, having the appropriate indexes on the base tables should eliminate the need for an indexed view.


text:
Q: How can I group data by matching identical cells in same column then counting instances of a related column? data output
I am pretty new to Webi and am having an issue creating a variable. I'm trying to check if there is more than 1 email address for each entity legacy account number and if 1 of the contact names contains "Annual Report". So when I flag each entity legacy account number for no email only the ones without a contact name that contains "Annual Report" will be pulled. In the example above only the yellow groups should be called no email. Right now all of them are being pulled into no email. I have tried using if and match as those are what I am most familiar with. Does anyone have any suggestions?

A: There are number of ways you could do this. I am going to give an example using two variables, but you could easily combine them into one.
Has No Email Var=If(Match(Upper([Contact EmailAddress]); "NOEMAIL*"); 1; 0)
Annual Report Contact Name Var=If(Match(Upper([Contact Name]); "ANNUAL REPORT*"); 1; 0)

Then you would apply a report filter with two components...
Has No Email Var = 1
AND
Annual Report Contact Name Var = 0

Let me explain a few things...

*

*The purpose of the Upper function is the Match function is case sensitive. If you know your email address are always lower case then you could remove that the Upper function and have it match on "noemail*".

*It is significant that I only have a asterisk ("*") at the end of the string being sought. That will only find a match where the corresponding column value starts with that string. If you want it to be true whenever the string is found anywhere in the column being searched you would be asterisks on both ends.

*You could also put limiting criteria in your query filter. But here is where thing can get confusing. Within the query filter you can choose the Matches pattern operator. However, the wildcard character is different ("%" rather than "*") and you do not put double-quotes around your search text. So you would have some thing like this...

Contact EmailAddress Matches pattern noemail%
AND
Contact Name Different from pattern Annual Report%

I am sure you noticed I didn't convert the search text to uppercase. In the Query Panel Web Intelligence is case-insensitive and would likely follow the case-sensitivity of the database of the source data. All of our databases are case-insensitive so if yours is case-sensitive you may need to play around this this a bit. Or just go with the approach of creating the variables and report filters as I initially laid out.

*If you want a wildcard for a single character rather than multiple characters (which is what "*" and "%" will do) you need to use a "?" within your variable definition or a "_" in your query filter.
Hope this helps,
Noel


text:
Q: SHFileOperation FOF_ALLOWUNDO fails on long filenames I'm using the following function to delete a file to the recycle bin: (C++, MFC, Unicode)
bool DeleteFileToPaperbasket (CString filename)
{
   TCHAR Buffer[2048+4];

   _tcsncpy_s (Buffer, 2048+4, filename, 2048);
   Buffer[_tcslen(Buffer)+1]=0; //Double-Null-Termination

   SHFILEOPSTRUCT s;
   s.hwnd                  = NULL;
   s.wFunc                 = FO_DELETE;
   s.pFrom                 = Buffer;
   s.pTo                   = NULL;
   s.fFlags                = FOF_ALLOWUNDO | FOF_SILENT | FOF_NOERRORUI;
   s.fAnyOperationsAborted = false;
   s.hNameMappings         = NULL;
   s.lpszProgressTitle     = NULL;

   int rc = SHFileOperation(&s);

   return (rc==0);
}

This works nicely for most files. But if path+filename exceed 255 characters (and still much shorter that 2048 characters), SHFileOperation returns 124. Which is DE_INVALIDFILES.
But what's wrong? I checked everything a million times. The path is double-null terminated, I'm not using \\?\ and it works for short filenames.
I'm totally out of ideas...

A: I think backwards comparability is biting you in the --- in several ways, and I'd need to actually see the paths your using and implement some error checking code to help.  But here are some hints.

*

*You would not get a DE_INVALIDFILES  0x7C "The path in the source or destination or both was invalid." for a max path violation, you'd get a DE_PATHTOODEEP  0x79 "The source or destination path exceeded or would exceed MAX_PATH."

*These error codes(return value) do, can, and have changed over time, to be sure what your specific error code means, you need to check it with GetLastError function(msdn)

*Also, taken from the SHFileOperation function documentation: "If you do not check fAnyOperationsAborted as well as the return value, you cannot know that the function accomplished the full task you asked of it and you might proceed under incorrect assumptions."

*You should not be using this API for extremely long path names, it has been replaced in vista+ by IFileOperation interface

*The explanation for why it may work in explorer and not thru this LEGACY api is - Taken from the msdn page on  Naming Files, Paths, and Namespaces

The shell and the file system have different requirements. It is
  possible to create a path with the Windows API that the shell user
  interface is not able to interpret properly.

Hope this was helpful

A: The recycle bin doesn't support files whose paths exceed MAX_PATH in length. You can verify this for yourself by trying to recycle such a file in Explorer - you will get an error message about the path being too long.


text:
Q: Kubuntu Live session is able to see local drive, but Home folder is empty I'm rebuilding my PC - for some reason Kubuntu 22.04 LTS has been buggy as hell and it finally got to the point where it wouldn't boot. I'm going to reinstall the OS and let the installer do what it wants in case my mucking about with partitions screwed something up.
I'd like to retrieve a few files from the old installation, but Dolphin says the Home folder is empty. I'm viewing the right partition because I recognize as mine the HOSTS file in the /etc folder.
I downloaded "Disks" and checked the physical drive and it appears to be fine.
I don't know what I don't know. What's going on?


text:
Q: Pjsip Use Sip-Specific Event Notification for Notify message I want to implement Notify event CallBack in CsipSimple here is the C code i have written
My C/C++ files
The pjsip_event_notification.h file
#include <pjsip-simple/evsub.h>

class EventCallBack {

public:
        virtual ~EventCallBack() {}

        virtual void on_evsub_state(pjsip_evsub *sub, pjsip_event *event){}
        virtual void on_tsx_state(pjsip_evsub *sub, pjsip_transaction *tsx,
                        pjsip_event *event){}
        virtual void on_rx_refresh(pjsip_evsub *sub, pjsip_rx_data *rdata,
                        int p_st_code, pj_str_t **p_st_text, pjsip_hdr *res_hdr,
                        pjsip_msg_body **p_body){}
        virtual void on_rx_notify(pjsip_evsub *sub, pjsip_rx_data *rdata, int *p_st_code,
                        pj_str_t **p_st_text, pjsip_hdr *res_hdr, pjsip_msg_body **p_body){}
        virtual void on_client_refresh(pjsip_evsub *sub){}
        virtual void on_server_timeout(pjsip_evsub *sub){}

};
extern "C" {
void setEventCallbackObject(EventCallBack* eventCallBack);
}

pjsip_event_notification.cpp file
#include "pjsip_event_notification.h"
static EventCallBack* registeredCallbackObject = NULL;

extern "C" {

 void on_evsub_state_wrapper(pjsip_evsub *sub, pjsip_event *event){
                registeredCallbackObject->on_evsub_state(sub,event);

 }
 void on_tsx_state_wrapper(pjsip_evsub *sub, pjsip_transaction *tsx,
                pjsip_event *event){
         registeredCallbackObject-> on_tsx_state(sub,tsx,event);
 }
 void on_rx_refresh_wrapper(pjsip_evsub *sub, pjsip_rx_data *rdata,
                int p_st_code, pj_str_t **p_st_text, pjsip_hdr *res_hdr,
                pjsip_msg_body **p_body){
         registeredCallbackObject->on_rx_refresh(sub,rdata,p_st_code,p_st_text,res_hdr,p_body);

 }
 void on_rx_notify_wrapper(pjsip_evsub *sub, pjsip_rx_data *rdata, int *p_st_code,
                pj_str_t **p_st_text, pjsip_hdr *res_hdr, pjsip_msg_body **p_body){
         registeredCallbackObject->on_rx_notify(sub,rdata,p_st_code,p_st_text,res_hdr,p_body);
 }
 void on_client_refresh_wrapper(pjsip_evsub *sub){
         registeredCallbackObject->on_client_refresh(sub);
 }
 void on_server_timeout_wrapper(pjsip_evsub *sub){
         registeredCallbackObject->on_server_timeout(sub);
 }

// struct event_callback wrapper_callback_event_struct = {
//               &on_evsub_state_wrapper,
//               &on_tsx_state_wrapper,
//               &on_rx_refresh_wrapper,
//               &on_rx_notify_wrapper,
//               &on_client_refresh_wrapper,
//               &on_server_timeout_wrapper
// };

 void setEventCallbackObject(EventCallBack* eventCallBack){
         registeredCallbackObject=eventCallBack;
 }

and the Java files used to implement
package com.csipsimple.events;

import org.pjsip.pjsua.EventCallBack;
import org.pjsip.pjsua.SWIGTYPE_p_int;
import org.pjsip.pjsua.SWIGTYPE_p_p_pj_str_t;
import org.pjsip.pjsua.SWIGTYPE_p_p_pjsip_msg_body;
import org.pjsip.pjsua.SWIGTYPE_p_pjsip_evsub;
import org.pjsip.pjsua.SWIGTYPE_p_pjsip_hdr;
import org.pjsip.pjsua.SWIGTYPE_p_pjsip_rx_data;
import org.pjsip.pjsua.SWIGTYPE_p_pjsip_transaction;
import org.pjsip.pjsua.pjsip_event;

public class EventNotify extends EventCallBack{

        @Override
        public void on_evsub_state(SWIGTYPE_p_pjsip_evsub sub, pjsip_event event) {

                System.out.println("EventNotify on_evsub_state");
                super.on_evsub_state(sub, event);
        }

        @Override
        public void on_tsx_state(SWIGTYPE_p_pjsip_evsub sub,
                        SWIGTYPE_p_pjsip_transaction tsx, pjsip_event event) {
                System.out.println("EventNotify on_tsx_state");
                super.on_tsx_state(sub, tsx, event);
        }

        @Override
        public void on_rx_refresh(SWIGTYPE_p_pjsip_evsub sub,
                        SWIGTYPE_p_pjsip_rx_data rdata, int p_st_code,
                        SWIGTYPE_p_p_pj_str_t p_st_text, SWIGTYPE_p_pjsip_hdr res_hdr,
                        SWIGTYPE_p_p_pjsip_msg_body p_body) {
                System.out.println("EventNotify on_rx_refresh");
                super.on_rx_refresh(sub, rdata, p_st_code, p_st_text, res_hdr, p_body);
        }

        @Override
        public void on_rx_notify(SWIGTYPE_p_pjsip_evsub sub,
                        SWIGTYPE_p_pjsip_rx_data rdata, SWIGTYPE_p_int p_st_code,
                        SWIGTYPE_p_p_pj_str_t p_st_text, SWIGTYPE_p_pjsip_hdr res_hdr,
                        SWIGTYPE_p_p_pjsip_msg_body p_body) {
                System.out.println("EventNotify on_rx_notify");
                super.on_rx_notify(sub, rdata, p_st_code, p_st_text, res_hdr, p_body);
        }

        @Override
        public void on_client_refresh(SWIGTYPE_p_pjsip_evsub sub) {
                System.out.println("EventNotify on_client_refresh");
                super.on_client_refresh(sub);
        }

        @Override
        public void on_server_timeout(SWIGTYPE_p_pjsip_evsub sub) {
                System.out.println("EventNotify on_server_timeout");
                super.on_server_timeout(sub);
        }

}

}

I wanted to ask how can i get call back to these methods
The complete Src can be cloned at
git clone https://Rs9766@bitbucket.org/Rs9766/csipsimple_virtualbox.git

A: This can be done using the
the below
pjsip_event_notification.cpp
#include "pjsip_event_notification.h"
#include <pjsip.h>
#include <pjsip_ua.h>
#include <pjlib-util.h>
#include <pjlib.h>
#include <pjlib.h>
#include <pjsua.h>
#include <pjsua-lib/pjsua_internal.h>

static EventCallBack* registeredCallbackObject = NULL;

extern "C" {

  pj_bool_t on_rx_response_wrapper(pjsip_rx_data *rdata){
          registeredCallbackObject->on_rx_response(rdata);
          return PJ_FALSE;
 }

  pj_bool_t on_rx_request_wrapper(pjsip_rx_data *rdata){
          registeredCallbackObject->on_rx_request(rdata);
          return PJ_FALSE;
  }

  /* The module instance. */
  static pjsip_module mod_event_handler =
  {
      NULL, NULL,             /* prev, next.      */
      { (char*)"mod-reg-event", 12 },  /* Name.        */
      -1,                 /* Id           */
      PJSIP_MOD_PRIORITY_TSX_LAYER - 1,  /* Priority         */
      NULL,               /* load()       */
      NULL,               /* start()      */
      NULL,               /* stop()       */
      NULL,               /* unload()     */
      &on_rx_response_wrapper,               /* on_rx_request()  */
      &on_rx_response_wrapper,               /* on_rx_response() */
      NULL,               /* on_tx_request.   */
      NULL,               /* on_tx_response() */
      NULL,               /* on_tsx_state()   */

  };

  PJ_DECL(pj_status_t) event_callback_init() {
      return pjsip_endpt_register_module(pjsua_get_pjsip_endpt(),
                          &mod_event_handler);
  }

 void setEventCallbackObject(EventCallBack* eventCallBack){
         registeredCallbackObject=eventCallBack;
 }

}

the h file for the same
pjsip_event_notification.h
#include <pj/config_site.h>
#include <pjsua-lib/pjsua.h>

class EventCallBack {

public:
        virtual ~EventCallBack() {}
        virtual void on_rx_response(pjsip_rx_data *rdata){
 // Target Call Back for Notify message
        }

        virtual void on_rx_request(pjsip_rx_data *rdata){

        }

};
extern "C" {
pj_status_t event_callback_init();

void setEventCallbackObject(EventCallBack* eventCallBack);
}


text:
Q: How can I make the WooCommerce "Add to cart" button switch to a quantity increment button when clicked? I would to like modify the WooCommerce "Add to cart" button behavior as follows:

*

*When the "Add to cart" button is clicked, the selected item is added to the cart and the button changes to a quantity increment selector with plus/minus buttons. (There should be no "View cart" button, either.)

*The quantity in the cart can then be increased or decreased by clicking the plus/minus buttons on the quantity selector.

*If the quantity is reduced down to zero, the quantity increment button reverts backs to the "Add to cart" button.

All these actions should take place without reloading the page. I would ideally like to apply this to all areas of the shop (shop archive pages, product pages, quick view modal windows, cart), however if this is not possible then just on the shop page is fine.
I have tried to use Themes.Zone's WooCommerce Ajax Quantity plugin, but cannot seem to get it to work on my site... shame, because it's exactly what I'm looking for!
Please refer to the resources below for examples of the ideal finished product:
Click here for screenshots
Click here to see a working example on The Happy Apple's website
Click here to see a working example on Woolworths' website
Any help would be much appreciated! I am super new to the web dev game so writing the code myself is totally unrealistic!! >D< Thank you in advance!


text:
Q: Unclosed TCP connections in CLOSE_WAIT for various processes I have cluster of several machines connected on 10GBE network (NICs are Intel 82599EB 10GBE SFI/SFP+) running under Debian 6.0 and faced with problem of hung up TCP connections in CLOSE_WAIT state. I know that in theory connection in CLOSE_WAIT state should be explicitly closed by application, but in my case at least two different applications generate these hung up connections and I think that problem is in something else.

At first this problem was reproduced by Cassandra running as daemon under 'jsvc' process. One node of Cassandra ("server") didn't close connection that was closed one the side of another node that initiated this connection ("client").
After that I ran 'netperf' TCP_CRR test and got error message:

netperf -H 172.15.2.166 -t TCP_CRR -l -5 -D    TCP
  Connect/Request/Response TEST from 0.0.0.0 (0.0.0.0) port 0 AF_INET to
  172.15.2.166   (172.15.2.166) port 0 AF_INET : demo    send_tcp_conn_rr: data recv error: Connection reset by peer

With TCP connaction hanging in CLOSE_WAIT state on the 172.15.2.166 machine with strange 1 byte in Recv-Q.

tcp        1      0 172.15.2.166:12865      172.15.2.161:42863      CLOSE_WAIT

I've updated 'ixgbe' driver to the latest 3.9-NAPI, but this problem still persists and now I wonder what else can cause the problem?

A: *

*Your notes indicate that the server saw a FIN followed by an RST from the client
and, most likely, the server-app has not closed properly

*For any reason if you are not sure which application the connection belongs to,
Use lsof -n | grep CLOSE.WAIT

*If this is Cassendra, you may want to check
this StackOverflow question, cassandra too many open files


text:
Q: Making use of Metal's volatile MTLPurgeableState while triple buffering I have a number of cached MTLTexture's which I would like to set to purgeable using MTLTexture's setPurgeableState API. In order to do this I follow the process outlined in Apple's 2019 WWDC video which suggests:

*

*Setting cached MTLTexture instances to volatile

*Flagging MTLTexture instances as nonVolatile while 'in use' as part of a command buffer

*Using MTLCommandBuffer's addCompletedHandler to set all MTLTexture instances back to volatile after the command buffer completes its work

This approach works great, but quickly runs into issues in a triple buffered renderer where more than one command buffer is in-flight simultaneously. In these instances I receive the following error:

Cannot set purgeability state to volatile while resource is in use by a command buffer.

... which makes sense. I'm obviously attempting to flag a MTLTexture as volatile while it's in-flight as part of a subsequent command buffer. But what's the best way around this without obliterating the performance advantages afforded by triple buffering in the first place?
Attached below is a basic sketch of the approach I'm using (and the one outlined by Apple in the aforementioned WWDC video):
let cache = [String:MTLTexture]()

// Insert a number of textures into CPU cache and set
// their purgeable state to volatile
for (key, texture) in cache {
    texture.setPurgeableState(.volatile)
}

// Ensure no more than 3 command buffers are in-flight
// at any given them
semaphore.wait()

// Determine which cached textures are to be used for the
// next render pass and mark them nonVolatile
if cache["texture_to_be_used"].setPurgeableState(.nonVolatile) == .empty {
    // If the texture has been purged recreate as necessary...
}

guard let commandBuffer = commandQueue.makeCommandBuffer() else { return }

// Construct command buffer, binding textures where necessary
// ...

// Set a completion handler for the command buffer
commandBuffer.addCompletedHandler({ (buffer) in
    // Set any textures marked as nonVoltile back to volatile
    // so that they can be purged when required
    //
    // The issue here is that as I'm using a triple buffered
    // approach I have no way of (efficiently) knowing if a given
    // texture is being bound as part of another in-flight
    // command buffer
    for (key, texture) in cache {
        texture.setPurgeableState(.volatile)
    }

    // Rely on a semaphore to manage triple buffered rendering
    self.semaphore.signal()
})
commandBuffer.commit()


text:
Q: From classic multithreaded to java.nio asynchronous/non-blocking server I'm the main developer of an online game.
Players use a specific client software that connects to the game server with TCP/IP (TCP, not UDP)
At the moment, the architecture of the server is a classic multithreaded server with one thread per connection.
But in peak hours, when there are often 300 or 400 connected people, the server is getting more and more laggy.
I was wondering, if by switching to a java.nio.* asynchronous I/O model with few threads managing many connections, if the performances would be better.
Finding example codes on the web that cover the basics of such a server architecture is very easy. However, after hours of googling, I didn't find the answers to some more advanced questions:
1 - The protocol is text-based, not binary-based. The clients and the server exchanges lines of text encoded in UTF-8. A single line of text represents a single command, each lines are properly terminated by \n or \r\n.
For the classic multithreaded server, I have that kind of code :
public Connection (Socket sock) {
this.in = new BufferedReader( new InputStreamReader( sock.getInputStream(), "UTF-8" ));
this.out = new BufferedWriter( new OutputStreamWriter(sock.getOutputStream(), "UTF-8"));
new Thread(this) .start();
}

And then in run, data are read line by line with readLine.
In the doc, I found an utilitiy class Channels that can create a Reader out of a SocketChannel. But it is said that the produced Reader wont work if the Channel is in non-blocking mode, what contradicts the fact that non-blocking mode is mandatory to use the highly performant channel selection API I'm willing to use. So, I suspect that it isn't the right solution for what I would like to do.
The first question is therefore the following: if I can't use that, how to efficiently and properly take care of breaking lines and converting native java strings from/to UTF-8 encoded data in the nio API, with buffers and channels?
Do I have to play with get/put or inside the wrapped byte array by hand? How to go from ByteBuffer to strings encoded in UTF-8 ? I admit to don't understand very well how to use classes in the charset package and how it works to do that.
2 - In the asynchronous/non-blocking I/O world, what about the handling of consecutive read/write that have by nature to be executed sequencially one after the other?
For example, the login procedure, which is typicly challenge-response-based: the server sends a question (a particular computation), the client sends the response, and then the server checks the response given by the client.
The answer is, I think, certainly not to make a single task to send to worker threads for the whole login process, as it is quite long, with the risk to freeze worker threads for too much time (Imagine that scenario: 10 pool threads, 10 players try to connect at the same time; tasks related to players already online are delayed until one thread is again ready).
3 - What happens if two different threads simultaneously call Channel.write(ByteBuffer) on the same Channel?
Do the client might receive mixed up lines ? For example if a thread sends "aaaaa" and another sends "bbbbb", could the client receive "aaabbbbbaa", or am I ensured that everyting is sent in a consist order? Am I allowed to modify the buffer used right after the call returned?
Or asked differently, do I need additional synchronization to avoid this sort of situation?
If I need additionnal synchronization, how to know when release locks and so on, upon write finishes?
I'm afraid that the answer isn't as simple as registering for OP_WRITE in the selector. By trying that, I noticed that I get the write-ready event all the time and always for all clients, exiting Selector.select early mostly for nothing, since there are only 3 or 4 messages to send pers second per client, while the selection loop is performed hundreds of times per second. So, potentially, active wait in perspective, what is very bad.
4 - Can multiple threads call Selector.select on the same selector simultaneously without any concurrency problems such as missing an event, scheduling it twice, etc?
5 - In fact, is nio as good as it is said to be ? Would it be interesting to stay to classic multithreaded model, but unstead of creating a thread per connection, use fewer threads and loop over the connections to look for data availability using InputStream.isAvailable ? Is that idea stupid and/or inefficient?

A: 1) Yes. I think that you need to write your own nonblocking readLine method. Note also that a nonblocking read may be signaled when there are several lines in the buffer, or when there is an incomplete line:
Example: (first read)
 USER foo
 PASS

(second read)
 bar

You will need to store (see 2) the data that was not consumed, until enough information is ready to process it.
 //channel was select for OP_READ
 read data from channel
 prepend data from previous read
 split complete lines
 save incomplete line
 execute commands

2) You will need to keep the state of each client.
    Map<SocketChannel,State> clients = new HashMap<SocketChannel,State>();

when a channel is connected, put a fresh state into the map
    clients.put(channel,new State());

Or store the current state as the attached object of the SelectionKey.
Then, when executing each command, update the state. You may write it as a monolithic method, or do something more fancy such as polymorphic implementations of State, where each state knows how to deal with some commands (e.g. LoginState expects USER and PASS, then you change the state into a new AuthorizedState).
3) I don't recall using NIO with many asynchronous writers per channel, but the documentation says it is thread safe (I won't elaborate, since I have no proof of this). About OP_WRITE, note that it signals when the write buffer is not full. In other words, as said here: OP_WRITE is almost always ready, i.e. except when the socket send buffer is full, so you will just cause your Selector.select() method to spin mindlessly.
4) Yes. Selector.select() performs a blocking selection operation.
5) I think that the most difficult part is switching from a thread-per-client architecture, to a different design where reads and writes are decoupled from processing. Once you have done that, it is easier to work with channels than working your own way with blocking streams.


text:
Q: Can't ping any websites, but can access websites through browser I'm using Ubuntu 13.10 running on the newest version of Macbook Pro (dual boot). I'm using wireless connection to access websites through the Chrome browser and it works. But ping doesn't work. For example, this is the output
$ping -c 3 www.google.com
PING www.google.com (74.125.226.212) 56(84) bytes of data.

--- www.google.com ping statistics ---
3 packets transmitted, 0 received, 100% packet loss, time 2015ms

It seems that it is not the issue of name resolving. So what could be wrong? I'm not using a proxy for my browser.
This is the output of tracepath
$ tracepath www.google.com
1:  <my machine name>.local                                     0.052ms pmtu 1500
1:  no reply
2:  no reply
3:  no reply
...
    Too many hops: pmtu 1500
    Resume: pmtu 1500

EDIT:
After re-installing Ubuntu, ping works again.

A: From man ping: ping  uses  the  ICMP  protocol's  mandatory ECHO_REQUEST datagram to elicit an ICMP ECHO_RESPONSE from a host or gateway.
Your browser opens a TCP connection on port 80.
Any system along the path between you and www.google.com could be deciding to treat these two connections differently.
You could use tracepath (from the iputils-tracepath package) to see which systems are in that path, then ping, or hping3 to explore.
FWIW, I get PING responses from www.google.com,(-c 3 limits ping to 3 ICMP packets, which IMHO, is more polite):
walt@aardvark:~(0)$ ping -c 3 www.google.com

PING www.google.com (74.125.225.114) 56(84) bytes of data.
64 bytes from ord08s08-in-f18.1e100.net (74.125.225.114): icmp_req=1 ttl=56 time=35.9 ms
64 bytes from ord08s08-in-f18.1e100.net (74.125.225.114): icmp_req=2 ttl=56 time=32.1 ms
64 bytes from ord08s08-in-f18.1e100.net (74.125.225.114): icmp_req=3 ttl=56 time=32.0 ms

--- www.google.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2002ms
rtt min/avg/max/mdev = 32.096/33.402/35.964/1.817 ms

A: I am not sure whether this may answer your Question.
but it may happen that you didn't update the proxy in "settings/network"
If you gave the proxy in manual proxy in mozilla, and not in settings/network
you will be able to access websites with browser but you will not be able to ping any site

A: your firewall or proxy server just left HTTP protocol for you so yo can browse but cannot ping any website or ip. you need to have other protocol such az ftp, UDP TCP/IP and etc to ping correctly.


text:
Q: Focus and blur component after action on different component in Reagent Here is my Clojurescript code:
(def focus-wrapper
  (with-meta identity
    {:component-did-update #(.focus (dom-node %))}))

(defn solution-input []
  (let [current-char (subscribe [:current-char])
        input (subscribe [:input])]
    [focus-wrapper
      (fn []
        [:input {:type "text"
                 :auto-focus true
                 :value (:value @input)
                 :disabled (:disabled @input)
                 :on-change #(dispatch [:input-value-updated (.-target.value %)])
                 :on-key-press #(when (= 13 (.-which %))
                                  (if (= (.-target.value %) (:solution @current-char))
                                    (dispatch [:right-option-picked])
                                    (dispatch [:wrong-option-picked])))}])]))

(defn quiz [props childrn this]
  (let [current-char (subscribe [:current-char])
        counter (subscribe [:counter])
        feedback (subscribe [:feedback])]
    (fn []
      [:div.panel-container
        [:h2 "Quiz"]
        [:div.counter (str (:correct-guesses @counter) "/" (:total-guesses @counter))]
        [:div.char (:hint @current-char)]
        [solution-input]
        [:div.feedback (when (not= @feedback "off") @feedback)]
        [:button {:type "button"
                 :on-click #(dispatch [:next-char])}
                 "Skip"]
        [:button {:type "button"
                 :on-click #(dispatch [:panel-changed "result"])}
                 "Finish"]])))

Notice I am also using re-frame. I am keeping the input state (its value and disabled state) in my app-db and subscribing to them in my component. Therefore, it is easy to force the focus on the component once any of these props change (that is what my focus-wrapper is for).
Nevertheless, I am struggling to find a way to force focus on the input once the skip button is clicked. As far as I am aware, this is a typical justified use case for ref in React, which seem to work differently in Reagent.
Can someone recommend a way to solve this specific focus management problem in Reagent/re-frame?

A: I think the use of effects is in order.
(reframe/reg-event-fx
    :next-char
    (fn [cofx [_ a]]
        (.focus (.getElementById js/document "text-field-id"))
        {}))

  ...
  [:button {:type "button"
             :on-click #(dispatch [:next-char])}
             "Skip"]


text:
Q: Read data from file in c++ I have a file like this:
Linear eqation parameters: a b

2 4

Circle coord and radius:

1 1 2

Heat conduction
Unit ms

23

I want to read numbers into variables, e.g. A=2 b=4 x=1 y=1 r=2 u=23
Do I have to use getline for each line, and then extract numbers from string?

A: Can, you can use getline to store into a string variable, then extract the number using sscanf.
For example,
sscanf(data, "%i %i %i", &x, &y, &r);

You can use float or double datatype as well, depending on your needs.

A: You can mix getline and reading from 'cin'. Say, read one line, then read two integers by 'cin' and so on

A: Do u can store data in file like "2 4 1 1 2 23" ? Then it will be much easier. just read the entire line, and fill the value by one.


text:
Q: Stuck at Jquery Ajax Db Encoding for ISO-8859-9 Charset I am trying to pass data to db via my Jquery application. I have serious problems with encoding.
Current page encoding is iso-8859-9. I've made my ajax page encoding to iso-8859-9 and passing .ajax data with contentType: "application/x-www-form-urlencoded;charset=ISO-8859-9"
It stores İZİN value as Ä°ZÄ°N with every single trying.
Is it work if I create a PHP page and set encoding with headers?
PS: I am processing data on an HTML page. Processor page is an ASP page and using MsSQL db I guess. I don't have access to processor page or db. Just entering data via form post.
İZİN word and some other similar words are using for sql query at some other pages on WHERE clauses. So I cannot convert characters into HTML codes. I have to use İ as İ.
Thanks for suggestions!

A: The application/x-www-form-urlencoded does not have a charset. It's simply ASCII characters. Specifying charset there will do nothing.
jQuery will normally urlencode your data as is specified:

*

*Encode to UTF-8

*Percent-encode

So:
$.post( "test.php", {data: 'İZİN'}); //Shorthand for $.ajax

Actually posts this to server:
data=%C4%B0Z%C4%B0N

When you access $_POST['data'] with php, they have been turned into bytes (0xC4B05AC4B04E), so echoing them will give you malformed data:
header("Content-Type: text/html; charset=ISO-8859-9");
echo $_POST['data'];
// Ä°ZÄ°N

You can test this is true with:
header("Content-Type: text/html; charset=ISO-8859-9");
echo "\xC4\xB0\x5A\xC4\xB0\x4E";
// Ä°ZÄ°N

In PHP you need convert it to ISO-8859-9 as soon as you receive it:
<?php
header("Content-Type: text/html; charset=ISO-8859-9");
$data =  "\xC4\xB0\x5A\xC4\xB0\x4E"; //$_POST['data'];
$proper = mb_convert_encoding( $data, "ISO-8859-9", "UTF-8" );
echo $proper;
//İZİN

Note that it's just much easier to use UTF-8 everywhere because it's pretty much the best encoding and the web loves it. If you use any other encoding then you will have to be on your toes all the time.


text:
Q: Simple Validation API Issue Java Swing I am using Netbeans 6.8 , JDK 1.6 and downloaded Simple Validation API. When I try the code, it gives me errors referencing "org/openide" classes.
Could this be a compatibility issue? How can I resolve this?
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: org/openide/util/Lookup
        at org.netbeans.validation.api.ui.swing.SwingComponentDecorationFactory.getDefault(SwingComponentDecorationFactory.java:154)
        at org.netbeans.validation.api.ui.swing.SwingValidationGroup.<init>(SwingValidationGroup.java:82)
        at org.netbeans.validation.api.ui.swing.SwingValidationGroup.create(SwingValidationGroup.java:87)


text:
Q: Question about ability to make a matrix's determinant 0 The question is as follows:
Given a natural number n, what is the maximum value of the natural number k in terms of n, such that for any arbitrary placement of random k real values on an n by n matrix, there must exist a combination of real numbers to fill the remaining entries so that the determinant will be 0?
So basically, what is the worst case scenario for any given random matrix if we need to make its determinant 0?
Another scenario for the same question is that assume two persons, A and B, are arranging an n by n matrix. First A will fill the matrix, and then B. A's goal is to prevent the matrix's determinant from being 0, and B's goal is to make it 0. A will fill any k entries on the matrix with any real values he wants. What is the biggest value for k such that B can still make the determinant 0 by filling the rest of the matrix with appropriate real numbers? Or in other words, what is the biggest value for k such that A canNOT guarantee that the matrix will have a non-zero determinant?
In case it is not clear, an example for n=2 is k cannot be 4, because obviously some combination of 4 entries will result in non-zero determinant. For k=3, there is this possibility:
[1 x]
[0 2]

that the determinant will always be 2 for any x. So this is also not a desired k. [Edited->] For k=2, no matter what those given two numbers and their positions on the matrix are, we can fill the rest of the matrix with some values (i.e all zeros) such that the determinant will be 0. So, for n=2, biggest possible k is 2.
For n=1, clearly k is 0 and obviously k is always smaller than n^2.
Appearantly, k must increase as n increases but I don't have a proof of it. If someone solves the question, I'm sure it will be easy to deduce that too.

A: $k=n(n-1)$
$$$$
The determinant of the matrix will be zero iff the column vectors of the matrix are linearly dependent, call these column vectors $X_1, X_2, ..., X_n$
If given $n(n-1)$ entries, the idea is to choose the remaining n entries so as to make the columns vectors linearly dependent. (Try to prove you can always do this!)
$$$$
Finally, for $k= n(n-1)+1$ consider an $n$ x $n$ unit matrix and remove the zeros in the first row and leave them blank. No matter how you change the (n-1) blank entries, the value of the determinant will be 1 hence nonzero. Hence $n(n-1)$ is the maximum such $k$.


text:
Q: How to make detail view in django html? How can I show the data based on its id ?
now, if I click one item, i got the url like this
    http://localhost:8000/novel/11
for now, this is the views.py i've write
 def novel_page(request, id):
     return render(request, 'novel.html')

and the urls.py is
 path('novel/<int:id>', views.novel_page, name='novel'),

and I want to show the detail of item with id like what I passed to url.
For example, if I click the data with id is 11, so the system will display all of data based on id 11.
The data is'n from database, but from the XML file with the preview like this:
<Collection>
    <DOC>
        <DOCNO>1</DOCNO>
        <Title>Neon Prey (A Prey Novel) Hardcover </Title>
        <Author>John Sandford</Author>
        <Text>
            This is novel 1
        </Text>
    </DOC>
    <DOC>
        <DOCNO>2</DOCNO>
        <Title>The Mother-in-Law</Title>
        <Author>Sally Hepworth</Author>
        <Text>
            This is novel 2
        </Text>
    </DOC>
    <DOC>
        <DOCNO>3</DOCNO>
        <Title>Saman</Title>
        <Author>Ayu Utami</Author>
        <Text>
            This is novel 3
        </Text>
    </DOC>
</Collection>

This is the views.py to pass the data to the index
def display(request):
    if request.method == 'POST':
        text = request.POST['input_text']
        result = main.main(text)
        content = {'result': result}
        return render(request, 'index.html', content)
    return render(request, 'index.html')

and i show the data with this code
{% for i in result %}

{{i.title}}

{% endfor %}

Thanks.

A: {{i.title}}

You should always use url to build the link unless it's very special occasion that you have to render the path yourself. In such case, you should write a custom template tag to do so.

A: Your detail function should query the database to bring a particular data in ID 11 so for that you just need a django query . So your fuction will be like:
views.py
def novel_page(request, id):

     qs = YourModelName.objects.get(id=id)           # <------This is what you add

     return render(request, 'novel.html', {'qs': qs})       #<---- Pass the qs as a dict