text:
Q: Visual Basic 6 - Runtime Error 75 - Path/File Access Error We have an enterprise VB6 application, this application require access to many shared resources. For testing purposes of new added functionality we have released a new version, then we set permissions to the users that will be testing the new functionality. In short we have prepare the scenario for the application test to success.
When trying to run the application in some user's PC using some development user account we succeed, but when we try to access to the same executable with the user account we receive a runtime Error 75 - Path/File Access Error.
Some ideas about the origin of such error? all the ideas will be appreciate.
Note: It is important to say that developers and users both are in the same intra-net and also in the same network domain.

A: The error almost always indicates a simple security violation.  Could be file permissions, or as simple as trying to write to a file marked read-only.
Or the path can be invalid for the user, such as trying to open a file on a drive letter that doesn't exist for the user.
Simply looking up error 75 in the VB6 manual will list most of the possibilities.

A: If you don't want to debug it, you could watch it with a tool like Process Monitor and just see the last accessed file system object. It most likely tries to access or do something the user account doesn't have or where there are insufficient rights. Its almost impossible to get the exact reason just from the error message (as the error number is more generic and will popup for different ressources or file operations).


text:
Q: How to allow using javascript in RichHtmlField control? Is it possible to set up RichHtmlField control to allow javascript in HTML?
I mean I need to insert some script into field content, but the code is removed from source after submit.

A: I don't think there is a way of inserting javascript into the RichHtmlField. Usually in this situation, the following options are available:
a) If you're just trying to get a piece of javascript anywhere on the page, you could insert a Content Editor Web Part. It allows you to insert javascript.
b) If you're stuck because you promised RichHtmlField javascript insertion to your client (or other common scenarios), you could purchase Telerik RadEditor.
It should get around the issue.
Hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Загрузка картинки в альбом одноклассники API Пытаюсь загрузить фотографию в альбом. Сначала проходит авторизация вот такой вот ссылкой
http://www.odnoklassniki.ru/dk?st.cmd=oAuthAuthorize&st.scope=VALUABLE+ACCESS%3BPHOTO+CONTENT%3BSET+STATUS&st.response_type=code&st.redirect_uri=http%3A%2F%2Fsite.com%2F&st.client_id=91****&tkn=4***

Дальше пытаюсь вызвать метод photosV2.getUploadUrl и получаю вот такую ошибку

( [error_code] => 10 [error_data] => photo content [error_msg] =>
  PERMISSION_DENIED : User must grant an access to permission 'PHOTO
  CONTENT' )

Может кто-нибудь что то посоветовать? Либо может кто уже занимался этим

A: Кроме VALUABLE ACCESS нужен так же PHOTO CONTENT.
Это права доступа.

A: В описании ошибки приведена исчерпывающая информация: запрещен доступ к привилегии PHOTO CONTENT.
Корректно сформированный запрос еще не гарантирует результата его выполнения. На другой стороне (в аккаунте пользователя) вам должно быть позволено реализовать ту или иную задачу (т.е. выполнить какой-то код).
Единственный способ реализовать запрос – делегировать право (grant permission) на программный доступ к фотографиям.


text:
Q: Perform annotated method param transformation in java i have a controller method:
@GetMapping
public Page<SomethingDto> getSomething(@RequestParam(required = false, defaultValue = 50)
   @ProperLimit Integer limit) {
    ...
    return service.getSomething(limit);
}

I need to set limit value to 50 in case it is present and it is greater then 50. How i have to implement @ProperLimit annotation to achive this?
Thanks.

A: You can try 'HandlerMethodArgumentResolver',get and reset the param value at 'resolverArgument'.


text:
Q: How to use @dev in project root when a package requires ^1.0 In my dev project composer.json I have:
"require": {
    "bastinald/laravel-automatic-migrations": "@dev",
    "bastinald/laravel-bootstrap-forms": "@dev",
    "bastinald/laravel-livewire-routes": "@dev",
    "bastinald/livewire-bootstrap-auth": "@dev"
},

They are all added as repositories from the filesystem and symlinked so I can work on them within this project. I use this project to develop all of my own packages.
In one of my projects (bastinald/livewire-bootstrap-auth), I have this composer.json:
"require": {
    "bastinald/laravel-automatic-migrations": "^1.0",
    "bastinald/laravel-bootstrap-forms": "^1.0",
    "bastinald/laravel-livewire-routes": "^1.0",
},

This is causing the following error:
    Your requirements could not be resolved to an installable set of packages.

    Problem 1
    - Root composer.json requires bastinald/livewire-bootstrap-auth dev-master -> satisfiable by bastinald/livewire-bootstrap-auth[dev-master].
    - bastinald/livewire-bootstrap-auth dev-master requires bastinald/laravel-automatic-migrations ^1.0 -> satisfiable by bastinald/laravel-automatic-migrations[1.0.0, 1.0.1, 1.0.2, 1.0.3] from composer repo (https://repo.packagist.org) but bastinald/laravel-automatic-migrations[dev-master] from path repo (packages/bastinald/laravel-automatic-migrations) has higher repository priority. The packages with higher priority do not match your constraint and are therefore not installable. See https://getcomposer.org/repoprio for details and assistance.

I need to keep ^1.0 inside of my package json file for when it gets released. How do I make it so that I can still use @dev for all the packages in my development project, while using released versions inside the package composer.json files? Also, I want to make sure the packages used by other packages use @dev while in the dev project.
Is this possible? Or should I just switch the version from @dev back to ^1.0 before pushing a release like I have been?

A: Use dev-master as 1.0 as version, for example in your case:
"require": {
    "bastinald/laravel-automatic-migrations": "dev-master as 1.0",
    "bastinald/laravel-bootstrap-forms": "dev-master as 1.0",
    "bastinald/laravel-livewire-routes": "dev-master as 1.0",
    "bastinald/livewire-bootstrap-auth": "dev-master as 1.0"
},


text:
Q: How can I populate text boxes with values from a properties file? I have an html page with a dropdown box and a text box.
When an option is clicked in the dropdown, the value from the .properties file must be populated in the text box using java or java script (no database).
My properties file:
 servers=Demo
 serversTolookfor=Links,name
 Demo_name=Demo Server
 Demo_Links=https://mobileapplication.gh:8080

server.html:

    Server Name:
    <selectname="serverName" class="dropdown">
    <option value="Demo Server">Demo Server</option>
    </select>

Server Link:	<input type="text" name="server">

     <input type="Submit" value="Save">

A: use place holder in your jsp(don't use html file ) file.
Spring config
<util:properties id="propertyConfigurer"
                  location="classpath:yourPropertyFileClasspathHere "/>
<context:property-placeholder properties-ref="propertyConfigurer" />

jsp
<spring:eval expression="@propertyConfigurer.getProperty('propertyNameHere')" />

A: I hope you want like this:
config.properties content
#Crunchify Properties
user=Crunchify
company1=Google
company2=eBay
company3=Yahoo

CrunchifyReadConfigMain.java
package crunchify.com.tutorial;

import java.io.IOException;

public class CrunchifyReadConfigMain {

    public static void main(String[] args) throws IOException {
        CrunchifyGetPropertyValues properties = new CrunchifyGetPropertyValues();
        properties.getPropValues();
    }
}

CrunchifyGetPropertyValues.java
package crunchify.com.tutorial;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;

public class CrunchifyGetPropertyValues {

    public String getPropValues() throws IOException {

        String result = "";
        Properties prop = new Properties();
        String propFileName = "config.properties";

        InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);

        if (inputStream != null) {
            prop.load(inputStream);
        } else {
            throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
        }
        Date time = new Date(System.currentTimeMillis());
        // get the property value and print it out
        String user = prop.getProperty("user");
        String company1 = prop.getProperty("company1");
        String company2 = prop.getProperty("company2");
        String company3 = prop.getProperty("company3");

        result = "Company List = " + company1 + ", " + company2 + ", " + company3;
        System.out.println(result + "\nProgram Ran on " + time + " by user=" + user);
        return result;
    }
}

Output:
Company List = Google, eBay, Yahoo
Program Ran on Mon Feb 23 21:54:55 PDT 2015 by user=Crunchify

A: If you want in normal jsp then use following code:
<%@ page import="java.io.FileInputStream"%>
<%@ page import="java.util.Properties"%>

<%
    Properties property = null;
    FileInputStream fis = new FileInputStream("path of A.properties") ;
    property =new Properties();
    property.load(fis);
    String username = property.getProperty("username");
%>


text:
Q: Replacing sequences of space-delimited numbers in huge input with awk How can I replace sequences of space-delimited numbers when those sequences span multiple lines and the input is too big to fit in RAM.
A sample input would be:
edit: I re-worked the sample input and input parameters for introducing border cases (excluding ones that have to do with the length of the matched sequence or replacement priorities)
   3  12  3   4
   0   6   7  10
   8   9  12   3
   4   6   7  8
  10  6   6   7
  9 199  10  11
  11

note: the number of fields per line is homogeneous but not known in advance; the last line might contain less fields
From that input I would like to:

*

*replace 3 4 with &

*replace 6 7 8 with 9 9

*replace 6 7 9 with 8 8

*replace 7 10 with 11 12

*replace 0 with nothing

*replace 10 with 13 10

*replace 8 9 12 3 5 with #
The expected output would have one number or replacement per line:
3
12
&

6
11 12
8
9
12
&
9 9
13 10
6
8 8
199
13 10
11
11

I'm trying to do the task with awk but I'm having a hard time implementing a dynamic state machine with a pseudo B-Tree:
tr -s '[:space:]' '\n' < input.txt |
awk '
    BEGIN {
        for (i = 2; i < ARGC; i += 2) {
            n = split(ARGV[i], arr)
            k = ""
            for (j = 1; j <= n; j++) {
                k = j SUBSEP k SUBSEP arr[j]
                Tree[k]
            }
            Tree[k] = "$" ARGV[i+1] #=> now can test "if (Tree[k])"
            delete ARGV[i]
            delete ARGV[i+1]
        }
    }
    {
        Key = (int(Key) + 1) SUBSEP Key SUBSEP $1
        if ( Key in Tree ) {
            if (Tree[Key]) {
                print substr(Tree[Key],2)
                Buffer = ""
                Key = ""
            }
            else
                Buffer = Buffer $1 "\n"

        } else {
            print Buffer $1
            Buffer = ""
            Key = ""
        }
    }
    END { if (Buffer != "") printf ("%s", Buffer) }
' - \
    '3 4'        '&'     \
    '6 7 8'      '9 9'   \
    '6 7 9'      '8 8'   \
    '7 10'       '11 12' \
    '0'          ''      \
    '10'         '13 10' \
    '8 9 12 3 5' '#'

edit: I realised that the code doesn't backtrack after failing to find a complete match in the B-tree, so it's wrong...

How I'm planning to tackle the problem
I'm emulating a B-tree with an array and keys in the following format:

*

*from the middle to the left of the key are the consecutive depths

*from the middle to the right of the key are the consecutive values

When a key exists in Tree:

*

*if it doesn't have an associated value then it's a node

*if there's a value then it's a leaf
So, for the current input parameters, the content of the Tree array will be:
# from param: "3 4" => "&"
Tree[  1,"",3  ]
Tree[2,1,"",3,4] = "$&"

# from param: "6 7 8" => "9 9"
Tree[    1,"",6    ]
Tree[  2,1,"",6,7  ]
Tree[3,2,1,"",6,7,8] = "$9 9"

# from param: "6 7 9" => "8 8"
Tree[    1,"",6    ]
Tree[  2,1,"",6,7  ]
Tree[3,2,1,"",6,7,9] = "$8 8"

# from param: "7 10" => "11 12"
Tree[  1,"",7   ]
Tree[2,1,"",7,10] = "$11 12"

# from param: "0" => ""
Tree[1,"",0] = "$"

# from param: "10" => "13 10"
Tree[1,"",10] = "$13 10"

# from param: "8 9 12 3 5" => "#"
Tree[        1,"",8         ]
Tree[      2,1,"",8,9       ]
Tree[    3,2,1,"",8,9,12    ]
Tree[  4,3,2,1,"",8,9,12,3  ]
Tree[5,4,3,2,1,"",8,9,12,3,5] = "$#"

A: FWIW I'd approach this by figuring out the max number of records that you might need to search in based on the mappings you want, keep a rolling buffer of that number of records, and then do the comparison part on each buffer, e.g.:
$ cat tst.awk
BEGIN {
    RS = "[[:space:]]+"
    map("3,4"   , "&")
    map("6,7,8" , "9")
    map("9"     , "")
    map("0"     , "\\000")
    map("13,10" , "10")
}
{ buf[((NR-1) % maxRecs) + 1] = $0 }
NR >= maxRecs { prt() }
END { prt() }

function prt(   nr,sep,str) {
    for ( nr=NR-maxRecs+1; nr<=NR; nr++ ) {
        str = str sep buf[((nr-1) % maxRecs) + 1]
        sep = ORS
    }

    print ">>>>" ORS str ORS "<<<<"

    # Replace the above with something that loops through the
    # strings you want replaced, e.g.
    #
    # for ( mapNr=1; mapNr<=numMaps; mapNr++ ) {
    #     old = olds[mapNr]
    #     if ( str ~ old ) {    # add something to avoid partial matches
    #         new = news[mapNr]
    #         replace old with new in the output
    #     }
    # }
}

function map(old,new,   numRecs) {
    ++numMaps
    numRecs = gsub(/,/,ORS,old) + 1
    maxRecs = ( numRecs > maxRecs ? numRecs : maxRecs )
    olds[numMaps] = old
    news[numMaps] = new
}

$ awk -f tst.awk file
>>>>
112
3
4
<<<<
>>>>
3
4
6
<<<<
>>>>
4
6
7
<<<<
>>>>
6
7
8
<<<<
>>>>
7
8
9
<<<<
>>>>
8
9
12
<<<<
>>>>
9
12
0
<<<<
>>>>
12
0
3
<<<<
>>>>
0
3
4
<<<<
>>>>
3
4
15
<<<<
>>>>
4
15
255
<<<<
>>>>
15
255
13
<<<<
>>>>
255
13
10
<<<<
>>>>
13
10
6
<<<<
>>>>
10
6
7
<<<<
>>>>
6
7
8
<<<<
>>>>
7
8
199
<<<<
>>>>
8
199
9
<<<<
>>>>
199
9
0
<<<<
>>>>
9
0
13
<<<<
>>>>
9
0
13
<<<<

The above is just printing the buff-sized strings, the part to be added is replacing the target strings with the new ones in a way that the next target doesn't match the replaced part which is a common problem with, I expect, lots of solutions online so it's left as an exercise.
You'll also need to tweak it to make sure it doesn't revisit lines at the end of the input.
The above uses GNU awk for multi-char RS, if you don't have GNU awk then just pipe the input from tr -s '[:space:]' '\n' as shown in the question.

A: UPDATE:

*

*previous answer (see edit revisions) was woefully slow (several minutes) when run against a ramped up input (7K mappings in map.txt; 25M tokens
in input.txt1)

*new answer (below) is a complete rewrite and processes the 7K-mappings/25M-tokens in ~45 seconds

The main component of this design centers around a tree-like node structure used to manage the series of tokens (lines of input from map.txt):
tree [ParentNodeNbr] [token] [NodeType] = value

Where:

*

*ParentNodeNbr == 0 for the root

*token from map.txt

*NodeType has one of two values 'node' or 'leaf'

*for NodeType = 'node' the value stored in the array is a numeric node number (implemented as an counter that's incremented each time a new node is added to the tree); this node number becomes the ParentNodeNbr for the next token in the series

*for NodeType = 'leaf' this designates the 'end' of a series of tokens (line of input from map.txt) and the value stored in the array is the line number (aka FNR) from map.txt; this line number (FNR) is used as an index into a couple other arrays and to determine precendence when an input sequence (from input.txt) has multiple matches from map.txt

*when processing a series of tokens from a map.txt line of input we start at ParentNodeNbr == 0 looking for a series of matching nodes, adding new nodes as needed

Setup: storing replacements in a comma-delimited file (map.txt), and adding one additional line to input.txt:
$ head map.txt input.txt
==> map.txt <==
2 3 4,X                    # "2 3 4" has precendence over ...
2 3,Y                      # "2 3"
3 4,&
6 7 8,9
9,
0,\000
13 10,10

==> input.txt <==
2 3 4                      # keep eye on "2 3" vs "2 3 4" precendence
112 3
4 6 7
 8  9 12  0  3
4 15   255 13
10 6
7 8 199 9
0 13

NOTE: here's what tree[][][] looks like when populated from map.txt:
tree [Parent] [Token] [NodeType] = NodeVal

Parent   Token  NodeType   NodeVal     MapTo    ** MapTo only applies to NodeType = leaf
======   =====  ========   =======     =====
     0       0      leaf         6    "\000"
     0       2      node         1
     0       3      node         3
     0       6      node         4
     0       9      leaf         5        ""
     0      13      node         6
     1       3      node         2
     1       3      leaf         1       "Y"
     2       4      leaf         2       "X"
     3       4      leaf         3       "&"
     4       7      node         5
     5       8      leaf         4       "9"
     6      10      leaf         7      "10"

One GNU awk (for multidimensional arrrays):
awk '

function replace(op) {

    while ( ((maxToken - minToken + 1) >= maxlen) || op == "flush" ) {

          NodeNbr=root
          minOrd=maxOrd

          for (j=0 ; j<maxlen; j++) {                             # loop through tokens in buffer[]
              token=buffer[ ((minToken + j - 1) % maxlen) + 1 ]

              # if we find a matching "leaf" node then keep track of the ordering (ie, FNR from map.txt; lower order == higher precedence)

              if ( token in tree [NodeNbr] && "leaf" in tree[NodeNbr][token] )
                 minOrd= ( tree[NodeNbr][token]["leaf"] < minOrd ) ? tree[NodeNbr][token]["leaf"] : minOrd

              # if we find a matching "node" node then grab the next node to compare against the next token from buffer[]

              if ( token in tree[NodeNbr] && "node" in tree[NodeNbr][token] ) {
                 NodeNbr=tree[NodeNbr][token]["node"]
                 continue
              }

              break                                               # if we get here we have a token from buffer[] that does not match any of our replacement mappings so abort checking rest of buffer[]
          }

          if (minOrd < maxOrd) {                                  # if we found at least one complete match (ie, hit a "leaf" node) then ...
             print map[minOrd]                                    # use the associated "ord"er to print the associated replacement string and ...
             minToken=minToken + len[minOrd]                      # update the pointer into the buffer[] array
          }
          else {                                                  # otherwise we did not find a match so ...
             print buffer[ ((minToken - 1) % maxlen) + 1 ]        # print the first token from buffer[] and ...
             minToken++                                           # update the pointer into the buffer[] array
          }

          if (minToken > maxToken)
             break
    }
}

BEGIN   { root=maxNodeNbr=maxToken=0
          minToken=1
          maxOrd=9999999999
        }

FNR==NR { split($0,a,",")

          map[FNR]=a[2]                                           # save replacement string for this input line from map.txt

          n=split(a[1],b)                                         # break our matching pattern into tokens

          len[FNR]=n                                              # make note of number of tokens in this line of input
          maxlen=(n > maxlen) ? n : maxlen                        # keep track of longest series of tokens

          NodeNbr=root                                            # initiate our tree search

          for (i=1 ; i<=n ; i++) {                                # loop through our list of tokens
              token=b[i]

              if (i==n)                                           # if the last token for this line then create a "leaf" node and store the line number (aka "order")
                 tree[NodeNbr][token]["leaf"]=FNR
              else
              if ( tree[NodeNbr][token]["node"] )                 # else if we already have a node at this point in the tree then grab its associated node number for the next level in the tree
                 NodeNbr=tree[NodeNbr][token]["node"]
              else {                                              # else create a new "node" node and populate with the next available node number
                 tree[NodeNbr][token]["node"]=++maxNodeNbr
                 NodeNbr=maxNodeNbr                               # use this as the next level in our tree traversal
              }
          }

          maxrec=FNR                                              # keep track of total number of replacement sets from map.txt (only used if we decide to print the contents of map[] to stdout
          next
        }

FNR==1  {

          # Uncomment following to display the contents of the map[] array:

#          for (i=1;i<=maxrec;i++)
#              print "map:" i ":" map[i] ":"
#
          # Uncomment following to display the contents of the tree[][][] array:

#         fmt="%6s%8s%10s%10s%10s\n"
#         fmt="%6s%8s%10s%10s%10s\n"
#         printf "tree [Parent] [Token] [NodeType]\n\n"
#         printf fmt, "Parent", "Token", "NodeType", "NodeVal", "MapTo"
#         printf fmt, "======", "=====", "========", "=======", "====="
#
#          for (NodeNbr=root ; NodeNbr<=maxNodeNbr ; NodeNbr++)
#              for (token in tree[NodeNbr])
#                  for (NodeType in tree[NodeNbr][token]) {             # ??
#                      NodeVal=tree[NodeNbr][token][NodeType]
#                      printf fmt, NodeNbr, token, NodeType, NodeVal, (NodeType=="leaf") ? "\"" map[NodeVal] "\"" : ""
#                  }
        }

        { for (i=1 ; i<=NF ; i++) {                               # loop through tokens in current line from input.txt
              maxToken++
              buffer[ ((maxToken - 1) % maxlen) + 1 ] = $i
              if ( (maxToken - minToken + 1) >= maxlen )          # if we have a "full" buffer then ...
                  replace()                                       # look for replacement match
          }
        }

END     { replace("flush") }                                      # flush the rest of buffer[]
' map.txt input.txt

This generates:
X                          # "2 3 4" has precendence over "2 3"
112
&
9

12
\000
&
15
255
10
9
199

\000
13

If we switch the first 2 lines of map.txt like such:
==> map.txt <==
2 3,Y                      # "2 3" has precendence over ...
2 3 4,X                    # "2 3 4"

We now generate:
Y                          # "2 3" has precendence over "2 3 4" thus ...
4                          # leaving "4" by itself
112
&
9

12
\000
&
15
255
10
9
199

\000
13


text:
Q: app crashes on assert() I am sending an audio file with extension .m4a on the server using ftp protocol for that firstly I store this file into my document directory path. I got document directory path in my console as follows:
NSLog(@"filepath=%@",filePath);
assert([[NSFileManager defaultManager] fileExistsAtPath:filePath]);

at the assert() function my app crases I don't know what is the reason.
My console is as follows:
filepath=/Users/macmini2/Library/Application Support/iPhone Simulator/5.1/Applications/B2CFB7FF-A4BF-4B83-8DD1-102C5680C16C/Documents/9_39.m4a
Assertion failed: ([[NSFileManager defaultManager] fileExistsAtPath:filePath])

if you have any solution plz provide
thanx in advance...

A: It is highly likely that the file you are looking for is not there.
For a double check, enter:
ls "/Users/macmini2/Library/Application Support/iPhone Simulator/5.1/Applications/B2CFB7FF-A4BF-4B83-8DD1-102C5680C16C/Documents/9_39.m4a"

in a terminal window.
In case you get an error, please, review the way you build filePath.
How do you make the 9_39.m4a file available on your iPhone? Is it part of the app bundle? (Should you not then search for it in the Resources folder?)


text:
Q: Date format changed using seaborn pointplot When I use seaborn to draw a pointplot, the date on the x-axis changes to this strange format 2020-01-06T00:00:00.000000000. The dates from the 'Current Year Week Ending' column are converted to DateTime object before drawing this figure. My other graph (lineplot) uses similar inputs and format, but it doesn't have this issue, the dates are like 2020-01-06.
Does anyone know how to fix this problem?
*The total_us dataframe and sub dataframe I use in my plots are subsets of the same dataset. And I converted the date on that big dataset before creating those two subsets. So the value in 'Current Year Week Ending' column of total_us and sub should have the same DateTime format.
#create a pointplot to capture the variability
plt.figure(figsize = (8, 6))
sns.pointplot(x = 'Current Year Week Ending',
              y = 'ASP Current Year',
              hue ='Type',
              data = sub,
              markers=["o", "x"],
              linestyles=["-", "--"])
plt.xticks(rotation=45, horizontalalignment='right', fontweight='light', fontsize='medium')
plt.ticklabel_format(style='plain', axis='y')

#create a lineplot
plt.figure(figsize=(10,7))
sns.lineplot(x='Current Year Week Ending',
             y='Total Bulk and Bags Units',
             hue='Type',
             data = total_us);
plt.xticks(rotation=45, horizontalalignment='right', fontweight='light', fontsize='medium')
plt.ticklabel_format(style='plain', axis='y')

this is what sub looks like, so the values in 'Current Year Week Ending' column are like "2020-01-06". I don't know why it changes when I draw a pointplot.

A: I think your date column may just include these trailing zeros, and seaborn deals with it differently depending on how much room there is on the plot. So try the following for your date column:
sub.iloc[:,1] = sub.iloc[:,1].dt.strftime('Y/%m/%d')

If for some reason that doesn't fix the problem (perhaps seaborn point plots and line plots do something different under the hood), then a possible workaround would be to split the text 2020-01-06T00:00:00.000000000 at the letter 'T' and throw out the trailing zeros after. We can use the fact that sns.pointplot returns a matplotlib.Axes object (from the documentation), setting the variable ax equal to your point plot:
ax = sns.pointplot(x = 'Current Year Week Ending',
          y = 'ASP Current Year',
          hue ='Type',
          data = sub,
          markers=["o", "x"],
          linestyles=["-", "--"])
ax.set_xticklabels([date_text.get_text().split("T")[0] for date_text in ax.get_xticklabels()])


text:
Q: ThreeJS texture issue I have a problem with my Three.js 3D application - at least according to some people I know.
My application rests at [http://176.9.149.205/planungstool/]. Some people who supposedly have the most recent version of Chrome and Firefox, can not see the textured areas. For example, they do not see the roof or front of the 3D house. They do, however, see the non-textured stuff like the tree or the floor.
What's weird is that I don't have that problem and most of the other people I asked do not have it as well. Here is what it should look like and does look like for me: [http://176.9.149.205/planungstool/house.jpg]
Does anyone have an idea what could cause this? Could it be some client-side settings? Or maybe some access control policy?
I'm loading the textures like this:
var myTexture = new THREE.ImageUtils.loadTexture('gfx/textures/texture.jpg');

And then I just create meshes with lambert material that have this texture as their map.
If you read this and do not know what could cause this error, it would be nice if you could at least tell me if you see the textured areas or not, given you have a recent version of Chrome or Firefox.

A: I can see the textures on current chrome on mac. I had a similar problem with the canvas renderer (anything textured was invisible). For me I changed from using the ImageUtils.loadTexture to a texture and texture loader and it works.
var texture = new THREE.Texture();
var texLoader = new THREE.ImageLoader();
texLoader.addEventListener( 'load', function(event){
    texture.image = event.content;
    texture.needsUpdate = true;
} );
texLoader.load('texture.png');

I do however still have problems with a canvas renderer in safari but you appear to only be using the webgl renderer. Hope this helps.


text:
Q: Handling partial return from recv() TCP in C I've been reading through Beej's Guide to Network Programming to get a handle on TCP connections. In one of the samples the client code for a simple TCP stream client looks like:
if ((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) {
    perror("recv");
    exit(1);
}

buf[numbytes] = '\0';

printf("Client: received '%s'\n", buf);

close(sockfd);

I've set the buffer to be smaller than the total number of bytes that I'm sending. I'm not quite sure how I can get the other bytes. Do I have to loop over recv() until I receive '\0'?
*Note on the server side I'm also implementing his sendall() function, so it should actually be sending everything to the client.
See also 6.1. A Simple Stream Server in the guide.

A: Yes, you will need multiple recv() calls, until you have all data.
To know when that is, using the return status from recv() is no good - it only tells you how many bytes you have received, not how many bytes are available, as some may still be in transit.
It is better if the data you receive somehow encodes the length of the total data. Read as many data until you know what the length is, then read until you have received length data. To do that, various approaches are possible; the common one is to make a buffer large enough to hold all data once you know what the length is.
Another approach is to use fixed-size buffers, and always try to receive min(missing, bufsize), decreasing missing after each recv().

A: The first thing you need to learn when doing TCP/IP programming: 1 write/send call might take
several recv calls to receive, and several write/send calls might need just 1 recv call to receive. And anything in-between.
You'll need to loop until you have all data. The return value of recv() tells you how much data you received. If you simply want to receive all data on the TCP connection, you can loop until recv() returns 0 - provided that the other end closes the TCP connection when it is done sending.
If you're sending records/lines/packets/commands or something similar, you need to make your own protocol over TCP, which might be as simple as "commands are delimited with \n".
The simple way to read/parse such a command would be to read 1 byte at a time, building up a buffer with the received bytes and check for a \n byte every time. Reading 1 byte is extremely inefficient, so you should read larger chunks at a time.
Since TCP is stream oriented and does not provide record/message boundaries it becomes a bit more tricky - you'd
have to recv a piece of bytes, check in the received buffer for a \n byte, if it's there - append the bytes to previously received bytes and output that message. Then check the remainder of the buffer after the \n - which might contain another whole message or just the start of another message.

A: Yes, you have to loop over recv() until you receive '\0' or an
error happen (negative value from recv) or 0 from recv().
For the first option: only if this zero is part of your
protocol (the server sends it). However from your code it seems that
the zero is just to be able to use the buffer content as a
C-string (on the client side).
The check for a return value of 0 from recv:
this means that the connection was closed (it could be part
of your protocol that this happens.)


text:
Q: C - delete element from array and reorganise Given this array:
int a[] = {5, 8, 5, 6, 9, 5};

Would it be possible to remove all ints which equals 5 and move the rest the front of the array?
So that after the removal the array would look like this:
int a[] = {8, 6, 9, 0, 0, 0}

I don't know if by removing a element it becomes a 0 or a NULL?
Thanks!

A: You can do it with two iterations over the array, first iteration two to turn the element you want to delete, second iteration to separate zeros from non-zeros.
    int a[] = {5, 8, 5, 6, 9, 5};
    int n = 6;
    for(int i = 0 ; i < n ; i++ ) {
        if(a[i] == 5 ) {
            a[i] = 0;
        }
    }
    int* zero = a;

    int* nonZero = a;
    int j = 0;

    while(j < n) {

        while(*zero != 0) {
            zero++;
        }

        while(*nonZero == 0) {
            nonZero++;
            j++;
        }
        if(zero < nonZero) {
            *zero = *nonZero;
            *nonZero = 0;
        }
        j++;
    }

A: Your array is statically allocated, so always has the same size and deleted elements have the 0 value (according how you define the deleted values).
This link can help you and explains about how to delete element from array.

A: It is been awhile that i have programmed in C but it is posibble.
This is just a pseudo code, but you just need to change it to way of C programming.
int a[] = {5, 8, 5, 6, 9, 5};
int b[] = {5, 8, 5, 6, 9, 5}; // copy of array a to hold temp
for(int i = 0; i < Size of array; i++ ){
  for(int j = i; j < Size of array; j++ ){
    if(b[j] != 5){
       a[i] = b[j];
       a[j] = b[i];
       break;
    }
  }
}

It will be like (▼: Target to swap, F: Finished, X: Not a targe to swap, N: Not processed):
▼, ▼, N, N, N, N
5, 8, 5, 6, 9, 5
F, ▼, X, ▼, N, N
8, 5, 5, 6, 9, 5
F, F, ▼, X, ▼, N
8, 6, 5, 5, 9, 5
Result:
8, 6, 9, 5, 5, 5
And remove 5s, it is quite different depends what you mean. If you do not change size of array then they can be 0 or undefined(null). So I think it differs by how you program the function that returns array.

A: your array is not dynamic so you just can't reduce its size after its been allocated.setting the value zero might solve the problem in your case.


text:
Q: missing public key file in chalice I am working with Chalice Chalice (to write python rest api) and cashfree sdk Cashfree SDK (to transfer money).
I have a public_key.pem file which helps in maintaining a dynamic IP DYnamic Link Info.
I have been able to run this code in local ... But when I deploy this ..it says cannot find key.pem. I am unable to understand how should I pass my key file to it.
@app.route('/payment', methods=[ 'POST'])
def payment():
    json_input = app.current_request.json_body
    transferID = json_input["transferID"]
    amt = json_input["amt"]
    try:
        Payouts.init(clientId,
        clientSecret,
        env ,
        public_key_path="key.pem")
        try:
            request_transfer_response = Transfers.request_transfer(beneId="JOHN18012",
                                                       transferId=transferID,
                                                       transferMode="upi",
                                                       amount=amt)
        except Exception as e:
            return {"error1":str(e)}
    except Exception as e:
        return {"error2":str(e)}

    return json.loads(request_transfer_response.content)

A: So, as I was not able to pass the key file with chalice deploy. I added the key file to S3 bucket and called it in runtime to successfully execute my code.


text:
Q: Laravel custom validation message for multiple fields with the same name I have the following validation in the controller's action:
foreach ($request['qtys'] as $key => $val){
            if (!$this->_validateMinQty($key, $job, $val)){
                $customerTitle = $job->customers()->where('customer_id',$key)->first()->title;
                return redirect()->back()->withErrors(['qtys' => __('The qty of the customer :customerTitle is less than allowed qty',['customerTitle' => $customerTitle])]);
            }
        }

This check multiple form's input named qtys in the view:
@foreach($job->customers as $customer)

first('qtys has-error')}}">
        {!! Form::label('qtys-'.$customer->id, __('Qty').' '.$customer->title) !!}

                {!! Form::text('qtys['.$customer->id.']',$customer->pivot->e_production,['class' =>'form-control qtys', "data-sumequal"=>"qty",'required' => 'required','title' => $customer->pivot->aid,'id' => 'qtys-'.$customer->id]) !!}

                 @php ($eleE =  $errors->first('qtys'))
                @include('layouts.form-ele-error')

                pivot->aid}}" class="btn btn-nile">{{__('Add Storage')}}

    @endforeach

The above code works, but with the following limitation:
The error message is rendered under every input named qtys[x] where x is an integer and the first input only Testana has the invalid qty, like the following screen shot:

In the controller's action return message, I have tried to use indexed name for the input like the following:
return redirect()->back()->withErrors(['qtys.10' => ....

However, it prevents rendering the error message under any qtys field. Is there any solution?

A: The solution that I have found starts from the definition of first method found in the view :
@php ($eleE =  $errors->first('qtys'))

This, in my code, should be changed to:
@php ($eleE =  $errors->first('qtys.'.$customer->id))

Because the multiple fields have gotten keys equals to the customer id. This is a technique I usually use, when I want to send double piece of data in single post or in single form element.
Then in the controller, I keep the first try,
return redirect()->back()->withErrors(['qtys.'.$key => __('The qty of the customer :customerTitle is less than allowed qty',['customerTitle' => $customerTitle])]);

Where $key is an integer.


text:
Q: Gitlab CI variables and script section give different results I've searched a lot of examples but they did not work for me.
I'm trying to run linters for changed files when MR is opened.
My .gitlab-ci.yml
run_linters:
  image: python:3
  variables:
    FILES: git diff --name-only $CI_MERGE_REQUEST_TARGET_BRANCH_NAME | grep *.py
  before_script:
    - python3 -m pip install black==21.5b1
    - python3 -m pip install flake8==3.9.2
  script:
    - echo $FILES
    - git diff --name-only $CI_MERGE_REQUEST_TARGET_BRANCH_NAME | grep *.py
    - black --check $FILES
    - flake8 $FILES
  only:
    - merge_requests

And I'm getting strange output.
echo $FILES says git diff --name-only main | grep incoming_file.py
incoming_file.py is the only file in that MR. Why is it around grep?
And git diff at script section says fatal: ambiguous argument 'main': unknown revision or path not in the working tree.

*

*Why is filename present around grep?

*Why are same git diff commands give different result?

A:
Why is filename present around grep?

In bash when you refer to * this will expand and try to match the files/directories present in your current path, in your case since only the incoming_file.py is present, so it expands to this.

Why are same git diff commands give different result?

variables:
  FILES: git diff --name-only $CI_MERGE_REQUEST_TARGET_BRANCH_NAME | grep *.py

When you define a variable in variables section, Gitlab doesnt execute the command, it simple populates the variable FILES with the string git diff --name-only $CI_MERGE_REQUEST_TARGET_BRANCH_NAME | grep *.py
Then in the script section, the runner expands *.py to incoming_file.py and $CI_MERGE_REQUEST_TARGET_BRANCH_NAME to main
that's why in echo you see git diff --name-only main | grep incoming_file.py
Here
 - git diff --name-only $CI_MERGE_REQUEST_TARGET_BRANCH_NAME | grep *.py

You actually execute the command and you get the mentioned message


text:
Q: libgdx firing event from actor to call another actor I'm using Scene2D and have 2 actors. When MyActor1 is touched, it should fire an event which should be handled by MyActor2. I've tried several different variants on how to fire and even from MyActor1, but it is still not being handled by MyActor2. The full code is below.
Game class which just forwards to a Screen
public class MyGdxGame extends Game {
   @Override
   public void create() {
       setScreen(new MyGdxScreen());
   }
}

Screen class (empty methods ommited)
public class MyGdxScreen implements Screen {

   private Stage stage;

   @Override
   public void show() {
       stage = new Stage(new ScreenViewport());
       stage.addActor(new MyActor1());
       stage.addActor(new MyActor2());
       Gdx.input.setInputProcessor(stage);
   }

   @Override
   public void render(float delta) {
       Gdx.gl.glClearColor(1, 1, 1, 1);
       Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

       stage.act(delta);
       stage.draw();
   }

   @Override
   public void dispose() {
       stage.dispose();
   }
}

First Actor (fires custom event when touched)
public class MyActor1 extends Actor {

   private Texture image;

   public MyActor1() {
       this.image = new Texture("badlogic.jpg");

       setPosition(0, 0);
       setBounds(0, 0, image.getWidth(), image.getHeight());
       setTouchable(Touchable.enabled);

       addListener(new InputListener() {
           @Override
           public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
               Gdx.app.log("touched", "First actor touched!");
               MyActor1.this.fire(new ActorTouchedListener.ActorTouchedEvent());
               MyActor1.this.getParent().fire(new ActorTouchedListener.ActorTouchedEvent());
               return true;
           }
       });
   }

   @Override
   public void draw(Batch batch, float parentAlpha) {
       batch.draw(image, 0, 0, image.getWidth(), image.getHeight());
   }
}

Second Actor (should handle an Event fired by Actor1)
public class MyActor2 extends Actor {

   public MyActor2() {
       addListener(new ActorTouchedListener());
   }
}

Event listener
public class ActorTouchedListener implements EventListener {
   @Override
   public boolean handle(Event event) {
       if (event instanceof ActorTouchedEvent) {
           Gdx.app.log("fired", "Second actor got event!");
           return true;
       }
       return false;
   }

public static class ActorTouchedEvent extends Event {
     public ActorTouchedEvent() {
     }
   }
}

A: These two lines do nothing.
MyActor1.this.fire(new ActorTouchedListener.ActorTouchedEvent());
MyActor1.this.getParent().fire(new ActorTouchedListener.ActorTouchedEvent());

To call Actor from another Actor you should create instance of it.
public class MyActor1 extends Actor {

   private Texture image;
   private Actor actor2; // instance of MyActor2

   public MyActor1(actor2: Actor) {
       this.image = new Texture("badlogic.jpg");
       this.actor2 = actor2;

       setPosition(0, 0);
       setBounds(0, 0, image.getWidth(), image.getHeight());
       setTouchable(Touchable.enabled);

       addListener(new InputListener() {
           @Override
           public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
               Gdx.app.log("touched", "First actor touched!");
               actor2.fire(event);  // Here we fire event on MyActor2
               return true;
           }
       });
   }

   @Override
   public void draw(Batch batch, float parentAlpha) {
       batch.draw(image, 0, 0, image.getWidth(), image.getHeight());
   }
}

A: Intercomponent events
LibGDX does not provide embeded intercomponent event system, but you can use additional frameworks. For example LibGDX Autumn. You can use two type events:

*

*text event - to notify components about changing of some state

*object event - this mechanism deliver your event object to observers

This framework have documentaion and examples, it will help to do what you want
Delayed actor update
For actor's update purposes LibGDX have actions mechanism. In your case I suggest to attach DelayAction to MyActor2 with wrapped MyRedrawAction
DelayAction delayAction = new DelayAction();

// set wrapped action dellay (in sec.)
delayAction.setDuration(1F);
// set wrapped action. It will be invoked after 1 sec. of stage drawing
delayAction.setAction(new MyRedrawAction());

actor2.addAction(delayAction);

You can do this in touchDown() method as @icarumbas suggest


text:
Q: How to simulate events in certain time? I am trying to make simulation, and I have some events that happened durring a day. Some times it s for example few events durring half hour for one day, and sometimes we have event, and then few hours nothihg happened, and then other events and so on. My data set collect data in period of 5 months and I am using R Studio for distribution fitting. This time events I transformed in minutes
> fit.weibull <- fitdist(x, "weibull")
> summary(fit.weibull)
Fitting of the distribution ' weibull ' by maximum likelihood
Parameters :
        estimate Std. Error
shape   4.542143 0.04348223
scale 679.305556 2.10832072
Loglikelihood:  -36309.37   AIC:  72622.74   BIC:  72636.03
Correlation matrix:
          shape     scale
shape 1.0000000 0.3358675
scale 0.3358675 1.0000000

> y <- rweibull(5672, shape = 4.54, scale = 0.043)
> chisq.test(x,y)

    Pearson's Chi-squared test

data:  x and y
X-squared = 2887048, df = 2886539, p-value = 0.416

What I tryed is:

*

*with fitdist I fitted data to weibull dist

2.using model parameter I created new vector of data from weibull dist. with parameters
3.use chisq test compared this two datasets and P = 0.41
I know that inter arrival times are times between events (in my case minimum time between events is 1 minutes, and maximum time is 400 minutes). Should I try to model interarrival time no matter if this events are rare and dispersed durring a day, or mybee to try find (somehow) disttribution of event times.
I analysed times when events occur, and result is shown at the picture below.

I am observing this data "per day" basis.
Any idea or advice is wellcome, thank you
EDITED:

*

*I read that when I validate continious variable KS test is more appropriate since chi square is for discrete variables?

I shifted data, using
A <- (x - 400)

then remove all data lower then 0 , (only 3 values - extreme) where removed
x2 <- A[!A %in% -500:0]

then I decided to fit to lognormal
> f1<-fitdistr(x2, "lognormal")
> f1
    meanlog       sdlog
  4.34742821   0.64709906
 (0.02859801) (0.02022185)
> summary(f1)
         Length Class  Mode
estimate 2      -none- numeric
sd       2      -none- numeric
vcov     4      -none- numeric
n        1      -none- numeric
loglik   1      -none- numeric

and gamma
f2<-fitdistr(x2,"Gamma")

hist(x2,col="gray", breaks = 24, freq = FALSE)

with(as.list(coef(f1)),
      curve(dlnorm(x,meanlog,sdlog),
            add=TRUE,col="red",lwd=2))
with(as.list(coef(f2)),
      curve(dgamma(x,shape=shape,rate=rate),
            add=TRUE,col="blue",lwd=2))

and for weibull (since this is my first guess)
with(as.list(coef(f3)),
       curve(dweibull(x,shape=shape,scale = scale),
            add=TRUE,col="black",lwd=2))
>

this produce graph

As we can see best fit is lognormal. I generated dataset using fited parameters
trlnomrG <- rlnorm(512, meanlog = f1$estimate['meanlog'],
sdlog = f1$estimate['sdlog'])
hist(trlnomrG, breaks = 24, freq = FALSE)

and graph is

And at the end KS test.
> ks.test(x2, trlnomrG)

    Two-sample Kolmogorov-Smirnov test

data:  x2 and trlnomrG
D = 0.089844, p-value = 0.03208
alternative hypothesis: two-sided

and comparing this two dataset using T test
> t.test(x2, trlnomrG)

    Welch Two Sample t-test

data:  x2 and trlnomrG
t = 0.45766, df = 990.82, p-value = 0.6473
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -6.840123 11.000993
sample estimates:
mean of x mean of y
 97.00391  94.92347

So my final question is can I use lognormal distribution to generate those times, thx?


text:
Q: Call ajax on the frontend In my plugin folder I have two file 1. hello-ajax.php 2. myajax.js
and by shortcode I add this form on frontend
<form id="theForm" method="post">
 <input id="name" name="name" value = "name" type="text" />
 <input name="action" type="hidden" value="the_ajax_hook" />  <!-- this puts the action the_ajax_hook into the serialized form -->
 <input id="submit_button" value = "Click This" type="button" onClick="submit_me();" />
 </form>
 <div id="response_area">
 This is where we\'ll get the response
 </div>

In plugin file I added js file as:
wp_enqueue_script( 'my-ajax-handle', plugin_dir_url( __FILE__ ) . 'myajax.js', array( 'jquery' ) );
 wp_localize_script( 'my-ajax-handle', 'the_ajax_script', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
 // THE AJAX ADD ACTIONS
 add_action( 'wp_ajax_the_ajax_hook', 'the_action_function' );
 add_action( 'wp_ajax_nopriv_the_ajax_hook', 'the_action_function' ); // need this to serve non logged in users
 // THE FUNCTION
 function the_action_function(){
 /* this area is very simple but being serverside it affords the possibility of retreiving data from the server and passing it back to the javascript function */
 $name = $_POST['name'];
 echo"Hello World, " . $name;// this is passed back to the javascript function
 die();// wordpress may print out a spurious zero without this - can be particularly bad if using json
 }
 // ADD EG A FORM TO THE PAGE

So form is displaying at front end but in console Uncaught ReferenceError: submit_me is not defined
submit_me() is defined in myajax.js file as:

function submit_me(){
//alert(a);
jQuery.post(the_ajax_script.ajaxurl, jQuery("#theForm").serialize()
,
function(response_from_the_action_function){
jQuery("#response_area").html(response_from_the_action_function);
}
);
}

But this function is not working, and as far i know there is some problem in ajax call, so suggest me what did I wrong and how to make it work.

A: Most of your code looks ok to me. Is your script loaded? (Verify by viewing page source).  Per Milo's suggestion, this is how to properly enqueue your plugin's scripts:
// Enqueue your scripts
function load_my_scripts(){
     wp_enqueue_script( 'my-ajax-handle', plugin_dir_url( __FILE__ ) . 'myajax.js', array( 'jquery' ) );
     wp_localize_script( 'my-ajax-handle', 'the_ajax_script', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'load_my_scripts' );

I don't know if it is causing problems, but I would probably switch from using an onclick call and trigger the ajax via form submit.  Switching your JS file to the following:
jQuery(document).ready(function($){

    $('#theForm').submit(function(e){

        $.ajax({
            data: jQuery("#theForm").serialize(),
            type: 'post',
            url: the_ajax_script.ajaxurl,
            success: function(response_from_the_action_function) {
                $("#response_area").html(response_from_the_action_function);
            }
        });

    });

});

A: Just need to add
e.preventDefault();

after the $.ajax
Also need to remove from the form:
onClick="submit_me();"


text:
Q: Static files are not getting loaded in Django Static files are not getting loaded when running on server.  I have tried the whitenoise library and referred to the Documentation (http://whitenoise.evans.io/en/stable/django.html) as well, but no luck. I am new to Django, would appreciate any help.
PS: I have also collected the static folder using-
python manage.py collectstatic

Below is what I have in my settings.py
INSTALLED_APPS = [
    'whitenoise.runserver_nostatic',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_celery_beat',
    'django_extensions',
    'haystack',
    'users.apps.UsersConfig',
    'rest_framework',
    'rest_framework.authtoken',
    'django_db_logger.apps.DbLoggerAppConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

WSGI_APPLICATION = 'server.wsgi.application'

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")

A: If static files are loading when you run locally, but not on your server, you may need to add something to your web server config.  E.g. for nginx and your static folder location:
location /static/ {
    root /home/user/testing;
}

location /media/ {
    root /home/user/testing;
}

More details and an example for Apache at https://docs.djangoproject.com/en/4.1/howto/deployment/wsgi/modwsgi/#serving-files

A: you need to specify in Project/urls.py file
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
]

# For static file and media
if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL,
                          document_root=settings.STATIC_ROOT)

A: For example, if your STATIC_URL is defined as static/, you can do this by adding the following snippet to your urls.py:
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)


text:
Q: Comandos de junções (join) em SQL Tenho algumas duvidas a respeito dos comandos inner join, left join, right join e full join, não sei se é apenas o join que faz as junções entre as tabelas, porem junto com ele vem esses comandos, e não estou conseguindo entender a finalidade deles, alguém poderia me explicar como eles funciona e quando usá-los?

A: Para fins de exemplo, considere o esquema abaixo:

CROSS JOIN
Quando queremos juntar duas ou mais tabelas por cruzamento. Ou seja, para cada linha da tabela FUNCIONARIO queremos todos os CARGOS ou vice-versa.

INNER JOIN
Quando queremos juntar duas ou mais tabelas por coincidência. Para cada linha da tabela FUNCINARIO queremos o CARGO correspondente que internamente (INNER), em seus valores de atributos, coincidam. No caso de FUNIONÁRIO e CARGO os atributos internos coincidentes são codigoCargo na tabela CARGO e codigoCargo na tabela FUNCIONARIO. Para efetivarmos a junção das duas tabelas se fará necessário ligar (ON) as duas tabelas por seus atributos internos (INNER) coincidentes.

LEFT OUTER JOIN
Observando a tabela FUNCIONARIO suponhamos que o funcionário Tadeu não possui cargo associado a ele. Se desejarmos listar todos os funcionários com seus respectivos cargos, incluindo os funcionários sem cargos, poderíamos usar todo o poder da junção INNER JOIN adicionando ainda OUTER(EXTERNOS/OUTROS) Funcionários que não fazem parte do INNER JOIN, justamente àqueles sem cargos, como Tadeu. Podemos conseguir esse feito com a junção FUNCIONARIO/CARGO através da declaração FUNCIONARIO OUTER LEFT JOIN CARGO, que promove a junção interna (INNER) de todos os funcionários a cargos e lista ainda outros (EXTERNOS/OUTER) não associados.
Uma observação importante é que a ordem da ligação (ON) não faz diferença, ou seja:
"ON (F.codCargo = C.codCargo)" é exatamente igual a "ON (C.codCargo = F.codCargo)"

RIGHT OUTER JOIN
Observando a tabela CARGO suponhamos que o cargo GERENTE, com código C3, não é referenciado/associado por/a nenhum funcionário na tabela FUNCIONARIO. Se desejarmos listar todos os CARGOS e seus respectivos FUNCIONARIOS, incluindo os CARGOS sem FUNCIONÁRIOS, poderíamos usar a junção RIGTH OUTER JOIN.

OUTER FULL JOIN
Aqui juntamos o poder das junções (JOIN) internas(INNER), a listagem de todas as outras linhas não associadas, tanto do lado direito (RIGHT) da junção como do lado ESQUEDO (LEFT).

@referência

A: Dener, todos fazem junções das tabelas com algumas diferenças:
Quando você utiliza o INNER JOIN com duas tabelas por exemplo,
tabela usuario e tabela cargo o, INNER join cria um conjunto de interseção como na matemática, como na imagem abaixo, o INNER JOIN traz todos os cargos relacionados por ids 4 e 5 da tabela de cargo que contem na tabela de usuário e ignora os demais, como no conjunto A e B.
SELECT * FROM usuario A INNER JOIN cargo B on B.id = A.id_cargo

Já o LEFT JOIN cria um conjunto de relação entre as duas tabelas, porem da seguinte diferença:
SELECT * FROM usuario A LEFT JOIN cargo  B A.id_cargo =  B.id

Na consulta acima terá preferência a tabela especificada na esquerda usuário, então terá como resultado os usuários que possuem cargo e os usuários que não possuem cargo e o RIGHT JOIN faz o oposto disso, o ful JOIN faz a união entre as tabelas.


text:
Q: Fourier series of iterated sin / Diagonalization of an infinite matrix of Bessel functions We define the iterated sine function as : $$ \sin^n(x) = \sin(\sin(.... \sin(x)))\:\:n\:\text{times.} $$
We know the "Frequency Modulation" formula based on Bessel functions :$$ \sin( p\, \sin(x) ) = \sum_{k=1, \,odd}^{\infty} 2 \, J_k(p) \, \sin( k \,x) \qquad, J_k(p) : \text{Bessel function of the first kind}$$
if we write the different harmonics of $\sin^n$ as an (infinite) vector over the $\sin(x), \sin(3x), \sin(5x),...$ base, we have:
$$ [\sin^n] = 2^{(n-1)} \begin{bmatrix} J_1(1) & J_1( 3) & \cdots & J_1(col)& \cdots \\
J_3(1) & J_3( 3) & \cdots & J_3(col)& \cdots\\
\vdots & \vdots & \vdots & \ddots\\
J_{line}(1) & J_{line}( 3) & \cdots &J_{line}(col)& \cdots\\
\vdots& \vdots& \vdots& \vdots& \ddots
\end{bmatrix}^{(n-1)} . \begin{bmatrix} 1 \\0 \\ 0 \\ \vdots\end{bmatrix}$$
which gives already excellent approximations of $ \sin^n$:
$$ \sin^{(2)}(x) = 0.8773 \sin(x) + 0.0411 \sin(3x) +0.0005 \sin(5x)+...$$
$$ \sin^{(^1/_2)}(x) = 1.0945 \sin(x) - 0.00392 \sin(3x) + 0.0056 \sin(5x)+...$$
and shows that most of the energy stays in the first 2 harmonics. It even "finds": $$ \sin^0(x) = \sum_{k=1, \,odd}^{\infty} \frac{4}{k^2 \pi} \sin( k \pi / 2) \sin(kx) \qquad \text{(sawtooth wave)} $$
Questions:

*

*How to stabilize the diagonalization of this "Bessel Matrix" : practically it works well, but eigenvalues / vectors vary wildly when dimensions change. Is there a way to "order" the eigen values so the diagonalization process somehow converges ?

*Do I have a way to get an approximation of the coefficient of $\sin(x)$(resp $\sin(3x) $ etc. as a function of n ? Numerical approximation gives  $\sin^n(x) = [0.67 \cdot 0.98^n + 0.34 \cdot 0.757^n ] \sin(x) + [0.12 \cdot 0.98^n - 0.10 \cdot 0.757^n - 0.17 \cdot 0.282^n ] \sin(3 x)+...$ but this seems very dependent upon the dimension used during diagonalization.

*How can I choose the dimension to "cap" the error on the iterate sin to a certain level, etc.

Anyway for me the best way to compute the iterated sin with only a few terms ... converges very fast over $\mathbb{R}$ and applicable also to iterated cos !

A: About question 1), stabilizing the eigenvalues of diagonalization for changing dimensions.
Just to make this better visible, I show two pictures, where the sets of eigenvalues for dimensions $N \in \{4,8,16,32,64,128\}$ are shown.
The indexes are rescaled to the interval $0..1$. The modification of the sets of eigenvalues seems nicely tamed instead of chaotic to me:

Even more tamed, if the x-axis is logarithmically scaled:

Perhaps from the second picture one can formulate a guess-function.


text:
Q: How to Transpose table in redshift? Is there some better way, to transpose a table in redshift, other than taking it out in Pandas and getting things done.

A: You can try using below query. But the below query would be helpful, if the number of rows per group is a constant value
SELECT col1,
       Split_part(col_values, ',', 1) col_value1,
       Split_part(col_values, ',', 2) col_value2,
       Split_part(col_values, ',', 3) col_value3
FROM  (SELECT col1,
              Listagg(col2, ',')
                within GROUP (ORDER BY col2) col_values
       FROM   (SELECT col1,
                      col2
               FROM   table1) derived_table1
       GROUP  BY col1) derived_table2

Note: The above query will be used if you have same number of rows per group or if you know the maximum number of rows per group.

A: Transposing data in SQL is never a fun task. However if the data does fit in memory in pandas this package might make the process smoother.
https://github.com/agawronski/pandas_redshift
An example of how to do this is as follows:
pip install pandas-redshift
import pandas_redshift as pr

# Provide your redshift credentials and connect to redshift
pr.connect_to_redshift(dbname = <dbname>,
                        host = <host>,
                        port = <port>,
                        user = <user>,
                        password = <password>)

# This next step reads the data from redshift to your python session
data = pr.redshift_to_pandas('select * from gawronski.nba_shots_log')

# Transpose the DataFrame
data_transposed = data.transpose()

# Provide S3 credentials
# (data goes to S3 then redshift so an S3 bucket is necessary)
pr.connect_to_s3(aws_access_key_id = <aws_access_key_id>,
                aws_secret_access_key = <aws_secret_access_key>,
                bucket = 'my-bucket-name',
                # this is and optional parameter:
                subdirectory = 'subdirectory-in-the-bucket')

# Write the transposed DataFrame back to redshift
pr.pandas_to_redshift(data_frame = data_transposed,
             redshift_table_name = 'public.my_transposed_table'

Edit: Updated to avoid providing a link only answer.


text:
Q: Magento 2 : Error While Preview Email Template From Admin Getting this error while preview newly created sales email template. Admin panel => Marketing => Email Templates - magento 2.1.1
Error filtering template: Warning: Missing argument 1 for Magento\Framework\View\Element\Template::setTemplate() in vendor/magento/framework/View/Element/Template.php on line 187

A: vendor/magento/module-sales/view/frontend/email/order_new.html:
<!--@vars {
"var formattedBillingAddress|raw":"Billing Address",
"var order.getEmailCustomerNote()":"Email Order Note",
"var order.increment_id":"Order Id",
"layout handle=\"sales_email_order_items\" order=$order area=\"frontend\"":"Order Items Grid",
"var payment_html|raw":"Payment Details",
"var formattedShippingAddress|raw":"Shipping Address",
"var order.getShippingDescription()":"Shipping Description"
"var shipping_msg":"Shipping message"
} @-->

There is a trailing comma missing after "Shipping Description"
This issue also exists in the order_new_guest.html
more info


text:
Q: How can I ensure my keypress isn't handled before a new element is loaded? I have a child element which focuses the appropriate element within itself on its Loaded event.  We're finding that some quick fingered testers are able to hit the keypress to open the element, and the next keypress goes to the parent instead of the newly focused container!  So the keypress is beating whatever async process WPF runs in order to load the child control.
The target in both the parent and child controls is a simple text box.
Is there a guaranteed way to ensure this doesn't happen?


text:
Q: TestDome Data Science: Not getting correct answer I tried to answer this question from TestDome and got 250877.19298245612 instead of 250000 as suggested. Please let me what went wrong. Thanks
import numpy as np
from sklearn import linear_model

class MarketingCosts:

    # param marketing_expenditure list. Expenditure for each previous campaign.
    # param units_sold list. The number of units sold for each previous campaign.
    # param desired_units_sold int. Target number of units to sell in the new campaign.
    # returns float. Required amount of money to be invested.
    @staticmethod
    def desired_marketing_expenditure(marketing_expenditure, units_sold, desired_units_sold):
        X = [[i] for i in units_sold]
        reg = linear_model.LinearRegression()
        reg.fit(X, marketing_expenditure)
        return float(reg.predict(desired_units_sold))

#For example, with the parameters below the function should return 250000.0.
print(MarketingCosts.desired_marketing_expenditure(
    [300000, 200000, 400000, 300000, 100000],
    [60000, 50000, 90000, 80000, 30000],
    60000))

A: I think this is the solution because we search to predict X from y, and the label in this problem is units_sold.
import numpy as np
from sklearn import linear_model

class MarketingCosts:

    # param marketing_expenditure list. Expenditure for each previous campaign.
    # param units_sold list. The number of units sold for each previous campaign.
    # param desired_units_sold int. Target number of units to sell in the new campaign.
    # returns float. Required amount of money to be invested.
    @staticmethod
    def desired_marketing_expenditure(marketing_expenditure, units_sold, desired_units_sold):
        marketing_expenditure = marketing_expenditure.reshape(-1, 1)
        units_sold = units_sold.reshape(-1, 1)
        reg = linear_model.LinearRegression()
        reg.fit(marketing_expenditure , units_sold)
        return (desired_units_sold - reg.intercept_)/reg.coef_

#For example, with the parameters below the function should return 250000.0.
print(MarketingCosts.desired_marketing_expenditure(
    [300000, 200000, 400000, 300000, 100000],
    [60000, 50000, 90000, 80000, 30000],
    60000))

A: import numpy as np
from sklearn import linear_model

class MarketingCosts:

    # param marketing_expenditure list. Expenditure for each previous campaign.
    # param units_sold list. The number of units sold for each previous campaign.
    # param desired_units_sold int. Target number of units to sell in the new campaign.
    # returns float. Required amount of money to be invested.
    @staticmethod
    def desired_marketing_expenditure(marketing_expenditure, units_sold, desired_units_sold):
        marketing_expenditure = np.asarray(marketing_expenditure).reshape(-1, 1)
        units_sold = np.asarray(units_sold).reshape(-1, 1)
        reg = linear_model.LinearRegression()
        reg.fit(marketing_expenditure , units_sold)
        return np.float((desired_units_sold - reg.intercept_)/reg.coef_)

#For example, with the parameters below the function should return 250000.0.
print(MarketingCosts.desired_marketing_expenditure(
    [300000, 200000, 400000, 300000, 100000],
    [60000, 50000, 90000, 80000, 30000],
    60000))

A: I had the same issue, I was rounding to solve the first test case and thus failing the second... This is a small sample, single variable regression so actually it looks like you can't use vanilla regression, but Theil-Sen regression. I checked the result and it comes to 250000.00003619, which you then just round.
Source:
https://gist.github.com/mfakbar/f97949299171c75e868a37f3f578fa54
import numpy as np
from sklearn import linear_model

class MarketingCosts:

    # param marketing_expenditure list. Expenditure for each previous campaign.
    # param units_sold list. The number of units sold for each previous campaign.
    # param desired_units_sold int. Target number of units to sell in the new campaign.
    # returns float. Required amount of money to be invested.
    @staticmethod
    def desired_marketing_expenditure(marketing_expenditure, units_sold, desired_units_sold):
        y, x = np.array(marketing_expenditure), np.array(units_sold).reshape(-1, 1)
        regressor = linear_model.TheilSenRegressor(max_subpopulation=10)
        regressor.fit(x, y)
        desired_units_sold = np.array([desired_units_sold]).reshape(-1, 1)
        return float(round(regressor.predict(desired_units_sold).item()))

# For example, with the parameters below the function should return 250000.0.
print(MarketingCosts.desired_marketing_expenditure(
    [300000, 200000, 400000, 300000, 100000],
    [60000, 50000, 90000, 80000, 30000],
    60000))

A: Here is my answer which passes all tests:
import numpy as np
from sklearn.linear_model import LinearRegression

def desired_marketing_expenditure(marketing_expenditure, units_sold, desired_units_sold):

    x = np.array(marketing_expenditure).reshape(-1, 1)
    y = np.array(units_sold).reshape(-1, 1)
    model = LinearRegression()
    model.fit(x , y)

    return (desired_units_sold - model.intercept_)/model.coef_

A: here is my answer that passes all testcases
You can find simple steps to perform a linear regression here
import numpy as np
from sklearn.linear_model import LinearRegression

def desired_marketing_expenditure(marketing_expenditure, units_sold, desired_units_sold):
    s_x = sum(marketing_expenditure)
    s_y = sum(units_sold)
    xy = []
    for i in range (len(marketing_expenditure)):
        z= marketing_expenditure[i]*units_sold[i]
        xy.append(z)
    s_xy = sum(xy)
    sq_x = [number ** 2 for number in marketing_expenditure]
    s_sq_x = sum(sq_x)
    sq_y = [number ** 2 for number in units_sold]
    s_sq_y = sum(sq_y)

    # calculating coefficients a and b for liner regression
    a=((s_y*s_sq_x) - (s_x*s_xy))/(len(marketing_expenditure)*s_sq_x - (s_x**2))
    b=(len(marketing_expenditure)*s_xy - (s_x*s_y)) /
       (len(marketing_expenditure)*s_sq_x - (s_x**2))
    return (desired_units_sold-a)/b

#For example, with the parameters below, the function should return 250000.0
print(desired_marketing_expenditure(
    [300000, 200000, 400000, 300000, 100000],
    [60000, 50000, 90000, 80000, 30000],
    60000))


text:
Q: Load a Java Charset explicitly, dynamically This is not a repeat of Loading a Java Charset manually.  I want to do the same thing, but without using META-INF.  Is it possible?  Is a general solution for various service types?
In this specific case, I need to process utf-7 data, using a CharsetProvider like JUTF7.  In addition to adding the jar to the classpath, this requires adding a file to META-INF/services, where the file name is java.nio.charset.spi.CharsetProvider and the contents identifies jutf7.  However, it is not possible to use META-INF in this case.  Is there a workaround?

A: No, it is not possible to register a new CharSet, other than by implementing a CharSetProvider, and it can only be registered thru META-INF/services. See the javadoc.
However, that doesn't mean that you have to provide that file for jutf7. The jutf7 jar file already has the necessary service file. As the page you linked says: Just drop the jar in your classpath, and you are ready to go.


text:
Q: HP ENVY 14 SPECTRE Notebook memory upgrade I'm planning to upgrade my memory and found Mac Memory 8GB 1600MHz DDR3 SODIMM RAM For Apple iMac MacBook Mac Pro
is it compatible for
HP ENVY 14 SPECTRE Notebook PC
Serial Number: 5CD2165QTR
According to this site I can use
www.crucial.com/usa/en/envy-14-3100eg-spectre/CT4005352
Crucial 8GB DDR3L-1600 SODIMM CT4005352 | ENVY 14-3100eg SPECTRE

A: Your system is a HP ENVY 14-3015tu SPECTRE supports only DDR3 1333MHz memory.
http://www.memorystock.com/memory/HewlettPackardENVY143015tuSPECTRE.html


text:
Q: Usability issues for first-time Stack Exchange users - a micro-study I come from lands afar, also known as Hardware Recommendations Stack Exchange. Over there, we have a serious problem with first-time Stack Exchange users coming along and asking off-topic questions - to the extent that 50% of incoming questions are closed. We've had a few attempts at solving this, but none have really worked.
So, this afternoon, I got together a group of people who had never seen Stack Exchange before. I gave them each a question (on various topics, each intended for a different site in the network), and asked them to find the most appropriate site to ask it, noting down the troubles they had along the way.
(They were all terrible questions, though the topic was clear. I did ask them not to actually post, but, by happy chance, the one who actually did demonstrated my issue perfectly.)
This post is a list of their most common problems with the sites as first-time users.
Help! How do I start?
People didn't start reading from the top bar. When they landed on a Stack Exchange site, the most common behaviour was:

*

*read the site title

*read the banner, be confused by it (more on that later)

*read question titles

After that, actions start diversifying. The point is, they don't see the topbar. Which, in turn, means they don't see the help link. Of 20 participants, only one ever saw a help center - and that wasn't by getting there from the topbar link. The topbar help link fails its purpose.
It's Free! Now sign up.
When you're a first-time user, your view of a site has a dismissible banner across the top giving you a 30-second introduction to the site:

That seems helpful enough, until you read the wording for the first time and notice this:

It's 100% free, no registration required.
Sign up

It's not technically incorrect or in any way wrong, but it reads very strangely for a first-time user. "You don't need to register - click me to register!"
Why can't I answer?
Okay, my test group weren't meant to be posting answers. Still, they identified this as another weird thing. Having just read that banner, and seeing "anyone can post an answer", the next thing many of them did was click on a question to see if its topic matched their question. When they scrolled down to read the answers, there weren't any, and they discovered that they couldn't post an answer either.
"What? But it said anyone could post an answer - how am I meant to do that?"
Of course, the question they're looking at has been closed. This raises several points:

*

*they didn't notice [on hold] in the title (or didn't place any significance on it)

*they scrolled past the close message

*there was no way to tell why they couldn't answer

When they did notice the close reason, it was generally fairly good at explaining what had happened, so that much is working. Perhaps we just need to emphasise the reason, and add a note to the bottom of the page in place of the answer controls explaining why the controls aren't present.
Hot Network Questions - what?
HNQ was one of the most confusing features mentioned. On a page full of questions about gardening, looking at the sidebar and seeing questions about Star Wars and Windows 10 next to each other confused my test group. Some sample reactions:

*

*Aren't those questions off topic here?

*What's the network?

*What's Hot?

*Why are they here with the gardening questions?

Ah, so I ask here. Or do I?
Many sites' scopes are not immediately obvious. That's not a bad thing, it's just a product of the system that a site can't take absolutely all questions about one topic. However, it seems that we do need to make sure the guidance is available.
On the Ask Question page (/questions/ask), there's an info box on the right-hand side of the page. Some sites have customised this with a custom message; others use the default.
A customised message (Hardware Recommendations):

The standard message (Open Source):

In both cases, my test group didn't notice, or didn't fully read this information until after they'd typed their question into the box.
At that point, if the guidance makes the question they've just typed off-topic, the majority reaction was "but I've already typed it out... they won't mind, right?". Clearly, that's not the reaction we want. If this guidance could be moved to the left hand side of the page, in consistency with most people's reading direction of left-to-right, I think more people would read the guidance before posting an off-topic question.

I've got a small table of results, which shows the site I intended the question for, the site the user decided to post on, the time it took them to reach a decision (hh:mm) and whether the question was on-topic at their decided site.

Intended
Decision
TTD
On Topic?

SU
HR
00:12
n

HR
HR
00:08
y

SO
SO
00:03
y

Progs
SQA
00:20
n?

Workplace
Workplace
00:19
y?

SF
SO
00:05
n

Gardening
Gardening
00:15
y

ELL
EL&U
00:10
y?

CS
TCS
00:12
shrug

Apple
Apple
00:07
y

SF&F
Movies
00:25
y?

Bicycles
Bicycles
00:09
y

Aviation
Aviation
00:11
y

Security
Progs
00:07
n?

Physics
Physics
00:06
y

Homebrew
Beer
00:17
n

Writers
WB
00:13
n

DBA
SO
00:15
y?

Crypt
Security
00:08
y?

Biology
Biology
00:06
y

So that's the results of my mini-research study on Stack Exchange. No doubt there are some obvious and some less obvious solutions to each of these points; if we could consider doing some of these things we'd make the sites a lot friendlier to first-time users. As a side benefit, we'd also give them more guidance, potentially reducing off-topic questions on some sites. So - can we make SE more friendly to first-timers?

A: Good job! This is awesome. There's a lot of useful observations here, but here are a few I'd highlight specifically:
The default copy in the hero is kinda goofy. It has that, "No charge - EVER. Enter your credit card below!" vibe. This actually got fixed on SO:

Normally, weird copy getting updated would get pushed to all sites, assuming it makes sense, but in this case, it was discovered in the context of some SO-specific A/B tests, so that didn't happen. We'll work on fixing that ASAP.
The absence of an "answer" button on closed questions is bad UX. It's happening more on HR due to the higher close rate, but it's sub-optimal anywhere: Sometimes a button isn't where the user expects it to be, and the only signal for why (that the question is closed) is off-screen, plus it requires you to know something most people won't intuit (that closed questions won't accept new answers).  I personally hadn't seen that raised before. It's slightly more work - requires some minor design thought on whether to grey out a button, what copy to use, etc.  But I think it's low cost to benefit - we'll look at adding something there.
The "ask question" page (and sidebar guidance specifically) aren't really great at helping new users be successful. I think your points here are dead-on, and this one needs more work than what you've described. At some point not-too-far-off, I'd like to see us put some real work into more of a "guided" version of how to ask, with more structured fields ("What did you want to happen?", "What was the actual result", etc.), and some guidance for each that's not easy to miss.  I also like enderland's Pre-fill question-box with text for new users (A/B study proposal), or something similar. This needs a bit more time available to kickoff, but I really want to see if we can't devote some focus to this page before this year's up.

A: I love your idea to move the infobox and while at it, I would extend the idea. After the user entered the question's name, the system already do a lookup with the question name on the site in question, but if the lookup would find more result on another site, could the system display a hotlink direct there in the infobox, like "Is this question could fit on sitename instead ?"
To prevent too much load, it could do a simple search on site that tend to overlaps (like for me on SF, it could be on SO & SU)


text:
Q: Enable Audit Logs using Cloud Deployment Manager GCP I am trying to enable Audit Logs i.e. Data Access Logs using Cloud Deployment Manager in GCP but I am getting some error, below is the script I have created in YAML.
resources:
- name: get-iam-policy
  action: gcp-types/cloudresourcemanager-v1:cloudresourcemanager.projects.getIamPolicy
  properties:
    resource: <project_id>
  metadata:
    runtimePolicy:
    - 'UPDATE_ALWAYS'
- name: patch-iam-policy
  action: gcp-types/cloudresourcemanager-v1:cloudresourcemanager.projects.setIamPolicy
  properties:
    resource: <project_id>
    policy:
      etag: $(ref.get-iam-policy.etag)
      auditConfigs:
      - auditLogConfigs:
        - logType: ADMIN_READ
        service: allServices

Above code is stored in file deploy.yaml and below command is used to create the deployment
gcloud deployment-manager deployments create test --config deploy.yaml

I am getting error below
(gcloud.deployment-manager.deployments.create) Error in Operation [operation-1621334235876-5c2984b310ba1-9e1e602f-d982565d]: errors:
- code: RESOURCE_ERROR
location: /deployments/test/resources/patch-iam-policy
message: '{"ResourceType":"gcp-types/cloudresourcemanager-v1:cloudresourcemanager.projects.setIamPolicy","ResourceErrorCode":"400","ResourceErrorMessage":{"code":400,"message":"Invalid
JSON payload received. Unknown name \"auditConfigs\": Cannot find field.","status":"INVALID_ARGUMENT","details":[{"@type":"type.googleapis.com/google.rpc.BadRequest","fieldViolations":[{"description":"Invalid
JSON payload received. Unknown name \"auditConfigs\": Cannot find field."}]}],"statusMessage":"Bad
Request","requestPath":"https://cloudresourcemanager.googleapis.com/v1/projects/******:setIamPolicy","httpMethod":"POST"}}'

A: I did some trying on this example and looked up some documentation for this.
Your code seems correct, and all yaml syntax validators say the same.
After I try to deploy your code I get exactly the same error message as you.
This looks like it may be a bug so I would recomment raising an issuge on Google IssueTracker.


text:
Q: KeyError on Generator So close, and yet so far.
I'm not sure what happened but a generator script that was working for me has suddenly started throwing KeyErrors. I am assigning properties to networkx nodes according to a category I am giving each node.
Each node looks like this...
539943797.0: {'category': 'perimeter'}

and I define the sizes with a variable like this...
node_sizes = {'core':500, 'perimeter':50}

and the actual node draw code looks like this, with the generator in place...
nx.draw_networkx_nodes(G, graph_pos,
                       node_size=[node_sizes[G.node[node]['category']]for node in G],
                       alpha=node_alpha,
                       node_color=[node_colors[G.node[node]['category']]for node in G])

The problem is, the above generator code (which was working not so long ago) gives me a KeyError:'category' error when I run it.
However, calling this...
node_sizes[G.node[539943797.0]['category']]

gets me the value of 50, as I would expect; pulling the category from 539943797.0 as 'perimeter' and the size for that is 50. So far so good. I'm not sure what I'm doing wrong here. I was hoping another few sets of eyes on this could give me a better idea.
I suspect I'm doing something wrong in how I calling the category, or setting it
(I set it here...)
for node in graph[1]:
    G.add_node(node)
    G.node[node]['category'] = 'perimeter'

If I need to put up more of the code to be better understood I'll try and trim things up and put it out here. Hopefully I've supplied enough.
thanks,

A: In your comment you say this started happening after you started adding edges.  I think that's where the problem is.  You'll get this error if even one node doesn't have the 'category' defined.  I think adding edges is resulting in the addition of a few nodes that don't have category defined.  The first test is to just go through
for node in G.nodes():
    if not G.node[node].has_key('category'):
        print node

right before where you get your error.
I bet that you'll see that most of your nodes are okay, but a few aren't.
If I have the code
import networkx as nx
G=nx.Graph()
G.add_node(1)
G.node[1]['category'] = 'perimeter'
for node in G.nodes():
    if not G.node[node].has_key('category'):
        print node

I get no output.  All (1) of the nodes has 'category' defined.
However, if I then try
G.add_edge(1,2)

for node in G.nodes():
    if not G.node[node].has_key('category'):
        print node

It outputs

2

This is because it when I added the edge, networkx saw a node that wasn't in G yet.  It assumes you want to add the node too.  So now you've added a new node 2, but it doesn't know that it should be defining 'category' as well.  So it doesn't.
From what you've described this is almost certainly what is happening.  To check this, before adding any edge you can check whether the two nodes are in the graph already.  Or, if your code adds a huge number of edges at once, just check whether G.order() is the same before and after.  Once you figure out why it's doing this, presumably you can decide what you want to do with those nodes.
If this doesn't find something that's an issue, then you'll need to post more code, so that we have something that reproduces your error.


text:
Q: MSTest /noisolation fails tests If I use MSTest with the parameter /noisolation my tests fail, but without it they pass.
If I run MSTest without the parameter for the first time a ms office configuration box appears and configures something because my tests depend on excel. this happens only the first time. then the test runs trough without problems.
but if I run my test with the parameter the box doesn't appear and tests fail.


text:
Q: Getting inkscape attribute with d3 I need to extract inkscape label attribute for a group node in a SVG file created with Inkscape:
SVG:
<g id="g123" inkscape:label="group 1">...</g>

Code:
d3.select("#g123").attr("inkscape:label"); // return null

Register inkscape namespace does not work either:
d3.ns.prefix.inkscape = "http://www.inkscape.org/namespaces/inkscape";
d3.select("#g123").attr("inkscape:label"); // return null

Even though this works:
d3.select("#g123").node().getAttribute("inkscape:label")

What am I doing wrong here?

A: Try this:
d3.select("#g123").node().getAttribute(":inkscape:label")

Read this posts to see why: 1 and 2.


text:
Q: Session being set but session data not being passed I have a session issue. for some reason, the session is being set, but the session data is not being passed. I check the session path and that's all correct. Below there's a login handler and then the session checks once a user is logged in.
I var_dumped the session and got nothing, but var_dumped the session_id() on both scripts and got the same session id, indicating that the session is being made, but for some reason not being passed.
Thanks for any help.
login_handler.php
<?php
session_name("tradesman");
session_start();
include '../includes/con.inc.php';

$errors = 0;
$email_address = $_POST['tradesman_email'];
$password = $_POST['tradesman_password'];
$remember_me = $_POST['tradesman_remember_me'];

    $login_check = $dbh->prepare("SELECT * FROM tradesman WHERE email_address = :email_address");

    $login_check->bindParam(':email_address', $email_address);

    $login_check->execute();

    if($login_check->rowCount() === 1){

    }else{
       $response["message"] = 'denied';
       $errors++;
    }

if($login_check->rowCount() === 1){

    while($row = $login_check->fetch()) {

            $db_password = $row['password'];
            $tradesman_id = $row['tradesman_id'];
            $trade_name = $row['trade_name'];
            $email_address = $row['email_address'];

        if (password_verify($password, $db_password)) {

            $update_key = $dbh->prepare("UPDATE tradesman SET token=:token WHERE tradesman_id=:tradesman_id");

                 $update_key->bindParam(':token', $token);
                 $update_key->bindParam(':tradesman_id', $tradesman_id);

            if($update_key->execute()){

            $token = sha1(microtime());
            $_SESSION['trade_name'] = $row['trade_name'];
            $_SESSION['tradesman_id'] = $row['tradesman_id'];
            $_SESSION['token'] = $token;

            $response["message"] = 'tradesman_login_success';
            }else{
            $response["message"] = 'denied';
            $errors++;
            }

        } else {

           $response["message"] = 'denied';
           $errors++;

        }
    }
}

echo json_encode($response);
exit();

?>

account.php - after login (session check only)
<?php
session_name("tradesman");
session_start();

 print_r($_SESSION['token']);
 print_r($_SESSION['tradesman_id']);
 print_r($_SESSION['trade_name']);

require_once 'includes/con.inc.php';

$session_key = $_SESSION['token'];

$check_user = $dbh->prepare("SELECT * FROM tradesman WHERE token =:session_key LIMIT 1");

$check_user->bindParam(':session_key', $session_key, PDO::PARAM_STR);

if($check_user->execute()) {
       $check_user->setFetchMode(PDO::FETCH_ASSOC);
    }

      if($check_user->execute()){

        if($check_user->rowCount() === 1){

     while($row = $check_user->fetch()) {

        $tradesman_id = $row['tradesman_id'];

      }

        }else{

          header('Location:index.php');
          exit();

        }

      }else{
          header('Location:index.php');
          exit();
      }
?>

A: The problem seems to be in your first script:
        ...
        $update_key = $dbh->prepare("UPDATE tradesman SET token=:token WHERE tradesman_id=:tradesman_id");

        // Here you bind the $token variable to the placeholder
        $update_key->bindParam(':token', $token);
        $update_key->bindParam(':tradesman_id', $tradesman_id);

        // Here you execute the query, $token is not defined yet
        if($update_key->execute()){

            // Here you set the token, it will not be available in the database
            $token = sha1(microtime());
            $_SESSION['trade_name'] = $row['trade_name'];
            $_SESSION['tradesman_id'] = $row['tradesman_id'];
            $_SESSION['token'] = $token;
            ...

You set the token in the database before you define it so you are setting an empty value in your database.
First define the token, then store it in the database and the session.
As you are binding parameters, moving it to before the if statement should do it:
...
$token = sha1(microtime());
if($update_key->execute()){
    ...


text:
Q: Why outer product isn't backward stable Outter product isn't backward stable. This is because output matrix most likely has rank one and thus can't be represented in the form $(x + \delta x)(y + \delta y)^*.$ Also we know that if output dimension more then input one then a problem is rarely backward stable. In this case $m + n > m n,$ given $m, n > 1.$
Question is why we can't represent matrix in the way pointed above? I can't find detailed proof. Thanks.
EDIT. So, let's start from the def. Algo is backward stable if
$$\tilde{f}(x) = f(\tilde{x}), \exists \tilde{x}, \|\tilde{x} - x\| = \|x\| \times O(\epsilon_{machine}) .$$
Consider single element of resultant matrix:
LHS is $\tilde{f}(x_i y_j) = \mbox{fl}(x_i)\otimes\mbox{fl}(y_j) = [x_i(1 + \epsilon_1) \times y_j(1 + \epsilon_1)](1 + \epsilon_2).$
RHS is $f(\tilde{x_i} \tilde{y_j}) = \mbox{fl}(x_i)\times\mbox{fl}(y_j) = x_i(1 + \epsilon_1) \times y_j(1 + \epsilon_1).$
So, what is the problem with rank one?

A: Ok, i've figured it out.
The thing is that it is exteremely unlikely for $\tilde{A}$ be of rank one, because every $\otimes$ introduces small error, e.g. $\frac{ \mbox{fl}(x_i)\otimes \mbox{fl}(y_j) }{ \mbox{fl}(x_i)\otimes \mbox{fl}(y_{j+1}) } \ne \frac{y_j}{y_{j+1}} $, so $(j+1)$-column no more multiple of $j$-column.


text:
Q: Laravel 5.1 Format date BEFORE being put in array inside controller I have the following code in my controller:
$gecko_id = Gecko::where(compact('user_id', 'name'))->first()->id;
$weight = Weight::where(compact('user_id', 'gecko_id'))->orderBy('weighed_date', 'desc')->take(7)->get()->reverse();
$gecko = Gecko::where(compact('user_id', 'name'))->first();

return view('gecko.show')
    ->with('gecko', $gecko)
    ->with('dates', $weight->lists('weighed_date'))
    ->with('amounts', $weight->lists('gecko_weight'));

Which is sending data to my view for a chart i'm plotting. My dates list is outputting the following data format:
["2015-06-01","2015-05-01","2015-04-01","2015-03-01","2015-02-01","2015-01-01"]

Ideally I would like to format this before it is passed to the view so it's more readable. So say 2015-06-01 would be be reformatted into 01/06/2016 - I know how to do this in the usual PHP way, but because I'm putting the data into an array, I'm unsure on the best way of achieving my goal.

A: You can archive this by writing an accessor in your model. Accessors & Mutators.
For example:
class Weight extends Model{
    ...
    public function getWeighedDateAttribute($value){
        return Carbon\Carbon::parse($value)->format('d/m/y');
    }
    ...
}


text:
Q: Divide if different than 0 I often have this kind of statement in my code :
(b != 0) ? a / b : a

In terms of speed and best C++ pratice, is it better to do a function
float divifnotzero(a,b) { ... return ... }

or a preprocessor macro like this ?
#define divifnotzero(a,b) ((b!=0)?a/b:a)

A: The pre-processor is just going to replace the code wherever you use the macro, so there is no difference there. As for a function, your compiler will almost certainly inline it, so again there should be no difference in speed. So, given that I would go with a function for readability.

A: Preprocessor macros inline any code you put in them. A function call allows you to reduce the size of the executable at the expense of some slight overhead. Based solely on that, in this instance you would want to use a preprocessor macro.
In practice, functions can be inlined just like preprocessor macros with the inline keyword, which gets rid of the overhead. The compiler can generally decide on whether or not to inline a function itself; one like this would almost certainly have that happen. Go for the function call, unless you're specifically compiling the program without optimizations while still valuing speed.


text:
Q: Regex match multiple lines before and after word delimited by start and end words I am wanting to search for {{ upc }} and start the capture not from the <div immediately ahead of the match but the 2nd <div ahead of the match i.e.
 and capture not up to the first
 after the match but the 2nd i.e closing
 or up to the start of the next
 (depending on how you look at it)
Here is the sample HTML/Twig template I am wanting to search and replace.

    {{ entry_sku }}

        <input type="text" name="sku" value="{{ sku }}" placeholder="{{ entry_sku }}" id="input-sku" class="form-control"/>

     {{ entry_upc }}

         <input type="text" name="upc" value="{{ upc }}" placeholder="{{ entry_upc }}" id="input-upc" class="form-control"/>

     {{ entry_ean }}

         <input type="text" name="ean" value="{{ ean }}" placeholder="{{ entry_ean }}" id="input-ean" class="form-control"/>

The expected regex match is as follows:

     {{ entry_upc }}

         <input type="text" name="upc" value="{{ upc }}" placeholder="{{ entry_upc }}" id="input-upc" class="form-control"/>

All help appreciated. Thank you.

A: You need to parse the div's you want and then absorb everything inside them and exclude the rest.
[\w\W] means match words and non-words. It matches newline characters for instance, which * does not.
[\w\W]*(<div[\w\W]*?<div[\w\W]*?{{ sku }}[\w\W]*?<\/div>[\w\W]*?<\/div>)[\w\W]*

A: One thing you can try is to use a negative lookahead to filter out the things you do not wish to be included in your match.  For instance, matching a <div, followed by anything and then another <div, can match things like

.
Instead, what you can say is to match <div, followed by anything - as long as it is not
 - and then another <div.
<div    (?:(?!
).)*    <div

Then, you can insert that same subpattern anywhere in your expression where you'd normally write .*.  In this particular case, you can repeat that to make sure you're not hitting a closing div before the UPC and then continue with the {{ UPC }} portion.
<div(?:(?!
).)*<div    (?:(?!
).)*    {{ upc }}    .*?
\s*

Here is a demo


text:
Q: Is it possible to find a file with specific text using the dev console or IntelliJ search? This would be useful, starting at another company with a new project.
It seems the dev console will show the HTML, not the source file.
In IntelliJ, I have tried the double shift search, and CTRL-shift+F.
If there is a Git equivalent, I'll try it too.
Thanks in advance.


text:
Q: default timeout for JAX-WS client We are calling web service for which using cxf-codegen-plugin for code generation from WSDL and have configured JAX-WS client in Spring xml as follows:
<jaxws:client id="abcApiInterface" serviceClass="abc.api.AbcApi" address="${xyz.abcApi.endpoint}" />

And we have our webservice interface generated by Apache CXF 3.0.3. We are seeing timed-out when calling that service, we have not specified any timeout on client side so just want to know what's the default value for timeout for JAX-WS client?

A: Default value is 30 seconds for connection timeout and 60 seconds for receive timeout.
See: http://cxf.apache.org/docs/client-http-transport-including-ssl-support.html#ClientHTTPTransport(includingSSLsupport)-Theclientelement