text:
Q: How to understand the different output of two UnsetShared? Update 2
In v11.0.0, situation seems getting worse. UnsetShared doesn't unshare at all. Even the code in help documentation doesn't work as expected.
Update
From technical support,

Thank you for contacting Wolfram Technical Support. I understand that you are reporting an issue with UnsetShared deleting the shared variable after a second evaluation. There seems to be an issue and I was able to reproduce it. I have forwarded an incident report to our developers and have included your contact information in my report.

Original Post
In[1]:= z = 1; SetSharedVariable[z];
ParallelEvaluate[z]
ParallelEvaluate[Print@z];

(==>
Out[2]= {1, 1})

(during the evaluation)
  (kernel 1) 1
  (kernel 2) 1

Looks resonable. However,
In[4]:= UnsetShared[z];
ParallelEvaluate[Print@z];

(during the evaluation)
  (kernel 1) 1
  (kernel 2) 1

this is pretty strange since the z is not recognized by the subkernels anymore.
The most strange part is if you evaluate the In[4] again :
In[6]:= UnsetShared[z];
ParallelEvaluate[Print@z];

(during the evaluation)
  (kernel 1) z
  (kernel 2) z

This really disturbes me. Is this a bug or did I misunderstand something? (Windows 10, Mathematica v10.4)

A: This is an extended comment.
This behaviour is new in 10.4.  I can reproduce it with 10.4.1 on OS X, but not with 10.3.1.
This may be related: DistributeDefinitions and synchronization in Mathematica 10
We can try to analyse what happens like this:
z := (Print[$KernelID]; 1);
SetSharedVariable[z];

ParallelEvaluate[z]
ParallelEvaluate[Print@Definition[z]]
ParallelEvaluate[Print@z];

This will let us figure out:

*

*Where does z get evaluated?  Since it's a shared variable, it is supposed to evaluate on the main kernel, then the result must be passed back to the subkernel.

*What does z evaluate to?

*What is the definition of z on the subkernels?
At this point we get what I would expect, and everything is in agreement with previous versions:

*

*z is evaluated on the main kernel

*z evaluates to 1

*z has a special definition on the subkernel that triggers the callback to the main kernel (I won't quote the output because it is very large)

Now we UnsetShared ...
UnsetShared[z];
ParallelEvaluate[Print@Definition[z]];
ParallelEvaluate[Print[z]]

... and we find that

*

*z evaluates on the subkernels

*z evaluates to 1 (which I consider wrong, like you).

*z has the same definition on the subkernels as on the main kernel, which is wrong, and differs from previous versions. This definition should not have been distributed by ParallelEvaluate.

And we do it again:
UnsetShared[z];
ParallelEvaluate[Print@Definition[z]];
ParallelEvaluate[Print[z]]

Now everything is back to normal. z has no definition on the subkernel any longer.


text:
Q: How do I get the entire error stack when raising an exception? I have the following code, which is meant to display a report of the state of the app when an error is encountered.
begin
    ... # makes calls to lower level instances
rescue
    send_report
end

def send_report
  str = ""
  str.concat("#{$!}\n\r")
  str.concat("Report ----------\n\r")
  ...
  raise str
end

The problem is that $! is only giving me a one line error without any of the usual stack trace.  An example error is:
DEBUG - undefined method `to_sym' for nil:NilClass

And this is shown without a file name or line number or any context.  How do I get that added?

A: You can specify the variable to store the exception in (although you're right that they do get stored in $!, I prefer explicit non-global variables).
begin
  # exception is raised
rescue Exception => e
  str = "#{e.message}\n"
  str << e.backtrace.join("\n")
  raise str
end

The reason you're only getting the error is that the exception being interpolated probably calls to_s on the Exception object, which returns its message and not its backtrace.

redpajama_set_name: RedPajamaStackExchange


text:
Q: WebStorm will not run Jest but Mocha when click on run button on left gutter I want to run Jest tests from the WebStorm's gutter (the green triangle icons on the left side, by the line numbers).

But it always opens Mocha config dialog:

My package.json
{
  "name": "beetrack-fe",
  "version": "4.0.1",
  "private": true,
  "description": "Front End App for Beetrack",
  "author": "Hung Truong",
  "scripts": {
    "build": "BABEL_ENV=build ENV=prd ./node_modules/.bin/quasar build",
    "build_dev": "BABEL_ENV=build ENV=dev ./node_modules/.bin/quasar build",
    "build_qa": "BABEL_ENV=build ENV=qa ./node_modules/.bin/quasar build",
    "build_stg": "BABEL_ENV=build ENV=stg ./node_modules/.bin/quasar build",
    "dev": "BABEL_ENV=build ENV=local ./node_modules/.bin/quasar dev",
    "test": "BABEL_ENV=test ./node_modules/.bin/jest --updateSnapshot",
    "lint": "./node_modules/.bin/eslint --ext .js,.vue src",
    "concurrently:dev:jest": "concurrently \"quasar dev\" \"jest --watch\"",
    "electron-chromedriver": "./node_modules/electron-chromedriver/bin/chromedriver --port=9515 --url-base=wd/hub --verbose",
    "selenium:install": "./node_modules/.bin/selenium-standalone install",
    "selenium:start": "./node_modules/.bin/selenium-standalone start",
    "serve:test:coverage": "./node_modules/.bin/quasar serve test/jest/coverage/lcov-report/ --port 8788",
    "styleguide": "vue-cli-service styleguidist",
    "styleguide:build": "vue-cli-service styleguidist:build"
  },
  "dependencies": {
    "@quasar/extras": "1.1.4",
    "axios": "0.19.0",
    "hooper": "^0.3.2",
    "jwt-decode": "^2.2.0",
    "lodash": "^4.17.15",
    "lscache": "^1.3.0",
    "quasar": "1.0.3",
    "vue-cookies": "^1.5.13",
    "vue-fragment": "^1.5.1",
    "vue-i18n": "^8.11.2"
  },
  "devDependencies": {
    "@quasar/app": "1.0.2",
    "@quasar/cli": "1.0.0",
    "@quasar/quasar-app-extension-testing": "1.0.0",
    "@quasar/quasar-app-extension-testing-e2e-webdriver": "1.0.0-beta.9",
    "@quasar/quasar-app-extension-testing-unit-jest": "1.0.0",
    "@vue/cli": "^3.9.2",
    "@vue/cli-service": "3.9.2",
    "@vue/eslint-config-airbnb": "4.0.0",
    "babel-eslint": "10.0.2",
    "eslint": "6.0.1",
    "eslint-loader": "2.2.1",
    "eslint-plugin-vue": "5.2.3",
    "jest": "^24.9.0",
    "json-loader": "^0.5.7",
    "node-sass": "4.12.0",
    "sass-loader": "7.1.0",
    "vue-cli-plugin-styleguidist": "^3.15.4",
    "vue-jest": "^3.0.4"
  },
  "cordovaId": "org.cordova.quasar.app",
  "engines": {
    "node": ">= 8.9.0",
    "npm": ">= 5.6.0",
    "yarn": ">= 1.6.0"
  },
  "productName": "Beetrack"
}

I already config Jest so that it can run for all test files by the run button on the toolbar. But it does not work for the gutter run button.
Please guild me how to set it up.

A: The IDE uses the test runners listed in package.json when running tests from gutter, and, when several runners are there, it gives certain ones a priority. There is currently no way to specify a test runner explicitly( Please follow WEB-28397 for updates.


text:
Q: How to use qcow2 disk image in Linux? I have a large qcow2 formatted disk image, which I use as storage. Often I need to move data to and from this disk image. I mount the disk using the qemu-nbd tool as follows:
modprobe nbd max_part=63
qemu-nbd -c /dev/nbd0 /host/disk100G.img
mount /dev/nbd0p1 /home/rup/disk

But disk access fails every now and then in the midst of some I/O operation with an "Input/output error". At that point I have to manually unmount the disk and re-mount it so that I can run the program again:
qemu-nbd -d /dev/nbd0
umount joborkhaki/

What could be the reason for this? Is there a better tool that I can use to maintain a qcow2 disk image?

A: Use qemu-nbd with -n key solved the same problem for me.


text:
Q: How can I make this Java method completely generic I have a method which calculates the 95th percentile of an ArrayList of type Float containing statistics data:
    public String calculatePercentile(ArrayList<Float> arrayOfStats) {
    this.statistics = (ArrayList<Float>) arrayOfStats.clone();
    int N = statistics.size();
    int integerPart =0;
    int fractionalPart =0;
    int fraction =0;
    float rank =0;
    float floatPoint =0;
    float interpolate=0;
    float interpolateFirstPart =0;
    float interpolateSecondPart =0;

      if (N == 0) {
        return Float.toString(0);
       } else {
         Collections.sort(statistics);
         rank = (float) ((P / 100.0) * (N - 1));
            if (rank == Math.round(rank)) {
              return Float.toString(statistics.get((int) rank));
            } else {
                String split = Float.toString(rank);
                Pattern pattern = Pattern.compile(floatRegExPattern);
                Matcher matcher = pattern.matcher(split);
                while(matcher.find()) {
                integerPart = Integer.parseInt(matcher.group(1));
                fractionalPart = Integer.parseInt(matcher.group(3));
                }

                if (fractionalPart < 10) {
                    floatPoint = (float) (fractionalPart / 10);
                } else {
                    floatPoint = (float) fractionalPart / 100;
                }
         fraction = integerPart + 1;
         interpolateFirstPart = statistics.get(fraction);
         interpolateSecondPart = statistics.get(integerPart);
         interpolate = interpolateFirstPart - interpolateSecondPart;
         return roundToTwoDecimalPlaces((floatPoint * interpolate) + interpolateFirstPart);
       }
      }
}

My question is how can I make this method generic so that it can not just accept and calculate ArrayLists of type Float, but it can also do Integers etc. I have tried to use templates such as
ArrayList<? as Number>

but when I get to Collections.sort, it complains and I couldn't figure out what was wrong. The return value needs to be a string.

A: You can use
public <T extends Number> String calculatePercentile(ArrayList<T> arrayOfStats) {

and then use Number.floatValue to retrieve each stat as a float. You'll probably have to use this to write your own comparator to do the sorting. A comparator might look like this:
Comparator<Number> c = new Comparator<Number>() {
    public int compare(Number a, Number b) {
        return Float.compare(a.floatValue(), b.floatValue());
    }
}

Incidentally, a better way to assign to statistics would be:
this.statistics = new ArrayList<Number>(arrayOfStats);

You don't need to clone and cast.


text:
Q: Grey border around tkinter widgets (not using canvas) I am experiencing issues with a Python 3 tkinter program I'm working on.
I am running macOS Sierra.
When running the app, every widget has a grey border around it.
Is there any way to remove this?
Screenshot of the border:

Here's the code:
# Item list
itemlist=Treeview(root)
itemlist.heading("#0", text="Item Name")
itemlist["columns"]=("1")
itemlist.column("1",width=50)
itemlist.heading("1",text="Item ID")
itemlist.bind("<Double-1>", select)
itemlist.grid(row=2,column=1,padx=10,pady=10)

# Nametag
Label(root,text="Name:").grid(row=3,column=0)

# 'Save' Button
saveButton=Button(text="Save")
saveButton.bind("<Button-1>",savebind)
saveButton.grid(row=1,column=0)

# 'Add New' button
newItemButton=Button(text="New Event")
newItemButton.bind("<Button-1>",newItem)
newItemButton.grid(row=0,column=1)

# Name entry text field
itemNameEntry=Entry(root,width=25)
itemNameEntry.grid(row=3,column=1)

# Submit Button
submitButton=Button(root,width=25,text="Submit")
submitButton.grid(row=4,column=1)
submitButton.bind("<Button-1>",submit)

# Begin loading
load()

# Start GUI
root.mainloop()

A: Configure your widgets to use highlightbackground = 'white' (or whatever your background colour is) and set your highlightthickness=0
This should remove the grey outline.
EG
itemNameEntry=Entry(root,width=25, highlightbackground='white')
itemNameEntry.config(highlightthickness=0)

A: You can use widget.config(highlightthickness=0) or pass this parameter in widget constructor.

A: If you are importing tkinter.ttk you need to import that first, then import tkinter.
from tkinter.ttk import *
from tkinter import *


text:
Q: How can I duplicate the split-view inside tabbed view seen in iTunes U 2.0 on iPad with Xamarin.iOS? The new iTunes 2.0 app allows you to transition into  what appears to be a split-view inside a tabbed view on the iPad:

I would like to create something similar in my own app written using Xamarin.iOS. Basically I want to be able to first present a login screen (full screen), then after login push a tabbed interface on top. In these tabs, the user could enter for example search terms, and then I would like to present the result in the tab as a split-view (like in the iTunes app).
How can this be accomplished?
As far as I can see, the split-view is restricted to be used as a root view controller only, so there must be some trick to it?
Unless Apple is using a non-official API, or they have reimplemented the split-view or something like that?

A: This is easy to do and does not require any private APIs.
UISplitViewController split;
UIViewController master, detail, second;

master = new UIViewController();
detail = new UIViewController();
second = new UIViewController();

split = new UISplitViewController ();

split.ViewControllers = new UIViewController[] { master, detail };

split.Title = "Split";

tabs = new UITabBarController ();
tabs.ViewControllers = new UIViewController[] { split, second };

window.RootViewController = tabs;


text:
Q: Session security and ASP.NET Ajax I'm starting to use ASP.NET Ajax.  Following Eric Pascarello's recommendations, I always operate under the assumption that anything can come from the client side (including fake requests).
One matter which I have a hard time accounting for is user authentication.  Since we use .NET's built-in session state management mechanism, I'm a bit ignorant of what security risks exist with the webservices.
What do I need to do to be certain that the user is who he says he is (to a reasonable enough probability)?  Is using
[WebMethod(EnableSession = true)]

enough?
Thanks

A: That's how you make sure the Session object is available in your method.  If you want to make sure they are authenticated then configure it in your web.config
<location path="MyService.asmx">
    <system.web>
      <authorization>
        <deny users="?" />
      </authorization>
    </system.web>
  </location>


text:
Q: Elasticsearch java api for full text search with filters I want to do a full text search on string "user" which can match any feild in my document and then apply filter so that i get only records where the value of x feild is either "abc" or "xyz".
Fiddling with Sense , the below request fulfills my requirement.
GET _search
{
   "query":{
      "filtered":{
         "query":{
             "query_string": {
                 "query": "user"
         }
         },
         "filter":
             [

                    {"term": { "x": "abc"}},
                     {"term": { "x": "xyz"}}
            ]
      }
   }
}

But, i want a java api to do the above stuff. I have searched the elastic documentation and the SO , but have not found what i am looking for as api like QueryBuilders.filteredQuery seems deprecated . I am currently using 2.3.4 but can upgrade.

A: Elasticsearch 2.x java Api doesn't have implementation for filtered query. According to the elasticsearch documentation, they suggest to use the bool query instead with a must clause for the query and a filter clause for the filter.
In java you could create a method to create a wrapper method for the filtered query. This would be like:
   public static QueryBuilder filteredQuery(QueryBuilder query, QueryBuilder filter){
        BoolQueryBuilder filteredQuery = QueryBuilders.boolQuery().must(query);
        return filteredQuery.filter(filter);

    }

where,
QueryBuilder query = QueryBuilders.queryStringQuery("user");
QueryBuilder filter = QueryBuilders.boolQuery().filter(QueryBuilders.boolQuery().should(QueryBuilders.termsQuery("x", "abc", "xyz")));

This query is equivalent to the one mentioned above. Hope this helps


text:
Q: Retrieve number from the string pattern using regular expression I have a string "Search result:16143 Results found", and I need to retrieve 16143 out of it.
I am coding in ruby and I know this would be clean to get it using RegEx (as oppose to splitting string based on delimiters)
How would I retrieve the number from this string in ruby?

A: I'm not sure on the syntax in Ruby, but the regular expression would be "(\d+)" meaning a string of digits of size 1 or more. You can try it out here: http://www.rubular.com/
Updated:
I believe the syntax is /(\d+)/.match(your_string)

A: > foo = "Search result:16143 Results found"
=> "Search result:16143 Results found"
> foo[/\d+/].to_i
=> 16143

A: This regular expression should do it:
\d+

A: For a non regular-expression approach:
irb(main):001:0> foo = "Search result:16143 Results found"
=> "Search result:16143 Results found"
irb(main):002:0> foo[foo.rindex(':')+1..foo.rindex(' Results')-1]
=> "16143"

A:  # check that the string you have matches a regular expression
 if foo =~ /Search result:(\d+) Results found/
   # the first parenthesized term is put in $1
   num_str = $1
   puts "I found #{num_str}!"
   # if you want to use the match as an integer, remember to use #to_i first
   puts "One more would be #{num_str.to_i + 1}!"
 end

A: > foo = "Search result:16143 Results found"
=> "Search result:16143 Results found"
> foo.scan(/\d/).to_i
=> 16143


text:
Q: Keyup and blur firing at same time I'm having an interesting problem where I'm using keyup and blur on a form element. I need to allow the blur and keyup events bubble up from the fields to the form where I can capture them.
$('form').on('focusout submit keyup', function(e) {
    console.log($(e.target).attr('id'));
    $(e.target).css('background','red');
});

http://jsfiddle.net/Z6Ayx/
Problem is that keyup and blur fire when you tab out of a field. This is because when you tab out of a field the blur events fires on that field, but when you lift the key you're already in the new field so the keyup event is also fired for that.
I've been trying to figure a good solution....I've thought of a really horrible solution which involves adding a focusin/focus event to each field. If a field gets focus then find the next field in the dom and add a class to it to flag it as 'don't validate on first keypress'. But this just seems like a bad idea

A: If you mean by tabbing out pressing tab key on keyboard, in that case tab is also the key so it will trigger the keyup event. Try the following to detect tab:
$('form').on('keyup focusout submit', function(e) {
    if (e.keyCode == 9) {
       //tab was pressed do something else, set a flag to true perhaps
    } else {
       console.log($(e.target).attr('id'));
       $(e.target).css('background','red');
    }
});

A: You will need to exclude the tab keyup event by checking for e.keyCode != 9 and preventing anything from happening.
This should work for you:
$('form').on('keyup focusout submit', function(e) {
  if (e.keyCode != 9) {
    console.log($(e.target).attr('id'));
    $(e.target).css('background','red');
  }
});


text:
Q: Crash in CollectionView For Invalid Header I want to understand what this error means?
 *** Terminating app due to uncaught exception   'NSInternalInconsistencyException', reason:
'the view returned from -collectionView:viewForSupplementaryElementOfKind:atIndexPath: was not
retrieved by calling -dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath:
for element kind 'UICollectionElementKindSectionHeader' at index path <NSIndexPath: 0x8aeb905cf5be0ed2>
{length = 2, path = 0 - 0}; supplementary view:
<UICollectionReusableView: 0x7f9236dc4ff0; frame = (0 0; 0 0); layer = <CALayer: 0x600001018620>>'

I am using custom header for UICollectionView.I am getting this crash as soon as the view is loaded. even before cellforrowatindexpath is called and the issue is not with the custom header, it is with the return UICollectionReusableView()
func collectionView(_ collectionView: UICollectionView,   viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

    if kind == UICollectionView.elementKindSectionHeader  && indexPath.section == 2
    {
     return someCustomHeader
    }

    return UICollectionReusableView()
}

A: When you work with custom header you have to register first the header class.
  collectionView.register(AppHeaderCollectionView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: AppHeaderCollectionView.headerIdentifier)

and after that for use the header you have to do it this.
 override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: AppHeaderCollectionView.headerIdentifier, for: indexPath) as! AppHeaderCollectionView
        return header
    }

A: You must always obtain the section header with the method dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath:, before calling it you must also register a header class. If you want to show only the header of the third section you must implement collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) to hide unwanted headers by giving them a .zero size (you can' t simply return an instance of UICollectionReusableView for unwanted headers).
import UIKit

class CollectionViewController: UICollectionViewController {
   private let headerId = "headerId"

   override func viewDidLoad(){
      super.viewDidLoad()

      // Registers a header class
      self.collectionView.register(YourClass.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: self.headerId)  // Replace YourClass with the name of your header class
   }

   func collectionView(_ collectionView: UICollectionView,   viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
      // This method must always call dequeueReusableSupplementaryView, even if section!=2
      if kind == UICollectionView.elementKindSectionHeader{
         return self.collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: self.headerId, for: indexPath)
      }

      return UICollectionReusableView()
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize{
       // Shows only the header of the third section
       return section == 2 ? desiredSize : .zero  // Replace desiredSize with the size of the visible header
    }
}

A: After the iOS update to 15.0, I had to subclass UICollectionReusableView for my header view.

   guard let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: MenuTitleHeaderView.sectionHeaderID, for: indexPath) as? MenuTitleHeaderView else {
       fatalError("Unexpected Sumplementary View")
   }
   switch kind {
   case  UICollectionView.elementKindSectionHeader:
  ...

}
Don't forget to return the size for the header or footer as well.
One more thing, don't forget to return the number of sections. Or you will only see one section display.


text:
Q: Let $(m,n)$ be the pair of integers satisfying $2(8n^3 + m^3) + 6(m^2 - 6n^2) + 3(2m + 9n) = 437.$ Find the sum of all possible values of $mn$.
Let $(m,n)$ be the pair of integers satisfying $2(8n^3 + m^3) + 6(m^2 - 6n^2) + 3(2m + 9n) = 437.$ Find the sum of all possible values of $mn$.

What I Tried:- Given this expression I had no idea to claim something out of it, because it looks like we need to $437$ in terms of sums of $2,3$ (the $6$ does not matter much here). I could break $(8n^3 + m^3)$, but it didn't help much.
Instead I simplified the whole expression and got :-
$$2m^3 + 6m^2 + 6m + 16n^3 - 36n^2 + 27n = 437.$$
$$\rightarrow 2m^3 + 6m^2 + 6m + 16n^3 - 36n^2 = 437 - 27n.$$
From here, $2 \vert (437 - 27n)$, so $n$ is odd. Let $n = (2k + 1)$. Substitute this back to the equation to get :-
$$64k^3 + 24k^2 + 3k + m^3 + 3m^2 + 3m = 215.$$
Now I am stuck here, it is given $(k,m)$ are integers, so they can range to negative values also. So I was not able to make an upper bound on $k$, and I have no other idea what I can claim from here.
Can anyone help me? Thank You.

A: First, substitute $x=m+1$ and move the constant term to the left side:
$$2x^3+16n^3-36n^2+27n=439$$
Then, note that $n$ must be odd.  We can replace $n=2y+1$ and divide out by $2$ and get:
$$x^3+64y^3+24y^2+3y=216$$
Some algebraic manipulation (multiplying both sides by $8$, adding $1$ to both sides, factoring, and then replacing $z=8y+1$):
$$8x^3+512y^3+192y^2+24y=1728$$
$$8x^3+512y^3+192y^2+24y+1=1729$$
$$(2x)^3+(8y+1)^3=1729$$
$$(2x)^3+z^3=1729$$
Expressing $m$ and $n$ in terms of $x$ and $z$ gives $m=x-1$, $n=\frac{z-1}{4}+1$.
$1729$ is famously the Ramanujan-Hardy taxicab number, the smallest natural number that can be written as the sum of two cubes in two different ways.  $1729=1^3+12^3=10^3+9^3$.  This results in possible $(x,z)$ of $(6,1)$ or $(5,9)$.  In terms of $(m,n)$, we have $(4,3)$ and $(5,1)$.
Therefore, our possible values for $mn$ are $5$ and $12$.

A: Edit: This is similar Moko19's answer (written in paralel but posted too late...), but I keep it here as it describes process how to get the solutions for the $a^3+b^3=1729$.
Notice that $m^3+3m^2+3m=(m+1)^3-1$, and similarly $$64k^3 + 24k^2 + 3k=\frac{1}{8}((8k)^3+3(8k)^2+3(8k))=\frac{1}{8}((8k+1)^3-1).$$
And so
$$
\frac{1}{8}((8k+1)^3-1)+(m+1)^3-1=215
$$
which in turn after simplification gives
$$
(8k+1)^3+(2m+2)^3=1729.
$$
Let $a=8k+1=4n-3$ and $b=2m+2$. Now notice that $a^3+b^3=(a+b)(a^2-ab+b^2)=1729$ and also $a^2-ab+b^2>0$, which implies $a+b>0$ (regardless of whether any of $a,b$ is negative). Finally, we need to only check finitely many cases, namely for each positive divisor $d \mid 1729 = 7\cdot 13\cdot 19$ (so $d\in \{1, 7, 13, 19, 91, 133, 247, 1729\}$), let $a+b=d$ and $a^2-ab+b^2=\frac{1729}{d}$ , which simplifies to quadratic (diophantine) equation in one variable.
For example, for $d=13$ we have $a+b=13$ and $a^2-ab+b^2=133$, and hence substituting first into the second and cancel $3$, we have $a^2-13a+12=0$. This solves to $a=12$ or $a=1$, applying the original substitution backwards we get $n=1,m=5$. Same way, we find that only other value that works is $d=19$, leading to $n=3,m=4$.
Bonus: You might recognize a famous Ramanujan's taxicab number 1729, which is the smallest natural number expressible as a sum of positive(!) two cubes in exactly two different ways: $$1729=1^3+12^3=9^3+10^3.$$
Which also gives us a solution (although we still need to be careful about the negative cubes).

A: This is just to fill in the unfinished part of Moko19's answer, showing that there are no solutions with mixed signs. That is, we'll show here that $1729$ can only be written as the sum of two positive cubes.
If $a^3-b^3=1729$ with $a\gt b\gt0$, then we have
$$1729=(a-b)(a^2+ab+b^2)=(a-b)((a-b)^2+3ab)\gt(a-b)^3$$
Consequently, since $(a-b)\mid1729=7\cdot13\cdot19$, we can only have $a-b=1$ or $a-b=7$. If $a-b=1$, then we have $ab=(1728-1)/3=576=24^2$, while if $a-b=7$, then we have $ab=(247-49)/3=66=11\cdot6$. It's easy to see that neither of these is possible.


text:
Q: Minecraft lag with the AMD A10 7850K APU? I've made my first custom build PC for my grandma. She doesn't really use it for gaming but her grandchildren do, and she didn't have much money to spare, so I've build a PC with an AMD A10 7850K without a graphics card, but with enough power to add one later. The PC has 8 GB of Corsair Vengeance RAM running at 2133 MHz.
The problem is that Minecraft lags at specific points, however, during normal gameplay it works just fine.
The Squid, for example, stutter instead of moving fluently. This only applies to the Squid though.
Also, I experience a severe FPS drop when it starts raining, but this only troubles me when I have Vsync enabled, however, turing Vsync off isn't an option.
When I have Vsync disabled, my maximum framerate is about 150 FPS, with Vsync enabled, it's limited to 60.
When it rains and Vsync is disabled, my framerate varies between 80 to 100 FPS, however, when Vsync is enabled, My framerate drops to 30 FPS.
Finally, the game freezes for a moment when I set something on fire.
Especially the second problem troubles me, as my gameplay is impaired.
I've seen videos of people running Minecraft just fine with 1920 by 1080 resolutions, while I'm only using a 1280 by 1024 resolution, so higher framerates should be achievable.
Does anyone know what could cause these problems?

A: By now, I've found the source of the problem myself. My RAM clock speed was too high, causing the game to become unstable. 2400 MHz is apparently too much for the 7850K. Once I turned the clock speed down to 2133 MHz, Minecraft was stable again. My framerate, however, was still quite low. I could get a maximum of 30 FPS on minimal settings with an 8 chunk render distance, when my much older A8 5500 could reach at least 60 on these settings. I think the temperatures may be the cause of that, but I'm not sure. Anyways, I've bought an R7 360 GPU and now everything works fine. I'm still disappointed, though. I expected a lot more of the 7850K. I guess I should have bought an Athlon X4 860 instead.


text:
Q: MysqlDump is getting Error : ('mysql.infoschema'@'localhost') does not exist (1449) I am running a mysqldump in my centos 7 terminal which has my mysql server setup.(with working sites),
it shows the following errors.

mysqldump: Error: 'The user specified as a definer
('mysql.infoschema'@'localhost') does not exist' when trying to dump
tablespaces
mysqldump: Couldn't execute 'SHOW DATABASES': The user specified as a
definer ('mysql.infoschema'@'localhost') does not exist (1449)

then tried logged in as the root user and "SHOW DATABASES" I got the following error

ERROR 1449 (HY000): The user specified as a definer
('mysql.infoschema'@'localhost') does not exist

Also with the command "CREATE USER TEST" I get the error

ERROR 1726 (HY000): Storage engine 'MyISAM' does not support system

any directions?
Thanks.

A: Okay here is the solution.
I tried updating the MySQL by
yum update MySQL

it will only update the MySQL client so we need to update both client and the server
so I used

yum update mysql* -y

then it updates both of them. and the issue fixed now.
Thanks.


text:
Q: How to map column and entity propery of different datatypes in entity framework code first I am using Entity Framework 5 - Code first.
I have a database that I am connecting to that already exists for some time now (I did not create it).  There is a table called T_Customers.  It contains a list of all the customers.  It has the following structure (only partially shown):
Customer_id | numeric (5, 0) | auto increment | not null (not set as primary key)
FName | varchar(50) | not null
LName | varchar(50) | not null

My Customer class:
public class Customer : IEntity
{
     public int Id { get; set; }

     public string FirstName { get; set; }

     public string LastName { get; set; }
}

My IEntity interface:
public interface IEntity
{
     int Id { get; set; }
}

I have the following in my database context class:
public class DatabaseContext : DbContext
{
     public DatabaseContext(string connectionString)
          : base(connectionString)
     {
     }

     public DbSet<Customer> Customers { get; set; }

     protected override void OnModelCreating(DbModelBuilder modelBuilder)
     {
          modelBuilder.Configurations.Add(new CustomerConfiguration());
     }

     public new DbSet<TEntity> Set<TEntity>()
          where TEntity : class, IEntity
     {
          return base.Set<TEntity>();
     }
}

My customer configuration class:
class CustomerConfiguration : EntityTypeConfiguration<Customer>
{
     internal CustomerConfiguration()
     {
          this.ToTable("T_Customers");
          this.Property(x => x.Id).HasColumnName("Customer_id");
          this.Property(x => x.FirstName).HasColumnName("FName");
          this.Property(x => x.LastName).HasColumnName("LName");
     }
}

I'm trying to be consistent in my entity declarations, I need all the IDs to be integers.  This customer ID is of type numeric in the database, and now I am running into issues when trying to return a list of all the customers.  How do I map from a database numeric type to a C# integer type?  I'm not changing my class's ID to nullable or decimal, my IDs are always non nullable and integer.  I also cannot change the database.
The error that I am getting is:
The 'Id' property on 'Customer' could not be set to a 'Decimal' value.
You must set this property to a non-null value of type 'Int32'.

A: Specify numeric type for column
Property(x => x.Id).HasColumnName("Customer_id").HasColumnType("numeric");

When generating database, it will create numeric column with precision 18,0. But when you are mapping to existing database, it will work fine with 5,0 numeric column.

A: The simplest solution is to use another field that will be mapped to the database field, and the ID property will read/write to this field. Something like this:
public class Customer : IEntity
{
   public decimal CustomerID {get; set;}

   [NotMapped]
   public int Id
   {
      get { return (int)CustomerID; }
      set { CustomerID = (int)value; }
   }

   public string FirstName { get; set; }

   public string LastName { get; set; }
}

Map this new field to the database field, using
this.Property(x => x.CustomerID).HasColumnName("Customer_id");

and the EF will use the customer id field, and your code could happily use the integer id field.

A: In .Net Core you can also use System.ComponentModel.DataAnnotations.Schema.ColumnAttribute to annotate the property with the underlying column type, e.g.,
    [Column(TypeName = "numeric(5, 0), not null")]
    public int Id { get; set; }

Or if the column is nullable:
    [Column(TypeName = "numeric(5, 0), null")]
    public int? Id { get; set; }

I prefer this to the accepted answer by @Sergey Berezovskiy, as you make the annotation actually on the model, not in elsewhere (in the DbContext).
The ColumnAttribute can also be used to map a property to a column with a different name, e.g.,
    [Column("Identifier", TypeName = "numeric(5, 0), not null")]
    public int Id { get; set; }

The ColumnAttribute may also work in the .Net Framework - I have not tested it.

A: You can convert it to an int with:
 int myInt = Convert.Int32(numberFromDatabase);

A: Another option to work out what the code first should be is to the MS EF Powertools
http://visualstudiogallery.msdn.microsoft.com/72a60b14-1581-4b9b-89f2-846072eff19d
You can add an empty project, right click, EF Reverse engineer code first from DB.
You often (not always) get a good start to the solution.
Did you try using decimal?
public class Customer : IEntity
{
 public decimal Id { get; set; }

 public string FirstName { get; set; }

 public string LastName { get; set; }
}

if you are concerned precision, you should add validation to the POCO.
There are also some interesting Anotation hacks you may like.
http://geekswithblogs.net/danemorgridge/archive/2010/12/20/ef4-code-first-control-unicode-and-decimal-precision-scale-with.aspx
good luck


text:
Q: Preventing console from taking input while printing in java? I'm having trouble with a method I've made. It reads off from a text file, and prints the contents onto the console with a delay, however, while it's printing it can randomly take inputs from the user. Sometimes it intertwines with the contents it's printing. Is there a better way to do this?
public static void filePrint(String location) throws IOException, FileNotFoundException, InterruptedException {

        File flScannedFile = new File(location);

        Scanner scFileScanner = new Scanner(flScannedFile);

        while (scFileScanner.hasNext()) {

            String file = scFileScanner.nextLine();

            System.out.print(file);

            Thread.sleep(650);
        }
    }

A: The user on an IDE will always be able to write on the console, I think this is what is happening to you. The fact that there is a long sleep time is what makes you clearly see that. However, even if the user writes anything on the console, it shouldn't affect the global output.
One thing that I want to add, is that you might want to switch the print to println; and also, it would be better to use a try and catch rather than listing all those exceptions on the method name :)


text:
Q: Exporting Invoices from Magento I have been trying to export all of our invoices in a specific format for importing into Sage accounting.  I have been unable to export via Dataflow as I need to export the customer ID (which strangely is unavailable) and also a couple of static fields to denote tax codes etc…
This has left me with the option of using the API to export the data and write it to a CSV.  I have taken an example script I found (sorry can't remember where in order to credit it...) and made some amendments and have come up with the following:
<?php
    $website = 'www.example.com';
    $api_login = 'user';
    $api_key ='password';

function magento_soap_array($website,$api_login,$api_key,$list_type,$extra_info){
$proxy = new SoapClient('http://'.$website.'/api/soap/?wsdl');
$sessionId = $proxy->login($api_login, $api_key);

$results = $proxy->call($sessionId,$list_type,1);

if($list_type == 'order_invoice.list'){
    /***  INVOICES CSV EXPORT START ***/
    $filename = "invoices.csv";
    $data = "Type,Account Reference,Nominal A/C Ref,Date,Invoice No,Net Amount,Tax Code,Tax Amount\n";
    foreach($results as $invoice){
        foreach($invoice as $entry => $value){
            if ($entry == "order_id"){
                $orders = $proxy->call($sessionId,'sales_order.list',$value);
            }
        }
        $type = "SI";
        $nominal = "4600";
            $format = 'Y-m-d H:i:s';
            $date = DateTime::createFromFormat($format, $invoice['created_at']);
        $invoicedOn = $date->format('d/m/Y');
        $invoiceNo = $invoice['increment_id'];
            $subtotal = $invoice['base_subtotal'];
            $shipping = $invoice['base_shipping_amount'];
        $net = $subtotal+$shipping;
        $taxCode = "T1";
        $taxAmount = $invoice['tax_amount'];

        $orderNumber = $invoice['order_id'];
        foreach($orders as $order){
            if ($order['order_id'] == $orderNumber){
                $accRef = $order['customer_id'];
            }
        }
        $data .= "$type,$accRef,$nominal,$invoicedOn,$invoiceNo,$net,$taxCode,$taxAmount\n";
    }
    file_put_contents($_SERVER['DOCUMENT_ROOT']."/var/export/" . $filename, "$header\n$data");

    /***  INVOICES CSV EXPORT END ***/
}else{
        echo "nothing to see here";
    }/***  GENERIC PAGES END ***/
}/*** END function magento_soap_array ***/

if($_GET['p']=="1")
{
magento_soap_array($website,$api_login,$api_key,'customer.list','Customer List');
}
else if($_GET['p']=="2")
{
magento_soap_array($website,$api_login,$api_key,'order_creditmemo.list','Credit Note List');
}
else if($_GET['p']=="3")
{
magento_soap_array($website,$api_login,$api_key,'sales_order.list','Orders List');
}
else if($_GET['p']=="4")
{
magento_soap_array($website,$api_login,$api_key,'order_invoice.list','Invoice List');
}
?>

This seems to be working fine, however it is VERY slow and I can't help but think there must be a better, more efficient way of doing it…
Has anybody got any ideas?
Thanks
Marc

A: i think on put break; would be okey. because only one key with order_id, no need to looping after found order_id key.
if ($entry == "order_id"){
    $orders = $proxy->call($sessionId,'sales_order.list',$value);
    break;
}

and you can gather all call(s) and call it with multicall as example:
$client = new SoapClient('http://magentohost/soap/api/?wsdl');

// If somestuff requires api authentification,
// then get a session token
$session = $client->login('apiUser', 'apiKey');

$result = $client->call($session, 'somestuff.method');
$result = $client->call($session, 'somestuff.method', 'arg1');
$result = $client->call($session, 'somestuff.method', array('arg1', 'arg2', 'arg3'));
$result = $client->multiCall($session, array(
     array('somestuff.method'),
     array('somestuff.method', 'arg1'),
     array('somestuff.method', array('arg1', 'arg2'))
));

// If you don't need the session anymore
$client->endSession($session);

source


text:
Q: Flutter / Sim Data / Slot - Subscription id how get sim subscription id depend on sim slot flutter
I wan to handle my API Response BY using USSD and I have to Slot Which Slot in part of Response … the problem is  the   "UssdService.makeRequest(subscriptionId, code)" Function require subscriptionId of sim and I want to get this subscriptionId depend on slot number


text:
Q: Why do power stations use steam to drive turbines? Wouldn't it make more sense to use a liquid with a lower specific heat capacity/latent heat of vaporisation so that less energy was used up in converting the water to steam?

A: A lot have been tried (or at least suggested) historically - see Unusual Working Fluids eg. Ammonia, Petrol and Alcohol, Mercury, Chloroform, Carbon Disulphide, Potassium vapour
Even legitimate researchers have tried a few interesting compounds, eg. methanol, Freons or toluene.
Most are highly toxic or corrosive or explosive - or frequently all of the above !

A: I'd like to address the question in the body of your question:

Wouldn't it make more sense to use a liquid with a lower specific heat capacity/latent heat of vaporisation so that less energy was used up in converting the water to steam?

For larger power plants this is actually not an issue, because they use condensing turbines. These condense the steam back to water, which increases the pressure gradient and allows more work to be extracted. For a turbine of this type, much of the energy that goes into latent heat of vaporisation is returned as work, so it's not wasted.
Old-fashioned piston-based steam engines use a similar principle. At one time it was thought that simply using air might be more efficient, since it expands without any of the energy going into latent heat. It was this kind of question that led Sadi Carnot to develop the first principles of thermodynamics, and it was his work that showed that you could recover all the energy that goes into latent heat.
Of course, if your power plant uses a non-condensing type of turbine and simply releases steam into the atmosphere, then the energy in latent heat is indeed wasted. I suppose the choice of working fluid in that case is determined by needing something that expands a lot on heating, is readily available in large quantities, and won't explode, corrode the machinery or pollute the environment --- in this case water is quite likely the only practical choice. In practice, I believe the waste steam from non-condensing turbines is not usually directly released but instead is used for some other industrial process or to heat homes, in which case the latent heat is not really wasted either, even if it's not turned into work.


text: Q: Ошибка после обновления базы данных После добавления нового поля в базу.  При запуске программы возникает ошибка 'Базовая модель контекста изменилась с момента создания базы данных. Рассмотрите возможность обновления базы данных с помощью Code First Migration. Но новое поле как раз и было добавлено таким способом. Подскажите пожалуйста что с этим делать.


text:
Q: Setting Current Node to Null? I've been practicing problems on Cracking the Coding Interview and I came up with a solution to a problem asking to remove a middle node in a linked list.
 public void deleteMidNode(Node mid){
    if(mid == head || mid.next==null){
        return;
    }
    Node current = mid;
    while(current.next.next!=null){
        current.data = current.next.data;
        current = current.next;
    }
    current.next = null;
}

Now this code does work - I've tested it. However, I'm curious as to why I can set current.next to null, but if I was to do this it doesn't work:
 public void deleteMidNode(Node mid){
    if(mid == head || mid.next==null){
        return;
    }

    Node current = mid;
    while(current.next!=null){
        current.data = current.next.data;
        current = current.next;
    }
    current = null;
}

Can anyone tell me why I can't set a current node to null?

A: To answer your question, because it's an example of dead code. It's a local variable, so as the final write to it is not later read by any code, it will have no effect on the program.
That is:
    current = null;
    //there are no reads of "current" here before:
} //the end of method which is the end of scope for the local "current"

A decent IDE would be hinting to you that this write was not read, by, for example, graying out, underlining or otherwise highlighting the dead code.
I don't think it's worth analyzing your code too closely though as it's totally wrong I'm afraid, removing an item from a linked list should be a O(1) constant time procedure (at least once you have the node and previous node located). You are moving the data around, causing it to be O(n), meaning it's no more efficient than removing from an array of data.
Given this:
node1 -> node2 -> node3 -> node4
  |        |        |        |
data1    data2    data3    data4

Removing node2, should go to:
node1 -> node3 -> node4
  |        |        |
data1    data3    data4

But you move the data around as though shuffling items along in an array. This causes it to be:
node1 -> node2 -> node3
  |        |        |
data1    data3    data4

current.data should never need to be reassigned for any linked list operation.

A: Is your list doubly-linked? In that case, you can just do
if (mid != null) {
    mid.prev.next = mid.next
    mid.next.prev = mid.prev
}

and let garbage collection do its magic.
In any case, to answer your question, realize that variables for objects (such as Node) in Java are always references (pointers).
In your function, current is a variable that points to a Node object. If you set it to null, it doesn't point anywhere. But that doesn't change the structure of the list.

A: If it's a double linked list we need to just link mid.pre to mid.next, if it's singleLinked List we need to traverse from beginning to mid (we need previous node Prv.next = mid) and just replace prv.next = mid.next.
Question: In both of your solutions how can we traverse from head after removing mid Node?

A: I don't get it why it is not giving the compilation error first of all for the below code:
current = current.next;

This should give compilation error, since you are assigning a node pointer to a node.
When I run the same function while passing the pointer it works.
#include<stdio.h>
#include<malloc.h> // C library to handle malloc functions

struct node{ // struct node declaration
    int data;
    struct node* link;
};
void deleteNode(struct node*);
void printList(struct node*);
int main(){
    struct node* head;
    struct node* first;
    struct node* second;
    struct node* third;
    struct node* fourth;
    struct node* fifth;
    struct node* sixth;
    head = (struct node*)malloc(sizeof(struct node));
    first = (struct node*)malloc(sizeof(struct node));
    second = (struct node*)malloc(sizeof(struct node));
    third = (struct node*)malloc(sizeof(struct node));
    fourth = (struct node*)malloc(sizeof(struct node));
    fifth = (struct node*)malloc(sizeof(struct node));
    sixth = (struct node*)malloc(sizeof(struct node));
    head->link = first;
    first->link = second;
    second->link = third;
    third->link = fourth;
    fourth->link = fifth;
    fifth->link = sixth;
    sixth->link = NULL;
    head-> data = 1;
    first-> data = 2;
    second-> data = 3;
    third-> data = 4;
    fourth-> data = 5;
    fifth-> data = 6;
    sixth-> data = 7;
    printList(head);
    deleteNode(second);
    printList(head);
}
void printList(struct node* head){
    struct node* node = head;
    while(node->link!= NULL){
        printf("%d\n",node->data);
        node= node->link;
    }
}
void deleteNode(struct node* kid){
    struct node* mid = kid;
    while(mid->link!= NULL){
        mid->data = mid->link->data;
        mid = mid->link;
    }
    mid = NULL;
}


text:
Q: 404 not found laravel 5.2 after publish on server i got error 404 not found on laravel 5.2 after i deployed my project on ubuntu server 16.04
i gave permission to storage and too i created virtual host and its directory on public folder of my project
Not Found
The requested URL /login was not found on this server.

Apache/2.4.18 (Ubuntu) Server at www.xxx.com Port 80

the laravel home page show but nothing work like login and register

A: i got the answer
you should run this on server:

a2enmod rewrite

that worked perfectly! xD


text:
Q: Processing output of python file called inside a bash script this is just the beginning of the fun that I'm going to have with bash scripting
for some reason it always returns Fail..
And I don't know why, it has been a looooooooong time that I have done bash scripting but this doesn't seem to work.
#!/bin/bash

python /var/lib/scripts/Hudson.py result
if test "$result" = "Success"
then
     echo "Done"
else
     echo "Fail"
fi

The python file returns either Success or Fail
if someone can point me in the right direction for this that would be greatly appreciated.
Thanks, Robert.
PS. The python file converts a XLSM file to CSV which is already working properly.

A: If you mean the output of python, you should test it with $() instead
#!/bin/bash

if test "$(python /var/lib/scripts/Hudson.py result)" = "Success"
then
     Run next command
else
     Exit the script
fi

And it's actually better with [[ ]]
#!/bin/bash

if [[ "$(python /var/lib/scripts/Hudson.py result)" == "Success" ]]
then
     Run next command
else
     Exit the script
fi

If you mean the exit code:
#!/bin/bash

if python /var/lib/scripts/Hudson.py result
then
     Run next command
else
     Exit the script
fi


text:
Q: Remove nodes after moving off screen Here is a newbie question. I am trying to remove nodes "rocks" after the fall off screen. This is what I applied in GameScene.m to which the nodes are added.
    -(void)update:(CFTimeInterval)currentTime {
[self enumerateChildNodesWithName:@"rock" usingBlock:^(SKNode *node, BOOL *stop) {
    if (node.position.y < 0) {
        [node removeFromParent];
    }
}];

}
This looks fine, however I get error:
Terminating app due to uncaught exception 'NSGenericException', reason: '* Collection <__NSArrayM: 0x608000046360> was mutated while being enumerated.'
I know what it means but how else can I remove nodes?
Context: I am following Sprite Kit Programming Guide from Apple.

A: You could run a remove action on the nodes:
[node runAction:[SKAction removeFromParent]];


text:
Q: Further examples of stalks I am currently learning about stalks for the first time. In my exploration online about the topic, I routinely run into the same three examples:

*

*In a constant sheaf associated with an abelian group $A$, any stalk is isomorphic to $A$.

*In the sheaf of real-valued continuous functions, stalks are all germs at the given point.

*In the sheaf of complex-analytic functions, stalks are all germs at the given point.

I understand why these examples are ubiquitous. Stalks are about local behavior, and germs are an example of functions locally behaving the same being identified. Great!
That said, I would love to see more examples of stalks outside of these.

A: Here are some examples that might be helpful to calculate to get more experience/intuition:

*

*Let $X$ be a topological space, and let $x\in X.$ Let $i : \{x\}\to X$ be the inclusion of $x$ into $X.$ Let $A$ be any set, and let $\underline{A}$ be the constant sheaf with value $A$ on $\{x\}.$ Then $i_\ast\underline{A}$ is called a skyscraper sheaf, and $\left(i_\ast\underline{A}\right)_y = A$ if $y\in\overline{\{x\}},$ and $\left(i_\ast\underline{A}\right)_y = \{\ast\}$ otherwise.

*Let $X$ be a topological space, $Z\subseteq X$ be a closed subset, $i : Z\to X$ be the inclusion of $Z$ into $X,$ and $\mathcal{F}$ a sheaf (of sets) on $Z.$ Then $(i_\ast\mathcal{F})_x = \mathcal{F}_x$ if $x\in Z,$ and $(i_\ast\mathcal{F})_x = \{\ast\}$ otherwise.

*Let $f : X\to Y$ be a continuous map of topological spaces, and let $\mathcal{F}$ be a sheaf on $Y.$ Then for any $x\in X,$ $\left(f^{-1}\mathcal{F}\right)_x\cong\mathcal{F}_{f(x)}.$

*You can also check that if $\mathcal{F}$ is a sheaf on $X,$ and $i : \{x\}\to X$ is the inclusion of a point, then $i^{-1}\mathcal{F}$ is the constant sheaf associated to $\mathcal{F}_x$ on $\{x\}.$

*You can find an example of a continuous map of spaces $f : X\to Y,$ a point $x\in X,$ and a sheaf $\mathcal{F}$ on $X$ such that $\left(f_\ast\mathcal{F}\right)_{f(x)}\not\cong\mathcal{F}_x.$

*If $\mathcal{F}$ is a quasicoherent sheaf on a scheme $X,$ then $\mathcal{F}_x = M_\frak{p},$ where $\operatorname{Spec}A = U\subseteq X$ is an affine open containing $x,$ $\mathfrak{p}\subseteq A$ is the prime ideal of $A$ corresponding to $x,$ and $M = \Gamma(U,\mathcal{F}).$

*A special case of the last example is when $\mathcal{F} = \mathcal{O}_X$ is the structure sheaf of $X.$ In this case, $\mathcal{O}_{X,x} = A_\mathfrak{p},$ where $x, A,$ and $\mathfrak{p}$ are as before.


text:
Q: Collection: filter by created_at by local time zone? (or CreatedAtStoreDate) I have to filter a collection (invoice) by date to get all invoices of one month.
For example: the create_at date of one invoice (in database) is: 2014-04-30 22:27:30
If I filter the collection:
    $dateFrom = '2014-04-01 00:00:00';
    $dateTo = '2014-04-30 23:59:59';
    $invoiceCollection->addAttributeToFilter('created_at', array(
        'from' => $dateFrom,
        'to' => $dateTo,
    ));

The invoice with this date will be in the collection.
There exists two kinds of dates:
$invoice->getCreatedAt()

And:
$invoice->getCreatedAtStoreDate()

In this case:
$invoice->getCreatedAt() = 2014-04-30 22:27:30 (UTC/GMT time)
$invoice->getCreatedAtStoreDate() = 2014-05-01 00:27:40 (local timezone)

Under Sales->Invoices "my" invoice will be collect under May. If I use
 $invoiceCollection = Mage::getModel('sales/order_invoice')->getCollection();

the invoice is in "April".
So I have to filter my collection by CreatedAtStoreDate - but this is not a database-field.
My question:
How can I filter the order or invoice collection by CreatedAtStoreDate, so that the invoice or order with the date 2014-04-30 22:27:30 will be NOT in my April-Collection but in May?
Thanks for help.

A: You can use some GET param to define local offset, then add this offset to dates in filter. It will something like this (I didn't test it):
/**
 * GET param which allow to set offset between local and server timezone. Server timezone is GMT.
 * Examples: add ?gmt=2 in URL for set local time to GMT+2, ?gmt=-5 for GMT-5, etc.
 */
$gmt_offset = (int)Mage::app()->getRequest()->getParam('gmt');
$dateFrom = '2014-04-01 00:00:00';
$dateTo = '2014-04-30 23:59:59';

if($gmt_offset > -13 && $gmt_offset < 15 && $gmt_offset != 0){
    $locale = Mage::app()->getLocale()->getLocaleCode();
    $date_from = new Zend_Date(strtotime($dateFrom), Zend_Date::TIMESTAMP, $locale);
    $date_to = new Zend_Date(strtotime($dateTo), Zend_Date::TIMESTAMP, $locale);

    if($gmt_offset > 0){
        $date_from->add($gmt_offset, Zend_Date::HOUR);
        $date_to->add($gmt_offset, Zend_Date::HOUR);
    }else{
        $date_from->sub($gmt_offset, Zend_Date::HOUR);
        $date_to->sub($gmt_offset, Zend_Date::HOUR);
    }

    $dateFrom = $date_from->get('YYYY-MM-dd HH:mm:ss');
    $dateTo = $date_to->get('YYYY-MM-dd HH:mm:ss');
}

$invoiceCollection->addAttributeToFilter('created_at', array(
    'from' => $dateFrom,
    'to' => $dateTo,
));


text:
Q: Where can I find the specification about the upcoming i3 Skylake processors? I saw that i3-6100, i3-6200, i3-6300, i3-6320 ... is coming in September, but no more details about it. Where can I find more information (frequency, cache, hyperthreading, ...)?

A: A month later the specs are now officially available on ARK.


text:
Q: Using ingress to access external service with contextPath I have a Wildfly with a set of applications, not running in the kubernetes cluster.
Lets say one is http://wildfly-external/FOO/
From within the cluster, I want that my cluster applications can reach FOO without knowing the contextPath on the wildfly.
Our approach was to generate a Endpint, Service and an Ingress for this Service containing the path
service.yaml
apiVersion: v1
kind: Service
metadata:
    annotations:
        meta.helm.sh/release-name: dns
        meta.helm.sh/release-namespace: test
    creationTimestamp: "2020-08-31T17:32:08Z"
    labels:
        app.kubernetes.io/instance: dns
        app.kubernetes.io/managed-by: Helm
        app.kubernetes.io/name: foo
        helm.sh/chart: dns-1.0.0-snapshot
    name: foo
    namespace: test
    resourceVersion: "151848872"
    selfLink: /api/v1/namespaces/test/services/foo
    uid: e5607cd4-ebaf-11ea-9f17-005056a7cff9
spec:
    clusterIP: 10.200.149.146
    ports:
        - name: foo
          port: 80
          protocol: TCP
          targetPort: 13000
    sessionAffinity: None
    type: ClusterIP
status:
    loadBalancer: {}

ingress.yaml
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
    annotations:
        meta.helm.sh/release-name: dns
        meta.helm.sh/release-namespace: test
    creationTimestamp: "2020-08-31T17:32:08Z"
    generation: 1
    labels:
        app.kubernetes.io/instance: dns
        app.kubernetes.io/managed-by: Helm
        app.kubernetes.io/name: foo
        helm.sh/chart: dns-1.0.0-snapshot
    name: foo
    namespace: test
    resourceVersion: "151848901"
    selfLink: /apis/extensions/v1beta1/namespaces/test/ingresses/foo
    uid: e56cc8c9-ebaf-11ea-9f17-005056a7cff9
spec:
    rules:
        - http:
              paths:
                  - backend:
                        serviceName: foo
                        servicePort: http
                    path: /FOO
status:
    loadBalancer:
        ingress:
            - ip: 10.6.1.1

Unfortunately when curl http//foo/ inside a pod, I reach the wildfly start page at http://wildfly, not the application at http://wildfly/FOO.
This looks like I access the service through http://foo/ and not going through the ingress.
Is it possible to do, what I want to do? Any hints?

A: From my view, the ingress is on top of service.
The sequence is browser->ingress(application load balance)->service. Now the url http//foo/ is to access service instead of ingress. You can use ingress to mapping context to service with ingress rewrite, but you need visit url with full host name of ingress.
Thanks,


text:
Q: PHP concatenation not working properly So i'm trying to build a pagination for my website without refreshing the page.
I'm using ajax, php and mysql for that purpose.
At  the moment i'm stuck with php, specifically with foreach and concatenation.
Here's my foreach loop:
if (isset($_POST['page'])) {
    $algus = $_POST['page'];
    $loos = '';
    $mitu = 5;
    $msg = [];

    foreach (uritused($conn, $id, $algus, $mitu) as $key => $vals) {
        $loos .= "
";
        $loos .= ''.$vals['eventi_nimi'].'
'.$vals['owner'].'	';
        $loos .= ''.$vals['loosiAeg'].'	';
        $loos .= ''.$vals['attendiloos'].'	';
        $loos .= '';
        if (is_array($vals['auhinnad'])) {
            foreach($vals['auhinnad'] as $keys => $val){
                $loos .= $val['auhind'].'
';
            }
        } else {
            $loos .= $vals['auhinnad'];
        }
        $loos .= '	';
        $loos .= 'Postitus: '.$vals['tingimused']['postitus'].'
Osalus: '.$vals['tingimused']['osalus'].'	';
        $loos .= '';
        if (is_array($vals['valista'])) {
            foreach($vals['valista'] as $keys => $val){
                $loos .= $val['nimi'].'
';
            }
        } else {
            $loos .= $vals['valista'];
        }
        $loos .= '	';
        $loos .= '
    radio_button_checked	';
        $loos .= "
";
    }
    $msg['data'] = $loos;
    $msg['success'] = true;

    echo json_encode($msg);
}

Here's my ajax call
var page = 1;
$.ajax({
   type: "POST",
   url: "pages/php/loosid_data.php",
   cache: false,
   dataType: 'json',
   data: {'page': page},
   success: function(msg){
   console.log(msg);
     if(msg['success']){
       $('.tr-data').remove();
       $('.m-loosid table').append(msg['data']);
     }
   },
   error: function(msg){
   console.log(msg);
 }
 });

EDIT: Heres the function
function uritused($conn, $id, $algus, $mitu){
try{
  $uritused = $conn->prepare("SELECT COUNT(*) FROM loosid WHERE usr_id='$id'");
  $uritused->execute();
}catch(PDOException $e){
  echo $e->getMessage();
}
$uritus_arr = [];
$count = $uritused->fetchColumn();
if($count > 0){
  try{
    $urituseds = $conn->prepare("SELECT * FROM loosid WHERE usr_id='176237127636' ORDER BY loosiAeg DESC LIMIT 1, 5");
    $urituseds->execute();
  }catch(PDOException $e){
    echo $e->getMessage();
  }
  $uritus = $urituseds->fetchAll();
    for ($z=0;$z<$count;$z++) {
      $uritus_arr[$z] = array(
        'eventi_nimi' => $uritus[$z]['eventi_nimi'],
        'loosiAeg' => $uritus[$z]['loosiAeg'],
        'tingimused' => array(
          'postitus' => $uritus[$z]['post'],
          'osalus' => $uritus[$z]['osalus']
        ),
        'sec' => $uritus[$z]['sec'],
        'staatus' => $uritus[$z]['staatus'],
        'attendiloos' => $uritus[$z]['attendiloos']
      );
      $auhinnad = explode(',', $uritus[$z]['auhinnad']);
      if($uritus[$z]['auhinnad'] != '-'){
        foreach ($auhinnad as $key) {
            $auhind = explode('-', $key);
            $auhinna_arr[] = array(
              'auhind' => $auhind[0],
              'voitjad' => $auhind[1]
            );
        }
        $uritus_arr[$z]['auhinnad'] = $auhinna_arr;
      }else{
        $uritus_arr[$z]['auhinnad'] = $uritus[$z]['auhinnad'];
      }

      $valista = explode(',', $uritus[$z]['valista']);
      if($uritus[$z]['valista'] != '-'){
        foreach ($valista as $keys) {
            $valistad = explode('-', $keys);
            $valista_arr[] = array(
              'nimi' => $valistad[0],
              'id' => $valistad[1]
            );
        }
        $uritus_arr[$z]['valista'] = $valista_arr;
      }else{
        $uritus_arr[$z]['valista'] = $uritus[$z]['valista'];
      }

      $valista_arr = [];
      $auhinna_arr = [];
    }

}
return $uritus_arr;
}

THIS NOW GIVES ME UNDEFINED OFFSET, ALTHOUGH I KNOW THAT THERE'S DATA WITH THAT INFO IN THE DB.
For some reason the data is always empty.

Whenever i try to run this same code inside my page directly without ajax, everything works as it should.
Maybe you guys have any suggestions on how to fix this? I know that there's already same kind of posts out here but i haven't found my answer yet.

A: @Gino Pane
I'm sorry but thats not the case actually. It seems that i made a rookie mistake with my query. I have only one instance of data in the database but my limit is set to 1, 5 but it should be 0, 5.
Basically my query was looking data from the database starting at 1 when it should've started at 0. Thats why it seemed to me that there is no data in the database.
I also said that when i echo foreach directly on the page it works because i had more than 1 instance of data in the database at that time.
Sorry for wasting your time guys.


text:
Q: this table isnt working in oracle apex can someone help me figure out why this table isnt working in oracle apex can someone help me figure out why
CREATE TABLE booking (
Booking_ID int GENERATED BY DEFAULT AS IDENTITY  NOT NULL,
Guest_ID int NOT NULL,
Room_ID int  NOT NULL,
Employee_ID int NOT NULL,
booking_date date NOT NULL,
booking_time timestamp NOT NULL,
booking_desc varchar(100) NOT NULL,
constraint GuestID_FK  references guest(Guest_ID),
constraint RoomID_FK  references room(Room_ID),
constraint EmployeeID_FK  references employee(Employee_ID),
primary key(Booking_ID));

A: It helps if you specify which error(s) you got when you ran this code.
As table references some other tables, I'll first create them (so that foreign key constraints wouldn't fail because of that); I'll create dummy tables with only primary key columns:
SQL> create table guest (guest_id int primary key);

Table created.

SQL> create table room (room_id int primary key);

Table created.

SQL> create table employee (employee_id int primary key);

Table created.

OK; now, your code:
SQL> CREATE TABLE booking (
  2  Booking_ID int GENERATED BY DEFAULT AS IDENTITY  NOT NULL,
  3  Guest_ID int NOT NULL,
  4  Room_ID int  NOT NULL,
  5  Employee_ID int NOT NULL,
  6  booking_date date NOT NULL,
  7  booking_time timestamp NOT NULL,
  8  booking_desc varchar(100) NOT NULL,
  9  constraint GuestID_FK  references guest(Guest_ID),
 10  constraint RoomID_FK  references room(Room_ID),
 11  constraint EmployeeID_FK  references employee(Employee_ID),
 12  primary key(Booking_ID));
constraint GuestID_FK  references guest(Guest_ID),
                                       *
ERROR at line 9:
ORA-00907: missing right parenthesis

SQL>

Aha. So, what's wrong with it? It is an outline constraint clause which has to follow certain syntax.
SQL> create table booking (
  2  booking_id   int generated by default as identity,
  3  guest_id     int not null,
  4  room_id      int not null,
  5  employee_id  int not null,
  6  booking_date date not null,
  7  booking_time timestamp not null,
  8  booking_desc varchar2(100) not null,
  9  constraint guestid_fk    foreign key (guest_id)    references guest(guest_id),
 10  constraint roomid_fk     foreign key (room_id)     references room(room_id),
 11  constraint employeeid_fk foreign key (employee_id) references employee(employee_id),
 12  constraint booking_pk primary key (booking_id));

Table created.

SQL>

Or, you could use inline constraints:
SQL> create table booking (
  2  booking_id   int generated by default as identity constraint pk_book primary key,
  3  guest_id     int constraint fk_book_guest references guest (guest_id) not null,
  4  room_id      int constraint fk_book_room  references room (room_id) not null,
  5  employee_id  int constraint fk_book_emp   references employee (employee_id) not null,
  6  booking_date date not null,
  7  booking_time timestamp not null,
  8  booking_desc varchar2(100) not null);

Table created.

Note that

*

*you don't have to specify NOT NULL constraint for primary key columns; they can't accept null by definition

*it is always a good idea to name constraints; you don't have to, but Oracle then creates system-generated names (such as SYS_C008464) which tell you nothing

*Oracle recommends us to use varchar2 instead of varchar datatype

*you probably don't need both booking_date and booking_time; one column would do: booking_date date as date datatype in Oracle contains both date and time; timestamp - if you meant to use it for time only - shouldn't be used for that purpose as it doesn't contain time only; it contains date and time (with fractional seconds). Do you need to know booking time with such a precision? I, somehow, doubt it


text:
Q: Zipfile with no parent folder I am able to compress files into a single zip file, however when I open the zip file the contents always include a "parent folder" which has the same exact name as the zip file itslef.
I'm simply trying to create a zip file that contains no folders at all.
Current: abc.zip > abc (folder) > files
Looking for: abc.zip > files
def create_zip(file_name, file_dir):
    """
    Function to create zip archive
    """
    os.chdir(file_dir)
    zipfiles_list = ['csv', 'txt']
    file_name_part = file_name
    zip_name = '{0}.zip'.format(file_name_part)
    with zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED) as
    zip_archive:
        for file_extension in zipfile_list:
            full_file_path = '{0}.{1}'.format(file_name_part, file_extension)
            zip_archive.write(full_file_path, basename(full_file_path))

Is this possible? I've seen that if I rename the zip file after it's created, it will still extract contents into a folder that matches the zip file name.
Original zip extracts to abc folder
Renamed same exact zip and contents extract to folder with new name

A: In your code you have a mistake in a word 'zipfiles': for file_extension in zipfile_list: (without 's' in the end).
It have to be for file_extension in zipfiles_list:.
Than I run your code in Win7x86 - it is OK, no inner folder (python 3.6.6).
Tried it on Win 10x64 - same.
Xubuntu 18.04 x64 - same, without folder.
Here is my script:
from os.path import basename
from os import path
import os
import zipfile

# current directory
script_dir = path.dirname(path.abspath(__file__))

def create_zip(file_name, file_dir):
    """
    Function to create zip archive
    """
    os.chdir(file_dir)
    zipfiles_list = ['csv', 'txt']
    file_name_part = file_name
    zip_name = '{0}.zip'.format(file_name_part)
    with zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED) as zip_archive:
        for file_extension in zipfiles_list:
            full_file_path = '{0}.{1}'.format(file_name_part, file_extension)
            zip_archive.write(full_file_path, basename(full_file_path))

create_zip("first", script_dir)

In a directory with script there two files: first.txt and first.csv. After runing this scrip I do have zip file first.zip with two files inside: first.txt and first.csv.


text:
Q: Trying to switch directories in Azure I am trying to switch directories in Azure but it prompts me to approve the request on the authenticator application. However, I have removed that entry from the authenticator application.

When i try to sign a different way it still prompts me to use the authenticator app

A: It seems that you did not set a phone number at the last step when you added the authenticator.
So, just as @juunas mentioned in the comment, you need to contact other admins to reset your MFA settings from Azure portal:

A: You can set up your Authenticator again going to: https://aka.ms/mfasetup but you probably need to have your AAD administrator Require re-register MFA again since you wont be able to login there without the MFA if you are not already logged in.


text:
Q: PHP: Nested json and value extraction I have this json below. I'm trying to get values using json_decode. I'm getting some of the values, but I'm having trouble with the deeply nested values. Here is the json:
{
"startAt": 0,
"issue": [
{
    "id": "51526",
    "fields": {
        "people": [
            {
                "name": "bob",
                "emailAddress": "bob@gmail.com",
                "displayName": "Bob Smith",
            },
            {
                "name": "john",
                "emailAddress": "john@gmail.com",
                "displayName": "John Smith",
            }
        ],
        "skill": {
            "name": "artist",
            "id": "1"
        }
    }
},
{
    "id": "2005",
    "fields": {
        "people": [
            {
                "name": "jake",
                "emailAddress": "jake@gmail.com",
                "displayName": "Jake Smith",
            },
            {
                "name": "frank",
                "emailAddress": "frank@gmail.com",
                "displayName": "Frank Smith",
            }
        ],
        "skill": {
            "name": "writer",
            "id": "2"
        }
    }
}
]

}

I know I can get one value by doing this:
foreach ($decoded_array['issue'][0]['fields']['people'] as $person) {
  echo $person['emailAddress'];
}

However, is there a simplistic way to get all the "emailAddresses" for bob,john,jake, and frank?
Thanks!

A: The easiest way really is just to loop, but nest loops first at $decoded_array['issue'] and then an inner loop over ['people'].  Collect your addresses into an output array.
// Note: this assumes you called json_decode() with the second
// param TRUE to force an associative array..
// $decoded_array = json_decode($input_json, TRUE);

$addresses = array();
foreach ($decoded_array['issue'] as $i) {
  foreach ($i['fields']['people'] as $person) {
    // Append the address onto an output array
    $addresses[] = $person['emailAddress'];
  }
}
// De-dupe them if necessary
$addresses = array_unique($addresses);
print_r($addresses);

// Prints
Array
(
    [0] => bob@gmail.com
    [1] => john@gmail.com
    [2] => jake@gmail.com
    [3] => frank@gmail.com
)

A slightly fancier method if you weren't certain of the structure except that the keys are named emailAddress would be to use array_walk_recurisve() to traverse the array looking for that key. This will collect all keys named emailAddress, not just those inside the ['people'] subarrays.
$addresses = array();
// Pass $addresses into the closure by reference so you can write to it
array_walk_recursive($decoded_array, function($value, $key) use (&$addresses) {
  // Find *all keys* called emailAddress
  if ($key == 'emailAddress') {
    $addresses[] = $value;
  }
});

A: Try:
function people($peopleArray, $searchProperty, $forValueArray){
  $fva = array_map('strtolower', $forValuArray);
  foreach($peopleArray as $v){
    $sp = $v[$searchProperty]; $sl = strtolower($sp);
    if(in_array($sl, $fva)){
      $q[] = $sp;
    }
  }
  return isset($q) ? $q : 0;
}
if($ans = people($decoded_array, 'emailAddress', array('bob', 'john', 'jake', 'frank'))){
  print_r($ans);
}
else{
  echo 'no results found';
}

A: Script:
$json = "......"                                          //Your json text.
$decoded_array = json_decode($json)->{'issue'};           //Decode Json string
foreach($decoded_array as $issue){                        //Get all Issues
    foreach($issue->{'fields'}->{'people'} as $person){   //Get all people
        echo $person->{'emailAddress'}."<br/>";           //Get person's email
    }
}

OutPut:
bob@gmail.com
john@gmail.com
jake@gmail.com
frank@gmail.com

live example:
http://codepad.org/R1K0Lysi


text:
Q: linux: how to batch rename folder name and the file name under folder I need a help to finish a script to rename a folders and .
eg: my current folders and files like below:
Gideon/gideon_lisha/Gideon_samuel/Gideon_nathan.xml
Gideon/lisha_gideon/Gideon_noah.xml
...

I want a shell command to rename them like below:
Liang/Liang_lisha/Liang_samuel/Liang_nathan.xml
Liang/lisha_Liang/Liang_noah.xml
...

I tied:
#!/bin/bash

path=$1
filename=$2
newfilename=$3

echo "We are finding '$filename' under the folder '$path'"

count=1

for i in `find $path -iname *$filename*`

do
    newpath=`echo $i | sed "s/$filename/$newfilename/g"`
    sudo mv "$i" "$newpath"
    echo "${count}: Renaming $i to $newpath"
    let count++
done

but the script will stop to:
Liang/gideon_lisha/Gideon_samuel/Gideon_nathan.xml

because it changed the folder name, so that can not find the next path. I do not know how let the script run from inner to outer instead of running outer to inner.

A: finally, I found out the anwser:
#!/bin/bash

path=$1
filename=$2
newfilename=$3

echo "We are finding '$filename' under the folder '$path'"

count=1
for i in `find $path -iname "*$filename*" | tac`
do
    newpath=`echo $i | sed "s@\(.*\)$filename@\1$newfilename@i"`
    sudo mv "$i" "$newpath"
    echo "${count}: Renaming $i to $newpath"
    let count++
done

really thank @susbarbatus !


text:
Q: sql server 2008 how do i disconnect everyone from my db? I need to rename the database, but I cannot since other processes is using it. I don't care about the process, and I need to kill it.
How do I remove all connections from the db?

A: Like this: Kill All Active Connections To A Database
ALTER DATABASE oldNameSET SINGLE_USER WITH ROLLBACK IMMEDIATE

EXEC sp_renamedb 'oldName', 'newName'

ALTER DATABASE newName SET MULTI_USER  --new name of course

A: As per my comment once in single_user mode you need to do the rename from the same connection. Don't try and rename it through Object Explorer as that will try and open up a new connection. The following works this end...
ALTER DATABASE AdventureWorks SET single_user WITH ROLLBACK IMMEDIATE

ALTER DATABASE AdventureWorks MODIFY NAME = NewAdventureWorks

ALTER DATABASE NewAdventureWorks SET multi_user

A: Run sp_who, then kill [pid] for everyone in your database.

A: This worked fine for me to rename database and force disconnect everybody:
ALTER DATABASE [old_name]
    SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
ALTER DATABASE [old_name]
    MODIFY NAME = [new_name]
GO
ALTER DATABASE [new_name]
    SET MULTI_USER
GO


text:
Q: text channel perms in discord.py? How do I change the channel permissions to specific roles in discord.py?
I've got this:
@commands.command()
async def change_perms(self, ctx, role):
    ctx.channel.set_permissions(ctx.guild.role, send_messages=true)

but it no work

A: Seems like you're doing a few things wrong.
Use TextChannel.set_permissions:
@commands.command()
async def change_perms(self, ctx):

    await ctx.channel.set_permissions(ctx.guild.default_role,send_messages=False)

That might work :)


text:
Q: React Admin - Get additional parameter from server and pass to List view props We get "total" and "data" from getList which is passed to List view. I want to show additional data Aside of list view, Eg. total sell, total amount etc. I can pass those data from server but it seems react admin ignore those parameters. How can i accept those parameters from server and pass to Aside props in List view?

A: If the API is RESTful, adding additional data to the response would break REST principles. You could expose a different endpoint for such "summary" information and call it form a custom component.


text:
Q: Synchronous/Blocking Application.Invoke() for GTK# Unfortunately, Application.Invoke() is asynchronous:
private string ThreadFunction(int i)
{
    string result = null;

    Gtk.Application.Invoke(delegate
    {
        OutputStringToUserInterface("i = " + i.ToString());
        result = GetStringFromUserInterface();
    });

    return result;
}

This means that in this example ThreadFunction() proceeds immediately after calling Application.Invoke(), resulting in an probably undefined state of the result string. -- Typically ThreadFunction() will be faster and will return with the old value (i.e. null).

This is a workaround using ManualResetEvent to make Application.Invoke() synchronous:
private string ThreadFunction(int i)
{
    string result = null;

    using (var ev = new ManualResetEvent(false))
    {
        Gtk.Application.Invoke(delegate
        {
            OutputStringToUserInterface("i = " + i.ToString());
            result = GetStringFromUserInterface();

            ev.Set();
        });

        ev.WaitOne();
    }

    return result;
}

This way, ThreadFunction() waits until Application.Invoke() returns, like it would do using WinForms Control.Invoke().
EDIT: Better example code
EDIT2: Add missing using

Now my question: Is there a better solution?

A: Well, yes, there's no reason to wait for the delegate to execute to get the proper return value.  Fix:
int result = i + 1;

And it's okay to let the OutputStringToUserInterface() execute asynchronously, assuming you don't call ThreadFunction() so often that it floods the UI thread with requests.
If your real code actually depends on a return value from a function that must run on the UI thread then, no, you can't make it faster.  Clearly, that's something you really want to avoid.

A: You can encapsulate your current code into a generic wrapper:
public static void GuiInvoke(Action action)
{
    var waitHandle = new ManualResetEventSlim();
    Gtk.Application.Invoke( (s,a) =>
                            {
                                action();
                                waitHandle.Set();
                            });
    waitHandle.Wait();
}

public static void BeginGuiInvoke(Action action)
{
    Gtk.Application.Invoke( (s,a) => {action();});
}


text:
Q: Access Violation While looping through array and threading I was playing around with Threading in windows and made up this example, it should add all positions of a 128Mb array. I create x threads to compute the sum, so i divide the array in x peaces and have each thread compute one of those peaces. It all works well until i try to create more than 64 threads. For example if i create 65 threads i get an access violation in my add function. My guess is that it's an array out of bound, i just can't understand why after 64 threads i get this error.
#include <windows.h>
#include <tchar.h>
#include <strsafe.h>

#define MAX_ARRAY_SIZE 128 * 1024 * 1024
#define MAX_THREADS_BUFFER 512

DWORD dwSampleData[MAX_ARRAY_SIZE];
DWORD dwTotal;

DWORD WINAPI DoWork(LPVOID lpParam);
void ErrorHandler(LPTSTR lpszFunction);
VOID InitializedwSampleData();
VOID CreateThreadsAndDoWork(DWORD MaxThreads, DWORD dwPrintIntermediateResults);

typedef struct _THREAD_ARGS{
    DWORD * pdwSampleData;
    DWORD dwOffset;
    DWORD dwSize;
    DWORD dwPrintIntermediateResults;
}THREAD_ARGS, *PTHREAD_ARGS;

DWORD _tmain()
{
    InitializedwSampleData();
    CreateThreadsAndDoWork(1, FALSE);
    CreateThreadsAndDoWork(2, FALSE);
    CreateThreadsAndDoWork(4, FALSE);
    CreateThreadsAndDoWork(8, FALSE);
    CreateThreadsAndDoWork(16, FALSE);
    CreateThreadsAndDoWork(32, FALSE);
    CreateThreadsAndDoWork(64, FALSE);
    CreateThreadsAndDoWork(128, FALSE); // <----------- More than 64 threads

    printf("Press any key to finish");
    getchar();
    return 0;
}

VOID InitializedwSampleData(){
    DWORD i;

    for (i = 0; i < MAX_ARRAY_SIZE; i++){
        dwSampleData[i] = 1;
    }
}

VOID CreateThreadsAndDoWork(DWORD MaxThreads, DWORD dwPrintIntermediateResults){
    PTHREAD_ARGS pDataArray[MAX_THREADS_BUFFER];
    DWORD   dwThreadIdArray[MAX_THREADS_BUFFER];
    HANDLE  hThreadArray[MAX_THREADS_BUFFER];
    DWORD BeginTickCount;

    // Reset dwTotal;
    dwTotal = 0;

    // Get Initial Tick Count
    BeginTickCount = GetTickCount();

    // Create MAX_THREADS worker threads.
    for (DWORD i = 0; i < MaxThreads; i++)
    {
        // Allocate memory for thread data.
        pDataArray[i] = (PTHREAD_ARGS)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
            sizeof(THREAD_ARGS));

        if (pDataArray[i] == NULL)
        {
            // If the array allocation fails, the system is out of memory
            // so there is no point in trying to print an error message.
            // Just terminate execution.
            ExitProcess(2);
        }

        // Generate data for each thread to work with.
        pDataArray[i]->dwOffset = i * (MAX_ARRAY_SIZE / MaxThreads);
        pDataArray[i]->dwSize = MAX_ARRAY_SIZE / MaxThreads;
        pDataArray[i]->pdwSampleData = dwSampleData;
        pDataArray[i]->dwPrintIntermediateResults = dwPrintIntermediateResults;

        // Create the thread to begin execution on its own.
        hThreadArray[i] = CreateThread(
            NULL,                   // default security attributes
            0,                      // use default stack size
            DoWork,                 // thread function name
            pDataArray[i],          // argument to thread function
            0,                      // use default creation flags
            &dwThreadIdArray[i]);   // returns the thread identifier

        // Check the return value for success.
        // If CreateThread fails, terminate execution.
        // This will automatically clean up threads and memory.

        if (hThreadArray[i] == NULL)
        {
            ErrorHandler(TEXT("CreateThread"));
            ExitProcess(3);
        }
    } // End of main thread creation loop.

    // Wait until all threads have terminated.
    WaitForMultipleObjects(MaxThreads, hThreadArray, TRUE, INFINITE);

    // Close all thread handles and free memory allocations.
    for (DWORD i = 0; i < MaxThreads; i++)
    {
        CloseHandle(hThreadArray[i]);
        if (pDataArray[i] != NULL)
        {
            HeapFree(GetProcessHeap(), 0, pDataArray[i]);
            pDataArray[i] = NULL;    // Ensure address is not reused.
        }
    }
    // Print Results
    _tprintf(TEXT("Computation task with %d thread(s): Added to %d in %d mills\n"), MaxThreads, dwTotal, GetTickCount() - BeginTickCount);
}

DWORD WINAPI DoWork(LPVOID lpParam)
{
    DWORD i;
    DWORD sum = 0;

    for (i = ((PTHREAD_ARGS)lpParam)->dwOffset; i < ((PTHREAD_ARGS)lpParam)->dwSize + ((PTHREAD_ARGS)lpParam)->dwOffset; i++){
        sum += ((PTHREAD_ARGS)lpParam)->pdwSampleData[i]; // <------------ ACCESS VIOLATION ERROR
    }

    dwTotal += sum;
    if (((PTHREAD_ARGS)lpParam)->dwPrintIntermediateResults){
        _tprintf(TEXT("\nSUM = %d\n"), sum);
    }

    return 0;
}

void ErrorHandler(LPTSTR lpszFunction)
{
    // Retrieve the system error message for the last-error code.
    LPVOID lpMsgBuf;
    LPVOID lpDisplayBuf;
    DWORD dw = GetLastError();

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dw,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR)&lpMsgBuf,
        0, NULL);

    // Display the error message.
    lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
        (lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR));
    StringCchPrintf((LPTSTR)lpDisplayBuf,
        LocalSize(lpDisplayBuf) / sizeof(TCHAR),
        TEXT("%s failed with error %d: %s"),
        lpszFunction, dw, lpMsgBuf);
    MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);

    // Free error-handling buffer allocations.
    LocalFree(lpMsgBuf);
    LocalFree(lpDisplayBuf);
}

A: WaitForMultipleObjects has a limit on how many threads it can wait on. That limit is MAXIMUM_WAIT_OBJECTS which has a value of 64.
What this means is that when you call WaitForMultipleObjects passing 128 handles, it returns immediately, with an error, that you just ignore. To be completely clear, WaitForMultipleObjects is returning before the threads are complete. You then deallocate the heap memory, with the consequence that the threads, which are still running, fail when attempting to access the now deallocated memory.
The main lesson to learn is always to check the return values of Win32 API functions. Had you checked the value returned by WaitForMultipleObjects you would have discovered the problem.
To workaround this, you will need to call WaitForMultipleObjects repeatedly in a loop. Wait for the first, MAXIMUM_WAIT_OBJECTS threads. Then the next WaitForMultipleObjects threads. And so on until there are no more to wait for.


text:
Q: Select First Row from Group using Entity Framework Given a table and data like
Id  Year  Code  ColB  ColC
1   2013  A     Foo   Bar
2   2014  A     Baz   Qux
3   2014  B     Jax   Fizz
4   2013  C     Buub  Baq

I wish to select the "newest" row for each code, e.g.:
Id  Year  Code  ColB  ColC
2   2014  A     Baz   Qux
3   2014  B     Jax   Fizz
4   2013  C     Buub  Baq

I see this can be done directly in SQL
select a,b
from (
select a,b,row_number() over(partition by a order by b desc) as roworder
from myTable
) temp
where roworder = 1

https://stackoverflow.com/a/7344770/141172
Can this be expressed in Linq to Entities?


text:
Q: Adding constraints to an SQL Table with altering I have a defined type:
CREATE TYPE salary AS (salary numeric);

and a table holding data:
CREATE TABLE employees (
lastname text,
firstname text,
salary salary,
);

I want to use ALTER TABLEto add a constraint to the salary attribute:
ALTER TABLE employees ADD CONSTRAINT minimum_salary CHECK(salary > 1.47333);

this gives me the error ERROR:  operator does not exist: salary > numeric. Why is this the case?

A: To start with: a type seems overkill to just store a scalar value. Why no just create a check constraint on the column?
create table employees (
    lastname text,
    firstname text,
    salary numeric check(salary > 1.473333)
);

Coming back to your original question: I don't think that it is possible to put a check constraint on a type column. One thing you could do, however, is to create a domain. Domains extend the standard types and do accept check constraints.
Consider this demo:
create domain salary numeric check(value > 1.47333);
create table employees (lastname text, firstname text, salary salary);
insert into employees values('foo', 'bar', 1);
-- ERROR:  value for domain salary violates check constraint "salary_check"


text:
Q: Which is the better Performance to read values from XML or JSon I am in a confusion that can you help me out this question i.e., I am directly reading xml message using xpath and reading values from it and also i  am trying to convert xml to json and reading values because of light weight object so which one is best approach to read values. I am attaching following snippet code.
Below is the code to read values from xml
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(source);

XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();

String eventNumber = xpath.evaluate("/event/eventnumber", document);

Below is to convert xml to json
JSONObject xmlJSONObj = XML.toJSONObject(xml1);

A: This really depends on what you will be using the data for.  If you need to do a lot of parsing/traversing through the data, JSON is much faster due to the nature of JSON APIs.  So in the case that you will be needing to do a lot of data extraction/examination on a single file, I would convert the XML to JSON.
If you only need to find a single field in the XML file or only do a small amount of parsing/data extraction, I would stick to XML.  It is not worth the extra processing of converting an XML file to JSON if you are only going to do a small amount of traversing through the XML file.  The processing time it takes to convert the XML to JSON and then traverse the JSON is more costly than the processing time it takes to traverse through the XML file once.

A: Another discussion that was published here:
JSON and XML comparison
Bottom line in my humble opinion since you receive the message in XML it won't increase efficient to convert it to JSON and then parse it - so stick to XML

A: With your input being XML, converting to JSON for the sake of speed looks like no good idea. I guess, with your other approach, you're losing time on the DOM creation and then even much more on xpath. The fastest solution is IMHO a SAX parser. It creates no objects and only calls you on events you're interested in.


text:
Q: $L^1$ convergent subsequence of increasing functions uniformly bounded in $L^2$
Problem:
  Suppose $f_n \colon [0,1] \to [0,\infty)$ for $n \in \mathbb{N}$ are
  increasing functions which are uniformly bounded in $L^2([0,1])$. Show
  that there exists a subsequence which converges in $L^1([0,1])$.

My attempt:
If $M > 0$ is such that $\Vert f_n \Vert_2 \leq M$ for all $n \in \mathbb{N}$, then since the $f_n$ are increasing and nonnegative we have
$$(1 - x)f_n(x)^2 = \int_x^1 f_n(x)^2 \,\mathrm{d}t\leq \int_x^1 \vert f_n(t) \vert^2 \,\mathrm{d}t \leq M^2$$
for all $n \in \mathbb{N}$, thus
$$f_n(x) \leq g(x) = \frac{M}{\sqrt{1 - x}}$$
for all $n \in \mathbb{N}$. We note that $g \in L^1([0,1])$.
Suppose we can find an increasing function $f \colon [0,1] \to [0,\infty)$, a countable dense subset $S$ of $[0,1]$, and a subsequence $\{f_{n_k}\}_{k=1}^{\infty}$ such that $f_{n_k} \to f$ on $S$. Since $f$ is increasing, the set of discontinuity points $D$ is countable. If $x \in [0,1] \setminus D$, then there exists $\delta > 0$ such that
$$\vert f(x) - f(y) \vert < \epsilon/6$$
if $\vert x - y \vert < \delta$. Since $S$ is dense, there exist $a,b \in S$ such that
$$a < x < b, \quad b - a < \delta.$$
Then
$$\vert f(b) - f(a) \vert \leq \vert f(b) - f(x) \vert + \vert f(x) - f(a) \vert < \epsilon/3.$$
Choose $N \in \mathbb{N}$ such that
$$\vert f_{n_k}(y) - f(y) \vert < \epsilon/3$$
if $y = a,b$ and $n_k > N$. Since $\vert f(b) - f(a) \vert < \epsilon/3$ and $f,f_{n_k}$ are increasing, this implies that
$$\vert f_{n_k}(x) - f(x) \vert < \epsilon$$
if $n_k > N$. This shows that $f_{n_k} \to f$ pointwise on $[0,1] \setminus D$, hence almost everywhere on $[0,1]$ since $D$ is countable. Since $f_{n_k} \leq g$ and $g \in L^1([0,1])$, the dominated convergence theorem guarantees that $f_{n_k}
\to f$ in $L^1([0,1])$.
I am not 100% sure about some of the details of this, particularly how to choose such a function $f$ and such a subsequence. I think given any countable dense set $S$ which does not contain $1$, I can use a diagonalization argument to find a subsequence $\{f_{n_k}\}_{k=1}^{\infty}$ which converges pointwise on $S$ such that $\lim_{k\to\infty}f_{n_k}(x) \leq \lim_{k\to\infty}f_{n_k}(y)$ if $x < y$ with $x,y \in S$. I think then I can define $f$ on $[0,1)$ by
$$f(x) = \begin{cases} \lim_{k\to\infty}f_{n_k}(x) & x \in S \\ \sup_{y \in S, y \leq x}\lim_{k\to\infty}f_{n_k}(y) & x \not\in S \end{cases}$$

A: Let $f(x)=\lim_{n\to\infty} f_n(x)$ which exists (but may be $+\infty$) for all $x$ due to monotonicity. By Fatou's lemma,
$$ \int f \le \liminf \int f_n .$$
By C-S $\int |f_n| \le \sqrt{\int f_n^2}\times 1 =\|f_n\|_2$. As the norms on RHS are bounded by some constant, we have that $f\in L^1$.
Finally finish off with dominated convergence: $|f-f_n| = f-f_n \le f \in L^1$, and $|f_n - f|\to 0$ pointwise.  Therefore, $\int |f-f_n| \to 0$. No need for subsequence.

A: Answering the correct question this time.
I. Local boundedness
Observe that for any $t>0$
$$\mu(f_n > t) \le \int_{\{f_n >t\}} f_n^2/t^2 \le \|f_n\|_2^2 /t^2\le M^2/t^2,$$
where $M=\sup \|f_n\|_2$.
II. Subsequence convergent on rationals
And since the functions are nondecreasing (in $x$) it follows that for any $t>M$, $f_n (x) \le t$ for all $x < 1-M^2/t^2$. A standard diagonal argument then shows that one can extract a subsequence $(n_k)$ such that $f_{n_k}(x)$ converges to a finite limit $f(x)$ as $k\to\infty$ at each rational $x\in [0,1)$.
III. Convergence a.e.
Extend the function $f$ to $[0,1)$ by letting $f(y) = \sup_{x\le y,x \in{\mathbb Q}}f(x)$. Note that this extension is nondecreasing, and is therefore continuous, possibly except on a countable set.
If $y\in (0,1)$ is a continuity point of $f$, then for $\epsilon>0$ there exist rationals $x_1<y < x_2$ with $0<f(x_2)-f(x_1)<\epsilon$. By taking $k$ large enough so that $|f_{n_k} (x_1) - f(x_1)|+|f_{n_k}(x_2)-f(x_2)|<\epsilon$, we have that
$$f(x)-f_{n_k}(x) \le f(x_2) - f_{n_k}(x_1)=f(x_2) -f(x_1) + f(x_1) - f_{n_k} (x_1)\le 2 \epsilon$$
Similarly,
$$ f(x) - f_{n_k} (x) \ge f(x_1) - f_{n_k}(x_2) \ge \dots -2\epsilon.$$
Since $\epsilon$ is arbitrary, we proved that $f_{n_k}(x)\to f(x)$ at all continuity points of $f$ on $(0,1)$.
IV. Convergence in $L^1$
By Fatou, $f \in L^2$ with $\|f\|_2 \le M = \sup \|f_n\|_2$,  and so by CS, $f \in L^1$. As noted in I, the functions $f_n$ are bounded above by $t$ on $1-M^2/t^2$. Therefore it follows from dominated convergence that for every $\epsilon>0$
Fix $\epsilon>0$. First observe that
$$ \int_{[0,1-\epsilon]} |f_{n_k} -f| \to 0.$$
Next, observe that
$$ \int_{[1-\epsilon,1]} |f_{n_k} -f |\le \int_{[1-\epsilon,1]} |f_{n_k}| + \int_{[1-\epsilon,1]}|f|\le 2M \sqrt{\epsilon},$$
by CS. Combining both, $\limsup \int |f-f_{n_k}| \le 2 M \sqrt{\epsilon}$, completing the proof.


text:
Q: Error while using pointers and new operators in C++(Microsoft VS) i was using pointers and new operator for printing different city names. But the Microsoft Visual Studio show that it is Exception thrown:read access violation.
This happen even when i write *ptr=n; or *ptr=20; ,but works properly if i give ptr=&n; (if n is the variable with some value).
Program to display names of cities
 #include <iostream>
#include <cstring>
using namespace std;
class city
{
protected:
    char *name;
    int len;
public:
    char *s;
    city();
    ~city();
    void getdata()
    {

        s = new char[20];
        cout << "enter the name of city" << endl;
        cin >> s;
        len = strlen(s);
        name = new char[len + 1];
        strcpy_s(name, 10, s);

    }

    void display()
    {
        cout << *name << endl;
    }

private:

};

city::city()
{
    len = 0;//initialization
    name = NULL;

}

city::~city()
{

    delete[]name;
    delete[]s;

}
int main()
{
    city *obj[10];
    int n = 0;
    int en=0;
    do
    {
        obj[n] = new city;
        obj[n]->getdata();
        n++;
        obj[n]->display();
        cout << "do you want to enter another city?" << endl;
        cout << "(enter 1 for yes and 0 for no"<<endl;
        cin >> en;

    } while (en);
    delete[]obj;
    system("pause");
    return 0;
}

Screenshot of error

A: Don't manage memory manually! Use STL to forget memory manage!
#include <iostream>
#include <string>
#include <array>
class city
{
protected:
    std::string name;
public:
    city() = default;
    //~city();
    void getdata()
    {
        std::cout << "enter the name of city" << std::endl;
        std::cin >> this->name;
    }

    void display()
    {
        std::cout << name << std::endl;
    }
};

int main()
{
    std::array<city, 10> obj;
    for(auto&& o : obj)
    {
        o.getdata();
        o.display();
        std::cout
            << "do you want to enter another city?" << std::endl
            << "(enter 1 for yes and 0 for no" << std::endl;
        int en=0;
        std::cin >> en;
        if(0 == en) return 0;
    }
    return 0;
}

https://wandbox.org/permlink/bz4iF3LNDSyUIZPb


text:
Q: finding the vector coordinates with respect to basis $B$
I'm given this representation matrix of a linear operator in $\mathbb{R^4}$ , i'm trying to find the values of $a,b,c,d,e,f$.
Now to my understanding every column vector of the matrix is $[Tv_1]_B,[Tv_2]_B,[Tv_3]_B,[Tv_4]_B$.
i try to find the third column by $[Tv_3]_B=[T]_B*v3=(3,3,3,3)$ and then i try to find [Tv4]_B in the same way but i'm not comfortable with my answer because i get
$[Tv_4]_B=[T]_B*v_4=(1,1,1,1)$ but the given vector $[Tv_4]_B$ starts with $4$ am i going at this wrong?

A: Ok, after clarification in the chat, I know that
$$ \dim \ker T =3 $$
the Rank–nullity theorem implies that
$$ \dim \operatorname{Im} T = 4- 3 = 1$$
Meaning that for every matrix representation,
$$ \dim \operatorname{rank} [T]_B =  1$$
And so there is only one vector in the basis of the space generated by the matrix's columns. One can see it is the vector $(1,1,1,1)^T$
Now you can understand that the missing columns are $(3,3,3,3) , (4,4,4,4)$