text:
Q: How to show data table in a box with background color in shinydashboard I want to put my data table in a box in my shiny dashboard. I set my box background color as green. However, I found my data table content does not display in the box.  Does anyone know how to fix this issue? thanks.
library(shiny)
library(shinydashboard)

ui <- dashboardPage(
    dashboardHeader(title = "example"),
    dashboardSidebar(),
    dashboardBody(
        box(width=6, background = 'green',
            DT::dataTableOutput('table')
        )
    )
)

server <- function(input, output, session) {

    output$table <- DT::renderDataTable({
        DT::datatable(iris)
    })
}

shinyApp(ui, server)

A: It is just a matter of your font color:
library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title = "example"),
  dashboardSidebar(),
  dashboardBody(
    box(width=6, background = 'green',
        DT::dataTableOutput('table')
    )
  )
)

server <- function(input, output, session) {

  output$table <- DT::renderDataTable({
    df <- iris
    DT::datatable(df) %>%
      # rowid is a column as well, therefore zero to nrow()
      DT::formatStyle(0:nrow(df), color = "black")
  })
}

shinyApp(ui, server)


text:
Q: AngularJS Dynamic Directives and Method Binding I'm trying to create an AngularJS version of the Bootstrap Panel to learn about dynamic directives. So far I've created a directive where you can insert arbitrary other directives, in example:
  <panel panel-model="panel" toggle-collapse="toogleCollapse">
    <panel-body>
      <some-other-directive display-text="panel.content" ></some-other-directive>
    </panel-body>
  </panel>

The panel directive has an isolated scope, that's why I'm passing the toggleCollapse function to the directive. Inside the panel template the function should be invoked via ng-click, but this never happens. Any hints are appreciated!
Regards,
Andi
There's a plunk to illustrate the problem.
[Update] Problem solved and plunk updated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add a ribbon instead of menubar and toolbar in a dialog based project - VS2010 I must edit an existing MFC dialog-based project. I must replace the menubar and toolbar with a ribbon. The project is made in VS2010. It can't be created again from scratch(would be a pain in the @$$, because it's enormous!). The only information I could find was that it isn't impossible. Please help!

A: In general I would convert the project into a standard SDI application with a CFormView.
CDialog isn't prepared for all those things needed to hold a ribbon.
PS: I would only choose a CDialog bases exe if I never use things like toolbars and all this things that are usually easily to implement in a SDI/MDI application.


text:
Q: Non-commutativity of certain Hopf spaces How do one prove (or disprove) that $\Omega S^{2}$ and $\Omega(S^{2} \vee S^{2})$ are non commutative Hopf spaces?
I thought this is a question for math.stackexchange, but not many people even viewed that question. Seems like it should be easy but right now I have no idea how to do it. Any hint?
Definition: If $X$ is commutative Hopf space if, for the multiplication $
\mu $ there is a homotopy between $ H: \mu \simeq \mu \circ T $, where $T : X \times X \to X \times X$ is the switch map.
Clarification: When I say multiplication, I mean multiplication induced by the loop structure. On $\Omega S^{2}$ there is another multiplication which is induced by multiplication on $S^{1}$ as $\Omega S^{2} = \Omega \Sigma S^{1} $ ( This is of course commutative).

A: Let us run the Serre SS for homology with $\mathbb{Z}/2$ coefficients for the fibration
$\Omega(S^{2} \vee S^{2}) \to * \to S^{2} \vee S^{2}$
Let $x,y \in H_{2}(S^{2} \vee S^{2})$ be the generators. Since these guys has to die, there exists $x_{1}, y_{1} \in H_{1}(\Omega(S^{2} \vee S^{2}))$ which are hit by $x$ and $y$ respectively.
Notice that there are $4$ terms at $E^{2}_{2,1}$ namely $x_{1}x, y_{1}x, x_{1}y, y_{1}y$.
$d_{2}(x_{1}y) = x_{1}y_{1}$ and $ d_{2}(y_{1}x) =y_{1}x_{1} $.
So $x_{1}y + y_{1}x$ survives if $x_{1}y_{1} = y_{1}x_{1}$ and never dies. Which is a contradiction.
this shows that in homology the elements $x_{1},y_{1}$ do not commute. So $\Omega(S^{2} \vee S^{2})$ is not a commutative Hopf space.
I think this is correct. But the case of $\Omega S^{2}$ still remains unanswered.
Edit: The complete answer is given by Justin in the comments below.


text:
Q: When Using Stokes Theorem, do you have to find the unit vector of the normal or just the normal? I know how to apply Stokes' Theorem, but have seen some examples where they find the unit vector for the normal and don't know when this has to be done?
Thanks


text:
Q: I can`t access the array that I create with scheduler I made the function to create the array everyday with scheduler.
And I want to get the date from that array.
But when I access the index page, array return nil.
Do you know why?
For example like this.
schedule.rb
every 1.day, at: '4:30 am' do
  runner 'User.create_user_group'
end

model/user.rb
class User < ActiveRecord::Base
    def self.create_user_group
        @user_array = self.all.shuffle
    end
end

controller/users_controller.rb
class UsersController < ApplicationController
  def index
    @user_array #=> nil
  end
end

A: Why would you expect the instance variable of model class User to be visible inside the controller class UsersController?!
If you need the @users in the controller, you are to retrieve them explicitly:
class UsersController < ApplicationController
  def index
    user_array
  end

  def user_array
    @user_array ||= User.all.shuffle
  end
end

Please do not use the code above as is, since it has too many other glitches. The answer just provides the explanation what went wrong in your code.


text:
Q: generating permutations using mathematica 4.0 Hi I am using Mathematica 4.0. I am trying to find all the permutations, for example, say there are two numbers 0 & 1. I am trying to generate all permutations using these two numbers in 3(say) places with repetition i.e. like {1,1,1},{1,1,0},{1,0,1},{1,0,0}... Also I am trying to put each of the permutation in an array. Is there any code or command in Mathematica 4.0 by which I can do all these things. Please help me in this task...

A: In Mathematica 5.1 and higher, there is a function Tuples which does what you want. You may try
getTuples[elements_List, length_Integer] :=
  Flatten[Outer[List, Sequence @@ Table[elements, {length}]], length - 1]

For example:
In[6]:= getTuples[{0, 1}, 3]

Out[6]= {{0, 0, 0}, {0, 0, 1}, {0, 1, 0}, {0, 1, 1}, {1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}}

But I don't know if this works in M4.0. It should, I guess, but I can not check. Generally, you will face tons of difficulties of various kinds working with such an obsolete version as 4.0, including lacking the functionality, inferior performance and interface (front-end), certain bugs that were fixed in later versions, incompatibility with code written in later versions, and getting help. This is especially true for Mathematica given huge advances in all sorts of directions introduced since 4.0. So, if you plan to use it regularly, I'd strongly suggest to upgrade.

A: Kind of archeological question :D. Version 4 is pretty old!
<<DiscreteMath`Combinatorica`

perm1[l_,n_]:=Union[KSubsets[Flatten[Table[l,{n}]],n]]

In[70]:= perm1[{1,2,1},4]
Out[70]= {{1,1,1,1},{1,1,1,2},{1,1,2,1},{1,1,2,2},{1,2,1,1},
          {1,2,1,2},{1,2,2,1},{1,2,2,2},{2,1,1,1},{2,1,1,2},
          {2,1,2,1},{2,1,2,2},{2,2,1,1},{2,2,1,2},{2,2,2,1},{2,2,2,2}}

In[73]:= perm1[{1,0},3]
Out[73]= {{0,0,0},{0,0,1},{0,1,0},{0,1,1},{1,0,0},{1,0,1},{1,1,0},{1,1,1}}

A: Just an aside - please note that documentation for all previous versions of Mathematica is freely available online at http://reference.wolfram.com/legacy - specifically for version 4, see http://reference.wolfram.com/legacy/v4.
You can search the v4 docs via google:
permutations site:reference.wolfram.com/legacy/v4
which turns up the v4 function Permutations http://reference.wolfram.com/legacy/v4/RefGuide/Permutations.html which has examples and a few links to other parts of the old Mathematica Book.


text:
Q: Pass a long list of ID's to Web API without putting them in the URL I'd like to be able to pass a long string (list of ID's) from our Angular front end to our .NET Web API. However, sometimes this string exceeds the URL character limit, so I don't want to pass it via the URL.
What's a good way to do this?
Front end: I first thought to send the string via PUT's HTTP Body in httpOptions, but then I realized with a PUT request, I may not even need HTTP Body - I think I can just pass the data straight into PUT's data parameter.
PUT request
public put(apiPath, data): Observable<any>
{
    var url = this.globals.getBaseUrl() + apiPath + "/" + data["ID"];

    const httpOptions =
    {
        headers: new HttpHeaders({"Content-Type": "application/json"})
        ,withCredentials: true
    };

    return this.httpClient.put<any>(url, data, httpOptions)
        .pipe(catchError(this.handleError));
}

.
.NET Web API: Then, in the API, how would  I dig into this data I've sent via the PUT request? My gameplan was to make a model for this controller that only has one field - the string of ID's. Then in the controller I'd grab it, parse, delimit and pass it to our database. Just unsure how to grab this data in the controller.
Controller:
// PUT: api/myApiPath/5
[ResponseType(typeof(void))]
public async Task<IHttpActionResult> Put_myTable(int id, _myTable _myTable)
{
    db.Entry(_myTable).State = EntityState.Modified;
        try
        {
            // ----- put -----
            await db.SaveChangesAsync();
            // ----- /put -----
        }
        else
        {
            error = "Unauthorized.";
            throw new HttpResponseException(HttpStatusCode.Forbidden);
        }

}

A: I'm using .net core, but I think you just need a [FromBody] attribute on your backend parameter something like the below.  Whatever object your passing in from the frontend should match the type of object that your backend is expecting.  So if you had a simple array of numbers on the frontend your backend would look like the below
[HttpPut]
public async Task<IHttpActionResult> Put_myTable([FromBody] List<int> ids)
{
}


text:
Q: Android Runtime Resource Overlay with custom attributes I'm trying to use the Runtime Resource Overlay (RRO) mechanism to overlay an xml resource, which is using custom attributes and custom namespace. When building the overlay APK the aapt2 (link) throws an attribute not found error.
How do I make known the custom attribute from the main application to the overlay?
Is it even possible to use custom attributes in an overlay?
Details:
The overlay contains of two files:
AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="de.test.simpleappoverlay">

    <overlay
        android:targetPackage="de.test.simpleapp"
        android:targetName="Test"/>
</manifest>

and the xml file res/xml/my_config.xml:
<?xml version="1.0" encoding="utf-8"?>
<MyConfig xmlns:app="http://schemas.android.com/apk/res/de.test.simpleapp"
    app:text="hello">
</MyConfig>

<!-- I also tried: xmlns:app="http://schemas.android.com/apk/res-auto" -->

The main application defines the attribute text in res/values/attrs.xml:
...
<declare-styleable name="MyConfig">
    <attr name="text" format="string" />
</declare-styleable>

Furthermore it defines the overlayable tag in res/values/overlayable.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <overlayable name="Test">
        <policy type="public">
            <item type="xml" name="my_config"/>
        </policy>
    </overlayable>
</resources>

To build the overlay I do this:

aapt2 compile -v --dir app/src/main/res/  -o SimpleAppOverlay.flata

and

aapt2 link -v --no-resource-removal
-I ~/Library/Android/sdk/platforms/android-29/android.jar
--manifest app/src/main/AndroidManifest.xml
-o sao.apk SimpleAppOverlay.flata

Which leads to the following output:

note: including /Users/bernd/Library/Android/sdk/platforms/android-29/android.jar
aapt2 W 09-01 14:33:06 20083 694697 ApkAssets.cpp:138] resources.arsc in APK '/Users/bernd/Library/Android/sdk/platforms/android-29/android.jar' is
compressed
note: linking package 'de.test.simpleappoverlay' using package ID 7f   note: merging archive SimpleAppOverlay.flata
note: merging 'xml/my_config' from compiled file app/src/main/res/xml/my_config.xml
note: enabling pre-O feature split ID rewriting   AndroidManifest.xml:
note: writing to archive (keep_raw_values=false)
note: writing AndroidManifest.xml to archive
note: linking app/src/main/res/xml/my_config.xml (de.test.simpleappoverlay:xml/my_config)
app/src/main/res/xml/my_config.xml:2: error: attribute text (aka
de.test.simpleappoverlay:text) not found
error: failed linking file resources.

A: I had a similar problem to this where I was trying to overlay an app with custom attributes in Android 10 and have a solution. There are two changes that are needed:
Part 1
It looks like your app name is de.test.simpleapp so your my_config.xml file should look like:
<?xml version="1.0" encoding="utf-8"?>
<MyConfig xmlns:app="http://schemas.android.com/apk/prv/res/de.test.simpleapp"
    app:text="hello">
</MyConfig>

The important piece is specifying the 'prv/res/app.packagename' so it uses the namespace of the base app for the private attributes. If you used 'apk/res-auto' that would not work as it resolves to the name of your app (which in this case is the overlay app de.test.simpleappoverlay) which does not contain the definition of the private attributes.
Part 2
Since you now have a dependency on the main app when linking, you have to include it in the link command with a -I simpleapp.apk (or whatever the APK name is of the base app). Right now you are just including android.jar in the aapt2 link step which only contains the 'android' namespace and attributes. Therefore, you now need to add your base app in the include step so it can link properly against its namespace and attributes.
Like some of the other answers said though, this problem goes away in Android 11, but if you're stuck on Android 10 like I am hopefully this helps.

A: I don't think including new ids is supported in the current implementation of the RROs (at least in Android Q).
Regarding your error, aapt uses the android.jar to generate the apk for your overlay. Since it cannot find your new attribute, it throws an error. For this to work I believe you would need to use a modified android.jar including your attribute. One way of doing this is by modifying the Android SDK in the AOSP and creating your own version that you would then use for the aapt command.

A: Some time ago I switched my AOSP environment from Android 10 to 11. Google made quite a few changes to the Overlay mechanism. To my big surprise these changes fixed the problems I had when trying to "overlay" custom attributes.
With the Android 10 environment I observed while debugging that the Android XML parser returns "null" when trying to read the mentioned attributes. With idmap I was able to confirm that the attributes were present in the overlay and the target app, and that they were properly mapped.
Also all the linker errors were gone.


text:
Q: How should I Handle duplicate times in time series data with pandas? I have the following returned from an API Call as part of a larger dataset:

{'Time': datetime.datetime(2017, 5, 21, 18, 18, 1,
tzinfo=tzutc()), 'Price': '0.052600'}
{'Time': datetime.datetime(2017, 5, 21, 18, 18, 1, tzinfo=tzutc()),
'Price': '0.052500'}

Ideally I would use the timestamp as an index on the pandas data frame however this appears to fail as there is a duplicate when converting to JSON:
df = df.set_index(pd.to_datetime(df['Timestamp']))
print(new_df.to_json(orient='index'))

ValueError: DataFrame index must be unique for orient='index'.

Any guidance on the best way to deal with this situation? Throw away one datapoint? The time does not get more fine-grain than to the second, and there is obviously a price change during that second.

A: I think you can change duplicates datetimes by adding ms by cumcount and to_timedelta:
d = [{'Time': datetime.datetime(2017, 5, 21, 18, 18, 1), 'Price': '0.052600'},
     {'Time': datetime.datetime(2017, 5, 21, 18, 18, 1), 'Price': '0.052500'}]
df = pd.DataFrame(d)
print (df)
      Price                Time
0  0.052600 2017-05-21 18:18:01
1  0.052500 2017-05-21 18:18:01

print (pd.to_timedelta(df.groupby('Time').cumcount(), unit='ms'))
0          00:00:00
1   00:00:00.001000
dtype: timedelta64[ns]

df['Time'] = df['Time'] + pd.to_timedelta(df.groupby('Time').cumcount(), unit='ms')
print (df)
      Price                    Time
0  0.052600 2017-05-21 18:18:01.000
1  0.052500 2017-05-21 18:18:01.001

new_df = df.set_index('Time')
print(new_df.to_json(orient='index'))
{"1495390681000":{"Price":"0.052600"},"1495390681001":{"Price":"0.052500"}}

A: You could use .duplicated to keep first or last entry. Have a look at pandas.DataFrame.duplicated

A: Just to expand upon the accepted answer: adding a loop helps for dealing with any new duplicates introduced by the first pass.
This isnull is important to catch any NaTs in your data. Since any timedelta + NaT is still NaT.
def deduplicate_start_times(frame, col='start_time', max_iterations=10):
    """
    Fuzz duplicate start times from a frame so we can stack and unstack
    this frame.
    """

    for _ in range(max_iterations):
        dups = frame.duplicated(subset=col) & ~pandas.isnull(frame[col])

        if not dups.any():
            break

        LOGGER.debug("Removing %i duplicates", dups.sum())

        # Add several ms of time to each time
        frame[col] += pandas.to_timedelta(frame.groupby(col).cumcount(),
                                          unit='ms')

    else:
        LOGGER.error("Exceeded max iterations removing duplicates. "
                     "%i duplicates remain", dups.sum())

    return frame


text:
Q: Multiple processes that open ports for localhost in Procfile I'm trying to start multiple processes with my Procfile in Foreman that open a port on localhost. Here's my Procfile.
web: bundle exec puma
mongo: mongod
pubsub: bundle exec firehose server

Now, web and pubsub open ports 9292 and 7272, respectively. However, when I run foreman start, Foreman starts the first process (web) and starts listening on port 9292, but not 7272. It's not until I quit the terminal process with Ctrl + C does the next process (pubsub) start.
Here is my Terminal output. The line break is where I hit Ctrl + C.
tardis:clock[experimental]$ be foreman start
21:33:49 web.1    | started with pid 12870
21:33:49 mongo.1  | started with pid 12873
21:33:49 pubsub.1 | started with pid 12876
21:33:49 mongo.1  | /usr/lib/mongodb/mongod --help for help and startup options
21:33:49 mongo.1  | Thu Aug  2 21:33:49 Mongo DB : starting : pid = 12875 port = 27017 dbpath = /data/db/ master = 0 slave = 0  32-bit
21:33:49 mongo.1  | ** NOTE: when using MongoDB 32 bit, you are limited to about 2 gigabytes of data
21:33:49 mongo.1  | **       see http://blog.mongodb.org/post/137788967/32-bit-limitations for more
21:33:50 mongo.1  | Thu Aug  2 21:33:50 db version v1.4.4, pdfile version 4.5
21:33:50 mongo.1  | Thu Aug  2 21:33:50 git version: nogitversion
21:33:50 mongo.1  | Thu Aug  2 21:33:50 sys info: Linux roseapple 2.6.24-28-server #1 SMP Wed Aug 18 21:17:51 UTC 2010 i686 BOOST_LIB_VERSION=1_42
21:33:50 mongo.1  | Thu Aug  2 21:33:50 waiting for connections on port 27017
21:33:50 mongo.1  | Thu Aug  2 21:33:50 web admin interface listening on port 28017
21:33:57 web.1    | Sass is in the process of being separated from Haml,
21:33:57 web.1    | and will no longer be bundled at all in Haml 3.2.0.
21:33:57 web.1    | Please install the 'sass' gem if you want to use Sass.
21:33:58 web.1    |   DEBUG - MONGODB [DEBUG] Logging level is currently :debug which could negatively impact client-side performance. You should set your logging level no lower than :info in production.
21:33:58 mongo.1  | Thu Aug  2 21:33:58 connection accepted from 127.0.0.1:37172 #1
21:33:58 web.1    |   DEBUG -
21:33:58 mongo.1  | Thu Aug  2 21:33:58 end connection 127.0.0.1:37172
21:34:01 web.1    | Puma 1.5.0 starting...
21:34:01 web.1    | * Min threads: 0, max threads: 16
21:34:01 web.1    | * Environment: development
21:34:01 web.1    | * Listening on tcp://0.0.0.0:9292
21:34:01 web.1    | Use Ctrl-C to stop

^C21:34:03 mongo.1  | Thu Aug  2 21:34:03 got kill or ctrl c signal 2 (Interrupt), will terminate after current cmd ends
21:34:03 mongo.1  | Thu Aug  2 21:34:03 now exiting
21:34:03 mongo.1  | Thu Aug  2 21:34:03  dbexit:
21:34:03 mongo.1  | Thu Aug  2 21:34:03    shutdown: going to close listening sockets...
SIGINT received
21:34:03 system   | sending SIGTERM to all processes
21:34:03 mongo.1  | Thu Aug  2 21:34:03    going to close listening socket: 5
21:34:03 web.1    |  - Gracefully stopping, waiting for requests to finishSIGTERM received

21:34:03 mongo.1  | Thu Aug  2 21:34:03    going to close listening socket: 6
21:34:03 web.1    |  - Gracefully stopping, waiting for requests to finish
21:34:03 mongo.1  | Thu Aug  2 21:34:03    shutdown: going to flush oplog...
21:34:03 web.1    | /home/ethan/.rvm/gems/ruby-1.9.3-p0/gems/puma-1.5.0/lib/puma/server.rb:639:in `close': closed stream (IOError)
21:34:03 mongo.1  | Thu Aug  2 21:34:03    shutdown: going to close sockets...
21:34:03 web.1    |   from /home/ethan/.rvm/gems/ruby-1.9.3-p0/gems/puma-1.5.0/lib/puma/server.rb:639:in `stop'
21:34:03 mongo.1  | Thu Aug  2 21:34:03    shutdown: waiting for fs preallocator...
21:34:03 web.1    |   from /home/ethan/.rvm/gems/ruby-1.9.3-p0/gems/puma-1.5.0/lib/puma/cli.rb:447:in `block in run'
21:34:03 mongo.1  | Thu Aug  2 21:34:03    shutdown: closing all files...
21:34:03 web.1    |   from /home/ethan/.rvm/gems/ruby-1.9.3-p0/gems/puma-1.5.0/lib/puma/server.rb:642:in `call'
21:34:03 mongo.1  | Thu Aug  2 21:34:03      closeAllFiles() finished
21:34:03 web.1    |   from /home/ethan/.rvm/gems/ruby-1.9.3-p0/gems/puma-1.5.0/lib/puma/server.rb:642:in `join'
21:34:03 mongo.1  | Thu Aug  2 21:34:03    shutdown: removing fs lock...
21:34:03 web.1    |   from /home/ethan/.rvm/gems/ruby-1.9.3-p0/gems/puma-1.5.0/lib/puma/server.rb:642:in `stop'
21:34:03 mongo.1  | Thu Aug  2 21:34:03  dbexit: really exiting now
21:34:03 web.1    |   from /home/ethan/.rvm/gems/ruby-1.9.3-p0/gems/puma-1.5.0/lib/puma/cli.rb:286:in `graceful_stop'
21:34:03 web.1    |   from /home/ethan/.rvm/gems/ruby-1.9.3-p0/gems/puma-1.5.0/lib/puma/cli.rb:458:in `rescue in run'
21:34:03 web.1    |   from /home/ethan/.rvm/gems/ruby-1.9.3-p0/gems/puma-1.5.0/lib/puma/cli.rb:455:in `run'
21:34:03 web.1    |   from /home/ethan/.rvm/gems/ruby-1.9.3-p0/gems/puma-1.5.0/bin/puma:10:in `<top (required)>'
21:34:03 web.1    |   from /home/ethan/.rvm/gems/ruby-1.9.3-p0/bin/puma:19:in `load'
21:34:03 web.1    |   from /home/ethan/.rvm/gems/ruby-1.9.3-p0/bin/puma:19:in `<main>'
21:34:03 pubsub.1 | >> Thin web server (v1.4.1 codename Chromeo)
21:34:03 pubsub.1 | >> Maximum connections set to 1024
21:34:03 pubsub.1 | >> Listening on 0.0.0.0:7474, CTRL+C to stop
21:34:03 pubsub.1 | >> Stopping ...
21:34:03 pubsub.1 | >> Stopping ...
21:34:03 web.1    | terminated by SIGTERM
21:34:03 mongo.1  | terminated by SIGTERM
21:34:03 pubsub.1 | terminated by SIGTERM


text:
Q: Is it possible to overload a method that takes the same data structure but different data types? Is it possible to overload a method that takes a particular data structure with different types? For example first a string array, then an int array?
I have two hashmaps in my code and I am trying to print out their key, value pairs. The first hashmap takes string arraylists as both its key and value. The second one takes strings as keys and string arraylists as values:
public static void printMap(HashMap<ArrayList<String>, ArrayList<String>> thisMap){
    int i = 0;
    for(ArrayList<String> key : thisMap.keySet()){
        System.out.println(i + " " + key + " >> " + thisMap.get(key).toString());
        System.out.println(" ");
        i++;
    }
}

public static void printMap(HashMap<String, ArrayList<String>> thisMap){
    int i = 0;
    for(String key : thisMap.keySet()){
        System.out.println(i + " " + key + " >> " + thisMap.get(key));
        System.out.println(" ");
        i++;
    }
}

I tried to overload a single method to print both maps but keep getting this error:
java: name clash: printMap(java.util.HashMap<java.util.ArrayList<java.lang.String>,java.util.ArrayList<java.lang.String>>)
and printMap(java.util.HashMap<java.lang.String,java.util.ArrayList<java.lang.String>>)
have the same erasure.

what am I doing wrong?

A: At compilation, Java performs Type Erasure. During that process, your parameters become plain ArrayList types. As such, their erasure is the same, hence your error.
In my limited experience, solutions to avoid clashes could be to:

*

*Use different (e.g. custom) classes, or

*Change the method names.

1. Use different classes
You can define custom classes that extend HashMap:
public class ArrayKeyHashMap<K, V> extends HashMap<ArrayList<K>, V> {
  // Constructors ...
}
public class StringKeyHashMap<V> extends HashMap<String, V> {
  // Constructors ...
}

public class Example {
  public static void printMap(ArrayKeyHashMap<String, ArrayList<String>> thisMap) {
    // ...
  }
  public static void printMap(StringKeyHashMap<ArrayList<String>> thisMap) {
    // ...
  }
}

This way, your method signatures will differ even after type erasure, since literally different classes are used.
2. Change method names
By changing the method names you unfortunately do not overload the methods anymore, but you avoid the issue of having clashes after type erasure:
public class Example {
  public static void printArrayArrayMap(HashMap<ArrayList<String>, ArrayList<String>> thisMap) {
    // ...
  }
  public static void printStringArrayMap(HashMap<String, ArrayList<String>> thisMap) {
    // ...
  }
}


text:
Q: How to get data in specific tag from XML file? I have code that for all intents and purposes follows the following format for a bunch of users. I need to be able to extract just the email part of the XML in Powershell. How would I do that? The indentation is messed up, I know and am sorry.
<user>
<primary_id>jd112</primary_id>
<first_name>John</first_name>
<middle_name/>
<last_name>Doe</last_name>
<full_name>John Doe</full_name>
-<contact_info>
-<addresses>
-<emails>
<email_address>john.doe@main.com</email_address>
</email>
</emails>
</addresses>
</contact_info>

</user>

A: Try following :
using assembly System.Xml.Linq
$xDoc = [System.Xml.Linq.XDocument]::Load('c:\temp\test.xml')
$user = $xDoc.Root

$primary = $user.Element("primary_id").Value
$first_name = $user.Element("first_name").Value
$middle_name = $user.Element("middle_name").Value
$last_name = $user.Element("last_name").Value
$full_name= $user.Element("full_name").Value

$emails_address = [System.Linq.Enumerable]::First($user.Descendants("email_address"))
$emails_address = [System.Xml.Linq.XElement]$emails_address
$emails_address = $emails_address.Value

Write-Output $primary_id
Write-Output $first_name
Write-Output $middle_name
Write-Output $last_name
Write-Output $full_name
Write-Output $emails_address
Write-Output $email


text:
Q: Power series associated with airy function When $x$ goes to $+\infty$, the quotient $$\frac{N(x)}{D(x)}=\frac{x+\frac{2}{4!}\,x^4+\frac{2.5}{7!}\,x^7+\frac{2.5.8}{10!}\,x^{10}+\ldots}{1+\frac{1}{3!}\,x^3+\frac{1.4}{6!}\,x^6+\frac{1.4.7}{9!}\,x^9+\ldots}$$ converges rapidly to $$c=\frac{\Gamma(\frac{1}{3})}{\sqrt[3]{3}\Gamma(\frac{2}{3})}\simeq1.37172116$$
As far as I understand, to find the exact value of $c$ requires complex analysis, indefinite integrals, fourier transforms,... But is there a simple proof of the fact that the quotient converges towards a constant, without knowing what it is ? Ideally, I am looking for a proof using the coefficients of the power series in the numerator and denominator.
Furthermore, is there a simple proof of the fact that $cD(x)-N(x)$ is bounded ? That it converges to 0 ?

A: A straight forward approach would be to first show (in terms of power series) that
$$N(x)=\frac{1}{6}\, 3^{5/6} \;\Gamma \left(\frac{1}{3}\right) \left(\text{Bi}(x)-\sqrt{3}\, \text{Ai}(x)\right)$$
and
$$D(x)=\frac{1}{2}\, 3^{1/6} \;\Gamma \left(\frac{2}{3}\right) \left( \text{Bi}(x)+\sqrt{3}\,\text{Ai}(x)\right);$$
$\text{Ai}(x)$ and $\text{Bi}(x)$ being the Airy functions.
Then attempt to find the limit of
$$ \frac{\left( \text{Bi}(x)-\sqrt{3}\,\text{Ai}(x)\right)}{\left( \text{Bi}(x)+\sqrt{3}\,\text{Ai}(x)\right)}=\frac{2 \text{Bi}(x)}{\sqrt{3} \text{Ai}(x)+\text{Bi}(x)}-1$$
as $x \rightarrow \infty$; which as it turns out gives a very simple result since $\text{Ai}(x)$ tends to zero as $x \rightarrow \infty$ and $\text{Bi}(x)$ does not.


text:
Q: Why does browser zoom in affect slickgrid autotooltip functioning, how to fix this? The issue is that tooltips are still appearing even when values aren't truncated.
The behavior varies in different browsers. In chrome, starting at 110%, the autotooltip isn't working correctly already. In firefox and IE, you have to zoom in more to replicate this issue.
My hunch is that cell widths are being messed up when zooming in the page but I'm not so familiar how each browsers scale the elements in the page. I'm also uncertain if there are ways to control this?
Any ideas on why this is happening and possible ways to fix this?


text:
Q: How to create uneven facet_wrap grid in R with ggplot? I am currently working on a graph with ggplot2 in R where I want to use facet_wrap to create 5 subplots.
Here is my code so far:
# getting the data
data = structure(list(type = c("red", "blue", "orange", "yellow", "green",
       "red", "blue", "orange", "yellow", "green", "red", "blue", "orange",
       "yellow", "green", "red", "blue", "orange", "yellow", "green"),
       cond = c("new", "new", "new", "new", "new", "old", "old",
       "old", "old", "old", "new", "new", "new", "new", "new", "old",
       "old", "old", "old", "old"), fact = c("light", "light", "light",
       "light", "light", "light", "light", "light", "light", "light",
       "shiny", "shiny", "shiny", "shiny", "shiny", "shiny", "shiny",
       "shiny", "shiny", "shiny"), score = c(2L, 4L, 8L, 6L, 10L, 3L,
       5L, 9L, 1L, 3L, 12L, 14L, 18L, 16L, 20L, 13L, 15L, 19L, 11L,
       13L)), class = "data.frame", row.names = c(NA, -20L))

library(ggplot2)

ggplot(data=data, aes(x=cond, y=score, fill=fact)) +
  geom_bar(stat="identity", position=position_dodge()) +
  theme_bw() + facet_wrap(. ~ type, ncol=3)

This creates the following plot:

However, since one of the colours is much more important than the others, I would like to create one of these options:

Does anyone know how to get facet_wrap to do that or can point me to another option to create this?
Cheers,
Max

A: Here's how to do it mixing patchwork and facets.
Create one plot for blue and another for everything else. Remove the legend from the blue plot and remove the y axis title from the other.
library(tidyverse)
library(patchwork)

p_other <-
  data %>%
  filter(type != "blue") %>%
  ggplot(aes(x = cond, y = score, fill = fact)) +
    geom_bar(stat = "identity", position = position_dodge()) +
    theme_bw() +
    facet_wrap(. ~ type, ncol = 2) +
    theme(axis.title.y = element_blank())

p_blue <-
  data %>%
  filter(type == "blue") %>%
  ggplot(aes(x = cond, y = score, fill = fact)) +
    geom_bar(stat = "identity", position = position_dodge()) +
    theme_bw() +
    facet_wrap(. ~ type, ncol = 2) +
    theme(legend.position = "none")

Add a column using | from patchwork.
(p_blue | p_other) + plot_layout(widths = c(1, 2))

A: Try this approach with patchwork, you will have to format your type variable to factor in order to have the desired order and then use a function for the plot. After that you can compose the desired plot. I have designed the function for you and this belongs to option 2 in your question. Here the code:
library(ggplot2)
library(patchwork)
#Data format
data$type <- factor(data$type,
                    levels = c("blue","green","orange", "red", "yellow"),
                    ordered = T)

We create a list for our data:
#Create list
List <- split(data,data$type)

Now, the function for plots:
#Create isolate plots
myplot <- function(x)
{
  text <- unique(as.character(x$type))
  #Plot
  G <- ggplot(data=x, aes(x=cond, y=score, fill=fact)) +
    geom_bar(stat="identity", position=position_dodge()) +
    theme_bw() + ggtitle(text)+
    theme(plot.title = element_text(hjust=0.5))
  return(G)
}

Then, we start building our plots:
#Plot for only first plot
P1 <- myplot(List[[1]])
P2 <- wrap_plots(lapply(List[-1], myplot),ncol = 2)

Finally, we arrange the plots:
#Now wrap plots
P3 <- P1 + P2
P4 <- P3 +  plot_layout(guides = 'collect')

And the output:


text:
Q: How to implement android RESTful client with Robospice (or something like this) + OAuth? How to implement Robospice (or something like this) + OAuth?
Maybe someone can share link to examples of good practices for creating RESTful android clients? I can't figure the architecture of RESTful app with OAuth, which cover all problems with activity's lifecycle.
Of course I know about Virgil Dobjanschi "Google I/O 2010 - Android REST client applications". With some Libraries like Robospice it is very easy to implement. But what if app uses OAuth for authorization to service? What libraries for OAuth could be useful? where store access token? How execute some requests synchronously? etc. ...
I am looking for complete code examples or at least advices about design and architecture.

A: It depends. Are you talking about OAuth 1 or OAuth 2? For the former, you could use signpost. For the latter, you could use RoboSpice + Google Http Client + Google OAuth Client Library.
If you use Google Http Client as your network library, what you need to do is to create your own HttpClientSpiceService based on GoogleHttpClientSpiceService, which you can find in RoboSpice. Then, you need something like this:
public static HttpRequestFactory createRequestFactory() {
    HttpTransport httpTransport = AndroidHttp.newCompatibleTransport();
    return httpTransport.createRequestFactory(new HttpRequestInitializer() {
        @Override
        public void initialize(HttpRequest request) {
            // TODO: authorize or sign request...
            // Note that this will authorize/sign ALL the requests you make,
            // so you will probably want to improve on that.
        }
    });
}

The rest is really up to you, but the basics are to implement a way to provide third-party log-in, get the required token and set up the OAuth library of your choice.


text:
Q: docker(1.5.1) artifactory (3.x) registry management
*

*The docker registry has gotten huge pretty quickly, is there a way to clean up the registry?

*Is there a way to combine all the dependent layers, I'd like to cut down on how long it takes to download an image

*Is there a way to pull a specific dependent layer:

8b44529354f3: Download complete
8b9b56bb19d4: Download complete
79b1e69a4835: Download complete

*

*Can you revert a docker push?

A: Seems as interview questions. Interesting.
Can't answer all of them, but try to answer some of them. Will update later if have better solution.

The docker registry has gotten huge pretty quickly, is there a way to clean up the registry?

Need be done by scripting currently.
https://github.com/docker/docker-registry/pull/409
https://github.com/docker/docker-registry/issues/706
https://github.com/docker/docker-registry/issues/523

Is there a way to combine all the dependent layers, I'd like to cut down on how long it takes to download an image

update later.

Is there a way to pull a specific dependent layer:

No, I can't find the way. If someone knows how to do, let me know.

Can you revert a docker push?

Some one answered it in https://groups.google.com/forum/#!topic/docker-user/wNHzbFv7cDw
That's one of the real strengths of Docker: the ability to go back to a previous commit. The secret is simply to docker tag the image you want.
Here's an example. In this example, I first installed ping, then committed, then installed curl, and committed that. Then I rolled back the image to contain only ping:
$ docker history imagename
IMAGE               CREATED             CREATED BY                SIZE
f770fc671f11        12 seconds ago      apt-get install -y curl   21.3 MB
28445c70c2b3        39 seconds ago      apt-get install ping      11.57 MB
8dbd9e392a96        7 months ago                                  131.5 MB

$ docker tag 2844 imagename   # <-- that's the secret right there

$ docker history imagename
IMAGE               CREATED             CREATED BY             SIZE
28445c70c2b3        56 seconds ago      apt-get install ping   11.57 MB
8dbd9e392a96        7 months ago                               131.5 MB


text:
Q: A problem of consecutive square full integers. I am stuck with the following problem of number theory.A number $n$ is said to be square full if $p^2|n$ for some prime $p$.
Let $P(k)$  be the product of all primes $\leq k$.Then show that there exist $31\times 21$ integers $n$ with $1\leq n\leq P(31)^2$ such that $n+1,n+2,...,n+10$ are all square full and none of them are divisible by $31$.(Note that $31$ is the $11$ th prime in ascending order.)
I tried to do that with chinese remainder theorem on $n\equiv -1\pmod{2^2},n\equiv -2\pmod{3^2},...,n\equiv -10\pmod{{p_{10}}^2}$,but then I am stuck.Can someone give me some hint?


text:
Q: Bootstrap modal not working on loop scenarios I am trying to create generalised method for ajax in my javascript and bootstrap modal is not working as expected.
HTML :

                <button id="con_close1_v2" type="button" class="close" data-dismiss="modal" aria-hidden="true">&times</button>

Admin Username

<input type="text" id="con_sect_name_v2" class="form-control">

Admin Password

<input type="password" id="con_sect_pass_v2" class="form-control">

                <button class="btn btn-default" id="con_close_v2" style="margin-top:3%;">Cancel</button>
                <button class="btn btn-default" id="con_sect_ok_v2" style="margin-right:2%;margin-top:3%;">Override</button>
                <button class="btn btn-default" id="con_upd_sect_ok_v2" style="display:none;margin-right:2%;margin-top:3%;">Override</button>

JavaScript:
Executed as
generalised_ajax('post_url',
    {
        'sub_id': sub_id,
        'status': status,
        '_token': csrf_token
    }, "POST", function () {
        console.log('success placing apt');
    }, {},
    function () {
        console.log('apt cancelled');
    }, {});

function generalised_ajax(url, data, type, post_success, post_success_params, post_cancel, post_cancel_params) {
    $.ajax({
        url: url,
        data: data,
        type: type,
        headers: {Accept: "application/json"},
        dataType: 'json',
        success: function (result, status, xhr) {
            post_success(post_success_params);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            if (xhr.responseJSON.type === "confirmation") {
                responseProcess = xhr.responseJSON;
                generalised_confirm(responseProcess.message, {
                    url: url,
                    data: data,
                    type: type,
                    post_success: post_success,
                    post_success_params: post_success_params,
                    post_cancel: post_cancel,
                    post_cancel_params: post_cancel_params
                }, responseProcess.config_name);
            } else if(xhr.responseJSON.type === "admin_auth"){
                generalised_authentication(responseProcess.message, {
                    url: url,
                    data: data,
                    type: type,
                    post_success: post_success,
                    post_success_params: post_success_params,
                    post_cancel: post_cancel,
                    post_cancel_params: post_cancel_params
                });
            }
        }
    });
}

function generalised_confirm(message, data, config_name) {
    var r = confirm(message);
    if (r === true) {
        data.data[config_name] = true;
        generalised_ajax(data.url, data.data, data.type, data.post_success, data.post_success_params, data.post_cancel, data.post_cancel_params);
    } else {
        data.post_cancel(data.post_cancel_params);
    }
}

var modelX = $("#consult_modal_v2");
function generalised_authentication(message, data){
    var uname = $("#con_sect_name_v2");
    var pass = $("#con_sect_pass_v2");
    $("#message_v2").val(message);
    modelX.modal('toggle');
    $("#con_sect_ok_v2").click(function(event){
        modelX.modal('toggle');
        data.data['a_uname'] = uname.val();
        data.data['a_pswd'] = pass.val();
        uname.val('');
        pass.val('');
        generalised_ajax(data.url, data.data, data.type, data.post_success, data.post_success_params, data.post_cancel, data.post_cancel_params);
    });
    $("#con_close_v2").click(function(event){
        modelX.modal('toggle');
        data.post_cancel(data.post_cancel_params);
    });
}

Expected scenarios:

*

*Sent ajax

*Server responded with admin_auth error

*Open modal

*Input admin creds (wrong ones)

*Close modal

*Sent ajax

*Server responded with admin_auth error

*Repeat from stage 3

How it's working right now

*

*Sent ajax

*Server responded with admin_auth error

*Open modal

*Input admin creds (wrong ones)

*Close modal

*Sent ajax

Now server responded with same ajax as Point 2. But modal won't open again.
It is working fine with javascripts confirmation popup.
Update:
After I removed fade class from modal, it started appearing everytime. But now it sends double of ajax of previous attempt.
Like for first time once, second time twice, third time 4 times, 4th time 8 times and so on.

A: I don't know what is the reason of this behaviour but
changing
$("#con_sect_ok_v2").click(function(event){
        modelX.modal('toggle');
        data.data['a_uname'] = uname.val();
        data.data['a_pswd'] = pass.val();
        uname.val('');
        pass.val('');
        generalised_ajax(data.url, data.data, data.type, data.post_success, data.post_success_params, data.post_cancel, data.post_cancel_params);
    });

to
$("#con_sect_ok_v2").one('click',function(event){
        modelX.modal('toggle');
        data.data['a_uname'] = uname.val();
        data.data['a_pswd'] = pass.val();
        uname.val('');
        pass.val('');
        generalised_ajax(data.url, data.data, data.type, data.post_success, data.post_success_params, data.post_cancel, data.post_cancel_params);
    });

solved it.
Credits https://stackoverflow.com/a/3393694/2598994


text:
Q: correct way to return a function's value in a method I'm having some troubles getting a method to work properly, right now I have a script that determine the user's privileges, then displays the page (main.php), and inside this main.php I check the privileges and display something different regarding if the user has or not the necessary privileges.
Here is a condensended version of my functions.php with the concerned methods/functions :
<?php

class gator {

    public function init() {

        // get user's privileges
        $this->checkPrivileges($getprivileges);

        include("header.php");
        include("main.php");
        include("footer.php");

    }

    public function checkPrivileges($getprivileges) {
        $directory = $_SESSION['cwd'];                  // current directory
        $user = $_SESSION['simple_auth']['username'];   // get username
        $repository = gatorconf::get('repository');     // get base repertory of the file manager
        $userdir = $repository.DS.'user'.DS.$user;      // user's repertory

        if ((gator::checkPermissions('rw')) || ($userdir == $directory && gator::checkPermissions('rp'))) {
                return true;
        }

        $getprivileges = $this->scanDirectory($userdir, $directory);   // user's privileges
        return $getprivileges;

    }

    private function scanDirectory($userdir = '', $directory) {
        $folders = glob($userdir . '/*' , GLOB_ONLYDIR);
        foreach($folders as $folder){
            if (($folder == $directory && gator::checkPermissions('rp')) || (gator::checkPermissions('rw')) || ($userdir == $directory && gator::checkPermissions('rp'))) {
                return true;
            }

            if($this->scanDirectory($folder, $directory) === true) {
                return true;
            }
        }
        return false;

        scanDirectory($userdir, $directory);
    }

}

?>

and here is an exemple of the code I use to check the user's privileges inside the main.php page :
<?php
    if (gator::checkPrivileges($getprivileges) == true) {
        echo "privileges granted";
    }
    else {
        echo "you don't have the privileges";
    }
?>

My problem is that my checkPrivileges() method is only working if the first condition is met and true is returned. If it's not it seems like it does not return anything, and my script stops being executed at some point most likely on the main.php page when I use if (gator::checkPrivileges($getprivileges) == true) (I'm not entirely sure since I'm not getting any error message).
Anyways it really looks like there is something wrong going on with my method, I'm not very experienced in php but so far after testing several things it looks like it may come from :
$getprivileges = $this->scanDirectory($userdir, $directory);   // user's privileges
        return $getprivileges;

maybe it cannot call the scanDirectory, or the value cannot be returned, or something else, I'm completely stuck :/
If anyone has a solution for this or suggestions regarding my code, I would really appreciate.
Thank you !
update :
I used error_reporting(E_ALL & ~E_NOTICE); ini_set('display_errors', '1'); and here are the results (2 errors) :

Strict standards: Non-static method gator::checkPrivileges() should
  not be called statically in ... main.php on line 34

if (gator::checkPrivileges($getprivileges) == true) {

and

Fatal error: Using $this when not in object context in ...
  functions.php on line 97

$getprivileges = $this->scanDirectory($userdir, $directory);   // user's privileges

Both theses lines are included in the original post.
solution :
I changed both function to a static state, and modified the way I call my scanDirectory function inside the checkPrivileges method.
public static function checkPrivileges($getprivileges = false) {

    $directory = $_SESSION['cwd'];                  // current directory
    $user = $_SESSION['simple_auth']['username'];   // get username
    $repository = gatorconf::get('repository');     // get base repertory of the file manager
    $userdir = $repository.DS.'user'.DS.$user;      // user's repertory

    if ($userdir == $directory && gator::checkPermissions('rp')) {
        return true;
    }

    $getprivileges = gator::scanDirectory($userdir, $directory);   // user's privileges
    return $getprivileges;

}

private static function scanDirectory($userdir = '', $directory) {

    $folders = glob($userdir . '/*' , GLOB_ONLYDIR);
    foreach($folders as $folder){
        if (($folder == $directory && gator::checkPermissions('rp')) || (gator::checkPermissions('rw')) || ($userdir == $directory && gator::checkPermissions('rp'))) {
            return true;
        }

        if(gator::scanDirectory($folder, $directory) === true) {
            return true;
        }
    }
    return false;

}


text:
Q: Need to install applications on Cent OS supercomputer that has no connection to the internet I've inherited a project where I need to install a number of applications onto a brand new supercomputer running CentOS.  For instance, I need to install Git and Bugzilla and other things on there that I'm used to using yum for (where it fetches things via a connection to the internet). I have a Mac OSX for my work laptop and I'm connecting to the super computer's command line via an ethernet connection.
What's the best way to approach this kind of project?  Installing all the CPAN modules that Bugzilla needs by hand seems painful.  Is there a better way approach to something like this?

A: If you are connected via ethernet you can setup a repo for your own and rsync all files from an offical mirror to your local repo.
How to setup your own repo is described in centos wiki http://wiki.centos.org/HowTos/CreateLocalMirror


text:
Q: setting sample_weight_mode="temporal" doesn't seem to work I am working with LSTM in tensorflow 2.0 and I am trying to assign a weight to the training samples (I've already tried with class_weights dictionary but it complains that 3-d arrays are not supported for it. my array shape is (26000, 7, 1)).
As suggested in the documentation, I am setting sample_weight_mode to "temporal" in compile, but after that when I try to fit the model I still get the error below:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-100-1bb94008291c> in <module>
      1 with tf.device("/device:GPU:0"):
----> 2     model.fit(X, y, epochs=500, batch_size=4096, verbose=1, validation_split=0.2, sample_weight=cw.reshape(26000,7,1))

C:\ProgramData\Anaconda3\envs\thesis-gpu\lib\site-packages\tensorflow\python\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs)
    641         max_queue_size=max_queue_size,
    642         workers=workers,
--> 643         use_multiprocessing=use_multiprocessing)
    644
    645   def evaluate(self,

C:\ProgramData\Anaconda3\envs\thesis-gpu\lib\site-packages\tensorflow\python\keras\engine\training_arrays.py in fit(self, model, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, **kwargs)
    630         steps=steps_per_epoch,
    631         validation_split=validation_split,
--> 632         shuffle=shuffle)
    633
    634     if validation_data:

C:\ProgramData\Anaconda3\envs\thesis-gpu\lib\site-packages\tensorflow\python\keras\engine\training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, batch_size, check_steps, steps_name, steps, validation_split, shuffle, extract_tensors_from_dataset)
   2459           training_utils.standardize_weights(ref, sw, cw, mode)
   2460           for (ref, sw, cw, mode) in zip(y, sample_weights, class_weights,
-> 2461                                          feed_sample_weight_modes)
   2462       ]
   2463       # Check that all arrays have the same length.

C:\ProgramData\Anaconda3\envs\thesis-gpu\lib\site-packages\tensorflow\python\keras\engine\training.py in <listcomp>(.0)
   2458       sample_weights = [
   2459           training_utils.standardize_weights(ref, sw, cw, mode)
-> 2460           for (ref, sw, cw, mode) in zip(y, sample_weights, class_weights,
   2461                                          feed_sample_weight_modes)
   2462       ]

C:\ProgramData\Anaconda3\envs\thesis-gpu\lib\site-packages\tensorflow\python\keras\engine\training_utils.py in standardize_weights(y, sample_weight, class_weight, sample_weight_mode)
    839     if sample_weight is not None and len(sample_weight.shape) != 1:
    840       raise ValueError('Found a sample_weight array with shape ' +
--> 841                        str(sample_weight.shape) + '. '
    842                        'In order to use timestep-wise sample weights, '
    843                        'you should specify '

ValueError: Found a sample_weight array with shape (26000, 7, 1). In order to use timestep-wise sample weights, you should specify sample_weight_mode="temporal" in compile(). If you just mean to use sample-wise weights, make sure your sample_weight array is 1D.

I have already tried changing the shape of the sample_weights passed in fit (also tried to flatten it), setting shuffle to False and removing the validation split without success.
Here's the code I am using
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import math

# Import TensorFlow
import tensorflow as tf
from tensorflow.keras.optimizers import RMSprop, Adam, SGD
from tensorflow.keras.layers import SimpleRNN, LSTM, Dense
from tensorflow.keras.models import Sequential

from sklearn.utils import class_weight

class_weights = class_weight.compute_class_weight('balanced',
                                                 np.unique(y_train),
                                                 y_train)

cw = class_weight.compute_sample_weight({False:1, True:50},#'balanced',
                                                 #np.unique(y_train),
                                                 y.flatten())

model = Sequential()
model.add(LSTM(160, return_sequences=True, dropout=0.05))
model.add(LSTM(80, return_sequences=True, dropout=0.05, activation='relu'))
model.add(LSTM(40, return_sequences=True, dropout=0.05, activation='relu'))
model.add(LSTM(10, return_sequences=True, dropout=0.05))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc', tf.keras.metrics.AUC()], sample_weight_mode="temporal")

with tf.device("/device:GPU:0"):
    model.fit(X, y, epochs=500, batch_size=4096, verbose=1, validation_split=0.2, sample_weight=cw.reshape(26000,7,1))

A: Sample weighting applies to outputs (because what you are weighting is the loss!), not inputs, so it doesn't matter what your input dimensions are. The error message is explicitly about output dimensions.

A: The dimension of sample_weight cannot be greater than 2. If sample_weight_mode in the compile function is None, then sample_weight must be 1 dimensional. If sample_weight_mode in the compile function is 'temporal', then sample_weight must be 2 dimensional.
Additionally, it is always be true that y.shape[:sample_weight.ndim] == sample_weight.shape.
For more details, please refer to the source code of keras.engine.training_utils.standardize_weights.


text:
Q: Compiler Linking: How to handle circular references? I'm currently writing a compiler for a new language and I'm struggling with the linking aspect of new Types when there exists a circular reference.
I've created a dependency tree so that I can compile the Types in the order of their dependencies which seemed to have fixed my problem... that is until I hit circular references like an example below (posted in c#):
public class A
{
  public A() {  var b = new B(); }
}

public class B
{
  public B() { var a = new A(); }
}

My limitation is that I can only create 1 Type at a time, and in the case of circular references, either A needs to be created first, or B needs to be created first, both of which poses the problem that I can't create either unless it's dependencies are first created!
How do compilers overcome this?

A: In general, you create A and add it to the scope. When you get to resolve B, you go and build B. When that gets to resolving A, it finds a (partially) constructed type and grabs that reference. Then you return back to building A.
There are other situations that are more problematic (like cyclical inheritence, dll references, recursive type declarations) that often require placeholder types or are simply not viable given other design constraints. In general, keeping each compilation phase thin helps prevent issues. For example, you can only do the partial type trick if nothing needs to know the members of A in B.

A: I think you're trying to solve in the compiler something that should be resolved by the linker.  Both A and B should compile to whatever intermediate code they use (traditionally an object file) and just list the other type as an external symbol.  When you generate the executable form, you go through the symbol table for each object file and resolve the external references.  See this for a good introduction to traditional linkers.

A:
How do compilers overcome this?

Some languages (C++, Objective-C) allow forward declarations which introduce the type but don't define it. It'd go something like:
public class B;  // now the compiler knows that B is a class that will be defined later

public class A
{
  public A() {  var b = new B(); }
}

public class B
{
  public B() { var a = new A(); }
}

That said, even a forward declaration won't solve the circular problem in your example: Creating a new A will create a new B, which in turn will create another A, which will create another B, and so on. If you want one A and one B that point to each other, you'll need to create constructors that take a reference to an existing object, like:
public class A
{
  public A(B _b) { var b = _b; }
  public A()     { var b = new B(this); }  // 'this' is a C++-style pointer to the current object
}


text:
Q: How do I return the sum of values from a file? I am trying to convert a string of plus and minus signs from a file to +1 and -1 respectively, and then print the resulting sum of all of the plus and minus 1's.
Here is my attempt at the problem:
Problem statement and attempted code
I think the issue is in my return statements, but I haven't been able to figure it out.

A: You are returning the first operator you come across before iterating through all of them.
You should remove both the return statements inside the for loop i.e
return num_plus
return num_minus


text:
Q: doubly linked list in nasm assembly I wanted to do a double linked list in Nasm .
I have this structure for Node
struc node
left:   resd    0
right:  resd    0
data:   resd    0
endstruc

I do this when i want to use malloc
push    dword   [node_sz]
call    [malloc]
add     esp,    4 * 1

Where:
node_sz dd 4*3

Now i have in eax a pointer (offset) to the new location . Where are locations for my structure Node camp ( left , right ,data  ). For example i want to create a root with no neighbours with value 6. How i do that ?
mov [eax + data] , DWORD 6
mov [eax +left],DWORD 0
mov [eax+right],DWORD 0

or maybe
mov [eax + 4*2] , DWORD 6
mov [eax +4*0],DWORD 0
mov [eax+4*1],DWORD 0

A: Your syntax is incorrect. You forgot the dots at the beginning of each structure member. Also, the value after resd is the number of data items to "reserve" in the structure. It should be 1 in this case, not 0.
;; Declare a structure called "node".
;; Its size is an EQU named "node_size".
struc node
  .left:   resd    1
  .right:  resd    1
  .data:   resd    1
endstruc

;; External functions we wish to link against
extern malloc

start:
    push    node_size    ;; Use this constant instead of manually calculating
    call    malloc
    add     esp, 4

    mov [eax + node.left],  DWORD 6
    mov [eax + node.right], DWORD 7
    mov [eax + node.data],  DWORD 0xDEADBEEF

Example:
$ nasm -f elf struc.s

$ objdump -Mintel -d struc.o

struc.o:     file format elf32-i386

Disassembly of section .text:

00000000 <start>:
   0:   6a 0c                   push   0xc
   2:   e8 fc ff ff ff          call   3 <start+0x3>
   7:   83 c4 04                add    esp,0x4
   a:   c7 00 06 00 00 00       mov    DWORD PTR [eax],0x6
  10:   c7 40 04 07 00 00 00    mov    DWORD PTR [eax+0x4],0x7
  17:   c7 40 08 ef be ad de    mov    DWORD PTR [eax+0x8],0xdeadbeef


text:
Q: JavaScript: Get clicked element I need to get clicked element in function getClickedElement. How can I do this?

  click me!!!

I can set only href attribute.
I can not set onclick event because this elements is generated by third party lib.
Thanks.

A: You can't get the clicked element in a javascript: URL. The event has already finished, so there's no event.target (or window.event.srcElement for IE), and javascript: links are not invoked with this set (so you get window).
Of course if you know the link in question is id="test" you can do document.getElementById('test'), but I suspect that's rather missing the point of what you want to do.

I can set only href attribute. I can not set onclick event because this elements is generated by third party lib.

Fix or drop the lib. javascript: URLs are utter horrors that should never be used.
Can you add a

or, if you can't predict the ID, you can use Javascript to attach events after page is loaded. Look at jQuery. Use something like $('a').click(function() {return this.id; });

A: To detect clicks on any element on the whole page, you can set the "click" event of the document, and that should activate no matter which element you click.
document.addEventListener("click", function(e) {
  console.log("You clicked this element:", e.target);
});

For right-clicking, the event is "contextmenu".
Even if the target element calls e.preventDefault(), this still detects the click. The only exception is if the the target or one of its parent calls e.stopPropagation().

A: you can pass this as a parameter and you can then know what is the element you are looking for.
for example:

enter code here

  click me!!!

hope it will help you, it helped me :)


text:
Q: What does the denominator in the second derivative mean? This occurred to me a few days ago.
We know that the derivative of a function $y=f(x)$ is $\frac{dy}{dx}$.
This is because it represents how $y$ changes with $x$, which is the rate of change of $y$, or more specifically, the gradient of a function.
Then the second derivative is the rate of change of rate of change, or the rate of change of gradient. Since a general rate of change is $\frac{d}{dx}$, the second derivative is $(\frac{d}{dx})(\frac{dy}{dx})$. Thus, the expanded form is $\frac{d^2y}{dx^2}$.
My question is, is the denominator $d(x)^2$ or is it $(dx)^2$? Surely, it would be the latter, because when you expand $(\frac{d}{dx})(\frac{dy}{dx})$, the $(dx)(dx)$ would become $(dx)^2$. But then why is it never written with brackets? I'm sure that would confuse some people and I only realised it myself when I started thinking about the second derivative properly, in terms of what it actually means.

A: You are completely correct. When we write $\frac{d^2y}{dx^2}$, we really mean to write $\frac{d^2y}{(dx)^2}$, but those parentheses make the denominator difficult to read and write. Mathematicians accept the form $\frac{d^2y}{dx^2}$ without question, because it is not exactly an algebraic expression (although sometimes it can be treated as one), rather it is a notation that represents the concept of finding the rate of change of the rate of change.

A: You're right that it should really be $(dx)^2$ (if you were asking "why should that be?", see my answer here).
I suspect the brackets/parentheses aren't written because Leibniz himself didn't write them when he first presented the notation and everyone just followed his lead.

A: You are correct that $dx^2$ actually means $(dx)^2$. Or, even better, $(\text{d}x)^2$ (note the non-italicized $d$ because it is an operator not a variable).  However, if you are treating differentials as algebraic units, you can't use the standard notation of $\frac{d^2y}{dx^2}$.  If you actually perform the derivative of $\frac{dy}{dx}$ you will notice that $\frac{dy}{dx}$ is a quotient, and therefore requires the quotient rule for solving.  After simplifying everything, the second derivative using algebraically-manipulable differentials is actually $\frac{d^2y}{dx^2} - \frac{dy}{dx}\frac{d^2x}{dx^2}$.  Here, $d^2y$ is a shorthand for  $\textrm{d}(\textrm{d}(y))$ and $dx^2$ is a shorthand for $(\textrm{d}x)^2$.
Using this notation, the differentials of the second derivative can be algebraically manipulated freely, while using the standard notation they cannot.  The paper "Extending the Algebraic Manipulability of Differentials" explores this idea further.


text:
Q: Change psql copy command with dynamic headers I have following working copy command:
export PGPASSWORD=****;psql -h "****" -U "****" -c "\copy (SELECT id, \"accountType\" as \"ACCOUNT TYPE\", \"actReasonCode\" as \"ACT REASON\",\"adrCity\" as \"ADR CITY\" FROM schemaName.\"tableName\" where id > 0 and id<=8238226) TO STDOUT CSV HEADER" dbName >/sourcefile/test.CSV

Now,  Instead giving alias name in the query,my requirement is to get the header as input and append it in the copy command, something like below:
export PGPASSWORD=****;psql -h "****" -U "****" -c "\copy (SELECT id, \"accountType\", \"actReasonCode\",\"adrCity\" FROM schemaName.\"tableName\" where id > 0 and id<=8238226) TO STDOUT CSV HEADERS(ID,\"ACCOUNT TYPE\",\"ACT REASON\",\"ADR CITY\") " dbName >/sourcefile/test.CSV

Can anyone please help me with this.

A: You might have misunderstood the HEADER keyword.

HEADER [boolean]
Specifies that the file contains a header line with the names of each column in the file. On output, the first line contains the column names from the table, and on input, the first line is ignored. This option is allowed only when using CSV format.

From https://www.postgresql.org/docs/9.2/sql-copy.html
As you can see, the option allows you to enable or disable the printing of a header line. It is not meant to be used to select which columns to print. That is part of your SELECT in the beginning of your query.


text:
Q: Resolve Promise in VueJs and IE11 In my project I need to setup an IE11 compatible VueJs application where I'm using polyfills for fetch and promises.
Now my problem is, that the IE11 obviously also doesn't support "Fat arrows" as well. Using functions instead of Fat arrows I'm loosing my context so that I'm not able to set the resposne to my data.
let app = new Vue({
    data: {
        myindex : []
    },
    beforeMount: function(){
        myClient.getIndex().then((index) => this.myIndex = index); //This does not work in IE11 due to the fat arrow

        myClient.getIndex().then(function(index) => {
            this.myIndex = index
        }); // This does not work due to the missing context. this.myIndex is not known here...
    }
});

Is there any "native" way to set the response/result to data.


text:
Q: href click2dial:9898989898 not working in IE9 show modal dialog I am opening a modal dialog with window.showModalDialog. My page is in AngularJs.
I have a simple link tag
c2d

clicking on that link does not work when the page is open in modal dialog.
if the page is opened directly in the browser that link works.
Is angularjs intercepting url change ?


text:
Q: Use StringCchCat function with CreateFile I have the following code to write a simple TXT using the CreateFile function from the WinAPI:
#include <stdio.h>
#include <windows.h>
#include <Wincrypt.h>

#include <string.h>
#include <tchar.h>
#include <strsafe.h>
#include <iostream>

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {

    LPCTSTR lpFileName = L"C:\\MyTest.txt";
    DWORD dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
    DWORD dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
    LPSECURITY_ATTRIBUTES lpSecurityAttributes = NULL;
    DWORD dwCreationDisposition = CREATE_NEW;
    DWORD dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
    HANDLE hTemplateFile = NULL;

    HANDLE C=CreateFile(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes,
        dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);

    DWORD Er=GetLastError();

    char *pMsg = NULL;

    FormatMessageW(
        FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ARGUMENT_ARRAY | FORMAT_MESSAGE_ALLOCATE_BUFFER,
        NULL,
        Er,
        LANG_SYSTEM_DEFAULT,
        (LPWSTR)&pMsg,
        0,
        NULL
        );

    if (C != INVALID_HANDLE_VALUE)

    {
        MessageBox(NULL, (LPCTSTR)pMsg, L"Explorando la API", MB_ICONINFORMATION);
    }
    else
    {

        MessageBox(NULL, (LPCTSTR)pMsg, L"Explorando la API", MB_ICONINFORMATION);
    }

    CloseHandle(C);

}

The question is: How can I use StringCchCat function to pass a customized string to the lpFile name?
I would like to read any number from a Registry Key (Using the RegQueryValue) and give a name to the file. For example, if I read "1" form a DemoValue, the TXT name would be: MyText1.txt or MyText(1).txt.
Can you help me? Thanks!

A: You probably want to use StringCbPrintf instead of StringCchCat.
int const filenamesize = 30;
TCHAR filename[filenamesize];
StringCbPrintf(filename, filenamesize * sizeof(TCHAR), TEXT("Myfile(%d).txt", somevalue);
// e.g: filename contains a "Myfile(1).txt" if 'somevalue' contains 1
...
HANDLE c = CreateFile(filename, ...) ;


text:
Q: docker: cannot map two container ports to one host port app.json for pm2 (src/app.py is Flask app):
{
    "apps": [
    {
      "exec_mode": "fork",
      "script": "src/app.py",
      "args": ["-p", "8080"]
    },
    {
      "exec_mode": "fork",
      "script": "src/app.py",
      "args": ["-p", "8081"]
    }
  ]
}
~

Dockerfile:
EXPOSE 8080 8081
CMD ["pm2", "start", "app.json"]

Error when running docker:
docker run -p 8080:8080 -p 8080:8081 oct20
docker: Error response from daemon: driver failed programming external connectivity on endpoint high_fermi (xxxxxxxxxxx): Bind for 0.0.0.0:8080 failed: port is already allocated.

Any ideas? Thanks

A: You can't have two things listening on one port in the host - whether they're separate ports in one container, or two Docker containers, or two other apps. It's not a Docker limitation, it's part of the OS networking stack.
Where would the host send a request to port 8080 if you could do that in this case? To port 8080 in the container, or port 8081, or multicast it to both?


text:
Q: How do I remove the elements of one vector from another? I have a double value, A, which is
[1,4,7,6]

I also have B, which is an array that contains many more values. I have a new variable, C, which is essentially a double value of all these numbers (all of them in one cell, vs. five).
[1,4,7,6]
[2,6,9,12]
[3,1,17,13]
[5,7,13,19]
[1,5,9,15]

How do I remove the elements (not the actual values) from C? I want to end up with this.
 [2,6,9,12,3,1,17,13,5,7,13,19,1,5,9,15]

How do I get this? I've used these commands:
C(A) = [];

and
C = C(setdiff(1:length(C),A));

The problem is that when I run that command, I get this instead of what I want.
[4,7,2,12,3,1,17,13,5,7,13,19,1,5,9,15]

Clearly that isn't the same as what I have. It's throwing off the rest of my results and I need to fix this specific issue.
Thanks in advance :)
EDIT:
So I figured out that it's spewing the CORRECT numbers out, just in the wrong order. I have to sort it in order for it to work correctly. This is a problem because it causes the next command to be non-functional because the ismember command has issues with the removal (I don't know why, I'm still working on it).

A: Double array case
If B is a double array, you can use setdiff with 'rows' and 'stable' options, like so -
C = reshape(setdiff(B,A,'rows','stable').',1,[])

With ismember, you can perform the same operation, like so -
C = reshape(B(~ismember(B,A,'rows'),:).',1,[])

You can also use a bsxfun approach as suggested by @Amro -
C = reshape(B(~all(bsxfun(@eq, B, A),2),:).',1,[])

Cell array case
If B is a cell array with number of elements in each cell equal to the number of elements in A, then you can firstly convert it to a double array - B = vertcat(B{:}) and then use either of the above mentioned tools.
Or you can use a cellfun based approach that avoids conversion to a double array, like so -
excl_rows = B(~cellfun(@(x1,x2) isequal(x1,x2), B, repmat({A},size(B,1),1)),:)
C = horzcat(excl_rows{:})

Or another cellfun based approach that avoids repmat -
exclB = B(~cellfun(@(x1) isequal(x1,A), B),:)
C = horzcat(exclB{:})

Example with explanation -
%// Inputs
A = [1,4,7,6]
B = {[1,4,7,6]
    [2,6,9,12]
    [3,1,17,13]
    [5,7,13,19]
    [1,5,9,15]}

%// Compare each cell of B with A for equality.
%// The output must be a binary array where one would be for cells that have
%// elements same as A and zero otherwise.
ind = cellfun(@(x1) isequal(x1,A), B)

%// Thus, ~ind would be a binary array where one would reperesent unequal
%// cells that are to be selected in B for the final output.
exclB = B(~ind)

%// exclB is still a cell array with the cells that are different from A.
%// So, concatenate the elements from exclB into a vector as requested.
C = horzcat(exclB{:})

Output -
A =
     1     4     7     6
B =
    [1x4 double]
    [1x4 double]
    [1x4 double]
    [1x4 double]
    [1x4 double]
ind =
     1
     0
     0
     0
     0
exclB =
    [1x4 double]
    [1x4 double]
    [1x4 double]
    [1x4 double]
C =
     2     6     9    12     3     1    17    13     5     7    13    19     1     5     9    15


text:
Q: Binary detection problem with side information Assume we have an input random variable that takes values +1 or -1. And it goes through AWGN channel. The noise is gaussian distributed N(0,1). The output is Y1.
a) How do we find the probability X=1 or -1 based on the output Y
This would be based on Bayes rule and you decide on X=1 if Y>0.
b) If we have another random variable Y2=N1+N2 , can we use Y2 and Y1 together in some way additional information to make decision on X.
I am thinking of computing P(Y1Y2|X1) but I don't know how to proceed.
Thank you for your help.

A: a) Yes. Let $Y=X+Z$ with $P(X=1)=p$, $P(X=-1)=1-p$, $Z\perp X$ and $Z\sim\mathcal{N}(0,1)$. Then $Y|X=x\sim\mathcal{N}(x,1)$:
$$P(X=1|Y=y)=\frac{f_{Y|X=1}(y)P(X=1)}{f_{Y|X=-1}(y)P(X=-1)+f_{Y|X=1}(y)P(X=1)}=\frac{pe^{-\frac{(y-1)^2}{2}}}{(1-p)e^{-\frac{(y+1)^2}{2}}+pe^{-\frac{(y-1)^2}{2}}}$$
b) Yes again. Let $Y_1=X+Z_1$ and $Y_2=X+Z_2$, with $P(X=1)=p$, $P(X=-1)=1-p$, $Z_1\perp Z_2\perp X$ and $Z_1,Z_2\sim\mathcal{N}(0,1)$. Then we can write
$$\binom{Y_1}{Y_2}=X\cdot\binom{1}{1}+\binom{Z_1}{Z_2}$$
Then $\binom{Y_1}{Y_2}|_{X=x}\sim\mathcal{N}_2\left(\left(\begin{array}{c}x\\x\end{array}\right),\left(\begin{array}{cc}1&0\\0&1\end{array}\right)\right)$ (remain iid: $Y_1|_{X=x}\sim Y_2|_{X=x}\sim Y|_{X=x}$ ) and
\begin{align}
P(X=1|Y_1=y_1,Y_2=y_2)&=\frac{f_{Y|X=1}(y_1)f_{Y|X=1}(y_2)P(X=1)}{f_{Y|X=-1}(y_1)f_{Y|X=-1}(y_2)P(X=-1)+f_{Y|X=1}(y_1)f_{Y|X=1}(y_2)P(X=1)}\\
&=\frac{pe^{\frac{(y_1-1)^2}{2}-\frac{(y_2-1)^2}{2}}}{(1-p)e^{\frac{(y_1+1)^2}{2}-\frac{(y_2+1)^2}{2}}+pe^{\frac{(y_1-1)^2}{2}-\frac{(y_2-1)^2}{2}}}
\end{align}


text:
Q: Выход из функции через confirm Есть функция-игра "Угадай число", в ней за 10 попыток пользователь должен угадать рандомное число. Если угадал-alert выводит "Вы угадали!" В этом же случае должно появиться сообщение через confirm "Начать новую игру?". У меня получается так, что если пользователь нажимает "отмена", игра все равно продолжается. Как сделать, чтобы при нажатии на отмену игра заканчивалась?

let guessNumber = (function () {
    let randomNum = parseInt(Math.random() * 1000);
    console.log(randomNum);
    let attempts = 9;
    let userNum = prompt('Введите число. У Вас 10 попыток');
    return function () {

        if (userNum) {

            if (isNaN(userNum)) {
                alert('Можно вводить только числа');
                userNum = +prompt('Введите число');
            }

            if (attempts === 0) {
                alert('Попытки закончились');
                return;
            }

            if (userNum == randomNum) {
                alert('Верно, Вы угадали загаданное число!');
                confirm('Начать новую игру?');
                attempts = 9;
                randomNum = parseInt(Math.random() * 1000);
                userNum = +prompt('Введите число');

            } else if (userNum < randomNum) {
                alert('Ваше число меньше! Осталось попыток: ' + attempts);
                userNum = +prompt('Введите число');

            } else if (userNum > randomNum) {
                alert('Ваше число больше! Осталось попыток: ' + attempts);
                userNum = +prompt('Введите число');

            }

            attempts--;
            guessNumber();
        }
    }

})();

A: confirm() возвращает только true или false. Можно сразу его и отправить на проверку if. Если отменят, вернется false, а !false → true (восклицательный знак при необходимости приводит к логическому типу и переворачивает полученное значение)

test();

function test() {
  if (!confirm('Начать новую игру?')) {
    console.log("Игра завершена.");
    return;
  }

  console.log("Игра продолжается!");
}

В контексте вашей функции это выглядит так:
if (userNum == randomNum) {
  alert('Верно, Вы угадали загаданное число!');

  if (!confirm('Начать новую игру?')) return;

  attempts = 9;
  randomNum = parseInt(Math.random() * 1000);
  userNum = +prompt('Введите число');

  return guessNumber();

}

В вопросе вы там забыли вызвать guessNumber();
Но получается, старт игры одинаково прописан и во время получения функции-замыкания, и после confirm. Тут вместо замыкания можно использовать отдельную функцию, запускающую игру. Псевдокод:
startGame();

function startGame(attempts = 9) {
  let randNum = Math.random() * 1000 | 0;

  guessNumber(attempts, randNum);
}

function guessNumber(attempts, randNum) {
  // Вместо замыкания, числа прилетают в виде параметров.

  let userNum = +prompt('Введите число');
  // prompt, alert, ляляля

  if (угадали) return confirm() ? startGame() : null; // см. → Тернарный Оператор

  guessNumber(--attempts, randNum);
}

A: Синхронная функция "confirm" не только выведет сообщение на экран, но и результатом своей работы вернёт true или false в зависимости от того, что нажал пользователь (Ок или Отмена)
Так что Вам необходимо получать результат работы функции и обрабатывать его
const answer = confirm('Ок или Отмена?');
if(answer === true) console.log('Нажали Окей')
else console.log('Нажали отмена')

Ссылка на документацию по функции:
https://www.w3schools.com/jsref/met_win_confirm.asp
Так же мой вариант исполнения. Но с рекурсией:
//"Правильная" функция рандомного числа от min до max
const randomInteger = (min, max) => Math.round(min - 0.5 + Math.random() * (max - min + 1));

const minNumber = 1, maxNumber = 1000;

const guessNumber = (attempts = 10, randomNum = randomInteger(minNumber, maxNumber)) => {

    if (attempts === 0) {
        alert('Попытки закончились');
        return;
    }

    console.log(`Загаданное число: ${randomNum}`);

    const userNum = Number(prompt(`Введите число от ${minNumber} до ${maxNumber}. У Вас ${attempts} попыток`));

    if (userNum < 0 || userNum > maxNumber || userNum < minNumber) {
        alert(`Можно вводить только положительные числа от ${minNumber} до ${maxNumber}`);
        return guessNumber(attempts, randomNum);
    }

    if (userNum === randomNum) {
        alert('Верно, Вы угадали загаданное число!');
        if(confirm('Начать новую игру?')) {
            return guessNumber();
        }
    } else {
        alert(`Ваше число ${(userNum < randomNum ? 'меньше' : 'больше')}! Осталось попыток: ${attempts -1}`);
        return guessNumber(--attempts, randomNum);
    }
}

guessNumber();


text:
Q: Magento 2 : Increase sold count after order status completes I'm new to Magento 2.
I want to show the sold count of product only after the order was complete.
I have used this code to display count.
$_product = $block->getProduct();
$sku = $_product->getSku();
$objectModelManager = \Magento\Framework\App\ObjectManager::getInstance ();
$soldproduct = $objectModelManager->get('Magento\Reports\Model\ResourceModel\Product\Sold\Collection')->addOrderedQty()->addAttributeToFilter('sku', $sku)->setOrder('ordered_qty', 'desc')->getFirstItem();
$soldnumber = $soldproduct->getOrderedQty();
?> <div class="sold_count"><b>Sold Count: </b> <?php echo (int)$soldnumber;?> </div>

But for every order placement the count is increasing.But I want show the count of products whose status was completed.
Thanks in advance

A: we added code above but not showing (magento 2.3.4)

A: I got the solution.We can filter based on the order state 'complete'(addAttributeToFilter('state', 'complete'))
$soldproduct = $objectModelManager->get('Magento\Reports\Model\ResourceModel\Product\Sold\Collection')->addOrderedQty()->addAttributeToFilter('sku', $sku)->setOrder('ordered_qty', 'desc')->addAttributeToFilter('state', 'complete')->getFirstItem();


text:
Q: Mongoose population ref Hye!
This is an example of http://mongoosejs.com/docs
var personSchema = Schema({
   _id     : Number,
   name    : String,
   age     : Number,
   stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});

var storySchema = Schema({
_creator : { type: Number, ref: 'Person' },
title    : String,
fans     : [{ type: Number, ref: 'Person' }]
});
var Story  = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);

Story
.findOne({ title: 'Once upon a timex.' })
.populate('_creator')
.exec(function (err, story) {
if (err) return handleError(err);
console.log('The creator is %s', story._creator.name);
// prints "The creator is Aaron"
})

And that is my codeMy '_creator' is not an array but an array of objects :
var storySchema = Schema({
   _creator : [{
       _id : { type: Number, ref: 'Person' },
       quantity : Number
   }],
   ...
});

And my request is :
Story
.findOne({ title: 'Once upon a timex.' })
.populate('_creator._id')
.exec(function (err, story) {
if (err) return handleError(err);
console.log('The creator is %s', story._creator.name);
// prints "The creator is Aaron"
})

But this solution 'populate('_creator._id')' doesn't work.
Have you got an idea?
Thank you!


text:
Q: How do I prevent access to a set of folders, but allow access to images in a subfolder of one of the folders (with .htaccess)? In my root web folder I have a list of folders (files, modules, classes) that I'm using .htaccess to prevent access to. However, in the modules/ folder, there are modules that carry their own images, which I'd like to allow access to.
How do I allow access to images in a folder under modules/, but still prevent accessing any other files in that same directory path?

A: Try this in your .htaccess. It should let you grant access to images within the directory. You may need to tweak this to make it work for you.
<FilesMatch "\.(gif|jpe?g|png)$">
Order allow,deny
Allow from all
</FilesMatch>

A: I believe if you read this document: http://httpd.apache.org/docs/1.3/howto/htaccess.html you will gain insight as to how to achieve the access permissions you desire.
To sum it up, without rewriting the document: you can allow access to the directories that you wish either through .htaccess files in those folders, and .htaccess files can be placed at any level in your directory tree.
Further, the article also makes some suggestions that may perform better by using your main server config file instead of .htaccess files.
Hope this helps,
-james


text:
Q: What is the right way to restart GlassFish 4? When I need to restart GF 4.0 I do
asadmin restart-domain

However, if there is running code at this time, for example if someone started database transaction and did half of this transaction? Will GF wait until all running threads finish their job?

A: Yes, if you gracefully shut down glassfish (using asadmin executed graceful commands), it will wait for all current requests to finish as well as prevent new requests.


text:
Q: How do I set an orientation specific background in a Windows Store Application? I have a Windows Store Application where I've been supplied a different background image asset depending on whether the app is running in Portrait or Landscape mode.
Other than this background image, there are no other orientation specific differences.
What is the tidiest way to implement this requirement?

A: You can set it in Window.Current.SizeChanged handler:
Window.Current.SizeChanged += (sender, args) =>
{
    if (ApplicationView.Value == ApplicationViewState.FullScreenLandscape)
    {
        // ...
    }
    else if (ApplicationView.Value == ApplicationViewState.FullScreenPortrait)
    {
        // ...
    }
};


text:
Q: SwiftUI ScrollView with Path element not showing all This sample code illustrates my problem:
import SwiftUI

struct ContentView: View {
    var body: some View {
        ScrollView {
            VStack {
                subviewone()
                subviewone()
                subviewone()
                subviewone()
                subviewone()
                subviewone()
                graph()
            }.padding(.all)

        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct graph: View {
    var body: some View {
        GeometryReader { geo in
            Path { path in
                path.move(to: CGPoint(x: 0, y: 0))
                path.addLine(to: CGPoint(x: geo.size.width, y: 0))
                path.addLine(to: CGPoint(x: geo.size.width, y: geo.size.width))
            }.fill(Color.red)

        }
    }
}

struct subviewone: View {
    var body: some View {
        VStack {
            Text("testtest")
            Text("testtest")
            Text("testtest")
            Text("testtest")
            Text("testtest")
            Text("testtest")
            Text("testtest")
        }

    }
}

I need one view to display some graph, and I need the size of the space allocated for the graph view to scale the axis.
That is why I placed it inside GeometryReader.
When I run this code on a device that would need to scroll (iPhone 8 for example), I am unable to scroll to see the whole "graph".
It looks as if the "graph view" is somehow drawn outside of the ScrollView.
Setting frame on the Path view doesn't help.
Thank you for any help provided.

A: 1) you should use Shape, because then you get a rect in which you can "paint"
2) you have to give a frame with it, because Apple does not know how big your shape is (see the Rectangles i appended at the end)
3) if you do not give a frame with it, you get a "default" height for your shape, as Rectangles get it
struct ContentView: View {
    var body: some View {
        ScrollView {
            VStack {
                subviewone()
                subviewone()
                subviewone()
                subviewone()
                subviewone()
                subviewone()
                graph()
                    .fill(Color.red)
                    .frame(height:400) // or:  .aspectRatio(contentMode: .fill)
                Rectangle()
                Rectangle()
                Rectangle()

            }.padding(.all)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct graph: Shape {
    func path(in rect: CGRect) -> Path {
        Path { path in
            path.move(to: CGPoint(x: 0, y: 0))
            path.addLine(to: CGPoint(x: rect.size.width, y: 0))
            path.addLine(to: CGPoint(x: rect.size.width, y: rect.size.width))
        }
    }
}

struct subviewone: View {
    var body: some View {
        VStack {
            Text("testtest")
            Text("testtest")
            Text("testtest")
            Text("testtest")
            Text("testtest")
            Text("testtest")
            Text("testtest")
        }

    }
}


text:
Q: ¿Por qué la animación de details no funcionaa en Safari ni Chrome? Quisiera darle una animación a details cuando se abre e intenté con:
transition
Esta fue la forma más sencilla:

details p {
    transition: background-color 1s;
    background-color: red;
}

details[open] p {
    background-color: greenyellow;
}

    África

Lorem ipsum dolor sit, amet consectetur adipisicing elit. Alias, aut.

Pero no se aplica la transición en Chrome ni en Safari como se muestra a continuación:

Firefox
Chrome, Safari

animation
Usando la respuesta de otra pregunta intenté con:

@keyframes transformColor {
    from {
        background-color: red;
    }
}

details[open] p {
    background-color: greenyellow;
    animation: transformColor 1s;
}

    África

Lorem ipsum dolor sit, amet consectetur adipisicing elit. Alias, aut.

Y me funciona bien esta opción en Chrome pero en Safari solo se ejecuta una vez la animación:

¿Hay alguna forma que la animación se vea como en Firefox?, no importa si es con transition o con animation.

Versiones:

*

*Chrome 89

*Safari (para ios 14.4.12)

*Firefox 89

A: Creo que no te lo toma porque no tiene las versiones definidas en css.
acá te dejo esto:

@keyframes transformColor {
    from {
        background-color: red;
    }
}
details[open] p {
  background-color: greenyellow;
  -webkit-animation: transformColor 1s; /* Safari y Chrome */
  -moz-animation: transformColor 1s;/* Firefox */
  -o-animation: transformColor 1s; /* IE 9 */
  -ms-animation: transformColor 1s; /* Opera */
  animation: transformColor 1s;
}

    África

Lorem ipsum dolor sit, amet consectetur adipisicing elit. Alias, aut.

Espero ayudarte con esto, cualquier cosa me comentas, Suerte!


text:
Q: How to retrieve Ids of a collection of objects after savechanges from database using Entity Framework code first I have a method to add a collection of objects to database using code first.
Here collection is added using AddRange method. But I need Ids (primary keys)
of each added object from database. Here primary key is numeric and auto incremented. How it retrieve it?
Thanks
private bool CaseTaskMapping(long workFlowId,long caseDetailId)
{
    if (workFlowId > 0)
    {
        try
        {
            var StateList = dbContext.States.Where(state => state.WorkflowId == workFlowId);
           List<CaseTaskMapping> CaseTaskMappingList = new List<CaseTaskMapping>();

           foreach (var state in StateList)
           {
               var TaskList = dbContext.Tasks.Where(task => task.StateId == state.StateId);

               foreach (var tasks in TaskList)
               {
                   CaseTaskMappingList.Add(new CaseTaskMapping
                        {
                            CaseDetailsId = caseDetailId,
                            TaskId = tasks.TaskId,
                            IsComplete = false,
                            LastUpdatedBy = GetLoggedUserId(),
                            LastUpdatedOn = DateTime.Now
                        });
               }
           }

           dbContext.CaseTaskMappings.AddRange(CaseTaskMappingList);
           dbContext.SaveChanges();

           // Here I need Ids of the above collection save to the database
           return true;
       }
    }
}

A: Entity Framework is going to automatically populate the Primary Keys on the newly added objects after SaveChanges is called.
Since you already have references to all the objects that are being added in a variable named CaseTaskMappingList, you can simply use that same variable to get the new Ids after SaveChanges operation.
var insertedKeys = CaseTaskMappingList.Select(x => x.Id); // assuming that Id is the name of Primary Key


text:
Q: Any android open source ImageView? I need an ImageView that can be touched zoom in/out and pan. Each time when I touch the ImageView, I need to know the touch position of the source image. For example the image resolution is 1280*720, even the image in the ImageView is zoomed in, I still know exactly the touch position of the image(not touch position of the ImageView)
Thanks.

A: Why don't you skip all that and use an existing library?
Try this: PhotoView  works perfectly for me on API 23, with just a few lines of code you will be able to zoom in/out and pan
compile 'com.github.chrisbanes:PhotoView:1.3.0'

repositories {
    ...
    maven { url "https://jitpack.io" }
}

Example
ImageView mImageView;
PhotoViewAttacher mAttacher;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Any implementation of ImageView can be used!
mImageView = (ImageView) findViewById(R.id.iv_photo);

// Set the Drawable displayed
Drawable bitmap = getResources().getDrawable(R.drawable.wallpaper);
mImageView.setImageDrawable(bitmap);

// Attach a PhotoViewAttacher, which takes care of all of the zooming functionality.
// (not needed unless you are going to change the drawable later)
mAttacher = new PhotoViewAttacher(mImageView);
}

// If you later call mImageView.setImageDrawable/setImageBitmap/setImageResource/etc then you just need to call
mAttacher.update();

A: Finally, I used this open source code
https://github.com/sephiroth74/ImageViewZoom
I modified the code, but there is still a lot of bugs in this open source project, I have fixed several of them.
The following function was added to class ImageViewTouch.GestureListener which is used to transfer touchpoint(in screen) to point in the real image(no matter the image is zoom in/out).
    private PointF calculatePositionInSourceImage(PointF touchPointF) {
        //point relative to imageRect
        PointF touchPointRelativeToImageRect = new PointF();
        RectF imageRect = getBitmapRect();
        touchPointRelativeToImageRect.set(touchPointF.x - imageRect.left,
                touchPointF.y - imageRect.top);

        //real image resolution
        int imageWidth = getDrawable().getIntrinsicWidth();
        int imageHeight = getDrawable().getIntrinsicHeight();

        //touch point in image
        PointF touchPointRelativeToImage = new PointF();
        touchPointRelativeToImage.set(touchPointRelativeToImageRect.x/imageRect.width() * imageWidth,
                touchPointRelativeToImageRect.y/imageRect.height() * imageHeight);

        if(touchPointRelativeToImage.x < 0 || touchPointRelativeToImage.y < 0 )
            touchPointRelativeToImage.set(0,0);

        return  touchPointRelativeToImage;
    }


text:
Q: Can I send a video stream even if the user does not have a webcam? I am working on a video conference and I am using connection.waitUntilRemoteStreamStartsFlowing = true; before I do something else. It works fine except when a user does not have a webcam. Is there any way I could still send a video stream from that user with no Webcam?

A: That would be a waste of good bandwidth. I'm not familiar with the library you're using, but with plain WebRTC, like in this textbook WebRTC sample which uses adapter.js, you can do this:
Call navigator.mediaDevices.enumerateDevices() to learn how many cameras and microphones the user has:
navigator.mediaDevices.enumerateDevices()
.then(function(devices) {
  var hasCam = devices.some(function(d) { return d.kind == "videoinput"; });
  var hasMic = devices.some(function(d) { return d.kind == "audioinput"; });
  ...
})

Armed with this info, skip asking the user for their camera if they don't have one:
var constraints = { video: hasCam, audio: hasMic };

navigator.mediaDevices.getUserMedia(constraints)
.then(function(stream) {
  myPeerConnection.addStream(stream);
})

Lastly, if you don't send video, then the default is not to receive video either (silly default), so in case the other party has a camera, use RTCOfferOptions:
var options = { offerToReceiveAudio: true, offerToReceiveVideo: true };

myPeerConnection.createOffer(options)
.then(function(offer) { ... })

In Chrome you'll need adapter.js for all but the last bit, but in the latest Firefox it should just work (note: uses arrow-functions):

var pc1 = new mozRTCPeerConnection(), pc2 = new mozRTCPeerConnection();

navigator.mediaDevices.enumerateDevices()
.then(devices => navigator.mediaDevices.getUserMedia({
  video: devices.some(device => device.kind == "videoinput"),
  audio: devices.some(device => device.kind == "audioinput")
}))
.then(stream => pc1.addStream(v1.mozSrcObject = stream))
.then(() => pc1.createOffer({ offerToReceiveAudio: true,
                              offerToReceiveVideo: true }))
.then(offer => pc1.setLocalDescription(offer))
.then(() => pc2.setRemoteDescription(pc1.localDescription))
.then(() => pc2.createAnswer())
.then(answer => pc2.setLocalDescription(answer))
.then(() => pc1.setRemoteDescription(pc2.localDescription))
.then(() => log("Connected!"))
.catch(failed);

pc1.onicecandidate = e => !e.candidate ||
    pc2.addIceCandidate(e.candidate).catch(failed);
pc2.onicecandidate = e => !e.candidate ||
    pc1.addIceCandidate(e.candidate).catch(failed);
pc2.onaddstream = e => v2.mozSrcObject = e.stream;

var log = msg => div.innerHTML += msg + "
";
var failed = e => log(e.toString() +", line "+ e.lineNumber);
<video id="v1" height="120" width="160" autoplay></video>
<video id="v2" height="120" width="160" autoplay></video>

Parts of this is brand new, so I'm not sure how well it integrates with the library you are using just yet, but it should over time.
Chrome has an older version of this API which I wont mention here since it is not standard.


text:
Q: How to dynamically switch color with Leaflet's pulse icon Given my code below, I have added a non-pulsing marker to my map, using L.icon.pulse:
m = L.geoJSON(metaFeatures, {
  pointToLayer: function (feature, latlng) {
    var pulsingIcon = L.icon.pulse({
      iconSize: [3, 3],
      color: color,
      fillColor: color,
      animate: false,
    });
    var pulseMarker = L.marker(coordinates, { icon: pulsingIcon });
    return pulseMarker;

    //...
  },
});

Later when I wish to change the animate:false to animate:true and change the color to red.
Note: if the marker was:
var circle = L.circleMarker(latlng, geojsonMarkerOptions);

I would be able to do: layer.setStyle({fillColor:'blue'}); and that would solve the problem but since this is a L.Marker it cannot be done.

A: In Leaflet, instances of L.Marker don't have any .setStyle(), method, but they do have a .setIcon() method.
Therefore, you can create several instances of L.Icon and have your markers use one or the other, e.g.:

var map = new L.Map('leaflet', {
    layers: [
        new L.TileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            'attribution': 'Map data © OpenStreetMap contributors'
        })
    ],
    center: [0, 0],
    zoom: 0
});

var blueIcon = L.icon.pulse({ color: "blue", fillColor: "blue", animate: false});
var redIcon = L.icon.pulse({ color: "red", fillColor: "red", animate: true});

var mymarker = L.marker([0,0], {icon: blueIcon}).addTo(map);

L.DomEvent.on(document.getElementById('change-to-red'), 'click', function(){
  mymarker.setIcon(redIcon);
})
#leaflet { min-height: 300px; }
<link type="text/css" rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
<link type="text/css" rel="stylesheet" href="https://unpkg.com/leaflet-pulse-icon@0.1.0/src/L.Icon.Pulse.css" />

<button id='change-to-red'>Change to red!</button>