text:
Q: Источник интересной информации о PHP Хотелось бы читать RSS какие-нибудь о PHP. Качественный материал, хороших блоггеров, незнаю что еще, главное чтобы влиться в мир PHP на всю катушку.
Кто что читает ?
Спасибо.
A: Читайте доки - они RULEZ :-)
Ну а если серьезно, то собственно PHP вторично, изучайте принципы программирования. А уже зная принципы можно писать хоть на PHP хоть на любом другом процедурном или ОО-языке. Собственно для того что-бы зная что и как вы хотите написать вам понадобится только документация доступная на php.net
Касаемо рунета по PHP есть несколько толковых форумов (phpforum.ru, phpclub.ru, раздел форума PHP на sql.ru) а вот чего-нибудь из блогоподобного можно с натяжкой назвать раздел PHP на habrahabr.ru


text:
Q: COUNT and MAX applied to LEFT JOIN Given the tables and relationships in the image below:
customer table & offices table
I would like to answer the following question:

*

*Which is the city with the largest office (most number of employees)?

To solve this answer, I tried this query:
SELECT counts.city, counts.numEmployees
FROM (
    SELECT o.city, COUNT(e.lastName) AS numEmployees
    FROM offices o
    LEFT JOIN employees e
    ON o.officeCode = e.officeCode
    GROUP BY o.city
    HAVING numEmployees = MAX(numEmployees)) AS counts;

This results in an empty set. However, this query worked:
SELECT counts.city, counts.numEmployees
FROM (
    SELECT o.city, COUNT(e.lastName) AS numEmployees
    FROM offices o
    LEFT JOIN employees e
    ON o.officeCode = e.officeCode
    GROUP BY o.city
    HAVING numEmployees = 6 ) AS counts;

I am trying to undestand why MAX() does not return the expected value and what is evaluating. Any insights would be appreciated.

A: You can't nest aggregates in the same query. Since numEmployees is a COUNT() aggregate, you can't use MAX(numEmployees) in the same query.
Do this in the outer query.
SELECT counts.city, counts.numEmployees
FROM (
    SELECT o.city, COUNT(e.lastName) AS numEmployees
    FROM offices o
    LEFT JOIN employees e
    ON o.officeCode = e.officeCode
    GROUP BY o.city) AS counts
HAVING numEmployees = MAX(numEmployees);

A: You need rows with employee count for each city/office combination, and then you also need to get the maximum of those counts, these are 2 steps but you initially tried to achieve both together and that does not work.
Using a CTE helps here (if this is available to you depending on MySQL version) because the CTE can be referenced in a subquery used within the where clause for the overall maximum.
Alternatively (again if version allows it) you can use the over() clause which will calculate the maximum on the grouped rows which is done AFTER the group by, so it is useable in a subsequent where clause.

with counts as (
    SELECT o.city, COUNT(e.lastName) AS numEmployees
    FROM offices o
    LEFT JOIN employees e
    ON o.officeCode = e.officeCode
    GROUP BY o.city)
select *
from counts

city | numEmployees
:--- | -----------:
A    |            3
B    |            2
C    |            2

with counts as (
    SELECT o.city, COUNT(e.lastName) AS numEmployees
    FROM offices o
    LEFT JOIN employees e
    ON o.officeCode = e.officeCode
    GROUP BY o.city)
select *
from counts
where numEmployees = (select max(numEmployees) from counts)

city | numEmployees
:--- | -----------:
A    |            3

select city, numEmployees, maxof
from (
    SELECT o.city, COUNT(e.lastName) AS numEmployees
    , max(COUNT(e.lastName)) over() as maxof
    FROM offices o
    LEFT JOIN employees e
    ON o.officeCode = e.officeCode
    GROUP BY o.city
    ) d

city | numEmployees | maxof
:--- | -----------: | ----:
A    |            3 |     3
B    |            2 |     3
C    |            2 |     3

select city, numEmployees
from (
    SELECT o.city, COUNT(e.lastName) AS numEmployees
    , max(COUNT(e.lastName)) over() as maxof
    FROM offices o
    LEFT JOIN employees e
    ON o.officeCode = e.officeCode
    GROUP BY o.city
    ) d
where numEmployees = maxof

city | numEmployees
:--- | -----------:
A    |            3

db<>fiddle here

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to return a closure or handle not returning a closure I am new to angular and I am working on a project in my company where I have to implement a delete function.
I have manage to implement the function where user goes ahead with the deletion. But if he changes his mind in the last minute and cancel the delete confirmation, I am getting an error.
Here is my code:
$scope.deleteButtonClick = function () {

    if ($scope.hasRemove()) {
        $scope.deleting = true;
        //Fetch the promise and add our own state management to it
        var promise = $scope.removeAction(); // this remove action calls the below 'remove' function
        if (!promise.then) {
            throw "Wizard's bound 'deleteAction' must return a closure."
        }
        promise.then(function () {
            $scope.deleting = false;
        }, function () {
            $scope.deleting = false;
        });
    }
};

Following is the remove function where I want to return a closure.
$scope.remove = function () {

    if (confirm("Confirm Delete?")){

        var data = {};

        data.id = EventService.event.id;

        // delete
        return $http.post('/admin/deleteAjax/', data).then(
              function (response) {

                 if (response.data.status == 'success') {
                     RegistryService.getItem("successModal").show();

                     setTimeout(()=>{
                           location.replace("/admin/index")
                     }, 2000);
                  }
                  else if (response.data.status == 'error'){
                       RegistryService.getItem("errorModal").show();
                  }
               }
          );
        }
        else {
           // This is where I need to return a closure
           // when user presses 'cancel' button how can I return a closure or skip the error?
        }
    };

Following is the error I am getting when I return false in the else section.

Wizard's bound 'deleteAction' must return a closure. undefined

Does anyone have an idea how to fix this issue?

A: The problem is that $scope.remove() needs to return a Promise, and the else clause in the confirm() block is not returning a Promise.
To do that, you can use the AngularJS $q service to create a Promise and return it.
So your else block would look like this:
} else {
  // This is where I need to return a closure
  // when user presses 'cancel' button how can I return a closure or skip the error?
  const deferred = $q.defer(); // <------------ use $q service to create a deferred
  deferred.resolve({ cancelled: true }); // <-- resolve it to whatever value you want
  return deferred.promise; // <---------------- and return its promise
}

Here's a fiddle showing this approach.


text:
Q: Auto play(áudio) com Javascript Existe algum método de dar auto play com áudio, já tentei varias formas mas nenhuma deu certo. Geralmente funciona em um pc e no pc de teste não funciona.
Já fiz o teste com iframe, video, audio, direto no Js e com Api do Youtube.
<audio id="musica" autoplay="true">
    <source src="/home/musicas/teste.ogg" type="audio/ogg">
    <source src="/home/musicas/teste.mp3" type="audio/mp3">
</audio>

A: Como não tenho pontos suficientes para comentar, coloco aqui:
O Chrome bloqueia o autoplay com som quando o usuário não realizou nenhuma interação com a página por medidas de segurança. Como especificado aqui, em New behaviors.

As you may have noticed, web browsers are moving towards stricter autoplay policies in order to improve the user experience, minimize incentives to install ad blockers, and reduce data consumption on expensive and/or constrained networks. These changes are intended to give greater control of playback to users and to benefit publishers with legitimate use cases.

A: Adicione a chamada via JavaScript no corpo do seu html, desta forma assim que a página for renderizada o JS vai ser executado:
function play() {
  document.getElementById("musica").play();
}

play();


text:
Q: Foreign keys vs secondary keys I used to think that foreign key and secondary key are the same thing.
After Googling the result are even more confusing, some consider them to be the same, others said that a secondary key is an index that doesn't have to be unique, and allows faster access to data than with the primary key.
Can someone explain the difference?
Or is it indeed a case of mixed terminology?
Does it maybe differ per database type?

A: A foreign key is a key that references an index on some other table. For example, if you have a table of customers, one of the columns on that table may be a country column which would just contain an ID number, which would match the ID of that country in a separate Country table. That country column in the customer table would be a foreign key.
A secondary key on the other hand is just a different column in the table that you have used to create an index (which is used to speed up queries). Foreign keys have nothing to do with improving query speeds.

A: "Secondary key" is not a term I'm familiar with. It doesn't appear in the index of Database Design for Mere Mortals and I don't remember it in Pro SQL Server 2012 Relational Database Design and Implementation (my two "goto" books for database design). It also doesn't appear in the index for SQL for Smarties. It sounds like its not an actual term at all.
I've always used the term "candidate key".
A candidate key is a way to uniquely identify an entity. You identify all the candidate keys during the design phase of a database system. During the implementation phase, you will decide on a primary key: either one of the candidate keys or an artificial key. The primary key will probably be implemented with a primary key constraint; the candidate keys will probably be implemented with unique constraints.
A foreign key is an instance of one entity's candidate key in another entity, representing a relationship between the two entities. It will probably be implemented with a foreign key constraints.

A: The definition in wiki/Foreign_key states that:

In the context of relational databases, a foreign key is a field (or
  collection of fields) in one table that uniquely identifies a row of
  another table. In other words, a foreign key is a column or a
  combination of columns that is used to establish and enforce a link
  between two tables.
The table containing the foreign key is called the referencing or
  child table, and the table containing the candidate key is called the
  referenced or parent table.

Take the example of the case:
A customer may place 0,1 or more orders.
From the point of the business, each customer is identified by a unique id (Primary Key) and instead of repeating the customer information with each order, we place a reference, or a pointer to that unique customer id (Customer's Primary Key) in the order table. By looking at any order, we can tell who placed it using the unique customer id.
The relationship established between the parent (Customer table) and the child table (Order table) is established when you set the value of the FK in the Order table after the Customer row has been inserted. Also, deleting a child row may affect the parent depending on your Referential Integrity stings (Cascading Rules) established when the FK was created. FKs help establish integrity in a relational database system.
As for the "Secondary Key", the term refers to a structure of 1 or more columns that together help retrieve 1 or more rows of the same table. The word 'key' is somewhat misleading to some. The Secondary Key does not have to be unique (unlike the PK). It is not the Primary Key of the table. It is used to locate rows in the same table it is defined within (unlike the FK). Its enforcement is only through an index (either unique or not) and it is implementation is optional. A table could have 0,1 or more Secondary Key(s). For example, in  an Employee table, you may use an auto generated column as a  primary key. Alternatively, you may decide to use the Employee Number or SSN to retrieve employee(s) information.
Sometimes people mix the term "Secondary Key" with the term "Candidate Key" or "Alternate Key" (usually appears in Normalization context) but they are all different.


text:
Q: events.js:183 throw Unhandled 'error' event The system cannot find the path specified.

events.js:183
        throw er; // Unhandled 'error' event
        ^
Error: spawn node_modules\webpack\bin\webpack.js ENOENT
      at notFoundError (D:\xampp\htdocs\learnlarvel\node_modules\cross-spawn\lib\enoent.js:6:26)
      at verifyENOENT (D:\xampp\htdocs\learnlarvel\node_modules\cross-spawn\lib\enoent.js:40:16)
      at ChildProcess.cp.emit (D:\xampp\htdocs\learnlarvel\node_modules\cross-spawn\lib\enoent.js:27:25)
      at Process.ChildProcess._handle.onexit (internal/child_process.js:198:12)
  npm ERR! code ELIFECYCLE
  npm ERR! errno 1
  npm ERR! @ development: cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js
  npm ERR! Exit status 1
  npm ERR!
  npm ERR! Failed at the @ development script.
  npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
  npm ERR!     C:\Users\iSkylarTechnology\AppData\Roaming\npm-cache_logs\2019-09-14T11_40_34_967Z-debug.log
  npm ERR! code ELIFECYCLE
  npm ERR! errno 1
  npm ERR! @ dev: npm run development
  npm ERR! Exit status 1
  npm ERR!
  npm ERR! Failed at the @ dev script.
  npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
  npm ERR!     C:\Users\iSkylarTechnology\AppData\Roaming\npm-cache_logs\2019-09-14T11_40_35_155Z-debug.log

A: Delete your node_modules folder and delete package-lock.json. Run npm cache clear --force and then npm install. Then try npm run dev or npm run watch.


text:
Q: why I have to use `drop` manually on unused rust variable to pass lifetime checker? Why doesn't `query` dropped before `url.as_str()` Why I have to run drop(query) manually to make the code compile? In my opinion, the drop(query) should be called implicitly in that place and has a very short lifetime.
The demo code:
// Cargo.toml
[package]
name = "lifetime1"
version = "0.1.0"
edition = "2021"

[dependencies]
url = "*"

// src/main.rs
use url::Url;

struct MockUrl {
    name: String,
}

struct MockQuery<'a> {
    test: &'a mut MockUrl,
}

impl MockUrl {
    fn take_mut(&mut self) -> MockQuery<'_> {
        MockQuery { test: self }
    }

    fn get_name_immut(&self) -> &String {
        &self.name
    }
}

fn main() {
    // case A: why drop is needed?
    let mut url = format!("{}/v2/private/position/list", "https://www.baidu.com").parse::<Url>().unwrap();
    let mut query = url.query_pairs_mut();
    drop(query); // position A
    println!("{}", url.as_str());

    // case B: works as expect.
    let mut t1 = MockUrl { name: "name".to_string() };
    let mut t2 = t1.take_mut();
    println!("{}", t1.get_name_immut());
}

A: Without the drop() call, this message from the compiler hints us at the problem:
mutable borrow might be used here, when `query` is dropped and runs the
destructor for type `Serializer<'_, UrlQuery<'_>>`

The answer is that the type returned by url.query_pairs_mut() implements Drop1 to customize what happens when the value is destroyed, and values aren't automatically dropped until the end of the block containing the declaration of the variable in which that value lives.  Since Drop::drop() takes a (mutable) reference to the value being dropped, this necessarily extends the length of the borrow on url until the end of main().
Since your type doesn't implement Drop, the line that declares and initializes t2 is also the last time the value in t2 is used in the function, so t2's borrow of t1 can end there.  If you implement Drop on your MockQuery type then the borrow of t1 by t2 can't end early and so you will see the same error from the compiler as you saw with query:
impl<'a> Drop for MockQuery<'a> {
    fn drop(&mut self) { }
}

(Playground)
Dropping query explicitly destroys the value contained in it, which necessarily causes the custom Drop::drop() implementation to be invoked at that point, and therefore ends query's borrow of url early.

1 It doesn't implement Drop directly, but the struct contains a member of a type that does implement Drop and this struct member holds the borrow on url.


text:
Q: SmartGWT DataSource string XML I am currently using a SmartGWT grid, that uses a DataSource object, which receives an xml file.  All is well with this approach, but I want to know if I can just send a string with an xml structure.  Something like the below:
String xml = "<listgrid><data><campo1></campo1>hola<campo2>mundo</campo2></data></listgrid>";
setData(xml);

This is pseudo-code, but it should give an idea to the reader.
I've searched and found no example that fulfills my requirements.

A: There is a better way. What you want to do is populate the dataSource dynamically.
Here's an example:
public void onModuleLoad() {
    DataSourceTextField continentField = new DataSourceTextField("continent");
    continentField.setPrimaryKey(true);

    DataSource dataSource = new DataSource();
    dataSource.setClientOnly(true);
    dataSource.setFields(continentField);
    for (CountryRecord record : new CountryData().getNewRecords()) {
        dataSource.addData(record);
    }

    ListGrid myGrid = new ListGrid();
    myGrid.setWidth(200);
    myGrid.setHeight(100);
    myGrid.setDataSource(dataSource);
    myGrid.fetchData();
    myGrid.draw();
}

class CountryData {

    public CountryRecord[] getNewRecords() {
        return new CountryRecord[] {
                new CountryRecord("North America"),
                new CountryRecord("Asia") };
    }
}

class CountryRecord extends ListGridRecord {
    public CountryRecord(String continent) {
        setContinent(continent);
    }

    public void setContinent(String continent) {
        setAttribute("continent", continent);
    }

    public String getContinent() {
        return getAttributeAsString("continent");
    }
}


text:
Q: C# Remove all Items from List if a property is in a List I have a List<T> where T has a string property let's call it Value
Then I have a List<string> that contains some keywords.
How can I remove all items from the List<T> where the property Value matches one keywords from the List<string>?

A: Use the List<T>.RemoveAll Method (Predicate<T>), with a predicate that checks if the keywords list contains the Value.
Example console application:
public static class Program
{
    public class A
    {
        public string Value { get; set; }
    }

    public static void Main(string[] args)
    {
        var keywords = new List<string>() {"A", "B", "C", "D"};

        var aas = new List<A>()
        {
            new A() {Value = "A"},
            new A() {Value = "AA"},
            new A() {Value = "B"},
            new A() {Value = "AB"}
        };

        Console.WriteLine("Before remove:");
        aas.ForEach(a => Console.WriteLine("  A.Value = {0}", a.Value));

        aas.RemoveAll(a => keywords.Contains(a.Value));

        Console.WriteLine("After remove:");
        aas.ForEach(a => Console.WriteLine("  A.Value = {0}", a.Value));
    }
}

Output console:
Before remove:
  A.Value = A
  A.Value = AA
  A.Value = B
  A.Value = AB
After remove:
  A.Value = AA
  A.Value = AB

A: public class test
{
    public string waarde { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        var teBeRemoved = new List<string> {"een", "twee"};

        var totalList = new List<test> { new test { waarde = "een" }, new test { waarde = "drie" } };

        var filteredList  = totalList.Where(i => !teBeRemoved.Contains(i.waarde));

    }
}


text:
Q: Selenium error : element is not attached to the page document Am extracting data with selenium and because the algorithm has high time complexity am also using multiprocessing.
I have the function that extract data called extract_tag_data():
def extract_tag_data(tag,dataset_dictionary,lst):
    driver= webdriver.Chrome(driver_location)
    driver.get("link")
    for _ in range (1):
        articles=driver.find_elements(By.XPATH, "//table[@class='table table-hover']/tbody/tr/td[2]/div[@class='media']/div[@class='media-body']/strong/a")
        for article in articles[:1]:
            article.click()
            dataset_dictionary['tag']=tag
            dataset_dictionary['article_title']= unidecode.unidecode(driver.find_element(By.XPATH,'//h1[@class="title"]').text)
            dataset_dictionary['abstract']= unidecode.unidecode(driver.find_element(By.XPATH,'//div[@class="abstract"]/div[1]').text)
            dataset_dictionary['authors']=(",".join([element.text for element in (driver.find_elements(By.XPATH,'//div[@class="authors"]/span'))]))
            dataset_dictionary['structs']=(",".join([element.text for element in (driver.find_elements(By.XPATH,'//div[@class="authors"]/div[@class="structs"]/div[@class="struct"]/a'))]))
            lst.append(dataset_dictionary)
            driver.back()
        driver.find_element(By.XPATH,'//table[@class="table table-hover"]/tfoot/tr[1]/th[2]/ul/li/a/span[@class="glyphicon glyphicon-step-forward"]').click()
    driver.quit()
    return(lst)

if __name__ == '__main__':
    manager = Manager()
    dataset_dictionary=manager.dict()
    dataset_dictionary = {
    'article_title':[],
    'authors':[],
    'abstract':[],
    'structs':[],
    'tag':[]
    }
    lst=manager.list()
    tags=['neural networks','evolutionary computation']
    pool= Pool(2)
    pool.starmap(extract_tag_data, zip(tags,repeat(dataset_dictionary),repeat(lst)))
    pool.close()
    df = pd.DataFrame.from_records(lst)
    df.to_excel(r"C:\\Users\\dell\\Desktop\\data collection\\myDataset.xlsx",  sheet_name='Sheet1')
    print(lst)

the idea is abt catching a list of article 'articles[]'  in the current page and then looping through it to extract data abt each article. I tested with only the first element in the list and its working.
        articles=driver.find_elements(By.XPATH, "//table[@class='table table-hover']/tbody/tr/td[2]/div[@class='media']/div[@class='media-body']/strong/a")
        for article in articles[:1]:
            article.click()

But when I try to loop through all the list elements It raises the following error:
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
  (Session info: chrome=105.0.5195.102)
Stacktrace:
Backtrace:
    Ordinal0 [0x00BA78B3+2193587]
    Ordinal0 [0x00B40681+1771137]
    Ordinal0 [0x00A541A8+803240]
    Ordinal0 [0x00A56BB4+814004]
    Ordinal0 [0x00A56A72+813682]
    Ordinal0 [0x00A56D00+814336]
    Ordinal0 [0x00A83F19+999193]
    Ordinal0 [0x00A79146+954694]
    Ordinal0 [0x00A9D7AC+1103788]
    Ordinal0 [0x00A78C04+953348]
    Ordinal0 [0x00A9D9C4+1104324]
    Ordinal0 [0x00AADAE2+1170146]
    Ordinal0 [0x00A9D5C6+1103302]
    Ordinal0 [0x00A777E0+948192]
    Ordinal0 [0x00A786E6+952038]
    GetHandleVerifier [0x00E50CB2+2738370]
    GetHandleVerifier [0x00E421B8+2678216]
    GetHandleVerifier [0x00C317AA+512954]
    GetHandleVerifier [0x00C30856+509030]
    Ordinal0 [0x00B4743B+1799227]
    Ordinal0 [0x00B4BB68+1817448]
    Ordinal0 [0x00B4BC55+1817685]
    Ordinal0 [0x00B55230+1856048]
    BaseThreadInitThunk [0x76CBFA29+25]
    RtlGetAppContainerNamedObjectPath [0x779E7A9E+286]
    RtlGetAppContainerNamedObjectPath [0x779E7A6E+238]

I know its something with the DOM but am going back to the previous page after every iteration.

A: driver.back()
is the main issue after each page switch regrab the elements.
articles=len(driver.find_elements(By.XPATH, "//table[@class='table table-hover']/tbody/tr/td[2]/div[@class='media']/div[@class='media-body']/strong/a"))
for i in range(articles):
    driver.find_elements(By.XPATH, "//table[@class='table table-hover']/tbody/tr/td[2]/div[@class='media']/div[@class='media-body']/strong/a")[i].click()
    dataset_dictionary['tag']=tag
    dataset_dictionary['article_title']= unidecode.unidecode(driver.find_element(By.XPATH,'//h1[@class="title"]').text)
    dataset_dictionary['abstract']= unidecode.unidecode(driver.find_element(By.XPATH,'//div[@class="abstract"]/div[1]').text)
    dataset_dictionary['authors']=(",".join([element.text for element in (driver.find_elements(By.XPATH,'//div[@class="authors"]/span'))]))
    dataset_dictionary['structs']=(",".join([element.text for element in (driver.find_elements(By.XPATH,'//div[@class="authors"]/div[@class="structs"]/div[@class="struct"]/a'))]))
    lst.append(dataset_dictionary)
    driver.back()


text:
Q: Javascript method call inside PHP page I have a PHP page in which am hiding a div using a javascript method. This method is called on a hyperlink click. The issue is its giving Uncaught Reference error. Not sure what is the cause. I tried even to have a external JS file and define the method in that, but still not working.

A: I'll give you a hint:
make sure you have defined your DIV tag before the action script
like:

Hide on click

<input type="button" value="hide" onClick="javascript:HideIt()"/>

A: Uncaught Reference error in javascript usually means that the object or accessor isn't defined at the time of calling the method.
I've seen it when using jQuery when jQuery is included at the bottom of the html and the javascript is being triggered before it.
So
$('divid').text = "blah";

before the

Hence the $ method doesn't exist.
The solution would be to put the method call on body load.

A: Here is the general code to hide any div onClick.

        //Here to add script tag, which i have writen below

This is to be hide on click

        Click to hide!

        Click to show!

NOTE: You should write apostrophes carefully. Bcox ' and " have different impact
Here is the script tag which u have to place in head tag:


text:
Q: How to convert Timestamp to DateTime from firebase with flutter I have Timestamp item in firebase. I get the item from dart code timestamp type.
It shows like 'Timestamp(seconds=1590903768, nanoseconds=26999000)' as it is.
I would like to show on my Application only Date like '2020-06-01' or '06-01'.
Please give me advice.

A: You can convert the Timestamp DataType to DateTime and then format the DateTime according to your requirements.
Note: you will have to install the intl package in your flutter project to make this code work.
Example
add the following method in your dart file.
String formatTimestamp(Timestamp timestamp) {
  var format = new DateFormat('y-M-d'); // <- use skeleton here
  return format.format(timestamp.toDate());
}

then get the TimeStamp from FireStore and pass it into this method
print(formatTimestamp(doc.data['timestamp']));

OutPut
year-month-day

For other available formats, use Skeleton to format.
 ICU Name                   Skeleton
 --------                   --------
 DAY                          d
 ABBR_WEEKDAY                 E
 WEEKDAY                      EEEE
 ABBR_STANDALONE_MONTH        LLL
 STANDALONE_MONTH             LLLL
 NUM_MONTH                    M
 NUM_MONTH_DAY                Md
 NUM_MONTH_WEEKDAY_DAY        MEd
 ABBR_MONTH                   MMM
 ABBR_MONTH_DAY               MMMd
 ABBR_MONTH_WEEKDAY_DAY       MMMEd
 MONTH                        MMMM
 MONTH_DAY                    MMMMd
 MONTH_WEEKDAY_DAY            MMMMEEEEd
 ABBR_QUARTER                 QQQ
 QUARTER                      QQQQ
 YEAR                         y
 YEAR_NUM_MONTH               yM
 YEAR_NUM_MONTH_DAY           yMd
 YEAR_NUM_MONTH_WEEKDAY_DAY   yMEd
 YEAR_ABBR_MONTH              yMMM
 YEAR_ABBR_MONTH_DAY          yMMMd
 YEAR_ABBR_MONTH_WEEKDAY_DAY  yMMMEd
 YEAR_MONTH                   yMMMM
 YEAR_MONTH_DAY               yMMMMd
 YEAR_MONTH_WEEKDAY_DAY       yMMMMEEEEd
 YEAR_ABBR_QUARTER            yQQQ
 YEAR_QUARTER                 yQQQQ
 HOUR24                       H
 HOUR24_MINUTE                Hm
 HOUR24_MINUTE_SECOND         Hms
 HOUR                         j
 HOUR_MINUTE                  jm
 HOUR_MINUTE_SECOND           jms
 MINUTE                       m
 MINUTE_SECOND                ms
 SECOND                       s

I hope this will be helpful!!

A: Timestamp class has a toDate function that converts it to a DateTime object. See this for more information. Any formatting you want to do in converting it to a string can be done more easily now with intl package formatters.
Example:
Timestamp stamp = Timestamp.now();
DateTime date = stamp.toDate();

A: You get back a map from firestore. Assuming you have named it "creationDate", you can convert the returned timestamp to a DateTime object using the toDate() dart function. The "simplest" way to format the datetime is to use the intl package
// Map From firestore
Map data = documentSnapshot.data();
var creationDate = data['creationDate'].toDate();

//Format using intl package
DateFormat _dateFormat = DateFormat('y-MM-d');
String formattedDate =  _dateFormat.format(dateTime);

A: If you want Hours and minutes(hh:mm) from timestamp, Simply create following method which gives you string in return.
String convertTimestampToHm(Timestamp timestamp) {
var format = DateFormat('Hm'); // convert into hours and minutes
return format.format(timestamp.toDate());

}
NOTE: - You can always use Skeleton base on requiremrnt.

A: There are  different ways to convert TimeStamp to DateTime which differs based on the scenario.
I have summarize all the possible ways, Pick the one which suits your case !!

Conversion of Firebase timestamp to DateTime:

*

*
document['timeStamp'].toDate()

*
(document["timeStamp"] as Timestamp).toDate()

*
DateTime.fromMillisecondsSinceEpoch(document['timeStamp'].millisecondsSinceEpoch);

*
Timestamp.fromMillisecondsSinceEpoch(document['timeStamp'].millisecondsSinceEpoch).toDate();

*If timeStamp is in microseconds use:
DateTime.fromMicrosecondsSinceEpoch(timestamp * 1000000);

*If timeStamp is in milliseconds use:
DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);

*Add the following function in your dart file.
 String formatTimestamp(Timestamp timestamp) {
   var format = new DateFormat('yyyy-MM-dd'); // <- use skeleton here
   return format.format(timestamp.toDate());
 }

call it as formatTimestamp(document['timestamp'])


text:
Q: Regression function of "non-regressible" data I have some background in probability, and now trying to understand statistics, which sometimes leads to the questions of the following kind. Let $X$ and $Y$ be two random variables that represent the data that we have in hand. Let's say we are interested in case when $X$ and $Y$ are not independent, and let $\mathbb P$ be their joint distribution. If we knew $\Bbb P$ we could deduce the marginal distribution of $X$, say $\mu(\mathrm dx)$ and a conditional distribution of $Y$ given $X$, say $m(x,\mathrm dy)$. In practice of course we do not know $\Bbb P$, rather we only have several samples from that distribution.
Let's consider the case when $Y$ is real-valued. As far as I understand, the regressiong function
$$
  r(x):=\mathbb E[Y|X = x] = \int y \, m(x,\mathrm dy)
$$
is what we are often trying to find. In case $\Bbb P$ is given by $Y = f(X) + \varepsilon$ and $\varepsilon$ is some noise, of course finding $r \approx f$ would give us quite a lot information. However, if $Y$ is distributed (given $X$) not as a nice curve $\pm$ some noise, but in a more complex way, then I would not expect any regression to provide us relevant model, not matter whether it is simple linear regression or some more complicated non-linear method. For example, if $Y = \delta\cdot f_1(X) + (1-\delta)f_2(X)$ where $\delta$ follows symmetric Bernoulli distribution, then $r(x) = \frac12(f_1(x) + f_2(x))$ but it is gonna be quite a bad of an estimate of $Y$.
I thus wonder, whether instead of a regression function we can focus on estimating just conditional distribution of $Y$ given $X$, and if we can, why would not we do this all the time? Please tell me in case the question is not clear.

A: I'm not entirely clear about what you're asking, but I think what you're after is non-parametric regression. The standard method is Nadaraya-Watson kernel regression, which is derived from the fact that $E[Y|X=x]=\int y f(y|x)dy = \int y \frac{f(y,x)}{f(x)}dy$. The numerator is a joint density, and the denominator is a density. These can be estimated using kernel density methods (basically smoothed histograms), yielding the estimator $$\hat{m}_h(x) = \frac{\sum K_h(x-x_i)y_i}{\sum K_h(x-x_i)} $$, where $K_h$ is a kernel with bandwidth $h$ (basically any probability density function can be used as a kernel).
Anyway, this estimator is derived with no assumptions about the functional form of the relationship between $Y$ and $X$. So why don't we always use kernel regression?
First, there's always a trade-off between assumptions and precision - the more structure I put on a problem, the more precise estimates I will be able to get with a given sample (but the risk of bias increases). Kernel regression has a slower rate of convergence than OLS, for example.
Second, kernel regression quickly gets computationally expensive, especially as the number of independent variables increases.
Third, kernel regression is harder to interpret - there will be a different marginal effect of each $X$ depending on the values of all the other $X$ variables. With a linear model, you get constant marginal effects.

A: Assessing the quality of predictors can be done only if we specify a criterion to use for the assessment (or a collection of criteria). So general statements like "...it is gonna be quite a bad of an estimate of $Y$", that are included in the OP's post are not really meaningful.
For example, by construction, the conditional expectation is such that
$$r(X)=\mathbb E[Y\mid X ] \Rightarrow Y = r(X) + u, \;\; E(u\mid X) =0$$
Not a bad property if you ask me (now, I am making statements that are not really meaningful, by silently assuming/implying a ton of things).
The conditional expectation is the best predictor in $L^2$ norm, and this has nothing to do with the specific functional form it may take.
To quote from Williams' Probability with Martingales (1991, ch. 9.4, p. 85)

(...) No surprise then that conditional expectation (and the martingale
  theory which develops it) is crucial in filtering and control- of
  space-ships, of  industrial processes, or whatever.

ADDENDUM
Responding to the OP's comment-clarification below, to the question "why estimate conditional expectation and not conditional distribution function", the answer is easy: for a given set of available data, the more unknowns we want to estimate and combine, the worse our estimator's properties will be. Estimating a distribution is a much more delicate and uncertain endeavor (as I think I have written also elsewhere), than estimating an expected value.

A: There are two issues you should pay attention:

*

*We don't need the distribution of any kind for $Y$ - we only want to be able to predict $y$ values using given $x$. Many people how use linear regression don't derive it using statistics, rather they minimize $l_2$ norm of residuals - and achieve the same result.

*In some cases we can't evaluate marginal distribution, while we are still able to calculate mean value of this distribution. See, for example, paper on heteroskedastic Gaussian processes regression http://www.icml-2011.org/papers/456_icmlpaper.pdf, at the end of the section 4: we can evaluate mean value of predictive distribution, but we can't calculate density for predictive distribution (as it is analytically intractable).


text:
Q: How to display or console.log messages in react from express.js? I have a working login/register function with jwt and all, but I don't know how could I log a message in react that comes from back-end.
I've tried using  if (emailExists) return res.status(400).send(console.log("user already exists"));, but that doen't work. And if I use if (!validPassword) return res.status(400).send('Invalid password');, then it also doens't dislay anything. I use axios and cors to connect react with node.js. And whenever I fill out a form in front-end, it actually stores the user in mongodb database.
Here is the code for the signup component:
import React, { useState } from "react";
import {
  Container,
  FormWrap,
  Icon,
  FormContent,
  Form,
  FormH1,
  FormLabel,
  FormInput,
  FormButton,
  Text,
} from "./SignupElements";
import axios from 'axios';

const Signup = () => {

  const [registerUsername, setRegiserUsername] = useState("");
  const [registerPassword, setRegiserPassword] = useState("");
  const [registerEmail, setRegiserEmail] = useState("");

  function register() {
    axios({
      method: "post",
      data: {
        username: registerUsername,
        password: registerPassword,
        email: registerEmail
      },
      withCredentials: true,
      url: "http://localhost:4000/user/signup"
    }).then((res) => {
      if (res.data){
        alert('user saved!');
      }
    }).catch (err => {
      console.log(err);
    })
  }

  return (
    <Container>
      <FormWrap>
        <Icon to="/">Amp Beats</Icon>
        <FormContent>
          <Form>
            <FormH1>Create an account</FormH1>
            <FormLabel htmlFor="for">Email</FormLabel>
            <FormInput type="email" onChange={e => setRegiserEmail(e.target.value)}></FormInput>
            <FormLabel htmlFor="for">Username</FormLabel>
            <FormInput type="username" onChange={e => setRegiserUsername(e.target.value)}></FormInput>
            <FormLabel htmlFor="for">Password</FormLabel>
            <FormInput type="password" onChange={e => setRegiserPassword(e.target.value)}></FormInput>
            <FormButton type="button" onClick={register}>Create Accout</FormButton>
            <Text>WARNING: Do not enter your real password or email, because if it gets leaked, I will probably be too lazy to fix it.</Text>
          </Form>
        </FormContent>
      </FormWrap>
    </Container>
  );
};

export default Signup;

The alert actually works, but whenever I try to log the error and I check the console, I see this: Error:
Request failed with status code 400
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:62)

And if I check it with postman, all the messages are getting displayed.


text:
Q: CMD Fileless equivalent of < redirection I have a batch that wraps AnyConnect Mobility Client CLI (vpncli.exe) and asks username and password to later handle them to vpncli.
Simplified code:
set /p user_id=Username:
set /p pwd=Password:
echo %user_id%> c:\temp\configvpn.txt
echo %pwd%>> c:\temp\configvpn.txt

set install_dir="C:\Program Files (x86)\Cisco\Cisco AnyConnect Secure Mobility Client"

%install_dir%\vpncli.exe connect myvpn.mydomain.TLD -s < c:\temp\configvpn.txt

net use h: \\fileserver\sharename /user:domain\%user_id% %pwd%

The last line it's why we do it this way: to not prompt user password twice (first for connecting VPN and second to map network drive)
For security reasons I'm improving the script to not write password to disk. I need a fileless equivalent of this "< c:\temp\configvpn.txt"
I tried :
(
    @echo %user_id%
    @echo %pwd%
) | %install_dir%\vpncli.exe connect myvpn.mydomain.TLD -s

Not success so far. The output is this loop:
  >> Please enter your username and password.
Group: VPN-TESTGROUP

Username: [myUsername] Password:
  >> Login failed.
Group: VPN-TESTGROUP

Username: [myUsername] Password:
  >> Login failed.

(repeats indefinitely)
Is there a way to do this?

A: It's probably a problem of the piped block, as there are spaces added at the end of each command.
This code avoids the spaces and should solve your problem
(SET LF=^
%=empty=%
)

(
    echo %user_id%%%LF%%rem.
    echo %pwd%%%LF%%rem.
) |  %install_dir%\vpncli.exe connect myvpn.mydomain.TLD -s

But you should test it without any special characters in you user_id or password!

A: As you already find out, the problems is trailing spaces inside the pipe, And as you can see in jeb's answer getting ride of the trailing spaces requires special handling.
One aspect of pipes that leads to confusion is that the piped commands are not executed in batch file context with batch syntax rules, but they are executed in command line context with command line syntax rules in a child cmd instance.
One needs to thoroughly understand the mechanics of the CMD/Batch pipes to be able to construct and maintain a working solution this way, and it is not a straightforward task for slightly more complex piped blocks.
Here is an alternate way which enables piping of any complex blocks of commands with the same level of flexibility as you have in normal batch codes.
@echo off
if "%~1"=="/LPipe" goto :/LPipe
if "%~1"=="/RPipe" goto :/RPipe

set /p user_id=Username:
set /p pwd=Password:

"%~f0" /LPipe | "%~f0" /RPipe
exit /b

:/LPipe
REM This will be executed inside a pipe but in batch context

REM Enable delayed expansion to be able to send any special characters
setlocal EnableDelayedExpansion

REM It's easy to take care of trailing spaces, no special hacks needed.
echo !user_id!
echo !pwd!
goto :EOF

:/RPipe
REM This will be executed inside a pipe but in batch context

%install_dir%\vpncli.exe connect myvpn.mydomain.TLD -s
goto :EOF


text:
Q: load components dynamically based on choice in the current step in Vue-Form-Wizard I'm trying to load components dynamically based on choice in the current step. For example, the user has 3 choices in the first step and if he chooses choice one, component One will be loaded in 2end step and so on.
The question is here is it possible to do something like this? if it is how to do it?

A: You just need to check the value of the radio button once you click the choices using v-model in the next step. It uses v-if so the components that are not selected will not render.
Check This. I haven't tested it but it looks like this.
<template>
  <div>
     <form-wizard @on-complete="onComplete">
        <template slot="step" slot-scope="props">
           <wizard-step :tab="props.tab"
                       :transition="props.transition"
                       :key="props.tab.title"
                       :index="props.index">
           </wizard-step>
          </template>
           <tab-content  title="Step1" :before-change="checkStep1">
              One <input type="radio" id="one" v-model="selectedOption" :value="1" >
              Two <input type="radio" id="two" v-model="selectedOption" :value="2" >
              Three <input type="radio" id="three" v-model="selectedOption" :value="3" >
           </tab-content>
           <tab-content  title="Step2" >
              <component1 v-if="selectedOption === 1" />
              <component2 v-if="selectedOption === 2" />
              <component3 v-if="selectedOption === 3" />
           </tab-content>
     </form-wizard>
  </div>
</template>
<script>
import Vue from 'vue'
import VueFormWizard from 'vue-form-wizard'
import component1 from '@/compononents/component1'
import component2 from '@/compononents/component2'
import component3 from '@/compononents/component3'

Vue.use(VueFormWizard)

export default {
  name: 'MyComponent',
  components: {
    component1,
    component2,
    component3
  },
  data () {
    return {
      selectedOption: 1
    }
  },
  methods: {
    checkStep1 () {
       //Add validation of step 1 here and return true or false
    }
  }
}

</script>

A: You can dynamically load components like this:
(assuming you use webpack)
<template>
            <!-- Just a combo to pick the string 'one' or 'two' into currentComponent variable -->
            <v-select v-model="currentComponent" :items="components" solo/>

            <!-- 1 - This component is a dynamic one: -->
            <component :is="currentComponent"/>
</template>

<script>

    // 2 - Importing dynamically
    const one = () => import(/* webpackChunkName: "one" */ "../vue/One.vue")
    const two = () => import(/* webpackChunkName: "two" */ '../vue/Two.vue')

    export default {
        name: "toto",
        components: {one, two},
        data: () => ({
            components: ['one', 'two'],
            currentComponent: null
        })
    }
</script>

1 - Using 'component' in template will dynamically display the component named by the value of 'currentComponent' variable. You can pass props etc.
2 - Using promises when importing components will load component from server only when used. Even if you have 20 big components to conditionnaly display, only used components at runtime will be loaded from server.
3 - Note you can also use one and two components with v-if conditions, it works too.
More info about dynamic components can be found here


text:
Q: [PANDAS]: How to Select a particular Column element corresponding to maximum of another Column element in Pandas? Suppose I am given the following dataset:
Country       Cold_drink_serving
India              54
Australia          64
Kenya              85

How do I Select the country with maximum cold_drink_serving in Pandas Python?

A: Use idxmax and loc
In [304]: df.loc[df.Cold_drink_serving.idxmax(), 'Country']
Out[304]: 'Kenya'


text:
Q: Python Regex to Extract Word From Multiline String How would I extract the serial number from the following python string:
blah:              asdf
blah:              asdf
Serial Number:     1234ABCD
blah               asdf
blah               asdf

I have tried the following, but it doesn't appear to be working:
serial_num = re.search("^Serial Number:\s*(\w*)$", serial_num, re.MULTILINE)

A: You may perhaps use the following regex ...
Serial\sNumber.*?(?=\w)(\w+)

see regex demo
python ( demo )
import re

s = """
blah:              asdf
blah:              asdf
Serial Number:     1234ABCD
blah               asdf
blah               asdf
"""
r = r"Serial\sNumber.*?(?=\w)(\w+)"
m = re.findall(r, s)
print(m)[0]


text:
Q: Почему не кластеризуются соседние метки Поэкспериментируем в песочнице: https://tech.yandex.ru/maps/jsbox/2.1/clusterer_create
Добавим в общий массив метку 1: [47.23500824,39.72497559], метку 2: [47.5500824,39.72497559] и 3: [47.22273254,39.72646713]
(эти точки располагаются в Ростове).
Метки 1 и 2 кластеризуются как положено. А вот метка 3 не кластеризуется ни с кем и накладывается на метку 1 (или на кластер меток 1 и 2).

Полноценная кластеризация происходит только на zoom ~7.
Параметр gridSize плавно изменял от 64 до 1024 - влияния на метку 3 это не оказывает (на все остальные - оказывает).
Экспериментировал с параметром minClusterSize, выставлял ему значение 1. Метки превращаются в кластеры по отдельности, но в единый кластер всё равно не объединяются.

Экспериментировал так же с различными настройками, типа margin, zoomMargin и т.п. - всё бесполезно. Проверял в Chrome и Firefox.
Подобные "магические" метки существуют также в Волгограде.
Как это понимать?

A: Так устроена Grid-кластеризация. Метки кластеризуются только если они попали в один тайл. Если метки попали в соседние тайлы, то пока эти тайлы не объединятся, метки не объединятся в кластер. Как формируется тайловая сетка можно почитать тут: https://tech.yandex.ru/maps/doc/theory/concepts/coordinates-docpage/ или тут: https://habr.com/post/268621/
Если вам хочется сделать свою кластеризацию, то можно воспользоваться RemoteObjectManager https://tech.yandex.ru/maps/doc/jsapi/2.1/ref/reference/RemoteObjectManager-docpage/ . Он позволяет написать свою серверную кластеризацию. А на карте будет отображаться то, что вы вернете с сервера.


text:
Q: When installing Windows 8, I didn't have a chance to create the default account or set up any settings I tried to install Windows 8 on a computer. I had some problems, so these are the steps I ended up taking:

*

*Install Windows 8 over Windows 7

*I got confused and installed Windows 8 again xP

*When the OS was starting, it never got to the login screen - it would just sit at a blank blue screen after loading

*I used the installation disc to repair the OS

Now Windows 8 is working correctly, but I'm bothered because I never saw any screens during the installation process that let me set up the default account or prepare any other settings. When the log-in screen appears, I don't know what information to put in to log in.
So here are the questions I have:

*

*Am I supposed to see any screens asking me to configure Windows before installation is completely finished?

*Is there a default username and password I can use to log into my machine or some way to connect to an on-line account that will give me administrator access over my machine to set up a local account?

*Would it be worth re-installing Windows 8 one more time to make sure I see the configuration options?

EDIT: I just finished talking to Microsoft support about the issue. The technician told me this:

I see, this issue is normally related to Sony and Dell computers, basically the Video Driver is not available on the PC, so I recommend you to contact them, in order to get the instructions to access the PC and install the Drivers !

I have a Sony Vaio, so now I'm off to talk to Sony...

A: Can you boot into the new O/S? Or even safe mode and see what accounts are there? It may be that it's using the same NT accounts from the previous O/S and bypassing it, especially if it's checking the TPM.

A: The computer I installed Windows 8 on is a Sony Vaio VPCF122FX. According to Sony's website, the computer doesn't support Windows 8. I'm going to try installing Windows 8 one more time and see if I can't "force" it to work, and if that doesn't help, I'll go back to Windows 7.
EDIT: After reinstalling Windows 8 one more time, everything worked.


text:
Q: ASHX image handler works with chrome, not IE8 I've created code to retrieve an image from the file system using an ASHX handler.  The code displays the image correctly in Chrome, but I get a broken image in IE:
public class ImageHandler : IHttpHandler
{

    private int? QS_ImageID
    {
        get
        {
            int? temp = null;

            if (HttpContext.Current.Request.QueryString["ImageID"] != null)
                temp = HA.Utility.DataHelper.ParseDbInt(HttpContext.Current.Request.QueryString["ImageID"]);

            return temp;
        }

    }

    private bool QS_Thumbnail
    {
        get
        {
            bool thumbNail = false;
            if (HttpContext.Current.Request.QueryString["Thumbnail"] != null)
            {
                if (HttpContext.Current.Request.QueryString["Thumbnail"].Equals("1"))
                    thumbNail = true;
            }

            return thumbNail;
        }

    }

    public void ProcessRequest(HttpContext context)
    {
        if (QS_ImageID.HasValue)
        {
            int uploadID = QS_ImageID.Value;
            context.Response.ClearHeaders();
            context.Response.ClearContent();
            context.Response.Cache.SetNoStore();
            context.Response.ContentType = UploadDAL.GetMetaData(uploadID).UploadContentType;
            context.Response.AddHeader("Content-Disposition", "inline;");

            if (QS_Thumbnail)
            {

                byte[] myImage = UploadDAL.GetFileThumbNail(uploadID);
                context.Response.AddHeader("Content-Length", myImage.GetLength(0).ToString());
                context.Response.BinaryWrite(myImage);
                context.Response.End();
            }
            else
            {
                byte[] myImage = UploadDAL.GetFile(uploadID);
                context.Response.AddHeader("Content-Length", myImage.GetLength(0).ToString());
                context.Response.BinaryWrite(myImage);
                context.Response.End();
            }
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

A: The problem could be that you didn't specify a mime type for the file. Here are some common image mime types, from a function meant to return the corresponding mime type of a file:

string getContentType(String path)
{
    switch (Path.GetExtension(path))
    {
        case ".bmp": return "Image/bmp";
        case ".gif": return "Image/gif";
        case ".jpg": return "Image/jpeg";
        case ".png": return "Image/png";
        default : break;
    }
    return "";
}

If the image is physically stored on the hard drive, you can use this piece of code as it is, if not at least it can give you an idea about how to determine the mime type.
In the ProcessRequest method, you would then use

context.Response.ContentType = getContentType(imageFileName);

Of course as i said before, if you don't have a physical path for the file (for example if it's stored in the database) you should still know the image type.
Hope this helps,
Andrei

A: IE does require a Mime type.
The following I use for getting the mime types of images, or force it to be a regular file and let the system handle it.
objMIMEType = Microsoft.Win32.Registry.GetValue("HKEY_CLASSES_ROOT\\." + objAttachment.Extension, "Content Type", "application/octetstream");

        if (objMIMEType != null)
            strMIMEType = objMIMEType.ToString();
        else
        {
            strMIMEType = "application/octetstream";
            context.Response.AddHeader("Content-Disposition", "attachment; filename=" + objAttachment.FullFileName);
            context.Response.AddHeader("Content-Length", objAttachment.AttachmentData.Length.ToString());
        }


text:
Q: BigCommerce App Flow - BC to my service and vise versa I am trying to clarify I understand the flow of BigCommerce authentication. This is what I understand I need to build:
BigCommerce to my service:
1.User clicks to install my app.
2. He approves the OAuth access to his account and then BigCommerce redirects to my app's callback URL.
3. My app should take in token and store credentials and assign it to a user in my system.
4. User is redirected to an installation page hosted on my end and I instruct him to install.
How does the other way around work? If user is exposed to the ability to use my service on BigCommerce on my website? Can I invoke the BigCommerce Oauth and operate the same as the process described above?
Moreover, is the process above correct?


text:
Q: How to insert fetch array properly How could I insert a fetch array into this code. I don't get fetcharray.
$ctext = "SELECT tekst FROM members";

if (mysqli_query($conn, $ctext))
    {
        echo $ctext;
    }
    else
    {
    echo "erooroorror";
    }
    mysqli_close($conn);

A: $ctext = "SELECT tekst FROM members";

$result = mysqli_query($conn, $ctext);
if ($result) {
    while($row = mysqli_fetch_array($result)) {
        echo $row['tekst'] . '<br />';
    }
} else {
    echo "erooroorror";
}

A: you can insert it by performing batch operation. please check below code, hope it will help you to find the solution
  $QueryToMember = mysql_query("SELECT tekst FROM members");

 if ($QueryToMember) {
      while ($row = mysql_fetch_array($QueryToMember)) {
        $Array[] = "('" . $row['tekst'] . "')";
       }

       if (isset($Array) && count($Array) > 0) {

           $InsertString = implode(',', $Array);

    $Query = mysql_query("INSERT INTO test1 (tekst) VALUES " . $InsertString);
        }
    }
    else {
       echo "erooroorror";
    }


text:
Q: Equivalence of 'vlookup' in R for multiple columns? I have a 9801 by 3 reference table.
The first 2 columns of this table is defined as follows.
x1 = x2 = seq(0.01,0.99,0.01)
x12 = data.matrix(expand.grid(x1,x2))

The 3rd columns contains the outcome values.
Now I have another n by 3 matrix where the 1st and 2nd columns are selected rows of the above matrix 'x12' and the 3rd column is to be filled. I would like fill in the 3rd column of the 2nd table by looking up the same combination of the 1st and 2nd column in the 1st table and find the value in the 3rd column.
How can I do this?

A: You can do this with the merge function:
# Original data frame
x1 = x2 = seq(0.01,0.99,0.01)
x12 = expand.grid(x1,x2)

# Add a fake "outcome"
x12$outcome = rnorm(nrow(x12))

# New data frame with 100 random rows and the first two columns of x12
x12new = x12[sample(1:nrow(x12), 100), c(1,2)]

# Merge the outcome values from x12 into x12new
x12new = merge(x12new, x12, by=c("Var1","Var2"), all.x=TRUE)

by tells merge which columns must match when comparing the two data frames. all.x=TRUE tells merge to keep all rows from the first data frame, x12new in this case, even if they don't have a match in the second data frame (not an issue here, but you'll often want to make sure you don't lose any rows when merging).
One other thing to note is that, unlike vlookup in Excel, merge will increase the number of rows in the new, merged data frame if there are multiple rows that match the criteria. For example, see what happens when you merge values from df2 into df1:
df1 = data.frame(x = c(1,2,3,4), z=c(10,20,30,40))
df2 = data.frame(x = c(1,1,1,2,3), y=c("a","b","c","a","c"))
merge(df1, df2, by="x", all.x=TRUE)

  x  z    y
1 1 10    a
2 1 10    b
3 1 10    c
4 2 20    a
5 3 30    c
6 4 40 <NA>

You can also use left_join from the dplyr package (other types of joins are available as well):
library(dplyr)

left_join(df1, df2, by="x")


text:
Q: How to load a machinlearning csv file in python I have never coded using python and I have to use it for my summer research project.
I'm learning ML(machine learning) techniques and i'm stuck. As you see from the attached picture.
I can't load a csv file.(which is kdd 99 test data according to UCI KDD Archieve https://kdd.ics.uci.edu/databases/kddcup99/kddcup99.html)
Could you please help me solve this problem?
scan of the file and error


text:
Q: Constructors with functions as arguments in C++ I got some objects which variables rely on different functions. To put it in different words: There are multiple types of functions on which the variables in the object rely, but there should be multiple objects with same of these functions. For more clearance I tried to give an example (which does not work).
#include <iostream>

class A
{
  double size;

  A( double (*f)() )
  {
    size = (*f)();
  };
};

double fun1()
{
  return 42.0;
}

int main()
{
  A a = A( &fun1() );

  std::cout << a.size << std::endl;
}

This is of course a minimal example. The variable size depends on a certain function which should be passed as an argument to the class. Imagine fun1 and fun2 as different kinds of random number generators.
I think that the ideomatic way in C++ would be a class which holds the variable and the classes inherited from it are modified by that function that differs the objects (please correct me if I'm wrong with this assumption). But my question is:
Is there any possibility to implement some kind of higher-order constructor? If so, an example would be nice.
p.s.: If I used some technical terms wrong, I'd be glad to be corrected.

A: Change to:
A( double (*f)() )
{
    size = f();
};

And:
A a = A( fun1 );

When you were passing &fun1() that was trying to call the function and then take the address of its result.  What you actually wanted was the function pointer itself which is stored in fun1.

A: This example is meaningless, because you don't save the function pointer for later use. You can rewrite this simply to just
class A
{
    double size;

    A(double sz) {
        size = sz;
    };
};

double fun1()
{
    return 42.0;
}

int main()
{
    A a = A(fun1());
    std::cout << a.size << std::endl;
}

A: I suggest writing a template instead so you can pass in any function pointer or function object. This allows the compiler to more easily do optimisations like inlining in many cases, and is more flexible. You should also not use parentheses when acquiring a function pointer.
#include <iostream>

class A {
public:
    template<typename F>
    explicit A(F&& f) : size(f()) {

    };

    double size;
};

double fun1() {
    return 42.0;
}

int main() {
    A a(&fun1);
    std::cout << a.size << std::endl;
}

A: Looks like you need only the function itself to be passed. You've almost got it. Here is the correct syntax:
typedef double (*functype)();

void foo(functype f) {
    cout << f();
}

double bar() {
    return 2.39;
)

foo(bar); // don't call bar here, just pass it as address.

You can also declare foo as follows:
void foo(double (*f)());

Functions are not first-class objects in C++, so the only way to create a closure with some variables (for example, if you want to carry the function or call a non-static member function) is functors (objects with overloaded operator() ). There are several ways of getting such object:

*

*Define it by yourself, store all necessary variables in fields and pass it as function's argument.

*Use C++11's lambda functions and std::function

*Use boost::function and boost::bind.


text:
Q: Regular expression to match strings in "" I have this \"([^"]*)\"
and on data """Storno ISP""- ""Nesprávne nastavená modulácia KZ (G.DMT/G.992.1B), potrebné nastaviť adsl2+ (G.992.5B)""" "Fast" "Battery" "JNAKA".
I would like to match only "Fast" "Battery" "JNAKA".
Where am I wrong?

A: You may  require no double quotes on each side:
(?<!")"([^"]+)"(?!")

See the regex demo
Details

*

*(?<!") - no " immediately on the left is allowed

*" - a " char

*([^"]+) - Group 1: one or more chars other than "

*" - a " char

*(?!") - no " immediately on the right is allowed.


text:
Q: Binding listview on a page control using template in Windows 8 For some reason, my template is not getting used in the binding of data.  I'm using Visual Studio's "Navigation App" project type for Windows 8 app.  When I run it, each item just gets filled with the full json string.  Similar to binding without using any templates at all.
home.js:
var dataList = new WinJS.Binding.List();
var publicMembers = { itemList: dataList };
WinJS.Namespace.define("VideosData", publicMembers);

(function () {
  "use strict";

  WinJS.UI.Pages.define("/pages/home/home.html", {
    ready: function (element, options) {
      dataList.push({title: 'title 1'});
      dataList.push({title: 'title 1'});
    }
  });
})();

home.html:

What's getting outputted:
{"title":"title 1"}
{"title":"title 2"}

Why isn't the template getting used in the binding? Thanks.

A: The reason for the behavior you're seeing is subtle. I'll explain below, but the short answer is:
Don't look stuff up by id in a page control. Use classes and the select syntax instead.
The following will work in your page control:

So, what's going on?
When you do itemTemplate: videosWin8Tmpl in your options record, at processing time WinJS will look for a global variable named videosWin8Tmpl, and that'll be passed to the control as the template object. This normally works because the browser automatically creates global variables for each element with an ID.
However, when loading a page control, at the time WinJS.UI.processAll is called, the DOM for the page hasn't yet been added to the global document. As such, the browser hasn't yet created the global variable, and thus it doesn't find the template.
the select(...) expression doesn't rely on global variables, instead looking upwards from the element the options record is specified on, so it can find the template correctly.

A: Got it - I moved the template snippet over to default.html just above
...
 and the binding could find it then. Not sure why it had to be in default.html and not in home.html.


text:
Q: Ruby on Rails: How to have multiple controllers for one table AND multiple models I'm new to Ruby and to Rails. I have played a bit with Sinatra but I think that Rails is a more complete framework for my project. However, I am running into trouble with this.
I am working with an fairly substantial existing, and heavily used, mySQL database and I am trying to build an API for this that will report on certain features. The features that are needed are, for the most part, counts of records by certain groupings, then drilling down into details.
For example we have a table - tableA, that contains lots of information relating to documentation. One piece of information we want to report on from that is the number of items in a given language. The language code is stored against each item and based on a get request I would like to return JSON.
Request: /languages/:code/count/:tablename
There are two variables in that most specific URL - the code we are counting and the table we are counting from.
I understand that in routes.rb I can set up a mapping:
get '/languages/:code/count/:table', :controller=>'languages', :action=>'count'

I have a controller - languages_controller.rb with a count method in it. this then matches to a corresponding view file count.html.erb
In all the tutorials I have read and examples I have followed the main point seems that 'languages' would be a table in the database and would therefore be available under the 'magic' Rails approach.
My issue is that it is not a table, rather the results of the call should be a limited subset of the fields in tableA. Such as languagecode and count(id).
The description of the language needs to be looked up 'manually' as it is stored as an internal code that is not in a database anywhere (historic decision/madness).
The questions:

*

*how do I have a model that is only a subset of fields, plus some that are manually populated - languagecode, isocode, description, count

*Am I right in thinking that once I have the model defined as such as I could use ActiveRecord to get data from the database and then in the controller add the extra information in?

*Can I change table in the model based on the parameter sent in the URL?

Essentially, I am at a loss at the moment on what to do with this. I have the routes defined, the view templates in place and the controller there and ready to go. The database component - getting some data from a pre-existing table seems mysterious to me.
Any help is greatly appreciated, it seems that the framework is currently getting in my way and I know that I can't be the only one trying this sort of thing so if you have any advice please share.

A: There's really no need for a model here, at all. This isn't what ORMs are for. What you should be doing is just running raw SQL against the database, and iterating over the results. Consider doing something like this: https://stackoverflow.com/a/14840547/229044


text:
Q: Set a password for external hard disk without format it My external hard disk is 1TB in size and nearly 900GB data on it. I want to set up a password without format it. Is it possible?
file format is ext4.

A: Yes that's possible.
That's called ATA password. You can either set it through your EFI/BIOS firmware, if it allows you to do so. Or you can use hdparm to set such a password.
I would recommend to use your EFI firmware if applicable because hdparm comes with a lot of warning that it can brik your disk. That's kind of scary, even it is unlikely to happen. That are just cautious and warn you of the worst.
So if you want to use hdparm, it's something like:
sudo hdparm --user-master u --security-set-passwd "Secret" /dev/sdx

That is to set a user password 'Secret'. This will let the master password as set by the manufacturer (and let anyone knowing it unlock the drive).
You can eventually also set a master password. But read documentation before to know the consequences.
A good read is this admin-magazine.com article
Note: if the drive with the ATA password is plugged-in while booting, your EFI firmware should ask you for that password. If you plugged it in after booting, I don't know how it is dealt with by ubuntu, but you might have to unlock the drive by issuing another hdparm command from a terminal, like
sudo hdparm --security-unlock 'Secret' --user-master u /dev/sdx

if we use the same variable in our previous example.
Another possibility is to use ext4 built-in encryption, but it only encrypts per directory. Meaning, if you have multiple top directory on your HDD, you will need a password for each directory, unless you move them under the same top root directory. More instruction in the archlinux wiki on how to enable ext4 encryption. This works on new files, so you will have to move all your data to the new encrpyted directory, just to encrypt them.


text:
Q: Listening to ICommandBar or ICommand OnClick event? I have an ArcMap extension and I'm listening to the IEditEvents.
When the OnChangeFeature, OnCreateFeature or OnDeleteFeature event is called, I want to know if it came from the "merge(Editor_Merge)" button.
Is there a way I can listen to the onClick event of the merge button?

A: Try implementing ICustomizationFilter.  When OnCustomizationEvent is called, check to see if it is esriCEInvokeCommand.  If it is, then you should be able to cast the object passed as an ICommandItem.  Check to see if the ICommmandItem references the Editor_Merge command (using ICommandItem.ID).  If it does, set a flag in your extension so that your eventhandler for edit events can know how to react.


text:
Q: Why "\\s" with "rlike" in Spark SQL not work? It's strange the "\s" not work, as the code below:
scala> case class Item(id: Int, name:String)
defined class Item

scala> val df = Seq((1, "hello"), (2, " "))
df: Seq[(Int, String)] = List((1,hello), (2," "))

scala> df.toDF("id", "name").as[Item].filter("name rlike '\\s'").show()
+---+----+
| id|name|
+---+----+
+---+----+

A: As LanguageManual UDF described, rlike need double escaped pattern \\s.
While in the spark-shell, Scala has escaped once. So more \ is needed:
scala> df.toDF("id", "name").as[Item].filter("name rlike '\\\\s'").show()
+---+----+
| id|name|
+---+----+
|  2|    |
+---+----+

scala> df.toDF("id", "name").as[Item].filter("name rlike '\\\\w'").show()
+---+-----+
| id| name|
+---+-----+
|  1|hello|
+---+-----+

Or use strings without escape, like:
scala> val er = """name rlike '\\s'"""
er: String = name rlike '\\s'

scala> df.toDF("id", "name").as[Item].filter(er).show()
+---+----+
| id|name|
+---+----+
|  2|    |
+---+----+


text:
Q: Bash script with the "paths must precede expression" output I'm trying to find all the SQL files that have BOM, using the following bash script:
#!/bin/bash

set -x

printf '\nStart!\n'
caminho="$PWD"
parametros="-type f -name "*.sql""

$(find ${caminho} ${parametros} -exec grep -l $'\xEF\xBB\xBF' {} \;)

But I'm always getting this output:
find /home/pablo/SQL -name ComBOM.sql ComVirgula.sql SemBOM.sql -exec grep -l $\xEF\xBB\xBF {} ;
find: paths must precede expression: `ComVirgula.sql'
find: possible unquoted pattern after predicate `-name'?

There's a lot of questions regarding this problem, which were solved by adding double quotes on the -name, but this didn't work for me. And this is also the same thing that the man says.

A: Adding pairs of unescaped (thus, syntactic) quotes inside a string quoted with the same type of quote characters does nothing at all, because those quotes just cancel each other out. Whereas if you did escape the quotes, they would be treated as data instead of syntax at expansion time, so the code still wouldn't behave as-desired but with a different error (a situation BashFAQ #50 goes into detail on).

Use an array, not a string, so you can pass your arguments through exactly as-quoted without unwanted globbing.
Instead of:
parametros="-type f -name "*.sql""

...use instead:
parametros=( -type f -name "*.sql" )

and then later:
find "$PWD" "${parametros[@]}" -exec grep -l $'\xEF\xBB\xBF' {} +


text:
Q: Cache state in Map of RxJS Subjects by id in Angular service I have a collection of widgets for each ownerId. I am trying to cache the state of these collections in an Angular service by using a Map<string, ReplaySubject<Widget[]>>.
@Injectable({
    providedIn: 'root',
})
export class WidgetService {

    private readonly widgetsByOwnerId: Map<string, ReplaySubject<Widget[]>> =
        new Map<string, ReplaySubject<Widget[]>>();

    constructor(
        private readonly httpClient: HttpClient
    ) {}

    getWidgets(ownerId: string): Observable<Widget[]> {
        if (!this.widgetsByOwnerId.has(ownerId)) {
            const widgets$ = this.httpClient.get<Widget[]>(`api/${ownerId}/widgets`);
            const widgetsCache$ = new ReplaySubject<Widget[]>(1);
            widgets$.subscribe(widgetsCache$);
            this.widgetsById.set(ownerId, widgetsCache$);
        }
        return this.widgetsById.get(ownerId).asObservable();
    }

    createWidget(widget: Widget): Observable<Widget> {
        return this.httpClient
            .post<Widget>(`api/${widget.ownerId}/widgets`, widget)
            .pipe(
                tap((createdWidget): void => {
                    this.widgetsByOwnerId.forEach((widgets$, ownerId) =>
                        widgets$.pipe(take(1)).subscribe({
                            next: (widgets: Widget[]) => {
                                if(createdWidget.ownerId == ownerId || isOwnedById) {
                                    widgets.push(createdWidget);
                                    widgets$.next(widgets);
                                }
                            },
                        })
                    );
                }
            );
    }

    //additional CRUD functions excluded for brevity
}

Some special types of widgets can be owned by multiple widget owners, so some of the CRUD functions in the WidgetService can next() on multiple ownerId's ReplaySubjects. In the sample above, I omitted some of this logic for brevity using isOwnedById.
A consumer of this service looks like this:
@Component({
    selector: 'app-widgets',
    templateUrl: './widgets.component.html',
})
export class WidgetsComponent implements OnInit, OnDestroy {

    widgets: Widget[];

    private readonly ngUnsubscribe$: Subject<unknown> = new Subject();

    constructor(
        private readonly widgetService: WidgetService
    ) {}

    ngOnInit(): void {
        const ownerId = this.getOwnerId();
        this.getWidgets(ownerId);
    }

    ngOnDestroy(): void {
        this.ngUnsubscribe$.next();
        this.ngUnsubscribe$.complete();
    }

    private getOwnerId(): string {
        ...
    }

    private getWidgets(ownerId: string): void {
        this.widgetService
            .getWidgets(ownerId)
            .pipe(takeUntil(this.ngUnsubscribe$))
            .subscribe({
                // TODO: this next is called once when first subscribed, but not when future widgets are created
                next: (widgets) => {
                    this.widgets = widgets;
                },
            });
    }

}

For some reason, when the consuming component first initializes, it gets the cached Widget[] successfully. However, when CRUD operations like WidgetService.createWidget() execute in other components (while the instance of WidgetComponent remains alive, e.g. before WidgetComponent.ngOnDestroy()), this WidgetComponent consumer never receives the next()-ed updates (as noted in the TODO comment).
Any suggestions for how to solve this so that consumers continue to get fed updates from the WidgetService's ReplaySubjects? Thanks.
This question is kind of similar to this one, but different enough that I was not able to figure out how to adapt their answer to this use case.

A: I think the main issue here in these lines:
 const widgets$ = this.httpClient.get<Widget[]>(`api/${ownerId}/widgets`);
 const widgetsCache$ = new ReplaySubject<Widget[]>(1);
 widgets$.subscribe(widgetsCache$);

httpClient create a finity Observable meaning that it will be completed once request finishes or fails.
As a result your ReplaySubject passed as Observer to subscribe method will be completed and you won't get any events anymore.
To fix it you can replace subscribe implementation with the following:
widgets$.subscribe(res => widgetsCache$.next(res));


text:
Q: openal application with visual studio 13 c++ by using qt-5.3.1 Add-in I'm trying to do an application that plays sound with OpenAL. I'm using Visual Studio 13 c++ with qt-5.3.1 Add-in. My code doesn't give an error but there's no sound. When I debug my code, I realized that when I initialize OpenAL device remains NULL. So, context couldn't be created. I'm using this code for initializing:
 const ALCchar* devicename = alcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER);
    ALCdevice* Device;
    ALCcontext* Context;
    Device = alcOpenDevice(devicename);
    if (Device)
    {
        Context = alcCreateContext(Device, NULL);
        alcMakeContextCurrent(Context);
    }

    ALboolean g = alIsExtensionPresent("EAX2.0");
    alGetError();
    alcGetError(Device);

Also, I realized that when I open my app, debugger says that:

'deneme2.exe' (Win32): Loaded 'C:\Windows\System32\wrap_oal.dll'. Cannot find or open the PDB file.

'deneme2.exe' (Win32): Unloaded 'C:\Windows\System32\wrap_oal.dll'

What can be the problem? If you help me, I will be so happy. Thanks in advance.


text:
Q: Backing up a 22 GB MySQL database daily Right now I am able to do the backup using mysqldump. But I have to take down the web server AND it takes around 5 minutes to do the backup. If I don't take down the web server, it takes forever and never finishes + the website becomes inaccessible during the backup.
Is there a quicker/better way to backup my 22 GB and growing database?
All the tables are MyISAM.

A: Pardon me for assuming the OS is Linux. If you are not using LVM, you should be. If you are, here is a very simple way to make backups via snapshot.
# Define these vars to meet your needs. These meet mine.
lvol="/dev/VolGroup03/lvol0"
snap_name="nightly_snapshot"
snap_vol="$(dirname $lvol)/$snap_name"
snap_path="/mnt/$snap_name"
snap_size="10g" # Not the size of your data, anticipated data changes during the backup
backup_path="/backups/$snap_name"

/usr/bin/time -f 'Databases were locked for %E' -- \
mysql <<- MYSQL
# based on http://pointyhair.com/tiki-view_blog_post.php?blogId=1&postId=5
FLUSH TABLES WITH READ LOCK;
\! lvcreate --size $snap_size --snapshot --name $snap_name $lvol
UNLOCK TABLES;
MYSQL
mount $snap_vol $snap_path
rsync -av --delete $snap_path/mysql $backup_path/
umount $snap_path
lvremove -f $snap_vol

This will allow you to make nightly backups without having to add a slave server. I am very much in favor of having a slave server for High Availability, but I don't want you the think that you are stuck until you can create that slave.

A: Yes.
Setup replication to a second machine. When you need to do a backup, you can lock the secondary machine, perform mysqlhotcopy or mysqldump, and then unlock it. It will catch back up with your master, and you never have to take the master offline.
You could even do this on the same machine, if you don't mind doubling the write I/O, but ideally you should back it up in real-time to a second physical server, and take your snapshot backups as often as you need without disturbing your production server.
It's also theoretically possible to restore a database using a known state and binlogs. I've never done it, so please investigate first, but you could backup a known state of your database, then just backup all new binlogs and replay them if you ever needed to restore. Since binlogs are written linearly, rsyncing new binlogs to a remote computer would be very fast.
Edit: Indeed, it looks like using binlogs for backup is documented.
This question is highly related

A: FLUSH TABLES WITH READ LOCK is not something you want to do on a regular (or even semi-regular) basis on a production system. It should be a last resort only.
Set up at least two replication slaves (This will require a FLUSH TABLES WITH READ LOCK, of course). Once they are set up, you can take a backup off one while the other stays in sync as a spare master.
Also, if one of your slaves fails, you can then use a snapshot from that to rebuild a second (or third) slave. If all your slaves fail, you're back to FLUSH TABLES WITH READ LOCK.
Remember to always have a process which regularly checks the data are in sync - use something like mk-table-checksum to do this (this is nontrivial to set up, consult the Maatkit documentation for details).
As 22 GB is relatively small, you will have no problems doing this. Doing it with a large database could be more problematic.

A: The solution here is twofold, as described above:

*

*Set up replication of your server to a slave which you can take offline. The best way to do this is to take a dump of the database using mysqldump and the --master-data parameter.

*Set up nightly backups on the slave. You can either user mysqldump with the --master-data --flush-logs and --single-transaction flags, or you can stop the mysql server, copy the data files on-disk, and restart it (replication will pick up where it left off).

*Run a script on the slave every  (e.g 5, 10, 20 minutes) to check and make sure that mysql is still replicating. I wrote a simple python script to do it, which you're welcome to use.

Note that if you are using InnoDB for your tables, you can use the --single-transaction flag to avoid having to do any table locks and still get a consistent dump of the database, even on the master, and thus do your backups without taking down the server. The above solution, however, is a better one.
Also, if you are using LVM on Linux, you can take an LVM snapshot of the partition, then back that up. LVM snapshots are atomic, so if you do 'flush tables with read lock' and then take your snapshot and unlock, you'll get a consistent snapshot.
If you're concerned about I/O contention making the dump take too long, you can add a third machine and run mysqldump on that over the network to avoid thrashing your disks.

A: Depending on your environment, snapshots are usually an excellent way to go. Particularly if you have to backup the master for some reason. We run master and slave pairs, and use snapshot backups on both.

*

*FLUSH TABLES WITH READ LOCK;

*Pull a snapshot on the database and log filesystems.

*UNLOCK TABLES;

*Copy your data files off the snapshot at your leisure.

With InnoDB tables, you'll want to run SET AUTOCOMMIT=0; before you execute the read lock.

A: Have a look at "Best practice for backing up a production MySQL database?". It is a similar post on Stack Overflow.

A: You could do a gradual backup. Backup 1/24th of the records every hour. The only problem with this approach is if it crashes during the first few hours of the day, you'll lose anything from that time to the time of the crash. Either way, it's less than 24 hours of records lost (I don't know how important that is to you).


text:
Q: How to make pretty url's with scopes using friendly_id? I'm building a blog and I want my categories to have beautiful URL's like
blog/music, blog/art, etc.
So far, I've managed to make them look like this
/blog?category=music
class Article < ActiveRecord::Base
  belongs_to :category

  extend FriendlyId
  friendly_id :title, use: :slugged

  scope :by_category, -> (slug) { joins(:category).where('categories.slug = ?', slug) if slug }
end

-
class Category < ActiveRecord::Base
  has_many :articles

  extend FriendlyId
  friendly_id :name, use: [:slugged, :finders]
end

view
= active_link_to category.name, articles_path(category: category.slug), remote: true,
     class_active: 'active', class_inactive: 'inactive', wrap_tag: :dd, active: /#{Regexp.escape(category=category.slug)}/

controller
Article.by_category(params[:category])

A: You don't need friendly_id for this task
add something like this to your routes:
  get 'blog/:category', to: 'articles#index', as: "category"

and then
 link_to category, category_path(category)

http://guides.rubyonrails.org/routing.html

A: You need friendly_id only to create slugs based on title of the category. If you want to make slug unique in scope of category you can use special friendly_id module to solve this problem.
To make nice nesting in url you can do something like this in your routes:
get 'blog/:category', to: 'articles#index', as: "category"

Something like this in your articles controller:
class ArticlesController < ApplicationController
  def index
    @category = Category.friendly.find(params[:category])
    @articles = @category.articles
    respond_to do |format|
      # and so on...
    end
  end
end

And something like this in your views:
link_to category.title, category_url(category)


text:
Q: Correctly cancel task from async method when wanting to return early I have a MVC WebApi ApiController that will start multiple async operations, but after awaiting the first one, the logic might no longer be interested in the results of the remaining tasks, and just return.
For simplicity I've made this sample:
[HttpGet]
public async Task<IHttpActionResult> Test2(CancellationToken cancellationToken)
{
    Task<ProductSearchResult> searchTask = _productService.SearchAsync("searchterm", cancellationToken);

    // Some sort of logic that means I want to return early, and not wait for the searchTask
    int next = new Random().Next(1, 5);
    if(next <3)
        return Ok("Done");

    ProductSearchResult productSearchResult = await searchTask;

    return Ok(productSearchResult.TotalResults);
}

If the code does decide to return early, I see entries of the following in my logs:

A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread. Object reference not set to an instance of an object.

System.AggregateException:
System.NullReferenceException:
at System.Web.ThreadContext.AssociateWithCurrentThread (System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
at System.Web.HttpApplication.OnThreadEnterPrivate (System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
at System.Web.HttpApplication.System.Web.Util.ISyncContext.Enter (System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
at System.Web.Util.SynchronizationHelper.SafeWrapCallback (System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)
at System.Threading.Tasks.Task.Execute (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)

So now my question is: How do I cancel the _productService.SearchAsync() call appropriately when I decide to return before awaiting it, in order to avoid that exception?
I don't want to just catch the exception, I want to actively cancel the task before I return. But I do not own the cancellationToken in this case.

A: I know this question is closed, but try this:
[HttpGet]
public async Task<IHttpActionResult> Test2()
{
    using (var tokenSource = new CancellationTokenSource())
    {
        var searchTask = _productService.SearchAsync("searchterm", tokenSource.Token);

        // Some sort of logic that means I want to return early, and not wait for the searchTask
        int next = new Random().Next(1, 5);
        if (next < 3)
        {
            tokenSource.Cancel();
            try
            {
                await searchTask; // let it gracefully exit since it was cancelled.
            }
            catch (OperationCanceledException)
            {
                // swallow this
            }
            catch (Exception ex)
            {
                // log this
            }
            return Ok("Done");
        }

        var productSearchResult = await searchTask;

        return Ok(productSearchResult.TotalResults);
    }
}


text: Q: cfexchangeconnection using current user by GetAuthUser() I'm looking at trying to show a user mail in a box. But I don't know their passwords and don't want them to login again, they're already authenticated. Can I do this?


text:
Q: Getting 403 with CSRF token in spring security I am encountering an issue with multiple tabs. If i logout from first tab and open another tab and after logging in and logging out if i go back to first tab and login i get 403. For example, the logout page of first tab had following added to the form by spring security and thymeleaf:
<input type="hidden" name="_csrf" value="7b9639ba-aaae-4ed2-aad2-bb4c5930458e">

where as the login form of second tab added a different csrf token.
<input type="hidden" name="_csrf" value="659324d5-ec5c-4c57-9984-dab740746285">

Now when i go to first tab and login from there i get 403 forbidden. Which makes sense since csrf token is now stale. But how do i get around this? I am also getting 403 forbidden if the user was logged out from inactivity and redirected to login page but tried logging in again only after a while, say half an hour.

A: As of Spring Security 3.2, we have the CsrfTokenRepository interface, which allows you to store the synchronizer token however you see fit, such as in a database. This gives you the option to expire those tokens however you want in order to avoid stale tokens in your use case.
If you want to provide a nicer error message when something does go awry, you can supply a custom AccessDeniedHandler implementation that manages the MissingCsrfTokenException and InvalidCsrfTokenException exceptions in order to produce a more informative message.
UPDATE:
I have an interceptor that handles all my uncaught exceptions, so I just built a little AccessDeniedHandler that rethrows the CSRF-related exceptions:
public class CustomAccessDeniedHandler extends AccessDeniedHandlerImpl {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        if(accessDeniedException instanceof MissingCsrfTokenException
                || accessDeniedException instanceof InvalidCsrfTokenException) {
            throw new ServletException(accessDeniedException);
        }
        super.handle(request, response, accessDeniedException);
    }
}

A: The simplest approach to handling access denied errors I've used has been setting the access denied handler within your security config to redirect to your login page.
<http ...>
    <access-denied-handler error-page="/login.html" />
...


text:
Q: rotation of the element does not fit in place i tried to rotate the elements with different widths but the result is 2 elements are not in place after being rotated and stacked on each other, i tried to change the css position of the elements after being rotated according to their place but still stacked

.drop{
      border: 1px solid gray;
      width:50px;
      height:200px;
      margin:50px;
    }
.drop div{
      transform:rotate(90deg);
      margin:0 auto;
  padding:0 auto;
    }

// i try this but not right

    /* .drop div.box1 {
            transform: rotate(270deg);
            position: relative;
        }

    .drop div.box2 {
            transform: rotate(-90deg) translate(-100%);
            transform-origin: top left;
            display: block;
            position: relative;
        }

     .drop div.box3 {
            transform: rotate(-90deg) translate(-100%);
            transform-origin: top left;
            display: block;
            position: relative;
        } */
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet"/>

desired the result, even though the placement of the elements is changed, the display remains neat

A: This is because the div elements are rotated from the center by default. This behavior can be modified with transform-origin
In your case you want to rotate them from the top left corner with transform-origin: left bottom

.drop{
      border: 1px solid gray;
      width:50px;
      height:200px;
      margin:50px;
    }
.drop div{
      transform:rotate(90deg);
      transform-origin: left bottom;
      margin:0 auto;
      padding:0 auto;
    }
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet"/>


text:
Q: Mensagem de erro sobre algo que não existe na aplicação Ao executar a minha aplicação está aparecendo essa mensagem, mas não existe esse parâmetro. Eis a mensagem de erro:
<%@ Application Codebehind="Global.asax.cs" Inherits="AgendaContato.MvcApplication" Language="C#" %>
<%@ Application Codebehind="Global.asax.cs" Inherits="AgendaContato.MvcApplication" Language="C#" %>

A: O Global.asax não aceita essa declaração em duplicidade:
<%@ Application Codebehind="Global.asax.cs" Inherits="AgendaContato.MvcApplication" Language="C#" %>

Verifique também se o arquivo está íntegro.


text:
Q: Error in storing member function as function pointers in C++ I am trying to store a pointer to a member function in a structure which will be used to call the function later in my program.
Something like this:
// abc.h
namespace XYZ {
typedef void func(const uint8_t *buf, int len);
struct holder
{
    // other members
    func * storePtr;
}
} // end of namespace

the other file as:
// pqr.h
#include abc.h
namespace XYZ {
 class pqr {
   // data members and other functions
   void func1(const uint8_t *buffer, int length);
   void func2(func *section);
   void func3();
   }
} // end of namespace

Now my cpp file needs to store instance of this func1 in my structure member storePtr
// app.cpp
#include pqr.h
void pqr::funct3()
{
   // Do something
   func2(func1);
}
void pqr::func2(func * section)
{
   holder h;
   h.storePtr = section;
}

But I am getting compilation error at line "func2(func1);" as
"error C3867: 'pqr::func1': function call missing argument list; use '&pqr::func1' to create a pointer to member"
I have used &pqr:: to define the scope but it also doesn't solve my problem and I am not able to understand what to do.

A: Pointers to member function are not the same thing as pointers to normal functions - have a look at the explanation and example here: http://msdn.microsoft.com/en-us/library/k8336763.aspx


text:
Q: No business POIs shown on GMSMapView, didTapPOIWithPlaceID not called I'm showing a GMSMapView, but can't achieve to have business places like restaurants, hotels, shops, etc shown. According to the docs using the mapType kGMSTypeNormal should provide that request.

In addition, business POIs appear by default on the map when the map type is kGMSTypeNormal

Unfortunately, it only shows "official" POIs like parks, sights, hospitals and alike.
Furthermore I would have expected that the GMSMapViewDelegate member function mapView:didTapPOIWithPlaceID:name:location: is called when I tap one of these "official" POIs, but no matter where I tap, I don't get the function to be called. I temporarily tried the corresponding mapView:didTapAtCoordinate: just to make sure I set up the delegate correctly and this works perfectly.
Here is my code:
import UIKit
import GoogleMaps

class PoiGoogleMapVC: UIViewController, UITextFieldDelegate, CLLocationManagerDelegate, GMSMapViewDelegate {

    @IBOutlet weak var mainMap: GMSMapView!

    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        mainMap.delegate = self
        locationManager.delegate = self

        let camera: GMSCameraPosition = GMSCameraPosition.camera(withLatitude: 48.857165, longitude: 2.354613, zoom: 8.0)
        self.mainMap.mapType = kGMSTypeNormal
        self.mainMap.camera = camera
        locationManager.requestWhenInUseAuthorization()
    }

    func mapView(_ mapView: GMSMapView, didTapPOIWithPlaceID placeID: String, name: String, location: CLLocationCoordinate2D) {
        print("You tapped \(name): \(placeID), \(location.latitude)/\(location.longitude)")
    }
}

What might be a hint to the solution, but at this point only confuses me, is that according to the api doc GMSMapView has a property called mapStyle. When I try to access this property Xcode gives me a compiler error:

Value of type 'GMSMapView' has no member 'mapStyle'

A: The mapStyle and business POIs were added in version 2.1, released on 22 September 2016. See here:
https://developers.google.com/maps/documentation/ios-sdk/releases#version_21_-_september_22_2016
Maybe you have an older version of the SDK?