text:
Q: Magento 2 Translations not working I'm trying to translate some text in the checkout page:

"Provided Zip/Postal Code seems to be invalid."

However, when I add the following to frontend/..theme../Magento_Checkout/i18n/en_US.csv and re-deploy, the translation isn't there:

"Provided Zip/Postal Code seems to be invalid.","Test."

I cleared cache as well. What am I doing wrong?

A: Had the same problem on my Magento 2 website, tried all sorts of suggestions how to fix it but the only thing that worked for me was -

*

*go to /pub/static/frontend/<theme>/<theme>/<language for example pl_PL>

*Find js-translation.json and delete it (make a copy of it just in case!)

*Go back to your magento root folder and run php bin/magento setup:static-content:deploy pl_PL

*Then run php bin/magento cache:flush
That's it. If you go back to /pub/static/frontend/<theme>/<theme>/<language for example pl_PL> folder, notice that js-translation.json have been generated again.
This problem happens because when you run static deploy, magento generates js-translation.json file with all your translations inserted into this one file and calls it in every time the page is loaded. So when it's already generated and usually empty, it cannot overwrite it with new information. By deleting it and regenerating it will solve the problem.
Hope this is going to help somebody.

A: You can change only text which is written in translation
Like : $this->__("Sample Taxt");
Suggested text not written in translation so you can not change it with translation.
If you want to change it, you can find it in JS file which is located  :
vendor/magento/module-checkout/view/frontend/web/js/model/shipping-rates-validator.js

Note : You have to override JS file to in your theme.
Delete pub/static/*
Run Command :
php bin/magento setup:static-content:deploy

php bin/magento cache:clean

Delete browser cache.

A: Create a directory app/i18n/Vendorname/en_US
Issue command:
bin/magento i18n:collect-phrases --output "app/i18n/Vendorname/en_US/en_US.csv" --magento This will collect all the translatable phrases in csv file and place it in the specified path. Make changes to the csv file as per your requirement and when ready issue command:
bin/magento i18n:pack app/i18n/Vendorname/en_US/en_US.csv -d en_US

This will deploy the translations from your file.
clear the cache etc and you should see your changes.

A: Tried editing the following, but nothing worked:
app/i18n/vendor/module/en_US.csv
app/design/frontend/package/theme/i18n/en_US.csv
app/design/frontend/package/theme/web/js-translation.json
app/design/frontend/package/theme/web/js-translation-en_US.json

Later on, found this answer and it worked: https://magento.stackexchange.com/a/299697/1883
It says:

Core Module translations will not be overridden in custom theme so you
need to place the new translations in your custom module folder.
Create an empty module or use your existing module.

*

*I created a new module (app/code/MyCompany/MyModule)

*Created a new file i18n/en_US.csv inside the module (app/code/MyCompany/MyModule/i18n/en_US.csv)

*Added necessary translation text in the csv file.

*Enabled the module and the translation finally got reflected in the frontend.

A: Just a reminder...
Magento stores some translation data in the browser storage.
You may have to clean browser storage items in addition to Magento internal caches.

A: Always you need to use
like: <?php echo __('Word To Translate'); ?>
to translate any words in magento.
After that you need to add translated words in your locale csv file which is located in app/locale/{lang_ISO}/Your_Module.csv
like app//locale/fr_FR/Mage_Catalog.csv.
Magento will automatically coinsider this translationat the frontend.

A: Always you need to use

to translate any words in magento.
After that you need to add translated words in your locale csv file which is

Magento will automatically coinsider this translationat the frontend.


text:
Q: Java - make eclipse show deprecated code as errors I am trying to update some code from jre 1.4 to 1.7. basically I am trying to swap out vectors and hashtables for arraylists and hashmaps. I am using the jre 1.7, however, when I try to change the compiler error settings to error for deprecated code, it doesnt error on vector's or hash tables despite them being deprecated. I am sure I have configured it to error on these before and was wondering if anyone had any idea what I might be missing?
Thanks

A: Vector and Hashtable are not officially deprecated, so the compiler won't warn you.  They are not marked with the @Deprecated annotation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Remove duplicates from nested array in array of objects I have this array of objects:
const arrayOfObjects = [{
    id: 10,
    children: [1000]
  },
  {
    id: 10,
    children: [2000]
  },
  {
    id: 20,
    children: [1000]
  },
  {
    id: 20,
    children: [1000, 2000]
  },
  {
    id: 20,
    children: [2000]
  },
];

I want to remove duplicates using this code:
  const arrayHashMap = arrayOfObjects.reduce((obj, item) => {
    if (obj[item.id]) {
      // obj[item.id].children.push(...item.children);
      const temporaryArray = [...obj[item.id].children, ...item.children];
      obj[item.id].children = [...new Set(temporaryArray)];
    } else {
      obj[item.id] = {
        ...item
      };
    }
    return obj;
  }, {});
  const result = Object.values(arrayHashMap);

In this code I commented part where I push values to array. I tried to use "new Set" to remove duplicates from final array, but I am always assigning the value to "obj[item.id].children". Is this OK or is there a better way to write this?
Expected result:
[{
  id: 10,
  children: [1000, 2000]
}, {
  id: 20,
  children: [1000, 2000]
}]

Thanks

A: You could group by id and check the array if the value not exists, then push the value.

const
    data = [{ id: 10, children: [1000] }, { id: 10, children: [2000] }, { id: 20, children: [1000] }, { id: 20, children: [1000, 2000] }, { id: 20, children: [2000] }],
    result = Object.values(data.reduce((r, { id, children }) => {
        r[id] ??= { id, children: [] };
        children.forEach(v => {
            if (!r[id].children.includes(v)) r[id].children.push(v);
        })
        return r;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: i dont know about "better", but perhaps terser:

const arrayOfObjects = [{
    id: 10,
    children: [1000]
  },
  {
    id: 10,
    children: [2000]
  },
  {
    id: 20,
    children: [1000]
  },
  {
    id: 20,
    children: [1000, 2000]
  },
  {
    id: 20,
    children: [2000]
  },
];

const arrayHashmap = arrayOfObjects.reduce((obj, {
  id,
  children
}) => ({
  ...obj,
  [id]: {
    id,
    children: [...new Set([
      ...obj[id]?.children ?? [],
      ...children
    ])]
  }
}), {})

const result = Object.values(arrayHashmap);
console.log(result)

edit: whoops, the "tidy" button changed semantics. fixed.

A: Use Array#prototype#reduce to reduce over the array and initialize a set over the children property and keep on adding to the set and lastly map the set back to an array.

const arrayOfObjects = [{
    id: 10,
    children: [1000]
  },
  {
    id: 10,
    children: [2000]
  },
  {
    id: 20,
    children: [1000]
  },
  {
    id: 20,
    children: [1000, 2000]
  },
  {
    id: 20,
    children: [2000]
  },
];

const result = Object.values(
    arrayOfObjects.reduce((r, c) => {
      r[c.id] = r[c.id] || {
        id: c.id,
        children: new Set()
      };

      c.children.forEach((item) => r[c.id].children.add(item));
      return r;
    }, Object.create(null))
  )
  .map((x) => ({
    id: x.id,
    children: [...x.children]
  }));

console.log(result);

A:

const arr = [
  {
    id: 10,
    children: [1000],
  },
  {
    id: 10,
    children: [2000],
  },
  {
    id: 20,
    children: [1000],
  },
  {
    id: 20,
    children: [1000, 2000],
  },
  {
    id: 20,
    children: [2000],
  },
];
let result = arr.reduce((acc, i) => {
  let obj = acc.find((a) => a.id === i.id);
  obj ? (obj.children = [...new Set(obj.children.concat(i.children))]): acc.push(i);
  return acc;
}, []);

console.log(result);

A: you can try this fiddle : https://jsfiddle.net/d0kboywv/2/
const arrayOfObjects = [
  {
    id: 10,
    children: [1000]
  },
  {
    id: 10,
    children: [2000]
  },
  {
    id: 20,
    children: [1000]
  },
  {
    id: 20,
    children: [1000, 2000, 3000]
  },
  {
    id: 20,
    children: [2000, 4000]
  },
];

let mappedArray = new Map(arrayOfObjects.map(o => [o.id, {}] ));
for (let obj of arrayOfObjects) {
    let child = mappedArray.get(obj.id);
    for (let [key, val] of Object.entries(obj.children)) {
        child[key] = (child[key] || new Set).add(val);
    }
}
let result = Array.from(mappedArray.entries(), ([id, child]) => ({
    id,
    children: [...new Set(Object.entries(child).map(([k, v]) =>
        [...v]
    ).reduce((a, b) => a.concat(b), []))].sort()
}));
console.log(result);

It do the job for me !

A: you can temporary transform data structure to more simple
const objectOfArray = {};
your id is key, your children is value
I use name initialData for refer to your array
  const objectOfArray = {};
  initialData.forEach(e => {
    if (objectOfArray[e.id] {
      objectOfArray[e.id].push(...e.children);
    } else {
      objectOfArray[e.id] = [...e.children];
    }
  });

  const result = Object.entries(objectOfArray).map(([id, children]) => {
    return {
      id,
      children: children.filter((e, i) => i === chilren.indexOf(i)),
    }
  });

A: You can also achieve expected output by running the below code
makeMapping = {};
for (let obj of arrayOfObjects) {
    makeMapping[obj.id] = {...obj, children: [...new Set([...obj.children, ...(makeMapping[obj.id]?.children || [])])]};
}
console.log(Object.values(makeMapping));


text:
Q: Use local storage to remember jQuery modal popups when minimized, even if page is reloaded or changed thank you in advance and sorry for my bad english. I'm not a javascript developer and therefore it's difficult, to me, to improve all alone the code that I have on my website, so any specific help is very welcome.
Inside the file called footer.inc.php that - of course - is common to all pages, I have a script that open the url inside the main page as modal popups. I can close them or reduce them.

dialogExtend({"minimizable" : true}) allows me to minimize the popup windows, but if I refresh or change the page, the popups will be lost.
Can I ask you how to change and improve the code above so that the opened modal popups won't be lost, even if I change or reload the page?
I got and answer but, since I don't know javascript well enough, I cannot improve the code by myself.
Thank you again!

A: You have a function that you call with few parameters. I would save those parameters in localStorage, then when reloading the page I would read the content of LS and call the function.
var modals = localStorage.getItem('modals');

if (modals) {
   modals = JSON.parse(modals);
} else {
   modals = [];
}

modals.forEach(args => {
   modalWindow(...args);
});

function modalWindow(name, title, url, width, height) {
   ...
   modals.push([name, title, url, width, height]);
   localStorage.setItem('modals', JSON.stringify(modals));
}

You probably also want to remove the modal from the list when you close it. You can come up with a better data structure that will allow you to do that.


text:
Q: Do Red Hat drivers work on CentOS? I'm thinking on buying a Dell PowerEdge T310. It's marked as certified hardware in Red Hat HCL, but I'd like to use CentOS. I know CentOS it's built from the RHEL sources, but do RHEL drivers work on CentOS?

A: Typically, RHEL drivers will work with CentOS. Sometimes, I'll need to modify the /etc/redhat-release file on the CentOS system to match a RHEL servers' in order to get certain drivers/software to install or run, but otherwise, things are pretty compatible.

A: CentOS is marketed as being binary compatible to RedHat. So while there is no guarantee for compatibnility (is there ever?), it is very likely that it works.


text:
Q: Why do I have to negate the definition of an intersection to prove that complement (A∩B) = complement(A) ∪ complement(B)? Now this was the explanation on how to solve a prove in my book :
We will prove that the two sets complement (A∩B) and complement(A) ∪ complement(B) are equal by showing that each is a subset of the other.
First,we will show that  complement (A∩B) ⊆ complement(A) ∪ complement(B). We do this by showing that if x is in complement (A∩B) ,then it must also be in complement(A) ∪ complement(B). Now suppose that x ∈ complement (A∩B).By the definition of complement,x ∈ complement (A∩B). Using the definition of intersection,we see that the proposition¬((x ∈ A)∧(x ∈ B))is true. By applying De Morgan's law for propositions, we see that¬(x ∈ A) or¬(x ∈ B). Using the definition of negation of propositions, we have x ∈ A or x ∈ B. Using the definition of the complement of a set, we see that this implies that x ∈ A or x ∈ B. Consequently, by the definition of union, we see that x ∈ complement(A) ∪ complement(B) . We have now shown that complement (A∩B) ⊆ complement(A) ∪ complement(B). Next, we will show that complement(A) ∪ complement(B) ⊆ complement (A∩B).We do this by showing that if x is in complement(A) ∪ complement(B), then it must also be in A∩B.Now suppose that x ∈ A∪B. By the definition of union, we know that x ∈ A or x ∈ B.Using the definition of complement,we see that x ∈ A or x ∈ B.Consequently, the proposition¬(x ∈ A) ∨¬(x ∈ B)is true. By De Morgan's law for propositions, we conclude that ¬((x ∈ A) ∧(x ∈ B)) is true. By the definition of intersection, it follows that ¬(x ∈ A∩B). We now use the definition of complement to conclude that x ∈ complement (A∩B). This shows that complement(A) ∪ complement(B) ⊆ complement (A∩B). Because we have shown that each set is a subset of the other,the two sets are equal,and the identity is proved.
Why do I have to negate the definition of an intersection to prove that complement (A∩B) = complement(A) ∪ complement(B)?
What does the definition of the intersection got to do with this?
Because this is my first time solving a proof. Am I just suppose to manipulate the equation complement (A∩B) and simplify it by definitions?

A: If you are asking for an intuitive explanation of why $(A \cap B)^c = (A^c \cup B^c)$, consider a set $X$ containing $A$ and $B$, so that $A^c = X - A$ and $B^c = X - B$. Then we see that any element in $X$ lies in exactly one of the following sets (they are all mutually exclusive):
$$A \cap B$$
$$A^c \cap B$$
$$A \cap B^c$$
$$A^c \cap B^c$$
Then you see that when you ask for what $(A \cap B)^c$ is, you see that it is precisely the union of the three remaining sets: $(A^c \cap B) \cup (A \cap B^c) \cup (A^c \cap B^c)$. As it turns out, we can see that $(A^c \cap B) \cup (A \cap B^c) \cup (A^c \cap B^c) = A^c \cup B^c$.

A: Because $(A\cap B)^c =\{a| a \not \in A\cap B\} $.  Now to further understand and describe what it means to not be in the intersection it helps to know the definition of intersection.
$(A\cap B)^c =\{a| a \not \in A\cap B\}=\{a\not \in both A and B\}=\{a|\lnot(a\in A \land a \in B)\}=\{a|\lnot (a\in A)\lor\lnot (a\in B)\}=\{a|a\in A^c \lor a\in B^c\}=\{a|a\in A^c \cup B^c\}= A^c \cup B^c=$.


text:
Q: WordPress database error: [Not unique table/alias: 'wp_postmeta'] Someone very kindly helped me out on another question, which has now lead to this problem of two functions causing a database error.  From what I've read it could have something to do with LEFT JOIN and/or no wp_reset_query() or wp_reset_postdata().   The error I'm getting is  :
WordPress database error: [Not unique table/alias: 'wp_postmeta']
SELECT SQL_CALC_FOUND_ROWS DISTINCT wp_posts.ID FROM wp_posts LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) LEFT JOIN wp_postmeta ON wp_posts.ID = wp_postmeta.post_id WHERE 1=1 AND ( wp_term_relationships.term_taxonomy_id IN (567) ) AND ( wp_postmeta.meta_key = 'featured_listing' ) AND wp_posts.post_type = 'business' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'acf-disabled' OR wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_postmeta.meta_value DESC LIMIT 0, 10

I've narrowed it down to two functions one being :
// Order posts for featured posts first in search and categories

function custom_special_sort( $query ) {

    // if is this the main query and is this post type of business
    if ( ($query->is_main_query() && is_post_type_archive('business') ) || (is_main_query() && is_tax ('location') ) ) {

        // order results by the meta_key 'featured_listing'
       $query->set( 'meta_key', 'featured_listing' );
        $query->set( 'orderby', 'featured_listing' );
        $query->set( 'order', 'DESC' );

    }
}
add_action( 'pre_get_posts', 'custom_special_sort' );

and the other being :
function cf_search_join( $join ) {
    global $wpdb;

    if ( is_search() ) {
        $join .=' LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
    }

    return $join;
}
add_filter('posts_join', 'cf_search_join' );

+
function cf_search_where( $where ) {
    global $pagenow, $wpdb;

    if ( is_search() ) {
        $where = preg_replace(
            "/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
            "(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where );
    }

    return $where;
}
add_filter( 'posts_where', 'cf_search_where' );

+
function cf_search_distinct( $where ) {
    global $wpdb;

    if ( is_search() ) {
        return "DISTINCT";
    }

    return $where;
}
add_filter( 'posts_distinct', 'cf_search_distinct' );

The first function changes the order of posts in a search result, to order them with a certain post_meta above the rest.
The second function,  add custom fields to the search query instead of wordpress just searching for post content and titles.
Any help in resolving the conflict would be much appreciated.   If I remove one of the functions,  the other one operates as it should but they just won't work together, from my reading i assume its because they are trying to edit the same query ?

A: You JOIN two elements both with the same table. When you need to join one table more than once, you need to make each join unique by giving the table alias. When WP makes the whole query, it takes that into account, but you have added your own code that doesn't do that.
So, first function:
function cf_search_join( $join ) {
    global $wpdb;

    if ( is_search() ) {
        $join .=' LEFT JOIN '.$wpdb->postmeta. ' cfmeta ON '. $wpdb->posts . '.ID = cfmeta.post_id ';
    }

    return $join;
}
add_filter('posts_join', 'cf_search_join' );

This sets postmeta table alias 'cfmeta' and uses it in the ON.
And the second one:
function cf_search_where( $where ) {
    global $pagenow, $wpdb;

    if ( is_search() ) {
        $where = preg_replace(
            "/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
            "(".$wpdb->posts.".post_title LIKE $1) OR (cfmeta.meta_value LIKE $1)", $where );
    }

    return $where;
}
add_filter( 'posts_where', 'cf_search_where' );

Using the 'cfmeta' instead of wp_postmeta.
Milan

A: If anyone is still looking at this issue and cannot fix it by the wonderful solution provided above, take a look that you don't have any display errors / error reporting code still active.
I was looking for a very long time for this solution and it seems like these options below can adjust the queries and cause errors.
Removing this code fixed the problem.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);


text:
Q: LSTM Loss is 0? I am new to neural nets and I don't know where I am doing it wrong.
My dataset has sensor readings and based on those readings model has to classify (total 4 classes).

col_1
col_2
col_3
....
col_6
y

first_1
first_2
first_3
....
first_6

second_1
second_2
second_3
....
second_6

third_1
third_2
third_3
....
third_6

fourth_1
fourth_2
fourth_3
....
fourth_6
0

So four rows in x correspond to one y. It is a many to one relationship.
Basically, these are the dimensions of my dataset.
print("Training Shape", X_train_tensors.shape, y_train_tensors.shape)
print("Testing Shape", X_test_tensors.shape, y_test_tensors.shape)

The output is
Training Shape torch.Size([224735, 4, 6]) torch.Size([224735, 1])
Testing Shape torch.Size([110691, 4, 6]) torch.Size([110691, 1])

The LSTM which I have built is
HIDDEN_SIZE = 1
NUM_LAYERS = 2
EPOCHS = 10

class RNN(nn.Module):
    def __init__(self):
        super(RNN, self).__init__()

        self.rnn = nn.LSTM(
            input_size=6,
            hidden_size=HIDDEN_SIZE,
            num_layers=NUM_LAYERS,
            batch_first=True,
        )

    def forward(self, x):
        out, (h_n, h_c) = self.rnn(x, None)
        return out[:, -1, :]  # Return output at last time-step

rnn = RNN()
optimizer = torch.optim.Adam(rnn.parameters(), lr=0.01)
loss_func = nn.CrossEntropyLoss()

for j in range(EPOCHS):
    for i, item in enumerate(X_train_tensors):
        item = item.unsqueeze(0)
        output = rnn(item)
        loss = loss_func(output, y_train_tensors[i])
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

    print(f"Epoch: {j}, Loss: {np.average(loss.detach())}")

Epoch: 0, Loss: 0.0
Epoch: 1, Loss: 0.0
Epoch: 2, Loss: 0.0
Epoch: 3, Loss: 0.0
Epoch: 4, Loss: 0.0
Epoch: 5, Loss: 0.0
Epoch: 6, Loss: 0.0
Epoch: 7, Loss: 0.0
Epoch: 8, Loss: 0.0
Epoch: 9, Loss: 0.0

Can someone tell me why I am getting loss as 0?

A: Your cross-entropy loss is 0, which means the output of the model is in one-hot encoded format. You should add a linear layer at the end of the model and map it through softmax. Also, you need to make sure your training set labels are in one-hot encoded data format.
You should first check whether the output format meets the requirements by the following code:
print(output, y_train_tensors[i])


text:
Q: AJAX script manager within a masterpage in asp.net I'm using Ajax in page which is under a masterpage.
I have a problem with the location of the script manager. I don't want the script manager to be for all the pages, just for one.
this is the master page :

                <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">

                </asp:ContentPlaceHolder>

and this is the page which I want to add the script manager to it
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
   <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:TextBox ID="TextBox1" runat="server" Width="120"></asp:TextBox>
    <asp:NumericUpDownExtender
        ID="NumericUpDownExtender1" runat="server" TargetControlID="TextBox1" Maximum="9" Minimum="1" Width="120">
    </asp:NumericUpDownExtender>
</asp:Content>

When I run it this problem occuer:" Control 'ContentPlaceHolder1_ScriptManager1' of type 'ScriptManager' must be placed inside a form tag with runat=server."
So I read on the internet that I have to put the content in the master page inside a form tag like this :

            <form id="form1" runat="server" style="height: 25px">
                <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">

                </asp:ContentPlaceHolder>
                </form>

but when I do this another problem occures:
"A page can have only one server-side Form tag."
I have no Idea what to do, Thanks for the help

A: In Asp.net you are not allowed to have more form tags. Instead of having many forms you have only one big form that will contain all your content.
In Master:

  <form id="form1" runat=server>

   <asp:ContentPlaceHolder runat="server" ID="MainContent" />

   </form>

In ContentPlaceHolder:
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    'your code here'
</asp:Content>

Use search in all files to check if you have more than one form tag.

A: The problem is because I had another form in this page. But not a form inside a form, Why can't I have more than one form In a master page ?

A: Site master page:
   <form runat="server">
             <asp:ScriptManager runat="server">

</asp:ScriptManager>

About

<asp:ContentPlaceHolder ID="MainContent" runat="server"> </asp:ContentPlaceHolder>

These are the Aspx page code:
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">

</asp:Content>

And the JS file:
$('#about').click(function (e) {

        e.preventDefault();
        $('#MainContent_subMenus').load('let.aspx');

    });

So the jquery 'load' an ajax call.This function give through the aspx file for the <asp:Content ID="BodyContent" to id=subMenus div

P.S:

BE careful the ID The master page give "MainContent_" tag before almost every element.
It works for me.
I hope this is helps for you.

A: Put your script manager inside contentplace holder.


text:
Q: Sort a map within a map and convert to list within a list Here's my data in Firebase:
prices
  price1
    priceAmount1: 10
    priceAmount2: 20
    priceAmount3: 30
  price2
    priceAmount1: 15
    priceAmount2: 5
    priceAmount3: 7
  price3
    priceAmount1: 2
    priceAmount2: 4
    priceAmount3: 6

If I straight away retrieve it. Sometimes the ordering is price2, price3, price1. So I tried sorting it like this:
      var sortedKeys = prices!.price!.keys.toList()..sort();
      for (var it = 0; it < sortedKeys.length; it++) {
        print('${sortedKeys[it]}');
      }

But since it becomes a list, I'm not able to access the map anymore. I wanted to sort the map within a map then store it in a list within a list. Please help. Thanks!
Edit:
final splayByPrice =
    SplayTreeMap<dynamic, dynamic>((a, b) => a.compareTo(b));

List<Map<dynamic, dynamic>> priceAmountMap = [
        {
          'priceAmount1': 10,
          'priceAmount2': 20,
          'priceAmount3': 30,
        },
        {
          'priceAmount1': 15,
          'priceAmount2': 5,
          'priceAmount3': 7,
        },
        {
          'priceAmount1': 2,
          'priceAmount2': 4,
          'priceAmount3': 6,
        }
      ];

      Map<dynamic, Map<dynamic, dynamic>> priceMap = {
        'price2': priceAmountMap[1],
        'price1': priceAmountMap[0],
        'price3': priceAmountMap[2],
      };

      priceMap.forEach((key, value) {
        splayByPrice.addAll(value);
      });

      priceMap.forEach((key, value) {
        print('$key \t $value');
      });

What it prints, is still not sorted.
price2   {priceAmount1: 15, priceAmount2: 5, priceAmount3: 7}
price1   {priceAmount1: 10, priceAmount2: 20, priceAmount3: 30}
price3   {priceAmount1: 2, priceAmount2: 4, priceAmount3: 6}

A: Dart's default Map implementation is a LinkedHashMap that stores entries in order of insertion.
(You haven't provided code that clearly shows your data structure, so I'll use my own example.)
If you want the Map to be sorted by the keys' alphabetic order, then you could:

*

*Create a new Map, adding items to it in the desired order:
var theMap = {
  4: 'four',
  7: 'seven',
  6: 'six',
  9: 'nine',
  5: 'five',
  1: 'one',
  8: 'eight',
  0: 'zero',
  3: 'three',
  2: 'two',
};

void main() {
  var sortedKeys = theMap.keys.toList()..sort();
  var sortedMap = {
    for (var key in sortedKeys)
      key: theMap[key]!,
  };
  print(sortedMap);
}

*Update the existing Map, removing and re-adding items in the desired order:
void main() {
  var sortedKeys = theMap.keys.toList()..sort();
  for (var key in sortedKeys) {
    var value = theMap[key]!;
    theMap.remove(key);
    theMap[key] = value;
  }
  print(theMap);
}

*Use a SplayTreeMap, which keeps entries sorted by a comparison rule.
import 'dart:collection';

void main() {
  var splayTreeMap = SplayTreeMap.of(theMap);
  print(splayTreeMap);
}

If you need to sort the data only once, I'd use one of the first two methods.  If you're frequently adding new entries, then I'd use a SplayTreeMap instead of a Map/LinkedHashMap so that entries are kept in a sorted order. (But note that lookups, insertions, and removals in a SplayTreeMap are O(log n) instead of O(1).)
Also, if you're sorting strings that contain numbers, you probably don't want to use the normal string sort.


text:
Q: Empty picture on checkout stripe I have implemented the stripe checkout using node.js
product.photo is https://test.s3.amazonaws.com/2213131
const session = await stripe.checkout.sessions.create({
  payment_method_types: ["card"],
  line_items: [{
    name: product.title,
    description: product.description,
    images: [product.photo],
    amount: product.price * 100,
    currency: "usd",
    quantity: 1
  }],
  success_url: "http://localhost:3000/success?session_id={CHECKOUT_SESSION_ID}",
  cancel_url: "http://localhost:3000/cancel"
});

For some reason, the picture is always empty

Other data is fine

A: Similar to Sumit Datta, it was the content-type metadata on S3 that was causing this issue. Make sure you use image/jpeg or image/png as the content-type, else Stripe's CDN won't be able to cache your images!

A: I had the same issue. Please make sure to use the correct "content-type" for your images when storing to S3. That should fix it. Check that your browser does not download image as attachment, rather shows image in browser.


text:
Q: Unable to connect jenkins server and fetch job information I have jenkins ec2 instance installed in mobxterm and via python jenkins api i need to exrtract the job information.
The code is
from jenkinsapi.jenkins import Jenkins

def get_server_instance():
    jenkins_url = 'http://10.220.116.190:8080/'
    server = Jenkins(jenkins_url, username = 'admin', password = 'admin123')
    return server

if __name__ == '__main__':
    print (get_server_instance().version)

I having been trying to connect to my jenkins server but i keep getting a
MaxRetryError error image


text:
Q: How to divide a list into a list of smaller lists based on a predicate? Let's say I have a list like this:
[('Yadda', 5), ('Yadda', 9), ('Blah', 12), ('Blah', 2), ('Blah', 4)]

And I'd like to convert it to a list like this:
[ [('Yadda', 5), ('Yadda', 9)], [('Blah', 12), ('Blah', 2), ('Blah', 4)] ]

Assuming the list is sorted wrt the predicate on which it should be split -
What's the Pythonic way of doing this?
Is there any function that does this or do I have to write it myself?

A: You can use itertools.groupby.
from itertools import groupby

l = [('Yadda', 5), ('Yadda', 9), ('Blah', 12), ('Blah', 2), ('Blah', 4)]

l.sort(key=lambda item: item[0])

result = [list(group) for _, group in groupby(l, key=lambda item: item[0])]

A: Groupby of itertools groups the adjacent elements.
>>> from itertools import groupby
>>> l = [('Yadda', 5), ('Yadda', 9), ('Blah', 12), ('Blah', 2), ('Blah', 4)]
>>> print [list(group) for _, group in groupby(l, key=lambda item: item[0])]
[[('Yadda', 5), ('Yadda', 9)], [('Blah', 12), ('Blah', 2), ('Blah', 4)]]
>>>
>>> #if the list is not sorted!
>>> l2 = [('Yadda', 9), ('Blah', 12), ('Blah', 2), ('Blah', 4), ('Yadda', 5)]
>>> print [list(group) for _, group in groupby(l2, key=lambda item: item[0])]
[[('Yadda', 9)], [('Blah', 12), ('Blah', 2), ('Blah', 4)], [('Yadda', 5)]]

*

*Its important to sort the list before you proceed!

So after sorting,
>>> l2 = [('Yadda', 9), ('Blah', 12), ('Blah', 2), ('Blah', 4), ('Yadda', 5)]
>>> get_first=key=lambda item: item[0]
>>> print [list(group) for _, group in groupby(sorted(l2,key=get_first), get_first)]
[[('Blah', 12), ('Blah', 2), ('Blah', 4)], [('Yadda', 5), ('Yadda', 9)]]

*

*You can also use filter!

As,
>>> l=[('Yadda', 5), ('Yadda', 9), ('Blah', 12), ('Blah', 2), ('Blah', 4)]
>>> s=set(map(lambda item: item[0],l))
>>> print [filter(lambda x:name in x,l) for name in s]
[[('Blah', 12), ('Blah', 2), ('Blah', 4)], [('Yadda', 5), ('Yadda', 9)]]

*

*You can also use itemgetter,

That is,
>>> l=[('Yadda', 5), ('Yadda', 9), ('Blah', 12), ('Blah', 2), ('Blah', 4)]
>>> from operator import itemgetter
>>> s=set(map(itemgetter(0),l))
>>> print [filter(lambda x:name in x,l) for name in s]
[[('Blah', 12), ('Blah', 2), ('Blah', 4)], [('Yadda', 5), ('Yadda', 9)]]

A: Assuming, you are splitting the list based on the first item of the inner list, I would use a dictionary.
l = [('Yadda', 5), ('Yadda', 9), ('Blah', 12), ('Blah', 2), ('Blah', 4)]
d={}
for x in l:
  if x[0] not in d:
    d[x[0]]=[x]
  else:
    d[x[0]].append(x)
print(d.values())

A: I have solved in this way.
list = [('Yadda', 9), ('Blah', 12), ('Blah', 2), ('Blah', 4), ('Yadda', 5)]
ls_set = (set([ls[0] for ls in list]))
ls_dict = {}
for ls in ls_set:
    ls_dict[ls] = []
for ls in list:
    ls_dict[ls[0]].append(ls[1])
final_list = []
for key, value in ls_dict.items():
    a = []
    for i in value:
        a.append(tuple([key,i]))
    final_list.append(a)
print(final_list)

A: if you want without any package or itertools then this will help you,
>>> l = [('Yadda', 5), ('Yadda', 9), ('Blah', 12), ('Blah', 2), ('Blah', 4)]
>>> l.sort(key= lambda x:x[1])
>>> values = set(map(lambda x:x[0], l))
>>> [[y for y in l if y[0]==i] for i in values]
[[('Blah', 2), ('Blah', 4), ('Blah', 12)], [('Yadda', 5), ('Yadda', 9)]]
>>>


text:
Q: Share folder between Windows and WSL I am using XMing to run Emacs from WSL, which is working quite well. My issue is when trying to share folders between Windows and WSL. I have tried the following:

*

*Project located in the Windows file system, accessed  via /mnt/ in WSL

*Symlink (created in WSL bash) of project located in the Windows file system

*Copy the project to the WSL file system

Out of the 3 listed options, only the last works with projectile (and likely other Emacs packages). But I need to be able to access/modify the files from Windows as well, so that is not a viable option.
Has anyone found a good solution for this?

A: I do it so (also to sync between Windows_laptop & Ubuntu_pc):
I have folder "workspace"
and symlinks to it: windows symlink under win and linux symlink under linux.
%USERPROFILE%\Cloud\workspace
for Win usage:
made windows symlink: %USERPROFILE%\workspace -> %USERPROFILE%\Cloud\workspace
for Ubuntu usage (WSL):
made linux symlink: ~/workspace -> /mnt/C/Users/USER/Cloud/workspace
May this help?

A: One of the advantages of WSL (windows subsystem for Linux) is that you can share files easily with your windows.
I have used the below codes with WSL Ubuntu (but this should work with other versions of Linux as well). Using /mnt will do all the magic.
Syntax:- cd /mnt/drive/Folder/Subfolder
Sample code:- cd /mnt/c/Users/Saswat


text:
Q: Convert silverlight to flash How can i convert silverlight app to flash?

A: The platforms are different enough that a "conversion" of code is out of the question.
Instead take the running Silverlight app as a prototype and build the Flash from scratch.
You might be able to re-use some assets such as images.

A: I imagine both platforms are turing complete.
Maybe you could embed a simple PC emulator from http://bellard.org/jslinux/ into one (or the other) of these, and install the opposing platform into it, and run it in that fashion.
Performance might suffer a bit.


text:
Q: MsiGetProductInfo returning ERROR_UNKNOWN_PRODUCT for an installed product I am trying to programmatically query for information from the installer project.  This information is defined in the installer and I don't want to duplicate it in code.  I need to get the Publisher installer property (and a few others), but can't seem to get things to work.
I am querying using:
[DllImport("msi.dll", CharSet = CharSet.Unicode)]
private static extern Int32 MsiGetProductInfo(
    string product,
    string property,
    [Out] StringBuilder valueBuf,
    ref Int32 len);

...
int length = 512;
StringBuilder builder = new StringBuilder(length);
var result = MsiGetProductInfo(
    "{censored}",
    "Publisher",
    builder,
    ref length);

Using RegEdit, I can see an uninstallable product:

{censored}_is1

And this is my application with a "Publisher" key that is what I expect.  I am not sure why the "_is1" suffix is there.  The installer was made using Inno Setup, maybe that is related.  I have tried adding this suffix on the product code in the call to MsiGetProductInfo but it had no effect.
The call returns 1605 which is ERROR_UNKNOWN_PRODUCT.
How do I properly query for the publisher of this product?

A: The MSI API is only useful for MSI-based installations. Inno Setup does not create MSI packages so you can't use the MSI API to query about Inno Setup installations.


text:
Q: Unexpected character encountered while parsing value: T. Path '', line 0, position 0. Does not update the entity in the database When updating an entity in the database, it throws an exception.
"Unexpected character encountered while parsing value: T. Path '', line 0, position 0."
 public void UpdateMainEditor(Photogallery entity)
        {

             _dbContext.Entry(entity).State = EntityState.Modified;

            _dbContext.SaveChanges();
        }

Unable to update entity and save it
after SaveChanges() gives an exception at endpoint
Endpoint Put
public async Task<IActionResult> Put([FromODataUri]int key, [FromBody] Photogallery oData)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (key != oData.Id)
            {
                return BadRequest();
            }

            try
            {
                await _targetHelper.Update(oData, User);

                return Ok(oData);
            }
            catch (Exception ex)
            {
                return StatusCode(500, ex.Message);
            }
}

Model Photogalleries
public class Photogallery : IBaseEntity<int>, ITargetItem
    {
        [Key]
        public int Id { get; set; }
        [Multilingual]
        [Required, StringLength(255)]
        public string Name { get; set; }
        [Multilingual]
        [StringLength(255)]
        public string Description { get; set; }
        [Required]
        public DateTime PublicationStart { get; set; }
        public int? CompanyId { get; set; }
        public bool IsGroup { get; set; }

        public virtual Company Company { get; set; }

        public virtual List<PhotogalleryFile> Files { get; set; }

        public virtual List<TranslatePhotogallery> TranslatePhotogalleries { get; set; }
    }

Model TranslatePhotogallery
 public class TranslatePhotogallery
    {
        [Key]
        public int Id { get; set; }

        public int PhotogalleryId { get; set; }

        public TranslateLanguage Language { get; set; }

        public string TranslateField { get; set; }

        public virtual Photogallery Photogallery { get; set; }

    }

TranslateLanguage is enum!!!! In database nvarchar! :D
Body in request
{
    "id": 46,
    "name": "Test Postman 2, 3,4",
    "description": "Text",
    "publicationStart": "2019-03-22T08:49:46.981Z",
    "companyId": 4,
    "isGroup": true,
    "translatePhotogalleries": [{
        "language": "Ukrainain",
        "translateField": "Some Text"
    }]
}


text:
Q: Number("999") gives 999 but Number(input.value) gives NaN, even though displaying input.value gives "999" exactly what I enter in Number("999") Screenshot of my attempt
I am a beginner to coding. Just started JS. This is my first post on this forum too.
Question: Please see the code. "999" is entered WITH quotation marks. First as Number("999") which displays 999 on screen. But if I enter "999" (quotes included) in an input box, then use Number() to convert value from input box, it displays NaN??? Even though when I display value from input it is "999".
Please guide.
p.s. i tried to upload screenshot, doesn't seem to show up! But url is in beginning of my post.

       <input id="number" />

       <button onclick="fn()"> Type "999" with quotes</button>

A: When you type 999 into the input box, then the value of the input box is "999". Referencing the value property will be treated the same in your code as the literal "999".
When you type "999" into the input box, the value of the input box is "\"999\"".
Think about it this way: if you typed foo bar into the input box, the value has to be the string "foo bar". The value couldn't be foo bar. That's not valid javascript syntax.

If you want to allow quotes but not require them, you could strip off all quotes with a text-replacement:
var age = Number(document.getElementById("number").value.replace(/"/g, ''));

If it's important that the quotes make sense and that the value be interpreted like a javascript string, you could use JSON.parse:
var age = Number(JSON.parse(document.getElementById("number").value));


text:
Q: glewInit() Causes memory leak according to valgrind I am trying to debug and fix all memory leaks in my program. I have went through the entire source code and there is not one call of new or malloc() which isn't supported by a free() or delete. I tried running the program in valgrind. Valgrind found that a consistent(throughout multiple executions of the program) 844 bytes of data were definitely lost. It also constantly points me back to the glewInit() function of my Window class. Is there anything I am doing wrong?
Couple things to note:

*

*My window class is completely static

*My window class calls InputManager::init() which is also a static class

*I have another completely static class for storing constants

class Window {
public:

     // void create(unsigned int width, unsigned int height, const std::string& name, bool resizable, bool decorated){
    //
    // }

    static void create(unsigned int width, unsigned int height, const std::string& name, bool resizable, bool decorated){

         if(!glfwInit()){
              Utils::log("Failed to initialize GLFW");
            return;
         }

         //Setting Window settings
         glfwWindowHint(GLFW_RED_BITS, 8);
         glfwWindowHint(GLFW_GREEN_BITS, 8);
         glfwWindowHint(GLFW_BLUE_BITS, 8);
         glfwWindowHint(GLFW_ALPHA_BITS, 8);
         glfwWindowHint(GLFW_DEPTH_BITS, 24);
         glfwWindowHint(GLFW_STENCIL_BITS, 8);
         glfwWindowHint(GLFW_DOUBLEBUFFER, GLFW_TRUE);
         glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
         glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
         glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
         glfwWindowHint(GLFW_SAMPLES, 4);
         glfwWindowHint(GLFW_RESIZABLE, resizable ? GLFW_TRUE : GLFW_FALSE);
         glfwWindowHint(GLFW_DECORATED, decorated ? GLFW_TRUE : GLFW_FALSE);

         m_width = width;
         m_height = height;

    #ifdef __APPLE__
         glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    #endif

         //Creating the window
         window = glfwCreateWindow(width, height, name.c_str(), NULL, NULL);
         if(!window){
              Utils::log("Window: Failed to create window");
            return;
         }

         //Settings for window
         glfwSwapInterval(1);
         glfwSetFramebufferSizeCallback(window, windowResized);

         //Creating the context for opengl
         glfwMakeContextCurrent(window);

         //Initializing glew
         if(glewInit() != GLEW_OK){
              Utils::log("Window: Failed to initialize glew");
         }

         //Enabling transparency
         glEnable(GL_BLEND);
         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

         //Enabling depth
         glEnable(GL_DEPTH_TEST);
         glClearDepthf(1.0f);

         //Enabling back face culling
         glEnable(GL_CULL_FACE);
         glCullFace(GL_BACK);

         //Enabling MSAA
         glEnable(GL_MULTISAMPLE);

         InputManager::init(window);

    }
     static void clear();
     static void update();
     static void close();

     //Window functions
     static void setVerticalSyncEnabled(bool enabled);
     static void setMouseCursorGrabbed(bool grabbed);
     static int getWidth();
     static int getHeight();
     static bool isResized();

     static bool isCloseRequested();

     static GLFWwindow* window;

private:

     static void windowResized(GLFWwindow* window, int width, int height);

     static int m_width;
     static int m_height;

     static bool m_isResized;
     static bool m_closeRequested;

};
#endif

A: I started using GLAD and it stopped causing the memory leak.


text:
Q: .NET Core: security access based on group membership I'll make this post short and get straight to the seriousness of the situation. Our application has the concept of "Organizations" which are comprised of "Members". We recently found a huge security flaw in our application. If a Member that does not belong to a specific Organization (but is logged into the application) gets access to a URL for any of that Organization's pages, he/she can access that page.
Is there something built into .NET Core 3.0 or Web API that would allow us to stop users from being able to access Organization pages that user is not a Member of? The only way I can think to do it is check if the Member (based on their MemberId) belongs to the Organization (based on OrganizationId). However, that  check would have to be added to every single API controller. There has to be a better way! Any help is appreciated...

A: Decided that I am going to:
1) Create a custom exception
2) Throw it in a base repo class that all of my derived classes are inheriting from
3) Propagate it up and catch it at the base controller class using an ActionFilter
4) Return 403 (w/ custom exception error message) to user (Angular)
5) Have the Angular HTTP interceptor handle the error message, meaning show to user
If anyone has a better idea please let me know.


text:
Q: Wordpress Network (multisite) -- how to ensure each site has their own admin URL? I would like my multisite network install to be at something like:
https://mybusiness.com

Now my business has multiple clients. Each of them will be a "site" inside my singular WP install. So they may have websites like these:
https://example.com
https://example222.com

Which means, I'd also like them to have WP admin areas like these:
https://example.com/wp/wp-admin/
https://example222.com/wp/wp-admin/

Is there an easy to accomplish this, with Nginx only? I do not use Apache, so some instructions that have been suggested in other posts are not entirely helpful. Also they do not change the domain of each site.


text:
Q: Check if command exists Is there any way to check if command exists?
I know that I can write:
try:
    call_command('some')
except:
    print "Command does not exists"

but maybe django allow to check if command is available?

A: See get_commands:
from django.core.management import get_commands, call_command

if 'some_command' in get_commands():
    call_command('some_command')


text:
Q: discord.py rewrite | Allow only one instance of a command Whilst using my bot, I discovered that multiple people can use the same command simultaneously. I would only like the command to be ran one at a time, due to it's nature.
Is there a way to ensure there is only one instance of the command running? If there is, please tell me. I need this fixed sort of quickly, so any help is appreciated.

A: You can have a cooldown for all users with some large timeout, then reset the cooldown at the end of the command:
from discord.ext.commands import cooldown

@bot.command()
@cooldown(1, 1000)  # 1000 second cooldown
async def comm(ctx):
    ...
    comm.reset_cooldown(ctx)

A: Using a global variable is also an option.
global set_active
set_active = 0
...
...
@bot.command("turn_on")
async def "Your command name"(ctx):
    global set_active
    #start command
    if set_active == 1:
        await ctx.send("This is already active")
    else/elif:
        ......
    #end command
    set_active = 1

@bot.command("turn_off")
async def "Your command name"(ctx):
    global set_active
    #start command
    ......
    #end command
    set_active = 0

I hope this is clear. It is my first time helping somebody.
I have this in my bot too. Let me know if I can help you out more!

A: Use the @commands.max_concurrecy(number, per=, wait=False) decorator on your command.
Example:
@commands.command()
@commands.max_concurrency(1, per=commands.BucketType.default, wait=False)
async def poll(self, ctx, *question):
    '''
    Code
    '''

When using the max_concurrency decorator, if you have wait=False then it will return the MaxConcurrencyReached error when the instances exceeds the number specified. Example of error handling the same command that is above is shown below
Example:
@poll.error
async def poll_handler(self, ctx, error):
    if isinstance(error, commands.MaxConcurrencyReached):
         (Whatever you want to do here)

If wait=True then the command will wait in a queue until it can be ran.
Remember to have this line as well in your bot
from discord.ext import commands


text:
Q: Syntax Error in Datetime range Query in Ruby on Rails I am executing a ruby query:
Timeslot.where("start_date >= ? AND end_date <= ?", Wed, 01 Jul 2015 18:00:00 SGT +08:00, Wed, 01 Jul 2015 21:00:00 SGT +08:00)

I am getting the following error
 SyntaxError: unexpected tCONSTANT, expecting ')'
...AND end_date <= ?", Wed, 01 Jul 2015 18:00:00 SGT +08:00, We...

I suppose it is because I am not escaping the ',' character after Wed. I have two questions:
1) How can I correct this query?
2) I will be replacing  Wed, 01 Jul 2015 18:00:00 SGT +08:00 with an actual datetime variable? How can I type this query in the right way if the datetime were variables and not constants?

A: I would write something like this:
Timeslot.where(
  'start_date >= ? AND end_date <= ?',
  Date.parse('Wed, 01 Jul 2015 18:00:00 SGT +08:00'),
  Date.parse('Wed, 01 Jul 2015 21:00:00 SGT +08:00')
)

A: It seem that you have to convert string date into in the proper date format to perform query operation. Like you have date in UTC time zone, then its better to use Time object and convert into proper date format and use that in your query,
str = "Tue, 10 Aug 2010 01:20:19 +0400"
puts Date.parse str
2010-08-10

puts Date.parse(Time.parse(str).utc.to_s)
2010-08-09

A: Did you input parameters Wed, 01 Jul 2015 18:00:00 SGT +08:00 without quotation marks?
I think if you want to use that format. Try this.
"Wed, 01 Jul 2015 18:00:00 SGT +08:00".to_time()
# to_time() method converted to Time Class (timezone is followed by rails setting)

or
"2015-07-01 18:00:00".to_time() # works well.

A: USE DATETIME ...
start_date=DateTime.parse(Wed, 01 Jul 2015 18:00:00 SGT +08:00)
end_date=DateTime.parse(Wed, 01 Jul 2015 21:00:00 SGT +08:00)
Timeslot.where("start_date >= ? AND end_date <= ?",start_date,end_date)


text:
Q: Python: numpy.ndarray object not callable error for root-finding function I've been trying to figure out how to use Python to find roots. If I'm understanding the documentation correctly, scipy.optimize.newton(f,x_o) can be used to find roots, f is a function and x_o an initial guess at the root.
The functions I'm working with are all polynomials and for the purposes I've ever used Python for (interpolation and line-fitting) it's always been sufficient to express a polynomial by an array of coefficients. Defining f in this manner gives me a numpy.ndarray error and I'm assuming it's because I'm giving f as an array and newton(f,x_o) is expecting a function for f.
I'm pretty inexperienced with Python and when I came across this I realized I actually don't know how to define generally f without having to define another variable that'll limit it to an interval. For some arbitrary polynomial, e.g. f = 2x^2 + 7, is there a way to define f without having to give an interval for x? Normally I'm used to having to also define x = arange(n) or something like that which limits it to an interval.

A: You're right, the error is because of the form of f. If you take a look at the scipy documentation for the newton function (here http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.newton.html), you can see that you have to provide a function f(x,a,b,c) with a,b,c as arguments.
if you then provide a function
def f(x, a, b, c):
    return a*x**2 + b*x + c

and then call the newton method as follows:
root = scipy.optimize.newton(f, x0, args=(a, b, c))

the variable root will contain the approximate location of the root of your function. Of course you will have to provide values for the parameters a,b,c before you call the method.
Hope it helps. Cheers.


text:
Q: I am trying to align movie cards one by one. But they are aligning according to imdb rating The below code is the movie list component. Whenever I add a movie to the list they are arranged in a row. After 5 movies if I add the 6th one then the cards are shuffled according to the IMDb rating (descending order). Where I did do wrong?
const MoviesList = (props) => {
const [search, setSearch] = useState('')
const [filterBy, setFilterBy] = useState([])
const [orderBy, setOrderBy] = useState('')

const movies = useSelector((state) => {
    //console.log(state.movies)
    return state.movies
})

const handleChange = (e) => {
    const inputValue = e.target.value
    setSearch(inputValue)

    //filtering the movies based on the search value
    const filteredValue = movies.filter((movie) => {
        return movie.Title.toLowerCase().includes(inputValue)
    })
    setFilterBy(filteredValue)
}

const handleSelectChange = (e) => {
    setOrderBy(e.target.value)
}

const show = (movies) => {
    //sorting based on orderBy
    switch (orderBy) {
        case 'a-z': return [].concat(movies).sort((a, b) => a.Title.localeCompare(b.Title))
        case 'z-a': return [].concat(movies).sort((a, b) => b.Title.localeCompare(a.Title))
        case '1-10': return [].concat(movies).sort((a, b) => a.imdbRating - b.imdbRating)
        case '10-1': return [].concat(movies).sort((a, b) => b.imdbRating - a.imdbRating)
        default: return [].concat(movies)
    }
}

return (

My Movie List

            <form style={{ float: 'right', marginRight: '35px',top:'80px',right:'5px',position:'absolute' }}>
                <input type="text" placeholder='search by name' value={search} onChange={handleChange} className="mr-4" style={{borderRadius:7,width:'300px',padding:'3px',marginRight:'15px'}}/>
                <select value={orderBy} onChange={handleSelectChange} style={{padding:'3px',borderRadius:7,width:90}} >
                    <option value="">orderBy</option>
                    <option value="a-z">a-z</option>
                    <option value="z-a">z-a</option>
                    <option value="1-10">1-10</option>
                    <option value="10-1">10-1</option>
                </select>
            </form>

            {
                filterBy.length > 0 ? (
                    filterBy.map((movie) => {
                        return <MovieCard key={movie.imdbID} Poster={movie.Poster} Title={movie.Title} imdbRating={movie.imdbRating} imdbID={movie.imdbID} />
                    })
                ) : (
                    show(movies).map((movie) => {
                        return <MovieCard key={movie.imdbID} {...movie} />
                    })
                )
            }

)
}

export default MoviesList


text:
Q: What do two bytes after e0 in JPEG header indicate? hex dump of a jpeg image :

Here is a hex dump of a jpeg image . What do two bytes 09 3a indicate?

A: According to Wikipedia, 09 3a indicates the length of the segment, excluding the ff e0 that immediately precedes it.
The article states that:

The bytes s1 and s2 are taken together to represent a big-endian 16-bit integer specifying the length of the following "data bytes" plus the 2 bytes used to represent the length.

So in your case, it indicates a "data bytes" length of 2,360 bytes.


text:
Q: subgroups generators of symmetric group
*

*does any subset of symmetric group generated by repeated multiplication of 3 or more permutations can be generated by only 2 of them?
(trivial cases of identity and single transpositions aside)

*is there a way for finding such set of two permutations from bigger sets? (naive brute-force search aside)
(and, well, what is correct name and terminology for this problem?)

A: If I understood your question (1) correctly the answer is certainly no. For example, in $\;S_6\;$ , we have that
$$\;H:=\langle\,(12),\,(34),\,(56)\,\rangle\cong\Bbb Z_2\times\Bbb Z_2\times\Bbb Z_2$$
and this group cannot be generated by less than three elements. You can easily generalize the above to any finite number of generators.


text:
Q: Talk to VM through host operating system I have here a Windows distribution server that runs an ANT task to build enterprise software. What I need to do is to have the ANT task copy and run a VM image (Linux), and then...talk to that Linux VM through the host operating system (through the ant task itself). We need to be able to send files and/or commands to it.
Is there a practical way to go about this? I know that we already have a way to send commands to VMs that are also running Windows (so windows-windows interaction) -- but is there a way to do a windows-linux interaction?

A: I've implemented the thing you wanted. Of course, for my own purposes, and then just found this question by googling on keywords "vmware" and "ant".
https://github.com/zhuravlik/ant-vix-tasks
This is the taskset for Ant to manage VMWare VMs.
It works via VIX API, so Linux guests should be supported by it.
I did not test it with VMWare Server, though. Only with Workstation.
But the API is common, so it should work.

A: Using ssh is probably the simplest. There is an ant task for that. Scp task is also there to copy files

A: It will depend on what you need to do, but:

*

*The Linux system could expose an SSH server, and the host can do just about anything it needs to via SSH.

*The Linux system could expose a web service that the host consumes.

*The Linux system could expose a Samba share which the host then connects to and reads/writes from (if all you need to do is deal with some files, but that seems unlikely).

There are probably dozens of options.


text:
Q: Arrayoutofboundsexception using setspan I receive an arrayoutofboundsexception error. When I attempt to format a draft text message to be displayed. This is just a simple text-messaging app and I am attempting to set the text size and color. When I comment these two lines my app does not crash but is not formatted as I would like.
The error occurs at:
buf.setSpan(new TextAppearanceSpan(getContext(), size, color), before,
buf.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

Here is the entire code:
private CharSequence formatMessage(ConversationListItemData ch) {
    final int size = android.R.style.TextAppearance_Small;
    final int color = android.R.attr.textColorSecondary;
    String from = ch.getFrom();

    SpannableStringBuilder buf = new SpannableStringBuilder(from);

    if (ch.getMessageCount() > 1) {
        buf.append(" (" + ch.getMessageCount() + ") ");
    }

    int before = buf.length();
    if (ch.hasDraft()) {
        buf.append(" ");
        buf.append(getContext().getResources().getString(R.string.has_draft));
        buf.setSpan(new TextAppearanceSpan(getContext(), size, color), before,
                buf.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        buf.setSpan(new ForegroundColorSpan(
                getContext().getResources().getColor(R.drawable.text_color_red)),
                before, buf.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    }

    // Unread messages are shown in bold
    if (!ch.isRead()) {
        buf.setSpan(STYLE_BOLD, 0, buf.length(),
                Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    }
    return buf;
}

A: I figured it out. You cannot use the TextAppearanceSpan constructor that has 3 parameters when using ForegroundColorSpan. I changed the line below by removing the color variable parameter:
buf.setSpan(new TextAppearanceSpan(getContext(), size, color), before,
        buf.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

to
buf.setSpan(new TextAppearanceSpan(getContext(), size), before,
        buf.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);


text:
Q: Sharepoint Column Fields not available on upload I have created a site content type based on an inherited parent type,
Currently when I create a new document, all the relevant fields appear in the dialog.  But if I upload a document these two fields (Grouping and Subgrouping) that I have created are not populated in the dialog form.
Could someone advise why this is possible?

A: Ensure below two things:

*

*You have added these Grouping and Subgrouping to your newly created content type.

*You have set your content type as default content type from Change new button order and default content type settings.

A: Yes they are both under the default content type and this content type is currently the default.


text:
Q: How to change gallery grid from 4 columns to 3 columns? I'm using WordPress 4.2.2 running Gridsby Child theme (version:1.0.1436164618, latest update). I run my site locally using Xampp.
My question: the Gridsby theme default homepage offers 4-column gallery grid. I would like to shrink the gallery container and to create a 3-column grid instead.
I'm new to WP but I managed to make style changes with Child Theme Configurator. However, not with the gallery grid...I looked everywhere for solutions (including the theme support page but found nothing quite like the issue I'm having).
Can anyone please help me? much appreciated!
Mey

A: In the admin panel, select custom CSS and add this code:
.gallery-image { width: 30%; }

That will increase the image width pushing the 4th image down to the next line :)


text:
Q: How to create invoice / money reciept with html I am working on an application, for a land developer company. The admin of my application has to make invoices, money receipts or bills.
I need to make them look like http://www.vertex42.com/ExcelTemplates/excel-invoice-template.html with HTML+CSS.  If you know any sample template links please inform me or give me suggestions on how to design with HTML+CSS.

A: You can use and  customize this editable invoice template.
http://css-tricks.com/4865-html-invoice/
here is the demo


text:
Q: WebRTC / rtcmulticonnection -> Chrome to Firefox -> No Video I have a question and a problem with following situation:
In my WebRTC-Application (based on rtcmulticonnection) I want Chrome (sender) connect with Firefox (Receiver).
The Datachannel is opened and I'm also able to send custom messages over the socket. But the main problem ist, that I'm not able to see the chrome-video in my Firefox-Receiver.
Chrome shows me following error:
setRemoteDescription failed
 DOMException: Failed to set remote answer sdp: Failed to push down transport description: Failed to set SSL role for the channel.

I already tried to set  DtlsSrtpKeyAgreement to false, but nothing changed.
These are the two SDP's:
Firefox 1:
    Remote peer's sdp: v=0
o=- 274606574180189315 2 IN IP4 127.0.0.1

s=-

t=0 0

a=group:BUNDLE sdparta_0

a=msid-semantic: WMS

m=application 9 DTLS/SCTP 5000

c=IN IP4 0.0.0.0

a=ice-ufrag:74Y5

a=ice-pwd:A8LqsLwstXZXz80HVY0rEexZ

a=ice-options:trickle

a=fingerprint:sha-256 EE:B8:F5:67:92:4C:14:15:34:2C:7C:90:3D:3F:0A:D1:0C:6B:43:E3:A1:DA:1C:29:DC:43:B3:75:0C:70:20:E0

a=setup:active

a=mid:sdparta_0

a=sctpmap:5000 webrtc-datachannel 1024

and Firefox 2:
12:11:11.560 Remote peer's sdp: "v=0
o=- 274606574180189315 3 IN IP4 127.0.0.1
s=-
t=0 0
a=group:BUNDLE sdparta_0 video
a=msid-semantic: WMS ZyYYGy4wOXFxay7ZeNkKR0YSjxXGvhwHSwZe
m=application 42300 DTLS/SCTP 5000
c=IN IP4 192.168.1.121
a=candidate:1910078557 1 udp 2122260223 192.168.1.121 42300 typ host generation 0 network-id 1
a=ice-ufrag:74Y5
a=ice-pwd:A8LqsLwstXZXz80HVY0rEexZ
a=ice-options:trickle
a=fingerprint:sha-256 EE:B8:F5:67:92:4C:14:15:34:2C:7C:90:3D:3F:0A:D1:0C:6B:43:E3:A1:DA:1C:29:DC:43:B3:75:0C:70:20:E0
a=setup:actpass
a=mid:sdparta_0
a=sctpmap:5000 webrtc-datachannel 1024
m=video 9 UDP/TLS/RTP/SAVPF 98 96 100 102 127 97 99 101 125
c=IN IP4 0.0.0.0
a=rtcp:9 IN IP4 0.0.0.0
a=ice-ufrag:74Y5
a=ice-pwd:A8LqsLwstXZXz80HVY0rEexZ
a=ice-options:trickle
a=fingerprint:sha-256 EE:B8:F5:67:92:4C:14:15:34:2C:7C:90:3D:3F:0A:D1:0C:6B:43:E3:A1:DA:1C:29:DC:43:B3:75:0C:70:20:E0
a=setup:actpass
a=mid:video
b=AS:600
a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
a=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time
a=extmap:4 urn:3gpp:video-orientation
a=extmap:5 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01
a=extmap:6 http://www.webrtc.org/experiments/rtp-hdrext/playout-delay
a=sendonly
a=rtcp-mux
a=rtcp-rsize
a=rtpmap:96 VP8/90000
a=rtcp-fb:96 ccm fir
a=rtcp-fb:96 nack
a=rtcp-fb:96 nack pli
a=rtcp-fb:96 goog-remb
a=rtcp-fb:96 transport-cc
a=rtpmap:98 VP9/90000
a=rtcp-fb:98 ccm fir
a=rtcp-fb:98 nack
a=rtcp-fb:98 nack pli
a=rtcp-fb:98 goog-remb
a=rtcp-fb:98 transport-cc
a=rtpmap:100 H264/90000
a=rtcp-fb:100 ccm fir
a=rtcp-fb:100 nack
a=rtcp-fb:100 nack pli
a=rtcp-fb:100 goog-remb
a=rtcp-fb:100 transport-cc
a=fmtp:100 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f
a=rtpmap:102 red/90000
a=rtpmap:127 ulpfec/90000
a=rtpmap:97 rtx/90000
a=fmtp:97 apt=96
a=fmtp:96 x-google-min-bitrate=1474560; x-google-max-bitrate=1474560
a=rtpmap:99 rtx/90000
a=fmtp:99 apt=98
a=rtpmap:101 rtx/90000
a=fmtp:101 apt=100
a=rtpmap:125 rtx/90000
a=fmtp:125 apt=102
a=ssrc-group:FID 3581008081 2076245827
a=ssrc:3581008081 cname:1t2rQehCkf48QVIU
a=ssrc:3581008081 msid:ZyYYGy4wOXFxay7ZeNkKR0YSjxXGvhwHSwZe 15ecfda4-75b7-4355-a3d0-fa371d630364
a=ssrc:3581008081 mslabel:ZyYYGy4wOXFxay7ZeNkKR0YSjxXGvhwHSwZe
a=ssrc:3581008081 label:15ecfda4-75b7-4355-a3d0-fa371d630364
a=ssrc:2076245827 cname:1t2rQehCkf48QVIU
a=ssrc:2076245827 msid:ZyYYGy4wOXFxay7ZeNkKR0YSjxXGvhwHSwZe 15ecfda4-75b7-4355-a3d0-fa371d630364
a=ssrc:2076245827 mslabel:ZyYYGy4wOXFxay7ZeNkKR0YSjxXGvhwHSwZe
a=ssrc:2076245827 label:15ecfda4-75b7-4355-a3d0-fa371d630364
" 1 index.php:681:21

and chrome shows:
setRemoteDescription failed
 DOMException: Failed to set remote answer sdp: Failed to push down transport description: Failed to set SSL role for the channel.
 v=0
o=mozilla...THIS_IS_SDPARTA-55.0.3 2654848822326037754 1 IN IP4 0.0.0.0
s=-
t=0 0
a=fingerprint:sha-256 F5:B7:C9:E8:9D:F4:E3:05:E6:20:31:C7:91:2A:DA:02:70:12:1A:D4:F1:A9:A5:0B:7B:CA:04:A2:96:4E:DA:B0
a=group:BUNDLE sdparta_0 video
a=ice-options:trickle
a=msid-semantic:WMS *
m=application 54696 DTLS/SCTP 5000
c=IN IP4 5.189.131.23
a=candidate:0 1 UDP 2122252543 192.168.1.121 55554 typ host
a=candidate:2 1 TCP 2105508095 192.168.1.121 52341 typ host tcptype passive
a=candidate:2 1 TCP 2105524479 192.168.1.121 9 typ host tcptype active
a=candidate:1 1 UDP 1686052863 xx.xxx.xxx.xx 59602 typ srflx raddr 192.168.1.121 rport 55554
a=candidate:3 1 TCP 1669292031 77.244.108.51 56741 typ srflx raddr 192.168.1.121 rport 52341 tcptype passive
a=candidate:4 1 UDP 8331263 x.xxx.xxx.xx xxxxx typ relay raddr x.xxx.xxx.xx rport 54696
a=sendrecv
a=ice-pwd:529f56ca1ad4e65862fe4c8885cba1b7
a=ice-ufrag:5f58ee5e
a=mid:sdparta_0
a=sctpmap:5000 webrtc-datachannel 256
a=setup:active
m=video 9 UDP/TLS/RTP/SAVPF 98
c=IN IP4 0.0.0.0
a=recvonly
a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
a=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time
a=fmtp:98 max-fs=12288;max-fr=60
a=ice-pwd:529f56ca1ad4e65862fe4c8885cba1b7
a=ice-ufrag:5f58ee5e
a=mid:video
b=AS:600
a=rtcp-fb:98 nack
a=rtcp-fb:98 nack pli
a=rtcp-fb:98 ccm fir
a=rtcp-fb:98 goog-remb
a=rtcp-mux
a=rtpmap:98 VP9/90000
a=setup:active
a=ssrc:3597408388 cname:{7124bea1-2004-4f4a-91bc-2fb05d225669}

Does somebody have an idea how to solve this?
This problem is well known for some years now, but it seems there is no proper solution for this. Thanks in advance!

A: To make sure RTCMultiConnection do not modify the SDP:
// in your HTML file
connection.processSdp = function(sdp) {
    return sdp; // return unchanged SDP
};

To make sure RTCMultiConnection do not pass DtlsSrtpKeyAgreement or ipv6 attributes:
// in your HTML file
connection.optionalArgument = {}; // ignore all DTLS/ipv6 parameters

You can modify dist/RTCMultiConnection.js and remove following two lines:
// in dist/RTCMultiConnection.js
bundlePolicy: 'max-bundle',
iceCandidatePoolSize: 0

Now make sure that you are using dist/RTCMultiConnection.js instead of minified file. By default all demos are using minified file.

Now both Chrome and Fireox will share non-modified SDP, and use similar API.

A: You're using old non-standard Chrome stuff. Remove all mention of DtlsSrtpKeyAgreement.


text:
Q: invoke virtual method 'void android.media.MediaRecorder.setAudioSource(int)' on a null object reference in Android I'm implementing the task of record the voice and save in external storage file.The voice is recording and stop the record this two functions are work only on one button click event.but the problem is when i click on button first time for recording the voice , then in-between recording again i click on button it will stop the record , again click on button application is crashed and getting NullPointerException. Can someone help me how to proper work with recording audio and stop recording on the same button. Thanks !!
Here is my Button click event code.
imageRecord = (ImageView) findViewById(R.id.image_Record);
    imageRecord.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            clickCount += 1;
            Log.e("clickCount ", " click !!! " + clickCount);
            if (clickCount == 1) {

                if (vesselId == null) {

                    SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
                    newAudioFile = 0 + "_" + s.format(new Date()) + ".mp3";
                    Log.e(" newAudioFile ", " = " + newAudioFile);
                    outputFile = baseDir + "/classnkk_audio/" + newAudioFile;
                    Log.e("outputFile ", " = " + outputFile);

                    myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                    myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
                    myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
                    myAudioRecorder.setOutputFile(outputFile);

                    imageRecord.setImageResource(R.drawable.record);
                    try {
                        myAudioRecorder.prepare();
                        myAudioRecorder.start();
                        myChronometer.start();

                    } catch (IllegalStateException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                } else if (vesselId != null)
                {
                    SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
                    newAudioFile = vesselId + "_" + s.format(new Date()) + ".mp3";
                    Log.e(" newAudioFile ", " = " + newAudioFile);
                    outputFile = baseDir + "/classnkk_audio/" + newAudioFile;
                    Log.e("outputFile ", " = " + outputFile);

                    myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                    myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
                    myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
                    myAudioRecorder.setOutputFile(outputFile);
                    imageRecord.setImageResource(R.drawable.record);
                    try {
                        myAudioRecorder.prepare();
                        myAudioRecorder.start();
                        myChronometer.start();

                    } catch (IllegalStateException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

            } else if (clickCount == 2) {
                imageRecord.setImageResource(R.drawable.record_pause);
                myAudioRecorder.stop();
                myAudioRecorder.reset();
                myAudioRecorder.release();
                myAudioRecorder = null;
                myChronometer.stop();
                long elapsedMillis = SystemClock.elapsedRealtime() - myChronometer.getBase();
                String strTime  = String.format("%d min, %d sec",
                        TimeUnit.MILLISECONDS.toMinutes((long) elapsedMillis),
                        TimeUnit.MILLISECONDS.toSeconds((long) elapsedMillis) - TimeUnit.MINUTES.toSeconds
                                (TimeUnit.MILLISECONDS.toMinutes((long) elapsedMillis)));

                Log.e("elapsedMillis ", " of myChronometer !!! " + strTime);

            }

            if (clickCount == 2) {
                imageRecord.setImageResource(R.drawable.record);
                clickCount = 0;
                myAudioRecorder = null;
                myChronometer.setBase(SystemClock.elapsedRealtime());
                Log.e("(clickCount == 3 ) ", " click !!! " + clickCount);
            }
        }
    });

A: You are doing null into clickCount == 2 block
} else if (clickCount == 2) {
                ...
                myAudioRecorder = null;

But you never initialized into first if block. So add initialization block into first if block.

Initialize myAudioRecorder like below code
if (clickCount == 1) {
        myAudioRecorder = new MediaRecorder(); // <<< Initialize here
                if (vesselId == null) {

A: In line no 84 you are making myAudioRecorder = null;. Thatswhy it is throwing the exception.Initilize it again inside the if (clickCount == 1) block


text:
Q: Long IF-ELSE vectorized DataFrame creation Is there a way to vectorize the following in a DataFrame:
d = a.diff()
out = d >=0 and a > b ? 0 : d < 0 and a > b ? 1 : d <= 0 and a < b ? 2 : d >= 0 and a < b ? 3 : 4

Here, both a and b are a simple timeseries in the form of a DataFrame or Series with unimportant data. In my test files I generate them as such:
range = pd.date_range('2019-01-01', freq='MS', periods=10)
a = pd.DataFrame(np.random.randint(20, size=(10, 1)),
                  columns=['value'],
                  index=range)

. What I thought about doing was using map() to something that looks like this:
out = (
        (d >= 0) & (a > b)
).map({
    True: 0,
    False: (
            (d < 0) & (a > b)
    ).map({ ...

This is of course not correct, because of the False case, but hopefully you get the idea.
How can I vectorize this complex statement into a DataFrame?

A: Perhaps the equivalent lambda and np.vectorize() would be of use?
# out = d >=0 and a > b ? 0 : d < 0 and a > b ? 1 : d <= 0 and a < b ? 2 : d >= 0 and a < b ? 3 : 4
import numpy as np
import pandas as pd

out = lambda a, b, d: 0 if d >= 0 and a > b else 1 if d < 0 and a > b else 2 if d <= 0 and a < b else 3 if d >= 0 and a < b else 4

out = np.vectorize(out)

df = pd.DataFrame({'A': {0: 1, 1: 2, 2: 3}, 'B': {0: 5, 1: 4, 2: 3}, 'C': {0: 4, 1: 4, 2: 4}})

print(out(df['A'], df['B'], df['C']))

Results:
[3 3 4]

A: TL;DR
Yes, you can, but you need to be very clear about all the cases.
Details
There are a couple of issues with the tests themselves:

*

*d = a.diff() means the first element of d is NaN. All the tests against a constant will return False (even d == d is False for the first element, which BTW is the canonical way to check for a NaN value).

*Your tests are not neatly separable into two independent tests (e.g. a < b on one hand an d < 0 on the other). Is that intentional? It sure complicates things.

First, let's express your conditions as Python ternary equivalents:
out = [
    0 if d >= 0 and a > b else
    1 if d < 0 and a > b else
    2 if d <= 0 and a < b else
    3 if d >= 0 and a < b else
    4 for a, b, d in zip(a.squeeze(), b.squeeze(), d.squeeze())
]

Obviously, that isn't vectorized.
One (of many) vectorized solution
To vectorize such an expression, let's look at the values table:

a < b
a == b
a > b

d < 0
2
4
1

d == 0
2
4
0

d > 0
3
4
0

d.isna()
4
4
4

You can express that as a sum of simple cases:

*

*Handle 4 separately (a == b or d.isna()).

*For the rest, it is largely 2 for the left column, and 0 for the right column, plus

*a < b XOR d < 0, and finally,

*an override for a < b and d == 0, which should get 2.

You can get a vectorized implementation of that table (note: I'm just using the numpy arrays for concision):
a_lt_b = a <= b
d_lt_0 = d < 0
d_isna = np.isna(d)
a_eq_b = a == b

out2 = a_lt_b * 2 + (d_lt_0 ^ a_lt_b)
out2[a_lt_b & (d == 0)] = 2
out2[d_isna | a_eq_b] = 4

Verification
a = np.tile([-1, 0, 1], 4)
b = np.zeros_like(a)
d = np.repeat([np.nan, -1, 0, 1], 3)
out = [
    0 if d >= 0 and a > b else
    1 if d < 0 and a > b else
    2 if d <= 0 and a < b else
    3 if d >= 0 and a < b else
    4 for a, b, d in zip(a, b, d)
]

# visualization
def view(df, valname='out'):
    df = df.assign(c1='a == b', c2='d == 0')
    df.loc[df.a < df.b, 'c1'] = 'a < b'
    df.loc[df.a > df.b, 'c1'] = 'a > b'
    df.loc[df.d < 0, 'c2'] = 'd < 0'
    df.loc[df.d > 0, 'c2'] = 'd > 0'
    df.loc[df.d.isna(), 'c2'] = 'd.isna()'
    return df.set_index(['c1', 'c2'])[valname].unstack('c1')

After the calculation of out2 above:
z = pd.DataFrame(dict(a=a, b=b, d=d, out=out, out2=out2))

>>> np.array_equal(z['out'], z['out2'])

>>> view(z, 'out2')  # same as for 'out'
c1        a < b  a == b  a > b
c2
d < 0         2       4      1
d == 0        2       4      0
d > 0         3       4      0
d.isna()      4       4      4


text:
Q: SQL SELECT WHERE only exact array values I have 2 tables:
threads (thread_id)
users   (thread_id,user_id)

Users create threads by inviting other users to be on a thread, so multiple users can be on the same thread. I am trying to prevent users from creating new threads that have the same exact users (duplicate user sets). Does someone have a quick SELECT statement to test this?

A: Since your user groups are dynamic (i.e. users can invite other users to a thread at any time), there is no strong reason to enforce the new thread validation. I would give up one of the requirements. Either make the user group static (i.e. a new user should define the group members at creation time) or allow users to create any threads they want. If the restriction on new threads is there to prevent spamming, use something else like CAPTCHAs (or a limit on # of new threads per hour per user) to accomplish the same objective.
You are going to run into SQL performance issues if you try to satisfy both requirements, since you'll be running multiple full-table scans on the database every time someone tries to start a new thread. Also, at any time you can end up in a situation where 2 threads have the same users. E.g. Thread 1 has users A, B and C. Thread 2 has users A and B. What happens when user B invites C to thread 2?


text:
Q: Como nomear vários dataframes de forma automática no Python? Preciso de ajuda para automatizar um processo de nomeação de dataframes que estou aplicando. Importei 3 arquivos csv e apliquei o código abaixo, que funcionou sem problemas:
Loja_1, Loja_2, Loja_3 = (pd.read_csv(cont) for cont in base)
Consigo operar os diferentes df (Loja_1, Loja_2 e Loja_3) perfeitamente, ou seja a parte do código (pd.read_csv(cont) for cont in arquivos) está funcionando. Entretanto, desejo automatizar a geração dos nomes Loja_1 até Loja_n. Como está, tenho que nomeá-los manualmente, mas a quantidade de df pode muito grande, então desejo faze-lo automaticamente.
Alguém pode me ajudar com esta parte do código?
Grato

A: for i in range(1, n): #sendo n o número de lojas+1
     loja ='Loja_'+str(i)
     print(loja)

Coloquei como print para você testar, mas é esse formato de string + contador que pode fazer essa tarefa por você :)


text:
Q: Would two astronauts one in a satellite, one on top of a tower have the same experience? Imagine two astronauts.
The first is in a satellite in geostationary orbit around the earth.
The second is on top of a 35,786 km tall tower that has been built from the equator to space. This means that that the top of the tower is at the same height as the geostationary satellite.
Naive logic would seem to indicate that the astronaut in the satellite would experience free-fall (as do all satellites in orbit), whereas the astronaut on top of the tower would feel the effects of gravity (albeit at a reduced level due to being 35,786 km above the surface of the earth.
However, I can't believe that this would be the case. What's the flaw in my logic? Is the acceleration due to the earth's gravity zero at 35,786 km above the earth?

A: They would both be free-falling.  YOur mountain dweller could stand on top of the mountain, and would feel no upward force from the ground.  The magic of geostationary orbit is that the gravitational force $G\frac{mM}{r^{2}}$ on an object is exactly equal to the centripetal force $\frac{mv^{2}}{r}$ required to keep something moving at the speed $v$ equivalent to one lap around the Earth per day.  Since gravity provides no less or more force than exactly the centripetal force required to keep your person above the same spot on the ground, your person would not need the ground to hold herself up.  She would feel weightless while standing on the mountaintop.


text:
Q: Как изменить время в QDateTimeEdit Имеется переменная date, которая имеет тип QDateTimeEdit.
date.dateTime() имеет тип QDateTime.
Как добавить или вычесть несколько дней или часов?

A: Попробуйте так:
import sys
from PyQt5.Qt import *

class MyWin(QWidget):
    def __init__(self):
        super().__init__()

        lblCurrentDateTime   = QLabel()
        self.lblDateTimeEdit = QLabel()
        btn_days = QPushButton("DateTime + 7 days")
        btn_days.clicked.connect(self.editDateDay_days)
        btn_hours = QPushButton("DateTime + 2 hours")
        btn_hours.clicked.connect(self.editDateDay_hours)

        lblCurrentDateTime.setText(
            QDateTime.currentDateTime().toString('yyyy MM dd hh:mm:ss'))

        self.dateTimeBegin = QDateTimeEdit()
        self.dt = self.dateTimeBegin.dateTime().currentDateTime()

        lay = QVBoxLayout(self)
        lay.addWidget(lblCurrentDateTime)
        lay.addWidget(self.lblDateTimeEdit)
        lay.addWidget(btn_days)
        lay.addWidget(btn_hours)

    def editDateDay_days(self):
        self.dateTimeBegin.setDateTime(self.dt.addDays(7))
        self.dt = self.dt.addDays(7)
        currentTime = self.dateTimeBegin.dateTime().toString(
            'yyyy MM dd hh:mm:ss')
        self.lblDateTimeEdit.setText(
            self.dateTimeBegin.dateTime().toString('yyyy MM dd hh:mm:ss'))

    def editDateDay_hours(self):
        self.dateTimeBegin.setDateTime(self.dt.addSecs(1*60*60*2))
        self.dt = self.dt.addSecs(1*60*60*2)
        currentTime = self.dateTimeBegin.dateTime().toString(
            'yyyy MM dd hh:mm:ss')
        self.lblDateTimeEdit.setText(
            self.dateTimeBegin.dateTime().toString('yyyy MM dd hh:mm:ss'))

if __name__ =="__main__":
    app = QApplication(sys.argv)
    w = MyWin()
    w.show()
    sys.exit(app.exec_())


text:
Q: Maven deploy check md5 before deploy I m using maven 3 and i work on an OSGi project with many module.
Each module have different version, so when someone do a modification, he need to update the version to -SNAPSHOT. But  Sometime people forgot to change the version so when deploy is made, nothing is deploy, and new code is not embeded in the release.
That why i want to overide deploy maven plugin to add a md5 verification only on release jar ( not snapshot because i m sure that they are deployed) and write an log.warn to say "check version for module X because it s seems module have change but version is the same as before"
Currenlty when i doing deploy, i got release jar for a module and i compare md5 with jar in my target directory, but because of MANIFEST, md5 is never the same so i got always my warning.
I change a little the code to check the md5 file by file, and now i can so a report of the different file without checking a list of file (MANIFEST....)
But if 90% of file have same md5, other not, but if. I open 2 different file, in reality they are identic...just because nexus jar is build on linux and target jar is build on windows...some file differ and many other not...
How can i create a jar build on linux or windows with same md5? Does it possible or it depends on many things like processeur, linux/windows?
Thanks by advance and if you have any other idea to do what i want in other manear...

A: You could improve your release process by not allowing that stable versions are allowed in your commits. In fact, commits should be made in SNAPSHOT versions. So how can you guarantee this? You can write a pre-hook commit that verifies if the pom.xml of this project that is being commited has a SNAPSHOT on his version property.
So before deploying your module, you run your release process, commiting the POM to a stable version. That's what Maven Release Plugin does, for example.


text:
Q: Formatar .wsdl para receber um array Sou iniciante com SOAP e estou tentando criar uma integração utilizando PHP para receber informações de um sistema de terceiros utilizando SOAP.
Eu gostaria de ter na requisição uma estrutura dessa, ou seja, o cliente deve enviar as credenciais para autenticação e um objeto de Lista de Preço onde pode haver vários itens para serem criados, algo como a estrutura abaixo:
Descrição da estrutura que gostaria de receber na chamada
Resultado que chego atualmente:
inserir a descrição da imagem aqui
Meu WSDL atual:
    <?xml version="1.0" encoding="UTF-8"?>

<xsd:complexType name='PriceLists'>
  <xsd:complexContent mixed='false'>
    <xsd:restriction base='soapenc:Array'>
      <xsd:attribute wsdl:arrayType='PriceItem[]' ref='soapenc:arrayType' />
    </xsd:restriction>
  </xsd:complexContent>
</xsd:complexType>
<xsd:complexType name='PriceItem'>
  <xsd:all>
    <xsd:element
      minOccurs='0'
      maxOccurs='1'
      name='itemnumber'
      type='xsd:string'/>
    <xsd:element
      minOccurs='0'
      maxOccurs='1'
      name='um'
      type='xsd:string'/>
    <xsd:element
      minOccurs='0'
      maxOccurs='1'
      name='amount'
      type='xsd:float'/>
  </xsd:all>
</xsd:complexType>

<message name="FilterRequest">
    <part name="params" type="xsd:string"/>
</message>

<message name="FilterResponse">
    <part name="result" type="xsd:string"/>
</message>

<message name='CreatePriceLists'>
  <part name='login' type='xsd:string'/>
  <part name='password' type='xsd:string'/>
  <part name='priceLists' type='PriceLists'/>
</message>
<message name='PriceListsResponse'>
  <part name='Result' type='xsd:string'/>
</message>

<portType name="FilterPort">
    <operation name="login">
        <input message="tns:LoginRequest"/>
        <output message="tns:LoginResponse"/>
    </operation>
    <operation name="CreatePriceLists">
        <input message="tns:CreatePriceLists"/>
        <output message="tns:PriceListsResponse"/>
    </operation>
</portType>

<binding name="FilterBinding" type="tns:FilterPort">
    <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
    <operation name="CreatePriceLists">
        <soap:operation soapAction="urn:CreatePriceLists"/>
        <input>
            <soap:body use="encoded" namespace="urn:Organization" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
        </input>
        <output>
            <soap:body use="encoded" namespace="urn:Organization" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
        </output>
    </operation>
</binding>

<service name="WSDLService">
    <port name="FilterPort" binding="tns:FilterBinding">
        <soap:address location="https://semplice.net.br/soap-server/soap-server.php"/>
    </port>
</service>

O que estou fazendo de errado e como posso fazer para chegar no resultado desejado?
Obrigado desde já.