text:
Q: Downloading a file into memory I am writing a python script and I just need the second line of a series of very small text files.  I would like to extract this without saving the file to my harddrive as I currently do.
I have found a few threads that reference the TempFile and StringIO modules but I was unable to make much sense of them.
Currently I download all of the files and name them sequentially like 1.txt, 2.txt, etc, then go through all of them and extract the second line.  I would like to open the file grab the line then move on to finding and opening and reading the next file.
Here is what I do currently with writing it to my HDD:
while (count4 <= num_files):
    file_p = [directory,str(count4),'.txt']
    file_path = ''.join(file_p)
    cand_summary = string.strip(linecache.getline(file_path, 2))
    linkFile = open('Summary.txt', 'a')
    linkFile.write(cand_summary)
    linkFile.write("\n")
    count4 = count4 + 1
    linkFile.close()

A: You open and close the output file in every iteration.
Why not simply do
with open("Summary.txt", "w") as linkfile:
    while (count4 <= num_files):
        file_p = [directory,str(count4),'.txt']
        file_path = ''.join(file_p)
        cand_summary = linecache.getline(file_path, 2).strip() # string module is deprecated
        linkFile.write(cand_summary)
        linkFile.write("\n")
        count4 = count4 + 1

Also, linecache is probably not the right tool here since it's optimized for reading multiple lines from the same file, not the same line from multiple files.
Instead, better do
with open(file_path, "r") as infile:
    dummy = infile.readline()
    cand_summary = infile.readline.strip()

Also, if you drop the strip() method, you don't have to re-add the \n, but who knows why you have that in there. Perhaps .lstrip() would be better?
Finally, what's with the manual while loop? Why not use a for loop?
Lastly, after your comment, I understand you want to put the result in a list instead of a file. OK.
All in all:
summary = []
for count in xrange(num_files):
    file_p = [directory,str(count),'.txt'] # or count+1, if you start at 1
    file_path = ''.join(file_p)
    with open(file_path, "r") as infile:
        dummy = infile.readline()
        cand_summary = infile.readline().strip()
        summary.append(cand_summary)

A: Just replace the file writing with a call to append() on a list. For example:
summary = []
while (count4 <= num_files):
    file_p = [directory,str(count4),'.txt']
    file_path = ''.join(file_p)
    cand_summary = string.strip(linecache.getline(file_path, 2))
    summary.append(cand_summary)
    count4 = count4 + 1

As an aside you would normally write count += 1. Also it looks like count4 uses 1-based indexing. That seems pretty unusual for Python.


text:
Q: Multiple forms on one page bugging textarea default value An image can best show the problem:

Of course I dont want my textarea to have a bunch of html tags as a default value, thats why I set the defaultvalue to 'Hi', which it aparently isnt showing right now, but which it should.
I already tried a few things to find/solve the problem. What I found out is that if I remove the other form on the page (a login form not visible on the image) this form works and properly shows 'Hi' as a value. So the problem seems to be that there are multiple forms on this page. Problem has only shown with the use of text-area's, input fields, on this page or any other, work fine. I also tried moving the textarea outside of the form tags, that does remove the html tags, but the 'hi' still isnt visible (plus I want the textarea inside my form, as it should be part of it).
Edit, after a few struggles finally managed to post the code as code instead of a document. Code for the first, properly working, form:

<form id="form1" action="auth/login" method="post">

        <input class="transparent-input" name="username" type="text" value="Gebruikersnaam">

        <input class="transparent-input" name="password"   type="password" value="Wachtwoord">

        wachtwoord
vergeten?

        <input class="transparent-input"  type="submit" value="Aanmelden">

</form>

Code for the second, faulty, form:

Contact

    <form id="form2">
        <input type="text" value="Pietje Puk" />

        <input type="email" value="mijn@email.nl" />

        <textarea rows="10" cols="50">Hi</textarea>
    </form>

edit: I did do a markup validation, nothing there that solved the problem

A: It turned out to be a markup problem after all. After trying some more I did find that moving a div closing tag to a different location in the document did solve the problem. Before I had opened a div before both forms and closed it in between them, closing it after both of them instead solved the problem.
Tnx Lars Beck for pointing me in the right direction :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Candy Box 2 When I am in quests I am constantly walking forward, is this normal? I have no idea if this is normal but when I am in quests like fighting the nougat monster, I can not stand still. I am constantly walking forward towards the monster. This makes beating the nougat monster very hard. Please tell me if this is normal or what I do to stop walking forward.

A: Yes it is normal. If you don't want to walk forward, you will need to obtain the Boots of Introspection.
Those can be obtained by defeating yourself.
To defeat yourself, you need to make an X-Potion and then use it in a quest. The only way to defeat yourself, is if you are wearing the Octopus King's Crown (not enchanted).
To make an X-Potion

*

*Put a candy in your cauldron.

*Heat up until the water is cold.

*Repeat steps 1 and 2 three more times.

*Put a lollipop in your cauldron.

*Heat up until the water is hot.

After you obtained the boots, you need to make sure you equip them.


text:
Q: symfony 4 - testing command against different data I have a command which runs over the database, then tests if any companies have a duplicate name, then outputs to the user for any remediation.
What I want to do for each test is:

*

*Change the database to prescribed set of companies, e.g. 10 companies with 5 of those having duplicate names or e.g. 10 companies with 5 having null names

*Run that test

Normally if this was a function, I could use a data provider in the annotation to provide different data to test e.g.
     * @dataProvider provideFoo
     * @param $data
     */
    public function testFooBar($data) {...

But the command has no args/params, so I think I have to update the database each time.
Can this be done with fixtures, or should I add new companies in each test e.g.:
public function testFooBar($data) {
  $company1 = (new Company())->setName('Company 1');
  $this->entityManager->persist($company1);
  $this->entityManager->flush();

  $commandTester->execute([]);
  // rest of test
}

I should add - the db is quite large and dropping it and resetting it takes a few hours.
** Edit **
I found this question, which seems to have helped me set up the test database, I will carry on to see if I can get fixtures working now the test database is up: How to setup a database for test environment in Symfony 4

A: I managed to get it working using this:
// tests/Command/FindDuplicatedCompaniesCommandTest.php:
<?php declare(strict_types=1);

namespace App\Tests\Command;

use App\DataFixtures\DuplicatedCompaniesFixtures;
use App\Tests\FixturesTrait;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Console\Tester\CommandTester;

class FindDuplicatedCompaniesCommandTest extends KernelTestCase
{
    use FixturesTrait;

    public function testExecuteDuplicates()
    {
        $kernel = static::createKernel();
        $application = new Application($kernel);
        $command = $application->find('app:find:duplicated-companies');
        $commandTester = new CommandTester($command);

        $this->addFixture(new DuplicatedCompaniesFixtures());
        $this->executeFixtures();

        $commandTester->execute([]);

        $output = $commandTester->getDisplay();

        $this->assertStringContainsString('Detected name', $output);
        $this->assertStringContainsString('Company 3', $output);
        $this->assertStringContainsString('Company 1', $output);
        $this->assertStringNotContainsString('violations', $output);
        $this->assertStringNotContainsString('No duplicates', $output);
    }

    protected function setUp(): void
    {
        self::bootKernel();
    }
}

// src/DataFixtures/DuplicatedCompaniesFixtures.php
<?php declare(strict_types=1);

namespace App\DataFixtures;

use App\Entity\Company;
use DateTimeImmutable;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;

/**
 * Class DuplicatedCompaniesFixtures
 * @package App\DataFixtures
 */
class DuplicatedCompaniesFixtures extends Fixture
{
    /**
     * @const CO_1_REFERENCE
     */
    public const CO_1_REF = 'COONE';

    /**
     * @const CO_2_REFERENCE
     */
    public const CO_2_REF = 'COTWO';

    /**
     * @const CO_3_REFERENCE
     */
    public const CO_3_REF = 'COTHREE';

    /**
     * @const CO_4_REFERENCE
     */
    public const CO_4_REF = 'COFOUR';

    /**
     * @param ObjectManager $manager
     */
    public function load(ObjectManager $manager)
    {
        $company1 = (new Company())
            ->setName('Company 1')
            ->setAlphaKey('COMPANYONE')
            ->setUpdatedAt(new DateTimeImmutable());
        $company2 = (new Company())
            ->setName('Company 1')
            ->setAlphaKey('COMPANYONE')
            ->setUpdatedAt(new DateTimeImmutable());
        $company3 = (new Company())
            ->setName('Company 3')
            ->setAlphaKey('COMPANYTHREE')
            ->setUpdatedAt(new DateTimeImmutable());
        $company4 = (new Company())
            ->setName('Company 3')
            ->setAlphaKey('COMPANYFOUR')
            ->setUpdatedAt(new DateTimeImmutable());

        $manager->persist($company1);
        $manager->persist($company2);
        $manager->persist($company3);
        $manager->persist($company4);
        $manager->flush();
        $this->addReference(self::CO_1_REF, $company1);
        $this->addReference(self::CO_2_REF, $company2);
        $this->addReference(self::CO_3_REF, $company3);
        $this->addReference(self::CO_4_REF, $company4);
    }
}

That way, I can add a different fixture per test in a file, so e.g. if I wanted a separate test for name violations, I would add src/DataFixtures/NameViolationCompaniesFixtures.php and call it in the test.


text:
Q: pandas bar plot cuts off ends of x-axis I have a DataFrame and want a fairly simple, horizonal bar chart. However, the edges of the x-axis are too tight and my values for the first and last item are cut off:
df = pd.DataFrame(np.random.rand(10,3))
df.columns = ['col1','col2','col3']
df.index = ['ind1','ind2','ind3','ind4','ind5','ind6','ind7','ind8','ind9','ind10']
df['col4'] = 0.5
df.drop('col4',axis=1).plot.bar(figsize=(15,8));
df['col4'].plot(kind='line',color='black',linestyle='dashed',label='All-time average',legend=True);

The chart looks like this in Jupyter Notebook

What change is needed to extend the x-axis. Most questions on this seem to cover continuous data where you can set an x_lim but I have a categorical x-axis.
Thanks


text:
Q: TypeError: Cannot read property '_id' of undefined (MongoDB and Node.js) Somehow this code from Chapter 7 of "Web Development with MongoDB and Node.js" doesn't work.
Can anyone explain why and also suggest possible fix?
It seems the issue is with doc[0]._id
If I comment out line [10], I won't see the error.
Here is the full code copied directly from the book.
1  var MongoClient = require('mongodb').MongoClient;
2
3  MongoClient.connect('mongodb://localhost:27017/mongotest', function(err, db) {
4    console.log('Connected to MongoDB!');
5
6    var collection = db.collection('testing');
7    collection.insert({'title': 'Snowcrash'}, function(err, docs) {
8        console.log(docs.length + ' record inserted.');
9        console.log(docs[0]._id + ' - ' + docs[0].title);
10
11       collection.findOne({title: 'Snowcrash'}, function(err, doc) {
12           console.log(doc._id + ' - ' + doc.title);
13           db.close();
14       });
15   });
16 });

After some googling, I found the the fix.
MongoDB. Undefined record inserted. Cannot read property 'title' of undefined
console.log(docs.ops.length + ' record inserted.');
console.log(docs.ops[0].title + ' – ' + docs.ops[0]._id);

Found more clues:
Check out https://www.w3schools.com/nodejs/nodejs_mongodb_insert.asp
See the paragraph on Result Object.
Still, can anyone explain how adding .ops made the difference?
Also, for line [9], why is there a need to add [0] after docs?

A: The insert() returns a WriteResult object that contains the status of the operation. Upon success, the WriteResult object contains information on the number of documents inserted:
WriteResult({ "nInserted" : 1 })


text:
Q: How to modify null value/two double quotes that contain nothing in xml with Powershell? I need to modify web.config file which I am reading as xml and the line i need to change is this:
<add key="My.Unique.Repository" value="" />

as you can see, there is nothing in value=" " just the double quotes.
I have no script written for this, I am trying to find out how to do it in the simplest way before I attempt to compile code
P.S. I have zero powershell experience, kindly respond in simple terms, thank you

A: Probably something along the lines of
    $xml = [xml]'<add key="My.Unique.Repository" value="" />'

    $target = $xml.SelectSingleNode("/add")
    $target.SetAttribute("value", "some value");

A: Found the answer that I needed, see the code below.
Thanks Theo for providing me with this answer.
https://stackoverflow.com/users/9898643/theo
$path        = '\\lonngp-ap\c$\Program Files\AIR\IIS\web2.config'
[xml]$config = Get-Content -Path $path -Raw
$stuffIwant  = "\\StringServer123"
$config.SelectNodes("//add[@key='My.Unique.Repository']") | ForEach-Object { $_.SetAttribute("value", $stuffIwant) }
$config.Save($path)


text:
Q: trigger javascript event handler already registered on a plugin Sorry for the title gore, will edit as appropriate..
I am using the Twitter Bootstrap Wizard for handling database manipulation. I would really like to be able to trigger the onTabShow() function at the press of a button. onTabShow() loads the data and generates an updated form, so this ability to register some kind of event would be of great help. The function is defined as below:
$('#location_wizard').bootstrapWizard({
        ...
        onTabClick: function (tab, navigation, index, clickedIndex) {
            ...
        },
        onNext: function (tab, navigation, index) {
            ...
        },
        onPrevious: function (tab, navigation, index) {
            ...
        },
        onTabShow: function (tab, navigation, index) {
            TRIGGER THIS FUNCTION WITHOUT SWITCHING PAGES!
        }
});

How might I write something like
('#add-new').on('click', function() {
    ... AJAX some stuff ...
    ... trigger "onTabShow()" without switching tabs in the wizard ...
})

A: Extract your "on tab show" handler from the plugin, so you can call the function from different parts of your code.
$('#location_wizard').bootstrapWizard({
    //...
    onTabShow: onTabShowHandler
    //...
});

$('#add-new').on('click', function(){
    //... ajax ...
    onTabShowHandler(x, y, z);
});

function onTabShowHandler(tab, navigation, index){
    // do tab show stuff
}

EDIT: additional details

since x, y, z are provided within bootstrapWizard, how might I access
  those when triggering onTabShowHandler from the click event?

You will have to pass those arguments to the function yourself. If you inspect each of those arguments when onTabShowHandler is triggered by the bootstrapWizard plugin, you'll see their values and be able to mock something similar.
function onTabShowHandler(tab, navigation, index){
    console.log(tab);        // element/jQuery object
    console.log(navigation); // element/jQuery object
    console.log(index);      // number
}

// in your click function...
$('#add-new').on('click', function(){
    var x = $('#tab-1');
    var y = $('#nav');
    var z = 0;

    onTabShowHandler(x, y, z); // reacts as though tab 1 was shown
});


text:
Q: NServiceBus: Scatter-Gatherer pattern I've searched the web on this topic for NServiceBus but haven't found any
example or solution.
I have a web service which receives a query from a client. The web service
should publish the query to subscribing servers and return the result back to
the web service. The web service aggregates the results before returning it to
the client.
I've run the Full Duplex example but i'm not sure how to make it work for my
scenario.
Any help would be appreciated.
Thanks in advance,
Kalvin


text:
Q: Creating a Script To Increase Numbers On Website We have a website, on the front page we show "Parcels Shipped", we'd love the numbers to updated via a formula - i.e. we shipped 34,502,233 parcels in 2014... We show a static stat.... But we'd love to have the numbers increased via a formula that increases the number by the second/minute
Thanks for all the replies guys - So we current have this: gyazo.com/d421a3675884e2610d368c9e60e8acca
we want it to increase around 76 times per minute.... so a rotating number basically - i've no idea how to achieve this. (left number) & We want it to increase around 43 times per minute for middle number
Does anyone know where I can find this sort of trick?

A: This achieves your desired functionality using setInterval() to fire a function that checks to see how long it's been since today. Then, multiplying by the increase you mentioned in the comments and adding it to the numbers in your screenshot.
JS:
function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

function timeSince() {
    var prevTime = new Date(2015,8,8,0,0);
    var thisTime = new Date();
    return (thisTime.getTime() - prevTime.getTime()) / 1000;
}

function parcelCount() {
    var secDiff = timeSince();

    var leftNum = document.getElementById("left");
    var midNum = document.getElementById("mid");
    var leftNumCount = Math.round(((76/60) * secDiff) + 40093794);
    var midNumCount = Math.round(((43/60) * secDiff) + 22874098);

    leftNum.innerHTML = numberWithCommas(leftNumCount);
    midNum.innerHTML = numberWithCommas(midNumCount);
}
parcelCount();
setInterval(parcelCount, 1000);

HTML:

Left

Mid

Demo: http://jsfiddle.net/hopkins_matt/513ng07d/
Used info from these answers to build this:

*

*https://stackoverflow.com/a/2901298/4556503

*https://stackoverflow.com/a/6636639/4556503

A: Use setInterval with the increasing function as 1st argument and ms as the 2nd one.
var el = document.getElementById('counter')
var x = 0
window.setInterval(function(){
  el.value = formula(++x)
}, 1000)

A: If the increase is completly random, just a "front-end design stuff" (sorry, guys), you can use setInverval() from Javascript.
It works this way:
every _s ms, the function will be called. If you have an increase factor, like a global constant you could do something like:
var myDiv = document.getElementById("myId");
var _mseconds = 1500; // mileseconds
var incFactor = 150;
var handlerInt = setInverval(function() {
 myDiv.innerHTML = incFactor+incFactor; // you can use Math.Random() or something, instead
}, _mseconds);

Hope it helps!


text:
Q: When we have some constants defined in a class in Ruby and Rails, can we guarantee to be able to access it in another class? If we have some constants inside of a class definition:
class Animal < ActiveRecord::Base
  GROWTH_FACTOR = 2

  ...
end

is it true that sometimes Animal::GROWTH_FACTOR is available to be used by another class or ERB, such as
class Plant < ActiveRecord::Base
  GROWTH_FACTOR = Animal::GROWTH_FACTOR / 2.0

  ...
end

or
<%= Animal::GROWTH_FACTOR %>

but sometimes not? (so it would be randomly failing, depending whether the Rails server re-run the class definition of Animal for that particular HTTP request?) Is GROWTH_FACTOR only really guaranteed to be useable inside of each class's own definition?  What if we want to guarantee it is available, is it to use @@GROWTH_FACTOR inside the class and then use Animal.GROWTH_FACTOR every where else in the code?

A: In your example, 'Animal' and 'Plant' are both global constants. As long as these declarations have been evaluated and as long as they haven't been somehow undefined, they're both accessible from anywhere, including any constants defined inside the classes.
If these two classes are defined in files named 'animal.rb' and 'plant.rb', then you can be sure both constants are available by requireing these files. If one depends on the other, then the order you require the files in matters.
Now in the second part of your question you mention a different syntax @@ which is not the same thing. I'd steer clear of that syntax unless you fully understand what a class variable is all about in Ruby.


text:
Q: How to place a Linearlayout at bottom inside a Relativelayout in android I need to place a linear layout at bottom inside a relativelayout which is the top most parent in xml. How can i do this?
Please help me.
 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/background"
android:orientation="vertical" >
<RelativeLayout .......   <<--- this should occupy total available space
</Relativelayout
 <Linearlayout .......     <<-- this should place at bottom always with height 50dp
 </LineaLayout>
 </ReltiveLayout>

A: Please try this:
<LinearLayout android:layout_alignParentBottom="true" android:layout_height="50dp" android:layout_width="wrap_content">
</LinearLayout>

you can align at bottom in xml from the above attribute.

A: Try with this:
 <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:minHeight="?android:attr/listPreferredItemHeight" >
 <RelativeLayout
    android:id="@+id/relativeLayout1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="119dp" >
 </RelativeLayout>

 <LinearLayout
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="50dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true" >
 </LinearLayout>

</RelativeLayout>

A: use this
 <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"      >
<RelativeLayout
    android:id="@+id/relativeLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_alignParentTop="true"
    android:background="#ff00ff00"
    android:layout_centerHorizontal="true" >
</RelativeLayout>
<LinearLayout
    android:id="@+id/linearLayout"
    android:layout_width="wrap_content"
    android:layout_height="50dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:background="#ffff0000"
    android:layout_alignParentRight="true" >

</LinearLayout>

A: found more generic way to do this
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".nestedLayoutActivity" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="seebelow" />

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

        <Button
            android:id="@+id/new_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="80dp"
            android:layout_gravity="bottom"
            android:text="@string/New" />

        <Button
            android:id="@+id/list_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:text="@string/list" />

        <Button
            android:id="@+id/more_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:text="@string/more" />
    </LinearLayout>

</RelativeLayout>


text:
Q: Show log object in console from ILogger log critical im using ILogger interface to log information about my app into console.
Im logging unathorized acces to my app:
private readonly RequestDelegate _next;
private readonly ILogger<SomeClass> _logger;

public SomeClass(RequestDelegate next, ILogger<SomeClass> logger)
{
      _next = next;
      _logger = logger ?? throw new ArgumentNullException(nameof(logger));
}

// some methods there

_logger.LogCritical(
      $"{DateTime.UtcNow} - Unauthorized Access",
      new
      {
          token = jwt,
          // other stuff
      });

But in console, i get only message;
crit: namespace.to.my.app.SomeClass[0]
      24.07.2020 07:36:37 - Unauthorized Access

How to display that anonymous object that i created into console?

A: ILogger is a semantic logger so you need a token in the log string to represent what you are logging. Try this:
_logger.LogCritical
(
  "{Time} - Unauthorized Access. Details {Details}",
  DateTime.UtcNow,
  new
  {
    token = jwt,
    // other stuff
});

Note that string interpolation doesn't play well with sematic logging so I've moved the DateTime.UtcNow expression out and given it a token in the log string.


text:
Q: What is the Angular currency pipe code for Angola country I am trying to output the price of products,
but I would like to know the currencyCode
for Angola in Angular
I hope there is some code that can
identify the currency of Angola
This is the variable that receive the value:
cur2 = 10.263782;

Here i use the curency pipe:
{{cur2 | currency:'USD':true:'2.2-4'}}

Tis is the output:
$10.2638

I've tried it this way:
{{cur2 | currency:'AOA':true:'2.2-4'}}

this too:
{{cur2 | currency:'AKZ':true:'2.2-4'}}
{{cur2 | currency:'KZ':true:'2.2-4'}}

and it was unsuccessful

A: It looks like Angolan currency is currently only available as a narrow symbol. Therefore the following should do the trick:
{{cur2 | currency:'AOA':'symbol-narrow':'2.2-4'}}

A: The previous answer is right. But I try to explain 'why?' not only for you but for other people who will read your question.
Yes for Angola currency in the angular pipe we need use 'symbol-narrow'.
Official documentation of angular explains that for transforming value using currency pipe we need to use format like:
{{ value_expression | currency [ : currencyCode [ : display [ : digitsInfo [ : locale ] ] ] ] }}

In your question, we are only interested in the parameter display.
And documentation gives this description of this parameter for us:

*

*code: Show the code (such as USD).

*symbol(default): Show the symbol
(such as $).

*symbol-narrow: Use the narrow symbol for locales that
have two symbols for their currency. For example, the Canadian dollar
CAD has the symbol CA$ and the symbol-narrow $. If the locale has no
narrow symbol, uses the standard symbol for the locale.

*String: Use
the given string value instead of a code or a symbol. For example, an
empty string will suppress the currency & symbol. Boolean (marked
deprecated in v5): true for symbol and false for code.

Anngolan currency has two symbols for its designation Kz and kz.
When you use true angular understand that thay needs to use the symbol. But you have two symbols for designation this currency in your locale. That's why this parameter did not work for you.


text:
Q: Read a file and get an array of strings I want to read a file and get back a vector of Strings. The following function works, but is there a more concise or idiomatic way?
use std::fs::File;
use std::io::Read;

fn lines_from_file(filename: &str) -> Vec<String> {
    let mut file = match File::open(filename) {
        Ok(file) => file,
        Err(_) => panic!("no such file"),
    };
    let mut file_contents = String::new();
    file.read_to_string(&mut file_contents)
        .ok()
        .expect("failed to read!");
    let lines: Vec<String> = file_contents.split("\n")
        .map(|s: &str| s.to_string())
        .collect();
    lines
}

Some things that seem suboptimal to me:

*

*Two separate error checks for reading the file.

*Reading the entire file to a String, which will be thrown away. This would be particularly wasteful if I only wanted the first N lines.

*Making a &str per line, which will be thrown away, instead of somehow going straight from the file to a String per line.

How can this be improved?

A: DK.'s answer is quite right and has great explanation. However, you stated:

Read a file and get an array of strings

Rust arrays have a fixed length, known at compile time, so I assume you really mean "vector". I would write it like this:
use std::{
    fs::File,
    io::{prelude::*, BufReader},
    path::Path,
};

fn lines_from_file(filename: impl AsRef<Path>) -> Vec<String> {
    let file = File::open(filename).expect("no such file");
    let buf = BufReader::new(file);
    buf.lines()
        .map(|l| l.expect("Could not parse line"))
        .collect()
}

// ---

fn main() {
    let lines = lines_from_file("/etc/hosts");
    for line in lines {
        println!("{:?}", line);
    }
}

*

*As in the other answer, it's worth it to use a generic type that implements AsRef for the filename.

*Result::expect shortens the panic on Err.

*BufRead::lines handles multiple types of newlines, not just "\n".

*BufRead::lines also gives you separately allocated Strings, instead of one big glob.

*There's no reason to collect to a temporary variable just to return it. There's especially no reason to repeat the type (Vec<String>).

If you wanted to return a Result on failure, you can squash the implementation down to one line if you want:
use std::{
    fs::File,
    io::{self, BufRead, BufReader},
    path::Path,
};

fn lines_from_file(filename: impl AsRef<Path>) -> io::Result<Vec<String>> {
    BufReader::new(File::open(filename)?).lines().collect()
}

// ---

fn main() {
    let lines = lines_from_file("/etc/hosts").expect("Could not load lines");
    for line in lines {
        println!("{:?}", line);
    }
}

A: As BurntSushi said, you could just use the lines() iterator.  But, to address your question as-is:

*

*You should probably read Error Handling in Rust; those unwrap()s should be turned into ?s, with the function's result becoming a Result<Vec<String>, E> for some reasonable E. Here, we reuse the io::Result type alias.

*Use the lines() iterator.  The other thing you can do is read the whole file into a String and return that; there's a lines() iterator for strings as well.

*This one you can't do anything about: file_contents owns its contents, and you can't split them up into multiple, owned Strings.  The only thing you can do is borrow the contents of each line, then convert that into a new String.  That said, the way you've put this implies that you believe creating a &str is expensive; it isn't.  It's literally just computing a pair of offsets and returning those.  A &str slice is effectively equivalent to (*const u8, usize).
Here's a modified version which does basically the same thing:
use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;

fn lines_from_file<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where
    P: AsRef<Path>,
{
    let file = File::open(filename)?;
    Ok(io::BufReader::new(file).lines())
}

One other change I made: filename is now a generic P: AsRef<Path>, because that's what File::open wants, so it will accept more types without needing conversion.


text:
Q: MySQL: Schedule event 15 minutes after table insert In my booking database, there is a RentOrder table with an orderStatus column. Users can access and make orders via a booking api.
I want MySQL to wait 15 minutes after an initial RentOrder insert and check if orderStatus is still set to RESERVED (i.e. check if the order hasn't been confirmed). If this is the case, then I want to automatically set the orderStatus to TIMEOUT.
My idea so far is to user AFTER INSERT and SLEEP but I'm not sure this is optimal? My main concern is that SLEEP might have some adverse effects on performance or anything else.
Any suggestions welcome and thanks in advance.

A: You could set an event.  Personally, I recommend a view for this purpose:
create view v_RentOrder as
    select . . .,
           (case when createdAt < now() - interval 15 minute and orderStatus = 'RESERVED'
                 then 'TIMEOUT'
                 else orderStatus
            end) as orderStatus
    from RentOrder;

The column createdAt is the time the record was created.
Voila!  The data is always up-to-date -- to the second -- for anyone using the view.
You can pair this with a job that periodically (say once per day or once per hour) updates the table with the status that you want.
The option of creating an event or job for every update has challenges:

*

*If the database goes down, updates may not take effect.

*If there is a heavy server load, updates may be delayed.

*If the table or rows are locked, the updates may be delayed.

*The updates increase the load on the system and might interfere with other activities.

These problems can be mitigated by using a queuing/messaging system for the updates.  However, that starts to get complicated for a simple problem.

A: Create event procedure which fires with safe time granularity (for example, each 10 second) and updates the rows which matches your condition as needed.

My idea so far is to user AFTER INSERT and SLEEP

Do it never. Trigger code must be as fast as possible. If trigger contains SLEEP(x) then each row will take x second for insertion.

CREATE TABLE test (id int);

-- no trigger, fast insertion
SELECT CURRENT_TIMESTAMP(3) INTO @CURRENT_TIMESTAMP;
INSERT INTO test VALUES (1);
SELECT TIMEDIFF(CURRENT_TIMESTAMP(3), @CURRENT_TIMESTAMP)

| TIMEDIFF(CURRENT_TIMESTAMP(3), @CURRENT_TIMESTAMP) |
| :------------------------------------------------- |
| 00:00:00.002000                                    |

CREATE TRIGGER tr_bi BEFORE INSERT ON test
FOR EACH ROW
SELECT NEW.id + SLEEP(2) INTO @tmp;
CREATE TRIGGER tr_ai AFTER INSERT ON test
FOR EACH ROW
SELECT NEW.id + SLEEP(3) INTO @tmp;

-- 2 triggers with SLEEP, over 2+3=5 second per row insertion
SELECT CURRENT_TIMESTAMP(3) INTO @CURRENT_TIMESTAMP;
INSERT INTO test VALUES (1);
SELECT TIMEDIFF(CURRENT_TIMESTAMP(3), @CURRENT_TIMESTAMP)

| TIMEDIFF(CURRENT_TIMESTAMP(3), @CURRENT_TIMESTAMP) |
| :------------------------------------------------- |
| 00:00:05.003000                                    |

db<>fiddle here


text:
Q: Executing grails service method in separate thread I have a Grails application (ver. 2.4.3) and I have problem with call a service method in a separate thread. I use a Promise concept according to documentation. I have two services: in the first I have the main method which saves a parent entity and then the second  saves children records for given parent. I would like to implement saving children records in separate thread. The main service looks like:
@Transactional
class ParentService {

    AsyncSourceService asyncSourceService

Parent save(Date dateFrom,  Date dateTill, File sourceFile){
        log.info "save - start"

        Parent parent = new Parent(dateFrom: dateFrom, dateTill: dateTill, status: Status.LOAD_IN_PROGRESS)
        parent.save(flush:true)

        //TODO: asynchronous call
        //sourceRecordService.decodeRecords(parent, sourceFile)

            def  promise = asyncSourceService.decodeSourceFile(Parent, sourceFile)
            promise.onComplete { results ->
                println("#### Results: $results ####")
            }
            promise.onError { Throwable t ->
                //t.printStackTrace()
                println "####### ${t.message}"
            }
        return parent
    }
}

SourceService looks like:
@Transactional
class SourceService {

   Integer decodeSourceFile(Parent parent, File sourceFile){
       int lineNo = 0
       sourceFile.eachLine {line->
           // convert line to record
           sourceRecord.save()
           lineNo++
       }
       return new IntegerlineNo

    }
}

And the wrapper for asynchronous calling a service looks like:
class AsyncSourceervice {

    @DelegateAsync
    SourceService sourceService

    Promise<Integer> decodeSourceFile(Parent parent, File sourceFile){
        Promises.task {
            sourceService.decodeSourceFile(parent, sourceFile)
        }
    }
}

And it doesn't works. When I run a process I get:
| Error 2014-10-14 08:47:26,586 [Actor Thread 2] ERROR gpars.LoggingPoolFactory  - Async execution error: null
Message: null
    Line | Method
->>   72 | doCall    in org.grails.async.factory.gpars.GparsPromise$_onError_closure2
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|     62 | run       in groovyx.gpars.dataflow.DataCallback$1
|   1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
|    615 | run       in java.util.concurrent.ThreadPoolExecutor$Worker
^    744 | run . . . in java.lang.Thread

I know that the service method for decoding works and it decodes proper count of records, but no callback method occurs (neither on onError or onComplete). What is wrong?
I've noticed that for file with few records (less than 50) it works fine but when file contains about 100 records or more I get such stack track. It seems to be strange because, I my debug shows that decoding process works fine and it return proper value of decoded records. And when I call the whole process in the same thread everythings seems to wok correct.
Has anyone idea what is wrong? I will be grateful for any suggestion. maybe I should use other solution. Which?

A: I've found the solution: when I comment handling onError and onComplete for the promise object, everything works ok. It seems to these handlers execute before the thread is finished, that's why for the larger files I got exception. I am thinking over, if it is a bug in Promise concept or if I wrong unnderstood it.


text:
Q: htaccess hide "Index of" I want display just the directory content of my Webserver.
My .htaccess file contains:
Options '+Indexes'
IndexOptions +FancyIndexing

And in the browser I got the path :
"Index of /~efc/"

In the footer :
"Apache/2.2.22 (FreeBSD) mod_ssl/2.2.22 OpenSSL/1.0.1c mod_hcgi/0.9.4 DAV/2 Server"
Is there a way to prevent these lines?
EDIT: In addition to the answer of Sàt i got my desired result with following directives:
Options '+Indexes'

# SET INDEX OPTIONS
IndexOptions IgnoreCase FancyIndexing FoldersFirst NameWidth=* DescriptionWidth=* SuppressHTMLPreamble

# SPECIFY HEADER FILE
HeaderName header.html

# SPECIFY FOOTER FILE
ReadmeName footer.html

# IGNORE THESE FILES
IndexIgnore header.html footer.html

A: Sure. Use the HeaderName and ReaderName directives, like this:
Options '+Indexes'
IndexOptions +FancyIndexing
HeaderName fancy_hdr.html
ReadmeName fancy_readme.html

HeaderName points at the html file rendered before the listing, ReadmeName points at the html rendered after the listing.
There are a whole lot of fun customization options, you might want to take a look at those in the docs or various tutorials.

A: The footer is also printed on error pages like 404. You can control its display via the ServerTokens directive in your httpd.conf.


text:
Q: How to loop through an object of arrays in Javascript? For the below code,
const groupbysubject = {
                    "Mathematics":
                    [
                      {totalStudents: "23", average: "78", class: "2"},
                      {totalStudents: "25", average: "80", class: "3"}
                    ],
                    "English":
                    [
                      {totalStudents: "33", average: "98", class: "2"},
                      {totalStudents: "35", average: "99", class: "3"}
                    ],
                    "Science":
                    [
                      {totalStudents: "43", average: "65", class: "2"},
                    ]
                  }

var isEnglishPresent = Object.fromEntries(
                           Object.entries(groupbysubject).filter(
                             ([key, val])=> key.includes("English")
                            )
                        );

I want the following output :

"33"
"98"
"2"
"35"
"99"
"3"

I have filtered the above groupbysubject object into isEnglishPresent object.
How do I proceed further to iterate over isEnglishPresent and get the above output.
Please help
Thank you.

A: You want a flat list of the values from the items inside the English key:

const groupbysubject = {
  "Mathematics":
  [
    {totalStudents: "23", average: "78", class: "2"},
    {totalStudents: "25", average: "80", class: "3"}
  ],
  "English":
  [
    {totalStudents: "33", average: "98", class: "2"},
    {totalStudents: "35", average: "99", class: "3"}
  ],
  "Science":
  [
    {totalStudents: "43", average: "65", class: "2"},
  ]
};

var englishData = groupbysubject.English.flatMap(item => Object.values(item));

console.log(englishData);

A: Assume you have an English array with N objects like below.
const English = [
  {totalStudents: "33", average: "98", class: "2"},
  {totalStudents: "35", average: "99", class: "3"},
  ...
]

Here's how you extract all the values and put it into an array.
English.map(item => Object.values(item)).flat()

Here's the output
["33", "98", "2", "35", "99", "3"]


text:
Q: Неопределенный объект 2 проекта, серверный и клиент, сервер ASP.NET Core, Клиент- Angular 8.
Опять Cannot read property 'id' of undefined. Дела обстоят так, принимаю с сервера объект User, все идет нормально, создаю форму по объекту в хтмл, на деле все работает, все распознано и вставляется в свои места, но в консоли получаю Cannot read property 'id' of undefined.
Код сервера:
[HttpGet, Route("getuser")]
        public IActionResult Get()
        {
            User user = db.Users.FirstOrDefault(x => x.UserName == User.Identity.Name);
            return Ok(user);
        }

Код компонента:
export class EditUserComponent implements OnInit {

  constructor(private router: Router, activeRoute: ActivatedRoute, public http: HttpClient,) {}
  user: User;
  invalidLogin: boolean;
  ngOnInit() {
    let token = localStorage.getItem("jwt");
    this.http.get("http://localhost:5000/api/user/getuser",
      {
        headers: new HttpHeaders({
          "Authorization": "Bearer " + token,
          "Content-Type": "application/json"
        })
      }).subscribe((response:User) => {
        this.user = response;
      }, err => {
        console.log(err)
      });
  }

Код хтмл:
<form class="form-signin" #loginForm="ngForm" (ngSubmit)="login(loginForm)">

Login

Invalid username or password.

    <input type="number" [(ngModel)]="user.id" id="id" name="id" ngModel class="form-control" placeholder="id" required>

    Login
    <input type="text" [(ngModel)]="user.userName" id="username" name="username" ngModel class="form-control" placeholder="User Name" required autofocus>

    LastName
    <input type="text" [(ngModel)]="user.lastName" id="lastname" name="lastname" ngModel class="form-control" placeholder="LastName" required>

    Password
    <input type="password" [(ngModel)]="user.password" id="password" name="password" ngModel class="form-control" placeholder="Password" required>

    <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>

</form>

Код самой сущьности в Ангуляре:
export class User {
  constructor(
    public id: number,
    public userName: string,
    public password: string,
    public lastName:string
  ) { }

}

Повторюсь-на деле все идеально, все работает как часы, если не открывать консоль, то ошибку и не заметить, но не могу понять почему она там...
С сервера приходит:
{"id":1,"userName":"laki_winners","password":"123","lastName":"lw1234"}
П.С. Знаю что id пока коряво запихал в форму, но это чисто для проверки, в дальнейшем скрою, да и если я убираю id, то ошибка ругается на userName, уберу userName, она ругается на lastName и так далее, в общем user будто неопределен, хотя по факту все работает и я получаю данные из юзера и она вставляются в форму как надо.

A: Компонент вызывал сначала пустого юзера, а потом перезаписывал в него данные из сервера, проблему решило -
. Другими словами задал условие, если юзер не пустой, то все ок.


text:
Q: Written data from scanner to arrays I would like to create a shopping list program, after entering the name and price of product enters them into the arrays and then print the entire list of what is wrong with this code?
import java.util.Scanner;
import java.util.Arrays;

public class List {
    public static void main (String[] args){
        Scanner sc = new Scanner(System.in);
        String [] name = new String[4];
        double [] price = new double[4];

        for (int i =0; i<name.length; i++) {
            System.out.println("name");
            name[i] = sc.nextLine();

            System.out.println("price");
            price[i] = sc.nextDouble();
        }
        System.out.println("your product: " + Arrays.toString(name) + Arrays.toString(price));
    }
}

A: You can resolve it by using nextLine() instead of nextDouble(). However, you need to parse it to a double as your value declared as double :
Scanner sc = new Scanner(System.in);
String [] name = new String[4];
double [] price = new double[4];

for (int i =0; i<name.length; i++) {
    System.out.println("name");
    name[i] = sc.nextLine();
    System.out.println("price");
    price[i] = Double.parseDouble(sc.nextLine()) ;
}
System.out.println("your product: " +  Arrays.toString(name) + Arrays.toString(price));

A: Scanner#nextLine() reads the whole line.
Scanner#nextDouble() reads the next token and not the whole line.
So for the second iteration of loop nextLine() will read the same line where you placed the token giving you empty in name[1] and error for double[1]=sc.nextDouble().
Docs
The problem can be solved by adding a nextLine() after reading double variable
for (int i =0; i<name.length; i++) {
          System.out.println("name");
          name[i] = sc.nextLine();

          System.out.println("price");
          price[i] = sc.nextDouble();

          if(i<name.length-1)
             sc.nextLine();        //will skip the line
 }

Demo

A: So I was using input.nextDouble()  and it was giving me Type mismatch error
public static void main (String[] args)
{
    Scanner input = new Scanner(System.in);
    double[] numbers = new double[4];
    String [] name = new String[4];

    for (int i = 0; i < numbers.length; i++)
    {
        System.out.println("Please enter product price");
        numbers[i] = Double.parseDouble(input.nextLine());

        System.out.println("Please enter product name");
        name[i] = input.nextLine();
    }

System.out.println(Arrays.toString(name));
System.out.println(Arrays.toString(numbers));
}


text:
Q: ES6 named imports in defineAsyncComponent I'd like to async load some elements of my web app:
This is the old import:
import {Popover, PopoverButton, PopoverPanel} from '@headlessui/vue'

export default {
    components: {
        Popover,
        PopoverButton,
        PopoverPanel,
    },
...

Now I would like to do this:
import {defineAsyncComponent} from "vue";

export default {
    components: {
        Popover: defineAsyncComponent(() =>
            import( {Popover} from "@headlessui/vue" ) // This does not work as I get the error " ')' expected"
        ),
        ...
    },
...

Any idea how I could solve this?

A: Static import is a statement and isn't supposed to be used anywhere but at the top of a module. Dynamic import() is an expression and follows JavaScript syntax that is used in expressions.
import() returns a promise of module exports. It should be:
Popover: defineAsyncComponent(async () => {
 return (await import("@headlessui/vue")).Popover;
})

Tree shaking is disabled for dynamically imported module and needs to be annotated for a bundler, e.g. Webpack.


text:
Q: Use iconv API in C I try to convert a sjis string to utf-8 using the iconv API. I compiled it already succesfully, but the output isn't what I expected.
My code:
void convertUtf8ToSjis(char* utf8, char* sjis){
  iconv_t icd;
  int index = 0;
  char *p_src, *p_dst;
  size_t n_src, n_dst;
  icd = iconv_open("Shift_JIS", "UTF-8");
  int c;
  p_src = utf8;
  p_dst = sjis;
  n_src = strlen(utf8);
  n_dst = 32; // my sjis string size
  iconv(icd, &p_src, &n_src, &p_dst, &n_dst);
  iconv_close(icd);
}

I got only random numbers. Any ideas?
Edit:
My input is
char utf8[] = "\xe4\xba\x9c";       //亜

And output should be:
0x88 0x9F
But is in fact:
0x30 0x00 0x00 0x31 0x00 ...

A: I was unable to duplicate the problem. The only thing I can suggest is to be careful about your allocations.
Code:
#include <iconv.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

void convertUtf8ToSjis(char* utf8, char* sjis){
 ...
}

int main(int argc, char *argv[])
{
  char utf8[] = "\xe4\xba\x9c";
  char *sjis;
  sjis = malloc(32);
  convertUtf8ToSjis(utf8, sjis);
  int i;
  for (i = 0; sjis[i]; i++)
  {
    printf("%02x\n", (unsigned char)sjis[i]);
  }
  free(sjis);
}

Output:
$ gcc t.c
$ ./a.out
88
9f


text:
Q: Testing authenticated file uploads in merb This is something that has been driving me mad over the past few days. I have an action which allows authenticated users to upload assets to the site. I know that the controller action is correct as I can run through the process manually however I want to test it using rspec.
I have to use the request helper so I can reuse an authenticated session which is a :given for this set of tests.
it "should allow authenticated file uploads" do
    file = File.open(a_valid_file)
    mock_file = mock("file")
    mock_file.stub!(:path).and_return(file.path)

    request( resource(:assets), :method => "POST",
        :params => { :file =>
            {:tempfile => mock_file, :filename => File.basename(file.path)} }
    )
end

If I breakpoint inside the spec it all works nicely, however when I run the spec and try to access the path in the controller action through the debugger I get this:
e file[:tempfile].path
NoMethodError Exception: undefined method `path' for "#[Spec::Mocks::Mock:0x3fda2a4736c0 @name=\"file\"]":String

My guess is that the stub!(:path) is not being set for whatever mock object is making it through the request.
The question is: Am I going about the right way for testing file uploads and if not what is another way?

A: I was doing it wrong. By using request it was calling to_s on all paramaters, so my mock object was being passed as "#[Spec::Mocks::Mock:0x3fda2a4736c0 @name=\"file\"]". That will teach me to pay more attention to exception output.
Instead I should use multipart_post and stub out the authentication calls in a block.
it "should allow authenticated file uploads" do
    file = File.open(a_valid_file)

    multipart_post( resource(:assets), :method => "POST",
            :params => { :file => file } ) do |controller|
        controller.stub!(:ensure_authenticated).and_return(true)
        controller.session.stub!(:user).and_return(User.first)

    )
end


text:
Q: Bundling not happening when deployed to production server I have created a bundle. However its not working when deployed to production server. I am running MVC4 RC
My bundle looks like
 public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/bundles/core").Include("~/Scripts/min/jquery-1.*",
           "~/Scripts/min/core.js",
          "~/Scripts/min/business-signup.js",
          "~/Scripts/min/slider.js",
          "~/Scripts/min/label-text.js",
          "~/Scripts/min/consumer-account.js",
          "~/Scripts/min/modernizr-2*"));

        bundles.Add(new StyleBundle("~/Content/min/css").Include(
            "~/Content/min/core.css",
            "~/Content/min/layout.css",
            "~/Content/min/reset.css",
            "~/Content/min/sprite.css",
            "~/Content/min/pricing.css",
            "~/Content/min/homepage-slider.css",
            "~/Content/min/transactions.css"));

    }

From my layout I call the bundles like
   @Styles.Render("~/Content/min/css","~/Content/min/css")
   @Scripts.Render("~/bundles/core")

However there is no minifaction or bundling happening. Instead a single request is made for each of the items within the the bundles.
I know the server is working correctly as I have another site running on the same server and the bundling is working ok.
Can anyone see something obvious to what I am doing wrong?

A: Make sure you are running in Release mode (debug="false" in your web.config). Also notice that there is a bug in the RC that prevents of properly caching the resources server side and thus increasing the CPU usage of your site everytime a request is made to the url that is supposed to serve the bundled and minified version of your resources.


text:
Q: stata logistic regression error code due to missing values- what can I do? I am performing a logistic regression
regress igg1ugml age_years term_spec cesareansection estradiollevels breastfeed_howlong, robust
when I run the code with both estradiollevels and breastfeed_howlong, it leads to the error. When I run it without one of those variables, it leads to an output.
Neither variables are string variables. However, they do hold many missing values (256/334) for breastfeed_howlong and (270/334) for estradiollevels
What can I do about this? I would like to include both variables in my analysis.
Thank you in advance


text:
Q: How can I delete data in coreData and Tableview with one Button? I'm actually doing an app for recipe, I already did the persistent data to save my ingredients in the list but when I want to delete my ingredients with my button it works at the first time but come back when I restart my app.
Here's my code :
class AddIngredientController: UIViewController, ShowAlert {

    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var ingredientsTableView: UITableView!

    var itemArrayIngredient = [Item]()

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    override func viewDidLoad() {
        super.viewDidLoad()
        let dataFilePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        print(dataFilePath)
        loadItems()
    }

    func saveItems() {
        do {
            try context.save()
        } catch {
            print("Error saving context \(error)")
        }
    }

    func loadItems(with request: NSFetchRequest<Item> = Item.fetchRequest()) {
        do {
            itemArrayIngredient = try context.fetch(request)
        } catch {
            print("Error fetching data from context \(error)")
        }
    }

    @IBAction func clearButton(_ sender: UIButton) {
        context.delete() //Here the problem
        itemArrayIngredient.removeAll()
        saveItems()
        ingredientsTableView.reloadData()
    }

    @IBAction func addButton(_ sender: UIButton) {
        if textField.text!.isEmpty {
            showAlert(title: "No Ingredients", message: "Please, add some ingredients to your list.")
        } else {
            newIngredientAdded()
        }
    }

    func newIngredientAdded() {
        let newItem = Item(context: context)
        newItem.title = textField.text!
        itemArrayIngredient.append(newItem)
        saveItems()
        ingredientsTableView.reloadData()
        textField.text! = ""
    }
}

extension AddIngredientController: UITableViewDataSource, UITableViewDelegate {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return itemArrayIngredient.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "customSearchCell", for: indexPath)
        let item = itemArrayIngredient[indexPath.row]
        cell.textLabel?.text = item.title
        cell.textLabel?.textColor = UIColor.white
        cell.textLabel?.font = UIFont(name: "Marker Felt", size: 19)
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        saveItems()
        tableView.deselectRow(at: indexPath, animated: true)
    }
}

A: You need to delete a specific object from core data. Please refer below code
let fetchRequest = NSFetchRequest(entityName: "EntityName")

if let result = try? context.fetch(fetchRequest) {
    for object in result {
        //Please check before delete operation
        if object.id == Your_Deleted_Object_ID{
            context.delete(object)
        }
    }
}

A: You can delete all data from particular entity by using NSBatchDeleteRequest. See following code. The main advantage of NSBatchDeleteRequest is, you don't need to enumerate on array of object.
let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "EntityName")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetch)

do {
    try context.execute(deleteRequest)
} catch {
    print(error.localizedDescription)
}

A: context.delete must be called with an argument. For example
@IBAction func clearButton(_ sender: UIButton) {
    itemArrayIngredient.forEach { context.delete($0) }
    itemArrayIngredient.removeAll()
    saveItems()
    ingredientsTableView.reloadData()
}


text:
Q: class AppDelegate Thread 1: SIGABRT Whenever I try to run the app I get Thread 1: SIGABRT error although my app does not have any outlets or actions (no visual elements)
and here is the console info:
    2017-02-19 12:43:31.787 ParseStarterProject-Swift[1623:158691] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderArray initWithObjects:count:]: attempt to insert nil object from objects[1]'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010f75fd4b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x000000010f1c121e objc_exception_throw + 48
    2   CoreFoundation                      0x000000010f66f783 -[__NSPlaceholderArray initWithObjects:count:] + 275
    3   CoreFoundation                      0x000000010f676994 +[NSArray arrayWithObjects:count:] + 52
    4   ParseStarterProject-Swift           0x000000010e3517d0 -[PFTaskQueue enqueue:] + 243
    5   ParseStarterProject-Swift           0x000000010e2f7e57 -[PFObject saveInBackground] + 121
    6   ParseStarterProject-Swift           0x000000010e2f7ef3 -[PFObject saveInBackgroundWithBlock:] + 49
    7   ParseStarterProject-Swift           0x000000010e2c13f0 _TFC25ParseStarterProject_Swift14ViewController11viewDidLoadfT_T_ + 832
    8   ParseStarterProject-Swift           0x000000010e2c1a92 _TToFC25ParseStarterProject_Swift14ViewController11viewDidLoadfT_T_ + 34
    9   UIKit                               0x000000010ff08a3d -[UIViewController loadViewIfRequired] + 1258
    10  UIKit                               0x000000010ff08e70 -[UIViewController view] + 27
    11  UIKit                               0x000000010fdd24b5 -[UIWindow addRootViewControllerViewIfPossible] + 71
    12  UIKit                               0x000000010fdd2c06 -[UIWindow _setHidden:forced:] + 293
    13  UIKit                               0x000000010fde6519 -[UIWindow makeKeyAndVisible] + 42
    14  UIKit                               0x000000010fd5ef8d -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 4818
    15  UIKit                               0x000000010fd650ed -[UIApplication _runWithMainScene:transitionContext:completion:] + 1731
    16  UIKit                               0x000000010fd6226d -[UIApplication workspaceDidEndTransaction:] + 188
    17  FrontBoardServices                  0x0000000112bac6cb __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 24
    18  FrontBoardServices                  0x0000000112bac544 -[FBSSerialQueue _performNext] + 189
    19  FrontBoardServices                  0x0000000112bac8cd -[FBSSerialQueue _performNextFromRunLoopSource] + 45
    20  CoreFoundation                      0x000000010f704761 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    21  CoreFoundation                      0x000000010f6e998c __CFRunLoopDoSources0 + 556
    22  CoreFoundation                      0x000000010f6e8e76 __CFRunLoopRun + 918
    23  CoreFoundation                      0x000000010f6e8884 CFRunLoopRunSpecific + 420
    24  UIKit                               0x000000010fd60aea -[UIApplication _run] + 434
    25  UIKit                               0x000000010fd66c68 UIApplicationMain + 159
    26  ParseStarterProject-Swift           0x000000010e2c37ff main + 111
    27  libdyld.dylib                       0x0000000111fe668d start + 1
    28  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

I appreciate any help that you can provide

A:
attempt to insert nil object

A nil object is being inserted into Array in the application's rootViewController. That is the source of the SIGABRT crash.


text:
Q: Add bottom border only at chapter name, not in chapter number I am trying to achieve something like the photo below using the titlesec package but I couldn't manage to add a border only at chapter name. Any ideas? :

My code snippet
\titleformat{\chapter}[block]
{\Huge\bfseries}
{{\fontsize{50pt}{1em}\textnormal{\thechapter}}}{1ex}{}
[\normalsize\vspace*{.8\baselineskip}{\titlerule[0.6mm]}]

A: Something like this?
\documentclass[11pt,a4paper]{book}
\usepackage[greek]{babel}
\usepackage{graphicx}
\usepackage{linegoal}
\newcommand{\ultitle}[1]{\makebox[\linegoal][r]{#1}}

\usepackage{titlesec}
\titleformat{\chapter}[block]{ \bfseries\huge}{\fontfamily{qag}\selectfont
\bfseries\raisebox{-6pt}{\scalebox{3}{\thechapter}}}{4ex}
{\mbox{}\rlap{\rule[-6pt]{\linegoal}{1.6pt}}\ultitle}

\begin{document}

\chapter{Introduction}%

\end{document}


text: Q: Mathematics of Geophysical Fluid Dynamics Does anyone know some of the contemporary mathematical challenges associated with the fluid dynamics behind climate modelling? Of course the Navier-Stokes equations are relevant, but even with these I am unsure of what approaches mathematicians who are  particularly interested in atmospheric or oceanic fluid dynamics are taking when it comes to studying them (as opposed to those with interests in complex fluids for engineering purposes). I am looking for mathematicians who research these things, but since I don't know what exactly they would be researching it is difficult to find them.


text:
Q: Javascript error in accessing JSON In the following JSON how to access id and name
console.log($scope.mylist)

{"data":"{\"projects\":[{\"id\":\"3\",\"title\":\"MYCLOUD\",\"desc\":\"DESC\"}]}"}

I tried the following
console.log($scope.mylist.data) //undefined
console.log($scope.mylist["data"])//undefined
console.log($scope.mylist.projects)//undefined
console.log($scope.mylist["projects"]) //undefined

A: Your data property contains JSON, so you need to JSON.parse that too.
$scope.mylist.data.projects = JSON.parse($scope.mylist.data);

Then you should be able to access it with
$scope.mylist.data.projects[0].id //etc

Though there's an underlying problem of how you're getting/sending that JSON.


text:
Q: Getting Data using the Zend Framework I've setup a page so that when you click on a link it will go to the specific action followed by the id of what was clicked on.
For instance, if I had a list of albums and clicked play on an album with an id of 2 it would go to www.mysite/albums/play/2.
I have this working as I would like it, however, when I'm in the playAction() method in the controller, how can I get the ID of the specific album I chose?

A: The ID can be found by adding this line to the controller:
$id = (int) $this->params()->fromRoute('id', 0);


text:
Q: Pasar de formato telefono a un number en javascript Buen dia, es posible en javascript pasar este telefono +1 (833) 555-2739 a formato numero? si tengo +1 (833) 555-2739 que me devuelva 18335552739

A: Puedes hacerlo con expresiones regulares, por ejemplo
function telToNumber(str) {
const regex = /[0-9]/gm
let m;
let result = []

while ((m = regex.exec(str)) !== null) {
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    // The result can be accessed through the `m`-variable.
    m.forEach(match => {
        result.push(match)
    });
}

return result.join('')
}
telToNumber('+1 (833) 555-2739') //retornara "18335552739"

espero que te haya ayudado


text:
Q: Why doesn't my Web Api proxy receive https requests when set as browser proxy, but can normally? I have written a http proxy using WebApi.
I have it registered on port 4443, and if I enter https://localhost:4443 into a browser, and set a breakpoint in my DelegatingHandler, it will be hit (and I get an SSL warning).
If I then set it to be the firefox proxy (see image), for SSL requests, and browse to https://somesite.com it is not hit - Web Api appears not to handle the call at all.

What is the browser doing differently when it uses a proxy as opposed to when it makes direct calls that causes Web Api to not handle the call?


text:
Q: Defining folder and parameters in process.start? I'm trying to create a simple launcher for anti-virus programs using c#, and having a bit of difficulty understanding what im missing.
i want to run cmd.exe, then run sav32cli.exe with the argument "e:" so it always scans drive E. this is located in "C:\Program Files (x86)\Sophos\Sophos Anti-Virus"
this is the line I have, but when I run it the program closes.
System.Diagnostics.Process.Start("cmd", "cd "c:/Program Files (x86)/Sophos/Sophos Anti-Virus/" && sav32cli.exe e: ");
or is there a better suited process for this?

A: You don't need to use cd to direct to the folder. Just use absolute path to access the exe.
Process p = new Process();
// the full path of exe
p.StartInfo.FileName = @"D:/Program Files (x86)/Sophos/Sophos Anti-Virus/sav32cli.exe";
// set the argument
p.StartInfo.Arguments = "e:";
p.Start();


text:
Q: I need to execute a AsynckTask object 5 times with an interval of 2 minutes I want to fire an event (sending a sms) every 2 minute . how can i do this . I am using AsyncTask Class to handle background task and want to use its object to execute 5 times with an interval of 2 minutes .I have seen the previous answers and try using Thread.sleep() ,Timer ,and wait but nothing worked for me . Please help guys.

A: private static final ScheduledExecutorService worker =
Executors.newSingleThreadScheduledExecutor();

void someMethod() {
 ⋮
Runnable task = new Runnable() {
public void run() {
  /* Do something… */
}
};
worker.schedule(task, 5, TimeUnit.SECONDS);
⋮
}

or if you want to use timer
you can refer to this post on stackoverflow
Android timer? How-to?


text:
Q: Stop nginx in django completely I have used nginx as web server for django project , And now i want to use my normal django local server (switch to older local server).
I tried
sudo service nginx stop

(It is showing nginx is stopped)
i killed all process too.
But still my localserver:127.0.0.1:8000 is under nginx control.And my computer ip is also under nginx control.(it shows the nginx default page)
I want free that particular port(localserver:127.0.0.1:8000). How can i completely stop nginx ?


text:
Q: How to get a value out of an array in typescript? I have an array that looks like this
   const array: any[] = []
   array.push({ 'Comments': this.comment, 'Name': this.name, 'Description' : this.description })

I pass that array back to a parent component. How can I grab the value that is in Comments?

A: You can use forEach loop :
const commentArray = [];
array.forEach(function(object) {
    var comment = object.Comments;
    commentArray.push(comment);
});
//You can store all comments in another array and use it...
console.log("This is comment array...", commentArray);

Or use map but it will work in new browsers possibly ones following ES6:
const commentArray = array.map(function(object) {
    return object.Comments;
});
console.log("This is comment array... ", commentArray);

A: As long as TGW's answer is "correct" and works, I think you should be aware of and use for...of (and for...in) construction, it's superior over Array.forEach (faster, you can use continue and break keywords, better readability) and more often you want to iterate over your array and do things with it, than just get one property (which Array.map is perfect for in this case :) )

A: You may try for this:
We can also use filter here.
let commentArray:any[];
array.filter(function(object) {
    var comment = object.Comments;
    commentArray.push(comment);
});
//Store here and use this.
console.log("This is comment array...", commentArray);

A: You can use Underscore JS for short and better performance like below:
    let ids: Array<number> = _.map(this.mylist, (listObj) => {
        return listObj.Id;
    });


text:
Q: Mathematics behind the function "approx3d" Can someone provide me reference regarding the mathematics of the "approx3d" function? Does this function apply "trilinear interpolation"?

A: The only approx3d implementation I could find is a library in R, here and indeed it says it uses "trilinear approximation."
The simpler case would be "bilinear interpolation". Given two points on a plane, the interpolated middle-point is just the average of those two given points.
Trilinear interpolation is similar, except that in three dimensions you must average three points (not two) and average their three coordinates. You may notice that if (for example) both points have the same X-coordinate (say x=0), then the problem reduces to bilinear interpolation again.


text:
Q: Neo4J Multiple Match Statement in Single Query I want to get Total Count of VoteUp and VoteDown on Pixel in Single Query but it return TRUE RESULT when it have Greater then Zero Value that means VoteUp and VoteDown Greater then Zero.
MATCH (n:pixel)-[vu:vote_up]-(:users),
  (n:pixel)-[vd:vote_down]-(:users)
  WHERE ID(n)=7445 RETURN count(vu),count(vd)

Above My Query. it return wrong result when VoteUp Zero and VoteDown Greater then Zero.

A: I got Solution of My Question from Following Query:
MATCH (n:pixel)WHERE ID(n)=7445
RETURN
size((n)-[:vote_up]-(:users)) as VoteUp,
size((n)-[:vote_down]-(:users)) as VoteDown

Finded Reference From Here


text:
Q: QGIS "difference" tool - "feature has invalid geometry" - returns empty layer
I am trying to return the areas of the red polygon that fall outside of the orange polygon, using the difference tool.
Both are vector layers I created by drawing around a georeferenced map. Their attribute tables only contain their area, shown below.
When I run the difference tool, it returns "Feature has invalid geography", and the resulting layer is empty and does not appear on my map.

A: Fix geometries:
(Processing toolbox -> Vector geometry -> Fix geometries)

This algorithm attempts to create a valid
representation of a given invalid geometry without losing any of the
input vertices. Already-valid geometries are returned without further
intervention.

Then try Difference


text:
Q: Unable to create requested service [org.hibernate.engine.spi.CacheImplementor] I am getting below error while I am using spring 4.3.9 and hibernate 5.2.10 with Java 8.
org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.spi.CacheImplementor]
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:271)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:233)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
        at org.hibernate.service.internal.SessionFactoryServiceRegistryImpl.getService(SessionFactoryServiceRegistryImpl.java:77)
        at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:240)
        at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:452)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:710)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
        at com.somename.emg.server.db.dataaccess.AlarmDaoTest.setUp(AlarmDaoTest.java:84)
        at junit.framework.TestCase.runBare(TestCase.java:139)
        at junit.framework.TestResult$1.protect(TestResult.java:122)
        at junit.framework.TestResult.runProtected(TestResult.java:142)
        at junit.framework.TestResult.run(TestResult.java:125)
        at junit.framework.TestCase.run(TestCase.java:129)
        at junit.framework.TestSuite.runTest(TestSuite.java:252)
        at junit.framework.TestSuite.run(TestSuite.java:247)
        at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:86)
        at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
        at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
        at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
        at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
        at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
        at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: org.hibernate.cache.NoCacheRegionFactoryAvailableException: Second-level cache is used in the application, but property hibernate.cache.region.factory_class is not given; please either disable second level cache or set correct region factory using the hibernate.cache.region.factory_class setting and make sure the second level cache provider (hibernate-infinispan, e.g.) is available on the classpath.
        at org.hibernate.cache.internal.NoCachingRegionFactory.buildTimestampsRegion(NoCachingRegionFactory.java:90)
        at org.hibernate.cache.spi.RegionFactory.buildTimestampsRegion(RegionFactory.java:261)
        at org.hibernate.internal.CacheImpl.<init>(CacheImpl.java:78)
        at org.hibernate.engine.spi.CacheInitiator.initiateService(CacheInitiator.java:28)
        at org.hibernate.engine.spi.CacheInitiator.initiateService(CacheInitiator.java:20)
        at org.hibernate.service.internal.SessionFactoryServiceRegistryImpl.initiateService(SessionFactoryServiceRegistryImpl.java:58)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:259)
        ... 28 more

my configuration file details are as below,
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.cache.use_second_level_cache">true</prop>
            <prop key="hibernate.cache.region.factory_class">
                org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
            </prop>
            <prop key="hibernate.cache.use_query_cache">true</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
            <prop key="hibernate.hbm2ddl.auto">create-drop</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
    <property name="annotatedClasses">
        <list>
            <value>some.class.here</value>
        </list>
    </property>
</bean>

Maven file is as below,
<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <junit.version>5.2.0</junit.version>
        <org.springframework.version>4.3.9.RELEASE</org.springframework.version>
        <cxf.version>3.1</cxf.version>
        <!-- <birt.version>3.7.1</birt.version> -->
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-runner</artifactId>
            <version>1.2.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-event</artifactId>
            <version>2.0.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${org.springframework.version}</version>
            <scope>test</scope>
        </dependency>
        <!-- Dependencies for apsect annotation -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.11</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.6.11</version>
        </dependency>
        <!--dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0</version>
        </dependency-->
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.5</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.10.Final</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-annotations</artifactId>
            <version>3.5.6-Final</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1</version>
        </dependency>
        <dependency>
            <groupId>asm</groupId>
            <artifactId>asm</artifactId>
            <version>2.2.3</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib-nodep</artifactId>
            <version>2.1_3</version>
        </dependency>
        <!--dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>3.0.0.ga</version>
        </dependency-->
        <dependency>            <groupId>hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <version>1.8.0.7</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.2</version>
        </dependency>
        <!--dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache-core</artifactId>
            <version>2.1.1</version>
        </dependency-->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-ehcache</artifactId>
            <version>4.1.12.Final</version>
            <exclusions>
                 <exclusion>
                     <groupId>net.sf.ehcache</groupId>
                     <artifactId>ehcache</artifactId>
                 </exclusion>
             </exclusions>
        </dependency>
        <dependency>
            <groupId>org.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>3.0.0</version>
        </dependency>
        <!-- Quartz Dependency -->
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.1.5</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.6</version>
        </dependency>

        <!-- Gson: Java to Json conversion -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>1.7.1</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4</version>
        </dependency>

        <!-- File Upload Dependency -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.1</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.0.1</version>
        </dependency>

        <!-- CSVParser Dependency -->
        <dependency>
            <groupId>net.sf.opencsv</groupId>
            <artifactId>opencsv</artifactId>
            <version>2.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-core</artifactId>
            <version>5.2.0</version>
        </dependency>

        <!-- Apache's velocity template engine jar -->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.6.2</version>
        </dependency>

I also tried disabling second-level-caching, but result is same.
Also went through the link, but no luck.
Any help would be deeply appreciated.

A: Second-level cache is used in the application, but property hibernate.cache.region.factory_class is not given; please either disable second level cache or set correct region factory using the hibernate.cache.region.factory_class setting and make sure the second level cache provider (hibernate-infinispan, e.g.) is available on the classpath.
You have to set the hibernate.cache.region.factory_class property. For instance with ehcache would be adding the following line:
<property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</property>


text:
Q: PHP - Multiple Api Call - Response time more then 15 seconds? I need to get the order count for the last 30 days in a 1 day period. That´s what I wrote but the response time is 15 seconds and up. Is there any smarter strategy, maybe a Simultaneous asynchronous API call? I did not found a direct call to the orders api to receive the daily orders with one request. Any one any ideas?
Here´s my code:
for ($i = 0; $i < 30; $i++)

{
    $timestamp = time();
    $tm = 86400 * $i; // 60 * 60 * 24 = 86400 = 1 day in seconds
    $tm = $timestamp - $tm;

    $the_date = date("Y-m-d", $tm);
    $newdate = date('Y-m-d', strtotime($the_date. ' + 1 days'));

    $orderinfo = shopify_call($token, $shop, "/admin/orders/count.json?status=any&created_at_min=".$the_date."&created_at_max=".$newdate, $array, 'GET');
    $orderinfo = json_decode($orderinfo['response'], JSON_PRETTY_PRINT);

    print_r($orderinfo);

}

A: Hello as per your code you are calling shopify Api in a loop that's why it is taking time . So you can fetch last 30 days order first and after that you can easily distinguish order by order created date.
You can take reference by this api doc
Shopify order Api
In this doc you can fetch last 30 days order by created_at_min  filter


text:
Q: Is there a way to prepend joined tablename in BigQuery Standard SQL? I would like to know if it is possible to force standard SQL to prepend joined tablenames, so that I can get all fields from a and b with a_ and b_ prepended, without manually naming each field.  Ie. I want to do a SELECT *, I don't want to generate each fieldname.
I know that if you switch from Legacy SQL to Standard SQL, a
SELECT *
FROM first_table a
JOIN second_table b
ON a.key = b.key

won't automatically prepend the a_ and b_ to each outputted variable, as described in this question: How to remove/avoid prepended tablename in bigquery?  But I want to know if that behavior can be modified.

A: The only option is to "separate" the names by using a dot, i.e. returning a struct with the columns from each side:
SELECT a, b
FROM first_table a
JOIN second_table b
ON a.key = b.key;

If you only want certain columns from each table, you can use subselects:
SELECT a, b
FROM (SELECT x, y, key FROM first_table) a
JOIN (SELECT foo, bar, key FROM second_table) b
ON a.key = b.key;

A: The question is a little generic - so my answer have chance to not to address PO's specific practical needs, but I thought it would be interesting to consider below approach in some cases
Idea is to have table (template table - it can be just empty) with needed columns names and than use it as first table in union all with your real query
Something like this:
#standardSQL
SELECT * FROM template WHERE NULL UNION ALL
SELECT *
FROM first_table AS a
JOIN second_table AS b
ON a.key = b.key

You can try/test this approach with below dummy tables
#standardSQL
WITH first_table AS (
  SELECT 777 AS key, 1 AS x, 2 AS y, 3 AS z
),
second_table  AS (
  SELECT 777 AS key, 4 AS x, 5 AS y, 6 AS z
),
template AS (
  SELECT NULL AS a_key, NULL AS a_x, NULL AS a_y, NULL AS a_z, NULL AS b_key, NULL AS b_x, NULL AS b_y, NULL AS b_z
)
SELECT * FROM template WHERE NULL UNION ALL
SELECT *
FROM first_table AS a
JOIN second_table AS b
ON a.key = b.key

with result as below
a_key   a_x a_y a_z b_key   b_x b_y b_z
777     1   2   3   777     4   5   6


text:
Q: On select row of WKInterfaceTable transfer data to Iphone I'm making watch app for iOS application. I get data from parent application in watch main InterfaceController and pass it to other InterfaceController for creating table. Here code of configuring table:
- (void)configureTableWithData:(NSArray*)dataObjects {

    [self.table setNumberOfRows:[dataObjects count] withRowType:@"rowType"];
    for (NSInteger i = 0; i < self.table.numberOfRows; i++) {

        RowType* row = [self.table rowControllerAtIndex:i];
        NSObject* object = [dataObjects objectAtIndex:i];

        [row.titleName setText:[object valueForKey:@"CharCode"]];
        [row.bottomValue setText:[object valueForKey:@"Value"]];
    }
}

When I select row, I want to transfer data back to first page. It's need for changing some label on first page. I'm doing it with transfer data to parent app and return it back to main InterfaceController
- (void)table:(WKInterfaceTable *)table didSelectRowAtIndex:(NSInteger)rowIndex {

     //Here must be dictionary, where I put row

     [WKInterfaceController openParentApplication:data reply:^(NSDictionary *replyInfo, NSError *error) {
          NSLog(@"data transfer");
     }];

     [self dismissController];
}

How can I get data of row? (row.titleName, row.value) May be it's stupid question, I am still just a beginner, but I can get it. I tried to print on console row.titleName and row.bottomValue and of course I've get nothing. (sorry for my english, not my mother tongue) What did I miss?

A: I have same issue with watch kit in tableview. For now we only set the text in cell label not get back so you have to do like this
- (void)table:(WKInterfaceTable *)table didSelectRowAtIndex:(NSInteger)rowIndex {

     //Here must be dictionary, where I put row
     NSDictionary* object = [dataObjects objectAtIndex:rowIndex];
     NSLog("used object as you want");

     [WKInterfaceController openParentApplication:object reply:^(NSDictionary *replyInfo, NSError *error) {
          NSLog(@"data transfer");
     }];

     [self dismissController];
}


text:
Q: Loading multiple gltf files in Three.js that should become hyperlinks js knowing people,
Below you can see my very first code of JavaScript. I would like to build a website with four different rotating gltf models. Each of them should be a hyperlink. So far I managed somehow to load two of them and let them rotate in the live server. But I'm stuck with this error 'Uncaught (in promise) TypeError: duck is undefined'.
How can I solve this problem? And how can I create the links?
I'm very thankful for your help.
// variables for setup
let container;
let camera;
let renderer;
let scene;
let box;
let duck;
let controls;

function init(){
    container = document.querySelector('.scene');

    //create scene
    scene = new THREE.Scene();

    const fov = 10;
    const aspect = container.clientWidth / container.clientHeight;
    const near = 0.1;
    const far = 900;

    // camera setup
    camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
    camera.position.set(0, 30, 1);

    const ambient = new THREE.AmbientLight(0x404040, 3);
    scene.add(ambient);

    const light = new THREE.DirectionalLight(0xffffff, 0.5);
    light.position.set(10,10,30);
    scene.add(light);

    //renderer
    renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
    renderer.setSize(container.clientWidth, container.clientHeight);
    renderer.setPixelRatio(window.devicePixelRatio);

    container.appendChild(renderer.domElement);

    controls = new THREE.OrbitControls (camera, renderer.domElement);

    //load model
    let loader = new THREE.GLTFLoader();

    loader.load('./3d/duck.gltf', function(gltf){
        scene.add(gltf.scene);
        duck = gltf.scene.children[0];
        duck.position.set(0,0,0);
        animate();
    })

    loader.load('./3d/cube.gltf', function(gltf){
        scene.add(gltf.scene);
        box = gltf.scene.children[0];
        box.position.set(-2,0,0);
        animate();
    })

}

function animate(){
    controls.update();
    duck.rotation.x += 0.01
    box.rotation.y += 0.01
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
}

init();

function onWindowResize () {
    camera.aspect = container.clientWidth / container.clientHeight;
    camera.updateProjectionMatrix();

    renderer.setSize(container.clientWidth, container.clientHeight);
}

    window.addEventListener('resize', onWindowResize);

A: The error occurs at duck.rotation.x += 0.01. Since loader.load function is asynchronous, the line duck = gltf.scene.children[0]; is not called before the first execution of animate(). Consequently, duck variable is undefined. You could avoid it with
if(duck) {
  duck.rotation.x += 0.01
}

Regarding hyperlink:
There is no concept of links in the three.js scene.
Anchor tags are only available in the DOM and it's not a standard element available in WebGL.
You will need to write some code to handle mouse events, click and open the corresponding URL.
The process goes as below:

*

*Listen to mouse move events and change cursor if the element being hovered on is clickable

*Listen to mouse click and navigate to the link corresponding to the clicked element

*Both of these require projecting a ray from the mouse pointer and checking intersections with the mesh

The three.js documentation is quite clear about the raycaster and intersections with mesh
https://threejs.org/docs/#api/en/core/Raycaster
Demo:
https://codepen.io/cdeep/pen/JjyjEdV