text:
Q: Is it bad to store server SSH keys in version control? We are writing scripts to automatically redeploy our servers.  These scripts are stored in version control.
Some of the servers require access to private Git repositories with access restricted by SSH.  Is it stupid to store private SSH keys in version control with the rest of the configuration scripts or is there an obvious alternative?
Ideally we would not need to create new keypairs every time we reinstalled a server.

A: Private keys can be compared with passwords, as if you have the private key you are able to access the systems this key is meant for.
It's only not a problem to put your keys into a version control system when only people who should have access to the keys have access to the version control system.

A: Ideally, I would separate the data from the code in the scripts you're writing. That means to store all your assets outside of the repository, probably in packages specific to your distribution (dpkg, RPM, etc.), signed using GPG. This will make your scripts more abstract, flexible and easier to maintain, but you will have to learn how to create packages for your distribution.
If you insist on using a key shared between all your servers, at least encrypt it and ask for a password during installation time. This way the password will not be stored in the repository and can be changed when necessary.
No matter how secure your repository is, you need to keep in mind that if you keep the private keys unencrypted in your (D)VCS, they will be distributed to all the people that will be developing as well. That, in my opinion makes containing any information leaks much more difficult. In this case, consider the situation when a member of your team leaves, you will need a way to revoke and issue a new set of keys anyway.
I would not easily discard the possibility of generating a new keypair for each new server. I guess that distribution of the public keys is what bothers your, but it is not an unsolvable task. Depending on your installation script, the generated public key can be displayed during the process and added to the repository's access lists.
Are you planning on using some kind of configuration management or instrumentation system to bootstrap and configure the servers? If not, I would strongly suggest you consider using one instead of developing a set of scripts. They provide a lot of other added benefits to server management, not only for this task in particular. Puppet, chef, cfengine, salt, bcfg2 (and a few others) and even some remote instrumentation systems like Fabric and Ansible make the process of exporting a set of public keys quite easy and pain-free.

A: You've to define your security level, is your repository secured? Is it more secured than your finals servers? At least same security?
You have to keep in mind, anybody accessing your repository will access your finals server.


text:
Q: Choosing weights for regression I want to weight observations for a regression. I'm worink in R and I'm using the method lmrob from the package robust.
As I saw in the description of the method, there is a parameter for the weights. I don't really know haw to define this array.
What I want is that the first 25% of the date should be more weightend and the last 25% should be less weighted.
Can someboe give me a hint?
Thank you!

A: The description of weights parameter in lmrob states that it is

vector of observation weights; if supplied, the algorithm fits to
  minimize the sum of a function of the square root of the weights
  multiplied into the residuals. The length of weights must be the same
  as the number of observations. The weights must be nonnegative and it
  is strongly recommended that they be strictly positive, since zero
  weights are ambiguous, compared to use of the subset argument.

and so it is defined as in other methods (e.g. lm), what means that it is used to provide some external weights such as survey weights. You use such weights to tell your function that some observations are "more important" than others in your data (e.g. they appear in your data less frequent than in population of interest). It is not connected anyhow to the robustness of this method and you do not have to provide this parameter - in most cases you leave it empty.
So if you want the first 25% of sample to have greater weight and the last 25% to have lower weight you define such weights that have this property and sum to 1. For example, if you have 4 observations, then the weights could be: $3/8, 2/8, 2/8, 1/8$. However generally, you do not use some arbitrary weights but you base them on some external criteria e.g. on how much undersampled some values are comparing to the population.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Docker do not use cache on Docker Tools on MacOS ElCapitan Using Docker-tools on MacOS ElCapitan, when I run docker build . or docker build -f Dockerfile . more than one time it rebuilds everything again and do not use the cache. With docker-compose build . is the same thing.
When I run it on Debian it works fine, with the cache. Maybe someone had the same problem, please share their solution .


text:
Q: Como fazer um print formatado? Olá. Desculpa a pergunta tão básica, mas comecei a mexer com python tem 1 semana.
Estou escrevendo um programa que grava os votos de candidatos em um arquivo binário. Mas, na hora de exibir não estou encontrando uma forma de deixar "bonito". Gostaria que aparecesse apenas o Nome e a Quantidade de votos. Segue código:
arquivo = open('C:\Users\Cassio\Documents\Python Programs\eleicao.dat', 'rb')
    print ('Os votos dos candidatos serao exibidos a seguir: ')
    for x in range(cont):
        aux = pickle.load(arquivo)
        print('O candidato(a): ', aux['NOME'], 'tem: ', aux['NUM_VOTOS'], 'votos.')
    arquivo.close()

Segue a saída do código:
Os votos dos candidatos serao exibidos a seguir:
('O candidato(a): ', 'CASSIO', 'tem: ', 50, 'votos.')

Gostaria que fosse exibido sem as aspas e parenteses. Desde já agradeço.
EDIT: consegui resolver de uma forma meio "grotesca", mas que funciona. Segue código:
print'Candidato(a): '+aux['NOME']+' - '+str(aux['NUM_VOTOS'])+' votos\n'

Saída:
Candidato(a): CASSIO - 300 votos

A: Poderia utilizar a função str.format (retro-compatível com python 2.6+).
print('O candidato(a): {} tem {} votos.'.format(aux['NOME'], aux['NUM_VOTOS']))

Uma versão compatível apenas para (Python 3.6+) seria utilizando a sintaxe de f-strings em python:
print(f'O candidato(a): {aux["NOME"]} tem {aux["NUM_VOTOS"]} votos.')


text:
Q: Combining various results from various queries/tables/views in summary table I've been pulling data from several different databases to create a summarised table of information all hinging on specific columns that they would have in common.
All of the tables have 3 columns in common:
Year
Month
Client
Other than this, they are a mixture of counts,sums,calculations and just general queries on various aspects of a client. I'm trying to map out a basic summary page on how each client is. My dream was to pull all of this into a centralised DB, with detailed information intact into tables. Then to have a series of views on each of these to summarise these tables 1 view per table. Then to have a summary table/view grouping all the views by year/month/client.
However i'm struggling to put everything together, I've got raw data in the tables like.
Ordernumber / Lines/ Client/Year/Month
with the view doing:
Count of orders / sum of lines / client/year/month.
However due to the variation with the views I can't do something like a UNION.
Example data (of the views)
View1

Year    Month   Count   Sum         ClientCode
2017    May     18      146         A
2017    May     7       110         B
2017    May     2       17          C

View2
Year    Month   CountOfOrders   CountOfFiles    SumOfLines  ClientCode
2017    May                 8              2           140    A
2017    May                 7              6           25     B

Dream goal would be:
Year Month ClientCode Count Sum CountOfOrders CountOfFiles SumOfLines
2017 May   A          18    146 8             2            140
2017 May   B          7     110 7             6            25
2017 May   C          2     17  0             0            0

Any advice would be great, I've tried doing a UNIONALL, so that I could do WHERE ALL_TABLES = Year 2017, Month = May. But realised that UNION's won't work as they merge rows now columns.

A: You can join views just like tables... Seems a LEFT JOIN is what you want here, with COALESCE() to handle nulls:
SELECT V1.Year, V1.Month, V1.ClientCode, V1.Count, V1.Sum,
       COALESCE(CountOfOrders,0) COALESCE(CountOfFiles,0) COALESCE(SumOfLines,0)
FROM View1 V1
LEFT JOIN View2 V2 ON V1.Year = V2.Year
                   AND V1.Month = V2.Month
                   AND V1.ClientCode = V2.ClientCode

Only thing to note, you will need more logic if not there are Year/Month/ClientCode combinations that exist in View2, and aren't in View1.


text:
Q: Switch Root Page in Ionic 2 Application I have a problem in switching root page in ionic 2 application.
My application has 2 pages called LoginPage and HomePage. When the user clicks logout button, he will have to navigate to LoginPage, and after successful login, he will have to navigate to HomePage.
I tried following:
This is my logout function which is in app.component.ts
public logOut() {
    this.nav.setRoot(LoginPage);
}

This is my login function in login.page.ts
public login() {
    this.navController.setRoot(HomePage);
}

But, the problem is...
If the user logout and login for the first time, it works fine. For the second time, the Homepage initiates twice. That means ngOnInit() method on HomePage gets called twice. For the third login, HomePage initiates three times.
When I debug the code, I found that the login function is getting called three times for the third login. But I couldn't find how it is getting called three times.
So now, I can't imagine why is this happening. Please anyone can give me an idea to overcome this problem.
Thanks.


text:
Q: how to add Additional information to the android ui element I'd like to     add to android widget more detailed description I.E I need an alternative to the HTML attribute aria-describedby for android.
e.G. I want to TB  announces exit button with additional description as "exit button press to close application", here "exit" i added by contentdescription
button.setContentDescription("exit");

but how can  i add more details: "press to close application"?

A: Short answer: You should not.

Longer answer: You should not because this can become pretty confusing for the user.
Reason 1:
Under "Settings -> Accessibility -> TalkBack -> Settings -> Verbosity" the user can decide to not let TalkBack read the element type.
Then your content description would not be read as "Exit, Button ... Double-tap to activate" but instead as "Exit".
So the information you have put into the second part is lost for the user.
Reason 2:
Depending on your target group the user might not even physically interact with your screen. Some users might use the voice-input or a switch-box as a proxy between them and the screen. TalkBack saying "Press" simply would be wrong or even confusing for the user, since they will never press anything on the screen.
Therefore Google has decided to use more generic terms and sentences, which you should keep using as well.
Reason 3:
A handicapped person that uses the TalkBack-reader a lot is used to much faster reading-speeds and they are used to the standard OS-elements. If you start to rename them, their usual flow gets interrupted and the user gets confused:
"ABC-Button ... Double-tap to activate"
"DEF-Button ... Double-tap to activate"
"GHI-Button ... Double-tap to activate"
"JKL-Button ... Press to close application" ... "Huh?!"
"MNO-Button ... Double-tap to activate"

Possible solution:
Do not give handicapped user (much) more information than a seeing user. Your elements should "speak for themselves" by having a generic but understandable description for seeing and non-seeing users.
If the user can deduce from the context that the button will close the application, then the text "Exit" on the button is sufficient.
Else you could name your button "Exit application", which will be the same text for the content description.


text:
Q: Get resulting SQL from wordpress functions I'm trying to do some inserting of posts but MySQL keeps dying. Solution is to actually run the insert/update queries manually through SQL than use wordpress. With this in mind, to save me rewriting huge chunks of logic, is there any way to dump the resulting SQL from the wp_insert_posts and other functions without actually running them?
I've tried the query save but it doesn't seem to save the insert queries. Ideally to a file but it'd be nice just to have a debug method to call to see the sql itself.

A: Edit wp-config.php and look for this line:
define('WP_DEBUG',false);
Change it to:
define('WP_DEBUG',true);
Then add this line right under it:
define('WP_DEBUG_LOG',true);
Run your offending command/operation and look for ./wp-content/debug.log.
That should give you more details on what is going wrong including the SQL error and some/all of the SQL command that caused the problem.
Make sure you turn off (set to false) both of those defines, ESPECIALLY if you do this on a live site.


text:
Q: HTML/CSS form as letter, textarea postioning i got problem with form who's look like letter, i want to create something like this
text                ......input.........
text                ......input.........
text                ......textarea......
......textarea............textarea......
......textarea............textarea......
......textarea............textarea......

for this moment, textarea going down after 3line text, or when i am trying do something else, its actually replace text on third line... how should i do this to make it worth? Ty for any respond


text:
Q: Proper way to zip xlsx-file from directory using Info-Zip's Zip utility I'm using Zip utility from the Info-Zip library to compress the tree of catalogs to get xlsx-file.
For that I'm using the next command:
zip -r -D res.xlsx source

source - contains the correct directory tree of the xlsx file.
But if you then look at the resulting file structure, the source directory will be included in the paths of all files and directories at the top level, and MS Office Excel will not be able to open this file. This is a well known problem. To avoid it zip.exe needs to be inside of the dest directory.
The problem is that I want to use the source code of this utility in my project, so this leads me to be unable to call my process, which will be responsible for compressing directories, to get xlsx files from these directories.
I've tried to find a place in the zip source code, where the parent catalog appending on the top-level happens. But seems
it is done implicitly.
Who can suggest how it can be done?


text:
Q: Fill section entries in table of contents with dots (using scrartcl) I use scrartcl and I want to …

*

*have list of figures and list of tables listed in the table of contents

*fill the space between sections and their pagenumbers with dots in the table of contents

*leave the rest of the table of contents unchanged.

So this is the desired output, generated using tocstyle (code below):

\documentclass[listof=totoc]{scrartcl}

% Problem: alpha version and warning.
\usepackage{tocstyle}
\newtocstyle[KOMAlike][leaders]{alldotted}{}
\usetocstyle{alldotted}

\begin{document}
\tableofcontents
\vfill\hrule
\listoffigures
\listoftables

\section{Test section}
\subsection{Test subsection}
\end{document}

Question: How can I get the same output without using tocstyle? I would like to avoid tocstyle because it always generates a warning that the package is an alpha version that may change in the future.
I would prefer a solution that is as minimal as possible, avoiding additional packages, manually adding LOF and LOT to the TOC, etc.
I already tried to use tocloft instead, but then other things break:

\documentclass[listof=totoc]{scrartcl}

% Problem: LOF and LOT not in TOC; different font style for sections.
\usepackage{tocloft}
\renewcommand{\cftsecdotsep}{\cftdotsep}
\renewcommand{\cftsecleader}{\cftdotfill{\cftsecdotsep}}

\begin{document}
\tableofcontents
\vfill\hrule
\listoffigures
\listoftables

\section{Test section}
\subsection{Test subsection}
\end{document}

A: Use the option toc=sectionentrywithdots. Though the manual says it is a beta feature, no warnings are generated.
\documentclass[listof=totoc,toc=sectionentrywithdots]{scrartcl}

\begin{document}
\tableofcontents
\vfill\hrule
\listoffigures
\listoftables

\section{Test section}
\subsection{Test subsection}
\end{document}


text:
Q: href with id of DOM element is not working with Angular I'm trying to implement sliding navigation using angular version 4.
 Click

 This is div

so , when anchor tag clicked it is realoading the complete page and rediercted to
http://localhost:4200#SlideTo.
any one can help

A: I have been through this problem before, and i solved it using this line.
 Click


text:
Q: Google App Engine queue.yaml not working in development server I can't get dev_appserver.py to recognize the custom queues I create using queue.yaml. They don't appear in http://localhost:8000/taskqueue, and when I try to add a task to them I get UnknownQueueError. It works fine in the production environment.
I'm using python 2.7 on Windows 10.
queue.yaml

total_storage_limit: 5G
queue:
- name: not-queue-a
  bucket_size: 500
  rate: 10/s
  retry_parameters:
  task_retry_limit: 2
  min_backoff_seconds: 10
  target: msnot
- name: ui-worker
  target: msbui
  bucket_size: 200
  rate: 1/s
  retry_parameters:
  task_retry_limit: 4
  min_backoff_seconds: 1

My project structure is like this:

    |-- root
        |-- queue.yaml
        |-- index.yaml
        |-- dispatch.yaml
        |-- cron.yaml
        |-- microservice1
            |-- app.yaml
            |-- microservice1.py
        |-- microservice2
            |-- app.yaml
            |-- microservice1.py
        |-- microservice3
            |-- app.yaml
            |-- microservice3.py
        |-- microservice4
            |-- app.yaml
            |-- microservice4.py

I tried adding a copy of queue.yaml to the microservice-subfolders, but I still had the same issue. I've also restarted dev_appserver.py several times.

A: I had the same problem when I split my app into several services, the dev_appserver.py didn't quite catch up with the multi-services app. I worked around it by symlinking the queue.yaml file inside each of the services:
    |-- microservice1
        |-- app.yaml
        |-- microservice1.py
        |-- queue.yaml -> ../queue.yaml

It might only be required for the default service, but I'm not entirely sure of this, I didn't try it.
Note: I applied a similar approach for other app-level config files. See also Can a default service/module in a Google App Engine app be a sibling of a non-default one in terms of folder structure?


text:
Q: How can i reset all commits in repository without losing local changes Problem
I clone my old resportory where I keep config but whene I clone it new resposytory inherited somehow old reposytory commits :P . I want to delete this commits to start with a clean slate.


text:
Q: Connecting to Ingres DB from .net Core 2.1 I am developing a .net core 2.1 API that needs to connect to an older Ingres DB.
In previous .net frameworks I have been able to use Ingres Client found here https://www.nuget.org/packages/Ingres.Client/1.0.1
However this is not compatible with .net core 2.1 and the last update was about 3 years ago! Some key files are missing which is causing runtime errors.

Exception thrown: 'System.IO.FileNotFoundException' in System.Private.CoreLib.dll

So I just wondered if anyone had any experience with connecting to Ingres from .net core 2.1 and knew of a way to do it. Or any suggestions or strategies to try would be appreciated.
Regards.

A: I managed to do this with Ingres ODBC driver. Available drivers in Windows are accessible from: Control Panel > Administrative Tools > ODBC Data Source Administrator. Select 'Add...' to find the name of installed Ingres ODBC driver (e.g. 'Ingres XC').
var connectionString = "Driver=Ingres XC;Server=@<db-server-ip>,tcp_ip,II;UID=ingresuser;PWD=password;database=mydatabase";

using (OdbcConnection connection = new OdbcConnection(connectionString))
{
// ...
}


text:
Q: How to distinguish the screen on/off status while incoming call? My app uses the TelephonyManager.ACTION_PHONE_STATE_CHANGED for some actions. But I want a different action while the phone rang when the user was present (screen was on) and different action when the user was not present (screen was off). I tried the isScreenOn() method just in the beginning of onReceive (because when screen is off and there is incoming call, the screen stays off for a short while). No luck however - sometimes it works, sometimes not. The broadcast is asynchronous with the screen state...
public void onReceive(Context context, Intent intent) {
    pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    Boolean screenOn = pm.isScreenOn();
    Log.w(TAG, "Screen on is " + screenOn.toString());

How could I change my code to truly determine if the phone was sleeping when the call arrived?

A: Ok, I got the answer which satisfies me:
public void onReceive(Context context, Intent intent) {
    KeyguardManager kg = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
    Boolean screenBlocked = !kg.inKeyguardRestrictedInputMode();
    Log.w(TAG, "Screen lock is " + screenBlocked.toString());

Such solution gives information if the screen is locked. And, in my case, it is enough - when screen is locked during the incoming call -  it means that there was no user.


text:
Q: Changing the data structure of my class to work with strings I have a working int Topological sorting class. but I need to change my methods to take string "a", "b" instead of integers, but the problem is that the methods that also count the nodes are also being used for the arraylist so I've been trying for weeks just to change  or  but it always says bad conversion, or cannot be converted to int, even when there isn't an int in my class(at one point) so my problem is all I want is for it to say q.addEdge("a","b");
here is my code, any help at all maybe to turn this into nodes or strings and I would be forever in your debt.
// A Java program to print topological sorting of a graph
// using indegrees
import java.util.*;

//Class to represent a graph
class Graph
{
int V;// No. of vertices

//An Array of List which contains
//references to the Adjacency List of
//each vertex
List <Integer> adj[];
public Graph(int V){//constructor
    this.V = V;
    adj = new ArrayList[V];
    for(int i = 0; i < V; i++)
        adj[i]=new ArrayList<Integer>();
}
// function to add an tasks to tree
public void addEdge(int u,int v){
    adj[u].add(v);
}
// prints a Topological Sort of the complete graph
public void topologicalSort(){
    // Create a array to store indegrees of all
    // vertices. Initialize all indegrees as 0.
    int indegree[] = new int[V];

    // Traverse adjacency lists to fill indegrees of
    // vertices. This step takes O(V+E) time
    for(int i = 0; i < V; i++){
        ArrayList<Integer> temp = (ArrayList<Integer>) adj[i];
        for(int node : temp){
            indegree[node]++;
        }
    }

    // Create a queue and enqueue all vertices with
    // indegree 0
    Queue<Integer> q = new LinkedList<Integer>();
    for(int i = 0;i < V; i++){
        if(indegree[i]==0)
            q.add(i);
    }
    // Initialize count of visited vertices
    int cnt = 0;
    // Create a vector to store result (A topological
    // ordering of the vertices)
    Vector <Integer> topOrder=new Vector<Integer>();
    while(!q.isEmpty()){
        // Extract front of queue (or perform dequeue)
        // and add it to topological order
        int u=q.poll();
        topOrder.add(u);
        // Iterate through all its neighbouring nodes
        // of dequeued node u and decrease their in-degree
        // by 1
        for(int node : adj[u]){
            // If in-degree becomes zero, add it to queue
            if(--indegree[node] == 0)
                q.add(node);
        }
        cnt++;
    }
    // Check if there was a cycle
    if(cnt != V){
        System.out.println("There exists a cycle in the graph");
        return ;
    }//else{System.out.println("no cycle in the graph");}
    // Print topological order
    for(int i : topOrder){
        System.out.print(i+" ");
    }
 }
}
// Driver program to test above functions
class Main
{
public static void main(String args[])
{
    Graph g=new Graph(8);//must be max number of letters+1
    Node one=new Node("a");
    Node two=new Node("b");
    g.addEdge(one,two);

   /*
    g.addEdge(1, 4);
    g.addEdge(2, 5);
    g.addEdge(7, 5);
    g.addEdge(5, 4);
    g.addEdge(3, 4);
    g.addEdge(4, 6);
    g.addEdge(2, 4);*/
    System.out.println("Following is a Topological Sort");
    g.topologicalSort();
 }
 }

A: You could add a type to Graph, then it would support any type. For example:
class Graph<T> {
    private final Map<T, List<T>> edgesByRoot = new HashMap<>();

    public void addEdge(T a, T b){
        getEdges(a).add(b);
    }

    private List<T> getEdges(T root) {
        List<T> edges = edgesByRoot.get(root);
        if (edges == null) {
            edges = new ArrayList<>();
            edgesByRoot.put(root, edges);
        }
        return edges;
    }
}

class Main {
    public static void main(String args[]) {
        Graph<String> g=new Graph<>();
        g.addEdge("a", "b");

        System.out.println("Following is a Topological Sort");
        g.topologicalSort();
    }
}

From there, implement your topological sort to use the Map instead of an array for edge lookups via getEdges and build out a List<T>. Make sure you also use .equals instead of == where necessary, and don't use mutable types for T (String is an immutable type, so you're good there).
One other note, don't use Vector. It's exactly the same as an ArrayList but with synchronized keywords on all its methods. It's really not that useful, and it's recommended to use Collections.synchronizedList if you really need it (which your code does not since it's not multi-threaded).
References

*

*Generic Types Java Trail (docs.oracle.com)

*Map interface Java Trail (docs.oracle.com)

*Why is Java Vector class considered obsolete or deprecated? (StackOverflow)


text:
Q: How to tell whether two folders (including content inside) are different fast? Given a path, I want to record the folder's unique characteristics, so that next time I check these characteristics, I can tell if the folder has been changed or not.
The solution I can think of is to recursively record all the files' path and checksum in string, and then calculate the checksum of the string.
I wonder if there's more efficient way to do this.

A: You could save some calculations by looking at the mtime of the files inside the folder instead of calculating their hash.
You'd still need to do it for all the files inside the folder, as altering a file does not update the mtime of the folder containing it.


text:
Q: Error converting PMML XML Schema (xsd) to C# Object using Xsd2Code I tried to create C# object from PMML 3.0 Schema (PMML 3.0 Schema) using Xsd2Code (Xsd2Code), but all I got was following error:

Error: Multiple definition of element 'http://www.dmg.org/PMML-3_0:Array' causes the content model to become ambiguous. A content model must be formed such that during validation of an element information item sequence, the particle contained directly, indirectly or implicitly therein with which to attempt to validate each item in the sequence in turn can be uniquely determined without examining the content or attributes of that item, and without any information about the items in the remainder of the sequence.

I am pretty sure this specification is correct. I also tried xsd.exe from VS, but without success.
Is there any other way to do such conversion?
Thanks for any help!

A: I found this old question: XSD sequence shows as abiguous!, so I checked the xsd http://www.dmg.org/v3-0/pmml-3-0.xsd and I found this part:
<xs:element name="ContStats">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="Extension" minOccurs="0" maxOccurs="unbounded" />
        <xs:element minOccurs="0" maxOccurs="unbounded" ref="Interval" />
        <xs:group minOccurs="0" ref="INT-ARRAY" />
        <xs:group minOccurs="0" maxOccurs="2" ref="NUM-ARRAY" />
      </xs:sequence>
      <xs:attribute name="totalValuesSum" type="NUMBER" />
      <xs:attribute name="totalSquaresSum" type="NUMBER" />
    </xs:complexType>
  </xs:element>

Just like in the answer of the question I linked, if the validator finds an Array can't tell if it is an INT-ARRAY or one of the maximun 2 NUM-ARRAY.
I can't tell if there is a way to do this conversion without modifying the xsd.


text:
Q: RT6224D-based step down circuit yields 0V - why? We received a set of prototype boards. They have a DC power supply input feeding into a step-down converter, which is built around an RT6224D. It is supposed to deliver 5.0V. The circuit is almost exactly straight from the datasheet, just that the designer chose a 3.3 uH inductivity.
Here is what we have:

This is the Typical Application Circuit from the datasheet:

The problem is, I get exactly 0V at the output. And I can not figure out why. Even on a quick breadboard reproduction of the same circuit, I still get 0 output. I have this feeling there must be something very obvious.
Do you have any idea what is going on here? I greatly appreciate your help!
Edit to answer SamGibson's questions:
(a) PCB layout:

(b) The populated PCB, sorry I don't have an unpopulated board:

(c) Someone else did the design and the layout, I am just trying to make it work. The boards came from a domestic manufacturer. I talked with the designer about the issue, he said U6 it must be a faulty chip. On all 5 boards. So I replaced it with a new one, same result.
(d) I don't know where the board manufacturer got the components initially, my replacement was from Digikey.
(e) I can't find any usable signal to scope, VIN and EN are at 12V, all other pins show a flat lines at 0V.
(f) The inductor is an ASPI-4030S-3R3M-T.
Thanks!
Edit 2:
This is my "hotfix" based on the feedback by Randy Nuss and Spehro Pefhany. The originial RT6224D did not work any more, but with a new chip and the 100k resistor, I get the desired 12V:

A: I'm fairly certain you're blowing up the chip by applying 12V to the EN pin. According to the data sheet the ABS MAX rating on that pin is 6V.  Typically one would use a voltage divider to attenuate the input voltage to a value that would yield around 3V on the EN pin with 12V applied.


text:
Q: break the for loops in matlab I have written a matlab code and want to terminate the code after finding the first one in the matrix. BUT, it continues until the last one and then break works. What is the problem?
% The code is as follows:
     for i=1:n
        for j=1:m
            if (bw(i,j)==1)  % element with value one
                p1(1)=i;p1(2)=j;
                % fprintf('value of a: %d\n', i ,j)
                sprintf('Found first one in the loop!!')
                break;    % terminate
            end
        end
    end

A: It looks like you want to find the first 1 value in a matrix, searching in row-major order (increase column index first, then row index). You can do that without loops using the find function:
M = [0 1; 1 1]; %// example matrix
v = 1; %// value you want to find
[col, row] = find(M.'==v, 1);

Note that the matrix is transposed and the order of the two outputs of find is reversed. This is because Matlab finds elements in column-major order (increase row index first, then column index).
In the above example, with
M =
     0     1
     1     1

the result is
row =
     1
col =
     2

A: Since break exits only the inner loop (the one that runs with j) but not the outer loop (the one that runs with i), you can tackle the problem by using a simple boolean which you initially set as false.
When you break the inner loop, change it to true and then check (in the outer loop) if such boolean is true. If it is, also break the outer loop.
IWantToBreak=false;
for i=1:n
    for j=1:m
        if (bw(i,j)==1)  % element with value one
            p1(1)=i;p1(2)=j;
            % fprintf('value of a: %d\n', i ,j)
            sprintf('Found first one in the loop!!')
            IWantToBreak=true;
            break;    % terminate
        end
    end
    if IWantToBreak==true
        break;
    end
end


text:
Q: Basic recurly.js testing Trying to work out the basic recurly.js demo here: https://github.com/recurly/recurly-js-examples
Only things I'm changing in the demo code are recurly public key on the form page, and my apiKey, subdomain, and plan_code on the new subscription page.  I can tell the form is hitting my recurly account correctly because if I change my billing requirements in Recurly to require a billing field (like City/State/etc.) without actually passing that form field it throws an error.
However, I'm not seeing any of these new test subscriptions/transactions/etc. in my Recurly dashboard.
I'm a js novice at best, so I feel like I'm just missing something really obvious in my test environment here.

A: I know this reply is a bit late.  But, here is my understanding of the process:

*

*At the time you submit your checkout form, recurly.js intercepts, encrypts, and sends any credit card (and other form) details directly to recurly, from your client-side js code.

*recurly.js then receives a unique token back (still entirely client side on your end).

*Pass the recurly-generated token to your own server's backend code (PHP, Ruby, etc).  You would not actually send any cc details along with the form at this point.

*From your backend code, issue a 'Create Subscription' call to the Recurly API, providing the token.

At that point, I believe Recurly makes a definite association between the CC and subscription, by using the token.
If you never complete the server-side part of this (steps 3 & 4), then Recurly would have no way to associate the CC details with any API entity/object (ie. Subscription, Customer, etc).  There would be no way of displaying these CC details on a dashboard of transactions, since the CC details alone are not a transaction.


text:
Q: How to bind dropdown values from Database through stored procedure in Strongly typed views in MVC..? I have a strongly typed view as shown below:

      @Html.LabelFor(model => model.Text, htmlAttributes: new { @class = "control-label col-md-2" })

             @Html.DropDownListFor(model => model.Text, "Drop");    @*Error Line*@

               @Html.ValidationMessageFor(model => model.Text, "", new { @class = "text-danger" })

With model Class DropdownCheck like below:
 public class DropdownCheck
 {
    public string Text { get; set; }
    public String Test { get; set; }
 }

Basically, I don't want to hard-code values to view through list items,but wants to bind it from database through stored procedure.
So, For that I have controller like below
   [HttpGet]
    public ActionResult Dropdown()
    {
        BusDataContext dtnew=new BusDataContext();
        ViewBag.Drop = new SelectList(dtnew.Bind_Dropdown().ToList(), "BusSrlNo", "Name");
        return View();
    }

Also storing dropdown id,text in ViewBag as above.
where Bind_Dropdown() is like below
  public IEnumerable<DropdownValues> Bind_Dropdown()
   {
       var res = dt.Get_Bus_Dropdown().ToList();
       List<DropdownValues> drop = new List<DropdownValues>();

       for (var i = 0; i < res.Count; i++)
       {
           DropdownValues name = new DropdownValues();
           name.drpbusid = Convert.ToInt32(res[i].BusSrlNo);
           name.drpbusname = Convert.ToString(res[i].Name);
           drop.Add(name);
       }
       return drop;
   }

where DropdownValues is a class like below:
   public class DropdownValues
{
    public int drpbusid { get; set; }
    public string drpbusname { get; set; }
}

Stored procedure returns dropdown value and Text as BusSrlNo and Name.
After doing all these stuff,getting error compilation like below:
:

CS1928: 'System.Web.Mvc.HtmlHelper' does not
  contain a definition for 'DropDownListFor' and the best extension
  method overload
  'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper,
  System.Linq.Expressions.Expression>,
  System.Collections.Generic.IEnumerable)'
  has some invalid arguments

A: 1) Change this line:
ViewBag.Drop = new SelectList(dtnew.Bind_Dropdown().ToList(), "BusSrlNo", "Name");

Into this:
ViewBag.Drop = new SelectList(dtnew.Bind_Dropdown().ToList(), "drpbusid", "drpbusname");

2)Change this line:
@Html.DropDownListFor(model => model.Text, "Drop");

Into this:
@Html.DropDownList("anyName", ViewBag.Drop as SelectList)

I've replicated your error on my side and those are the only two changes I had to make to get it working.I hope it helps you.

A: I am not familiar with the signature you are trying to use (can .NET bind a value from a string like this?)
@Html.DropDownListFor(model => model.Text, "Drop");    @*Error Line*@

What happens if you switch this to:
@Html.DropDownListFor(m => m.Text,
 ((IEnumerable<SelectListItem>)ViewBag.Drop.Items))


text:
Q: i want to remove the hash function and use the same code to store password as varchar I have the below code from a tutorial but i want to understand its working and hence want to simplify it. I dont want the password to be stored with encryption, just plain text. what are the changes i need to make? will i need to make any changes in corresponding java file, that uses the json object/array?
<?php

class DB_Functions {

private $db;

//put your code here
// constructor
function __construct() {
    require_once 'DB_Connect.php';
    // connecting to database
    $this->db = new DB_Connect();
    $this->db->connect();
}

// destructor
function __destruct() {

}

/**
 * Storing new user
 * returns user details
 */
public function storeUser($name, $email, $password) {
    $uuid = uniqid('', true);
    $hash = $this->hashSSHA($password);
    $encrypted_password = $hash["encrypted"]; // encrypted password
    $salt = $hash["salt"]; // salt
    $result = mysql_query("INSERT INTO users(unique_id, name, email, encrypted_password, salt,created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$salt', NOW())");
    // check for successful store
    if ($result) {
        // get user details
        $uid = mysql_insert_id(); // last inserted id
        $result = mysql_query("SELECT * FROM users WHERE uid = $uid");
        // return user details
        return mysql_fetch_array($result);
    } else {
        return false;
    }
}

/**
 * Get user by email and password
 */
public function getUserByEmailAndPassword($email, $password) {
    $result = mysql_query("SELECT * FROM users WHERE email = '$email'") or die(mysql_error());
    // check for result
    $no_of_rows = mysql_num_rows($result);
    if ($no_of_rows > 0) {
        $result = mysql_fetch_array($result);
        $salt = $result['salt'];
        $encrypted_password = $result['encrypted_password'];
        $hash = $this->checkhashSSHA($salt, $password);
        // check for password equality
        if ($encrypted_password == $hash) {
            // user authentication details are correct
            return $result;
        }
    } else {
        // user not found
        return false;
    }
}

/**
 * Check user is existed or not
 */
public function isUserExisted($email) {
    $result = mysql_query("SELECT email from users WHERE email = '$email'");
    $no_of_rows = mysql_num_rows($result);
    if ($no_of_rows > 0) {
        // user existed
        return true;
    } else {
        // user not existed
        return false;
    }
}

/**
 * Encrypting password
 * @param password
 * returns salt and encrypted password
 */
public function hashSSHA($password) {

    $salt = sha1(rand());
    $salt = substr($salt, 0, 10);
    $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
    $hash = array("salt" => $salt, "encrypted" => $encrypted);
    return $hash;
}

/**
 * Decrypting password
 * param salt, password
 * returns hash string
 */
public function checkhashSSHA($salt, $password) {

    $hash = base64_encode(sha1($password . $salt, true) . $salt);

    return $hash;
}

}

?>

A: public function storeUser($name, $email, $password) {
    $uuid = uniqid('', true);
    $result = mysql_query("INSERT INTO users(unique_id, name, email, password, salt,created_at) VALUES('$uuid', '$name', '$email', '$password', NOW())");
    // check for successful store
    if ($result) {
        // get user details
        $uid = mysql_insert_id(); // last inserted id
        $result = mysql_query("SELECT * FROM users WHERE uid = $uid");
        // return user details
        return mysql_fetch_array($result);
    } else {
        return false;
    }
}

You need to modify the variable and leave out the hashing function, you also need to modify the name of the field you insert to from encrypted_password to password and since you won't be using the salt anymore, you don't insert it.
With all that being said, you must understand that hashing passwords is the number one rule of storing password, the number one rule of building web application. YOU MUST HASH PASSWORDS FOR THE SECURITY OF YOUR USERS


text:
Q: If x is real , the numbers $ 5^{1+x} + 5^{1-x} $ , a/2 , $ 25^x + 25^{-x} $ form an A.P. then to which interval must ' a ' belong to? A) [ 1 , 5 ]
B) [ 2 , 5 ]
C) [ 5 , 12 ]
D) [ 12 , $ \infty $ ]
My progress so far :
Let  $ 5^{x} = y $
Since they are in AP so ,
=> $ 5y $ + $ 5\over y $ + $ y^2 $ + $ 1\over (y^2)  $ = a
=> $ {5y^3 + 5y + y^4 + 1 }\over (y)^2 $ = a
As you can see , It becomes a mess . How do I solve it with a better approach .

A: For questions like this I try to find useful values of $x$.  The three that immediately suggest themselves to me here are $x=0, x\to +\infty,x \to -\infty$  If $x=0$, we need $10, a/2, 2$ to form an AP, which works with $a=12$.  That rules out two of your choices. Now consider what happens when $x$ is large and positive and again when $x$ is large and negative.

A: As they are in AP, we have
$$
a = 5^{1+x} + 5^{1-x} + 25^{x} + 25^{-x}.
$$
So say $5^x = t$, then,
$$
a = 5t + \frac{5}{t} + t^2 + \frac{1}{t^2}.
$$
Now
$$
5t+\frac{5}{t} \geq 10
\qquad\text{and}\qquad
t^2+\frac{1}{t^2} \geq 2
$$
by the AM-GM inequality.
So $a \ge 12$, are the values that $a$ can take.
Hope that helps.


text:
Q: Rails Carrierwave if (:medium).present? I am currently in the process of trying to move users from version 1 to version 2 of my app. Version 2 is a complete rewrite.
I would like to show the :medium version ONLY if it exists. If it doesn't exist then I would like to show :small.
How would I go about doing this?

A: avatar.medium.file.exists? is the test you are looking for.

A: This is a pretty old question but here is what I would do
as I really like draper, I would create a method in the associated Decorator, but it can also simply be a classic helper method such as
def avatar_for(user)
  avatar = user.avatar
  avatar.medium.url || avatar.small.url
end

A: I got this to work by testing the size not equal to zero
if avatar.medium.size == 0

A: The correct answer is:
if asset.file.medium.file.exists?
  #show medium version
else
  #show small version
end

where file = mounted_uploader and asset = model


text:
Q: Notificación IPN de pago realizado en checkout basico modo sandbox no llega Bueno mi consulta es que no me llega la notificación IPN de pago realizado en checkout basico modo sandbox. Llegan de "merchant_order", pero no de "payment". Tengo configurada la URL en https://www.mercadopago.com.ar/ipn-notifications , con los dos cuadritos chequeados de "payment" y "merchant_order".
Sin embargo sólo me llegan notificaciónes de "merchant_order", que es cuando el comprador hace click en el link para pagar, antes de hacer el pago.
Probé de mil maneras diferentes, agregué la url "notification_url" en $preference_data, usé 2 servidores distintos para recibir la notificación, probé con modo $mp->sandbox_mode activado y desactivado, usé todas las tarjetas de sandbox para pagar (el pago se hacía correctamente), habilité recibir datos tanto de POST como GET, pero el IPN de pago realizado nunca llegó.
Supuse que sería un tema de mercadopago que para sandbox no manda IPN de "payment", pero sí en producción, así que me dispuse a hacer las pruebas fuera del sandbox, usando mi cuenta personal para pagar, y la cuenta de la página para cobrar, por una compra de 1 peso. Pero creo que los sistemas de mercadopago de alguna manera detectan que soy la misma persona y no me permite hacer el pago.
En definitiva no tengo ninguna manera de probar y por consiguiente desarrollar con las herramientas que mercadopago proporciona y no puedo avanzar...
Espero que me puedan ayudar, saludos.

A: Esto me pasó cuando hice la integración en diciembre 2016 y aparentemente sigue igual... Fijate que en la documentación ellos mismos aclaran lo siguiente:

Podés probar la integración en producción creando usuarios y tarjetas de prueba. Revisá estos dos links que te van a servir:

*

*Crear usuarios de PRUEBA en entorno de PRODUCCIÓN

*Crear TARJETAS de PRUEBA en entorno de PRODUCCIÓN
Al estar trabajando en entorno de producción, y no sandbox, vas a tener que crear dos usuarios de prueba, ya que un comprador de prueba NO le puede pagar a un usuario real, obviamente.
Un usuario de prueba actuará como vendedor y otro usuario de prueba actuará como comprador.
(Es decir, en tu servidor, donde recibís la notificación, tenés que hacer la consulta del payment usando las credenciales del usuario de prueba vendedor y apuntando a producción).
Una vez que tenés todo funcionando pipí cucú, lo único que hacés es cambiar las credenciales del usuarios de prueba vendedor, por las credenciales de tu usuario real de MP.
Cualquier cosa avisame y te doy una mano.
Saludos!


text:
Q: Problem receiving data from API and assigning it to model I have a method that makes an asynchronous call to an API, the structure of the data that the API returns is identical to the model I want to assign. However it never loads the object. The data is always null, but if there is a response from the API and if it delivers the data, but does not assign it to the variable:"podcast"
The purpose of this method is to pass the data to view.
(I use .Net core 5 in a Web Project)
this is my method
        public async Task<IActionResult> details(int id)
    {
        if (id != 0)
        {
            //Read Service for config Metas
            PPodcast podcast = new PPodcast();

            using (var httpClient = new HttpClient())
            {
                using (var response = await httpClient.GetAsync($"{_storageOption.devVirtualPath}{_endpoints.ObtenerPodcast}" + id))
                {
                    string apiResponse = await response.Content.ReadAsStringAsync();
                    podcast = JsonConvert.DeserializeObject<PPodcast>(apiResponse);
                }
            }
            ViewBag.idPodcast = id;
            return View(podcast);

        }
        return View(null);
    }

This is my model:
 public class PPodcast
{
    public int id { get; set; }
    public int idSeccion { get; set; }
    public string titulo { get; set; }
    public string descripcion { get; set; }
    public string contenido { get; set; }
    public string embeb { get; set; }
    public string imagenRef { get; set; }
    public string tags { get; set; }
    public string fecha_PE { get; set; }
    public DateTime Fecha { get; set; }
    public string Hora { get; set; }
    public string urlPodcast { get; set; }
    public string SeccionNombre { get; set; }

}

A: if all of your responses have the same shape, it is better to create a generic class that contains the classes you want
example:
public class Response<T>
{
    public T Data {  get; set; }
    // additional items like errors and such
}

then in your deserilizer you would use it as such
podcast = JsonConvert.DeserializeObject<Response<PPodcast>>(apiResponse).Data;


text:
Q: cgo and pkg-config I want to run GraphicsMagick with cgo.
/*
#cgo pkg-config: GraphicsMagick-config

#include <magick/api.h>

static int gm(int argc, char **argv) {
    int status;
    status = GMCommand(argc, argv);
    return 1-status;
}
*/

then I run 'go install', it says:
# pkg-config --cflags GraphicsMagick-config
Package GraphicsMagick-config was not found in the pkg-config search path.
Perhaps you should add the directory containing `GraphicsMagick-config.pc'
to the PKG_CONFIG_PATH environment variable
No package 'GraphicsMagick-config' found
exit status 1

but I run 'pkg-config GraphicsMagick-config' in shell and it's ok.

A: The GraphicsMagick-config script is a separate program rather than a pkg-config resource, which explains the problem.
Also, running pkg-config with a non-option argument seems to fail without printing an error message, which might have confused you.
In addition to this script though, the library does install a GraphicsMagick.pc data file for pkg-config.  So you should be able to get your code running with:
#cgo pkg-config: GraphicsMagick


text:
Q: Comparing geometric intersection numbers.  Let $a$, $b$, and $c$ be simple closed curves in an orientable surface $S$ such that
$i(a,b) \geq 2$, $i(a,c) \geq 1$, and $i(b,c) = 0$.
Let $w$  be a nontrivial element of the free group $\langle T_a,T_b \rangle$ which is different from $T_a^p$, $p$ nonzero integer, and set $x = w(a)$.
If $i(a,x) > i(b,x)$ and $n$ is a nonzero integer, is there a way to compare $i(a,T_c^n(x))$ and
$i(b,T_c^n(x)) = i(b,x)$ ?


text:
Q: Live Image resized and mover (JQuery) I need a plugin or a sample code because I've a div with a background and the user once has uploaded his own image he must be able to live resize it and move above the background provided by me.
Any idea?
Thanks!

A: What about this one: http://www.webresourcesdepot.com/jquery-image-crop-plugin-jcrop/, or this one is maybe better http://odyniec.net/projects/imgareaselect/
Hope it helps.


text:
Q: Why wsimport tool for generating files from wsdl file not working showing error code 400 I am working on webservices to integrate with the application and as a newbee needs more input.
Can any anyone tell me the issue why wsimport throws error on console : Server returned HTTP response code: 400 for URL:
http://localhost:8084/service/HelloWorld.wsdl

Following is my code below :
HelloWorld.java
//Service Endpoint Interface
@WebService
@SOAPBinding(style = Style.RPC)
public interface HelloWorld {

    @WebMethod String getHelloWorldAsString(String msg);

}

HelloWorldImpl.java
@WebService(endpointInterface = "com.pack.service.HelloWorld")
public class HelloWorldImpl implements HelloWorld{

    @Override
    public String getHelloWorldAsString(String msg) {
        return "Hello, "+msg+ "  How are you ?" ;
    }

}

HelloWorldPublisher.java
//Endpoint Publisher
public class HelloWorldPublisher {

    public static void main(String[] args){
        System.out.println("Webservice Running ... ");
        Endpoint.publish("http://localhost:8084/service/HelloWorld", new HelloWorldImpl());
    }

}

Now, when i want to generate stub files from wsdl file. It gives the following error :
Note : Using command prompt and entering the following on command line :
wsimport -keep http://localhost:8084/service/HelloWorld?wsdl

At command line it shows >>

D:\Personal\WebService>wsimport -keep http://localhost:8084/service/HelloWorld?wsdl
parsing WSDL...

[ERROR] Server returned HTTP response code: 400 for URL: http://localhost:8084/service/HelloWorld?wsdl

Failed to read the WSDL document: http://localhost:8084/service/HelloWorld?wsdl, because 1) could not find the document; /2) the document could not be read; 3) the root element of the document is not
<wsdl:definitions>.

[ERROR] failed.noservice=Could not find wsdl:service in the provided WSDL(s):

 At least one WSDL with at least one service definition needs to be provided.

        Failed to parse the WSDL.

D:\Personal\WebService>

wsdl file >>.
<?xml version="1.0" encoding="UTF-8"?>
<!-- Published by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.2-hudson-740-. -->
<!-- Generated by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.2-hudson-740-. -->
<definitions xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsp="http://www.w3.org/ns/ws-policy" xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://service.pack.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://service.pack.com/" name="HelloWorldImplService">
<types/>
<message name="getHelloWorldAsString">
<part name="arg0" type="xsd:string"/>
</message>
<message name="getHelloWorldAsStringResponse">
<part name="return" type="xsd:string"/>
</message>
<portType name="HelloWorld">
<operation name="getHelloWorldAsString">
<input wsam:Action="http://service.pack.com/HelloWorld/getHelloWorldAsStringRequest" message="tns:getHelloWorldAsString"/>
<output wsam:Action="http://service.pack.com/HelloWorld/getHelloWorldAsStringResponse" message="tns:getHelloWorldAsStringResponse"/>
</operation>
</portType>
<binding name="HelloWorldImplPortBinding" type="tns:HelloWorld">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"/>
<operation name="getHelloWorldAsString">
<soap:operation soapAction=""/>
<input>
<soap:body use="literal" namespace="http://service.pack.com/"/>
</input>
<output>
<soap:body use="literal" namespace="http://service.pack.com/"/>
</output>
</operation>
</binding>
<service name="HelloWorldImplService">
<port name="HelloWorldImplPort" binding="tns:HelloWorldImplPortBinding">
<soap:address location="http://localhost:8084/service/HelloWorld"/>
</port>
</service>
</definitions>

A: I had the exact same issue when trying to generate the client side from the command line. After switching of my proxy settings, the error went away and I successfully generated the client files.

*

*Disable Proxy Settings.


text:
Q: In a Virtual Machine, is the Virtual Processor using RAM or part of the Processor? I am running a 15" MacBook Pro (2.66GHz) and 4GB of RAM. I am considering downgrading to a 13 MacBook Pro (2.4GHz) with 8GB of RAM.
Most of what I do at work is through Windows and I need to run it virtually. So my real question is when running a virtual machine will the virtual processor be utilizing RAM or part of the hosts processor?
My assumption is that it will utilize the allocated RAM but I have seen zero documentation to support that.

A: The virtual machine uses both physical RAM and physical CPU Time.


text:
Q: asynchronous UI design with calling webservice i am writing web application in Flex (SDK 3.5).
my program sends web service calls asynchronically to the server that gives me data.
I want to handle a case when the user sends a few requests before the answers to the previous requests were answered. In such a case i want to give the UI only the last request answer.
It is similar to web page where the user clicks many times on a button. how to show only the final answer?
I have an idea for saving the last request id in my proxy/BusinessDelegate class. and then, check the token id to see if it is identical to the last request id. And then i send the data to the UI to display.
What Do you think about this idea? Does anyone have a better idea?
thanks,

A: Here's how I handle this kind of situation
private var lastToken:AsyncToken;
public var service:RemoteObject;

public function makeRequest():void
{
    lastToken = service.doSomething();
    lastToken.addResponder(
        new AsyncResponder(handleResult, handleFault, lastToken)
    );
}

public function handleResult(result:Object, requestToken:Object):void
{
    if(requestToken !== lastToken) return;
    else
    {
        // handle result
    }
}

public function handleFault(fault:Object, requestToken:Object):void
{
    if(requestToken !== lastToken) return;
    else
    {
        // handle fault
    }
}

A: I think your idea is the right approach, because that's the way it is! :-)
I do it similarly like in Ryan's in answer and I think you idea has the same direction. The Flex RPC classes use the same approach with the lastResult property.


text:
Q: Put dropdown selection menu to hide/show div in wordpress I need your help please... I want to put a drpdown menu in wordpress page... i put this code but i cant hide them.....

Αγωνιστικές

      <select style="margin: 2% 0 3% 37.84%;" class="div-toggler" data-target=".Greekinfo">
          <option value="">Επιλέξτε αγωνιστική...</option>
<option value="agwn1" data-show=".agwn1">Αγωνιστική 1</option>
<option value="agwn2" data-show=".agwn2">Αγωνιστική 2</option>
<option value="agwn3" data-show=".agwn3">Αγωνιστική 3</option>
<option value="agwn4" data-show=".agwn4">Αγωνιστική 4</option>
<option value="agwn5" data-show=".agwn5">Αγωνιστική 5</option>
<option value="agwn6" data-show=".agwn6">Αγωνιστική 6</option>
<option value="agwn7" data-show=".agwn7">Αγωνιστική 7</option>
<option value="agwn8" data-show=".agwn8">Αγωνιστική 8</option>
<option value="agwn9" data-show=".agwn9">Αγωνιστική 9</option>
<option value="agwn10" data-show=".agwn10">Αγωνιστική 10</option>
<option value="agwn11" data-show=".agwn11">Αγωνιστική 11</option>
<option value="agwn12" data-show=".agwn12">Αγωνιστική 12</option>
<option value="agwn13" data-show=".agwn13">Αγωνιστική 13</option>
<option value="agwn14" data-show=".agwn14">Αγωνιστική 14</option>
<option value="agwn15" data-show=".agwn15">Αγωνιστική 15</option>
<option value="agwn16" data-show=".agwn16">Αγωνιστική 16</option>
<option value="agwn17" data-show=".agwn17">Αγωνιστική 17</option>
<option value="agwn18" data-show=".agwn18">Αγωνιστική 18</option>
<option value="agwn19" data-show=".agwn19">Αγωνιστική 19</option>
<option value="agwn20" data-show=".agwn20">Αγωνιστική 20</option>
<option value="agwn21" data-show=".agwn21">Αγωνιστική 21</option>
<option value="agwn22" data-show=".agwn22">Αγωνιστική 22</option>
<option value="agwn23" data-show=".agwn23">Αγωνιστική 23</option>
<option value="agwn24" data-show=".agwn24">Αγωνιστική 24</option>
<option value="agwn25" data-show=".agwn25">Αγωνιστική 25</option>
<option value="agwn26" data-show=".agwn26">Αγωνιστική 26</option>
<option value="agwn27" data-show=".agwn27">Αγωνιστική 27</option>
<option value="agwn28" data-show=".agwn28">Αγωνιστική 28</option>
<option value="agwn29" data-show=".agwn29">Αγωνιστική 29</option>
<option value="agwn30" data-show=".agwn30">Αγωνιστική 30</option>

    Γηπεδούχος
    Φιλοξενούμενος
    Ημερομηνία
    Ώρα
TV

        ΑΕΚ
        Παναιτωλικός
        00/00/00
        00:00
        Nova

        ΑΕΛ
        Βέροια
        00/00/00
        00:00
        Nova

        Α.Ο.Κέρκυρα
        Ατρόμητος Αθ.
        00/00/00
        00:00
        Nova

        ΑΕΠ Ηρακλής
        Α.Ο Ξάνθη
        00/00/00
        00:00
        Nova

        Λεβαδειακός
        ΠΑΟΚ
        00/00/00
        00:00
        Nova

        Ολυμπιακός
        Αστέρας Τρίπολης
        00/00/00
        00:00
        Nova

        Πανιώνιος
        ΠΑΣ Γιάννινα
        00/00/00
        00:00
        Nova

        Πλατανιάς
        Παναθηναϊκός
        00/00/00
        00:00
        Nova

I need something like that...
http://bettube.gr/tables/SuperLeague.php
Sorry my page is in Greek


text:
Q: The series of $\frac{1}{\cosh(z)}$ How to show that
$$\frac{1}{\cosh(z)} =\sum _{n=0}^{\infty }{\frac {\left(
-1 \right)^{n}\left(\psi \left( 2\,n,\frac{3}{4}\right)-\psi \left( 2\,n,\frac{1}{4} \right) \right) {z}^{2\,n}}{ {4}^{n}{\pi }^{2\,n+1}\left( 2\,n \right) !}},$$
where $\psi$ is a polygamma function?
Is there maybe some link with an answer, or a book in which the above is shown?

A: Commonly known, the expansion
$$\frac{1}{\cosh(x)}=\sum_{n=0}^\infty E_n \frac{t^n}{n!}$$
with $E_n$ the Euler numbers (see here or definition here).
In order to grasp the foundation of the calculation from here, I have to refer you first directly to the following article from Kölbig that discusses deeply the relation between the Euler numbers and the polygamma function $\psi^{(k)}(x)$ for $x=\frac{1}{4}$ and $x=\frac{3}{4}$. This is a standard article that is often cited.
However, then you will need another reference since the calculation not trivial: there are deep fundamental relations between the Dirichlet $\beta$-function, Euler numbers, and Riemann $\zeta$-function for positive integers; this is shown by Idowu in another standard article where the author based on the work of Kölbig and a prior article shows that the Euler numbers $(E_{2k})$ relate in the above scheme, which you have, to the polygamma function $\psi^{(2k)}(x)$ for $x=\frac{1}{4}$ and $x=\frac{3}{4}$, see final result on last page equation 3.3.
So as you can see the answer to your question is not trivial and it needs some further elaboration and study by yourself in the details. But the articles above should deliver the foundation.


text:
Q: How to receive the changes from nested firestore collections into a single flutter stream? For example when we need to read the changes in all cities (a subcollection under the country collection) using the following path:
Countries/{country_id}/cities/{city_id}
For each country_id we need a separate stream. How to receive changes in cities in a single stream for all countries?

A: Use a collection group query.  On Flutter, you will want to use the collectionGroup() method to create that query.
firestore.collectionGroup("cities")


text:
Q: view is not instantiating I'm doing a tutorial and my problem is at the very bottom of my code where you instantiate a new App.Views.AddTask view it's not working because when you click submit the page reloads and the e.preventDefault() isn't working. If I just type in the console new App.Views.AddTask then the e.preventDefault() works and the page doesn't submit what is cause this to not work correctly. my problem is in the adTaskView variable at the bottom.
    (function() {

    window.App = {
        Models: {},
        Collections: {},
        Views: {}

    };

    window.template = function(id) {
        return  _.template($('#' + id).html());
    }

    App.Models.Task = Backbone.Model.extend({
        validate: function(attrs) {
            if(!$.trim(attrs.title)) {
                return 'A task requires a valid title.'
            }
        }
    });

    App.Collections.Tasks = Backbone.Collection.extend({
        model: App.Models.Task
    })

    App.Views.Tasks = Backbone.View.extend({
        tagName: 'ul',

        render: function() {
            this.collection.each(this.addOne, this);

            return this;
        },

        addOne: function(task) {
            var taskView = new App.Views.Task({model: task});

            this.$el.append(taskView.render().el);
        }
    })

    App.Views.Task = Backbone.View.extend({
        tagName: 'li',

        template: template('taskTemplate'),

        initialize: function() {

            this.model.on('change', this.render, this);
            this.model.on('destroy', this.remove, this);
        },

        events: {
            'click .edit': 'editTask',
            'click .delete': 'destroy'
        },

        editTask: function() {
            var newTask = prompt('What would you likje to change the text to?', this.model.get('title'));

            if(!$.trim(newTask)) return;

            this.model.set('title', newTask);
        },

        destroy: function() {
            this.model.destroy();
        },

        remove: function() {
            this.$el.remove();
        },

        render: function() {
            var template = this.template(this.model.toJSON());
            this.$el.html( template );
            return this;
        }
    })

    window.tasksCollection = new App.Collections.Tasks([
        {
            title: 'Go tot the store',
            priority: 4
        },
        {
            title: 'Feed the dog',
            priority: 2
        },
    ]);

    // PROBLEM WITH THIS PART
    App.Views.AddTask = Backbone.View.extend({
        el: '#addtask',

        events: {
            'submit': 'submit'
        },

        initialize: function() {

        },

        submit: function(e) {
            e.preventDefault();

            console.log('hit');
            var newTaskTitle = $(e.currentTarget).find('input[type=text]').val();
            var task = new App.Models.Task({ title: newTaskTitle});
            this.collection.add(task);

        }

    });

    var tasksView = new App.Views.Tasks({ collection: tasksCollection});
    var addTaskView = new App.Views.AddTask({ collection: tasksCollection });

    $(document).ready(function() {
        $('.tasks').html(tasksView.render().el);
    });

})();

Form:
<form action="" id="addtask">
    <input type="text" name="task" id="task" />
    <button type="submit">Add Task</button>
</form>

A: Look at this:
events: {
    'submit': 'submit'
},

You add event to submit element on the page. But You wanted:
events: {
    'button[type=submit]': 'submit'
},

or
events: {
    'button': 'submit'
},

A: submit event is too late to prevent the submission. You should bind the handler to click event instead.
 events: {
        'click': 'submit'
    },


text:
Q: Using terminal on mac via an executable file Right so I wanted to automate a process which I have to do quite often for a program that I run quite often and sometimes open up multiple of.
Normally I open up Terminal and type in the following commands in order:
cd ExoClient
mono ExoClient.exe
(email)
(pass)

So I made an executable file for this called login.command on my mac.
I typed in this is order:
cd ExoClient
mono ExoClient.exe
example_email@gmail.com
example_password

So the first two lines work but the last two don't do anything. I thought that this could be because the top 2 commands are actual mac commands and the last two lines are just inputs. But I don't know how to make sure the inputs are inputted.
OR another reason why it might not work could be because I need to delay the inputs. I'd love to know what I can input here to make it wait a second before an input is inputted.
Thanks for reading, would appreciate any help.

A: I made a similar post on mac rumours.
The solution was to do :
cd ExoClient
mono ExoClient.exe email pass

A: The first thing to understand about the command-line is that there's a bunch of different things in play.
The first is the commands themselves, these are typically typed in or run from a script.
The second is "standard input" or STDIN, which is where programs take keyboard input. As far as you're concerned there's no difference when using the shell, but to the shell itself there's a huge difference. That program wants input from STDIN. The shell script is being told to run two subsequent commands.
Instead try this:
cd ExoClient
echo "example_email@gmail.com\
example_password" | mono ExoClient.exe

The | character means "send output to" in rough terms, so the output of echo goes through to the mono program. Output, or STDOUT, is another thing the shell wants to deal with.
Or have a secondary file that contains those two lines and give that as "input":
cd ExoClient
mono ExoClient.exe < login.txt

Where login.txt has the two lines and < means "take input from this file".


text:
Q: AWS API Gateway immediate timeout when using child_process in Lambda I have a Lambda function that I'm calling using API gateway. When the Lambda hits the spawn call on a child_process object the API Gateway immediately fails with a 504 timeout error. My timeout setting on the the API gateway is the max 30 seconds and the Lambda is set for a minute. It only takes up to 1400ms for the lambda to run, but it still reports timeout in the API. The Lambda runs successfully after the API Gateway gets the 504.
This happens during a call to FFMPEG and to a call to resize an image with the Sharp library. This happens whether I use synchronous or asynchronous calls.
function resizeVideo(next) {
    var ffmpegOutput = exec.spawnSync('ffmpeg', [
        '-i', tmpFilePath,
        '-f', 'image2',
        '-frames:v', '1',
        '-filter:v', 'scale=w=-1:h=' + MAX_HEIGHT + ":force_original_aspect_ratio=decrease",
        'pipe:1'
    ]);

    console.log(ffmpegOutput.stderr);

    next(null, JPG_CONTENT_TYPE, ffmpegOutput.stdout);
}

Any thoughts would be appreciated. Thanks!

A: OP's co-worker here.  We got this working and I just wanted to post in case it ever helps somebody else with this issue.  My understanding is that this was occurring because the timeout had mistakenly been set to a low number (180), mistakenly thinking that number was seconds.  We updated the timeout (to the max of 29000) after realizing the value should be specified in milliseconds, but didn't realize we had to "Deploy" the API in order for the change to take effect.  After re-deploying the API, the issue was resolved.


text:
Q: How to check if Contact has Image? I am assigning to an ImageView contacts images using this code:
mPhotoView = (ImageView) findViewById(R.id.photo);
mPhotoView.setImageURI(objItem.getPhotoUri());

If the contact has no image, this does nothing, and no error is raised.
When there is no image, I want to add a default image. So I need to check either if the image was added to the view, or check that the URI holds some image data
How do I achieve that?
Than I will set default image by this:
mPhotoView.setImageResource(R.drawable.ic_contact_picture_2);

A: If your target device is running android 2.0/2.0.1/2.1 you will have to query ContactsContract.Data.CONTENT_URI with a selection like:
Data.MIMETYPE + "='" + Photo.CONTENT_ITEM_TYPE

Otherwise query Contacts.Photos.CONTENT_URI
Edit by Pentium10
For reference I include here the method I come up with (if you still see bugs, update it):
public Uri getPhotoUri() {
    Uri person = ContentUris.withAppendedId(
            ContactsContract.Contacts.CONTENT_URI, Long.parseLong(getId()));
    Uri photo = Uri.withAppendedPath(person,
            ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);

    Cursor cur = this.ctx
            .getContentResolver()
            .query(
                    ContactsContract.Data.CONTENT_URI,
                    null,
                    ContactsContract.Data.CONTACT_ID
                            + "="
                            + this.getId()
                            + " AND "
                            + ContactsContract.Data.MIMETYPE
                            + "='"
                            + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE
                            + "'", null, null);
    if (cur != null) {
        if (!cur.moveToFirst()) {
            return null; // no photo
        }
    } else {
        return null; // error in cursor process
    }
    return photo;
}

A: Depending on your use case, there may be another(better?) option. If you have a cursor of all contacts and you're say, binding them to a listview, you can simply attempt to retrieve a photo using openContactPhotoInputStream, and check for null.
InputStream stream = Contacts.openContactPhotoInputStream(context.getContentResolver(), lookupUri);
if (stream == null) {
    //your logic here when no photo found
}

Here's a quick example for any who may stumble upon this :
import android.provider.ContactsContract.Contacts;

//Define someDefaultPhoto somewhere accessible

protected Bitmap getContactPhoto(Context context, Uri lookupUri) {
    Bitmap resultPhoto;
    InputStream stream;
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        //For some reason this seems to be necessary pre-ICS. If anyone knows why, I'd love to hear
        lookupUri = Contacts.lookupContact(context.getContentResolver(), lookupUri);
    }
    stream = Contacts.openContactPhotoInputStream(context.getContentResolver(), lookupUri);

    if (stream == null) {
        resultPhoto = someDefaultPhoto;
    }
    else {
        resultPhoto = BitmapFactory.decodeStream(stream);
    }
    return resultPhoto;
}

Then you can call it with something like this:
int columnLookupKey = cursor.getColumnIndex(Contacts.LOOKUP_KEY);
String lookupKey = cursor.getString(columnLookupKey);
Uri lookupUri = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey);
Bitmap contactPhoto = getContactPhoto(context, lookupUri);

A: This is what I came up with based on the other answers.
    private Uri getUserPictureUri(long id) {
        Uri person = ContentUris.withAppendedId(
        ContactsContract.Contacts.CONTENT_URI, id);
        Uri picUri = Uri.withAppendedPath(person,
            ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
        try {
            InputStream is = getContentResolver().openInputStream(picUri);
            is.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return picUri;
}

A: Just check if the PHOTO_ID column in PhoneLookUp Content provider is null or not
Here is a method I've developed:
public static boolean hasContactPhoto(Context context, String number) {
    String thumbUri = "";
    String photoId = "";
    String id = "";
    Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
            Uri.encode(number));
    Cursor cursor = context.getContentResolver().query(uri,
            new String[] {ContactsContract.PhoneLookup._ID,ContactsContract.PhoneLookup.PHOTO_ID}, null, null, null);
    if (cursor.moveToFirst()) {
        id = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup._ID));
        photoId = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.PHOTO_ID));
    }
    cursor.close();
    if(!id.equals("") && photoId != null && !photoId.equals(""))
        return true;
        //sms.setContactThumb(ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.valueOf(id)).toString());
    else
        return false;
}

if you need the contact image uri get it from:

ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.valueOf(id)).toString()

and if you need to set it to an image view use the following line (I've used Universal Image Loader 1.9.2 for image loading purposes):

        ImageLoader.getInstance().displayImage(currentRecord.getContactThumb(),viewHolder.mThumbIV);

note : contactThumb is the last described uri
Cheers!


text:
Q: Autogenerate of years within a span of numbers Yep, it may sound confusing so I thought i'll explain the problem more detailed.
Now I'm not asking for a solution of what, I just need to know if it is possible. I tried searching the net for answer but it seems that those sites I visited does not fulfill the answer I need to see.
Is it possible to display year using php/html without writing the years in the code behind like the below
<label for="year" style="padding-right: 10px;margin-top:7px;">Year</label>
          <select name="year" id="year" class="text ui-widget-content ui-corner-all">
                <option value="0">Choose Year</option>
                <option value="1990">1990</option>
                <option value="1991">1991</option>
                <option value="1992">1992</option>
                <option value="1993">1993</option>
                <option value="1994">1994</option>
                <option value="1995">1995</option>
                <option value="1996">1996</option>
                <option value="1997">1997</option>
                <option value="1998">1998</option>
                <option value="1999">1999</option>
                <option value="2000">2000</option>
                <option value="2001">2001</option>
                <option value="2002">2002</option>
                <option value="2003">2003</option>
                <option value="2004">2004</option>
                <option value="2005">2005</option>
                <option value="2006">2006</option>
                <option value="2007">2007</option>
                <option value="2008">2008</option>
                <option value="2009">2009</option>
                <option value="2010">2010</option>
                <option value="2011">2011</option>
                <option value="2012">2012</option>
                <option value="2013">2013</option>
                <option value="2014">2014</option>
                <option value="2015">2015</option>
                <option value="2016">2016</option>
                <option value="2017">2017</option>
                <option value="2018">2018</option>
                <option value="2019">2019</option>
                <option value="2020">2020</option>
          </select>

What I want to know if is it possible to show the year without the above code like for example display 2004 to 2024. Now today is 2014. When year changes to 2015 then year range will be 2005 to 2025.
Is this possible?
Thanks for the answer.

A: Not really complicated. Just get your current year and then subtract 100 from it. Then use a for loop that starts with your start year and ends when it reaches the current year.
$last  = date("Y");
$start = $year - 100;
for ($i = $start; $i <= $last; $i++) {
    echo '<option value="' . $i. '">' . $i. '</option>';
}

You can improve upon this by adding new lines, not embedding your HTML in your PHP, etc.


text:
Q: php rename(file) is making 2 copies. sometimes. why? on my php server I have 3 folders (including the root)
/
/lists
/lists/archive
I have a file called /lists/make.php which generates a static html file using today's date as the filename like this: /lists/20160203.htm
but before it makes today's list, it first checks for yesterday's list. If found, it MOVES it using the rename() command to the /lists/archive folder. However, it's doing more than just moving to archive, it is also creating a copy in root but it only does this every other day. And it's not just an even/odd problem because that switched at the end of January. For example, here is my file structure now. (note: today is 2016-02-03)
/20160128.htm
/20160130.htm
/20160201.htm
/20160203.htm
/lists/20160203.htm
/lists/archive/20160128.htm
/lists/archive/20160129.htm
/lists/archive/20160130.htm
/lists/archive/20160131.htm
/lists/archive/20160201.htm
/lists/archive/20160202.htm
So there are 3 odd things happening here that I need help fixing:
(1) yesterday's list should be only in the archive, not also in root
(2) why is this only a problem every other day???
(3) why is today's list already in root when the archive script has not executed yet?
(4) will tomorrow's list be in root?
Here is relevant code in /lists/make.php
<?php
$filename = date('Ymd',strtotime('yesterday')).'.htm';
if( file_exists($filename) ){
    //email a copy to admin
    $message = file_get_contents($filename);
    mail($emailAdmin, $subject, $message, $headers));
    //move list to archive
    rename('../lists/'.$filename, '../lists/archives/'.$filename);
}

//start or overwrite today's list
$filename = date('Ymd').'.htm';
$fh = fopen($filename,'w');
fwrite($fh, 'stuff1, stuff2');
fwrite($fh, 'stuff3, stuff4');

?>

If the "../lists/" part of rename() seems redundant, I agree, but adding that halfway fixed my problem. Before, I was just doing rename($filename,'archives/'.$filename) and it was making copies every day. Now it just makes copies every other day. I'm so confused. help!
/lists/make.php is included in a few other files on my site so that it is executed several times per day. That is my hacked solution to triggering backups since I can't control chron events on my shared host. Most of the files that call make.php are also in the /lists/ folder but one of them is in root, and one other is buried 2 levels deep in subfolders of /lists/. I don't think that is relevant but this problem is a mystery to me.

A: I would use rename(__DIR__.'/'.$filename, __DIR__.'/archives/'.$filename).  __DIR__ refers to the directory of the script you use it in.  If you're including the script from multiple places then the relative path to /lists will give you different results from different scripts.
If it's being called by different scripts on different days it could explain why it's inconsistent.  Today's having run already could possibly be that you haven't adjusted the timezone, and in your server's time it's already tomorrow.


text:
Q: Alter file path based on cell reference A short explanation; I have a large amount of reports in one folder, and they are all formatted the exact same way every time, except for the date in the file name (ex. Out of Stock Report WE 04.20.16.xlsx). In the workbook where I have my formula, I'm referencing a cell that has a date in it, and then using that date (DT$3 reference is a date) as an input for the last part of the file path, so that it goes to the correct file and looks up the file. I don't need any actual index/match or lookup formula, because these reports are all formatted the exact same way, so the needed value is always in the same cell on the same worksheet. Here is my formula that I'm getting a #REF error on:
='\\dhqshareddata\data\Supply_Chain\Planning\Strategic Planning - Forecasting\Out of Stock\All Reports\[Out of Stock Report WE "&TEXT(DT$3, ("MM.DD.YY"))&".xlsx]Category Report'!$C$5

This should be simple but I can't get it to work. Additionally, an indirect function won't do me any good because I'll have to open every single report and copy/paste values, for hundreds of reports.


text:
Q: Replace string in one node of Mongodb document I need your help to write one replace query.
I have connected one third party software mongodb.
I am SQL guy and not able to write query of replace specific node value.
I am using Robo 3T software. Below is one record json from the document.
{
    "_id" : ObjectId("6036c343445f3640c53e0a"),
    "shares" : [
        {
            "shareId" : ObjectId("6035cc6acf345f3640c53d1a"),
            "type" : "user"
        },
        {
            "shareId" : ObjectId("6035b536cf345f3640c53cae"),
            "type" : "group",
            "rule" : "view",
            "subscribe" : false
        }
    ],
    "tags" : [],
    "lastUsed" : ISODate("2021-03-09T16:51:30.059Z"),
    "usageCount" : 1,
    "layout" : {
       too many values with multiple node.
    },
    "instanceType" : "owner",
    "original" : null,
    "editing" : true,
    "filters" : [
        {
            "jaql" : {
                "table" : "Xyz",
                "column" : "title",
                **"dim" : "[dbo.ketan.Title]",**
                }
            }
            "disabled" : false
        },
        {
            "jaql" : {
                "table" : "abc",
                "column" : "name",
                **"dim" : "[dbo.ketan.name]",**
                "datatype" : "text",
                "merged" : true,
                "title" : "Inventor Name",
                "filter" : {
                    "explicit" : false,
                    "multiSelection" : true,
                    "all" : true
                },
                "collapsed" : false
            },
            "instanceid" : "1B1E4-F6DC-28",
            "isCascading" : false
        },

}

Here I want to replace "dim" : "[dbo.ketan.name]", to "dim" : "[kiran.name]",
Can you please help me to write query ?
This is my first post. The Writing may be not up to mark. Please let me know if you need any more details.
Thank you.

A: This is how you can acheive the functionality. Although your MongoDB Version should be >= 3.6
db.collection.update(                                     //collection
  {"filters.jaql.dim": {"$regex": "dbo.ketan"}},          //update filter
  {"$set": {"filters.$[elem].jaql.dim": "[kiran.name]"}}, //update action
  {
    "arrayFilters": [
      {
        "elem.jaql.dim": {
          "$regex": "dbo.ketan"
        }
      }],
    "multi": true
  }                                               //filters for all element to be updated
)

To see this logic in action: MongoPlayground Example


text:
Q: Nested for loop for column data processing in MATLAB I have 100 column xlsx file with size (4097,100). I need to read first column and do some processing and this results in four row variables (1,4097 each) for the first column data only. Further, I need to process each of these four row variables to obtain its statistical parameters such as min, max, mean, SD, var in MATLAB. How to do it with nested for loop?
I appreciate your help. The sample MATLAB code that I am trying is where I have considered only two columns A1 and A2:
A = xlsread('S.xlsx');
num_rows = size(A,1);
num_cols = size(A,2);
A1 = A (:,1);
A2 = A (:,2);
B = {A1,A2};
for i = 1:2
for j = 1:4
IMF = emd(B{i},'STOP',[0.1,0.5,0.05],'MAXITERATIONS',100);
I1 = IMF (1,:);
I2 = IMF (2,:);
I3 = IMF  (3,:);
I4 = IMF (4,:);
imf = {I1, I2, I3, I4};
m1(j) = mean(imf{j});
m2(j) = min(imf{j});
m3(j) = max(imf{j});
m4(j) = std(imf{j});
m5(j) = var(imf{j});
end
end

Another variation in the code I tried is:
A = xlsread('S.xlsx');
num_rows = size(A,1);
num_cols = size(A,2);
A1 = A (:,1);
A2 = A (:,2);
B = {A1,A2};
for i = 1:2
IMF = emd(B{i},'STOP',[0.1,0.5,0.05],'MAXITERATIONS',100);
I1 = IMF (1,:);
I2 = IMF (2,:);
I3 = IMF  (3,:);
I4 = IMF (4,:);
imf = {I1, I2, I3, I4};
for j = 1:4
m1(j) = mean(imf{j});
m2(j) = min(imf{j});
m3(j) = max(imf{j});
m4(j) = std(imf{j});
m5(j) = var(imf{j});
end
end

But no success. I am getting the stats values only for the first column i.e. four values for I1, I2, I3 and I4. The second column A2 is not being processed.

A: I think the problem is that you overwrite your results. You can always run your code step by step using the Matlab debugger to check what exactly happens.
A = xlsread('S.xlsx');
m1 = zeros(2, 4);
m2 = zeros(2, 4);
m3 = zeros(2, 4);
m4 = zeros(2, 4);
m5 = zeros(2, 4);
for i = 1:2
    IMF = emd(A(:, 1),'STOP',[0.1,0.5,0.05],'MAXITERATIONS',100);
    m1(i, :) = mean(IMF, 2);
    m2(i, :) = min(IMF, [], 2);
    m3(i, :) = max(IMF, [], 2);
    m4(i, :) = std(IMF, 0, 2);
    m5(i, :) = var(IMF, 0, 2);
end

Note that I removed some temporary variables, avoided the nested loop and preallocated the variables outside the loop. This may decrease the execution time.


text:
Q: Vue Jasmine: Two different ways of triggering click result in different results I am having an issue when trying to switch the way I trigger clicks in my jasmine tests.  This is my current setup:
Parent

    <MovieData :movie="currentMovieData" :isSubscribed="isSubscribed" @selected="handleMovie(currentMovieData)" />

Child (MovieData.vue)
<template>
  <component :is="unType" v-bind="linkProps" :class="$style.container" data-ut="Movie-link" ref="link">

  </component>
</template>

When creating my tests in the Parent component, I have:
(first method of triggering a click)
const movie = this.wrapper.vm.$refs.currentMovie;
triggerEvent(movie.querySelector('div'), 'click');
expect(this.wrapper.emitted().selected).toBeTruthy();

this works as expected and passes.  I am trying to switch to using from using triggerEvent to data-ut and doing this instead:
(second method of trigger a click)
this.wrapper.find(testID('Movie-content')).trigger('click');
expect(this.wrapper.emitted().selected).toBeTruthy();

I get:  ERROR Some of your tests did a full page reload!


text:
Q: Sum of binary quadratic forms over inputs of equal Hamming weight $\DeclareMathOperator{\field}{\mathbb{F}}$
Let $n$ be a positive integer, and let $q : \field_2^{n} \rightarrow \field_2$ be a quadratic form, specified in coordinates as
$$q(x)=\sum_{i =1}^n \alpha_i x_i + \sum_{\substack{j,k=1\\ j<k}}^n \beta_{j,k} x_j x_k$$
for some $\alpha_i, \beta_{j,k} \in \field_2$. For each integer $a\in \{0,\dots, n\}$, I am interested in the quantity
$$ C_{q,a}=\sum_{\substack{x \in \field_2^{n}\\ |x|=a}} (-1)^{q(x)} \in \mathbb{Z},$$
where $|x|$ denotes the Hamming weight of $x$.
Is there a simple formula for $C_{q,a}$? Have these quantities $C_{q,a}$ been studied before?


text:
Q: Iterated Integral with variable substitution I need to calculate the double integral of the function $f(x,y) = (x+y)^9(x-y)^9$:
$\int_0^{1/2} \int_x^{1-x}  (x+y)^9(x-y)^9 dydx$
I have a solution but I definitely arrived at it after a sloppy attempt. I got -0.0025. To begin with, I know you need to separate the variables. I tried integration by parts, but got lost in it. How can I separate the variables to continue the integration?

A: It's convenient to solve this integral with substitution. Since we want to separate the variables in the Integral
\begin{align*}
\int_0^{1/2} \int_x^{1-x}  (x+y)^9(x-y)^9 dy\,dx\tag{1}
\end{align*}
it's reasonable to use  the substitution
\begin{align*}
\left.
\begin{matrix}
u=x+y\\
v=x-y\\
\end{matrix}
\right\}
\quad\Longleftrightarrow\quad
\left\{
\begin{matrix}
x=\frac{1}{2}(u+v)\\
y=\frac{1}{2}(u-v)
\end{matrix}
\right.\tag{2}
\end{align*}

According to the Change of variable theorem we want to calculate
  \begin{align*}
\int_{x_0}^{x_1}\int_{y_0}^{y_{1}}f(x,y)\,dy\,dx
=\int_{u_0}^{u_1}\int_{v_0}^{v_{1}}f(x(u,v),y(u,v))
\left|\operatorname{det}
\begin{pmatrix}
x_u&x_v\\
y_u&y_v
\end{pmatrix}
\right|
\,dv\,du\tag{3}
\end{align*}
Jacobian
At first we calculate the absolute value of the determinant of the Jacobian matrix
  \begin{align*}
\left|\operatorname{det}
\begin{pmatrix}
x_u&x_v\\
y_u&y_v
\end{pmatrix}
\right|=
\left|\operatorname{det}
\begin{pmatrix}
\frac{1}{2}&\frac{1}{2}\\
\frac{1}{2}&-\frac{1}{2}
\end{pmatrix}
\right|
=\frac{1}{2}
\end{align*}
Area transformation
We observe from (1) the region of integration is
  \begin{align*}
&0\leq x\leq \frac{1}{2}\\
&x\leq y\leq 1-x
\end{align*}
This is the area of a triangle with three lines as boundary lines,  the $y$-axis  $x=0$, the  major diagonal $x=y$ and a parallel to the minor diagonal through $(1,0)$, $y=1-x$.
Since the transformation (2) is linear, lines are transformed to lines. So, the transformed $(u,v)$-area is again enclosed by three lines.
\begin{array}{lclcl}
x=0\qquad&\rightarrow&\qquad \frac{1}{2}(u+v)=0
&\qquad\rightarrow&u=-v\\
x=y\qquad&\rightarrow&\qquad \frac{1}{2}(u+v)=\frac{1}{2}(u-v)
&\qquad\rightarrow&v=0\\
y=1-x\qquad&\rightarrow&\qquad \frac{1}{2}(u-v)=1-\frac{1}{2}(u+v)
&\qquad\rightarrow&u=1\\
\end{array}
We see the $(u,v)$-triangle area is given by the three lines $u=-v, v=0$ and $u=1$ which can be written as
  \begin{align*}
0\leq u \leq 1\\
-u\leq v\leq 0
\end{align*}

$$ $$

Integration
Now we have all ingredients to perform the integration according to (3). We obtain
\begin{align*}
\int_0^\frac{1}{2}\int_x^{1-x}  (x+y)^9(x-y)^9 dy\,dx
&=\int_0^1\int_{-u}^0(uv)^9\cdot\frac{1}{2}\,dv\,du\\
&=\frac{1}{2}\int_0^1u^9\left(\int_{-u}^0v^9\,dv\right)\,du\\
&=\frac{1}{2}\int_0^1u^9\left(\left.\frac{1}{10}v^{10}\right|_{-u}^0\right)\,du\\
&=-\frac{1}{20}\int_0^1u^{19}\,du\\
&=-\frac{1}{20}\left.\left(\frac{1}{20}u^{20}\right)\right|_{0}^1\\
&=-\frac{1}{400}
\end{align*}


text:
Q: How can I check if a python file is ran by a user or not? I created a python file namedwizard.py and in that file, I wanted to check if the file > wizard.py is already run by a user or not.
if not > run it, if it is >  print a statement.
Is there a way to do it?. Thanks in the future!
*using python

A: easy way)
import psutil

my_script_name='my_script.py'

for process in psutil.process_iter():

    boolFind=any([x for x in process.cmdline() if my_script_name in x])
    if boolFind:

            '''
                your code

            '''


text:
Q: Area chart looks flat because Y Axis starts from 0 Area chart looks flat due to the fact that Y axis always starts from 0 in compare to a line chart which in the same data uses some sort of auto-fit.
Plunkr
I would like to have similar auto-fit on the area chart that works on line chart as default.
(Using yAxis[0].setExtremes is not an option really).

Is there any configuration to do so?

A: You can achieve it by setting xAxis.min property like that:
  yAxis: {
    min: 10000,
    labels: {
      formatter: function() {
        return this.value / 1000 + 'k';
      }
    }
  }

Demo:

*

*https://jsfiddle.net/BlackLabel/Layfnuz4/
API reference:

*

*https://api.highcharts.com/highcharts/xAxis.min

The second approach is to set plotOptions.area.threshold
  plotOptions: {
    area: {
      threshold: 10000,
      marker: {
        enabled: false,
        symbol: 'circle',
        radius: 2,
        states: {
          hover: {
            enabled: true
          }
        }
      }
    }
  }

Demo:

*

*https://jsfiddle.net/BlackLabel/r7qc1jpk/
API reference:

*

*https://api.highcharts.com/highcharts/series.area.threshold

EDIT
Automatic approach: set series.area.softThreshold = true as line series has.
  series: [{
    softThreshold: true,
    name: 'Data',
    data: data
  }]

Demo:

*

*https://jsfiddle.net/BlackLabel/8uj3kz4a/
API reference:

*

*https://api.highcharts.com/highcharts/series.area.softThreshold


text:
Q: SQL Insert top n names from table A to a table B row, with n names in row I have a table A(id integer,name varchar(10)) and a table B(id integer,name1 varchar(10),name2 varchar(10), name3 varchar(10))
I want the top 3 names of table A to get inserted into the a table B row.
for example, if i have:
table A
id    name
1     ed
2     edd
3     eddd
4     mike

i want this:
table B
id    name1    name2    name3
1     ed       edd      eddd

a normal order by id of table A is fine.

A: You can pivot using conditional aggregation and insert:
insert into b (name1, name2, name3)
    select max(case when seqnum = 1 then name end),
           max(case when seqnum = 2 then name end),
           max(case when seqnum = 3 then name end)
    from (select a.*, row_number() over (order by id) as seqnum
          from a
          order by id
          limit 3
         ) a;

This assumes that id is a serial column.  If not, just throw in min(id) as the first column being selected and inserted.

A: with t as ( -- get first 3 names into single array
  select array_agg(name) as first_3_names
  from table_a
  order by id limit 3)
insert into table_b (name1, name2, name3) -- then insert array's elements into the appropriate columns
select first_3_names[1], first_3_names[2], first_3_names[3] from t;


text:
Q: Move an SVG object along a line or a path I'd like to animate an SVG object so that it follows a SVG path that I have built from a line generator in d3.js. Is there any easy way to achieve this? In particular, I'd like to obtain the interpolated coordinates that correspond to my path. From there, it would be easy to perform the animation using tween.js or d3.js itself.

A: As far as I know, there's no way to easily get the coordinates of an interpolated SVG path in D3, i.e. you might have to do the interpolation yourself.
To animate an SVG object along that path, you don't need to use D3 however. You can use the SVG <animateMotion> element to get a native SVG animation -- see here for an example.

A: You may be able to modify this example: http://bl.ocks.org/mbostock/1705868
In this case, a circle is translated along an SVG path using SVG's getTotalLength and getPointAtLength. You should be able to replace the circle with any SVG object.


text:
Q: Cannot write Dataframe result as a Hive table/LFS file I have encountered an issue while writing the filtered data to a file. There are around 27 files created in local file system but with no output.
Below is the code used:
I'm reading the file as a dataframe
val in_df=spark.read.csv("file:///home/Desktop/Project/inputdata.csv").selectExpr("_c0 as Id","_c1 as name","_c2 as dept")
Then to register this dataframe as a temp table
in_df.registerTempTable("employeeDetails")
Now the requirement is to count the number of employees for each department and store it to a file.
val employeeDeptCount=spark.sql("select dept,count(*) from employeedetails group by dept")
//The following code is writing to Hive default warehouse as n number parquet files.
employeeDeptCount.write.saveAsTable("aggregatedcount")
//The following code is writing to LFS but No Output but n files are created
employeeDeptCount.write.mode("append").csv("file:///home/Desktop/Project")

A:   val in_df=spark.read.csv("file:///home/Desktop/Project/inputdata.csv").selectExpr("_c0 as Id","_c1 as name","_c2 as dept")

  // please, show your result
  in_df.show(false)

  val employeeDeptCount= in_df.groupBy("dept").count().alias("count")
  employeeDeptCount.persist()
  employeeDeptCount.write.format("csv").mode(SaveMode.Overwrite).saveAsTable("aggregatedcount")
  employeeDeptCount.repartition(1).write.mode("append").csv("file:///home/Desktop/Project")
  employeeDeptCount.unpersist()

// in_df.createOrReplaceTempView()
// in_df.createOrReplaceGlobalTempView()