text:
Q: Optimize Network Graph creation I have the following code that goes through a matrix of 188k x 188k rows of data and attempts to create a network graph out of it. The problem here is my algorithm is extremely slow (as expected since its quadratic). Is there a better way of doing this that I'm not seeing? I'm already thinking of using openMP to parallelize this but would be great if I don't have to.
Here's whats true about my matrix - its symmetric, its over 188 thousand by 188 thousand, each value in the matrix corresponds to the edge weight So for example, an element aij is the weight of the edge between i and j. Here's my code:
The graph creation:
typedef boost::adjacency_list
<
boost::vecS,
boost::vecS,
boost::undirectedS,
boost::property<boost::vertex_name_t, std::string>,
boost::property<boost::edge_weight_t, float>,
boost::property<boost::graph_name_t, std::string>
> UGraph;

typedef UGraph::vertex_descriptor vertex_t;
typedef UGraph::edge_descriptor edge_t;

Now the function creating the network:
    vertex_t u;
    vertex_t v;
    edge_t e;

    bool found=0;
    int idx =0;

    float cos_similarity;
    for(int p =1;p<=adj_matrix.cols();p++){

            //using a previously created vector to track already created nodes
            if(std::find(created_nodes.begin(), created_nodes.end(), nodes[idx]) == created_nodes.end()){
                    u = add_vertex(nodes[idx], ug);
                    created_nodes.push_back(nodes[idx]);
            }else{
                    u = vertex(p,ug);
            }
            int jdx = 0;

            for(int q =1;q<=adj_matrix.cols();q++){

                    if(p!=q){//NO LOOPS IN THIS GRAPH
                            //using a previously created vector to track already created nodes
                            if(std::find(created_nodes.begin(), created_nodes.end(), nodes[jdx]) == created_nodes.end()){
                            v = add_vertex(nodes[jdx], ug);
                    created_nodes.push_back(nodes[jdx]);
                            }else{
                                    u = vertex(q,ug);
                            }

                            tie(e, found) = edge(u, v, ug);

                            if(!found){//check that edge does not already exist
                                    cos_similarity = adj_matrix(p,q);
                                    fil<<cos_similarity<<endl;
                                    fil.flush();
                                    if(cos_similarity >= 0.2609){ //only add edge if value of cell is greater than this threshold
                                            boost::add_edge(u,v,cos_similarity, ug);
                                            edge_out<<p<<" "<<q<<" "<<cos_similarity<<endl; //creating an edge-weight list for later use
                                    }
                            }
                    }
                    jdx++;
            }
            idx++;
    }

A: A simple tip:

*

*I think your algorithm is cubic rather than quadratic, because vector and std::find(vector.begin(), vector.end()) are used to avoid duplicates in the inside loop.

*To avoid duplicates and keep the algorithm quadraic, you can just traverse the upper triangle of the matrix as it's symmetric, which means the graph is an undirected graph.


text:
Q: 'DIRS': [os.path.join(BASE_DIR, 'myfolder', 'templates'),], NameError: name 'os' is not defined - Django I have installed python3, pip3 and created virtualenv for my project and then installed django. I have installed needed packages and when I am trying to run this command in terminal
./manage.py syncdb --settings=myfolder.settings.local
I get this error
'DIRS': [os.path.join(BASE_DIR, 'myfolder', 'templates'),], NameError: name 'os' is not defined

I have read some comments to add import os in top of my setting.py file an to add BASE_DIR = os.path.dirname(os.path.abspath(__file__))
I have that already in my settings file but still I'm getting same error.
How can I solve it?

A: You have to import os.path in your settings.py file, where you have your templates settings.
import os
...

TEMPLATES = [
{
    'DIR':[os.path.join(BASE_DIR, 'templates_folder_name')],
    ...
}]

A: IN NEW VERSION YOU JUST TYPE A TEMPLATE FOLDER NAME IN DIR
'DIRS': ['templates']

A: The quick fix is to import os at the top of your settings.py file
# settings.py
import os # new
from pathlib import Path

A: I had been obtaining the same error so I just replaced 'DIRS': [os.path.join(BASE_DIR, 'myfolder', 'templates'),], with 'DIR': ['templates'] and it worked.
You can also solve this error by just writing import os right after the path import line.

A: in django version 3.1 . You have to import os at your setting.py file
Otherwise you can install Django version below 3.0
# settings.py
import os

redpajama_set_name: RedPajamaStackExchange


text:
Q: Use Sql server column alias in where condition I am writing a sql server query with one column as a expression like
Select name , name + age as Test from myTable
where Test like '%b%';

Now i cannot use Test either i need to write
Select name , name + age as Test from myTable
where (name + age) like '%b%';

Now the expression (name + age) can be very big sometimes so cant i give it some alias and use it
Any help is appreciated,
Thank You

A: How about this way..
select name, Test
(
Select name , (name + age) as Test from myTable
) t
where Test like '%b%'

The query needs to be modified as it has syntax error:
So it should be written like
select name from
(
Select name , (name + age) as Test from myTable
) t
where Test like '%b%'

A: You can use cross apply like this
select M.name , T.Test
from myTable as M
  cross apply(select name + age) as T(Test)
where T.Test like '%b%';


text:
Q: Inputting string using (gets.chomp) and producing a histogram I'm having struggles understanding ruby. I wish to have a program in which a user can input a set of text and it come back with asterisks. So far I was able to do it via a .txt file. Can anyone explain where I went wrong? I am struggling with ruby a lot.
Image of outcome when I run it
print "Please enter any length of text:"
user_input = String(gets.chomp)
h = Hash.new
f = user_input
f.each_line { |line|
  letters = line.split(//)
  letters.each { |w|
    if h.has_key?(w)
      h[w] = h[w] + 1
    else
      h[w] = 1
    end
  }
}

# sort the hash by
h.sort{|a,b| a[1]<=>b[1]}.each { |elem|
  puts "\"#{elem[0]}\": " + '*' * elem[1]
}

Error message I encountered
Undefined method `chomp' for nil:NilClass (NoMethodError)

A: In the script runner of Atom where you are currently running your Ruby program, you can not read from standard input using gets. It appears that the script-runner package can extend this to provide a real terminal to the script where you can then also use STDIN.
Alternatively, you could also run your program from a real console. For that, you have run it from a command line window, e.g. with ruby name_of_program.rb instead of starting it from Atom.

A: The gets method must be called alone. Try it in your second line:
user_input = gets.chomp

without String.
I hope it useful for you. :)

A: Your code is working as intended. You went wrong by running the code in your text editor instead of through the console. The Kernal#gets method requires user input, which would need to be mocked in order to run within your text-editor. Because your editor is returning nil instead of user input in string format, the chomp method is raising your NoMethodError.
Essentially your code is fine, but your are trying to run it in a limited environment. As a beginner, if your code requires user input, it's easier to test the code by running your ruby file through the console/terminal with ruby <filename.rb>.


text:
Q: how to keep specific element of array always in the middle? php I've following php that generates the array of languages:
<?php
/**
 * Language chooser for qtranslate-x plugin
 *
 * @package
 */

function get_language_list() {

    if ( function_exists( 'qtranxf_getSortedLanguages' ) ) {

        global $q_config;

        $list = array();
        foreach ( qtranxf_getSortedLanguages() as $key => $language ) {
            $list[] = array(
                'url' => qtranxf_convertURL( '', $language, false, true),
                'lan' => $q_config['language_name'][ $language ],
                'cur' => $language == $q_config['language'] ? 'current' : '',
            );
        }

        return $list;
    }

}

Its great, but I need to rewrite this array in a way that element which has 'cur' == 'current' is always in the middle e.g. key is 1.
array has 3 elements. dump looks like this:
array(3) {
  [0]=>
  array(3) {
    ["url"]=>
    string(24) ".dev/en/"
    ["lan"]=>
    string(7) "English"
    ["cur"]=>
    string(0) ""
  }
  [1]=>
  array(3) {
    ["url"]=>
    string(24) ".dev/ka/"
    ["lan"]=>
    string(21) "ქართული"
    ["cur"]=>
    string(0) ""
  }
  [2]=>
  array(3) {
    ["url"]=>
    string(24) ".dev/ru/"
    ["lan"]=>
    string(14) "Русский"
    ["cur"]=>
    string(7) "current"
  }
}

note, issue is that this order comes at random, and only rule is that current one should always be in the middle.

A: I would say :
1) search the current and remove it from the array
2) then re-insert it in the middle of the array
$current = array_splice($list,
    array_search('current', array_column($list, 'cur')), 1);
array_splice($list, round(count($list)/2), 0, $current);

A: as suggested by @flynorc
/**
 * Language chooser for qtranslate-x plugin
 *
 * @package marcopolo
 */

function get_language_list() {

    if ( function_exists( 'qtranxf_getSortedLanguages' ) ) {

        global $q_config;

        $list = array();
        foreach ( qtranxf_getSortedLanguages() as $key => $language ) {
            if ( $language == $q_config['language'] ) {
                $cur = true;
                $cur_key = $key;
            } else {
                $cur = false;
            }
            $list[ $key ] = array(
                'url' => qtranxf_convertURL( '', $language, false, true),
                'lan' => $q_config['language_name'][ $language ],
                'cur' => $cur,
            );
        }

        $middle = $list[1];
        $list[1] = $list[ $cur_key ];
        $list[ $cur_key ] = $middle;

        return $list;
    }

}


text:
Q: select all string between single quotes using vim I have the following text:
select region_id, 'Males_Negative_Nil_income_Age_15_19_years' as category, Males_Negative_Nil_income_Age_15_19_years as number from income_mf_pivot
union
select region_id, 'Males_Negative_Nil_income_Age_20_24_years' as category, Males_Negative_Nil_income_Age_20_24_years as number from income_mf_pivot
union
select region_id, 'Males_Negative_Nil_income_Age_25_34_years' as category, Males_Negative_Nil_income_Age_25_34_years as number from income_mf_pivot
union
select region_id, 'Males_Negative_Nil_income_Age_35_44_years' as category, Males_Negative_Nil_income_Age_35_44_years as number from income_mf_pivot

What I would like to finish up with (I presume via a selection) is
Males_Negative_Nil_income_Age_15_19_years,
Males_Negative_Nil_income_Age_20_24_years,
Males_Negative_Nil_income_Age_25_34_years,
Males_Negative_Nil_income_Age_35_44_years

I thought it would be something like /g to do the selection (using it to select everything between the two '), then somehow yank that, but I have run out of steam.
I am not a vim purist.  I don't mind if it is more than one command.  I am after this to be able to be run on a whole document.

A: You could place the cursor on the first M, then start block visual mode with CTRL-v, move to the other end of what you want to yank with 6je and yank it with y.
This does yank the empty lines though, but they should be easy to get rid of once pasted.
Another way, which would also append the commas is to use an external filter like sed:
:r!sed -n "s/.*'\(Males[^']*\).*/\1,/p" %

This results in
Males_Negative_Nil_income_Age_15_19_years,
Males_Negative_Nil_income_Age_20_24_years,
Males_Negative_Nil_income_Age_25_34_years,
Males_Negative_Nil_income_Age_35_44_years,

A: The yi' command allows to you yank the text between the single quotes, but that only works for a single instance at a time.
As long as the width is identical (i.e. you have a rectangular selection), you can use blockwise visual mode, started with <C-v> (often <C-q> on Windows).
To get all text within single quotes, you can use my ExtractMatches plugin. It provides the following command:
:%YankMatchesToReg /'\zs[^']\+\ze'/

After that, you can just paste the text and add the trailing commas. If all matches should be in one single line, the g,p from my UnconditionalPaste plugin can do that in one swoop.

A: I will assume that there are exactly two single quotes in each target line, as in your example text.
I would select the desired lines in Visual mode, then enter Ex mode with :.  The range `'<,'>' (representing the Visual selection) will be inserted automatically.  I would complete that to
:'<,'>v/'.*'/d

(remove all lines that do not contain two ' characters) to get rid of the "union" lines.  Then gv: to re-select the Visual selection, and complete the command line to
:'<,'>s/^[^']*'\|'.*//g
:'<,'>-s/$/,

or maybe, instead of those two commands,
:'<,'>s/.*'\(.*\)'.*/\1,

and then remove the , from the last line.

A: To select
Males_Negative_Nil_income_Age_15_19_years

from
select region_id, 'Males_Negative_Nil_income_Age_15_19_years' as category, Males_Negative_Nil_income_Age_15_19_years as number from income_mf_pivot

Use vi' (select inner single quotes)
Do :help object-select to read about it


text:
Q: SQLMembershipProvider source code compatability with latest mvc I got the source code from here
http://weblogs.asp.net/scottgu/archive/2006/04/13/442772.aspx
is it compatible with latest ASP.net MVC 3?

A: The default ASP.Net MVC (including versions 1, 2 and 3) site templates can use Membership Providers including SQLMembershipProvider.
Configuration is via the same methods for standard ASP.Net applications.


text:
Q: Multiple Polymer Paper-Listbox in a Page I'd like to have a form with multiple Polymer list boxes in it.
<paper-listbox selected="0">
<paper-item>Item 1</paper-item>
<paper-item>Item 2</paper-item>
<paper-item>Item 3</paper-item>
</paper-listbox>

<paper-listbox selected="0">
<paper-item>Item A</paper-item>
<paper-item>Item B</paper-item>
<paper-item>Item C</paper-item>
</paper-listbox>

When I do this, I am only able to select one item in both lists. How do I enable selection one from each list?

A: You most likely would have use same variable in the selected={{myVariable}} attribute in both the listboxes. You can use different variables in different listbox selected={{myVariableOne}} for the first listbox and selected={{myVariableTwo}} for the second listbox.
Checkout the plunker: http://plnkr.co/edit/AR4HGIGPTPWmgwv6M2jF


text:
Q: EF Core DbContext in Azure Functions with Repository I've an Azure Function App with multiple Azure functions and EF Core 6.
In the Startup.cs I add the repository with AddScoped and pass the connectionString.
class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        string connectionString = Environment.GetEnvironmentVariable("SqlConnectionString");
        builder.Services.AddScoped<SQLRepository>(x => ActivatorUtilities.CreateInstance<SQLRepository>(x, connectionString));
    }
}

The repository itself create the dbContext and initiate the migration.
public class SQLRepository
{
    private readonly MyDBContext _context;

    public SQLRepository(String connectionString)
    {
        var options = new DbContextOptionsBuilder<MyDBContext>().UseSqlServer(connectionString).Options;
        _context = new MyDBContext(options);
        _context.Database.Migrate();
    }
}

But since the Configure in Startup is called twice (once for each Azure function) the second time the repository is created, I get the error, the object __EFMigrationsHistory exists. Maybe, because the first migration is still in progress as the second try is started.
Is there a way to prevent this? Or do I have to perform the migration in an extra Azure function that is only called on start once?

A: Inspired by EF Core Migrations in Azure Function startup I use a custom IWebJobsStartup and perform the migration there and not in the SQLRepository itself.


text:
Q: Bounding generics in Java Good day, I have trouble with understanding a bounding generics in Java. I readed Oracle article about this and write simple code, but he work conversely and i not understand why.
Why can not I pass a Float type when putting a restriction on the Number type and its subtypes, even though it is inherited from Number, and when I put the border on the type and its superclasses, then I can pass the type Float, even though Double is not superclass for Number.
// Work
List<? super Number> gen1 = new ArrayList<>();
gen.add(3.14);

// Not work
List<? extends Number> gen = new ArrayList<>();
gen.add(3.14);


text:
Q: Unable to find Directory name I wanted to get directory name from path, but it returns the following error :

The directory name is invalid

the following are example path:

strFilePathName = C:\inetpub\wwwroot\PSSWeb\foldername\xxx.ini

the following code I use to get Directoryname based on prefix PSS and its should return PSSWeb. I'm unable find solution for this.
var directories = Directory.GetDirectories(strFilePathName,
                                           "PSS?",
                                           SearchOption.AllDirectories);

A: the path name you have specified "C:\inetpub\wwwroot\PSSWeb\foldername\xxx.ini" is not a directory but a file.
    //
    // Summary:
    //     Returns the names of the subdirectories (including their paths) that match the
    //     specified search pattern in the specified directory, and optionally searches
    //     subdirectories.
    //
    // Parameters:
    //   path:
    //     The relative or absolute path to the directory to search. This string is not
    //     case-sensitive.
    //
    //   searchPattern:
    //     The search string to match against the names of subdirectories in path. This
    //     parameter can contain a combination of valid literal and wildcard characters
    //     (see Remarks), but doesn't support regular expressions.
    //
    //   searchOption:
    //     One of the enumeration values that specifies whether the search operation should
    //     include all subdirectories or only the current directory.
    //
    // Returns:
    //     An array of the full names (including paths) of the subdirectories that match
    //     the specified criteria, or an empty array if no directories are found.
    //
    // Exceptions:
    //   T:System.ArgumentException:
    //     path is a zero-length string, contains only white space, or contains one or more
    //     invalid characters. You can query for invalid characters by using the System.IO.Path.GetInvalidPathChars
    //     method.-or- searchPattern does not contain a valid pattern.
    //
    //   T:System.ArgumentNullException:
    //     path or searchPattern is null.
    //
    //   T:System.ArgumentOutOfRangeException:
    //     searchOption is not a valid System.IO.SearchOption value.
    //
    //   T:System.UnauthorizedAccessException:
    //     The caller does not have the required permission.
    //
    //   T:System.IO.PathTooLongException:
    //     The specified path, file name, or both exceed the system-defined maximum length.
    //     For example, on Windows-based platforms, paths must be less than 248 characters
    //     and file names must be less than 260 characters.
    //
    //   T:System.IO.IOException:
    //     path is a file name.
    //
    //   T:System.IO.DirectoryNotFoundException:
    //     The specified path is invalid (for example, it is on an unmapped drive).
    public static string[] GetDirectories(string path, string searchPattern, SearchOption searchOption);

thats the documentation  of the method. It is mentioned that the first parameter must be a directory.

A: Finally i got the result as i wanted with using quite different method from above , which is  as following :
string strFilePathName = "C:\inetpub\wwwroot\PSSWeb\foldername\xxx.in";
string x = Path.GetDirectoryName(strFilePathName);
DirectoryInfo dir = new DirectoryInfo(@x);
DirectoryInfo OneLevelsUp = dir.Parent;

the Result i got PSSWeb folder name from the path C:\inetpub\wwwroot\PSSWeb\foldername\xxx.ini.
To get two level folder name
if anyone want to get two level up you may try following line ,
just change to
 DirectoryInfo OneLevelsUp = dir.Parent
 DirectoryInfo TwoLevelsUp = dir.Parent.Parent

it will return wwwroot folder name according to the path mentioned above


text:
Q: Exposing redis to external clients We are building a system that runs on our cloud and that needs information from our clients network that must not be exposed openly. We have concluded that the only way this could work, is if our clients can install an agent in their network, that would gather the required information and push it to our system through the internet.
This agent application, cannot communicate to our server using a regular RestAPI or webservice, because we have use cases that require us requesting specific information to the specific agent instances (a request to resync data from client 1 should only go to client 1's agent). We looked into gRPC streams and keep a stream open with every agent and just routes those requests to the stream, but since our backend has multiple instances, it would be hard to identify and reuse a single stream from different instances.
Then something that works for us, is using Redis streams and create a stream per agent, then our backend would only have to write to the specific agent redis stream (it would know the name of the stream as it would the agent/client identifier) from whichever of our instances.
The concern though, is the "over the internet" part.
Redis has TLS support since version 6, allows us to block certain commands (flushall for example) and supports defining users with access to only specific commands and keys/streams...
I understand exposing Redis over the internet or to any other network that not the one serving redis itself, has always been discouraged (AWS ElastiCache only allows access from within the same VPC/subnet for example). However, everything I find about redis security, say something in the lines of:

Do not publicly expose the Redis server
Since Redis has no default authentication, it does not support encryption. All data is stored in cleartext. An attacker can use FLUSHALL command to delete all key-value data sets...
Source

That type of statement holds very true to older versions of Redis that didn't provide TLS nor access control. But since those are now supported since version 6, am I crazy to go forward with this?
There's a concern about rate limiting, which is probably something that is not addressed by Redis itself, but that we can possibly find a solution with Kubernetes or network configuration in the cloud.
So, I know this is an unusual architecture and I am not the only one to think about it, but  I am just looking for your opinions on whether exposing Redis streams over the internet for my use case, considering the features that Redis now has, is that much of a security risk/ bad idea overall.

A: Exposing Redis to the Internet as a whole is generally a bad idea (as their documentation says).
However, exposing Redis over the Internet to specific trusted IP addresses is much less dangerous, especially if you have strong TLS encryption and strong authentication enforced. This should be done at the network/firewall level, rather than in Redis itself. If you can use client-certifiate authentication (also known as mutual TLS) rather than a username/password that would be even better.
Alternatively, would it be possible to send the Redis traffic over a VPN, to avoid exposing the service directly.
In this case, in order to exploit it an attacker would need to compromise one of the trusted IP addresses belonging to your clients, and then exploit either a Redis vulnerability or a set of stolen credentials.
It's still not an ideal architecture, but the real-world risk is likely to be relatively low.


text:
Q: Understanding the spectral measure of unbounded self-adjoint operator Let $\mathcal{H}$ be a Hilbert space and
$$\Delta: D(\Delta) \rightarrow \mathcal{H}$$
a (unbounded) self-adjoint operator, densely defined on $D(\Delta) \subset \mathcal{H}$. Denote by $\mu^{\Delta}$ the spectral measure of $\Delta$. For a Borel set $E \subset \mathbb{R}$, the spectral subspace $V_E$ of $\mathcal{H}$ may be defined as
$$
V_E = Range(\mu^{\Delta}(E)).
$$
Let $(\lambda_n)_n$ be a real-valued sequence such that $\lambda_n \rightarrow \infty$ for $n \rightarrow \infty$. Define
$$
V_n := V_{(-\lambda_n, + \lambda_n)}
$$
and let $P_n$ be the orthogonal projection onto $V_n$ for $n \in \mathbb{N}$.
The question is: Does $\Delta P_n$ converge to $\Delta$ in strong operator norm, i.e. for $f \in D(\Delta)$
$$
\label{1}
\|\Delta P_n f - \Delta f\| \rightarrow 0.
$$
My thought was following: We could write $P_n$ as $\chi_{(-\lambda_n, + \lambda_n)}(\Delta)$, i.e. the functional calculus on $\Delta$ evaluated in $\chi$, the indicator function. Then,
$$
\begin{aligned}
\|\Delta P_n f - \Delta\| & = \|\Delta \chi_{(-\lambda_n, + \lambda_n)}(\Delta) f - \Delta f\| \\
& =  \|(id \cdot \chi_{(-\lambda_n, + \lambda_n)})(\Delta) f - \Delta f\|  \\
& = \|(id \cdot \chi_{(-\lambda_n, + \lambda_n)} - id)(\Delta) f\|.
\end{aligned}
$$
First question: Is $P_n = \chi_{(-\lambda_n, + \lambda_n)}(\Delta)$?
Further, I am a) not sure if this works, b) not sure if the measurable functional calculus is continuous in the unbounded case c) not happy that $\|id \cdot \chi_{(-\lambda_n, + \lambda_n)} - id \|_{L^{\infty}} \rightarrow 0$ does not hold, since the identity is defined on the spectrum of $\Delta$ which is unbounded in general. Can somebody answer some of those question, or has another solution?


text:
Q: Clarification on the flow of realtime work to a GPU I just started learning CUDA, and I am confused by one point. For the sake of argument, imagine that I had several hundred buoys in the ocean. Imagine that they broadcast a std::vector intermittently once every few milliseconds. The vector might be 5 readings, or 10 readings, etc, depending on the conditions in the ocean at that time. There is no way to tell when the event will fire, it is not deterministic.
Imagine that I had the idea that I could predict the temperature from gathering all this information in realtime, but that the predictor had to first sort all std::vectos on temperature accross all buoy. My question is this. Do I have to copy the entire data back to the GPU every time a single buyoy fires an event? Since the other buoy's data has not changed, can I leave that data in the GPU and just update what has changed and ask the kernel to rerun the prediction?
If yes, what is the [thrust pseudo]-code that would do this?  Is this best done with streams and events and pinned memory? What is the limit as to how fast I can update the GPU with realtime data?
I was told that this sort of problem is not well suited to GPU and better in FPGA.

A: A basic sequence could be like this.
Setup phase (initial sort):

*

*Gather an initial set of vectors from each buoy.

*Create a parallel set of vectors, one for each buoy, of length equal to the initial length of the buoy vector, and popluated by the buoy index:
b1:  1.5 1.7 2.2 2.3 2.6
i1:    1   1   1   1   1
b2:  2.4 2.5 2.6
i2:    2   2   2
b3:  2.8
i3:    3

*Concatenate all vectors into a single buoy-temp-vector and buoy-index-vector:
b:  1.5 1.7 2.2 2.3 2.6 2.4 2.5 2.6 2.8
i:    1   1   1   1   1   2   2   2   3

*Sort-by-key:
b:  1.5 1.7 2.2 2.3 2.4 2.5 2.6 2.6 2.8
i:    1   1   1   1   2   2   1   2   3

The setup phase is complete.  The update phase is executed whenever a buoy update is received.  Suppose buoy 2 sends an update:
b2:  2.5 2.7 2.9 3.0

*

*Do thrust::remove_if on the buoy vector, if the corresponding index vector position holds the updated buoy number (2 in this case).  Repeat the remove_if on the index vector using the same rule:
b:  1.5 1.7 2.2 2.3 2.6 2.8
i:    1   1   1   1   1   3

*Generate the corresponding index vector for the buoy to be updated, and copy both vectors (buoy 2 temp-value and index vectors) to the device:
b2: 2.5 2.7 2.9 3.0
i2:   2   2   2   2

*Do thrust::merge_by_key on the newly received update from buoy 2
b: 1.5 1.7 2.2 2.3 2.5 2.6 2.7 2.8 2.9 3.0
i:   1   1   1   1   2   1   2   3   2   2

The only data that has to be copied to the device on an update cycle is the actual buoy data to be updated.  Note that with some work, the setup phase could be eliminated, and the initial assembly of the vectors could be merely seen as "updates" from each buoy, into initially-empty buoy value and buoy index vectors.  But for description, it's easier to visualize with a setup phase, I think.  The above description doesn't explicitly point out the various vector sizings and resizings needed, but this can be accomplished using the same methods one would use on std::vector.  Vector resizing may be "costly" on the GPU, just as it can be "costly" on the CPU (if a resize to larger triggers a new allocation and copy...) but this could also be elmiminated if a max number of buoys is known and a max number of elements per update is known.  In that case, we could allocate our overall buoy value and buoy index vector to be the maximum necessary sizes.
Here is a fully-worked example following the above outline.  As a placeholder, I have included a dummy prediction_kernel call, showing where you could insert your specialized prediction code, operating on the sorted data.
#include <stdio.h>
#include <stdlib.h>
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <thrust/sort.h>
#include <thrust/merge.h>

#include <sys/time.h>
#include <time.h>

#define N_BUOYS 1024
#define N_MAX_UPDATE 1024
#define T_RANGE 100
#define N_UPDATES_TEST 1000

struct equal_func{

  const int idx;

  equal_func(int _idx) : idx(_idx) {}

  __host__ __device__
  bool operator()(int test_val) {
    return (test_val == idx);
  }
};

__device__ float dev_result[N_UPDATES_TEST];

// dummy "prediction" kernel
__global__ void prediction_kernel(const float *data, int iter, size_t d_size){
    int idx=threadIdx.x+blockDim.x*blockIdx.x;
    if (idx == 0) dev_result[iter] = data[d_size/2];
  }

void create_vec(unsigned int id, thrust::host_vector<float> &data, thrust::host_vector<int> &idx){
  size_t mysize = rand()%N_MAX_UPDATE;
  data.resize(mysize);
  idx.resize(mysize);
  for (int i = 0; i < mysize; i++){
    data[i] = ((float)rand()/(float)RAND_MAX)*(float)T_RANGE;
    idx[i] = id;}
  thrust::sort(data.begin(), data.end());
}

int main(){

  timeval t1, t2;
  int pp = 0;
// ping-pong processing vectors
  thrust::device_vector<float> buoy_data[2];
  buoy_data[0].resize(N_BUOYS*N_MAX_UPDATE);
  buoy_data[1].resize(N_BUOYS*N_MAX_UPDATE);
  thrust::device_vector<int>  buoy_idx[2];
  buoy_idx[0].resize(N_BUOYS*N_MAX_UPDATE);
  buoy_idx[1].resize(N_BUOYS*N_MAX_UPDATE);

// vectors for initial buoy data
  thrust::host_vector<float> h_buoy_data[N_BUOYS];
  thrust::host_vector<int> h_buoy_idx[N_BUOYS];

//SETUP
 // populate initial data
  int lidx=0;
  for (int i = 0; i < N_BUOYS; i++){
    create_vec(i, h_buoy_data[i], h_buoy_idx[i]);
    thrust::copy(h_buoy_data[i].begin(), h_buoy_data[i].end(), &(buoy_data[pp][lidx]));
    thrust::copy(h_buoy_idx[i].begin(), h_buoy_idx[i].end(), &(buoy_idx[pp][lidx]));
    lidx+= h_buoy_data[i].size();}
 // sort initial data
  thrust::sort_by_key(&(buoy_data[pp][0]), &(buoy_data[pp][lidx]), &(buoy_idx[pp][0]));

//UPDATE CYCLE
  gettimeofday(&t1, NULL);
  for (int i = 0; i < N_UPDATES_TEST; i++){
    unsigned int vec_to_update = rand()%N_BUOYS;
    int nidx = lidx - h_buoy_data[vec_to_update].size();
    create_vec(vec_to_update, h_buoy_data[vec_to_update], h_buoy_idx[vec_to_update]);
    thrust::remove_if(&(buoy_data[pp][0]), &(buoy_data[pp][lidx]), buoy_idx[pp].begin(), equal_func(vec_to_update));
    thrust::remove_if(&(buoy_idx[pp][0]), &(buoy_idx[pp][lidx]), equal_func(vec_to_update));
    lidx = nidx + h_buoy_data[vec_to_update].size();
    thrust::device_vector<float> temp_data = h_buoy_data[vec_to_update];
    thrust::device_vector<int> temp_idx = h_buoy_idx[vec_to_update];
    int ppn = (pp == 0)?1:0;
    thrust::merge_by_key(&(buoy_data[pp][0]), &(buoy_data[pp][nidx]), temp_data.begin(), temp_data.end(), buoy_idx[pp].begin(), temp_idx.begin(), buoy_data[ppn].begin(), buoy_idx[ppn].begin() );
    pp = ppn; // update ping-pong buffer index
    prediction_kernel<<<1,1>>>(thrust::raw_pointer_cast(buoy_data[pp].data()), i, lidx);
  }
  gettimeofday(&t2, NULL);
  unsigned int tdiff_us = ((t2.tv_sec*1000000)+t2.tv_usec) - ((t1.tv_sec*1000000)+t1.tv_usec);
  printf("Completed %d updates in %f sec\n", N_UPDATES_TEST, (float)tdiff_us/(float)1000000);
//  float *temps = (float *)malloc(N_UPDATES_TEST*sizeof(float));
//  cudaMemcpyFromSymbol(temps, dev_result, N_UPDATES_TEST*sizeof(float));
//  for (int i = 0; i < 100; i++) printf("temp %d: %f\n", i, temps[i]);
  return 0;

}

Using CUDA 6, on linux, on a Quadro 5000 GPU, 1000 "updates" requires about 2 seconds.  The majority of the time is spent in the calls to thrust::remove_if and thrust::merge_by_key  I suppose for worst case real-time estimation, you would want to try and time the worst case update, which might be something like receiving a longest-possible update.


text:
Q: AngularJS - ng-Style not changing when updated in the directive So, here is a custom directive to resize an element and it's contents based on a screen size change. I can see that the value of 'scalify' is changing how I would like it to, but the style itself is not changing. I know that the styles work when applied with static values directly in the css file.
.directive("card", function(){
    return{
        restrict : "E",
        controller: function($scope, $element, $attrs){
            var w = this;
            window.onresize = function () {

                $scope.scalify = {
                    '-ms-zoom': window.innerHeight/675,
                    '-moz-transform': 'scale(' + window.innerHeight/675 + ')',
                    '-o-transform': 'scale(' + window.innerHeight/675 + ')',
                    '-webkit-transform': 'scale(' + window.innerHeight/675 + ')'
                };
                $scope.$apply();
            }
        }
    };
})

And here's how I use the ng-Style in the HTML
<card ng-style="scalify">
    ...
</card>

A: Hi please see here: http://run.plnkr.co/jfeF9NcPcGroNCsg/ probably you need to work a bit on your css transformation but style is changing when you change size of window as you wanted
app.directive("card", function($window) {
  return {
    restrict: "E",
    link: function(scope, element, attrs) {

      scope.onResizeFunction = function() {
        //$scope.windowHeight = $window.innerHeight;
        // $scope.windowWidth = $window.innerWidth;

        var scalify = {
          '-ms-zoom': $window.innerHeight / 675,
          '-moz-transform': 'scale(' + $window.innerHeight / 675 + ')',
          '-o-transform': 'scale(' + $window.innerHeight / 675 + ')',
          '-webkit-transform': 'scale(' + $window.innerHeight / 675 + ')',
          'background-color': 'red'
        };

        element.css(scalify);
        console.log(element);
      };

      angular.element($window).bind('resize', function() {
        scope.onResizeFunction();
        scope.$apply();
      });
    }
  }
});


text:
Q: c# Inject settings in aspnet core external library I have a project with an entry point that is ASP.NET Core API and an infrastructure project that is a Client for MongoDB. I have a problem, I would inject my interface IDatabaseSettings (that is in a common project) in a project with mongo client, so I create concrete type in my principal project like this:
public class MongoSettings : IDatabaseSettings
{
    private const string Mongo = "Mongo";
    private static IConfiguration _configuration;

    public LogMongoSettings(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public string ConnectionString { get; } = _configuration.GetValue<string>($"{Mongo}:ConnectionString");
    public string DatabaseName { get; } = _configuration.GetValue<string>($"{Mongo}:Database");
    public string Username { get; } = _configuration.GetValue<string>($"{Mongo}:Username") ?? string.Empty;
    public string Password { get; } = _configuration.GetValue<string>($"{Mongo}:Password") ?? string.Empty;
}

the problem is that _configuration is always null and this code throws an exception.
I use SimpleInjector container and my Startup project is like this:
public class Startup
{

    private static readonly Container Container = new Container();
    private static readonly Assembly LogReaderAssembly = Assembly.Load("LogReader.IdP");
    private static readonly Assembly MongoLogReaderAssembly = Assembly.Load("LogReader.Mongo");

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddSimpleInjector(Container, options =>
        {
            options.AddAspNetCore()
                .AddControllerActivation();
            options.AddLogging();
        });
        services.AddSwaggerGen(options =>
        {
            options.SwaggerDoc("LogReader", new OpenApiInfo
            {
                Version = "V1"
            });
        });

       InitializeContainer();
    }

    private static void InitializeContainer()
    {
        Container.RegisterSingleton<IDatabaseClient, DatabaseClient>();
        Container.Register<IFileRepositoryReader, TraceFileRepositoryReader>();
        Container.Register(typeof(IRepositoryReader<>), MongoLogReaderAssembly);
        Container.RegisterSingleton(() => Container.GetInstance<MapperProvider>().GetMapper());
        Container.Register(typeof(IQueryHandler<,>), LogReaderAssembly);
        Container.Register<IDatabaseSettings, MongoSettings>();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseSimpleInjector(Container);

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();

        });
        app.UseSwagger();
        Container.Verify(VerificationOption.VerifyAndDiagnose);
    }
}

Why does this happen? What is the problem?
I wouldn't use IOptionMonitor in my Mongo client because I wouldn't that this class depends on concrete TOptions.
Is there a better solution to the problem?
Thank you.

A: in the end, I solved the problem with this code:
public class MongoDatabaseSettings : IDatabaseSettings
{
    private const string Mongo = "Mongo:";

    public MongoDatabaseSettings(IConfiguration configuration)
    {
        Host = configuration.GetValue<string>($"{Mongo}{nameof(Host)}");
        Port = configuration.GetValue<int>($"{Mongo}{nameof(Port)}");
        DatabaseName = configuration.GetValue<string>($"{Mongo}{nameof(DatabaseName)}");
        Username = configuration.GetValue<string>($"{Mongo}{nameof(Username)}");
        Password = configuration.GetValue<string>($"{Mongo}{nameof(Password)}");
    }

    public string Host { get; }
    public int Port { get; }
    public string DatabaseName { get; }
    public string Username { get; }
    public string Password { get; }
}

I don't understand why in this case the properties are initialized correctly, instead the original question code doesn't work.
Do you have any idea why this happens? Thank you


text:
Q: First Law of Thermodynamics as a rate equation In a standard engineering thermodynamics textbook (Fundamentals of Thermodynamics, Sonntag, et. al, 6th ed) the First Law of Thermodynamics is differentiated with respect to time, and written as a rate equation. It is stated (p. 141): "In so doing we are departing from the strictly classical point of view, because basically classical thermodynamics deals with systems that are in equilibrium. However, since these rate equations are...used in many applications of thermodynamics, they are included in this book".
The authors have not provided a rationale. Under what conditions is it valid to write the First Law of Thermodynamics as a rate equation ?
[Equation referred to is: dU/dt=dQ/dt-dW/dt]

A: I'm not sure exactly how you are using the phrase "first law of thermodynamics". In a strict treatment, that phrase equates to the statement
First law of thermodynamics: Energy is conserved.
One can also express the same law by:
First law of thermodynamics: The amount of work required to change the state of a closed and thermally isolated system depends solely on the initial and final states.
As I say, it is one or other of these statements in words which is correctly called the "first law of thermodynamics".
Now I guess that the expression you are referring to in your question might be something like:
$$
dU = T dS - p dV
$$
which applies to a closed simple mechanical system. This expression is true for any situation in which the quantities are well-defined. In particular, in order for the temperature and pressure to be well-defined quantities, the state of the system will usually need to be an equilibrium state, and the small quantities are differences between properties of neighbouring equilibrium states. You can if you like divide such an equation by a small time $dt$ so as to obtain
$$
\frac{dU}{dt} = T \frac{dS}{dt} - p \frac{dV}{dt}
$$
but this would require careful interpretation, because if the movement between states takes place too fast then the system will not be passing through a sequence of thermal equilibrium states (the change will not be quasistatic) and in this case the quantities $T$ and $p$ may not be well-defined. If the movement between states is slow compared to the thermal relaxation time then the process is called quasistatic. To be precise, a quasistatic process is one in which the system moves through a sequence of equilibrium states; this is an idealization so might arguably be said to never apply exactly, but in practice relaxation to equilibrium involves exponential decay, such that the degree of approximation in assuming the idealization is acceptable for many real processes. After all, we never take everything into account when we apply science to experimental realities. The assumption of a quasistatic model may often be among the more precise aspects of a given treatment.

A: It is virtually always valid, even locally (I.e., differentially), as long as you are dealing with small molecule ( non-polymeric) fluids with time scales for relaxation that are short compared to the time scale for the process.  In other words, if the time between collisions is short compared to the process time, the approach is valid.

A: I can't speak to the validity of the approach, but I would think that any processes and the cycles they comprise if carried out at a finite rate must necessarily be irreversible.  Reversible processes need to be carried out quasistatically (infinitely slowly).
Hope this helps


text:
Q: web.xml in war getting misplaced using gradle My build.gradle looks somewhat like this. Its so clear that my web.xml is in WebContent/WEB-INF, then why does the war get created with web.xml under WebContent/WEB-INF/lib folder ?
I inflated the war, and got this

inflating: WEB-INF/lib/web.xml

apply plugin: 'java'
apply plugin: 'war'

repositories {
    jcenter()
}

dependencies {
    compile 'org.slf4j:slf4j-api:1.7.21'
    compile group: 'org.apache.tomcat', name: 'tomcat-catalina', version: '8.5.0'
    compile group: 'log4j', name: 'log4j', version: '1.2.16'

    compile files('WebContent/WEB-INF/lib/coregeneral.jar')
    compile files('WebContent/WEB-INF/lib/operationserverendpoints.jar')

    compile files('WebContent/WEB-INF/web.xml')
    testCompile 'junit:junit:4.12'
}

sourceSets {
    main {
        java {
            srcDir 'src'
        }
    }
}

A: I had added web.xml as a compile option, that was incorrect. I removed it from the compile option and added this, it worked.
war {
webXml = file('WebContent/WEB-INF/web.xml') // copies a file to WEB-INF/web.xml
}


text:
Q: insert before last 2 char in javascript How would I insert a % before the last 2 characters in a word?
For example:
var str = "Because";

Output:
Becau%se

A: How about
var str = "Because";
var len = str.length;
var x = str.substring(0, len-2) + "%" + str.substring(len-2);

Hope this helps.

A: Here you go! :)
http://jsfiddle.net/6WNk8/

A: Try this
var str = "Because";
var result = str.slice(0, -2) +"%"+str.slice(-2);

A: str.substring(0, str.length - 2) + "%" + str.substring(str.length - 2)

A: Try using this:
str.substring(0,str.length-2)+"%"+str.substring(str.length-2)

A: Try
function insert(str, value, position){

   return str.substring(0,str.length-position) + value + str.substring(str.length-position);
}

A: Alternatively...
var str = "Because",
    chars = str.split('');

chars.splice(-2, 0, '%');
str = chars.join('');

jsFiddle.

A: Here's a function I wrote for you to do it!
var MyString = "Because";

// Inserts a string into another string at a given point
function InsertString(OriginalString, InsertingString, Position) {
    return OriginalString.substring(0, Position) + InsertingString + OriginalString.substring(Position, OriginalString.length);
}

// You can call this as well if you want it n positions from right
function InsertStringFromRight(OriginalString, InsertingString, CharsFromRight) {
    return InsertString(OriginalString, InsertingString, OriginalString.length - CharsFromRight);
}

// Call the function!
var Test1 = InsertString(MyString , "#", 5);
var Test2 = InsertStringFromRight(MyString , "#", 2);

alert(Test1);
alert(Test2);


text:
Q: Cocos-2dx JS can't load scene from JSON file with version 3.10.0.0 I'm using Cocos-2dx JS for a game project. The Cocos version I use is 3.10. To create the GUIs of my game, I used Cocos Studio and then I generate JSON file of said scene using Cocos Studio. However, the generated JSON file version is 3.10.0.0, and when I compile my project, it got the error "JSON is undefined". When I changed the version attribute of the JSON file to 2.1.0.0, the project run without a problem. Anyone has experienced same error can explain why this happens and how to fix it? Thank you very much.

A: I found a simple solution that works well for me. All you need to do is go to the Cocos Studio project folder and open YourProjectName.cfg. Find two lines that look something like below.
<CreateFrameworkVersion Value="cocos2d-x-3.10.0.0" />
<CurrentFrameworkVersion Value="cocos2d-x-3.10.0.0" />

Modify the value of CreateFrameworkVersion and CurrentFrameworkVersion to "cocos2d-x-2.10". Then, save it. Now, whenever you publish the project, the JSON file version will be 2.10.
Remember you have to close your Cocos Studio project first.


text:
Q: Restart android machine we have android + linux m/c, we log in into linux shell and boot the machine in android GUI.
now we have the some script that is running on the same machine through linux shell. In that case when the script hangs we need to restart android machine. but it result into restarting the linux machine too. as they are on same machine. so i need the way to restart the android so it comes out of hang state and control remains on the script that is running through the linux shell.
so is there any adb or linux command that work for me?

A: You can reboot the device by sending the following broadcast:
$ adb shell am broadcast -a android.intent.action.BOOT_COMPLETED

A: adb reboot should not reboot your linux box.
But in any case, you can redirect the command to a specific adb device using adb -s <device_id> command , where
Device ID can be obtained from the command adb devices
command in this case is reboot

A: Have you tried simply 'reboot' with adb?
  adb reboot

Also you can run complete shell scripts (e.g. to reboot your emulator) via adb:
 adb shell <command>

The official docs can be found here.

A: I think the only way to do this is to run another machine in parallel and use that machine to issue commands to your android box similar to how you would with a phone. If you have issues with the IP changing you can reserve an ip on your router and have the machine grab that one instead of asking the routers DHCP for one. This way you can ping the machine and figure out if it's done rebooting to continue the script.


text:
Q: How to implement a 2D vector of enum class objects? This is the enum class I use.
enum class PlayerColor {BLACK, BLUE, RED};

This is how I want to create a vector. Basically, store a vertex name along with its color.
I am getting plenty of errors.
typedef pair<int, PlayerColor> ip;

vector< vector< ip > > vertices;

This is how I want to initialize the 2D vector (inside a constructor)
for(auto i=vertices.begin()+1;i<vertices.end();++i)
    for(auto j=i->begin()+1;j<i->end();++j)
    {
        *(j.first)=c++;   //error
        *(j.second)=PlayerColor::BLACK;  //error
    }

This function takes the names of two vertices and adds an edge between them. (Routine works fine otherwise)
addEdge(vertices[i][j+1].first,vertices[i][j].first); //error

EDIT:
addEdge function is defined as:
void HexBoard::addEdge(int u, int v)
{
    edge[u].push_back(v);
    edge[v].push_back(u);
}

edge is :
vector< vector<int> > edge;

It is initialized in C++11 style as:
edge(vector< vector<int> > (size*size + 1 + 4)),EAST(size*size+1),WEST(size*size+2)

size is an integer.

A: The only error i see is in the expressions *(j.first)=c++; and *(j.second)=PlayerColor::BLACK;
you need to dereference the iterator j like such:
    (*j).first=c++;   //no error
    (*j).second = PlayerColor::BLACK;  //no error

Edit:
The other errors are probably because your code does't declare things correctly like in the line:
addEdge(vertices[i][j+1].first,vertices[i][j].first);
there is no error here if i and j are of integer types. If i and j are iterators then you will get an error.


text:
Q: How to apply a MVC architecture to a ExtJS project? I would like to build a web project, using ExtJS, the famous JavaScript library. The goal is to use only ExtJS (and some CSS and HTML) to build the entire client-side web application. I also would like to apply a Model-View-Controller structure to the code of this project.
First question: is it possible and pertinent to apply such an architecture to an ExtJS project?
Second question: how can I easily apply a MVC architecture to a ExtJS project?
I already read this but it does not answer my questions.
The documentation from the ExtJS community does not provide such tips.
In all given samples, code is contained in one single file, and UI code is not separated from the application logic code. For example, listeners methods and calls to server come along with UI code.
In fact, all tips to separate application logic from user interface code are welcomed.
Edit
Another question: What do you think is the best way to design a ExtJS based web application? I did not found any good designer for ExtJS. The designers I found (this and this) don't seem to be reliable (code generation of the first sometimes fails).

A: In my experience, you want to think about two separate applications.
On the server side, you want to fashion a pretty typical MVC application that simply provides a web service.  You're probably fine just talking JSON.  Look into doing things RESTfully.
On the client side, you have a javascript application.  If you're really leveraging ExtJS, you should only have an initial request/response that sets up the application.  Everything from then on should just be XHR requests to your web service (and, if you're getting fancy, lazy-loading of ExtJS-driven javascript files).
This kind of architecture will pay for itself when all of a sudden you want to open up a public web service, or write some alternative client (iPhone apps, for example).  These alternative clients should be able to rely on the already-running web service.
Switching gears to the client-side, ExtJS driven stuff -- MVC can help you here, but you're making a mental context switch from a request-driven system (on the server), to a more open-ended event-driven system in the browser.
Use a lot of the practices the ExtJS community talks about (smart use of factory methods, extending built-in classes, module pattern, ExtJS's template methods, etc).
While organizing your javascript application, try to think in an MVC sort of way.  Learn how event bubbling and relayEvents() work.  You've got your model stuff (basically, they'll derive from the built-in store classes), view stuff (Grids, Trees, etc), and controller stuff (usually attached to some container.  Read Saki's stuff about inter-component communication at extjs.eu.)
There's certainly more than one way to do it when it comes to heavyweight client-side application design.  But if you want to seriously leverage ExtJS's potential, it's worth it to take the time to read up on things.  Look at articles or books about GUI programming in general -- writing an ExtJS app is more similar to writing a traditional desktop application than writing a web application.
In this domain, the "web" stuff gets very simple -- you're just handling data on the server side.  The tricky stuff is figuring out how to organize and optimize the in-browser code.

A: Use some libraries which makes javascript OOP lang. Then use MVC pattern.  Also you can use Ext-GWT for developing web on OOP java.


text:
Q: Is reportgenerator in fortify exist some command to filter issue? to shorten the work time on handling fortify scanning, i am trying to do some automatic bat. now i have some trouble on filtering the issue of scanning result(*.fpr).
the command i try is
sourceanalyzer -b %FileName% -scan -filter filter.txt -format fpr -f "D:\%~2%FileName%.fpr" -logfile "%FileName%3.log"
and the filter.txt content:
Insecure SSL: Server Identity Verification Disabled
JSON Injection

In the UI(Fortify Audit Workbench) export the filter(*.xml, i find the name of "filter" is "Issue Templates"), you can try the following format to filter the JSON Injection issue in Critical priority order:
<Filter>
    <actionParam>true</actionParam>
    <query>[category]:"JSON Injection" AND [fortify priority order]:"Critical"</query>
    <action>hide</action>
</Filter>

but it can't be in command line....QQ
i also had tried FPRUtility.bat, BIRTReportGenerator.cmd, and ReportGenerator.bat, but the filter couldn't be custom. does anyone have some advice?


text:
Q: m3u8 not playing offline - swift 3.0 I am trying to stream an m3u8 url and save offline.
Then play from offline.
I am using  Apple HTTP Live Streaming
Start Download by using the below code
func setupAssetDownload() {
        // Create new background session configuration.
         configuration = URLSessionConfiguration.background(withIdentifier: DOWNLOAD_ID)

        // Create a new AVAssetDownloadURLSession with background configuration, delegate, and queue
         downloadSession = AVAssetDownloadURLSession(configuration: configuration,
                                                    assetDownloadDelegate: self,
                                                    delegateQueue: OperationQueue.main)
        let url = URL(string: urlString)
        let asset = AVURLAsset(url: url!)

        // Create new AVAssetDownloadTask for the desired asset
        let downloadTask = downloadSession.makeAssetDownloadTask(asset: asset, assetTitle: "asset_Title", assetArtworkData: nil, options: nil)
        // Start task and begin download
        downloadTask?.resume()

    }

Where,
let DOWNLOAD_ID = "downloadIdentifier"

let urlString = "http://domain/vod/mp4:sample1.mp4/playlist.m3u8"

// Saving the Download Location

    func urlSession(_ session: URLSession, assetDownloadTask: AVAssetDownloadTask, didFinishDownloadingTo location: URL) {

        print("didFinishDownloadingTo \(location.relativePath)")
        // Do not move the asset from the download location
        UserDefaults.standard.set(location.relativePath, forKey: "assetPath")
    }

When try to play Offline,
I can get the AVURLAsset,
<AVURLAsset: 0x1742319e0, URL = file:///var/mobile/Containers/Data/Application/79C0043F-6161-4231-9129-B71C95903E05/Library/com.apple.UserManagedAssets.bhVNRN/asset_Title_63128673BE57FBDD.movpkg/>

But, not paying from the asset.
func playOfflineAsset() {
        guard let assetPath = UserDefaults.standard.value(forKey: "assetPath") as? String else {
            // Present Error: No offline version of this asset available
            return
        }
        let baseURL = URL(fileURLWithPath: NSHomeDirectory())
        let assetURL = baseURL.appendingPathComponent(assetPath)
        let asset = AVURLAsset(url: assetURL)

        let player = AVPlayer(url:assetURL)

        let playerLayer = AVPlayerLayer(player: player)
        playerLayer.frame = videoView2.bounds
        playerLayer.backgroundColor = UIColor.purple.cgColor
        videoView2.layer.addSublayer(playerLayer)

        player.play()

        if let cache = asset.assetCache, cache.isPlayableOffline {
            // Set up player item and player and begin playback

            print("exist")

        } else {
            // Present Error: No playable version of this asset exists offline
            print("doesn't exist")
        }
    }

A: you need add AVPlayerController to AVPlayer can play with sounds, i dont know why, but its work for me
// Set up player item and player and begin playback
let playerItem = AVPlayerItem(asset: asset)

player = AVPlayer(playerItem: playerItem)

// play without present playerController
self.player?.play()

// play with present playerController
// let playerController = AVPlayerViewController()

// playerController.player = player
// self.present(playerController, animated: true) {
//       self.player?.play()
// }

Edit: Make sure hls not encrypt.


text:
Q: Can I do a mathematical-shape mask for a (Nx,Ny) matrix? I have a matrix of numbers (Nx,Ny) and I would like to select from that matrix a mathematical shape coordinates/components as it could be a line with a given slope.
I learned how to create a mask and how to do it in a random way but I cannot think of how to generate a mathematical-shape mask in python.
This is some of the code that I've been able to develop. If you know a better way to do this I will be also grateful of being told.
import random
import numpy as np

threshold = 0.85
radius=40
sq7=1/(radius*radius)

matrix=np.zeros((Nx,Ny))

for i in range(0,Nx):
    for j in range(0,Ny):
        if ((i-Nx*0.5)*(i-Nx*0.5)*sq7+(j-Ny*0.5)*(j-Ny*0.5)*sq7<=1.0):
            matrix[i,j]= 1.0 - 0.1*random.random();
        else:
            matrix[i,j]=-1.0 + random.random();

randoms = np.random.normal(0,scale=0.002, size=matrix[mask].shape)
mask = matrix**2 < threshold
matrix[mask] += randoms * (1 - matrix[mask]**2)

A: At the end I found a very easy way of doing so. What I just did was to create a new matrix of the same dimensions as the one that I want to mask and then just by going through the matrix itself and comparing with the values of my function I could do it so easily. I will leave the code here.
def func_normaldist(x,Ny):
    y = np.exp(-0.5*(x-int(Ny/2))**2)/np.sqrt(np.pi*2.)
    return y

def mask_uvalues_centered_geometry(Nx, Ny): #u
    mask = np.zeros((Nx,Ny))
    # Initial configuration: rectangle of Nx x Ny
    for j in range(0,Ny):
        for i in range(0,Nx):
            if (i < Ny*Nx*func_normaldist(j,Ny)):# and (i > int(Nx/2 + 1)):
                mask[j,i] = True

            else:
                mask[j,i] = False;
    return mask
Nx = 50
Ny = 50
a = mask_uvalues_centered_geometry(Nx,Ny)
print(a)


text:
Q: Editing a program with Ollydbg This is my C++ code:
#include <conio.h>
#include <iostream>

using namespace std;

void func1()
{
    static int _count = 0;
    if (_count < 5)
    {
        __asm
        {
            pop eax
            push func1
        }
    }

    _count++;
    cout << _count << endl;
}

int main()
{
    func1();

    cout << "ok" << endl;
    return 0;
}

Now, I need to remove asm inline.
It is loaded into Ollydbg, and this is position of asm inline:

I will fill two instructions which is marked in the image with NOP's. Ok. I know how to do it. Then, I saved it with a new name.
But when I loaded the program that I edited into Ollydbg.
The places that I edited was added a new instruction.

And the new instruction makes the program crashs.
Ok, If my question is clearly enough, I need to know:
How did that instruction was added automatically?
And How do I fix it?
Thanks.
UPDATE 1:
The following is how I modified the program

But.. I don't know why?

A: A NOP allocates 1 byte, so to replace those two instructions by NOPs
POP  EAX              ; 1 byte
PUSH Console.func1    ; 5 byte

You need to put 6 of NOP not 2. Otherwise, you have 2 NOPs and 4 bytes of garbage.


text:
Q: Indefinite integral of expression including DiracDelta function doesn't work Here is the simplified code:
e[t_]:=DiracDelta[t] Exp[-I omegaC t]
R[t1_] := Exp[-I omega21 t1]
Integrate[R[t1]*e[t- t1], t1,Assumptions -> {t1 >= 0, t >= t1}]

It doesn't calculate, just return the input.
I don't know why, the integrated expression is simple.

A: Workround:
e[t_] := DiracDelta[t]*Exp[-I*omegaC*t]
R[t1_] := Exp[-I*omega21*t1]
{a, b} = ReIm[R[t1]*e[t - t1]] // ComplexExpand
sol = Integrate[{a, b}, t1, Assumptions -> {t1 >= 0, t >= t1}]
sol[[1]] + sol[[2]]*I // TrigToExp // FullSimplify

(* E^(-I omega21 t) HeavisideTheta[-t + t1] *)

A: Simplifying a bit your integrand, and assuming that $t, omegaC, t1,a ,b$ and $omega21$ are Reals:
Assuming[t >= t1 && a > 0 && b >= 0 && omegaC \[Element] Reals &&
omega21 \[Element] Reals,
Exp[-I omegaC t] Integrate[ComplexExpand@(E^(-I (omegaC (-t1) + omega21 t1)))
DiracDelta[t - t1], t1, Assumptions -> True]] // FullSimplify

and it yields:
E^(-I omega21 t) HeavisideTheta[-t+t1]

A: If you change your integral slightly you get what you're looking for:
Integrate[R[t1]*e[t - t1], {t1, low, high}, Assumptions -> {low < t < high}]
(* E^(-I omega21 t) *)


text:
Q: How can I identify the cause of unexpectedly large sync data requirements? iPhone 6, 64 GB memory, updated to iOS 12.4.5 this morning. I attempted to sync with my Mini afterwards and got an error:
"cannot be synced because there is not enough free space to hold all the selected items (additional 14.10 GB required)".
According to the summary on my desktop, my phone has 12 GB free, so it looks as if it wants to upload about 26 GB total from the desktop to the phone.
I have no idea why it should be so much. I'm on the latest OS update so it shouldn't need to copy an update across. I've checked through my sync settings and can't see anything obvious that would account for the large upload requirement - I'm not in the habit of syncing video to the phone, or anything like that, just occasional music, and I haven't added anywhere near 26 GB of music to the desktop since my last sync about a month ago. I barely have 30 GB total on the Mini and most of that is already on the phone.
Any ideas on how I can figure out what's taking so much space for this sync?


text:
Q: Find correlation/covariance of two distributions with shared marginal distributions I have two distributions which represent the sum of smaller distributions.
Say distribution X is made up of distributions a, b and c: $\mu_a$ = 10, $\sigma_a$ = 3; $\mu_b$ = 15, $\sigma_b$ = 5; $\mu_c$ = 20, $\sigma_c$ = 4; so $\mu_X$ = 45 and $\sigma_X$ = $\sqrt{50}$.
Distribution Y is made up of a, d and e: $\mu_a$ = 10, $\sigma_a$ = 3 (this is of course the same as the a above); $\mu_d$ = 18, $\sigma_d$ = 2; $\mu_e$ = 12, $\sigma_e$ = 4; so $\mu_X$ = 40 and $\sigma_X$ = $\sqrt{29}$.
With this information, is there a way that I can find the correlation/covariance between the two distributions? Would it have to do with how much a contributes to X and Y's means and/or variances?


text:
Q: Pasar una variable de un Activity a una clase en Android Hola a todos como puedo pasar una variable a una clase en Android estoy trabajando con una libreria llamada Retrofit, la variable que quiero pasar se llama link4 y quiero pasarla a la clase RetroFitObjectAPI
Aca esta mi activity
public class Preaprobado extends AppCompatActivity {

    private String link4;
    public Preaprobado(String link4){
        this.link4=link4;
    }
    public String getLink4(){
        return link4;
    }
    public void setLink4(String link4){
        this.link4=link4;
    }
    TextView txt1, txt2, txt3;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_preaprobado);
        txt1 =(TextView) findViewById(R.id.text1);
        txt2 =(TextView) findViewById(R.id.text2);
        txt3 =(TextView) findViewById(R.id.text3);
        Intent intent1 = getIntent();
        String link4 = intent1.getStringExtra("NAME4");
        final TextView mtextView = findViewById(R.id.finaltextView);
        mtextView.setText(""+link4+"");
        getRetrofitObject();
 }
        public void getRetrofitObject(){

        Uri.Builder builder = new Uri.Builder();
        builder.scheme("https")
                .authority("valeria-serv-inf.herokuapp.com");
        String url = builder.build().toString();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
}

Aca esta mi clase
package com.robotics.sistemaexpertocredito;

import retrofit2.Call;
import retrofit2.http.GET;

/**
 * Created by Jaink on 24-08-2017.
 */

public interface RetrofitObjectAPI {
    Preaprobado g = new Preaprobado(String link4);

    @GET("link4")
    Call<model> getJsonObjectData();
}

Como puedo resolver este problema porfavor necesito que trasladar la variable link4

A: Podrías solucionarlo creándote una clase "x", y definiendo una variable estática : mi_link4, para que luego hagas uso de esa variable estática en cualquier parte de tu código, simplemente llamando a la clase y utilizando el valor de la variable estática.
    public class Estatico {
        static  String mi_link4="";
         }

    //añadiendo valor a la variable estática en cualquier parte del código(o en otra clase):
       Estatico.mi_link4="hola mundo";

    //Utilizando el valor de la variable en cualquier parte del código (o en otra clase):

       String cadena=Estatico.mi_link4;

No olvides importar la clase si la utilizas en otra clase o
  directorio, Android studio te da la opción de importar la clase asi
  que no creo que tengas problema con eso


text:
Q: Derivative of a function being equal to 0 Suppose $f(x, 0) = 0$ for all $x$ in some domain of definition. Let $g = \partial f/\partial x$. Does it follow that $g(x, y) = 0$ for all $(x, y)$ in our domain?

A: No, for example:
$$f(x,y)=xy$$
$$f(x,0)=0$$
$$g(x,y)=y$$


text:
Q: React Build Hosting in Apache: Forbidden error Getting 403 Forbidden error while hosting react build app to apache server in ubuntu.
I tried setting up virtual host from /etc/apache2/sites-available/000-default.conf
 <Directory /var/www/html>
       Options Indexes FollowSymLinks
       AllowOverride All
       Require all granted
 </Directory>

Still getting the error. What should I do?
PS: I have the index.html file in /var/www/html/build

A: Have you tried adding .htaccess file to the root of your host?
If not, add this to .htaccess and then restart apache server.
<IfModule mod_rewrite.c>
    RewriteEngine On
        # If an existing asset or directory is requested go to it as it is
        RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
        RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
        RewriteRule ^ - [L]
        # If the requested resource doesn't exist, use index.html (in your case /build/index.html)
    RewriteRule ^ /build/index.html
</IfModule>

You have to enable mod_rewrite though.


text:
Q: jqGrid ShowLink Formatter - Custom ID Parameter Am I just missing something simple here?  Without going into custom formatting, I'd just like to use my ID values for the ID parameter in the showlink formatter.  Here is an example of my sub-grid:
subGridRowExpanded: function (subgrid_id, row_id) {
    var subgrid_table_id = subgrid_id + '_t';
    $('#' + subgrid_id).html('<table id="' + subgrid_table_id + '" class="scroll" />');
    $('#' + subgrid_table_id).jqGrid({
    datatype: 'local',
    colNames: ['Order Number', 'Request Type', 'Owner', 'Order Status', 'Status Date'],
    colModel: [{
        name: 'orderid',
        index: 'orderid',
        width: 150,
        key: true,
        formatter: 'showlink',
        formatoptions: { baseLinkUrl: 'AOFOrderFacilities.aspx', idName: 'orderid' }
    }, {
        name: 'type',
        index: 'type',
        width: 100
    }, {
        name: 'owner',
        index: 'owner',
        width: 200
    }, {
        name: 'status',
        index: 'status',
        width: 150
    }, {
        name: 'date',
        index: 'date',
        width: 150
    }],
    sortname: 'num',
    sortorder: 'asc',
    height: 'auto'
    });
    // TODO: Make this into an AJAX call.  This is just for demo.
    var mysubdata = [
    { orderid: 'O00001234', type: 'Data', owner: 'Melanie Martin', status: 'Saved', date: '2/4/2011 11:48:18 AM' },
    { orderid: 'O00001235', type: 'Voice', owner: 'Billy Solomon', status: 'Submitted to TC', date: '2/4/2011 12:03:47 PM' }
    ];
    for (var i = 0; i <= mysubdata.length; i++)
    jQuery('#' + subgrid_table_id).jqGrid('addRowData', i + 1, mysubdata[i]);
}

When the links in the first column of the grid are rendered, they correctly display the orderid value as the text of the column (the pre-pended "O" is intentional, and should be passed through the system like that), but the resulting links are:
http://localhost/somestuff/AOFOrderFacilities.aspx?orderid=1
http://localhost/somestuff/AOFOrderFacilities.aspx?orderid=2

And so on, where the ID parameter value is the ordinal index of the grid row rather than the desired value from the data.  Is there an easy way to use the value from the data instead?

A: The format option idName of the formatter showlink say only that the name the parameter in the url which you need. The value of the id is always the rowid. In your example you use
var mysubdata = [
    { orderid: 'O00001234', type: 'Data', owner: 'Melanie Martin',
      status: 'Saved', date: '2/4/2011 11:48:18 AM' },
    { orderid: 'O00001235', type: 'Voice', owner: 'Billy Solomon',
      status: 'Submitted to TC', date: '2/4/2011 12:03:47 PM' }
];
for (var i = 0; i <= mysubdata.length; i++)
    jQuery('#' + subgrid_table_id).jqGrid('addRowData', i + 1, mysubdata[i]);

which give as the rowid of the rows the values 1,2, mysubdata.length. The setting key:true for the column orderid will be ignored by the method addRowData. You can verify in Developer Tools or in Firebug which id has <tr> elements of your grid.
I recommend you to modify the above code or just use data:mysubdata as a additional parameter of jqGrid instead of the usage more slow old method addRowData. Because you defined key:true all should work correct. You can also use localReader:{id:'orderid'} as additional jqGrid parameter.

A: Not sure if you guys have solved this yet BUT I got it to send across the id of my choice by setting the json reader as follows:
jsonReader: {
   repeatitems: false,
   id: "[property whose value you want to pass]"
},
Rich


text:
Q: How do these powerline networking adapters work? I have some powerline networking adapters which can transfer at a peak rate of 200 Mbps (I get around 60 Mbps typical, but I am sharing the network with many other devices and many pieces of equipment are running on the line.) How do they do it? I always thought that it was during the zero crossing, but packing so many bits into such a space must be very difficult, nigh impossible. HowStuffWorks has an article on it, but it's only relevant to adapters which go at 14 Mbps.

A: Your power line only has significant frequency content at 50-60hz and the first few harmonics which means there is a massive chunk of the cable in the frequency domain that is being unused.  So use it to transmit digital data.
Thats pretty much it, if your interested in encoding techniques you may want to just look at those directly.  The encoding system is really the only interesting thing about it, you don't get controlled impedance twisted pair cable for power line networking, you get busted romex with screw terminals all over the place so the encoding system has to be robust and deal well with poorly controlled transmission line impedance.
IEEE 1901 is the standard that covers power line networking and allows for OFDM or Wavelet modulation for the PHY.  New versions are getting up to 500mbps -> 1gbps.
As to the many devices, ODFM splits the available bandwidth into a lot of different channels, multiple channels can be used for different things at 1 time.  Device A and B are talking on channel 1 while device A and C are talking on channel 2, etc.  I don't know the negotiation protocol for what channels get used and when within IEEE 1901.
OFDM is also the basis for 4G LTE, WiMAX, and other multiple access systems.
EDIT:
You can insert/remove high frequency information from the power line with a simple isolation transformer specced for your frequency (look in the pulse transformer section) and a high pass filter on the receiver side.
Example from one of Maxim's datasheets:

A: If you want a simplistic answer. Here it is
You have the power source. It gives you 220 Volts at rather low frequency (as noted: 50-60 Hz). You connect a capacitor with a low value and an inductance of a low value to this line this way: low inductance doesn't allow 50-60 Hz to pass in - it shorts such currents to the ground (being placed after capacitor! not to short everything at all), on the other hand capacitor in it's place again doesn't allow low frequency in and passes through high frequency, which we send or receive. The other party does the same - we have a working transfer line.
But, ofcourse we connect different devices to our power socket. What happens in such a situation is simple too: mostly they are - ac/dc convertors, which use either transformer, or impulse scheme. This schematic doesn't allow high frequencies, eg they provide huge resistance to it. But we remember the capacitor in both our devices - it provides low resistance, so our-generated high frequency signal takes the easiest way: our receiver.
Ofcource there will be noise and leakage, our coding system and filters will deal with it.
That's the picture in it's simplest form. Hope this is what you were asking ;)

A: I think it would be helpful to consider power line modems as radio devices since they use  traditional radio techniques (modulation) to achieve data transfer. If you take two radio modems and plug a cable between them instead of an antenna they will still be able to communicate (impedance matching aside).
The basic idea is not to encode the data as high-low voltage levels (which can be prone to interference) but as frequency/phase of (a set of) sinusoids. The second thing to do is to eliminate low-frequency components by clever encoding and/or frequency conversion. This makes it possible to separate different users by frequency filtering (in addition to being critical in radio since electromagnetic waves won't happen from a DC signal).


text:
Q: get the name of subsites on which user dont have permision in sharepoint using client object model Hi I am using client object model in .net to access sharepoint data.
I have site in which i have some subsites. out of these subsites some sites are not accisible to me.
I want to get the list of this subsites (at least title for that subsite), so i can inform the user that this are the subsites on which he dont have access.
Is there any way to achive this using the client object model in the .Net.
currently i am using getsubwebsforcurrentuser method as follows: which gives me the list of subsite on which i have access. but i am more interested in subsite title on which i dont have access.
ClientContext clientContext = new ClientContext(path);
                Web oWebsite = clientContext.Web;
                WebCollection collWeb = oWebsite.GetSubwebsForCurrentUser(null);
                clientContext.Load(collWeb);

Earlier i used the following code. which is throwing serverunauthorizedaccessexception eception, obviously because i dont have access on one of the subsite
            ClientContext clientContext = new ClientContext(path);
            Web oWebsite = clientContext.Web;
            clientContext.Load(oWebsite, website => website.Webs, website => website.Title);

So kindly help me to get the list of subsites on which i dont have access, if there is any way to achive this?

A: Not via CSOM due to security trimming.
But you could accomplish it via SharePoint Web Services, in particular using Webs.GetWebCollection method:
using(var proxy = new Webs())
{
     proxy.Url = webUri + "/_vti_bin/Webs.asmx";
     var result = proxy.GetWebCollection();
     var nodes = result.SelectNodes("*");
     foreach (XmlNode node in nodes)
     {
            var webTitle = node.Attributes["Title"].Value;

     }
}


text:
Q: Removing an element from group but keeping "odd/even" state accurate What are I am trying to achieve is fairly easy (I think) but unfortunately I can't get a hold of the solution.
Consider the following HTML syntax:

        close

        close

        close

        close

        close

Basically all boxes are floating left and that makes room for 2 per line. The first box has a margin-right of 25px so that the 2nd box is pushed to the edge of its container.
When I click the ".close" link I want the element to "hide();" and if the element I clicked is ":even" then the one that will come into place (the odd one) is to become "even" so the margin is applied and vice versa.
Basically it's a dynamic ":nth-child(2n)"... Every 2nd element has to have no margin, and then first one has to have a margin-right of 25px, even if I remove one element from that group.
Hope that makes sense! Thank you very much

A: Add .even and .odd classes and bind this function:
$('.box').click( function() {
    $(this).hide().nextAll(':visible').toggleClass('even odd');
});

Here is demo: http://jsfiddle.net/X5eCa/

A: nth-child is a CSS selector, so you should be able to do:
div.box:nth-child(odd) {
  margin-right:25px
}

div.box:nth-child(even) {
  margin-right:0;
}

...and you can add whatever other styling you need.

A: This should work for you. The fiddle uses red/blue backgrounds for clarity
CSS first:
.redback {
  background-color:red;
}
.blueback {
  background-color:blue;
}

Now some Javascript
colorBoxes();

$(".box").on('click', function() {
  $(this).hide();
    colorBoxes();

});

function colorBoxes() {
  $(".box").removeClass('redback blueback');
  $(".box:visible:odd").addClass('redback');
  $(".box:visible:even").addClass('blueback');
}


text:
Q: full URL path in ajax Is it okay to put full URL path in ajax? I'm having problems accessing the url and I'm getting status 0 for my error response.
    $.ajax({
        url: "http://fullurlpath.com/php/myphppagedata.php",
        type: "GET",
        data:  "somedata="+somedata,
        error: function(XMLHttpRequest, textStatus, errorThrown) {
             alert(XMLHttpRequest.responseText);
        }
    }).error(function(xhr){
             alert(xhr.responseText);
             alert(xhr.status);
    }).done(function(data){
             alert(data);
    });

Also, inside my http://fullurlpath.com/php/myphppagedata.php I have
header('Access-Control-Allow-Origin: *');

A: http://en.wikipedia.org/wiki/Same_origin_policy
http://bob.ippoli.to/archives/2005/12/05/remote-json-jsonp/

A: Instead of requesting it with your client's browser using jQuery, I would make a page on your own domain, for instance call it request.php with:
echo file_get_contents("http://fullurlpath.com/php/myphppagedata.php");

This way your server will request the resource, so that you won't have the same origin policy issues. Then ajax this file instead.
$.ajax({
    url: "request.php",
...

You can also use cURL instead of file_get_contents() for more elaborate functionality.


text:
Q: How would I build a Bootstrap React Modal using Scala Js React How would I create a Modal component from the React Bootstrap library using the Scala.js React library?

A: The fact that a Modal has to change state (show = true/false) to show/hide the dialog made the solution non-trivial. I resolved this by wrapping it in a component that had a Boolean state that could be changed - and when it needs to be shown/hidden I change state with effects impure.
Another issue was that if the Modal has buttons that need to change the state their event handlers need access to this state somehow. I resolved this issue by giving users of the component access to the Backend of the component on creation.
Here is my implementation of the Modal:
class Modal(bs: BackendScope[Unit, Boolean], onHide: => Unit, children: Modal => Seq[ChildArg]) {

  def render(show: Boolean) = {
    val props = (new js.Object).asInstanceOf[Modal.Props]
    props.show = show
    props.onHide = () => {
        dismiss()
        onHide
    }

    Modal.component(props)(children(this): _*)
  }

  def dismiss() = {
    bs.withEffectsImpure.setState(false)
  }
}

object Modal {

  @JSImport("react-bootstrap", "Modal")
  @js.native
  object RawComponent extends js.Object

  @js.native
  trait Props extends js.Object {
    var show: Boolean = js.native
    var onHide: js.Function0[Unit] = js.native
  }

  val component = JsComponent[Props, Children.Varargs, Null](RawComponent)

  type Unmounted = Scala.Unmounted[Unit, Boolean, Modal]

  def apply(onHide: => Unit = Unit)(children: Modal => Seq[ChildArg]): Unmounted =   {
    val component = ScalaComponent.builder[Unit]("Modal")
    .initialState(true)
    .backend(new Modal(_, onHide, children))
    .renderBackend
    .build
    component()
  }
}

And a Dialog object that uses it:
object Dialog {
  object Response extends Enumeration {
    type Response = Value
    val OK, CANCEL = Value
  }

  import Response._

  def prompt(title: String, body: String, okText: String): Future[Response] = {

    // Add an element into which we render the dialog
    val element = dom.document.body.appendChild(div(id := "dialog").render).asInstanceOf[Element]

    // Create a promise of a return and a method to send it
    val p = Promise[Response]
    def respond(ret: Response) = {
        // Remove the containing element and return the response
        dom.document.body.removeChild(element)
        p.success(ret)
    }

    Modal(respond(Response.CANCEL)) { modal =>

        // Function to dismiss the dialog and respond
        def quit(ret: Response) = {
            modal.dismiss()
            respond(ret)
        }

        // Create the components for our Modal
        Seq(
            ModalHeader(true,
                ModalTitle(title)
            ),
            ModalBody(body),
            ModalFooter(
                Button(variant = "secondary", onClick = () => { quit(Response.CANCEL) })("Cancel"),
                Button(variant = "primary", onClick = () => { quit(Response.OK) })(okText)
            )
        )
    }.renderIntoDOM(element).backend

    p.future
  }
}


text:
Q: I am trying to define some methods for my User schema but all of them are throwing that the method is not a function This is my first ever question on SO ,  so please forgive me incase of question format :)
in Schema
UserSchema.pre('save' , async function (next){
    this.password = await bcrypt.hash( this.password , 5)
    next()
})

UserSchema.method = {
    createJwt : function(){
        return jwt.sign({
            name:this.name ,  email: this.email , id:this._id
        } , process.env.jwt_secret)
    },
    checkPassword  : async function(pass){
        const isOk = await bcrypt.compare(pass,this.password)
        return isOk
    }
}

in Controller
const User = require('../database/schemas')

const createUser = async (req,res) => {
    const user = await User.create(req.body)
    const token = user.craeteJwt()
    res.status(StatusCodes.CREATED).json({
        username : user.name , email : user.email  , token
    })
}

in Route
router.route('/register').post(createUser)

//the error says 'data and salt argumets required' for registration and if i continue without bcrypt then the error says 'user.createJwt isn't a function'


text:
Q: download file by aws lambda I have few files in S3, need to download the same from an Angular download button as in zip format.
how to zip files from S3 in lambda and how to return the zip file as an attachment from lambda.

A: Much like a regular Python webservice route (like Flask or Django). You would use the boto package to download the files, zipfile to produce the .zip file in memory or in temporary storage, and send its bytes in the response with the appropriate Content-disposition header.
This is assuming you need to join multiple S3 files into a zip, dynamically, in the request. If the file you need to send is already in S3 and you need it as-is, you just need to return an HTTP response redirecting to an S3 presigned URL.

A: Updated the same with s3predesigned url.


text:
Q: Keystrokes sending incorrect identifier in Win32 So I am working on making a calculator with a GUI for a class project and I am currently working on setting up my input detection so I can filter out what keystokes I want to be included in user input and which I want to exclude. I have been debugging it along the way which has been going smoothly up until about 10 complies ago when the wParam value that gets passed in switched from being a Hex value to being a Dec value. I didn't make any significant changes between when it was sending the code in Hex and now as it sends it in Dec so I can't figure out why it changed, in fact I believe it changed after I finished writing a comment to myself in one of the functions I am filtering the message with so I'm pretty confused as to why it changed. The relevant code is posted below (I can't just undo the changes I made because at some point my IDE closed), if someone could tell me why it changed, how to change it back, and if I'm even filtering keystrokes the correct way that would be much appreciated.
The ShiftPressed variable is stored in the class that is using this WinProc method and is accessible to all of these functions. All the code below was working with the wParam being sent in Hex at one point but after I finished the longer comment in the CheckKeyForOp() method, the wParam started being sent in Dec.
LRESULT CALLBACK EditBoxClass::WinProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
    switch( msg )
    {
    case WM_KEYUP:
        if( wParam == VK_SHIFT )
            ShiftPressed = FALSE;
        return 0;
    case WM_KEYDOWN:
        if( wParam == VK_SHIFT )
        {
            ShiftPressed = TRUE;
            return 1;
        }
        else if( CheckKeyForNum( wParam ) )
            return 1;
        else if( CheckKeyForOp( wParam ) )
            return 1;
        else
            return 0;
...
}

BOOL EditBoxClass::CheckKeyForNum( WPARAM wParam )
{
    switch( wParam )
    {
    case 0x30: case VK_NUMPAD0:
    case 0x31: case VK_NUMPAD1:
    case 0x32: case VK_NUMPAD2:
    case 0x33: case VK_NUMPAD3:
    case 0x34: case VK_NUMPAD4:
    case 0x35: case VK_NUMPAD5:
    case 0x36: case VK_NUMPAD6:
    case 0x37: case VK_NUMPAD7:
    case 0x38: case VK_NUMPAD8:
    case 0x39: case VK_NUMPAD9:
    default: return FALSE;
    }
}

BOOL EditBoxClass::CheckKeyForOp( WPARAM wParam )
{
    switch( wParam )
    {
    case VK_OEM_2:                               // For both of these keys, VK_OEM_2: "/ and ?" and VL_OEM_MINUS: "- and _" the
    case VK_OEM_MINUS:                           // regular keystroke can be used in the calculator but the "second version"
        if( ShiftPressed == TRUE ) return FALSE; // denoted by holding the shift key during the keystroke, cannot be used; so filter.

    case VK_OEM_PLUS: // This key acts in the same way the VK_OEM_MINUS key does, having both "+/=" register under the
                      // VK code VK_OEM_PLUS, but both are operators used by the calculator so allow both

    case VK_ADD:      case VK_SUBTRACT:
    case VK_MULTIPLY: case VK_DIVIDE:
    case VK_DECIMAL:  case VK_OEM_PERIOD: return TRUE;
    default: return FALSE;
    }
}

A: Messages do not give you hex/decimal, they just give you binary numbers, which you can then interpret as hex/decimal as needed.
The only error I see in this code is that CheckKeyForNum() is not returning TRUE for allowed number keys:
BOOL EditBoxClass::CheckKeyForNum( WPARAM wParam )
{
    switch( wParam )
    {
    case 0x30: case VK_NUMPAD0:
    case 0x31: case VK_NUMPAD1:
    case 0x32: case VK_NUMPAD2:
    case 0x33: case VK_NUMPAD3:
    case 0x34: case VK_NUMPAD4:
    case 0x35: case VK_NUMPAD5:
    case 0x36: case VK_NUMPAD6:
    case 0x37: case VK_NUMPAD7:
    case 0x38: case VK_NUMPAD8:
    case 0x39: case VK_NUMPAD9:
        return TRUE;  // <-- add this
    default: return FALSE;
    }
}


text:
Q: How to deploy a vue project? I have been playing with the Vue  for few months and i really loved it. I am using the webstorm as an editor, it has all the pre-installed templates for the Vue and other frameworks and the development was really fun with the Vue. Anyway, when i decided to deploy the app on Heroku, it didn't work. When i run the project on my local machine it works fine but when i deploy on the Heroku, i get an empty page. I googled for the solution and i found out there should be some dist folder that i never had, even on my local machine i can't find this folder. For now, i have these folders:

My question, do i have to create DIST folder and move there the index.html and some other files?  Do i have to run the npm build(i did and nothing actully happened). Here is my p.json:
"scripts": {
        "postinstall": "npm install express",
        "start": "node server.js"
},
      "dependencies": {
        "vue": "^2.5.2"
},

so what i do wrong and how i make my app work?
Thx

A: You need to create a final version. If you use cli vue version 3, you can use command vue-cli-service build.
Link: https://cli.vuejs.org/guide/build-targets.html#library
After build project you can download folder dist in heroky (or example surge.sh) and visit you site online.
Good luck.


text:
Q: ember-cp-validations form error message not showing I am trying to validate input in a form using ember-cp-validations. The actual validation itself seems to be working, however I cannot get the error message to show on the template. I am fairly new to ember in general, and I am assuming that I am not correctly using the model in the v-get helper.
Here is my model:
import DS from 'ember-data';
import { validator, buildValidations } from 'ember-cp-validations';

const Validations = buildValidations({
    name: validator('presence', true),
})

export default DS.Model.extend(Validations, {
    name: DS.attr('string'),
});

Here is the action I am running in my controller when the form is submitted:
//tried to get character model here to make validation work
let character = this.get('model');

//create new character record to store
let newCharacter = this.store.createRecord('character', {
    name: name,
});

//validating here
newCharacter.validate()
    .then( ({validations}) => {
        console.log(validations)
        if(validations.get('isValid')) {
            console.log('form is valid')
            //record will be saved here
        }else{
            console.log('form is invalid')
        }
    })

In this action when the name field is empty it does say that the form in invalid as expected.
Lastly, I attempt to show the error here:
{{input type="text" class="form-control" value=name placeholder="Character Name" focus-out=(action (mut showNameError) true)}}
  {{#if showNameError}}
    <div class="error">
      {{v-get character 'name' 'message'}}
    </div>
  {{/if}}

The div is created here when you lose focus on the field, but the message never shows. From what I understand, the arguments for the helper here should be the model, the field you are validating, and then the message that is to be displayed. The fact that it knows the form is invalid, but the message never shows leads me to believe that I am misunderstanding something and not actually accessing the character model correctly in the v-get helper.
After reading around, and watching some tutorials on ember-cp-validations I still seem to be stuck. Any help would be appreciated.
Thanks in advance!
EDIT: I wanted to add some more information after trying for another several hours to solve this problem. I created a new action in my controller extremely similar to the example from the ember-cp-validations github page located here:
https://github.com/offirgolan/ember-cp-validations/blob/7433fdb2ce7d22f956ca97a9b3291fe9c6637446/tests/dummy/app/controllers/index.js
I have also made sure that I am importing and defining all of the necessary information in my model file. I have made it to look exactly like their example here:
https://github.com/offirgolan/ember-cp-validations/blob/7433fdb2ce7d22f956ca97a9b3291fe9c6637446/tests/dummy/app/models/user.js
When I run the action however, I am given the error model.validate is not a function. I do not understand why in their example they would be able to run validate on their model, but I would not be able to on mine. The more I try to resolve this, the more confused I become.


text:
Q: Listar os telefones na mesma linha eu tenho um banco de dados que tem as seguintes tabelas: contato, telefone e tabela contato_telefone já que a cardinalidade na minha aplicação tem que ser N:N. Quando eu faço um inner join, o retorno me traz, por exemplo, 3 registros se forem três telefones, 4 registros se forem 4 e assim por diante. Eu preciso agrupar os telefones em único registro, já que só essa informação muda, como por exemplo:

CREATE DATABASE Agenda;
USE Agenda;

CREATE TABLE contato(

 id_contato INT NOT NULL AUTO_INCREMENT,
 tipo_contato INT NOT NULL,
 nome_contato VARCHAR(50),
 empresa_contato VARCHAR(50),
 cargo_funcao VARCHAR(25),
 departamento VARCHAR(20),
 CONSTRAINT pk_contato PRIMARY KEY(id_contato)
);

CREATE TABLE telefone(

 codigo_telefone INT NOT NULL AUTO_INCREMENT,
 tipo_telefone INT NOT NULL,
 operadora VARCHAR(10),
 numero_telefone VARCHAR(20),
 CONSTRAINT pk_telefone PRIMARY KEY(codigo_telefone)
);

CREATE TABLE contatoTelefone(

 contato_telefone INT NOT NULL AUTO_INCREMENT,
 contato INT NOT NULL,
 telefone INT NOT NULL,
 CONSTRAINT pk_contato_telefone PRIMARY KEY(contato_telefone),
 CONSTRAINT fk_contato_fone FOREIGN KEY(contato) REFERENCES
 contato(id_contato),
 CONSTRAINT fk_fone_contato FOREIGN KEY(telefone) REFERENCES
 telefone(codigo_telefone)
);

E o select:
SELECT contato.*, telefone.*, contatotelefone.* FROM contato
INNER JOIN contatotelefone ON contato.id_contato =
contatotelefone.contato_telefone
INNER JOIN telefone ON contatotelefone.contato_telefone =
telefone.codigo_telefone;

Para ver como está a relação contato/telefone, ou só dou um select na tabela
contatotelefone:

SELECT * FROM contatotelefone;

Como posso fazer isso no mysql? Tem como resolver de forma dinâmica?
Obs.: cada contato pode ter no máximo 4 número de telefones registrados.
Desde já agradeço!


text:
Q: Count block of time I've been at this for days and so stuck! They want to know how many AM, PM and Evening sessions in April and how many total visits for the sessions
i.e.
Month: April
ct_AM_sess 19, #Visits 38
ct_PM_sess 21, #Visits 116
ct_Eve_sess 4, #Visits 23
I've tried to do it Crystal and even moved the data to excel.
select resourceid, ApptStart,datename(m,ApptStart) as daymonth,datename(dd,ApptStart) as day,
datename(yy,ApptStart) as year, count(AppointmentsId) As Visits,
CASE WHEN DATEPART(hour, ApptStart) BETWEEN 0 AND 12 THEN 'AM' END AS 'MORNING_SESSION',
CASE WHEN DATEPART(hour, ApptStart) BETWEEN 13 AND 17 THEN 'PM' END AS 'AFTERNOON_SESSION',
CASE WHEN DATEPART(hour, ApptStart) BETWEEN 18 AND 24 THEN 'EVE' END AS 'EVENING_SESSION'
from appointments
where Resourceid = '50' and
datename(m,ApptStart) = 'April' and datename(yy,ApptStart) = '2014' --using timeframe for sample data
and status in ('Arrived','Completed')
group by resourceid, ApptStart,datename(m,ApptStart),datename(dd,ApptStart),datename(yy,ApptStart)

A: do a count on your case statements then groupy by whatever you need, this will give you a count on sessions since you didnt really let us know how to differenciate between visits and sessions
CASE WHEN DATEPART(hour, min(ApptStart)) BETWEEN 0 AND 12 THEN count(distinct appointmentid) END AS 'MORNING_SESSION',
CASE WHEN DATEPART(hour, min(ApptStart)) BETWEEN 13 AND 17 THEN count(distinct appointmentid) END AS 'AFTERNOON_SESSION',
CASE WHEN DATEPART(hour, min(ApptStart)) BETWEEN 18 AND 24 THEN count(distinct appointmentid) END AS 'EVENING_SESSION'