text:
Q: How to fix FileNotFoundError in docker-compose I am taking a course on docker and it seems there is an issue with the docker build of the sample backend node app.
frontend dockerfile:
FROM node:14.16.0-alpine3.13
RUN addgroup app && adduser -S -G app app
USER app
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["npm", "start"]

backend dockerfile:
FROM node:14.16.0-alpine3.13
RUN addgroup app && adduser -S -G app app
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3001
USER app
CMD ["npm", "start"]

docker-compose.yml:
version: "3.8"

services:
  frontend:
    depends_on:
      - backend
    build: ./frontend
    ports:
      - 3000:3000

  backend:
    depends_on:
      - db
    build: ./backend
    ports:
      - 3001:3001
    environment:
      DB_URL: mongodb://db/vidly
    command: ./docker-entrypoint.sh

  db:
    image: mongo:4.0-xenial
    ports:
      - 27017:27017
    volumes:
      - vidly:/data/db

volumes:
  vidly:

Tracback:
Building backend
Sending build context to Docker daemon  291.3kB
Step 1/9 : FROM node:14.16.0-alpine3.13
14.16.0-alpine3.13: Pulling from library/node
ca3cd42a7c95: Pull complete
cf8dc363e30f: Pull complete
074ae49463c4: Pull complete
48fd78e4b532: Pull complete
Digest: sha256:2c51dc462a02f15621e7486774d36d048a27225d581374b002b8477a79a59b4b
Status: Downloaded newer image for node:14.16.0-alpine3.13
 ---> 50bfd284aa0d
Step 2/9 : RUN addgroup app && adduser -S -G app app
 ---> Running in 4183bada01d2
Removing intermediate container 4183bada01d2
 ---> 0c55d313489a
Step 3/9 : WORKDIR /app
 ---> Running in e6da0a502c0c
Removing intermediate container e6da0a502c0c
 ---> c62eee1e61e1
Step 4/9 : COPY package*.json ./
 ---> caad8596ddd4
Step 5/9 : RUN npm install
 ---> Running in 5d2f331053db

> nodemon@2.0.7 postinstall /app/node_modules/nodemon
> node bin/postinstall || exit 0

Love nodemon? You can now support the project via the open collective:
 > https://opencollective.com/nodemon/donate

npm WARN vidly-backend@1.0.0 No description
npm WARN vidly-backend@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.1 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.1: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

added 770 packages from 462 contributors and audited 771 packages in 10.856s

35 packages are looking for funding
  run `npm fund` for details

found 90 vulnerabilities (61 moderate, 28 high, 1 critical)
  run `npm audit fix` to fix them, or `npm audit` for details
Removing intermediate container 5d2f331053db
 ---> 89123dc063c8
Step 6/9 : COPY . .
 ---> 74c3d17d99a8
Step 7/9 : EXPOSE 3001
 ---> Running in db775adf83f0
Removing intermediate container db775adf83f0
 ---> 82e0d9220d54
Step 8/9 : USER app
 ---> Running in 95d1419578ac
Removing intermediate container 95d1419578ac
 ---> ffb4ca92826e
Step 9/9 : CMD ["npm", "start"]
 ---> Running in d1b88a01f889
Removing intermediate container d1b88a01f889
 ---> 418d04e16184
Successfully built 418d04e16184
Successfully tagged vidly_backend:latest
Traceback (most recent call last):
  File "docker-compose", line 3, in <module>
  File "compose/cli/main.py", line 81, in main
  File "compose/cli/main.py", line 203, in perform_command
  File "compose/metrics/decorator.py", line 18, in wrapper
  File "compose/cli/main.py", line 1186, in up
  File "compose/cli/main.py", line 1182, in up
  File "compose/project.py", line 664, in up
  File "compose/service.py", line 364, in ensure_image_exists
  File "compose/service.py", line 1133, in build
  File "compose/service.py", line 1948, in build
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmpafoiltwd'
[39279] Failed to execute script docker-compose

I am thinking /tmp/tmpafoiltwd may be on the host machine (?) and there is a permissions conflict (though it isn't a permissions error). I am confused on the next step to take. Any direction would be appreciated :)
EDIT:
If I move USER app up to the 3rd line I get a permissions error:
FROM node:14.16.0-alpine3.13
RUN addgroup app && adduser -S -G app app
USER app
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3001
CMD ["npm", "start"]

Traceback:
npm WARN checkPermissions Missing write access to /app
npm WARN vidly-backend@1.0.0 No description
npm WARN vidly-backend@1.0.0 No repository field.

npm ERR! code EACCES
npm ERR! syscall access
npm ERR! path /app
npm ERR! errno -13
npm ERR! Error: EACCES: permission denied, access '/app'
npm ERR!  [Error: EACCES: permission denied, access '/app'] {
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'access',
npm ERR!   path: '/app'
npm ERR! }

A: Looks like this issue. The problem is the snap version of docker, which does not allow accessing the docker-compose to the temporal folder (the folder /tmp/tmpafoiltwd should be in /tmp/snap.docker/tmp/tmpafoiltwd).
The solution proposed is to remove the snap version and install the official one


text:
Q: Win32's FindWindow() can find a particular window with the exact title, but what about "try.bat - Notepad"? Win32's FindWindow() can find a window having the title of "Untitled - Notepad", but what if I just want to find a Notepad window but don't know whether it is "try.bat - Notepad" or some other file name on the title bar?
It seems that if the title is passed in a NULL value, then any window will be returned, but only one window is returned, so there is no way to grep for the title using regular expression.
(I am doing this using Ruby's Win32API)

A: I would follow Eric's advice to use EnumWindows. You can provide Ruby callbacks to Windows API functions through win32-api. Here's an example that was trivially modified from the sample in the win32-api README:
require 'win32/api'
include Win32

# Callback example - Enumerate windows
EnumWindows     = API.new('EnumWindows', 'KP', 'L', 'user32')
GetWindowText   = API.new('GetWindowText', 'LPI', 'I', 'user32')
EnumWindowsProc = API::Callback.new('LP', 'I'){ |handle, param|
  buf = "\0" * 200
  GetWindowText.call(handle, buf, 200);

  if (!buf.index(param).nil?)
    puts "window was found: handle #{handle}"
    0 # stop looking after we find it
  else
    1
  end
}

EnumWindows.call(EnumWindowsProc, 'Firefox')

A: The 1st argument of FindWindow searches by class name, if you use "Notepad" (Notepad's main window class name) for this and a null title you would get the 1st matching handle irrespective of its caption.

A: You almost certainly want to use the EnumWindows function; this function will call you back with a window handle, and then you can use GetWindowText to inspect the window title and find the one you want.
Now, I have no idea how to write a callback function in Ruby, so you'll need some help there.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to get the number after '-' in Oracle I have some strings in my table. They are like 1101-1, 1101-2, 1101-10, 1101-11 pulse, shock, abc, 1104-2, 1104-11, 2201-1, 2202-4. I tried to sort them like below:
1101-1
1101-2
1101-10
1101-11
1104-2
1104-11
2201-1
2202-4
abc
pulse
shock

But I can't get the sort correctly. Below is my codes:
select column from table
order by regexp_substr(column, '^\D*') nulls first,
         to_number(substr(regexp_substr(column, '\d+'),1,4)) asc

A: For your examples, this should do:
order by regexp_substr(column, '^[^-]+'), -- everything before the hyphen
         len(column),
         column

A: Sort numbers as numbers:

*

*first the ones in front of the hyphen (line #16)

*then the ones after it (line #17),

*then the rest (line #18)

Mind the to_number function! Without it, you'll be sorting strings! and get the wrong result.
SQL> with test (col) as
  2  ( select '1101-1'  from dual union all
  3    select '1101-2'  from dual union all
  4    select '1101-10' from dual union all
  5    select '1101-11' from dual union all
  6    select 'pulse'   from dual union all
  7    select 'shock'   from dual union all
  8    select 'abc'     from dual union all
  9    select '1104-2'  from dual union all
 10    select '1104-11' from dual union all
 11    select '2201-1'  from dual union all
 12    select '2202-4'  from dual
 13  )
 14  select col
 15  from test
 16  order by to_number(regexp_substr(col, '^\d+')),
 17           to_number(regexp_substr(col, '\d+$')),
 18           col;

COL
-------
1101-1
1101-2
1101-10
1101-11
1104-2
1104-11
2201-1
2202-4
abc
pulse
shock

11 rows selected.

SQL>

A: To get the number after '-' specifically:
with ttt (col) as (
    select cast(column_value as varchar2(10)) as second_str
    from   table(sys.dbms_debug_vc2coll
           ( '1101-1'
           , '1101-2'
           , '1101-10'
           , '1101-11'
           , '1104-2'
           , '1104-11'
           , '2201-1'
           , '2202-4'
           , 'abc'
           , 'pulse'
           , 'shock'
           ))
    )
select col
     , regexp_substr(col, '(^\d+-)(\d+)', 1, 1, '', 2)
from   ttt;

COL        SECOND_STR
---------- ----------
1101-1     1
2201-1     1
1101-10    10
1101-11    11
1104-11    11
1101-2     2
1104-2     2
2202-4     4
abc
pulse
shock

11 rows selected

This treats the text string as two values, (^\d+-) followed by (\d+), and takes the second substring (the final '2' parameter). As only positional parameters are allowed for built-in SQL functions, you also have to specify occurrence (1) and match param (null, as we don't care about case etc).


text:
Q: Do DynamoDB consumed capacity units in on-demand mode compare to provisioned capacity? Right now I am using on-demand mode for my DynamoDB tables, as I didn't know how much data to expect. But now that the application has run a while, I can see the metrics for ConsumedReadCapacityUnits and ConsumedWriteCapacityUnits for my tables in CloudWatch.
In on-demand mode I pay per request, whereas in provisioned capacity mode I have to pay for the provisioned capacity. If I simply take the metrics for (max) consumed capacity units and compare the prices of those in provisioned capacity mode to my current costs, I believe provisioned capacity mode would be a lot cheaper for me.
My question is, can I simply take the metrics and take the max (plus some buffer) of the consumed capacity units and configure them as provisioned capacity, or is that an error in reasoning on my part?

A: There are two other things you need to consider:

*

*How 'bursty' is your throughput?

*Are you using SDKs to connect to your database?

Setting your provision to the maximum throughput you ever see will ensure you don't get throttled requests, however you will probably be setting the provision too high. Dynamodb can actually consume more provision than you have set using Burst Capacity. This will accomodate short bursts of high throughput over the space of 5 minutes. If you see sustained peaks, for example your database is busy in the day but not the night, you might consider setting your tables to Autoscale. In this case you can set the provisioned throughput lower, and Dyanmodb will automatically scale up provision as required. Note that autoscale is good for workloads that vary over the course of hours (e.g. for handling daily peak hours). It's not good for reacting to events that occur in less than about 30 minutes.
If you are using official SDKs, they will handle throttle responses, and retry any failed requests. This gives Dynamodb some time to scale without your application failing requests.


text:
Q: problems with node en vscode I have a very strange problem with node. When I open a folder in my vscode, node does not recognize me but without opening a folder it recognizes it perfectly, I do not understand what the error may be. On the other hand I already have node added to the path.

Without opening a folder just opening the vscode

In cmd

Path

I don't understand why node doesn't grab me when I open a folder in vscode.


text:
Q: How do I detect any block around an entity using the /execute command in Minecraft? I'm trying to create an RPG launcher kind of device to make a tutorial on for my YouTube channel. I am using crossbows and firework rockets and so far I have succeeded in having the firework rocket explode when flying above grass blocks. Is there any way to detect when the rocket flies into any block, rather than a particular block / category?

A: Try the following:
/execute unless block X Y Z minecraft:air run SOMETHING...

Theoretically this should work, as minecraft:air is a block type, and should be detectable using the /execute command.

A: You could use the command /execute as @e[type=minecraft:firework_rocket] at @s anchored eyes unless block ^ ^ ^1 air run summon minecraft:creeper ~ ~ ~ {Fuse:0s,ignited:1b} in a repeating command block, which checks if the block infront of the firework rocket is not air, which causes an explosion, though pressing F3 + B (and looking at the blue line) reveals that the facing direction can be a bit wonky with fireworks.
I'd also recommend having /execute as @e[type=minecraft:firework_rocket] at @s anchored eyes unless block ^ ^ ^1 air run kill @s in a chain command block to make sure the explosion only happens once
Having an area full of string would make the system more reliable, as the rocket could pass through the string but be facing string, a non-air block


text:
Q: Html table convert into latex table `input html table:

    First Name:
    Bill Gates

    Telephone:
    5

    7

    4545
    5656

    q56
    q566

My xslt program:
<xsl:template match="table">
<xsl:variable name="noc" select="max(tr/sum(td/(@colspan/number(.),1)[1]))"/>
<xsl:text>\begin{tabular}{*{</xsl:text>
<xsl:value-of select="$noc"/>
<xsl:text>}{|l}|}
</xsl:text>
<xsl:apply-templates select="tr[1]">
 <xsl:with-param name="rspans" select="for $i in 1 to xs:integer($noc) return 0"/>
</xsl:apply-templates>
<xsl:text>\end{tabular}</xsl:text>
</xsl:template>

<xsl:template match="tr">
 <xsl:param name="rspans"/>
<xsl:text/>% [<xsl:value-of select="$rspans"/>]
 <xsl:variable name="tr" select="."/>
 <xsl:for-each select="$rspans">
  <xsl:variable name="c" select="position()"/>
  <xsl:variable name="td" select="$tr/td[count($rspans[position() <=$c][.=0])]"/>
  <xsl:if test=".=0">
   <xsl:if test="$td/@rowspan[. > 1]">
    <xsl:text>\multirow{</xsl:text>
    <xsl:value-of select="$td/@rowspan"/>
    <xsl:text>}{*}{</xsl:text>
   </xsl:if>
   <xsl:if test="$td/@colspan[. > 1]">
    <xsl:text>\multicolumn{</xsl:text>
    <xsl:value-of select="$td/@colspan"/>
    <xsl:text>}{|l|}{</xsl:text>
   </xsl:if>
   <xsl:apply-templates select="$td"/>
   <xsl:if test="$td/@colspan[. > 1]">}</xsl:if>
   <xsl:if test="$td/@rowspan[. > 1]">}</xsl:if>
  </xsl:if>
  <xsl:choose>
   <xsl:when test=". >1 and position()=last()">&\\
</xsl:when>
   <xsl:when test="position()=last()">\\
</xsl:when>
   <xsl:otherwise>&</xsl:otherwise>
  </xsl:choose>
 </xsl:for-each>
 <xsl:apply-templates select="following-sibling::tr[1]">
  <xsl:with-param name="rspans" select="for $c in 1 to count($rspans)
   return
   ($rspans[$c] +
   td[count($rspans[position() <=$c][.=0])]/(@rowspan,1)[1]
   -1)"/>
 </xsl:apply-templates>
</xsl:template>

I am getting tex file like this
\begin{tabular}{*{2}{|l}|}
% [0 0]
 First Name:&Bill Gates\\
% [0 0]
 \multirow{2}{*}{Telephone:}&5\\
% [1 0]
 &7\\
% [0]
 4545\\
% [0]
 q56\\
\end{tabular}

In input html rowspan is 2 value, it takes only 2 rows. But in our coding its take throughout after rowspan and not printing properly in tr.
You can see our tex code its not printing last two tr tag in properly.
Please give solution of rowspan convertion.


text:
Q: Export and Append Data to CSV I am trying to export data to existing csv file.
I have been using these methods to export data.

*

*Microsoft.Jet.OLEDB.4.0

*SQLCMD

*Data Export Wizard

However I cannot find if there is any parameter / option to append the exported data to existing file. Is there any way? Thanks.

A: Note: answer is biased towards *nix operating systems; I'm not too familiar with windows.
If you can run your sql query via the command line,

*

*using a scripting language, you can use a library that creates an MSSQL connection, (an example of this is a node.js program I authored (https://github.com/skilbjo/aqtl but any tool will do), or

*a windows binary that runs something like sqlcmd from the command line,

you can just pipe the output to the csv file. For example:
$ node runquery.js myquery.sql >> existing_csv_file.csv


text:
Q: Wordpress tinymce prints empty P tag and break html format I'm raising this problem because I don't find a latest answer and the problem still exist to me.
I'm running wordpress 4.2.2 with x theme when I'm editing the content via WP default editor (tinymce). I'm having lot of problem with HTML format. For example if I edit the content in VISUAL/TEXT mode in the front-end I'm getting empty

 tags even sometime I noticed if I add content like this:

Content1

Content2

Content3

it'll be transform into: (this is happening once in while)

Content1

Content2

Content3

My questions are:

*

*Is there a solution for this?

*Or can we change the default editor to the plain text area? perhaps disable the tinymce editor

A: You can disable the visual editor entirely in your profile settings. If you need to disable it on a per page basis, take a look at this answer.
Using text mode may not solve the empty paragraph problem, the wpautop filter is applied to the content regardless of how the content is edited. You can remove the filter, but then you'll have to manually break and paragraph your content.
remove_filter( 'the_content', 'wpautop' );
remove_filter( 'the_excerpt', 'wpautop' );

Alternatively, you can use a filter to strip out any empty paragraphs when displaying your content:
https://gist.github.com/ninnypants/1668216
Regarding the issue with the anchors, I haven't had this particular issue with the editor. In general, if I am writing a lot of HTML in a post I like to use a "raw html" plugin. For example: https://wordpress.org/plugins/preserved-html-editor-markup-plus/

A: It's called wpautop. There is a plugin that will help you to effectively deal with this
Please check PS Disable Auto Formatting
Hope it helps

A: you can use this if you looking any certain post type
remove_filter('the_content','wpautop');

//decide when you want to apply the auto paragraph

add_filter('the_content','my_custom_formatting');

function my_custom_formatting($content){
if(get_post_type()=='my_custom_post') //if it does not work, you may want to pass the current post object to get_post_type
    return $content;//no autop
else
 return wpautop($content);
}

please find here remove_filter( 'the_content', 'wpautop' ); only for certain post types


text:
Q: How to force IntelliJ plugin to parse a file's PsiReference resolutions? I have an IntelliJ plugin that is walking PsiReference resolutions to a "distant" class, and having trouble because the resolve() method is returning null if and only if i have not navigated to the distant file in the editor during the current IntelliJ session. I suspect that IntelliJ needs to be prodded to parse the file in some sense (when you navigate to the file, you can see that IntelliJ kicks off some sort of parsing run as a lot of the code goes from being minimally highlighted to fully highlighted) but I don't know how to do that. I looked in PsiManager and PsiFile, where I found some refresh() and reloadFromDisk() methods, but I'm guessing these have a lot of side-effects I don't want and probably won't kick off the parsing run anyways. Details/clarification below.
The code looks something like this:
File 1, in which I invoke a plugin action on foo:
@AnnotationReferringToAnotherType(File2.class)
class File1 {
  String foo;
}

File 2, which the plugin must lookup in order to perform the action on foo:
class File2 {
  @File3
  void mustBeLookedUpToHandleAction() {}
}

File 3 must also be looked up:
@interface File3 {
  public enum SomeEnum {
    DEFAULT,
    SOMETHING_ELSE
  }

  SomeEnum value() default SomeEnum.DEFAULT;
}

I perform the action on foo, and then the logic finds the @AnnotationReferringToAnotherType at the top of the containing file (File 1) and resolve()s to the definition of File2. Then it looks for a method in File2 that is annotated with @File3. Since the @File3 annotation on mustBeLookedUpToHandleAction does not specify its value, the plugin must now look up the definition of @File3 in order to determine what the default value is. All of this works completely smoothly after freshly loading IntelliJ. The part that fails is the resolve() from the PsiReferenceExpression SomeEnum.DEFAULT to the actual definition of DEFAULT in SomeEnum. It consistently returns null, until i navigate, in the editor, to File 3, and after that it works every time for the remainder of the session. It seems clear that the references' resolutions are being parsed lazily, and if i can just find some way to kick off that parsing everything should be OK?
You may be thinking "why the hell is this logic so complicated?". Most of the logic is actually in a library i'm using - it's internal, so i may be able to get some changes made but I doubt i'll be able to make fundamental changes on account of this issue unless this issue turns out to be completely unmanageable.

A: Turns out this is a bug in IntelliJ: https://youtrack.jetbrains.com/issue/IDEA-133994
the workaround is to call getText() on one of the annotation definition's PsiElements before calling resolve() - e.g. once you have the PsiAnnotationMethod for File3.value call getText() on it before calling getDefaultValue().resolve()
deets:
The definition for File3 is "stubbed", so only the core components of its psi tree are actually available. Whenever information is requested from the stub that the stub doesn't have (e.g. by calling getText), the file containing the stubbed psi tree will be fully parsed and the stub replaced with a complete psi tree (see https://confluence.jetbrains.com/display/IDEADEV/Indexing+and+PSI+Stubs+in+IntelliJ+IDEA). The particular implementation of PsiAnnotationMethod.getDefaultValue will return a dummy PsiAnnotationMemberValue if the annotation is stubbed, and that dummy element is apparently not knowledgeable to honor the resolve().


text:
Q: Display scaling setting - difference between Gnome Tweaks and Gnome Display settings Both gnome-tweak-tool and Display settings tools seem to offer a way to change the scaling of the display (See screenshot below), however it is not clear to me how they are related and which controls what. Also, they don't seem to be in sync.
Do you know What is the difference between these two tools?
Thanks!

A: Gnome-Tweaks -- Font Scaling.. means size of the Font is Increased..
Fonts Scaling Factor set to 2

Fonts Scaling Factor set to 3

Display Settings.. is the scaling of all elements..
Displays Scale set to 100%

Displays Scale set to 200%

Based on your needs and resources both the cases are used..


text:
Q: All users suddenly disappeared in Settings > User and Contacts Odoo All users including administrator's account suddenly disappeared in Settings > User and Contacts but I still can login as Administrator, I didn't do anything in the system.
Here's my Settings, there is no users at all: https://snipboard.io/73qArR.jpg
But I can still login as Administrator and can access all in my main menu but I can't create a user in Contacts and Settings, I'm not sure if all internal/portal users were still there, I tried to filter Inactive Users but still no users has found. How to solve this?


text:
Q: UIButton's title mysteriously disappears when sliding back too fast I have a UIButton in the main screen, of which title should always show the currently playing or to-be-played music, if the playlist is empty, it should show "Music", clicking it will bring up a song selecting screen(when playlist empty) or a play list screen(when playlist not empty), after selecting a song and go to playlist screen, and delete the song and slide back to the main screen, the title of UIButton should show "Music".
Here's the problem: when you are sliding back too fast, the "Music" text would show up in a split second and then disappears, but when you are sliding slowly, the "Music" text stays.
I've recorded the very strange behavior in this 25-second video.
Here's the related code:
- (void)updateChooseMusicButton {
    if(self.songQueue.count == 0) {
        [self.chooseMusicButton setTitle:@"Music" forState:UIControlStateNormal];
    }
}

- (void)setChooseMusicButton:(UIButton *)chooseMusicButton {
    _chooseMusicButton = chooseMusicButton;
    [_chooseMusicButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_chooseMusicButton setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
}

A: Found the solution: Change the type of the button to "Custom", it was using "System". And it also takes care of the flashing when title changes.

A: Comment this code and try to run..
- (void)setChooseMusicButton:(UIButton *)chooseMusicButton {
        _chooseMusicButton = chooseMusicButton;
        [_chooseMusicButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_chooseMusicButton setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
}

and call the updateChooseMusicButton function in viewWillAppear method.


text:
Q: Losing Current Filter on PagedList Can somebody please help me and tell me where I am going wrong. I have a dashboard that shows a list of errors. There is a textbox at the top with type="date" allowing the user to select a date. The list then updates itself to show the errors that happened on the date that has been selected. I am wanting to implement PagedList on this but when I click on the second page it doesn't show any results whatsoever
Controller
public ActionResult Index(string sortOrder, int? page)
    {
        ViewBag.CurrentSort = sortOrder;
        ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";

        var applications = from s in db.ElmahErrors
                           where s.TimeUtc == DateTime.Today
                           select s;

        switch (sortOrder)
        {
            default:
                applications = applications.OrderByDescending(x => x.TimeUtc);
                break;
        }

        int pageSize = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["DefaultPageSize"]);
        int pageNumber = (page ?? 1);
        return View(applications.ToPagedList(pageNumber, pageSize));
    }

    [HttpPost]
    public ActionResult Index(string sortOrder, string currentFilter, int? page)
    {
        ViewBag.CurrentSort = sortOrder;
        ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";

        DateTime userSelectedDate = DateTime.Parse(Request["datePicker"]).Date;

        string dateString = userSelectedDate.ToString("yyyy-MM-dd");

        if (dateString != null)
        {
            page = 1;
        }
        else
        {
           dateString = currentFilter;
        }

        ViewBag.CurrentFilter = dateString;

        var startDate = userSelectedDate.Date;
        var endDate = startDate.AddDays(1);

        var applications = from s in db.ElmahErrors
                           //where s.TimeUtc >= startDate && s.TimeUtc < endDate
                           select s;

        if (!String.IsNullOrEmpty(dateString))
        {
            applications = applications.Where(s => s.TimeUtc >= startDate && s.TimeUtc < endDate);
        }

        switch (sortOrder)
        {
            default:
                applications = applications.OrderByDescending(x => x.TimeUtc);
                break;
        }

        int pageSize = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["DefaultPageSize"]);
        int pageNumber = (page ?? 1);
        return View(applications.ToPagedList(pageNumber, pageSize));
    }

View
@model PagedList.IPagedList<DataIntelligence.Models.ElmahError>
@using PagedList.Mvc;
<link href="Content/PagedList.css" rel="stylesheet" type="text/css" />

@{
    ViewBag.Title = "Errors By Day";
}

Errors By Day

@using (Html.BeginForm("Index", "Day", FormMethod.Post, new { id = "frmSearch" }))
{
    Find By Date:
    @Html.TextBox("datePicker", ViewBag.CurrentFilter as string, new { @type = "date"})

}

            Application

            Host

            Type

            Date

            Message

    @foreach (var item in Model)
    {

                 @Html.DisplayFor(modelItem => item.Application)

                @Html.DisplayFor(modelItem => item.Host)

                @Html.DisplayFor(modelItem => item.Type)

                @Html.DisplayFor(modelItem => item.TimeUtc)

                @{
                    string parameterValue = item.Message.Substring(0, 8);
                }

                @Html.DisplayFor(modelItem => parameterValue)

    }

Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount

@Html.PagedListPager(Model, page => Url.Action("Index",
new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))

I have tried changing from POST to GET but I can't seem to get my head around how to get it working.
Could someone please advise me on what to change in order to get my PagedList working?
Thanks in advance.

A: PagedList, as most of paging modules you may find, uses GET, not POST, when you click on the next page. So the request arrives not to the action marked with HttpPost, but to the default one. Therefore date filter is not applied, and you receive second page with today's errors. I am guessing there were not enough errors today (good, huh?) to fill second page with data.
I would recommend you to switch to a single action that handles GET requests only. After all, this is the recommended way for idempotent operations like data viewing. POST should be used, ideally, only when data is being changed on server.


text:
Q: NextJs Image Optimisation Error ERROR:INVALID_IMAGE_OPTIMIZE_REQUEST Next Js image is working properly in the local environment but in production, the images are showing for some domains and not showing for some domains for example image is working fine with unsplash but not with svgbox.net
images: {
    domains: [
      's2.svgbox.net',
      'avatars.dicebear.com',
      'lh3.googleusercontent.com',
      'images.unsplash.com',
    ],
  },


text:
Q: change maxlength of input text field onblur event  <h:inputText id="interestrate" value="#{bean.interestrate}" maxlength="5" onblur="convert();"/>

instance= i need to accept maximum 5 digit value(12345) in my input field and convert to float variable with fixed 3.
(12.345)
conversion is done by calling  javascript method convert();.
But now the field value size is 6 including "."(dot).
So how to change the maxlenth of this input field ONBLUR event.

A: Thank you for posting your code. You can just add this line into your convert() function:
this.setAttribute("maxlength", 6);

A: Don't do this on blur event, because on blur event the maximum field size will increase to 6 and in this case the user can go back to the previous field and can enter the six digit value which is against your validation.
Change the maximum length of that field on convert() method call.


text:
Q: Find sum of largest subset of array I'm solving one CS problem, namely we have given array with size N, such that N<=100000, and the array will have both negative and positive integers, now we have to find the sum of the largest subset of the array, or more formally we have to find the indexes i and j such that the sum of the elements between those elements will me maximum possible.
Here is one example:
N=5, array={12, -4, -10, 4, 9}, answer = 13, because 4+9 is the best we can get.
I know that this can be solved by bruteforce in quadratic time, but I wonder if this can be solved in linear, on logarithmic time.
Thanks in advance.

A: According to this presentation, the algorithm by Kadane apparently yields a linear runtime bound; an implementation in C++ taken from there looks as follows.
int maxSubArraySum(int a[], int size)
{
    int max_so_far = INT_MIN, max_ending_here = 0;

    for (int i = 0; i < size; i++)
    {
        max_ending_here = max_ending_here + a[i];
        if (max_so_far < max_ending_here)
            max_so_far = max_ending_here;

        if (max_ending_here < 0)
            max_ending_here = 0;
    }
    return max_so_far;
}


text:
Q: Probability that the sum of the two rolls is $4$ given that the first roll is not a $1$ You roll two six-sided dice, one then the other.
A = {The first roll is a 1}
B = {The sum of the two dice is 4}
What is the value of $P(A^c | B)$?
$A^c$ = $5/6$
B =$1/12$
I thought that the formula would be:
$$1/12 * 5/6 \div 1/12$$
but the result is 10, which is wrong

A: You have correctly found that $P(A^C) = \frac{5}{6}$ and that $P(B) = \frac{1}{12}$.  The conditional probability that event $A^C$ occurs given that event $B$ occurs is
$$P(A^C \mid B) = \frac{P(A^C \cap B)}{P(B)}$$
There are three ways for event $B$ to occur:  (1, 3), (2, 2), (3, 1).  Of these, two do not involve rolling a 1 on the first roll.  Since there are $36$ ordered pairs of rolls in the sample space,
$$P(A^C \cap B) = \frac{2}{36} = \frac{1}{18}$$
Hence,
$$P(A^C \mid B) = \frac{P(A^C \cap B)}{P(B)} = \frac{\frac{1}{18}}{\frac{1}{12}} = \frac{2}{3}$$


text:
Q: Dipole potential and sphere grounded
Find the electrostatic potential arising from an electric dipole of
magnitude d situated a distance L from the center of a grounded
conducting sphere of radius a. Assume the dipole axis cross the sphere's
center.

Honestly, this is not a hard question, it is more about be patient, solve somes cosine laws and know the right approximations that is needed to use.
But the problem is not how to solve it, i have actually tried by another way than calculate the potential of the dipoles separated and sum it (including the potential of the net charge that will arise).
I have considered to use the formula $$\vec p = \int \rho \vec r d^3x$$ (in this case, basically $\sum q z$).
Assuming, first, that the distance between the dipole's charges is $2l$.
So, considering the sphere's center as the origin, the dipole we will get is (without any approximation)
$$\vec p = (2ql - \frac{qR^3}{(L+l)^2} + \frac{qR^3}{(L-l)^2} )\space \hat z$$
the net charge will be
$$\delta q = \frac{2qR}{l^2-L^2}$$
Here comes the problem:
Isn't the potential of a system, until the dipole order, $$\phi = \frac{k \space q_{net} }{r} + \frac{k \space \vec p \vec r}{r^3}$$
$$?$$
Using this as the potential, we get a answer that involve just $cos(\theta)$. But the right answer is different, and i understand how the answer the book got was arrived. My question is why i can't use the one i posted here?
EDIT:
BOOK ANSWER

A: I noticed a little mistake (which is even detectable by dimensional analysis):
$$
q_{net}= \frac{2qRl}{L^2-l^2}
$$
Coming back to your question, how are the two answers different? The exact answer is the field created by the $4$ point charges (including the $2$ induced,virtual ones) so it has multipolar contributions at every order. However, each term should agree whether you expand out the exact solution in multipole term or whether you calculate the multipole moment of the distribution and plug in the formula of the resulting multipole field.
By the way, since the net charge is non trivial, you can kill the dipolar term by choosing the origin of the multipole expansion as the center of charge, ie at the position $\vec p/q_{net}$. Hope this helps and tell me if you find some mistakes.


text:
Q: .desktop that copies clicked urls to clipboard in place of a default browser I would like to create a simple .desktop file that I can use in place of a default browser that simply copies any clicked url to the clipboard and displays a short confirming message. I have written this desktop entry but am having some problems with it...
[Desktop Entry]
Name=urltoclip
Exec=bash -c 'echo %U | xclip -selection c; echo copied url to clipboard!; $SHELL'
Terminal=true
Type=Application
Icon=browser

The .desktop runs from explorer (though without any input to %U doesn't copy anything) but when I set it as the default browser in the system settings and click a link I get the following error:

Unknown error code 100 execvp: Exec format error Please send a full bug report at https://bugs.kde.org

I am running kde plasma (within ubuntu-studio) and setting the default browser in the system settings here:

Anyone have an idea as to what might be the issue here? Thank you for any help.


text:
Q: XHTML meta description and keywords with lang attribute Is it ok to have this kind of meta declarations in the head section of a XHTML document?
<meta name="keywords" lang="en" content="..."/>
<meta name="description" lang="en" content="..."/>
<meta name="keywords" lang="ro" content="..."/>
<meta name="description" lang="ro" content="..."/>
<meta name="keywords" lang="fr" content="..."/>
<meta name="description" lang="fr" content="..."/>

etc
Basically is it good to have all at once, or should I just put two by two depending on what language is selected?
Thank you.

A:
Is it ok to have this kind of meta declarations in the head section of a XHTML document?

Yes, it's perfectly valid to do so; you can find a similar example in the HTML4 spec on the META element. The XHTML spec additionally suggests that you also add xml:lang when using lang.

Basically is it good to have all at once, or should I just put two by two depending on what language is selected?

This is a choice you must make depending on various factors. If you have a large number of languages and it's easy for you to dynamically generate a page with just the selected language, do so because it will save bandwidth. Otherwise, you can leave it as it is. Both ways are correct though.


text:
Q: How to Unit Test A Method Argument which is a Builder Class in Mockito? I have a dependency in the Spring Boot which is called from my class. This dependency makes a call with a newly instantiated builder pattern class as an argument. I need to know if it is possible to verify if this single builder class was constructed with certain values when the dependency call is made, e.g.:
public class MyClass {

  @Autowired
  private MyDep myDep;

  public void callMyDepService() {
    myDep.serviceCall(new MyBuilder().paramOne("One").paramTwo("Two").build());
  }

}

As you can see, a new MyBuilder is instantiated every time, so I can't just use Mockito's eq() to match the arguments' value.

A:
I would like to make sure callMyDepService calls myDep.serviceCall with certain parameter values.

Using a captor seems to be the easiest way to do that.
Something like this, where SomeClass is the class your MyBuilder builds.
@ExtendWith(MockitoExtension.class)
public class CaptureTest {

    @InjectMocks
    MyClass classUnderTest;

    @Mock
    MyDep myDep;

    @Test
    public void test() {

        classUnderTest.callMyDepService();

        Captor<SomeClass> captor = ArgumentCaptor.forClass(SomeClass.class);
        Mockito.verify(myDep).serviceCall(captor.capture());

        SomeClass parameter = captor.getValue();
        // do assertions
    }
}


text:
Q: Возведение числа в степень по модулю Здравствуйте.
Возвожу число в степень по модулю:
(x ^ y) mod N = z

Мне известно y, N, z. Как найти x?

A: *

*Составное N можно факторизовать и свести исходное сравнение к системе сравнений по взаимно простым модулям - степеням простых чисел.

*Решение каждого из таких сравнений сводится к решению нескольких сравнений по простому основанию.

*Решение сравнений по простому основанию рассмотрено в статье по ссылке ОП. Понизить степень такого сравнения можно с помощью малой теоремы Ферма.

*Зная классы искомого числа по взаимно простым модулям, нетрудно восстановить класс этого числа по их произведению, т. е. по основанию N.

Подробности по пп. 1, 2, 4 - в книге И. М. Виноградова, гл. IV.


text:
Q: Can't load .qml with loadNamedStyle properly with PyQGIS I created a categorized symbology with labels and saved it to a .qml file.
When trying to load this .qml via PyQGIS nothing happens.
layer.loadNamedStyle('path\to\file.qml')
layer.triggerRepaint()

What I'm doing is clipping from a layer that already has this style applied, but the new clipped layer doesn't inherit the styling.  I'm trying to put it back by loading from an external file. (Is it possible to easily copy the styling of an existing layer?)
If I manually apply the style via the GUI, it loads perfectly (categories, labels, etc).
The above code DOES work perfect when loading a different .qml I made that consists of a simple outline for a single symbol.
I think I'm missing something when it comes to loading a .qml and getting the QgsCategorizedSymbolRenderer set correctly.
I have tried adding iface.layerTreeView().refreshLayerSymbology( layer.id()) to no avail.
EDIT:
I have a similar layer I am clipping with it's own categorized symbology exported to a .qml.  The code I have successfully loads the .qml for that clipped layer.  Seems the code isn't the problem.
For the layer I'm having an issue with, I tried exporting a .qml from it representing a single symbol with a solid color.  Not even that .qml loads successfully via pyqgis, not on any layer I try it.  It still loads if I do it manually. It seems that perhaps when exporting a style from that layer, there is an error with the .qml it generates. At least in terms of loading it via loadNamedStyle.

A: Edit:
I was wrong. Devs pointed out what is now obvious. One needs to use "/" slashes in paths, even on Windows. Try:
layer.loadNamedStyle('path/to/file.qml')

"something\bxxx.qml" is interpreting "\b" as a "backspace" character. See https://docs.python.org/3/reference/lexical_analysis.html#strings


text:
Q: __builtin_clz returns incorrect value for input zero I'm using the function __builtin_clz provided by GCC, which should count the number of leading zero bits in an unsigned int. But __builtin_clz returns an incorrect value for input 0:
#include <stdio.h>
int main(void) {
  unsigned int x = 0;
  int lz = __builtin_clz(x);
  printf("%d\n", lz);
  return 1;
}

I expect this to print 32 on my machine. Instead, it prints 4195634:
$ gcc -Wall clz.c
$ ./a.out
4195634

Is this my fault? Have I invoked some undefined behavior somewhere?

A:
Is this my fault? Have I invoked some undefined behavior somewhere?

Yes, by passing 0 to __builtin_clz. From the GCC documentation:

Returns the number of leading 0-bits in x, starting at the most
  significant bit position. If x is 0, the result is undefined.


text:
Q: Request.UrlReferrer returns only google.com not the whole keywords I want to capture the keywords that user enter in search engine to visit my website, Issue is that when I use Request.UrlReferrer it returns me only google.com and not returns me the whole url string that contains keywords seperated by hyphen. How can I get the keywords?

A: You could use Request.Url to get the full URL or Request.QueryString to get a collection of query strings from the URL.
You can specify which querystring you want to retrieve like so:
Request.Querystring["NameOfQueryStringHere"]

I think that for google the querystring name for search terms is "q", so try:
Request.Querystring["q"]


text:
Q: Deadlock on single table We occasionally encounter the following deadlock:
Process 1: Multiple INSERTS into DeadlockedTable, inside a transaction
Process 2: Calling a table-valued function with multiple SELECTs on DeadlockedTable. Some of the SELECTS are within CTEs, some contain subselects on DeadlockedTable.
Deadlock:
Process 2 --> Request Mode S --> PageLock (DeadlockedTable) --> Owner Mode IX   --> Process 1
Process 2 <-- Owner Mode S   <-- PageLock (DeadlockedTable) <-- Request Mode IX <-- Process 1

The queries (only the ones using DeadlockedTable):
WITH T
AS (
SELECT ID1 = ROW_NUMBER() OVER (
        ORDER BY ENTRY_DATE DESC
        )
    ,*
FROM DeadlockedTable
WHERE ENTRY_ID = @ENTRY_ID
    AND ENTRY_TYPE = @ENTRY_TYPE
    AND ENTRY_DATE BETWEEN @FROM_DATE
        AND @TO_DATE
    AND SOURCE_ID IN (
        SELECT max(SOURCE_ID)
        FROM DeadlockedTable
        WHERE ENTRY_ID = @ENTRY_ID
            AND ENTRY_TYPE = @ENTRY_TYPE
            AND ENTRY_DATE BETWEEN @FROM_DATE
                    AND @TO_DATE
        GROUP BY ENTRY_DATE
        )
)
 INSERT INTO @dtTmpTable
 SELECT *
 FROM (
 SELECT min(ENTRY_DATE) AS ENTRY_DATE
    ,SRC_VALUE AS REF_DATE
FROM DeadlockedTable P
  WHERE P.ENTRY_ID = @ENTRY_ID
    AND ENTRY_TYPE = @ENTRY_TYPE
    AND ENTRY_DATE BETWEEN @FROM_DATE
        AND @TO_DATE
    AND SOURCE_ID IN (
        SELECT max(SOURCE_ID)
        FROM DeadlockedTable
        WHERE ENTRY_ID = @ENTRY_ID
            AND ENTRY_TYPE = @ENTRY_TYPE
            AND ENTRY_DATE BETWEEN @FROM_DATE
                AND @TO_DATE
        GROUP BY ENTRY_DATE
        )
GROUP BY SRC_VALUE
) #
 WHERE ENTRY_DATE NOT IN (
    SELECT rd.REFDATE
    FROM @dtTmpTable RD
    )

 UPDATE @dtTmpTable
 SET TotalValue = SRC_VALUE
 FROM @dtTmpTable
 INNER JOIN DeadlockedTable P ON P.ENTRY_ID = @ENTRY_ID
    AND ENTRY_TYPE = @ENTRY_TYPE
    AND ENTRY_DATE = refDate
 WHERE SOURCE_ID = (
    SELECT max(SOURCE_ID)
    FROM DeadlockedTable
    WHERE ENTRY_ID = @ENTRY_ID
        AND ENTRY_TYPE = @ENTRY_TYPE
        AND ENTRY_DATE = refDate

The indexes:
Index 1:  Non-Unique, Non-Clustered (SOURCE_ID)
Index 2:  Non-Unique, Non-Clustered (SOURCE_ID, ENTRY_ID, ENTRY_DATE, LOT)

I don't understand why process 2 would request multiple shared locks on DeadlockedTable. I would assume that a lock is only held for the duration of one SELECT and then released, is that wrong? What would be the right way to fix this?

A: I have resolved this issue by following steps,

*

*Use lock while inserting the records.sp_getapplock (Transact-SQL)
EXEC sp_getapplock @Resource = 'DeadlockedTable', @LockMode = 'Exclusive';
 --perform insertion work here
 EXEC sp_releaseapplock @Resource = 'DeadlockedTable';

*Use with(nolock) while selecting the data from the DeadlockedTable


text:
Q: RegEx matches if newline is included, but should not match Strange behaviour in perl.
Given a regular Expression ($reg) which matches on "Beginning" then "1" or "2" and then "End" also matches on "1\n" - why?
my $reg='^[1-2]$';
my $x="1\n";
if ($x =~ m/$reg/) {
    print "matches";
} else {
    print "doesn't match";
}

if i do two newlines in $x it doesn't match any longer.
I'm looking for a code, which doesn't match the above. It should only be true, when "1" or "2" is in $x. Only RegEx is allowed - no chomp or other comparison/substition.

A: $ matches an optional linefeed.
http://perldoc.perl.org/perlre.html
$        Match the end of the string (or before newline at the end
         of the string)

It won't match a double linefeed though.
You probably want:
my $reg='\A[1-2]\z';

Which will:
\A  Match only at beginning of string
\Z  Match only at end of string, or before newline at the end
\z  Match only at end of string

Edit: As mentioned in comments by mpapec:
Given you've got a static pattern you're matching, potentially multiple times - you're doing needless work, because the interpreter is compiling your regular expression each time it checks it.
You can compile a static pattern using qr which saves this processing.
http://perldoc.perl.org/perlop.html#Regexp-Quote-Like-Operators
my $reg = qr/\A[12]\z/;

if ( $x =~ $reg ) {
    #...
}

That's particularly applicable if you're testing the same pattern a lot (especially if it's a complicated pattern).

A: ^[1-2]$' matches 1\n because $ (end of the line anchor) matches before the \n character.


text:
Q: Team Foundation Server 2015 install error with SQL Server 2017 Express TF400533 Installing TFS Server on Win10 box with SQL Server 2017 Express already installed and detected by the TFS installer.
Then I get this error:

TF400533: The SQL Server Express instance installed on this machine cannot be upgraded to the latest version of SQL Server Express until you have applied a more recent service pack to it. It is recommended that you run Microsoft Update, which will install the most recent service pack for you automatically, then re-run this wizard. For more information on upgrade requirements for SQL Server Express, visit: http://go.microsoft.com/fwlink/?LinkId=301277.

Does anyone have any idea how to work around this?
Thanks

A: TFS2015 will not install on a new DB server like this SQL Server 2017 Express I found out after searching to find the install docs.


text:
Q: How does the Constructibility Degree of a real compare with its Turing Degree? Specifically, is it the case that (for $a,b\in\omega^\omega$) $a$ $\leq_T$ $b$ implies $a$ $\leq_c$ $b$?
I suspect it might be trivial, but not knowing much Recursion Theory, it's hard to see how it could.
Thank you in advance.

A: Yes, if $a\le_T b$ then $a$ is first-order definable from $b$; in particular $a\in L(b)$ so $a\le_c b$.

A: As Bjorn pointed out, $a\leq_Tb$ implies $a\leq_cb$.  But it should also be mentioned that constructible degrees are much coarser then Turing degrees:  Suppose $\aleph_1^L$ is the real $\aleph_1$.  Then every constructible degree (set of $\leq_c$-equivalent reals) is uncountable (take your real $a\in\omega^\omega$ and consider all coordinate wise sums of $a$ and a constructible real.  These sums are all of the same constructible degree as $a$).  Every Turing degree is countable since there are only countably many Turing machines.
This observation explains Carl Mummert's statement "in $L$ there are extremely large Turing degrees".


text:
Q: SQL CASE with one condition and multiple results I'm writing a stored procedure which takes a string as one of the input parameter and then retrieve result.
I'm familiar with the below SQL CASE format.
CASE
  WHEN col1 in ('val1', 'val2', 'val3')
  THEN 'HELLO'
  WHEN col1 in ('val4', 'val5', 'val6')
  THEN 'WORLD'
END AS col2

What should be the query for other way around?
Like when I give col2 value as 'HELLO', it should return all the rows with col1 containing 'val1', 'val2', 'val3'

A: Just wrap it in another query...
SELECT *
FROM (
      SELECT CASE
             WHEN col1 in ('val1', 'val2', 'val3')
             THEN 'HELLO'
             WHEN col1 in ('val4', 'val5', 'val6')
             THEN 'WORLD'
             END AS col2
...
     )t
WHERE t.col2 = 'HELLO'

A: WHERE 1 = CASE
  WHEN (col2 = 'HELLO' and col1 in ('val1', 'val2', 'val3'))
    OR (col2 = 'WORLD' and col1 in ('val4', 'val5', 'val6'))
  THEN 1
  ELSE 0
  END

or, more simply..
WHERE  (col2 = 'HELLO' and col1 in ('val1', 'val2', 'val3'))
    OR (col2 = 'WORLD' and col1 in ('val4', 'val5', 'val6'))

A: where (col2 = 'HELLO' and col1 in ('val1', 'val2', 'val3'))
   or (col2 = 'WORLD' and col1 in ('val4', 'val5', 'val6'))

A: You could try this.
SELECT
   col1,
   CASE
   WHEN col1 in ('val1', 'val2', 'val3')
   THEN 'HELLO'
   WHEN col1 in ('val4', 'val5', 'val6')
   THEN 'WORLD'
   END AS col2
FROM
   --wherever you are getting your data from...
WHERE
   col2 = :SEARCH

which will return results tht look like this when you pass HELLO into the bind variable.
col1 col2
---- ----
val1 HELLO
val2 HELLO
val3 HELLO

If you only want col1 returned, you could do something like this
WITH SEARCH_RESULTS AS
(
   SELECT
      col1,
      CASE
      WHEN col1 in ('val1', 'val2', 'val3')
      THEN 'HELLO'
      WHEN col1 in ('val4', 'val5', 'val6')
      THEN 'WORLD'
      END AS col2
   FROM
      --wherever you are getting your data from...
   WHERE
      col2 = :SEARCH
)

SELECT col1 FROM SEARCH_RESULTS


text:
Q: Is a continuous function on a compact subset of $GL(\mathbb{R}^n)$ bounded? Let $\chi$ is a continuous function on $GL(\mathbb{R}^n),$ for example $$\chi(\alpha):=\left(1+\max_{1\leq i,j\leq n}|\alpha_{ij}|\right)^\ell\left(1+\max_{1\leq i,j\leq n}|\alpha^{-1}_{ij}|\right)^m|\det\;\alpha|^{1/p},$$
where $\alpha\in GL(\mathbb{R}^n)$ with coefficients $\alpha=[\alpha_{ij}]_{i,j=1,\ldots,n}$ and the coefficients of the inverse of $\alpha$ denoted by $\left( \alpha^{-1}_{ij}\right)$ and $m,\ell$ is a positive integers and $1\leq p\leq \infty.$
$\textbf{Question}:$ If we know the that matrix $\alpha$ is an element of a $\textbf{compact}$ subset of $GL(\mathbb{R}^n),$ say $\alpha\in \mathcal{G}$ where
$$\mathcal{G}:=\left(b: |\det\;b|\geq\varepsilon>0,\;|b_{ij}|\leq\frac{1}{t_o}  \right), $$
then it is true that $\chi$ is bounded $\forall\alpha\in\mathcal{G}$?

A: Yes, a continuous function $\chi : GL(n, \mathbb{R})\to \mathbb{R}$ is bounded on any compact set $\mathcal{G}\subset GL(n, \mathbb{R})$. Namely, as $\chi$ is continuous, $\chi(\mathcal{G})$ is compact in $\mathbb{R}$, and the Heine-Borel theorem implies that we can choose an $M > 0$ such that $\lvert \chi(\alpha)\rvert\leq M$ for all $\alpha\in GL(n, \mathbb{R})$.


text:
Q: How can I show an Message Box after the final dialog in Wix We are using Wix V3.10 Toolset to build an .msi setup for our software. On uninstall this is the last dialog:

Problem: When the user pressed the button "Finish" we want to show an Message Box:

But the message box will be shown before the "Finish" dialog.
Code:
<Custom Action="UninstallConfirmation" OnExit="success">(NOT UPGRADINGPRODUCTCODE) AND (REMOVE="ALL")</Custom>

<CustomAction Id="UninstallConfirmation" Script="vbscript">
  <![CDATA[MsgBox("The software was successfully removed from your computer.")]]>
</CustomAction>

Question: How can we show the Message Box after the "Finish" dialog?

A: Here is an example on how to trigger a custom action from an UI element. This example shows how to launch the application when the installation is complete, using a custom action.


text:
Q: Creating a raster based on a where clause I am writing a script that deals with a raster that will need a subset of the raster outputted and the rest of the original raster needs to be "no data".
To clarify,  say, there is a raster and with random values 1-10.  I want to input this raster and return a new  raster that is all no data except for where the original raster = 5.  I thought that the spatial analyst tool "con" would handle this but I can't seem to get it to work.  Here is a code sample.
fillRaster = str(Playa_Name) + "_fillRaster"
arcpy.gp.Fill_sa(oneFoot, fillRaster)

extractPoint = str(Playa_Name) + "_extractPoint"
arcpy.gp.ExtractValuesToPoints_sa(waterBodyPoints, fillRaster, extractPoint, "NONE", "VALUE_ONLY")

extractPoint_2 = str(Playa_Name) + "_extractPoint_2"
arcpy.TableSelect_analysis(extractPoint, extractPoint_2, ' "PLAYA_NUM" = ' + "'%s'" %Playa_Name)

field = ["RASTERVALU"]

arcpy.AddMessage("Working...")

with arcpy.da.SearchCursor(extractPoint_2, field) as cursor:
    for row in cursor:
        elevation = row[0]

ofElev = elevation

conRaster = str(Playa_Name) + "_conRaster"
whereClause = ' "VALUE" <> ' + "'%s'" %elevation
outCon = Con(fillRaster, elevation, "", whereClause)
outCon.save(conRaster)

The part that's not working is the very end where I use the Con() function.
Am I using it incorrectly?
I've looked at several examples but can't seem to figure it out.  The only other thing I can think of is maybe the "VALUE" field is incorrect, is this not the default name given to a raster's "attributes".  Using "VALUE" with the con works perfectly in ModelBuilder which is where this script is being adapted from.

A:
To clarify, say, there is a raster and with random values 1-10. I want
  to input this raster and return a new raster that is all no data
  except for where the original raster = 5

I use numpy.where for that. Something like:
    numpy.where ( [condition], [if TRUE do this], [if FALSE do this] )

    outarray = numpy.where((outarray==5),5 , 9999)

This keeps the outarray at 5 where it is 5 and sets it to 9999 where it is not 5.
I did not try myself if you instead 9999 just can set numpy.nan in the line above, maybe something like that is possible. Otherwise set it to 9999 or so and define this later as NaN value.
I wrote some more on using numpy.where here: http://geoinformaticstutorial.blogspot.no/2014/01/raster-calculations-with-numpywhere.html


text:
Q: What is "sharing filesystem information"? What's exactly meant by saying "sharing filesystem information"? What is in "filesystem information"?
(This question arose when I saw the CLONE_FS flag in some linux headers)

A: File system information includes root of the file, current working directory, and the umask (file permission). [Represented in the kernel by struct fs_struct]
So when you will set CLONE_FS flag, child process and parent process will share file system information.
Now, Take an example: a parent is processing some file, and at that time child process has changed working directory then parent will get problems (if relative path specified) because they share same working directory.
Hope you got your answer.


text:
Q: HighChart not rendering perfectly in IE8 i integrated highcharts with Orchard1.6 everything was comes perfect but the problem is that the chart does not render perfectly in IE8, i dont know whether this is browser issue or i need to work out more for this here is the screen shot for that issue

anyone know the fix for this issue it would be more helpful
 Thanks.

A: I think it is the browser issue as and when i hear Chart and IE8 its like someone using myspace on Netscape. Who to blame!
The issue you are looking at is z-index of the tootltip if not let me know as you need to give us some more direct impact to this interface via jsfiddle or something so we can tinkerbin or play with it to get you right values.
Try to see if IE8 with chrome frame solves this issue or try compatibility mode to see if that helps. Most probably a css hack would solve this.
Try this Jsfiddle for the issue reported on github as an issue but closed now so one of the fiddles in there will help you solve this.
color: rgb(51, 51, 51);
cursor: auto;
display: block;
fill: #333333;
font-family: 'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, Helvetica, sans-serif;
font-size: 12px;
height: 16px;
line-height: normal;
text-align: left;
white-space: nowrap;
width: 141px;

Check the version and css you are loading


text:
Q: Object serializing/deserializing doesn't work I have an extension method for System.Object to serialize and deserialize objects using Json.Net. this is my Extension methods:
public static void SaveToFile(this object data, string FileName)
{
    using (StreamWriter writer = new StreamWriter(FileName))
    {
        string encode = WpfApplication.Helper.Encrypt(JsonConvert.SerializeObject(data));
        writer.Write(encode);
        writer.Close();
    }
}

public static void LoadFromFile<t>(this object data, string FileName)
{
    using (StreamReader reader = new StreamReader(FileName))
    {

        data = JsonConvert.DeserializeObject<t>(WpfApplication.Helper.Decrypt(reader.ReadToEnd()));
        reader.Close();
    }
}

and It's the class that I want to deserialize:
public class CardPack
{
    #region Properties
    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    private List<FlashCard> cards;

    public List<FlashCard> Cards
    {
        get { return cards; }
        set { cards = value; }
    }

    private bool registered;
    public bool Registered
    {
        get { return registered; }
        set { registered = value; }
    }

    private int currentCardIndex;

    public int CurrentCardIndex
    {
        get { return currentCardIndex; }
        set { currentCardIndex = value; }
    }

    public string RegisterKey { get; set; }

    public string ViewName { get; set; }

    public List<FlashCard> TodayCards { get; set; }
    #endregion
    ~CardPack()
    {
        foreach (FlashCard card in cards)
        {
            card.Check();
        }
        currentCardIndex = 0;
        TodayCards = null;
        this.SaveToFile(string.Format(System.IO.Path.GetDirectoryName(
  System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Split(@"file:\\")[1] + @"\Packs\{0}.json", name));
    }

but whenever I deserialize the class cards is empty and I don't know how to resolve the problem. Can anybody help me?
Update
I find the error when I had this code:
public CardPack(string Name)
    {
        this.name = Name;
        this.LoadFromFile<CardPack>(string.Format(System.IO.Path.GetDirectoryName(
  System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Split(@"file:\\")[1] + @"\Packs\{0}.json", name));
        foreach (var item in cards)
        {
            if (item.NextTime == null)
            {
                int a = 0;
            }
        }
        TodayCards = cards.Where(c => c.NextTime.Date == DateTime.Today).ToList();
    }

because the application closed when it tries to run foreach (var item in cards)!
I asked here and found out that cards is empty!
update2 I serialized the CardPack object with a little different structure. in previous structure Cards property was read-only.

A: I found that data = JsonConvert.DeserializeObject<t>(WpfApplication.Helper.Decrypt(reader.ReadToEnd())); in extension method doesn't change to 'data' class then Cards in CardPack is always null. I'll ask a question to find out why I cant set the class from it's extension method later.


text:
Q: Como mandar a llamar un Procedimiento Almacenado desde php con el patron MVC Buen dia, alguien sabe como puedo mandar llamar un procedimiento almacenado de Mysql desde PHP con el patron MVC, El procedimiento es para validar si un campo ya existe si existe manda un mensaje que no esta disponible y si no existe manda que el campo esta disponible
AQUI LES COMPARTO EL CONTROLADOR DEL FORMULARIO

Cita en bloque

var App = angular.module('app', []);

App.controller('alumnoCtrl', function($scope, $http) {

    $scope.alumno = {};

    $scope.guardar = function() {

        $http.post('./modelo/guardarAlumno.php', $scope.alumno).success(function(data, status, headers, config) {

            alert(data);
            location.href = "./pdf/Ficha.php";
        }).error(function(data, status, headers, config) {
            alert("Error BD");

        })

    }

});

AQUI LES COMPARTO MI MODELO
<?php
error_reporting(E_ALL);
require_once 'conexion.php';
$obj = json_decode(file_get_contents("php://input"));
$stmt = $db->prepare("INSERT INTO gestion(Pk_gestion,N_control,Nombre_Completo,R1,R2,R3,R4,R5,R6,R7,R8,R9,R9_1,R10,R10_1,R11,R11_1,R12) VALUES
(null,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");

@session_start();

$stmt->bind_param('sssssssssssssssss',$obj->N_control,$obj->Nombre_Completo,$obj->R1,$obj->R2,$obj->R3,$obj->R4,$obj->R5,$obj->R6,$obj->R7,$obj->R8,$obj->R9,$obj->R9_1,$obj->R10,
$obj->R10_1,$obj->R11,$obj->R11_1,$obj->R12);
$stmt->execute();
$stmt->close();
$_SESSION['folio'] =$obj->N_control;

echo "Registro Almacenado\nPasará a la siguiente seccion";
?>

AQUI LES COMPARTO EL PROCEDIMIENTO ALMACENADO
BEGIN
    DECLARE CONTADOR INT;
    SELECT COUNT(*) INTO CONTADOR FROM gestion WHERE N_control=N_control;

    IF CONTADOR = 0 THEN
        SELECT
            'N° Control DISPONIBLE' AS RESPUESTA,
            '1' AS VALOR;
    ELSE
        SELECT
            'ESTE N° Control YA ESTÁ SIENDO OCUPADO' AS RESPUESTA,
            '2' AS VALOR;
    END IF;


text:
Q: $I \subset \mathbb{R}$ a not empty, open interval and $f: I \rightarrow \mathbb{R}$ convex function. Let $I \subset \mathbb{R}$ a not empty, open interval and  $f: I \rightarrow \mathbb{R}$ convex function.
Show that, $f$ is in every point in $I$ differentiable from the left and differentiable from the right, that the one-sided derivations $f'_+, f'_-:I \rightarrow \mathbb{R} $ growing monotonously and $\forall x_0\in I$: $f'_-(x_0)\le f'_+(x_0)$.
And show that you can infer from that: $f$ is continuous and in differentiable in every point except in countless many

A: Hint : $\forall \ (x,y,z) \in I^3, \ x<y<z \implies \frac{f(y)-f(x)}{y-x}≤ \frac{f(z)-f(x)}{z-x}≤\frac{f(z)-f(y)}{z-y} $


text:
Q: efficiently creating a list of pointers to a character in a buffer using arm neon simd I've been rewriting some performance sensitive parts of my code to aarch64 neon.  For some things, like population count, i've managed to get a 12x speed.  But for some algorithms i'm having trouble..
The high level problem is quickly adding a list of newline separated strings to a hashset.  Assuming the hashset functionality is optimal (I am looking into it next), first i need to scan for the strings in the buffer.
I have tried various techniques - but my intuition tells me that I can create a list of pointers to each newline, and then insert them into the hashset afterwards now that i have the slices.
The fundamental problem is I can't work out an efficient way to load a vector, compare against the newline, and spit out a list of pointers to the newlines. eg. the output is a variable length, depending on how many newlines were found in the input vector.
Here is my approach;
fn read_file7(mut buffer: Vec<u8>, needle: u8) -> Result<HashSet<Vec<u8>>, Error>
{
    let mut set = HashSet::new();
    let mut chunk_offset: usize = 0;

    let special_finder_big = [
        0x80u8, 0x40u8, 0x20u8, 0x10u8, 0x08u8, 0x04u8, 0x02u8, 0x01u8, // high
        0x80u8, 0x40u8, 0x20u8, 0x10u8, 0x08u8, 0x04u8, 0x02u8, 0x01u8, // low
    ];

    let mut next_start: usize = 0;

    let needle_vector = unsafe { vdupq_n_u8(needle) };
    let special_finder_big = unsafe { vld1q_u8(special_finder_big.as_ptr()) };

    let mut line_counter = 0;
    // we process 16 chars at a time
    for chunk in buffer.chunks(16) {

        unsafe {
            let src = vld1q_u8(chunk.as_ptr());
            let out = vceqq_u8(src, needle_vector);
            let anded = vandq_u8(out, special_finder_big);
            // each of these is a bitset of each matching character
            let vadded = vaddv_u8(vget_low_u8(anded));
            let vadded2 = vaddv_u8(vget_high_u8(anded));

            let list = [vadded2, vadded];
            // combine bitsets into one big one!
            let mut num = std::mem::transmute::<[u8; 2], u16>(list);
            // while our bitset has bits left, find the set bits
            while num > 0 {
                let mut xor = 0x8000u16; // only set the highest bit
                let clz = (num).leading_zeros() as usize;

                set.get_or_insert_owned(&buffer[(next_start)..(chunk_offset + clz)]);
                // println!("found '{}' at {} | clz is {} ", needle.escape_ascii(), start_offset + clz, clz);
                // println!("string is '{}'", input[(next_start)..(start_offset + clz)].escape_ascii());
                xor = xor >> clz;
                num = num ^ xor;
                next_start = chunk_offset + clz + 1;
                //println!("new num         {:032b}", num);
                line_counter += 1;
            }
        }
        chunk_offset += 16;

    }

    // get the remaining
    set.get_or_insert_owned(&buffer[(next_start)..]);

    println!(
        "line_counter: {} unique elements {}",
        line_counter,
        set.len()
    );

    Ok(set)
}

if I unroll this to do 64 bytes at a time, on a big input it will be slightly faster than memchr.  But not much.
Any tips would be appreciated.

A: I've shown this to a colleague who's come up with better intrinsics code than I would. Here's his suggestion, it's not been compiled, so there needs to be some finishing off of pseudo-code pieces etc, but something along the lines of below should be much faster & work:
let mut line_counter = 0;
for chunk in buffer.chunks(32) { // Read 32 bytes at a time
    unsafe {
        let src1 = vld1q_u8(chunk.as_ptr());
        let src2 = vld1q_u8(chunk.as_ptr() + 16);
        let out1 = vceqq_u8(src1, needle_vector);
        let out2 = vceqq_u8(src2, needle_vector);
        // We slot these next to each other in the same vector.
        // In this case the bottom 64-bits of the vector will tell you
        // if there are any needle values inside the first vector and
        // the top 64-bits tell you if you have any needle values in the
        // second vector.
        let combined = vpmaxq_u8(out1, out2);
        // Now we get another maxp which compresses this information into
        // a single 64-bit value, where the bottom 32-bits tell us about
        // src1 and the top 32-bit about src2.
        let combined = vpmaxq_u8(combined, combined);
        let remapped = vreinterpretq_u64_u8 (combined);
        let val = vgetq_lane_u64 (remapped, 0);
        if (val == 0) // most chunks won't have a new-line
          ... // If val is 0 that means no match was found in either vectors, adjust offset and continue.
        if (val & 0xFFFF)
          ... // there must be a match in src1. use below code in a function
        if (val & 0xFFFF0000)
          ... // there must be a match in src2. use below code in a function

    ...
    }
}

Now that we now which vector to look in, we should find the index in the vector
As an example, let's assume matchvec is the vector we found above (so either out1 or out2).
To find the first index:
// We create a mark of repeating 0xf00f chunks. when we fill an entire vector
// with it we get a pattern where every byte is 0xf0 or 0x0f. We'll use this
// to find the index of the matches.
let mask = unsafe { vreinterpretq_u16_u8 (vdupq_n_u16 (0xf00f)); }

// We first clear the bits we don't want, which leaves for each adjacent 8-bit entries
// 4 bits of free space alternatingly.
let masked = vandq_u8 (matchvec, mask);
// Which means when we do a pairwise addition
// we are sure that no overflow will ever happen.  The entries slot next to each other
// and a non-zero bit indicates the start of the first element.
// We've also compressed the values into the lower 64-bits again.
let compressed = vpaddq_u8 (masked, masked);
let val = vgetq_lane_u64 (compressed, 0);
// Post now contains the index of the first element, every 4 bit is a new entry
// This assumes Rust has kept val on the SIMD side. if it did not, then it's best to
// call vclz on the lower 64-bits of compressed and transfer the results.
let pos = (val).leading_zeros() as usize;
// So just shift pos right by 2 to get the actual index.
let pos = pos >> 2;

pos will now contain the index of the first needle value.
If you were processing out2, remember to add 16 to the result.
To find all the indices we can run through the bitmask without using clz, we avoid the repeated register file transfers this way.
// set masked and compressed as above
let masked = vandq_u8 (matchvec, mask);
let compressed = vpaddq_u8 (masked, masked);
int idx = current_offset;
while (val)
{
  if (val & 0xf)
   {
     // entry found at idx.
   }
   idx++;
   val = val >> 4;
}


text:
Q: What's the relationship among Enclave , thread and process? What's the relationship among Enclave , thread and process?
Does SGX support multi-thread or multi-process?
What will happen if I call the "fork" to create a new process inside a enclave?

A:
What's the relationship among Enclave , thread and process?

An enclave can be considered part of a process. A process can add enclave pages to its memory. After initializing the enclave, the process can execute the enclave code by issuing EENTER [1]. When the enclave call returns, it returns execution to non-enclave (untrusted) memory via EEXIT.
A thread is one of possibly multiple threads of executions of a process.

Does SGX support multi-thread or multi-process?

You can't run multiple processes in the same enclave, but you can run multiple threads in the same enclave. Each thread must have their own Thread Control Structure (TCS), which is supported by SGX [2]. With the SGX2 extensions (which are not supported by any CPU yet) it is also possible to add and remove TCS pages after enclave initialization, thereby allowing the enclave to dynamically adjust the amount of threads.

What will happen if I call the "fork" to create a new process inside a enclave?

fork is a system call, which is an illegal instruction in an enclave, therefore it will result in an exception [3].
Sources: The following chapters in https://software.intel.com/sites/default/files/managed/7c/f1/332831-sdm-vol-3d.pdf:
[1] 36.3 Enclave Life Cycle
[2] 38.8 TCS
[3] 38.6.1 Illegal Instructions


text:
Q: Is there a way to get elements from Chrome Browser in pure C#, without Selenium In C# I use FindElement to find element:
string text = driver.FindElement(By.XPath("//*[@id='errorPopup']")).text;

Is there a way to perform such action on chrome without Selenium altogether (that means no IJavaScriptExecutor as well)?
Here's my problem:
I'm working with Selenium on a Chrome page in a certain IFrame in my main thread.
I need to constantly search for an Error Popup, in a different IFrame which the Driver points to, without (and this is very important), using SwitchTo(), in a different thread.
Is there a way to go outside an IFrame without SwitchTo()?


text:
Q: To add Images to a JavaScript Array and then display them on another function call I have a small problem here which I have been breaking my head over but somehow the solution has evaded me. Can anybody please tell me what I am doing wrong here?
On a function saveImages() call, I have to save an image from a canvas to an ImageArray which is a Javascript array. I have declared the ImageArray as a global variable (i.e outside any of the functions)
var ImageArray = new Array(); // is this the proper way to do it?

Next, I call the saveImages() function.
function saveImages() {

  //here I draw on the canvas
   Image = canvas.toDataURL('image/jpeg');
   //window.open(Image, 'new_window');   // I see the window with the Jpeg Image data So I am sure that the image actually comes
   ImageArray[0].src = Image; // Looked up the internet to find that dataToURL can be used as img source
   no_of_pics_compared= ImageArray.length();
   alert('no_of_pics_compared' + no_of_pics_compared)     // I do not get this alert

}

I do not get the last alert which means that there is some flaw in the code which makes it stop working.
I want to be able to call this saveImages() function multiple times until a limit is reached (say 5) and want to display all the 5 images in the ImageArray on call of a separate function say displayImages(). This is the reason I want to keep the ImageArray as global
Can someone please tell me how do I correct what is going wrong. Thanks very  much in advance :)

A: Use this instead.
var array = [] ;
array.push(Image) ;

A: *

*You didn't initialize the ImageArray[0] before setting its src property. You can write the following instead:
ImageArray[0] = {
    src: Image
};

*Array's length is a property, not a function, so it should be:
no_of_pics_compared = ImageArray.length;

*The question:
var ImageArray = new Array(); // is this the proper way to do it?

Yes! But you can write the following short version instead:
var ImageArray = [];

You can read more on how to create arrays in JavaSscript here.

Finally, your code after the mentioned changes:

var ImageArray = [];

function saveImages() {
   Image = canvas.toDataURL('image/jpeg');
   ImageArray[0] = {
     src: Image
   };

   no_of_pics_compared= ImageArray.length;
   alert('no_of_pics_compared' + no_of_pics_compared);

}

A: In an array first you have to create the object that you want to add to the array and then push it right to the array:
var ImageArray = new Array(); // Yes this is one of the proper ways to do it.
   //Second Way:
   // var ImageArray = [];
function saveImages() {

   var newImage = new Image();
   newImage.src = canvas.toDataURL('image/jpeg');
   .
   .
   .
   ImageArray.push(newImage);
   .
   .
   .

}

And also the length is a property not a function so you have to get it like this:
no_of_pics_compared= ImageArray.length;


text:
Q: Is there any open source project in c# or python to plot a Gantt chart? I would like to plot an operating system log contains:
time-stamp   event

Events can be tid or enter_irq#_handler or exit_irq#_handler and each has its own unique identifier.
Does any one have a recommendation for a c# or wxpython I can use to build my own tool?
I have 100K events and about 2k unique events list of tid, irq etc.
I found this and that, but they are not designed for 2k unique events identifier.
I thought that Gantt chart is the right solution:

A: I would write some GNU gawk script feeding a GnuPlot script.
You certainly want to collapse (= group), or select a tiny subset of, some event kinds together (and you should know which ones). Showing 2000 loosely related curves to a user has no sense, even on a gigantic high-resolution screen set.
Because human brains and eyes cannot grasp thousands of different curves at once


text:
Q: How to find which level causes a crash in Android I have a small game which has a few levels. In the google play console, I am getting crashes in the Game-Fragment but it's hard for me to find which level is causing the crash. The first few levels look okay and tested. I am just wondering what is best/standard approach to get the crash along with the level ID/some more information.

A: There are different good libraries that allow you to improve logging of the exceptions, one of them is Crashlytics from Google.
With Crashlytics, you can catch exceptions that are happening with following code and log it(and include custom parameters in the message variable):
try {
    methodThatThrows();
} catch (Exception e) {
    Crashlytics.log(priority, tag, message);
    // additional handling of your exception
}

You can improve your logging this way to include all kind of helpful information. See documentation page for details:
https://firebase.google.com/docs/crashlytics/customize-crash-reports


text:
Q: Nest and merge JSON based on namespaces I've got the following JSON document:
(sorted by namespace; any namespace can appear multiple times)
[ {"namespace": "/"       , "exports": {"a": 10, "b": 11}}
, {"namespace": "/"       , "exports": {"c": 12, "d": 13}}
, {"namespace": "/bar"    , "exports": {"e": 14, "f": 15}}
, {"namespace": "/bar/baz", "exports": {"g": 16, "h": 17}}
]

that I need to convert into this JSON document:
(the risk of key collisions can be ignored)
{ "a": 10
, "b": 11
, "c": 12
, "d": 13
, "bar": { "e": 14
         , "f": 15
         , "baz": { "g": 16
                  , "h": 17}}}

Note that whilst nesting namespaces we only keep their basename e.g.,
/
/bar
/bar/baz
/bar/baz/bat

becomes:
{"bar": {"baz": {"bat": {}}}}

Members must be nested under their corresponding namespace object with the only expection of members of the root "/" namespace which become top-level properties.
I've scratched my head a few times over this problem as I'd like to get this done in one pass (ideally) but I'm open to any other suggestions.

A: Convert namespaces to paths and you can build the desired output using getpath/setpath built-ins.
reduce .[] as {$namespace, $exports} ({};
  ($namespace | ltrimstr("/") | split("/")) as $path
  | setpath($path; getpath($path) + $exports)
)

Online demo


text:
Q: Load encrypted PKCS1 private key from file I have a PKCS1 private key in a file and I load it using
b, err := ioutil.ReadFile(path)
if err != nil {
    return nil, err
}

Then, I try to convert it into private key object
block, _ := pem.Decode(b)
der, err := x509.DecryptPEMBlock(block, []byte("qwerty"))
if err != nil {
    return nil, err
}

bytes := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: der})

return x509.ParsePKCS1PrivateKey(bytes)

But this code throws exception in DecryptPEMBlock
x509: no DEK-Info header in block

I didn't find any documentation about this in golang

A: I made a mistake with my private key file and here is a working code
func GetPrivateKey(path string) (*rsa.PrivateKey, error) {
    b, err := ioutil.ReadFile(path)
    if err != nil {
        return nil, err
    }

    block, _ := pem.Decode(b)
    der, err := x509.DecryptPEMBlock(block, []byte(*PrivateKeyPassword))
    if err != nil {
        return nil, err
    }

    return x509.ParsePKCS1PrivateKey(der)
}

P.S. Go does have a package to decrypt PKCS1 private keys, but does not have for PKCS8.

A: Go does not have package to decode PKCS files it seems
Checkout this link for more details PKCS
I cant find a package to decode PKCS1 keys
Use this package to decode the PKCS8 files, there are some packages to decode PKCS8, PKCS10, PKCS12 but not for PKCS1


text:
Q: jquery lightGallery plugin showing images on the side/edge I have tried using lightGallery plugin for displaying a gallery, but when I click on an image it show them in half and on the side like this. All I want is to center the image. I have looked on the inspector and found some not friendly css markups and styles which I don't understand. Please help

My html markup is
<link rel="stylesheet" href="css/lightgallery.min.css">

and javascript is

    $(function () {
        $("#photos").lightGallery();
    })

I don't know what's wrong, I have searched the net and found nothing. Maybe because I don't know what to search for.

A: I'm not sure you have solved this issue or not.
I'm facing this issue few days, today I had figure out the problem, but I not sure your issue is it same as mine. How I fix this issue is my CSS body have "text-align:center", once I deleted the "text-align:center", issue fixed.
I hope this can help you.
Sorry for my poor english.


text:
Q: window.open function load CSS Is there any way to load CSS during pop up a window?
       function kmt_ShowBoxPopup(targetDivID, aTag)
        {
        var orgin_div_content=document.getElementById(targetDivID).innerHTML;
        //alert(targetDivID);
        showBoxPopupWin =window.open("",targetDivID,'height=400,width=710,screenX=250,screenY=80, scrollbars=yes');
        showBoxPopupWin.document.write ('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">'+
'<title>'+targetDivID+'</title>'+orgin_div_content+'</body');
        if (window.focus) {showBoxPopupWin.focus()}
        }

    show me how..

    p
    p
    p

Here is my code. I would like to load a CSS in showBoxPopupwin.document.write function. Is it possible?
cheers,
Qing

A: Why not just write a <link href="your.css" ... /> just like you're writing the rest of the HTML?

A: Just add a link element before  just as you would in any other HTML document.

A: Sure, just output a normal link tag in the HTML you're writing.


text:
Q: How to install module in Jupyter Notebooks for iPython I am using an iPython note in Jupyter Notebooks and need to use the import lmfit. How can I import it such that it will become available in my jupyter notebook?
I should clarify this question applies to multiple modules (really anything you could install using pip or conda).  I am trying to determine how to install modules in a Jupyter Notebook.

A: Run ! pip install <package> within the jupyter notebook.
The ! tells the notebook to run the command in bash, just make sure the pip you are using is the same interpreter the notebook is using

A: Please check the installation guide for lmfit here.

There is some problem with this package. Even after installation, import to lmfit is not possible. My advise is to ask for support here or check the git repository and raise an issue.


text:
Q: Проблема установки Laravel в логах вот так индекс загружается но когда обращается к ядру сбой загрузки происходит
[Sat Mar 05 16:51:43.843787 2016] [fcgid:warn] [pid 56608] (104)Connection reset by peer: [client 91.192.136.218:46566] mod_fcgid: error reading data from FastCGI server
[Sat Mar 05 16:51:43.843822 2016] [core:error] [pid 56608] [client 91.192.136.218:46566] End of script output before headers: index.php


text:
Q: Subsetting the data frame and applying cumulative operation on multiple columns I have a dataset that looks like below.
df=pd.DataFrame({'unit': ['ABC', 'DEF', 'GEH','IJK','DEF','XRF','BRQ'], 'A': [1,1,1,0,0,0,1], 'B': [1,1,1,1,1,1,0],'C': [1,1,1,0,0,0,1],'row_num': [7,6,5,4,3,2,1]})

I am trying to get the logic

*

*Step 1-Consider a subset with row_number <=4.

*Step 2- Column A,B,C has total 12 values(0's and 1's).

*Steps 3-Count number of '1' within columns A,B,C. From the example
there are five 1's and seven 0's which    calculates to 40%(5/12) of
1's.

*Steps-4 since count of 1's is greater than 40% create a column flag
with 1 else if count of 1 is less than 10% then 0.

A: Hopefully I got it this time:
subdf = df.iloc[3:, 1:4]
df['flag'] = 1 if subdf.values.sum()/subdf.size >= 0.1 else 0

output:
  unit  A  B  C  row_num  flag
0  ABC  1  1  1        7     1
1  DEF  1  1  1        6     1
2  GEH  1  1  1        5     1
3  IJK  0  1  0        4     1
4  DEF  0  1  0        3     1
5  XRF  0  1  0        2     1
6  BRQ  1  0  1        1     1


text:
Q: How do I define a data type consisting of other data types? I want to define the data type Currency, which consists of three other data types. I have the problem that Haskell doesn't recognize the data types as a part of currency, which breaks everything.
My idea was to define the different currencies as their own data types and then add them to the Currency type, which I tried with:
data Euro = MkEuro Integer Integer
data Dollar = MkDollar Integer Integer
data Yen = MkYen Integer
data Currency = Euro | Dollar | Yen

If I want to use the type Currency in any function I get a variation of the following error message:
Couldn't match expected type `Currency' with actual type `Dollar'

Sadly I have to use the type Currency and can't create different functions for all three currencies.

A: Currently your Currency is constructed as three values, that take no parameters. So Euro is a value, Dollar is a value, and Yen is a value, but not MkYen 15.
You can add parameters to your data constructors like:
data Currency = Euro Euro | Dollar Dollar | Yen Yen
Then you thus can construct a Currency with:
Euro (MkEuro 14 25) :: Currency
The :: Currency is not necessary. The MkEuro will thus construct an object of the Euro type, and then we use the Euro data constructor with type Euro -> Currency to construct a Currency.

Sadly I have to use the type Currency and can't create different functions for all three currencies.

You might want to make a Currency typeclass however, that provides an interface that says what functions a currency should implement, and then make Euro, Dollar, and Yen instances of that typeclass.

A: The issue with what you attempted is that the Euro, Dollar and Yen defined on the first 3 lines (on the left-hand-side of the = signs) are types, whereas those in the last line, on the right-hand-side, are data constructors. These are different things, which is why you're allowed to give them the same names - but also means that the value Dollar has the type Currency, not the type Dollar.
You had the right idea to create a union type combining the other three - but you are confusing the data constructors (which are just "tags") with the types of the values they hold. You can fix it like this:
data Currency = Euro Euro | Dollar Dollar | Yen Yen

That might look confusing to have the same name twice (three times, too) - but the two occurrences of the name have different meanings. In Euro Euro, for example, the first Euro is a data constructor (a function which "tags" the value), while the second is the type on which the constructor function operates.


text:
Q: sass реализация ::before пытаюсь прописать красную полоску как на картинке, но пока ничего не выходит

мой код
.news h2
 color: $red

 &::before
  margin-top: 15px
  margin-bottom: -18px
  content: ""
  height: 1px
  width: 50%
  position: relative
  background: green
  display: inline-block

может кто-нибудь помочь?

A: Например можно так реализовать:
.news h2
  color: red
  padding-left: 50px
  position: relative
  &:before
    margin-top: 15px
    content: ""
    height: 1px
    width: 50px
    left: 0
    position: absolute
    background: green
    display: inline-block

Посмотреть на CodePen


text:
Q: Subtracting datetimes in pandas always equals 0 two columns of dates in my dataframe. The first column is df['schedule_day'] and the second is df['appointment_day']. I am trying to create another column that will be the different between these two. However, when I do the subtraction, the new column just has 0 for each answer.
The original data has these dates as strings and I convert them to datetime objects before doing the subtraction and the result is still a datetime object.
Here is the code I have used so far.
df = pd.read_csv('noshowappointments-kagglev2-may-2016.csv')

df['schedule_day'] = pd.to_datetime(df['schedule_day'])
df['appointment_day'] = pd.to_datetime(df['schedule_day'])

df['difference'] = df['schedule_date'] - df['appointment_date']

When I inspect the dtypes the after the initial read they are object / string types. After I do the conversion they are datetime64[ns].
I also tried to split the date and time apart into seperate columns to do the subtractions but I still just get 0 days for each row.

A: Small copy error, you use  df['schedule_day'] for both conversions
df['schedule_day'] = pd.to_datetime(df['schedule_day'])
df['appointment_day'] = pd.to_datetime(df['schedule_day'])

Change to:
df['schedule_day'] = pd.to_datetime(df['schedule_day'])
df['appointment_day'] = pd.to_datetime(df['appointment_day'])


text:
Q: regarding conditional independence and its graphical representation When studying covariance selection, I once read the following example. With respect to the following model:

Its covariance matrix and inverse covariance matrix are given as follows,

I do not understand why the independence of $x$ and $y$ is decided by the inverse covariance here?
What is the mathematical logic underlying this relationship?
Also, the left graph in the following figure is claimed to capture the independence relationship between $x$ and $y$; why?

A: The inverse covariance matrix can be used to work out conditional variances and covariances for multivariate Gaussian distributions. An earlier question gives some references
For example to find the conditional covariance of $Y$ and $Z$ given the value $X=x$, you would take the bottom right corner of the inverse covariance matrix
$$\left( \begin{array}{rr}
1 & -1  \\
-1 & 3  \end{array} \right) \text{ and re-invert it to }\left( \begin{array}{rr}
\tfrac32 & \tfrac12  \\
\tfrac12 & \tfrac12  \end{array} \right)$$
which does indeed give the covariance matrix of $Y$ and $Z$ conditioned on the the value for $X=x$.
So similarly to find the conditional covariance matrix of $X$ and $Y$ given the value for $Z=z$, you would take the top left corner of the inverse covariance matrix
$$\left( \begin{array}{cc}
1 & 0  \\
0 & 1  \end{array} \right) \text{ and re-invert it to }\left( \begin{array}{cc}
1 & 0  \\
0 & 1 \end{array} \right)$$
telling you that the conditional covariance between $X$ and $Y$ given $Z=z$ is $0$ (and that each of their conditional variances is $1$).
To conclude that this zero conditional covariance implies conditional independence, you also have to use the fact this is a multivariate Gaussian (as in general zero covariance does not necessarily imply independence).  You know this from the construction.
Arguably you also know about the conditional independence from the construction, since you are told that $\epsilon_1$ and $\epsilon_2$ are iid, so conditioned on a particular value for $Z=z$, $X=z+\epsilon_1$ and $Y=z+\epsilon_2$ are also iid. If you know $Z=z$, there is no additional information from $X$ that helps you say anything about possible values of $Y$.

A: This is a supplement to the correct and accepted answer. In particular, the original question contains a follow-up question about the statement the book makes.

Also, the left graph in the following figure is claimed to capture the independence relationship between $X$ and $Y$, why?

This is what is addressed in this answer, and is the only thing addressed in this answer.
To make sure we are on the same page, in what follows I use this definition of (undirected) conditional independence graph which corresponds (at least roughly) to Markov random fields:

Definition: The conditional independence graph of $X$ is the undirected graph $G=(K,E)$ where $K=\{ 1, 2, \dots, k \}$ and $(i,j)$ is not in the edge set if and only if $X_i \perp \! \! \! \perp X_j | X_{K \setminus \{i,j\}}$. (Where  $X_{K \setminus \{i,j\}}$ denotes the vector of all of the random variables except for $X_i$ and $X_j$.)

From p. 60 of Whittaker, Graphical Models in Applied Mathematical Multivariate Statistics (1990).
Here, using the argument given by Henry in the correct, accepted answer, we can establish that $X$ and $Y$ are conditionally independent given $Z$, in notation, $X \perp \! \! \perp Y \ | Z$.
Since the only three random variables are $X, Y$, and $Z$, this means that $X$ and $Y$ are conditionally independent when given all of the other remaining random variables (in this case just $Z$).
Using the definition of conditional independence graph given above, this means that all edges in the graph should be included except for the edge between $X$ and $Y$. Indeed, this is exactly what is shown on the right graph of that picture.
Regarding the left graph, it is unclear without having more context, but I think the idea is just to show what the conditional independence graph would look like if we didn't have zeros in those entries of the inverse covariance matrix.
In particular, using the above definition, we see that we can start with the complete graph on the nodes $X, Y, Z$, which is the left graph in that picture, and then derive the conditional independence graph from that first graph by removing all edges corresponding to conditionally independent random variables. The picture does compare the two graphs explicitly ("versus"), which to me suggests a comparison between the complete graph one might start with and the conditional independence graph one ends up with if/when they apply the definition of conditional independence graph as given above.


text:
Q: Generate presigned url for uploading file to google storage using python I want to upload a image from front end to google storage using javascript ajax functionality. I need a presigned url that the server would generate which would provide authentication to my frontend to upload a blob.
How can I generate a presigned url when using my local machine.
Previously for aws s3 I would do :
pp = s3.generate_presigned_post(
            Bucket=settings.S3_BUCKET_NAME,
            Key='folder1/' + file_name,
            ExpiresIn=20  # seconds
        )

When generating a signed url for a user to just view a file stored on google storage I do :
    bucket = settings.CLIENT.bucket(settings.BUCKET_NAME)
    blob_name = 'folder/img1.jpg'
    blob = bucket.blob(blob_name)
    url = blob.generate_signed_url(
        version='v4',
        expiration=datetime.timedelta(minutes=1),
        method='GET')

A: Spent 100$ on google support and 2 weeks of my time to finally find a solution.
client = storage.Client() # works on app engine standard without any credentials requirements

But if you want to use generate_signed_url() function then you need service account Json key.
Every app engine standard has a default service account. ( You can find it in IAM/service account). Create a key for that default sv account and download the key ('sv_key.json') in json format. Store that key in your Django project right next to app.yaml file. Then do the following :
from google.cloud import storage
CLIENT = storage.Client.from_service_account_json('sv_key.json')
bucket = CLIENT.bucket('bucket_name_1')
blob = bucket.blob('img1.jpg') # name of file to be saved/uploaded to storage
pp = blob.generate_signed_url(
    version='v4',
    expiration=datetime.timedelta(minutes=1),
    method='POST')

This will work on your local machine and GAE standard. WHen you deploy your app to GAE, sv_key.json also gets deployed with Django project and hence it works.
Hope it helps you.

A: Editing my answer as I didn't understand the problem you were facing.
Taking a look at the comments thread in the question, as @Nick Shebanov stated, there's one possibility to accomplish what are you trying to when using GAE with flex environment.
I have been trying to do the same with GAE Standard environment with no luck so far. At this point, I would recommend opening a feature request at the public issue tracker so this gets somehow implemented.

A: *

*Create a service account private key and store it in SecretManager (SM).

*In settings.py retrieve that key from SecretManager and store it in a constant - SV_ACCOUNT_KEY

*Override Client() class func from_service_account_json() to take json key content instead of a path to json file. This way we dont have to have a json file in our file system (locally, cloudbuild or in GAE). we can just get private key contents from SM anytime anywhere.

settings.py
secret = SecretManager()
SV_ACCOUNT_KEY = secret.access_secret_data('SV_ACCOUNT_KEY')

signed_url_mixin.py
import datetime
import json

from django.conf import settings
from google.cloud.storage.client import Client
from google.oauth2 import service_account

class CustomClient(Client):
    @classmethod
    def from_service_account_json(cls, json_credentials_path, *args, **kwargs):
        """
        Copying everything from base func (from_service_account_json).
        Instead of passing json file for private key, we pass the private key
        json contents directly (since we cannot save a file on GAE).
        Since its not properly written, we cannot just overwrite a class or a
        func, we have to rewrite this entire func.
        """
        if "credentials" in kwargs:
            raise TypeError("credentials must not be in keyword arguments")
        credentials_info = json.loads(json_credentials_path)
        credentials = service_account.Credentials.from_service_account_info(
            credentials_info
        )
        if cls._SET_PROJECT:
            if "project" not in kwargs:
                kwargs["project"] = credentials_info.get("project_id")

        kwargs["credentials"] = credentials
        return cls(*args, **kwargs)

class _SignedUrlMixin:
    bucket_name = settings.BUCKET_NAME
    CLIENT = CustomClient.from_service_account_json(settings.SV_ACCOUNT_KEY)
    exp_min = 4  # expire minutes

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.bucket = self.CLIENT.bucket(self.bucket_name)

    def _signed_url(self, file_name, method):
        blob = self.bucket.blob(file_name)
        signed_url = blob.generate_signed_url(
            version='v4',
            expiration=datetime.timedelta(minutes=self.exp_min),
            method=method
        )
        return signed_url

class GetSignedUrlMixin(_SignedUrlMixin):
    """
    A GET url to view file on CS
    """

    def get_signed_url(self, file_name):
        """
        :param file_name: name of file to be retrieved from CS.
            xyz/f1.pdf
        :return: GET signed url
        """
        method = 'GET'
        return self._signed_url(file_name, method)

class PutSignedUrlMixin(_SignedUrlMixin):
    """
    A PUT url to make a put req to upload a file to CS
    """

    def put_signed_url(self, file_name):
        """
        :file_name: xyz/f1.pdf
        """
        method = 'PUT'
        return self._signed_url(file_name, method)