text:
Q: Meteor build refresh after file change saving drops an EACCES error in a docker container SUMMARY
First of all I run my Meteor web app using docker-compose with docker-compose -f docker-file.dev.yml up -d --build. Everything works fine for the first build. The app is reachable on my browser via localhost.
Then I have an EACESS error while I use my code editor (vscode) to edit some .jsx files, this runs the build refresh, then, the application, running in a docker container crashes. It means I have a permission error.
But, when I save an updated file, this is done with my current (windows) user into VSCode, anyway, the app is run by "meteoruser" user defined in the docker-compose.dev.yml file below.
So what is the problem with this configuration, it worked well on a previous computer running ubuntu 16.04. Is windows the problem?
If I check docker logs I have this output :

If I rerun docker-compose build command, then everything is fine, the files are updated and the app is running. But I can't work like that and rerun this command every time I make a file change.
What I expect is a build refresh working without dropping an EACCESS error.
Additionnal informations about my project
This is a React project within Meteor framework in a container, using mongodb container within an nginx proxy in a container as well.
Project scaffold:

docker-compose file

docker file (.dev)

nb: as you can see, I create an user in the container, then I run the app into the container with this user. This is needed to ensure not running locally the app as root user.
WHAT I HAVE  TRIED

*

*Delete the .meteor folder and rebuild locally with meteor run to ensure my current windows user has the rights for the meteor app build folder. It do not work.

*Remove the usage of meteoruser in the dockerfile, this does not work and instead drop an error, because meteor do not allow running app in a dev environment with root user, because it could lead to permission errors later in production..

Thanks in advance for your help!


text:
Q: How to invoke a specific intent among many intents and communicate with it until it wants to end I want to create Alexa skill having several intents. However I want one intent among them such that user can invoke it and communicate with it (sending slots) till intent want. For example, user starts sending values through slot to that intent and intent keep receiving the value and outputs it as response. However as soon as it receives integer > 1000, it stops.
I found something called dialog which can be used to communicate multiple times with intent. So suppose we want to book ticket, then we can have :
user: I want to go from {Berlin} to {London}.

Alexa: (gets Berlin and London as slot values) Please tell the date

user:  28

Alexa: (gets 28 as slot value) Please tell month and year

user : November 2022.

Intent ends the communication after that. Ofcourse we can again start communication with same intent.
In similar way I want user to communicate with intent of skill until user doesn't gives integer greater than 1000.
How to do it in java ? Other language will also be helpful since concepts are same.
It should work as following :
User: ContinousIntentHandler invoked

ContinousIntentHandler : Say anything

User: hello

ContinousIntentHandler : hello

User: 56 and 57 and 81

ContinousIntentHandler: 56 and 57 and 81

User: 1001

ContinousIntentHandler now stops the communication and needs to be re-invoked to start process again.

A: It sounds like you are looking for the Delegate Dialog feature.  See this link https://developer.amazon.com/en-US/docs/alexa/custom-skills/delegate-dialog-to-alexa.html
There is a code sample using the Java SDK v2 in that link

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why can't this html change body color when I shake my phone? I leaned that html5 contains a device motion detector and wrote this html.
I opened this html with my cell phone browser.
<!DOCTYPE html>
...
var color = new Array('#FFF8DC', '#DC143C', '#00FFFF', '#00008B', '#008B8B', '#B8860B', '#A9A9A9', '#006400', '#BDB76B', '#8B008B');
function mark(n0)
{
    do
        {
            n = Math.floor(Math.random()*11)%10
        }
    while n == n0;
    return n;
}
if(window.DeviceMotionEvent) {
    var speed = 15;
    var x = y = z = x0 = y0 = z0 = n0 = 0;

    window.addEventListener('motionListener', function(){
        var acceleration =event.accelerationIncludingGravity;
        x = acceleration.x;
        y = acceleration.y;
        n = mark(n0)
        if(Math.abs(x-x0) > speed || Math.abs(y-y0) > speed) {
            document.body.style.backgroundColor = color[n];
        }
        x0 = x;
        y0 = y;
        n0 = n;
    }, false);
}
..

But the body color cannot be changed.


text:
Q: How to get the front part of some words in R? I am trying to get the front part of some words in a sentence.
For example the sentence is -
x <- c("Ace Bayou Reannounces Recall of Bean Bag Chairs Due to Low Rate of Consumer Response; Two Child Deaths Previously Reported; Consumers Urged to Install Repair", "Panasonic Recalls Metal Cutter Saws Due to Laceration Hazard")

Now I want get the front part of Recall or Recalls. I have tried various functions from R like grep, grepl, pmatch , str_split. However, I could not get exactly what I want .
what I need is only
"Ace Bayou Reannounces"
"Panasonic"

Any help would be appreciated.

A: If you want to use regular expressions.
gsub(pattern = "(.*(?=Recall(s*)))(.*)", replacement = "\\1", x = x, perl = T)


text:
Q: rails config gem issue with template rendering I'm using rails config gem to set feature flags.
Settings.yml
enable_grading: <%= 'true' == ENV['ENABLE_GRADING'] %>

When I try to hide/show some part of the template based on the feature flag, it responds inconsistently.
<% if Settings.enable_grading %>

      ...

<% end %>

So here, even if Settings.enable_grading is true, the div block is not being rendered. But if I modify this to:
<% if Settings.enable_grading == true %>

      ...

<% end %>

now this starts working!(the content is rendered). This is working if we use some sort of ruby interpolation just before the condition check.
<%= Settings.enable_grading %>
<% if Settings.enable_grading %>

      ...

<% end %>

This is really weird. What is wrong in this code? I was using this gem to set feature flags before also which was working well.


text:
Q: How to calculate forces (Hooke's law) efficiently? I'm trying to optimize a force-directed graph. So far I have implemented it using the naïve O(n2) method. It can only handle around 1000 nodes, which is far too few for my needs.

Those of you familiar with the algorithm know that it has two main components: repulsion between nodes in Coulomb's law fashion and spring-like attraction along edges using Hooke's law, both of these components involve pairwise calculations between nodes.
The Barnes-Hut algorithm works nicely for the former which would bring the repulsion component to O(n log n). However I have not been able to find something similar for the spring component. I have considered the following:

*

*Dividing the nodes based on location into overlapping bins and performing pairwise calculations only between nodes in the same bin. However, this might not work in all cases, especially since the initial configuration of the nodes is random and connected nodes could be anywhere. I could change how I generate the nodes but unless they are all in the same bin it would still produce incorrect results.

*Storing the edges separately and iterating through them to calculate the spring forces. Right now this looks to be the most promising method to me.
Is there a better way I haven't considered? If it matters at all, I'm using C# and it'd be nice if it were trivial to throw in a parallel loop.

A: I feel the second option that you gave should work with linear complexity in terms of the number of edges. Just iterate through them and keep updating the resultant forces on the respective 2 nodes.
EDIT: Sorry I earlier thought that each node is connected to every other node through a spring.

A: If I understood you correctly you have O(n log n) for the repulsion component and the attraction component is sparse: for each node you have on average k << n spring-like attractions. If so you can take care of the attraction component in O(n * k) by storing attraction in adjacency list instead of adjacency matrix.

A: In the end, I implemented what I described in my second case and it worked well. I maintained and iterated through a collection of neighbours for each node, which allowed the entire acceleration routine to be easily parallelized (along with Barnes-Hut). Overall time complexity is O(max(n log n, k)) where k is the total number of edges. My C# implementation handles around 100000 nodes and 150000 edges at an acceptable level of performance.


text:
Q: C# - Se puede hacer un list de struct? Como se declara? Se puede hacer un list de struct? Como se declara? Como se añadiria o borraría un elemento?, Gracias.
Lo que pretendo hacer es algo como:
    List<T_POC> DatosActu= new List<DatosActu>();

    public struct DatosActu
    {

        public string Color;
        public DateTime Time;
        public double Altura;
        public string Categoria;

    }

A: Por supuesto que se puede hacer un List de una estructura. Tanto la declaración como el añadir elementos se hace exactamente igual que con cualquier otra lista:
List<DatosActu> DatosActuList = new List<DatosActu>(); //Definición de la lista

//Añado dos elementos a la lista
DatosActuList.Add(new DatosActu() { Color = "Rojo", Time = DateTime.Now, Altura = 2, Categoria = "categoria" });
DatosActuList.Add(new DatosActu() { Color = "Azul", Time = DateTime.Now, Altura = 5, Categoria = "categoria2" });

//Borrado de elementos
DatosActuList.RemoveAt(0); //Borro elemento por indice
DatosActuList.Remove(DatosActuList.Where(x => x.Color == "Azul").FirstOrDefault()); //Borro por color


text:
Q: Присвоить нескольким серверам один внешний IP У нас есть 4  убунту сервера.
Каждый имеет свой внешний ip.
Для работы с серверами нам нужен VNC.
Задача:
Нам нужно чтобы при любом выходе в интернет (браузер, запросы из приложений) внешний ip был у всех одинаковый.
И при этом чтобы остался доступ к каждому серверу через VNC.
Подскажите как это возможно реализовать?

A: Сделать один из серверов шлюзом для остальных.
А доступ к vnc можно перенаправлением портов.
Минус - утилизация сети через один сервер. Но можно выбрать самый мощный сервер с хорошей сетевухой


text:
Q: Is there any way to replay events in a date range? I am implementing an example of spring-boot and axon. I have two events
(deposit and withdraw account balance). I want to know is there any way to get the state of the Account Aggregate by a given date ?
I want to get not just the final state, but to replay events in a range of dates.

A: I think I can help with this.
In the context of Axon Framework, you can start a replay of events by telling a given TrackingEventProcessor to 'reset' it's Tokens. By the way, the current description on this in the Reference Guide can be found here.
These TrackingTokens are the objects which know how far a given TrackingEventProcessor is in terms of handling events from the Event Stream. Thus resetting/adjusting these TrackingTokens is what will issue a Replay of events.
Knowing all these, the second step is to look at the methods the TrackingEventProcessor provides to 'reset tokens', which is threefold:

*

*TrackingEventProcessor#resetTokens()

*TrackingEventProcessor#resetTokens(Function<StreamableMessageSource, TrackingToken>)

*TrackingEventProcessor#resetTokens(TrackingToken)
Option one will reset your tokens to the beginning of the event stream, which will thus replay everything.
Option two and three however give you the opportunity to provide a TrackingToken.
Thus, you could provide a TrackingToken starting from several points on the Event Stream. So, how do you go about to creating such a TrackingToken at a specific point in time? To that end, you should take a look at the StreamableMessageSource interface, which has the following operations:

*

*StreamableMessageSource#createTailToken()

*StreamableMessageSource#createHeadToken()

*StreamableMessageSource#createTokenAt(Instant)

*StreamableMessageSource#createTokenSince(Duration)
Option 1 is what's used to create a token at the start of the stream, whilst 2 will create a token at the head of the stream.
Option 3 and 4 will however allow you to create a token at a specific point in time, thus allowing you to replay all the events since the defined instance up to now.
There is one caveat in this scenario however. You're asking to replay an Aggregate. From Axon's perspective by default the Aggregate is the Command Model in a CQRS set up, thus dealing with Commands going in to your system. In the majority of the applications, you want Commands (e.g. the requests to change something) to occur on the current state of the application. As such, the Repository provided to retrieve an Aggregate does not allow specifying a point in time.
The above described solution in regards to replaying is thus solely tied to Query Model creation, as the TrackingEventProcessor is part of the Event Handling side in your application most often used to create views. This idea also ties in with your questions, that you want to know the "state of the Account Aggregate" at a given point in time. That's not a command, but a query, as you have 'a request for data' instead of 'the request to change state'.
Hope this helps you out @Safe!


text:
Q: ViewFlipper is causing Null Pointer Exception with animation I am making a calculator app that of course has lots of buttons specifically imagebuttons in my case. The app works in 2.3 but cause issues for 4.0. The issue is that I get a NullPointerException with my ViewFlipper showing the next view.
phhistbnt.setOnClickListener(new View.OnClickListener()
{
    @Override
    public void onClick(View v)
    {
    try
    {
        vib.vibrate(30);

        if(animChoice == 0)
            vf1.showNext(); // issue here and most likely the rest of them
        else if(animChoice == 1)
        {
            vf1.setOutAnimation(topUp);
            vf1.showNext();
            vf1.setInAnimation(Fl);
        }
        else if(animChoice == 2)
        {
            vf1.setOutAnimation(fadeOut2);
            vf1.showNext();
            vf1.setInAnimation(hy);
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}
});

Here is LogCat:
08-18 21:55:29.301: W/System.err(6141): java.lang.NullPointerException
08-18 21:55:29.301: W/System.err(6141):     at
f7Calc.com.KidzCalcActivity$12.onClick(CalcActivity.java:751)
08-18 21:55:29.301: W/System.err(6141): at
android.view.View.performClick(View.java:3549)
08-18 21:55:29.301: W/System.err(6141): at
android.view.View$PerformClick.run(View.java:14393)
08-18 21:55:29.311: W/System.err(6141):     at
android.os.Handler.handleCallback(Handler.java:605)
08-18 21:55:29.311: W/System.err(6141):     at
android.os.Handler.dispatchMessage(Handler.java:92)
08-18 21:55:29.311: W/System.err(6141):     at android.os.Looper.loop(Looper.java:154)
08-18 21:55:29.311: W/System.err(6141):     at
android.app.ActivityThread.main(ActivityThread.java:4945)
08-18 21:55:29.311: W/System.err(6141):     at
java.lang.reflect.Method.invokeNative(Native Method)
08-18 21:55:29.311: W/System.err(6141):     at
java.lang.reflect.Method.invoke(Method.java:511)
08-18 21:55:29.311: W/System.err(6141):     at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
08-18 21:55:29.311: W/System.err(6141):     at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
08-18 21:55:29.311: W/System.err(6141):     at dalvik.system.NativeStart.main(Native
Method)

In the emulator, Logcat will show:
08-18 22:19:25.144: I/Choreographer(1290): Skipped 67 frames!  The application may be
doing too much work on its main thread.

but it continue to work as usual.
I have started to use AsyncTask but I am unsure how to use it. Please any help will be appreciated.

A: I figure it out with the help of Paul. Before upgrade to ICE 4.0.x, I had to resize in code the buttons for a screen size that had 960x540 resolution because there was no layout for that screen size. Apparently when I had upgraded my phone to ICE (Evo 3D), ICE uses the layout-sw360dp layout for 960x540 instead of nothing at all. After adding that to the list of layouts and entering in the corrected IDs need for the activity, walla, it works.


text:
Q: Printing rhomboid using scanner in eclipse Enter edge length of your rhomboid: 5
Here is your rhomboid:

    *****
   *****
  *****
 *****
*****

I need to print that rhomboid with scanner. I get like: * * * * * *
My code was like that normally I'm not that bad but i couldn't even do the first line:
import java.util.Scanner;
public class rhomboid {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        System.out.println("Enter edge lenght of your rhomboid: ");
        int edgelenght = scan.nextInt();
        System.out.println("Here is your rhomboid:");

        while(edgelenght > 0){
            System.out.print(" ");
            System.out.print("*");
            edgelenght--;

A: So your code will just print 1D output..
Output:- *****
So, to solve this you need two loops one for row and column.Now a little modification in 2D printing for rhombus is, first now there must be gap of 4 spaces before printing,it can be achieved by using one more variable k as shown below.
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    System.out.println("Enter edge lenght of your rhomboid: ");
    int edgelenght = scan.nextInt();
    int k = edgelenght - 1;
    for (int i = 0; i < edgelenght; i++) {

        for (int j = 0; j < k + edgelenght; j++) {
            if (j < k) {
                System.out.print(" ");
            } else {
                System.out.print("*");
            }
        }
        k--;
        System.out.println();
    }
}

A: What you get is what you wrote in your code.
while(edgelenght > 0){
    System.out.print(" ");
    System.out.print("*");
    edgelenght--;
}

will print edgelenght times a space " " and after that a "*".
What you want is something like this:
for(int line = 0; line < edgeLength; line++){
    // in line 0 print 4 spaces (5-1), in line 3 print 1 (5-1-3), in line 4 (the last one) print 0
    for(int space = 0; space < edgeLength - line - 1; space++){
        System.out.print(" ");
    }
    for(int asterix = 0; asterix < edgeLength; asterix++){
        System.out.print("*");
    }
    // print a newline
    System.out.println("");
}

You need to first loop over the lines.
For every line you need a loop to print spaces. And one to print *.


text: Q: how to access portable usb storage device from android code? Currently I am working on a project which needs the capability to access the portable usb storage device connecting to an android device using OTG cable. How can I access the connected storage device in android code? Thanks!


text:
Q: log4net Adonet Appender Connection Issue I have developed a windows service in which I am using a timer control to perform some scheduled tasks. The timer elapse event occurs every 5 minutes in which a log entry is made using log4net appender to Oracle database.
All works fine until the DB Server closes all connections for nightly cold backup. Since that time all logs in DB are missed and nothing is logged unless service is restarted even though the backup process takes less than 30 mins.
From other posts I found that log4net uses only one connection which if lost then all subsequent logs are discarded. To remedy this I started using ReconnectOnError attribute set as true in its configuration. But unfortunately, the issue is still there. The logs are still missing after the backup. I enabled tracing and found following errors but I don't know how to resolve this issue.

log4net:ERROR [CustomAdoNetAppender] Exception while writing to database
  Oracle.DataAccess.Client.OracleException ORA-03113: end-of-file on communication channel    at Oracle.DataAccess.Client.OracleException.HandleErrorHelper(Int32 errCode, OracleConnection conn, IntPtr opsErrCtx, OpoSqlValCtx* pOpoSqlValCtx, Object src, String procedure)
     at Oracle.DataAccess.Client.OracleException.HandleError(Int32 errCode, OracleConnection conn, String procedure, IntPtr opsErrCtx, OpoSqlValCtx* pOpoSqlValCtx, Object src)
     at Oracle.DataAccess.Client.OracleCommand.ExecuteNonQuery()
     at log4net.Appender.AdoNetAppender.SendBuffer(IDbTransaction dbTran, LoggingEvent[] events)
     at log4net.Appender.AdoNetAppender.SendBuffer(LoggingEvent[] events)

and:

log4net:ERROR [CustomAdoNetAppender] Exception while writing to database
  System.InvalidOperationException: Connection is already part of a local or a distributed transaction
     at Oracle.DataAccess.Client.OracleConnection.BeginTransaction(IsolationLevel isolationLevel)
     at Oracle.DataAccess.Client.OracleConnection.BeginDbTransaction(IsolationLevel isolationLevel)
     at System.Data.Common.DbConnection.System.Data.IDbConnection.BeginTransaction()
     at log4net.Appender.AdoNetAppender.SendBuffer(LoggingEvent[] events)

Any help on this highly appreciated!!

A: Personally I'd consider this to be a bug in the log4net AdoNetAppender.
In log4net 1.2.11 AdoNetAppender commits the cardinal sin of keeping an open connection rather than using connection pooling.
Also the ReconnectOnError option looks broken: it only attempts to reconnect if the current connection state is not ConnectionState.Open, which seems wrong: I don't believe that the connection state changes when there has been an error (the enum value ConnectionState.Broken is documented in MSDN as being reserved for future versions of the product).
All in all, I'd recommend you implement your own custom appender that does connection pooling properly.  It's not a very big class so would be easy to duplicate and fix.


text:
Q: Exec format error when compiling C file for Python extension I am trying to extend python using a simple C file.  I succeeded in creating my own python module, but I also need the C file itself to compile and run as a standalone executable.  I can successfully compile it, but when I try to run it I get the error "cannot execute binary file: Exec format error".
Here is my C source file (hellomodule.c):
#include <Python.h>

void print_hello(const char* name){
    printf("Hello %s!\n", name);
}

//Only used by Python
static PyObject*
say_hello(PyObject* self, PyObject* args)
{
    const char* name;

    if (!PyArg_ParseTuple(args, "s", &name))
        return NULL;

    //printf("Hello %s!\n", name);
    print_hello("World");

    Py_RETURN_NONE;
}

//Only used by Python
static PyMethodDef HelloMethods[] =
{
    {"say_hello", say_hello, METH_VARARGS, "Greet somebody."},
    {NULL, NULL, 0, NULL}
};

//Only used by Python
PyMODINIT_FUNC
inithello(void)
{
    (void) Py_InitModule("hello", HelloMethods);
}

int main(){
    print_hello("World");
}

I can "successfully" compile it without any errors or warnings with the following:
gcc -I /usr/include/python2.7 -c hellomodule.c -o hellomodule

After making the "hellomodule" file executable, I run it and get the error:
-bash: ./hellomodule: cannot execute binary file: Exec format error

Why would this be causing such an error?

A: You are trying to execute an object file, that is not an executable. To compile your code as a module you need something like

gcc -Wall -Werror -Wextra -O2 -I/usr/include/python2.7 \
    -shared hellomodule.c -o hellomodule.so -lpython2.7

but to link correctly to everything and add all the possible include directories there is a script called python-config you just need to invoke it like this
gcc -Wall -Werror -Wextra -O2 `python-config --includes` \
    -shared hellomodule.c -o hellomodule.so `python-config --libs`

and even better, the script providesCFLAGS and LDFLAGS too, so finally
gcc -Wall -Werror -Wextra -O2 `python-config --cflags` \
    -shared hellomodule.c -o hellomodule.so `python-config --ldflags`

and then, copy the resulting file to /usr/lib/python2.7/site-packages.
After that, you can load the module in a python script like this

import hellomodule

Object files are intermediate binary files used ultimately by the linker (ld probably) to produce the final binary. A python module has no main() function and it has to be a runtime loadable shared object which exports some predefined symbols that the python interpreter will use to load the module into the python script/program.
Note: To correctly do this and not die trying create a Makefile, like this
CFLAGS = `python-config --cflags` -Wall -Werror # add more if needed
LDFLAGS = `python-config --ldflags` # add more if needed
OBJS = hellomodule.o # add more if needed

all: $(OBJS)
    $(CC) $(CFLAGS) $(LDFLAGS) -shared -o modulename.so $(OBJS)

%.o: %.c
    $(CC) -c $(CFLAGS) $<

ensure that you use tabs instead of spaces for indentation, and then run make in the same directory where the Makefile and the source files are.


text:
Q: Feeding output of nvidia-smi to tail command returns error I have a custom nvidia-smi message where some additional information (e.g., username) is also output underneath the original output of the nvidia-smi message.
I want to feed that output to a tail command so that I only see the bottom part of the message. How should I go about doing that?
Right now I have the following:
alias gpu='watch -n 1 "nvidia-smi | tee /dev/stderr | awk '"'"'/ C / {print \$3}'"'"' | xargs -r ps -up"'

which works fine. But again, it only shows the top portion.
In order to show the bottom portion, I've tried something like:
alias gpu2="watch -n 1 \"nvidia-smi | awk \"/ C / {print \$3}\" | xargs -r ps -up | tail -n $(($LINES - 2))\""

but when I run this command I get the following output:
Every 1.0s: nvidia-smi | awk / C {print } | xargs -r ps -up | tail -n 40

awk: cmd. line:1: /
awk: cmd. line:1:  ^ unexpected newline or end of string

I'm not exactly sure what the problem is and how to interpret the error message. I've tried escaping the slashes but that didn't work.
How should I go about solving this issue? Thanks.


text:
Q: Opscenter doesn't show my key spaces I have Cassandra cluster (ver 2.0.12) and Datastax Agents 5.0.1. Also I using OpsCenter 5.1.0. In "Explorer" tab I see no keyspaces.
Query from CLI:
 SELECT keyspace_name FROM system.schema_keyspaces;

show my keyspaces. I try URL:
http://<cluster_url>:8888/<cluster_name>/keyspaces

that show me JSON output which conatain keyspaces info(i think), but "Explorer" tab still empty.

A: Opscenter does not necessarily automatically connects to the local node to get the cluster information. You can review this piece of documentation to check what is in your configuration files, and update them properly. There can be multiple reasons why OpsCenter can't connect to your local instance.
Or you can use the wizard to add a cluster to manage. This should populate data properly into the config files.


text:
Q: Python - Move files to root directory in Ubuntu I have to move all files from a particular directory to a root directory by using Python script. I failed with the following code with [Errno 13] Permission denied error.
import shutil
import os

source = '../json'
dest = '/var/www/json'
files = os.listdir(source)

for f in files:
    shutil.move(source+"/"+f, dest)

Is it possible to add sudo with this code or is there any other method to move files to root folder?
I am working in Ubuntu16.04

A: you could add your user to the folder permissions and give the user write access to that folder.
use chown or chmod to adjust permissions on the destination folder

A: I can think of three possible solutions to this:

*

*Running python as sudo: sudo python script.py. Probably not the nicest way as there are possible security concerns.

*Change the permissions of the folder so the user running the python script has access to copy/edit files in those folders.

*Call cp/mv as a subprocess from python as root. Basically the same as the first option. Can either be done by getting the user to type in root's password which I guess isn't great for you. Or you can use something like polkit to avoid using a password.

I would suggest the 2nd option is best and easiest in the long run.


text:
Q: Sort an associative array with custom order How can we sort an associative array with custom order?
My array look like this
Array
(
    [pa_color] => Array
        (
            [name] => pa_color
            [value] =>
            [position] => 0
            [is_visible] => 1
            [is_variation] => 1
            [is_taxonomy] => 1
        )

    [pa_dimension] => Array
        (
            [name] => pa_dimension
            [value] =>
            [position] => 1
            [is_visible] => 1
            [is_variation] => 0
            [is_taxonomy] => 1
        )

    [pa_travel-duration] => Array
        (
            [name] => pa_travel-duration
            [value] =>
            [position] => 2
            [is_visible] => 1
            [is_variation] => 0
            [is_taxonomy] => 1
        )

    [pa_travel-type] => Array
        (
            [name] => pa_travel-type
            [value] =>
            [position] => 3
            [is_visible] => 1
            [is_variation] => 0
            [is_taxonomy] => 1
        )

    [pa_travelling-with] => Array
        (
            [name] => pa_travelling-with
            [value] =>
            [position] => 4
            [is_visible] => 1
            [is_variation] => 0
            [is_taxonomy] => 1
        )

    [pa_volume] => Array
        (
            [name] => pa_volume
            [value] =>
            [position] => 5
            [is_visible] => 1
            [is_variation] => 0
            [is_taxonomy] => 1
        )

    [pa_weight] => Array
        (
            [name] => pa_weight
            [value] =>
            [position] => 6
            [is_visible] => 1
            [is_variation] => 0
            [is_taxonomy] => 1
        )

)

and i want this array is like pa_travel-duration first pa_volume second ?? I know there is a native php function usort but i could not understand this.

A: This will do the work, but im pretty sure there's much better ways to do it:
Code:
$array = array("pa_color" => "color",
              "pa_dimension" => "dimension",
              "pa_travel-duration" => "Random Stuff: " . rand(100,999),
              "pa_volume" => "volumen"
              );
$tmp = array("pa_travel-duration" =>  $array["pa_travel-duration"],
            "pa_volume" =>  $array["pa_volume"],
);

unset($array["pa_travel-duration"], $array["pa_volume"]);
$array = array_merge($tmp,$array);

print_r($array);

Result:
Array
(
    [pa_travel-duration] => Random Stuff: 127
    [pa_volume] => volumen
    [pa_color] => color
    [pa_dimension] => dimension
)

Take care because if the array doesn't have the proper key it will throw an error, you need to add few checks there.

A: $sort_by = array('pa_travel-duration', 'pa_volume', 'pa_color','pa_dimension','pa_travel-type','pa_travelling-with','pa_weight');
$temp_arr = array();
foreach ($sort_by as $key) {
    $temp_arr[$key] = $data[$key];
}
$data = $temp_arr;

echo '<pre>'; print_r($data);

Define your order in $sort_by array


text:
Q: Detecting the termination of multiple child processes I have to write code for creating multiple child processes using a parent.
Parent process should be sleeping until it creates the number of processes.
Child processes send SIGCHLD signal to parent process to interrupt from the sleep and force the parent to call wait for the Collection of status of terminated child processes.
I have write following code on UBUNTU:
#include <stdlib.h> /* needed to define exit() */
#include <unistd.h> /* needed for fork() and getpid() */
#include <signal.h> /* needed for signal */
#include <stdio.h>  /* needed for printf() */

int main(int argc, char **argv)
{
void catch(int);    /* signal handler */
void child(int);    /* the child calls this */
void parent(int pid);   /* the parent calls this */
int pid;        /* process ID */
int i;          /* Number of processes*/

signal(SIGCHLD, catch); /* detect child termination */

for(i=0;i<5;i++)
{
    pid = fork();   /* create child process*/
    switch (pid)
    {
    case -1:    /* something went wrong */
        perror("fork");
        exit(1);
    case 0:     /* a fork returns 0 to the child */
        child(i+1);
        break;
    default:    /* a fork returns a pid to the parent */
        //parent(pid);
        break;
    }
}
exit(0);
}

void child(int id)
{
    printf("\tchild%d: I'm the child\n",id);
    sleep(10);      /* do nothing for 3 seconds */
    printf("\tchild: I'm exiting\n");
    exit(id);       /* exit with a return code of 123 */
}

void parent(int pid)
{
    printf("parent: I'm the parent\n");
    sleep(15);      /* do nothing for five seconds */
    printf("parent: exiting\n");
}

void catch(int snum)
{
    int pid;
    int status;

    pid = wait(&status);
    printf("parent: child process exited with value %d\n",WEXITSTATUS(status));
    /* WEXITSTATUS(status):
     * Since only the last 8 bits are available
     * it will be logical to mask the upper bit by
     * doing a bitwise and operation with 255.
     * A system defined macro does this for us.
     */
}

And I am getting output like this:
parent: I'm the parent
    child1: I'm the child
    child: I'm exiting
parent: child process exited with value 1
parent: exiting
parent: I'm the parent
    child2: I'm the child
    child: I'm exiting
parent: child process exited with value 2
parent: exiting
parent: I'm the parent
    child3: I'm the child
    child: I'm exiting
parent: child process exited with value 3
parent: exiting
parent: I'm the parent
    child4: I'm the child
    child: I'm exiting
parent: child process exited with value 4
parent: exiting
parent: I'm the parent
    child5: I'm the child
    child: I'm exiting
parent: child process exited with value 5
parent: exiting

whereas I want output like this:
parent: I'm the parent
    child1: I'm the child
    child: I'm exiting
parent: child process exited with value 1
    child2: I'm the child
    child: I'm exiting
parent: child process exited with value 2
    child3: I'm the child
    child: I'm exiting
parent: child process exited with value 3
    child4: I'm the child
    child: I'm exiting
parent: child process exited with value 4
    child5: I'm the child
    child: I'm exiting
parent: child process exited with value 5
parent: exiting

what changes I should make in my code...?
please help..!!!

A: As far as I understand the code, the main function exits after starting the children. You need to add code that waits until all children have exited, means the SIGCHLD signal was caught for each exit of your child.

A: You are printing parent: I'm the parent and parent: exiting within the loop. If you want them to be printed only once, move them out of the loop.
You may also want to look into using the wait or waitpid functions for waiting for child process termination instead of using a signal handler and sleep.


text:
Q: After a clean installation Ubuntu does not see the hdmi port Acer Nitro 5 i5-8300H GeForce 1050.
Installed Ubuntu 20.04 and stopped working monitor via hdmi(before it was 19.10 and everything worked). xrandr does not output only the laptop display, there are no lines with the mention of hdmi. Tried switching to lightdm didn't help. Reinstalling the system several times also failed. Switching drivers didn't help.

A: I had the same problem. What worked for me was to downgrade the NVIDIA driver to version 390.

A: Check in the NVIDIA Server. If it is empty, this implies your video graphics card (NVIDIA) is not being loaded. if so, reboot your system and while booting stop at the grub system and press e to change to edit mode.
You should see some line that starts with Linux. In that line, if nomodeset is written, remove it and press Ctrl+x to save and now after booting up, try connecting the monitor. It should work like a charm.


text:
Q: Convert Mo-Sa and Mo-Fr to: Mo, Tue, Wed, ... -columns I want to transform following Column:
Col_openingHours:
1: Mo-Sa: 03:00 - 11:00
| 2: Mo-Sa: 02:00 - 10:00
into:
Col_monday:
1: 03:00 - 11:00 |
2: 02:00 - 10:00
Col_tuesday:
1: 03:00 - 11:00 |
2: 02:00 - 10:00
...
How i can get this in Dataprep?
I also have some values in the col1 like "Mo-Fr". And then de Col_saturday has a different columns as source than the showed example (e.g.: Col_openingHours2).
I tried convert values to Columns, but it seems like the wrong tool.
Then i tried to create new columns like col_monday and wanted to set the values with "If(equal (col-openingHours, "Mo-Sa"), ... ) ..
(For this i splitted the cell [Mo-Sa |split| 03:00 - 11:00])
But that wasnt the right tool, too i think.
would be very happy for helping me :)

A: The most straightforward way to handle this would be to turn your openingHours column into a quick JSON object, so you'd have something like

    {
        "1": [{
            "Mon": "03:00 - 11:00",
            "Tues": "03:00 - 11:00",
            "Weds": "03:00 - 11:00"
        }],
        "2": [{
            "Mon": "02:00 - 10:00",
            "Tues": "02:00 - 10:00",
            "Weds": "02:00 - 10:00"
        }]
    }

This should be achievable by using text pattern replacements and a bit of regex as needed. Once that's done, you can unnest the data itself into columns as you desire, now with the right splits per value.


text:
Q: How to take postgres backup via pg_basebackup I have to take the pg_basebackup of my postgres cluster. So how I can take the backup of this cluster.
I use the Bitnami Helm chart for PostgreSQL installation. Following Link for reference
https://phoenixnap.com/kb/postgresql-kubernetes
from that 2nd part. Deploy PostgreSQL by Creating Configuration from Scratch.
After successful installation
I tried to take pg_basebackup from localhost
from Localhost execution-->
pg_basebackup -h localhost -U postgres -D /root/base_bkp -v

pg_basebackup: error: server closed the connection unexpectedly
        This probably means the server terminated abnormally
        before or while processing the request.

2023-01-03 07:16:42.889 GMT [1005845] FATAL:  no pg_hba.conf entry for replication connection from host "10.XX.XXX.X", user "postgres", SSL off
2023-01-03 07:16:42.889 GMT [1005845] DETAIL:  Client IP address resolved to "10-XX-XXX-X.postgres-postgresql-ha-pgpool.postgres.svc.cluster.local", forward lookup not checked.

host "10.XX.XXX.X" --> This is the pgpool node ip
root@hostname~a# kubectl get pods -n postgres -o wide
NAME                                             READY   STATUS    RESTARTS   AGE     IP              NODE        NOMINATED NODE   READINESS GATES
postgres-postgresql-ha-pgpool-6XXXXXX-fXXXX   1/1     Running   0          1d7h   10.XX.XXX.X            <none>           <none>
postgres-postgresql-ha-postgresql-0              1/1     Running   0          1d7h   10.XX.YYY.Y        <none>           <none>
postgres-postgresql-ha-postgresql-1              1/1     Running   0          1d7h   10.XX.ZZZ.Z      <none>           <none>
postgres-postgresql-ha-postgresql-2              1/1     Running   0          1d7h   10.XX.PPP.P            <none>           <none>

Can anyone help me that from where I need to initiate the backup and how?


text:
Q: django-rest-framework: How to prepopulate django-rest-framework serializer fields before validation? Hello I am new to django and I am using django-rest-framework for making res APIs. Is there any hook or any Signals like django for executing a callback on pre validation state?
I need to prepopulate some data outside the admin area before the validation and then I am doing this stuff:
  if serializer.is_valid():
      serializer.save()

Here is my serializer class:
class HeroSerializer(serializers.HyperlinkedModelSerializer):
  class Meta:
    model = Hero
    fields = ['name', 'alias', 'gender']

Do I need another serializer for write operations? or should I create a custom Signal for it? Please suggest me an efficient way to do this.


text:
Q: cannot chain joins using string to left_joins Summary:
I have a many to many relationship between attachments and rules, through alerts.
I have a given rule and a given selection of attachments (those with a given bug_id).
I need to go through all the selected attachments an indicate whether there is an alert for the rule or not, with a different CSS background-color.
Outer Join
I get the correct results with the following query:
SELECT attachments.*, alerts.rule_id
FROM attachments
     LEFT OUTER JOIN alerts ON alerts.attachment_id = attachments.id
                               and alerts.rule_id = 9
WHERE attachments.bug_id;

I'm looking for something like:
bug.attachments
   .left_joins(alerts: {'rules.id' => 9})
   .select('attachments.*, alerts.rule_id')

Database
class Alert < ApplicationRecord
  belongs_to :attachment

class Attachment < ApplicationRecord
  has_many :alerts

attachments
|  id   | bug_id |
| 14612 | 38871  |
| 14613 | 38871  |
| 14614 | 38871  |

alerts
| attachment_id | rule_id |
|     14612     |    9    |
|     14614     |    8    |

Condition in the From Clause
Without the alerts.rule_id = 9 condition in the FROM clause, we get the following result:
|  id   | rule_id |
| 14612 |    9    |
| 14614 |    8    |
| 14613 |   NULL  |

So having a WHERE clause WHERE alerts.rule_id = 9 or alerts.rule_id is NULL would lose the result for 14612
So the following won't work:
bug.attachments
   .joins(:alerts)
   .select('attachments.*, alerts.rule_id')
   .where( ??? )

Edit
The above is a simplified and corrected version of my original question.
The original question is below:
alerts belongs to rules and attachments, and attachments belong to bugs.
class Alert < ApplicationRecord
  belongs_to :attachment
  belongs_to :rule

class Attachment < ApplicationRecord
  belongs_to :bug
  has_many :alerts

class Bug < ApplicationRecord
  has_many :attachments

For a given rule, I need to show all the attachments for a given bug, and whether there is an alert or not.  I want the following SQL:
SELECT attachments.*, alerts.id as alert_id
FROM `attachments`
  LEFT OUTER JOIN `alerts` ON `alerts`.`attachment_id` = `attachments`.`id`
  LEFT OUTER JOIN `rules` ON `rules`.`id` = `alerts`.`rule_id` AND rules.id = 9
WHERE `attachments`.`bug_id` = 38871

I can get this from:
bug.attachments
   .joins("LEFT OUTER JOIN `alerts` ON `alerts`.`attachment_id` = `attachments`.`id`")
   .joins("LEFT OUTER JOIN `rules` ON `rules`.`id` = `alerts`.`rule_id` AND rules.id = 9")
   .select('attachments.*, alerts.id as alert_id')
   .map{|attach| [attach.file_name, attach.alert_id]}

What I want to know is how to avoid calling joins with a string SQL fragment.
I'm looking for something like:
bug.attachments
   .left_joins(alerts: {rule: {'rules.id' => 9}})
   .select('attachments.*, alerts.id as alert_id')
   .map{|attach| [attach.file_name, attach.alert_id]}

Is there anyway to avoid passing an SQL string?

A: Actually I think you will able to get the right results by putting rules.id = 9 in where clause.
SELECT attachments.*, alerts.id as alert_id
FROM `attachments`
LEFT OUTER JOIN `alerts` ON `alerts`.`attachment_id` = `attachments`.`id`
LEFT OUTER JOIN `rules` ON `rules`.`id` = `alerts`.`rule_id`
WHERE `attachments`.`bug_id` = 38871 AND (rules.id = 9 OR rules.id IS NULL)


text:
Q: Equation for force needed to replace energy lost by a pendulum each swing I'm sure this is just a question of not knowing the right search terms, but I'm trying to find out how much energy I would need to put back into a pendulum in order to keep it swinging forever.
Specifically, I'm toying with the idea of building something like one of those automatic swings that rocks a baby but mechanical, rather than electric and possibly large enough for a bigger kid or even an adult. Kind of like a giant grandfather clock with a human pendulum.
I'm sure the amount of push required to keep the swing going indefinitely would be in proportion to the weight of the pendulum (or kid, or lazy grown up) but while I've found dozens of websites with equations describing the period of the pendulum but nothing describing with how much force I need to push to keep it going. Can someone direct me to a resource or suggest different search terms?

A: The force needed would be equal to the total air resistance of the pendulum, and the friction resistance of the bearing point. these will vary depending on the aerodynamics of the pendulum, and the type of bearing point and it's lubrication, and the weight on the bearing point. A good set of steel roller bearings with thin oil lubricant will normally have very little resistance, the most resistance will normally be from air displacement, depending on air density and aerodynamics. The weight of the pendulum only affects the bearing point, as a pendulum's "weight"  does not change its duration.


text:
Q: Keras slow on GPU with LSTM Networks I am training my model with keras. When I compare the performance on GPU vs CPU. The CPU version is much faster as the GPU version
How i can fix these errors below?
I tried to force tensorflow to the GPU, i get these errors:
tensorflow.python.framework.errors_impl.InvalidArgumentError: Cannot assign a device to node 'gradients/simple_rnn_1/while/Select_1_grad/Select/f_acc':
Could not satisfy explicit device specification '/device:GPU:0' because no supported kernel for GPU devices is available.
Colocation Debug Info:
Colocation group had the following types and devices:
Tile: CPU
StackPush: GPU CPU
Relu: GPU CPU
ReluGrad: GPU CPU
ZerosLike: GPU CPU
Select: GPU CPU
StackPop: GPU CPU
AddN: GPU CPU
RefEnter: GPU CPU
Stack: GPU CPU

My Model looks like this:
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
masking_1 (Masking)          (None, None, 3)           0
_________________________________________________________________
simple_rnn_1 (SimpleRNN)     (None, None, 50)          2700
_________________________________________________________________
time_distributed_1 (TimeDist (None, None, 11)          561
_________________________________________________________________
activation_1 (Activation)    (None, None, 11)          0
=================================================================
Total params: 3,261
Trainable params: 3,261

EDIT: When i switch the backend to theano, the same net runs much faster on the GPU, i think there is a problem with "tile" on GPU in tensorflow

A: If you are using ReLU, try use a Tanh loss.
I was using ReLU for a LSTM-DNN model at 100 epochs. Each Epoch went from about 14 second to 2
hopefully this solves your problem - I was running on GPU too so it could just be your processor unfortunately - use google Colab if you are bottlenecked - you get access to free GPU usage


text:
Q: Addresses in USA I have a problem with street part of an address.
Can you give me some examples?
How do you write this address on an envelope? Consider a tall building. I want to send my letter to 9th floor and 4th unit, for example.
What is 799 in "799 E DRAGRAM". Is it street number or house number. How do you say?

A: In the US, an apartment in a high-rise is almost always addressed by a simple number (e.g. 1204) or a number  with an alpha suffix (e.g. 12C):
{addressee}
{building number on the street} {street name}
Apt {apartment number}
{City} {State abbreviation} {zipcode}

Mr Tom Jones
123 Main Street
Apt 1204
Philadelphia PA 19104

The apartment chunk can be positioned after the street address, and the abbreviation for "Apartment", "Apt", can appear as a #-sign:
Mr Tom Jones
123 Main St #1204
Philadelphia PA 19104

The alpha suffix on the apartment number usually indicates which unit on the floor the apartment is, but you cannot assume that every building would use this convention; some do, some don't:
Mr Tom Jones
123 Main St #12D
Philadelphia PA 19104

On some occasions a floor number is given, but that is not typical with residences but businesses:
Acme Widgets Inc
500 Wilson Boulevard
2nd Floor
Baltimore MD 21222


text:
Q: CATiledLayer or CALayer drawing UIImage not working Good day all;
I am trying to manually (not using sublayers) draw images within a CATiledLayer but it is not behaving as it should with the defined solution. I undertand that when you call 'CGContextDrawImage' you must scale and translate so as to flip it but I cannot for the life of me, get it to work.
I have a method called
 - (void)drawInContext:(CGContextRef)context Image:(UIImage *)image

which is called several times from with in
 - (void)drawInContext:(CGContextRef)context

to render all the images that go into the CATileLayer.
The following renders no images:
- (void)drawInContext:(CGContextRef)context Image:(UIImage *)image  {
    CGRect rect = CGRectMake(x, y, image.size.width, image.size.height);
    CGContextSaveGState(context);

    CGContextTranslateCTM(context, 0, image.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextDrawImage(context, rect, image.CGImage);

    CGContextRestoreGState(context);

The following produces an image but rendered incorrectly:
- (void)drawInContext:(CGContextRef)context Image:(UIImage *)image  {
     CGRect rect = CGRectMake(x, y, image.size.width, image.size.height);
     CGContextDrawImage(context, rect, image.CGImage);

Like wise with this:
- (void)drawInContext:(CGContextRef)context Image:(UIImage *)image {
    CGRect rect = CGRectMake(x, y, image.size.width, image.size.height);

    CGContextTranslateCTM(context, 0, image.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextDrawImage(context, rect, image.CGImage);

I have also tried:
UIGraphicsBeginImageContext
UIGraphicsEndImageContext

and
UIGraphicsPushContext
UIGraphicsPopContext

All do not work. I am missing something fundamental here and I suspect my approach to saving the contexts is not working.

A: OK I think I know what is happening here;
It appears that the image is actually rendering but rendering off screen. The flipping is not happening relative to the origin of the layer but rather the origin of the super layer.
The issue I am seeing is that I have a large layer and a large grid of sublayers. I assumed that a flip within the sublayer, would be relative to it's own co-orindates but that is not the case.


text:
Q: LED Hissing issue with circuits I have just recently designed and manufactured my very first PCB with the goal of it being a dedicated circuit to my project. I developed an ESP8266 WiFi Mood Light, but the problems I currently face with VERSION 1 is that is makes a sort of hissing noise when I change colors via Blynk, and the transistors used in the project get very hot very fast. I know this has something to do with the current throughout the circuit being to high, but I don't know how to go about it.
I am open to further suggestions as well.
Thanks
UPDATE: Thanks for the telling me the solution to the problem, but unfortunately after implementing it on a breadboard, the circuit didn't the way I wanted it too. After swapping the emitter with the collector, the RGB led strip would not change color via Blynk. I have no idea how to fix it now. (LED strip uses 3 Amps)
]3
[]4
UPDATE 2: I have changed the BJT type transistors to MOSFETS now. The system works without overheating, however the hissing noise still persists, I have researched about the idea of a low pass RC filter, but I am not sure if it would be suitable.

UPDATE 3: Thank you all for helping me troubleshoot this circuit. It now works without overheating, and hissing. It turns out the hissing was related to the MP1584EN, so I changed it.

A: All your output transistors are wired the wrong way round (red box): -

Neither are you using current limiting resistors in series with R, G and B pins.

A: Based on your other question where you say the strip uses 3 amps:
1 amp per 2n2222 is too much for the to-92 package 2n2222. Max collector emitter current for it is 800mA or 0.8A. Find a higher current transistor or use a logic level mosfet. The hissing may be related to the over driven transistor.


text:
Q: which algorithm is better for encrypt and decrypt data inside a project? which algorithm is better for encrypt and decrypt data inside a project?
i designed and developed a site like below :
htttp://www.soscharge.com
this site is about mobile charge codes ...
i want to encrypt mobile charge codes during insert to database and decrypt them for showing to users...
hash algorithm is not a good idea about this purpose (one way algorithm)
i heard something about symmetric and asymmetric algorithms (but i want to learn how can i write a simple and powerfull algorithm by myself)
thanks in advance

A: never - NEVER write your encryption-algorithms yourself if you are not an expert and get paid for it! Seriously: you will never get a good and secure algorithm working just by yourself. Use the tools in the Framework - System.Security.Cryptography namespace! And you don't ask for synchronous vs. asynchronous but I guess you are thinking on symmetric vs. assymetric algorithms
now to the answer:
as you have full controll of your database and an outsider should not be able to get to it you can use symmetric key algorithms because you protect your "secret" (the key) on your system and the user will never see it (or so it should be - if your system is secure can only a IT-guy tell you)

A:
which algorithm is better for encrypt and decrypt data inside a project?

You didn't give us any criteria on which to evaluate "better."
Frankly, it sounds like you're not a security expert. This stuff is so easy to get wrong, even if you pick the "best" algorithm (look at the recent RSA debacle). If you have secrets that truly need to be safeguarded, you should hire a security expert. Your stakeholders will thank you later.

(but i want to learn how can i write a simple and powerfull algorithm by myself)

Take a course. Read a book (or two; the Bruce Schneier books are decent). Practice for about 10,000 hours.

i heard something about synchronous and asynchronous algorithms

Symmetric and asymmetric, perhaps? I mean, this tells us all we need to know about your level of expertise on this subject.
Seriously, don't do this yourself. Get an expert to help you.

A: I assume that you need symmetric algo, by now best choice is AES. It's easy, strong and has implementations for most platforms and languages.


text:
Q: Suppose G is a group, and p is prime. Then the number of elements of G of order p is multiple of p-1. I need help.

Suppose $G$ is a group, and $p$ is prime. Then the number of elements of $G$ of order $p$ is multiple of $p-1$.

Give me any advise or note.

A: Hints:
1) Every element of order $p$ generates a cyclic subgroup of order $p$ isomorphic to $\mathbb Z_p$.
2) In that subgroup, every element except the identity has order $p$.
3) Any two subgroups of order $p$ intersect either at $e$, or they are identical.
4) The collection of all elements of order $p$ is a union of such subgroups of order $p$.
5) Count...

A: This can be generalized for arbitrary $n \geq 1$.
The number of elements of order $n$ is $k \cdot \varphi(n)$, where $k$ is the number of cyclic subgroups of order $n$ and $\varphi$ is the Euler totient function. This follows from the fact that a cyclic subgroup of order $n$ has exactly $\varphi(n)$ generators.


text:
Q: Update records using rake task desc "This task is called by the Heroku scheduler add-on"
task :queue => :environment do
  puts "Updating feed..."
  @books = Book.all
  @books.update_queue
  puts "done."
end

I have the above code in a file called scheduler.rake located in lib/tasks. When I run rake queue I get:
Updating feed...
rake aborted!
undefined method `update_queue' for #<Array:0x007ff07eb3ffd0>

That method is defined in my Books model as such:
def update_queue
    days_gone = (Date.parse(:new_books.last.created_at.to_s) - Date.today).to_i

    unless days_gone > -7
        new_book = self.user.books.latest_first.new_books.last
        new_book.move_from_queue_to_reading
        user.books.reading_books.move_from_reading_to_list
    else
        self.user.books.create(:title => "Sample book", :reading => 1)
    end
  end

Is this just not accessing the books and that's why it's giving me this undefined error? What am I doing wrong here? I simply want to update each book record.

A: As the error message states, you can't run an instance method on an array. Book.all returns an array of all items in your books table. You will need to loop through each instance in the array for this to work. You can do this one of two ways.
With standard block syntax:
@books.each do |book|
  book.update_queue
end

or by using the send method
Book.all.each.send(:update_queue)

Either way should accomplish the same thing.


text:
Q: Can javascript rewrite an external file I am working on a program where you would chose a directory and than the website will save data there. I know I could do this with cookies but I am challenging myself to do do it differently.
I would really appreciate help with this. Is it possible? If so how would I do it?

A: This is not possible, because JavaScript has no access to your filesystem.
The only thing you could do it trigger a filedownload from within JavaScript. But in this case the browser handles the whole download (maybe without selecting a directory).
And the other point is that your server has to serve the data. So you need another roundtrip and maybe sending some user information to the server is necessary.


text:
Q: Regex digit and dot(point) from a combined String I have got a String for example.
"Quantity : 2.85 kg"

Here I only need to extract the number with exact configuration 2.85.
String.replaceAll("[^0-9]",""); only extracts number as 285, but I need 2.85.
Kindly help.

A: You must be kidding guys, the pattern for a digit is
p = "/d*(./d+)?"

and extract it is :
 Matcher m = Pattern.compile(p)
while(m.find())
res = m.group(0)

A: Regex is any character, then one or more digits with a dot and following two digits, space and kg.
A capturing group is used to capture the part thas is to be extracted.
String test = "Quantity : 2.85 kg";

Pattern pattern = Pattern.compile(".*(\\d+\\.\\d\\d) kg");
Matcher matcher = pattern.matcher(test);

if(matcher.matches()){
    System.out.println(matcher.group(1));
}else{
    System.out.println("no match");
}


text:
Q: Regex expression for any times any character between two set of literals Hi a am new to regex and programming. I in a textual file want to search any thing (all characters) between first occurrences of two literal namely- 'html' and 'http'. I have tried lot of expression, but no success. Any help will be appreciated.

A: You could try this regex,
(?<=html).*?(?=http)

Use s switch to make dot to match newlines also.
Explanation:

*

*(?<=html) Positive lookbehind is used. It matches all the characters after the word html.

*.*? It matches any character zero or more times. ? after * makes the regex engine to match the shortest possibility.

*(?=http) Positive lookahead. Matches any characters before http.


text:
Q: DevExpress TableView Cell does have focus on CopyingToClipboard event I am trying to fix this customized DevExpress TableView. As you guess the following method handles CopyingToClipboard. When I cast FocusedElement it is a BaseEdit but not the one that I accually have selected. Its DisplayText is different.
I have changed the background color of the cell to make sure that it has the focus and it is the one that is selected. That is not the issue. Could you please share your wisdom.
private void CustomizedTableView_CopyingToClipboard(object sender, CopyingToClipboardEventArgs e)
    {
        TableView view = sender as TableView;

        if (view == null || view.Grid == null)
        {
            return;
        }

        BaseEdit edit = System.Windows.Input.Keyboard.FocusedElement as BaseEdit;
        edit.Background = Brushes.Red;
        VantageUtilities.SafeCopyToClipboard(DataFormats.Text, edit.DisplayText);
        e.Handled = true;
    }

A: You can use DataViewBase.ActiveEditor property to get the focused editor or you can use DataControlBase.CurrentCellValue property to get the focused value.
Here is example:
private void CustomizedTableView_CopyingToClipboard(object sender, CopyingToClipboardEventArgs e)
{
    TableView view = sender as TableView;

    if (view == null || view.Grid == null)
        return;

    string text = null;

    if (view.ActiveEditor != null)
        text = view.ActiveEditor.DisplayText;
    else
    {
        object value = view.Grid.CurrentCellValue;

        if (value != null)
            text = value.ToString();
    }

    if (text == null)
        return;

    VantageUtilities.SafeCopyToClipboard(DataFormats.Text, text);
    e.Handled = true;
}

PS: There are some CopySomethingToClipboard methods in DataControlBase class: DataControlBase.CopyCurrentItemToClipboard method, DataControlBase.CopyRangeToClipboard method, DataControlBase.CopyRowsToClipboard method, DataControlBase.CopySelectedItemsToClipboard method and DataControlBase.CopyToClipboard method. You can take a look at it.


text:
Q: Two Same MongoDB queries one yeild results one empty responce db.posts.find({comments:{$elemMatch:{user:'Khan'}}})
db.posts.find({comments:{$elemMatch:{user:'khan'}}})

this is really a mind twister for me, above are two $elemMatch search queries i use in MongoDb shell, i typed these in Code Studio, when i copy paste first line in shell it return nothing, when i copy paste the 2nd line in shell, expected result is returned...
both are same then why the response is different???

following is the posts collection in the db
{
    "_id": {
        "$oid": "5eda19c6a38d4418e311e43b"
    },
    "title": "post1",
    "body": "body of post 1",
    "category": "news",
    "tags": [
        "news",
        "events"
    ],
    "user": {
        "name": "author name",
        "status": "author"
    },
    "date": "Fri Jun 05 2020 15:09:10 GMT+0500 (Pakistan Standard Time)",
    "likes": 6,
    "comments": [
        {
            "user": "mehtab",
            "body": "this is some comments 1",
            "date": "Fri Jun 05 2020 16:47:17 GMT+0500 (Pakistan Standard Time)"
        },
        {
            "user": "khan",
            "body": "this is some comments 2",
            "date": "Fri Jun 05 2020 16:47:17 GMT+0500 (Pakistan Standard Time)"
        },
        {
            "user": "saad",
            "body": "this is some comments 3",
            "date": "Fri Jun 05 2020 16:47:17 GMT+0500 (Pakistan Standard Time)"
        }
    ]
}

MongoDB 4.2.7 Community

A: Your two queries are indeed different. One has the first letter upper-cased, and one does not, and string-matching is case-sensitive.
Uppercase K:
db.posts.find({comments:{$elemMatch:{user:'Khan'}}})

Lowercase k:
db.posts.find({comments:{$elemMatch:{user:'khan'}}})

A: I'm sure you want to know why this happens and me too, but following the MongoDB Documentation, if you specify a single query predicate in the $elemMatch expression, $elemMatch is not necessary.
Since the $elemMatch only specifies a single condition, the $elemMatch expression is not necessary, and instead you can use the following query:
db.posts.find(
   { "comments.user": "Khan" }
)


text:
Q: Deserialized object type casting at runtime Say I have this class hierarchy:
public abstract class Base {};
public class Child1 : Base {};
public class Child2 : Base {};

At some point I persist one of inherited classes in IsolatedStorageSettings.ApplicationSettings and then get it back as object. How can I find out whether it is Child1 or Child2 and type cast it to right type at runtime?

A: Can you not just use is ?
if(myobject is Child1)
    var child1 = (Child1)myobject;
else if (myobject is Child2)
    ....

A: The easiest way would be casting it using as keyword and checking the result:
Base child;
child = mysteryObject as Child1;
if(child == null)
{
    // mysteryObject is Child2
    child = mysteryObject as Child2;
}
else
{
    // mysteryObject is Child1
}

You could also use is keyword instead.


text:
Q: Converting timezone in in Python (Django) adding a mysterious 30 minutes I have a datetime object that is set to 2014-02-24 19:00:00+00:00 and I believe this is set as UTC by default (through the Django admin panel).
This time is actually Africa/Johannesburg, so I convert it like this:
local_timezone= pytz.timezone("Africa/Johannesburg")
local_time_start = self.start_time_unix.replace(tzinfo=local_timezone)

This will now output 2014-02-24 19:00:00+01:30
Now I want to store this as the converted UTC timezone, so I do it like this:
utc_time = local_time_start.astimezone(utc)

For some reason, this outputs 2014-02-24 17:30:00+00:00. The time is should output is 17:00:00 so where is the extra 30 mins coming from?
Basically I am trying to take the given input from the django admin panel as the local timezone of the models time_zone field, but store it as UTC.
Is there a better way I can approach this? The Django docs explain how to convert the users local timezone but I need to convert it based on the timezone in the models attributes.

A: Don't use datetime.replace() with pytz timezones. The pytz timezones contain historical timezone data (to allow for dates in the past to use the right offsets from UTC), but datetime.replace() cannot use the correct information in that case.
Use the timezone.localize() method instead:
local_timezone = pytz.timezone("Africa/Johannesburg")
local_time_start = local_timezone.localize(self.start_time_unix)

See the pytz documentation.
Use this only on non-timezone-aware objects. For timezone aware datetime values, use datetime.astimezone() to translate value from one timezone to another:
local_timezone = pytz.timezone("Africa/Johannesburg")
local_time_start = self.start_time_unix.astimezone(local_timezone)

If you have a datetime value that has the wrong timezone attached (it should represent the given time in a different timezone, not a different time in that timezone), remove the old timezone first using .replace(tzinfo=None), then usetimezone.localize()`:
local_timezone = pytz.timezone("Africa/Johannesburg")
local_time_start = local_timezone.localize(self.start_time_unix.replace(tzinfo=None))


text:
Q: Sketching functions with an uncountable number of turning points (sinusoids) In my attempt to sketch functions, I usually employ the following algorithm:

*

*Differentiate the function

*Find which $x$ has $\frac{dy}{dx} = 0$

*Find which $y$ correspond to the aforementioned $x$

*Find its limits to infinity and negative infinity (unless the function is not defined at one of those limits, like a logarithmic function)

*Find the nature of the function between the ends of the function found using the limit nature and the turning point, and/or between turning point to turning point until you have a satisfactory framework for the function's rate of change that can model it appropriately

However, upon trying to graph:
$$y = x\sin\ 3x$$
I had some trouble.
I knew the function would be even, so I could only really concern myself with one side and draw the same for the other side, but finding which $x$ has $\frac{dy}{dx} = 0$ was an issue. $f'(x)$ here is $sin\ (3x) + 3xcos\
 (3x)$. However, trying to find turning points is proving to be difficult for me, as I have:
$$0 = sin\ (3x) + 3xcos\
 (3x)$$
$$sin\ (-3x) = 3xcos\ (3x)$$
However, other than $0$, I can't seem to find any other solutions for this, allow graphing out the functions tells me there're infinitely many. How do I work something like this out? I was thinking once I got a groove I could do something like $$sin\ (-3x+2\pi\ k) = 3xcos\ (3x+2\pi\ k)$$ once I worked out a solution for $x$.

A: Substitute $t = 3x$ to get $$\sin t + t\cos t = 0\tag{1}$$ and note that if $t_0$ is a solution to the above, then $\cos t_0 \neq 0$. Assume the contrary, i.e. $\cos t_0 = 0$. Then we have $$0 = \sin t_0 + t_0\cos t_0 = \sin t_0,$$ but $\sin t_0^2 + \cos t_0^2 = 1$, so we can't have $\sin t_0 = \cos t_0 = 0$ and we arrive at contradiction.
Now, if $t_0$ is a solution of $(1)$, since $\cos t_0\neq 0$, we can write $$0 = \sin t_0 + t_0\cos t_0 = \cos t_0(\tan t_0 + t_0)$$ which implies that $$\tan t_0 + t_0 = 0.$$ This means that any solution of $(1)$ is also a solution of $$\tan t = - t\tag{2}$$ and conversely, any solution of $(2)$ must be a solution to $(1)$.
We conclude that equations $(1)$ and $(2)$ are equivalent, i.e. have the same set of solutions.
There is a great answer how to approach this kind of problem here.


text:
Q: GDB Debugger: An internal issue to GDB has been detected I'm new to GNU Debugger. I've been playing around with it, debugging Assembly Files (x86_64 Linux) for a day or so and just a few hours ago I ''discovered'' the TUI interface.
My first attempt using the TUI interface was to see the register changes as I execute each line at a time of a simple Hello World program (in asm). Here is the code of the program
section .data
        text db "Hello, World!", 10
        len equ $-text
section .text

        global _start

_start:

        nop

        call _printText

        mov rax, 60
        mov rdi, 0
        syscall

_printText:

        nop

        mov rax, 1
        mov rdi, 1
        mov rsi, text
        mov rdx, len
        syscall
        ret

After creating the executable file in the terminal of linux I write
$ gdb -q ./hello -tui

Then I created three breakpoints: one right of the _start, another right after _printText and the last just above the mov rax, 60 for the SYS_EXIT.
After this:
1) I run the program.
2) On gdb mode I write layout asm to see the written code.
3) I write layout regs.
4) Finally I use stepi to see how the register change according the the written hello world program.
The thing is that when the RIP register points to the address of ret, corresponding to SYS_EXIT and I hit Enter I get the following message in console
[Inferior 1 (process 2059) exited normally]
/build/gdb-cXfXJ3/gdb-7.11.1/gdb/thread.c:1100: internal-error: finish_thread_st
ate: Assertion `tp' failed.
A problem internal to GDB has been detected,
further debugging may prove unreliable.
Quit this debugging session? (y or n)

If I type n It appears this (as it says, it quits if I type y):
This is a bug, please report it.  For instructions, see:
<http://www.gnu.org/software/gdb/bugs/>.

    /build/gdb-cXfXJ3/gdb-7.11.1/gdb/thread.c:1100: internal-error: finish_thread_st
    ate: Assertion `tp' failed.
    A problem internal to GDB has been detected,
    further debugging may prove unreliable.
    Create a core file of GDB? (y or n)

As I don't know what a core file of GDB (and what is useful for), so I type n and the debugging session closes.
Does anyone know why this is happening and how can be fixed?
By the way, I'm new in Assembly also, so if this occurs because of something wrong in the program I'd also appreciate if anyone can point that out.

A:
Does anyone know why this is happening

It's happening because there is a bug in GDB (more precisely, an assertion that GDB internal variable tp is not NULL has been violated).

and how can be fixed?

You should try to reproduce this with current version of GDB (the bug may have already been fixed), and file a bug report (like the message tells you).

I don't know what a core file of GDB (and what is useful for),

It's only useful to GDB developers.

A: I use the same GDB version as you and I always use the TUI features; but I've never had this problem. However, when I use your code the internal GDB error occurs.  But if I make one change in your write syscall function, the error does not manifest.
Although you are not calling another function from within a function, I generally create a stack frame by including at least the "push rbp", "mov rbp, rsp", and "leave" instructions in my x86-64 function calls.  This may be a band-aide or a work around with respect to the "bug".
_printText:
        push rbp
        mov rbp, rsp
        mov rax, 1
        mov rdi, 1
        mov rsi, text
        mov rdx, len
        syscall
        leave
        ret