text:
Q: align div content to right + use margin from right I have a following problem, my div contend does not want to align to right. As you can see on the picture, my left side menu /blured/ is on the left + I used margin so it is not under each other like in an column, but it does not matter now. Menu links which should be aligned to right /whole div/, is on the left and when I try to use css float: right; it goes to right but content is aligned to left, So I can not make the menu symetric when I use the same margin as I used for left side. understand? I am struggling with it, please help.
jsfiddle>> HERE
Picture
HTML:

                            ■ Uvod
                            ■ Tim
                            ■ Sluzby

                            Kontakty ■
                            Referencie ■
                            Odkazy ■

CSS>
html {
    height: 100%;
}

body{
    background-image: url("imgs/repeat.gif");
    background-repeat: repeat-x;
    width: 1024px;
    background-color: #B20035;
    margin: 0 auto;

}

a{
    color: #fff;
    font-size: 16pt;
    font-family: Arial;
    text-decoration: none;
}

#tabulka{
    background-image: url("imgs/fidal.jpg");
    background-repeat: no-repeat;
    width: 1024px;
    height: 600px;

}

#logo{
    width: 250px;
    height: 250px;
    margin: 0 auto;
    padding-top: 40px;

}

#switch{
    margin: 0 auto;
    width: 70px;
}

.uvod{
    position: absolute;
    margin-left: 100px;
    margin-top: 100px;
}

.tim{
    position: absolute;
    margin-left: 150px;
    margin-top: 200px;
}

.sluzby{
    position: absolute;
    margin-left: 200px;
    margin-top: 300px;
}

#right{
    float: right;

    width: 0px;
}

.kontakty{
    text-align: right;
    position: absolute;
    margin-right: 0px;
    margin-top: 100px;
}

.ref{
    position: absolute;
    margin-left: 4px;
    margin-top: 200px;
}

.odkazy{
    position: absolute;
    margin-left: 4px;
    margin-top: 300px;
}

A: something like this? (revised based on comments)

html {
    height: 100%;
}
body{
    background-image: url("imgs/repeat.gif");
    background-repeat: repeat-x;
    width: 1024px;
    background-color: lightgray;
    margin: 0 auto;
}
a{
    color: #fff;
    font-size: 16pt;
    font-family: Arial;
    text-decoration: none;
}
#tabulka{
    background-image: url("imgs/fidal.jpg");
    background-repeat: no-repeat;
    width: 1024px;
    height: 600px;

}
#logo{
    width: 250px;
    height: 250px;
    margin: 0 auto;
    padding-top: 40px;

}
#switch{
    margin: 0 auto;
    width: 70px;
}
.menu {
    margin-top:50px;
    float:right;
    padding-right:10px;
}
.odkazy {
    margin-left: 20px;
}
.sluzby {
    margin-left: -110px;
}
.ref{
    margin-left: 65px;
}
.tim{
    margin-left: -135px;
}
.kontakty{
    margin-left: 115px;
}
.uvod{
    margin-left: -160px;
}

        ■ Uvod
        Kontakty ■

        ■ Tim
        Referencie ■

        ■ Sluzby
        Odkazy ■

A: Revised code: copy, paste, save, launch. This should be what you want

      ■ Uvod
      ■ Tim
      ■ Sluzby

      Kontakty ■
      Referencie ■
      Odkazy ■


text:
Q: is DatagramSocket.send thread safe? I'm planning to use an instance of DatagramSocket and call its send method from different threads... to send UDP packets to different clients. Is the method thread safe i.e. calling this method from different threads will not create any trouble/inconsistency/race condition?
Thanks!

A: Yes. This is only a thin layer on the native OS, which is threadsafe.
See here http://www.velocityreviews.com/forums/t150685-is-datagramsocket-thread-safe.html

A: UDP guarantees that datagrams arrive intact (if at all). In other words there can be no interleaving even if there is multithreading at the sender. That's all you need. You don't actually need thread safety. However the C send() system call is thread safe, like all system calls, because they are atomic.

A: The answer is yes, the layer on the native operating system is thread safe.
BUT, because network throughput is limited, if you send more packets than the network can handle, some packets will be dropped.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Webapp application cache updates I have a Webapp that uses the application cache for offline and online access. The problem I'm running into is that some of my users are not seeing updates when I change the manifest file. It works for me and for others, so my only theory is that some ISPs are caching the manifest file.
Has anyone else encountered this?
I don't know of any way to programmatically flush the browser application cache to force the update. window.applicationCache.update() does not seem to do the trick (at least on iPad). The usual trick of adding queryies to the URLs probably would defeat offline behavior.
In desperation I could simply use an unchanging loader page and put all the code in localStorage and do my own updates.

A: Normal practice is to expire the manifest file immediately, as per HTML5 Boilerplate:
ExpiresByType text/cache-manifest       "access plus 0 seconds"

Firefox in particular is known to have issues with caching the manifest file if it is not explicitly expired.  The HTML5 Boilerplate file linked to above also has a load of sensible defaults for other file types.


text:
Q: Elevated command line prompt can't access shared drives
*

*I map a share from another machine using my user account.

*I launch an elevated command prompt (cmd.exe, right click, Run as administrator).

*Navigating to shared drive (Z:) results in:

The system cannot find the drive specified
Now if I open a non elevated command prompt, I can navigate to Z: just fine.
Note added by barlop
With net use, An administrative(elevated) cmd prompt can access mapped drives created from an administrative cmd prompt, but the issue is that an administrative cmd prompt can't access a drive created from a non-administrative cmd prompt, and vice versa. So a mapped drive created by net use, from a non-administrative cmd prompt, can't be seen from an administrative cmd prompt. Net use can be used with local drives too and same issue for that. The Subst has the same problem.

A: Opening a Windows Explorer as administrator and recreating the network shares didn't work for me. Then, I found this solution: create the share on the command prompt itself. It worked for me.
net use f: \\remoteserver\subfolder

Even if the drive is already mapped in windows explorer, still it worked.
Note: Only use a single backslash before subfolder

A: Probably that is not a problem of file permissions but it's related with:

*

*Network shares being associated with sessions (i.e. different users may have a different set of network shares). Note that an user can have more that one session.

*How User Account Control works.

Since almost all users used an administrator account in XP (as most programmers didn't bother to make their programs work with limited accounts), Microsoft made a "limited version" of administrator accounts starting with Vista, an in some situations the two "versions" counts as different users (since they are separate sessions).
Try launching an elevated Windows Explorer (i.e. a Windows Explorer launched with "Run as administrator") and recreate all network shares, that should do the trick.
The reason for having to recreate the shares is explained on this MSDN blog entry:
Mapped Network Drives with UAC on Windows Vista
Edit: relevant bits from the blog entry (emphasis mine):

To simplify things, let's assume you are running as an administrator with UAC enabled (although, to be more secure, it is better to run as a standard user). When you log in, you create a new token. We then detect that you have UAC enabled, we log in a second time, and end up with a new (highly restricted) token, which we use to launch the shell. There are two separate login events.
(...)
This convenience feature makes it easier to run into issues with mapped network drives. Prior to Windows 2000 SP2, device names remained globally visible until explicitly removed or the system restarted. For security reasons, we modified this behavior beginning with Windows 2000 SP2. From this point forward, all devices are associated with an authentication ID (LUID) - an ID generated for each logon session.
(...)
Because these mapped drives are associated with LUID, and because elevated applications are using a different LUID generated during a separate login event, the elevated application will no longer see any mapped drives for this user.

A: Another work-around that took me ages to find is to run net use from a scheduled task as the NT AUTHORITY\SYSTEM account. Apparently drives mapped under this account show up for all users and all elevation levels.
I've tested this and it works even on NFS shares (which can be a bit finicky). Just create a scheduled task set to run at system startup, and specify the following command:
net use //server/share Z: /persistent:no

It might possibly work to run it just once with /persistent:yes, but I haven't tried that. Granted, "just map it again" works too, but that drive still won't be visible to scheduled tasks running in different contexts. The downside is that all real users see it too, so not so good for multiuser setups.
(re-post from https://superuser.com/a/832042/7076 which is closed as duplicate)

A: Alberto Martinez answer describes why the mapped network drive is not accessible.
Here is registry fix to solve the problem:

*

*Open regedit and go to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System

*Add a new DWORD (32-bit) Value named EnableLinkedConnections.

*Adjust the value to 1 (or 00000001).

Exit regedit and restart the computer.

A:
I map a share from another machine using my user account.

that network drive is available ONLY in user account  mapped the network drive.

A: A far from ideal solution, is mklink, as it's not creating a new drive, but it is creating a directory on your local drive, that links to a network drive.
mklink doesn't have the problem that you are running into,  that net use and subst have, which is that administrative cmd prompts and non-administrative cmd prompts can't see the results of each others net use or subst mappings.
You can use mklink, (some don't realise that mklink can be used for network "shares"). By the way likewise net use can be used for local directories too, just net use has the issue, as does subst(subst of course can't link to network drives).
Creating a symbolic link to mapped network drive in Windows
C:\Windows\system32>mklink /d c:\asdfbba \\192.168.0.30\carp
symbolic link created for c:\asdfbba <<===>> \\192.168.0.30\carp

C:\Windows\system32>dir c:\asdfbba
 Volume in drive C has no label.
 Volume Serial Number is 4645-5DCE

 Directory of c:\asdfbba

25/01/2022  20:31    <DIR>          .
25/01/2022  20:31    <DIR>          ..
25/01/2022  20:31               126 blah.txt
               1 File(s)            126 bytes
               2 Dir(s)  424,086,941,696 bytes free

C:\Windows\system32>

One weakness of mklink compared to net use, is that with mklink you can't specify a new drive letter.  mklink will happily create whatever link, just not whatever drive.
C:\Windows\system32>mklink /d c:\asdfbbadsfsff \\192.168.0.30\acrp
symbolic link created for c:\asdfbbadsfsff <<===>> \\192.168.0.30\carp

C:\Windows\system32>mklink /d n:\asdfbbadsfsff \\192.168.0.30\carp
The system cannot find the path specified.

C:\Windows\system32>

You could make a c:\nw directory to make clearer that a thing in there is on the network, and you could get the link to be to c:\nw\blahcomp\carp for shared directory \\192.168.0.30\carp. You'd have to mkdir c:\nw\blahcomp then mklink /d c:\nw\blahcomp\crp \\192.168.0.30\carp  (when you give mklink the first argument / the first actual parameter, if it's just one level then it isn't funny, but if it's multi-level e.g. c:\blah\bleh that you want to be your local link, then it willl create the last subdirectory (bleh), but you have to mkdir the parent of it.

A: Verify your network path, and disconnect the mapped drive (Z:)
Run CMD as administrator, once there, use the "net use" command to map the drive again.
net use Z: \SharePath
then try access it again.

A: Start cmd as administrator, type in the command net use z: \\net\path /persistent:yes and you're done. Another thing I did, and this is extending past the op's question, was after pinning the cmd to the task bar and in properties->Advanced setting it to run as admin, I added /K z: to the end of the 'target' text box, so it became: %windir%\system32\cmd.exe /K z:. Because setting the "Start in" parameter didn't seem to work. This resulted in an icon on my taskbar that starts a cmd window as admin and with the prompt on the mapped drive. And don't forget to go to the properties again and customizing the font, colors, window size and position, as well as text scroll back buffer and command history buffer sizes!

A: Opening a Windows Explorer as administrator and recreating the network shares didn't work for either (as user MSB's earlier comment). Running this in elevated command prompt would work, but cumbersome when having many mapped drives.
net use f: \\remoteserver\subfolder

My solution was running a 3rd party file manager with elevated privilegies. That would list the drives, even as they were not connected (and could not be reached from elevated cmd). Upon clicking on each drive in the file manager, it would be connected automatically, and it would then of course work from elevated cmd too. I tested this with two 3rd party filemanagers, total commander and double commander.


text:
Q: Composing environment variables with other environment variables in k8s containers Can environment variables passed to containers be composed from environment variables that already exist? Something like:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80
        env:
        - name: URL
          value: $(HOST):$(PORT)

A: Helm with it's variables seems like a better way of handling that kind use cases.
In the example below you have a deployment snippet with values and variables:
    spec:
      containers:
        - name: {{ .Chart.Name }}
          image: "image/thomas:{{ .Values.image.tag }}"
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          env:
            - name: URL
              value: {{ .Values.host }}:{{ .Values.port }}

And here is one of the ways of deploying it with some custom variables:
helm upgrade --install  myChart . \
  --set image.tag=v2.5.4 \
  --set host=example.com \
  --set-string port=12345 \

Helm allows you also to use template functions. You can have defaultfunctions and this will go to default values if they're not filled. In the example above you can see required which display the message and fails to go further with installing the chart if you won't specify the value. There is also include function that allows you to bring in another template and pass results to other template functions.

A: These manifests are complete files. Not a good way to use variables in it. Though you can.
use the below command to replace and pipe it to kubectl.
sed -i -e "s#%%HOST%%#http://whatever#" file.yml;

Though I would suggest to use Helm.
Read more:
https://kubernetes.io/docs/tasks/inject-data-application/define-environment-variable-container/

A: Within a single Pod spec, this works with exactly the syntax you described, but the environment variables must be defined (earlier) in the same Pod spec.  See Define Dependent Environment Variables in the Kubernetes documentation.
env:
  - name: HOST
    value: host.example.com
  - name: PORT
    value: '80'
  - name: URL
    value: '$(HOST):$(PORT)'

Beyond this, a Kubernetes YAML file needs to be totally standalone, and you can't use environment variables on the system running kubectl to affect the file content.  Other tooling like Helm fills this need better; see @thomas's answer for an example.


text:
Q: Custom modal dialog and background operations I have a Cocoa app with a custom, multi-step account setup that I implemented as a custom modal dialog with a set of views.
The problem is that the background operations (fetching a URL) seem to get stuck. I assume that this is because the application is in a modal mode.
Here the code to start the modal dialog:
[NSApp beginSheet:accountSetupController.window modalForWindow:self.window
            modalDelegate:nil didEndSelector:NULL contextInfo:NULL];

[accountSetupController beginAccountSetup]; // this later launches the background operation
[NSApp runModalForWindow:accountSetupController.window];

NSApp endSheet:accountSetupController.window];

First of all, is my assumption correct? Is there a way to have the background operation proceed even if the application is running modal?
The actual background operation is not under my control. It is an external API that takes a completion block.

A: Take a look at the "discussion" section of your call to [NSApplication beginSheet: modalForWindow: ...]:

Discussion
This method runs the modal event loop for the specified sheet
  synchronously. It displays the sheet, makes it key, starts the run
  loop, and processes events for it. While the application is in the run
  loop, it does not respond to any other events (including mouse,
  keyboard, or window-close events) unless they are associated with the
  sheet. It also does not perform any tasks (such as firing timers) that
  are not associated with the modal run loop. In other words, this
  method consumes only enough CPU time to process events and dispatch
  them to the action methods associated with the modal window.

To me, this means that background threads and tasks aren't running while this modal session is going.  I've run into this problem before with my own modal dialogs trying to access web servers (for registration purposes, if I remember correctly).
The best solution is to not use modal dialogs if you need to talk to a server asynchronously.  If you must use modal dialogs, try to do your communication between modal sheets (i.e. when the user hits "submit", end the sheet and do the server chatting, then bring up the next sheet for the next step).


text:
Q: How to get Geany to link with the math library in C? I'm using the Linux Mint distribution, and writing a program in C. However, I'm having trouble with the compilation part. Specifically, none of the math.h functions seem to work (like sqrt() or pow()).
I know that if I were compiling through the terminal I would have to link it myself by adding the -lm part at the end of the command. But is there a way to do it through Geany? Or do I have to do it manually?

A: under the geany 'build' menu item is the selection: Set Build Commands
after clicking build then Set Build Commands the Set Build Commands window opens.
under the first column is label under that is Compile to the right of Compile is a text box where you type the compile command.
ON my system, the contents of the compile text box is:
gcc -ggdb  -Wall -Wextra  -Wconversion -std=gnu11 -pedantic -Wmissing-prototypes  -c "%f"  -I.

the next line down is labeled Build to the right of the Build is a text box where you type the link command.
On my system, the contents of the build text box is:
gcc -ggdb  -Wall -Wextra -Wconversion -std=gnu11 -pedantic -o "%e" "%f"   -lpthread -lm

(actual contents will vary for special needs)
Notice, at the END of the Build text box are the library items to be included.   Amongst those libraries is the libm.so (which is written without the lib and without the so.)  I.E. -lm
That is all that is needed to compile and link 'many/most' programs.
Note: the parameter -ggdb is to have the compile and link steps include all the debug information for the gdb debugger


text:
Q: L1 (MAE) vs L2 (MSE) when data is normalized between 0 and 1 In most of the literature, it is emphasized that the L2 norm (MSE) gives a higher error when dealing with outliers compared to the L1 norm (MAE).
But what happens when we normalize the data between 0 and 1?
Doesn't normalizing the data reduce L2's sensitivity to outliers since it will have to calculate the square of values which are below 1 (thus resulting in even smaller errors compared to L1)?

A: Scaling does not change relations between the values, because when scaling you divide all the values by the same constant. Outliers will stay outliers. If there is a big difference between two values $x_1,x_2$ squared and smaller difference between $x_1,x_3$ squared, then after normalizing the values, the differences between them will change, but their relations will be the same. Same with differences of absolute values. Obviously, after normalizing in squared case the distances will still be on squared scale, and in absolute values case, they still will be linear.


text:
Q: Populate image after postback problem I have the following problem:
On button click I want to populate an image source and show an image inside a ModalPopupExtender.
In order to open the ModalPopupExtender I call __doPostBack that cause UpdatePanel to do postback and show appropriate View with the image inside it.
 <script src="jquery-1.5.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
    window.pageLoad = function () {
        $addHandler($get('btn1'), 'click', function (e) {
            __doPostBack('pbcTest', '');
            // setTimeout("PopulateImage()", 100);
            PopulateImage();
            $find('<%=mpePopup.ClientID%>').show();
            e.preventDefault();
        });
    }

    function PopulateImage() {
        $(".testImage").attr("src", "6.jpg");
    }

</script>

<ajaxtoolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" CombineScripts="false">
    </ajaxtoolkit:ToolkitScriptManager>
    <button id="btn1"> Click</button>
    <asp:LinkButton ID="lbTest" runat="server" Text="show popup" Style="display: none;" />
    <ajaxtoolkit:ModalPopupExtender runat="server" ID="mpePopup" TargetControlID="lbTest"
        PopupControlID="pnlPopup" BackgroundCssClass="modalBackground" CancelControlID="lbClose" />
    <asp:Panel runat="server" ID="pnlPopup" CssClass="modalPopup">
        <asp:LinkButton runat="server" ID="lbClose">Close</asp:LinkButton>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
            <ContentTemplate>
                <asp:MultiView runat="server" ID="mvPopup">
                    <asp:View ID="View1" runat="server">
                        <img class="testImage" />
                    </asp:View>
                </asp:MultiView>
                <cs:PostBackControl runat="server" ID="pbcTest" OnCallBack="pbcTest_CallBack" />
            </ContentTemplate>
        </asp:UpdatePanel>
    </asp:Panel>

 protected void pbcTest_CallBack(object sender, CallBackEventArgs e)
    {
        mvPopup.ActiveViewIndex = 0;
    }

If after __doPostBack I call immediately PopulateImage(), the image is empty (although PopulateImage() is called and the image appears for a while, but after that disappears,  it's possible to see in firebug).
But if I put a timeout setTimeout("PopulateImage()", 100); image shows up.
What could be the cause of such behavior?

A: If you want to always call PopulateImage(); after the UpdatePanel has completed a refresh you should do it by registering the function to execute after the UpdatePanel has loaded.  You can register your function by doing the following in javascript when your page is loaded:
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(PopulateImage);

I think you might be experiencing a synchronization issue where you UpdatePanel refresh is happening AFTER your PopulateImage() code has run so it replaces it.


text:
Q: MySQL too many prepared statements Is there a way to see what the prepared statements are that are associated with this error:
(OperationalError) failed to prepare the MySQL query:
Can't create more than max_prepared_stmt_count statements (current value: 20000)

One of several processes might be responsible for this problem and I'm trying to figure out which one it could be the easiest way I can think of, which is to see the text of the prepared statements and track it back to the source.
Is there any way to see what these prepared statements are so I can find the guilty party?

A: To see how many prepared statements are currently open, you can run:
SHOW GLOBAL STATUS LIKE 'com_%prepare%';

Which gives you something like:
Variable_name      | Value
-------------------+--------
Com_prepare_sql    | 2
Com_stmt_prepare   | 2
Com_stmt_reprepare | 0
Com_xa_prepare     | 0

To read the actual statements, you will need to look in the general query log for a while, and then read from it.
I like using a table for the general log:
-- set up
TRUNCATE TABLE mysql.general_log;
SET GLOBAL log_output = 'TABLE';
SET GLOBAL general_log = 'ON';

-- wait for some time
SET GLOBAL general_log = 'OFF';

-- read results
SELECT * FROM mysql.general_log WHERE argument LIKE 'prepare%' OR argument LIKE 'execute%';

You can see statements being prepared and executed:
command_type | argument
-------------+--------------------------------------------------------
Query        | prepare st from "select * from people where name = ?"
Query        | execute st Using @name


text:
Q: C# Expressions easy conversion with == or Equals operator and external parameter Let's say i had two parameters:
parameter 1 an expression that takes a T and fetches the associated product's ID from it
Expression<Func<T,int>> prodIdProperty = x=>x.Product.Id

parameter 2 a productid to compare with , let's say
int productid = 5;

Is there any way I could runtime transform  this (in code) into a new expression like this:
Expression<Func<T,bool>> prodIdProperty = x=>x.Product.Id == 5

I basically need something like this:
Expression<Func<T,bool>> TransformToPredicate(Expression<Func<T,int>> prodIdProperty,int productid){
//insert expression transform magic I don't seem to grasp...
}

I need this because I want to pass it as a predicate to my EF Where clause, that means I cannot included Compiled versions of my prodIdProperty as It requires calling Invoke() wich is not supported
(I already tried formulating my problem another way in this question, but I think I overcomplicated it there)

A: It sounds like you want something like:
Expression<Func<T, bool>> TransformToPredicate(
    Expression<Func<T, int>> prodIdProperty,
    int productId)
{
    Expression equals = Expression.Equal(prodIdProperty.Body,
                                         Expression.Constant(productId));
    return Expression.Lambda<Func<T, bool>>(equals, prodIdProperty.Parameters);
}

Sample code showing it in action:
using System;
using System.Linq.Expressions;

class Test
{
    static Expression<Func<T, bool>> TransformToPredicate<T>(
        Expression<Func<T, int>> prodIdProperty,
        int productId)
    {
        Expression equals = Expression.Equal(prodIdProperty.Body,
                                             Expression.Constant(productId));
        return Expression.Lambda<Func<T, bool>>(equals, prodIdProperty.Parameters);
    }

    static void Main()
    {
        Expression<Func<string, int>> length = x => x.Length;

        var predicate = TransformToPredicate(length, 5);
        var compiled = predicate.Compile();

        Console.WriteLine(compiled("Hello")); // True
        Console.WriteLine(compiled("Foo")); // False
    }
}


text:
Q: systemd: cgroups: BlockIOWeight or IOWeight I want to set  block I/O weight for one of my services. Should I use BlockIOWeight or IOWeight?
Do I need to add BlockIOAccounting=yes or IOAccounting=yes?
~/ mount
...
cgroup2 on /sys/fs/cgroup/unified type cgroup2 (rw,nosuid,nodev,noexec,relatime,nsdelegate)
cgroup on /sys/fs/cgroup/systemd type cgroup (rw,nosuid,nodev,noexec,relatime,xattr,name=systemd)


text:
Q: Unexpected NestJs error: Nest can't resolve dependencies of the UserService I'm trying to build a simple api in NestJs with authentication to save recipes to a MongoDB.
I was trying to add an email service to send a confirmation email for new users and ran into a dependency error I'm not able to figure out myself.
The error in question:
Error: Nest can't resolve dependencies of the UserService (?). Please make sure that the argument UserModel at index [0] is available in the EmailModule context.

Potential solutions:
- Is EmailModule a valid NestJS module?
- If UserModel is a provider, is it part of the current EmailModule?
- If UserModel is exported from a separate @Module, is that module imported within EmailModule?
  @Module({
    imports: [ /* the Module containing UserModel */ ]
  })

    at Injector.lookupComponentInParentModules (C:\Users\Jonathan\Documents\Repos\pantry-api\node_modules\@nestjs\core\injector\injector.js:241:19)
    at Injector.resolveComponentInstance (C:\Users\Jonathan\Documents\Repos\pantry-api\node_modules\@nestjs\core\injector\injector.js:194:33)
    at resolveParam (C:\Users\Jonathan\Documents\Repos\pantry-api\node_modules\@nestjs\core\injector\injector.js:116:38)
    at async Promise.all (index 0)
    at Injector.resolveConstructorParams (C:\Users\Jonathan\Documents\Repos\pantry-api\node_modules\@nestjs\core\injector\injector.js:131:27)
    at Injector.loadInstance (C:\Users\Jonathan\Documents\Repos\pantry-api\node_modules\@nestjs\core\injector\injector.js:57:13)
    at Injector.loadProvider (C:\Users\Jonathan\Documents\Repos\pantry-api\node_modules\@nestjs\core\injector\injector.js:84:9)
    at async Promise.all (index 4)
    at InstanceLoader.createInstancesOfProviders (C:\Users\Jonathan\Documents\Repos\pantry-api\node_modules\@nestjs\core\injector\instance-loader.js:47:9)
    at C:\Users\Jonathan\Documents\Repos\pantry-api\node_modules\@nestjs\core\injector\instance-loader.js:32:13

It states the UserModel is missing in the EmailModule but that doesn't seem to be the case.
EmailModule:
import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
import { UserModule } from "src/user/user.module";
import { JwtService } from "@nestjs/jwt";
import { UserService } from "src/user/user.service";

@Module({
  imports: [ConfigModule, UserModule],
  controllers: [],
  providers: [JwtService, UserService],
})
export class EmailModule {}

Email Service:
import { Injectable } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { createTransport } from "nodemailer";
import * as Mail from "nodemailer/lib/mailer";

@Injectable()
export default class EmailService {
  private nodemailerTransport: Mail;

  constructor(private readonly configService: ConfigService) {
    this.nodemailerTransport = createTransport({
      service: configService.get("EMAIL_SERVICE"),
      auth: {
        user: configService.get("EMAIL_USER"),
        pass: configService.get("EMAIL_PASSWORD"),
      },
    });
  }

  sendMail(options: Mail.Options) {
    return this.nodemailerTransport.sendMail(options);
  }
}

Email Confirmation Service:
import { Injectable } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import { ConfigService } from "@nestjs/config";
import EmailService from "./email.service";
import { UserService } from "src/user/user.service";
import { AccountStatus } from "src/types";
import { BadRequestException } from "@nestjs/common/exceptions";

interface VerificationTokenPayload {
  email: string;
}

@Injectable()
export class EmailConfirmationService {
  constructor(
    private jwtService: JwtService,
    private configService: ConfigService,
    private emailService: EmailService,
    private userService: UserService,
  ) {}

  sendVerificationLink(email: string) {
    const payload: VerificationTokenPayload = { email };
    const token = this.jwtService.sign(payload, {
      secret: this.configService.get("JWT_VERIFICATION_TOKEN_SECRET"),
      expiresIn: `${this.configService.get("JWT_VERIFICATION_TOKEN_EXPIRATION_TIME")}s`,
    });

    const url = `${this.configService.get("EMAIL_CONFIRMATION_URL")}?token=${token}`;

    const text = `Welcome to Pantry! To confirm the email address, click here: ${url}`;

    return this.emailService.sendMail({
      to: email,
      subject: "Pantry Account Confirmation",
      text,
    });
  }

  async confirmEmail(email: string) {
    const user = await this.userService.findOne(email);

    if (user && user.status !== AccountStatus.Created)
      throw new BadRequestException("Email already confirmed");

    await this.userService.markEmailAsConfirmed(email);
  }

  async decodeConfirmationToken(token: string) {
    try {
      const payload = await this.jwtService.verify(token, {
        secret: this.configService.get("JWT_VERIFICATION_TOKEN_SECRET"),
      });

      if (typeof payload === "object" && "email" in payload) {
        return payload.email;
      }
      throw new BadRequestException();
    } catch (error) {
      if (error?.name === "TokenExpiredError") {
        throw new BadRequestException("Email confirmation token expired");
      }
      throw new BadRequestException("Bad confirmation token");
    }
  }

  public async resendConfirmationLink(email: string) {
    const user = await this.userService.findOne(email)
    if (user.status === AccountStatus.Confirmed) {
      throw new BadRequestException('Email already confirmed');
    }
    await this.sendVerificationLink(user.email);
  }
}

I will add the other services & modules below in case they are of any use.
User Module:
import { Module } from "@nestjs/common";
import { MongooseModule } from "@nestjs/mongoose";
import { User, UserSchema } from "./schemas/user.schema";
import { UserController } from "./user.controller";
import { UserService } from "./user.service";

@Module({
  imports: [MongooseModule.forFeature([{ name: User.name, schema: UserSchema }])],
  controllers: [UserController],
  providers: [UserService]
})
export class UserModule {}

User Service:
import { BadRequestException, Injectable } from "@nestjs/common";
import { NotFoundException } from "@nestjs/common/exceptions";
import { InjectModel } from "@nestjs/mongoose";
import { Model, isValidObjectId } from "mongoose";
import { AccountStatus } from "src/types";
import { User, UserDocument } from "./schemas/user.schema";
import { MSG_USER_NOT_FOUND } from "./user-messages";

@Injectable()
export class UserService {
  constructor(@InjectModel(User.name) private userModel: Model<UserDocument>) {}

  private readonly defaultProjection = {
    __v: false,
    password: false,
  };

  async findOne(email: string): Promise<User> {
    const user = this.userModel.findOne({ email }, this.defaultProjection);
    if (user === null) throw new NotFoundException(MSG_USER_NOT_FOUND);
    return user;
  }

  async deleteOne(id: string): Promise<any> {
    if (!isValidObjectId(id)) throw new BadRequestException();

    const result = await this.userModel.deleteOne({ _id: id }).exec();

    if (result.deletedCount !== 1) throw new NotFoundException(MSG_USER_NOT_FOUND);
    return result;
  }

  async updateOne(id: string, userData: User) {
    if (!isValidObjectId(id)) throw new BadRequestException();
    let result;

    try {
      result = await this.userModel.findByIdAndUpdate(id, userData).setOptions({ new: true });
    } catch (e) {
      throw new BadRequestException();
    }

    if (result === null) throw new NotFoundException(MSG_USER_NOT_FOUND);
    return result;
  }

  async markEmailAsConfirmed(email: string) {
    const user = await this.findOne(email);
    return this.updateOne(user.email, {...user, status: AccountStatus.Confirmed})
  }
}

Auth Module:
import { Module } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { JwtModule } from "@nestjs/jwt";
import { MongooseModule } from "@nestjs/mongoose";
import { PassportModule } from "@nestjs/passport";
import { EmailModule } from "src/email/email.module";
import { EmailConfirmationService } from "src/email/emailConfirmation.service";
import { User, UserSchema } from "src/user/schemas/user.schema";
import { UserModule } from "src/user/user.module";
import { UserService } from "src/user/user.service";
import { AuthController } from "./auth.controller";
import { AuthService } from "./auth.service";
import { JwtStrategy } from "./jwt.strategy";
import { LocalStrategy } from "./local.auth";

@Module({
  imports: [
    UserModule,
    EmailModule,
    PassportModule,
    JwtModule.register({ secret: "secretKey", signOptions: { expiresIn: "10m" } }),
    MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
  ],
  providers: [
    AuthService,
    JwtStrategy,
    UserService,
    LocalStrategy,
    EmailConfirmationService,
    ConfigService,
  ],
  controllers: [AuthController],
})
export class AuthModule {}

Auth Service:
import { Injectable, NotAcceptableException, BadRequestException } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import { InjectModel } from "@nestjs/mongoose";
import * as bcrypt from "bcrypt";
import {
  MSG_USER_EMAIL_TAKEN,
  MSG_USER_NAME_TAKEN,
  MSG_USER_NOT_FOUND,
  MSG_USER_WRONG_CRED,
} from "src/user/user-messages";
import { UserService } from "../user/user.service";
import { LoginDto } from "./dto/login.dto";
import { RegisterDto } from "./dto/register.dto";
import { Model } from "mongoose";
import { User, UserDocument } from "src/user/schemas/user.schema";
import { AccountStatus } from "src/types";

@Injectable()
export class AuthService {
  constructor(
    @InjectModel(User.name) private userModel: Model<UserDocument>,
    private userService: UserService,
    private jwtService: JwtService,
  ) {}

  async validateUser({ email, password }: LoginDto) {
    const user = await this.userService.findOne(email);
    if (!user) throw new NotAcceptableException(MSG_USER_NOT_FOUND);

    const passwordValid = await bcrypt.compare(password, user.password);

    if (user && passwordValid) return user;
    return null;
  }

  async register({ email, username, password }: RegisterDto) {
    const userWithEmail = await this.userModel.findOne({ email });
    if (userWithEmail) throw new BadRequestException(MSG_USER_EMAIL_TAKEN);

    const userWithName = await this.userModel.findOne({ username });
    if (userWithName) throw new BadRequestException(MSG_USER_NAME_TAKEN);

    const createdUser = new this.userModel({email, username, password});
    createdUser.status = AccountStatus.Created;
    const newUser = await createdUser.save();
    return newUser;
  }

  async login(login: LoginDto) {
    const user = await this.validateUser(login);
    if (!user) throw new NotAcceptableException(MSG_USER_WRONG_CRED);

    const payload = { email: user.email, sub: user._id };

    return {
      access_token: this.jwtService.sign(payload),
    };
  }
}

I hope this is enough to get some help, it's hard for me to share the entire repository at this point since it's work related

A: as you're trying to use UserService in another module other than where it was registered (which was UserModule), you need to expose it, like this:
@Module({
  imports: [MongooseModule.forFeature([{ name: User.name, schema: UserSchema }])],
  controllers: [UserController],
  providers: [UserService]
  exports: [UserService], // <<<<
})
export class UserModule {}

then remove UserService from EmailModule.


text:
Q: Rewrite correlated subquery, Redshift throwing This type of correlated subquery pattern is not supported yet Error I'm working on a query that needs to left join table A with table B on A.user_id=B.user_id and B.day is less than A.day but is closest to A.day.
Here's what I wrote:
Select A.user_id, A.date, b1.v1 from A
Left Join B as b1
on A.user_id=b1.user_id and b1.day=(Select max(day) from B as b2 where b2.user_id=A.user_id
and b2.day < A.day)

I'm doing this in python using psycopg2 and it's returning error: This type of correlated subquery pattern is not supported yet.
Can someone help me rewrite this so it doesn't use correlated subquery?

A: One way to do this can be:
Select A.user_id, A.date, b1.v1, max(b1.day)
from A Left Join B as b1 on A.user_id=b1.user_id and b1.day < A.day
group by A.user_id, A.date, b1.v1;

A: One method is rather expensive, but . . . :
select . . .
from (select A.user_id, A.date, b1.v1,
             row_number() over (partition by a.user_id, a.date order by b.day desc) as seqnum
      from A Left Join
           B
          on A.user_id = b1.user_id and b.day < a.day
     ) ab
where seqnum = 1;

There may be other ways to accomplish this -- and that have better performance.  If that is needed, ask a new question, provide sample data, desired results, and a clear explanation of the logic you want to implement.


text:
Q: How to increase the size of xticks in pandas plot This is a follow up for a question which i asked here:
The code is as follows:
from pandas_datareader import data as web
import matplotlib.pyplot as plt
import matplotlib.dates as md

fig, (ax1, ax2) = plt.subplots(2, 1)
df = web.DataReader('F', 'yahoo')
df2 = web.DataReader('Fb', 'yahoo')
ax = df.plot(figsize=(35,15), ax=ax1)
df2.plot(y = 'Close', figsize=(35,15), ax=ax2)
plt.xticks(fontsize = 25)

for ax in (ax1, ax2):
    ax.xaxis.set_major_locator(md.MonthLocator(bymonth = range(1, 13, 6)))
    ax.xaxis.set_major_formatter(md.DateFormatter('%b\n%Y'))
    ax.xaxis.set_minor_locator(md.MonthLocator())
    plt.setp(ax.xaxis.get_majorticklabels(), rotation = 0 )

plt.show()

This produces this plot:

How can i increase the size of both the xticks in the two subplots as you can see the size was increased for the bottom one only.
  [1]: https://stackoverflow.com/questions/62358966/adding-minor-ticks-to-pandas-plot

A: You can use the tick_params function on the ax instance to control the size of the tick-labels on the x-axis. If you want to control the size of both x and y axis, use axis='both'. You can additionally specify which='major' or which='minor' or which='both' depending on if you want to change major, minor or both tick labels.
for ax in (ax1, ax2):
    # Rest of the code
    ax.tick_params(axis='x', which='both', labelsize=25)


text:
Q: How can I shift In a binary file while reading? I would able to read all my struct bytes by bytes (block of bytes are large "sizeof(Today)" so it's 8 bytes large). I attempt more and more times, but I can't! Give me help please!
Bin file: "temp.bin"
My struct:
typedef struct
{
    int year;
    int month;
} Today;

And this is part of code that should be read 8 bytes each cycle:
 Today *d;
 d = malloc(sizeof(Today));

 fp = fopen("temp.bin", "rb");

 while(!feof(fp))
 {
     fread(d, sizeof(Today), 1, fp);

     printf("Year = %i\n", d->year);
     printf("Month = %i\n", d->month);
 }

 fclose(fp);

More probably is wrong the while condition and fread() function, but I tried all possible combination but the output is never the right one!
Thank you all

A: You may want to allocate space for all your blocks first e.g.
fp = fopen( "temp.bin", "rb" );
if ( fp != NULL )
{
   fseek( fp, 0L, SEEK_END );
   size_t size = ftell(fp);
   rewind(fp);

   Today *d;
   d = malloc(size);
   fread( d, sizeof(Today), size/sizeof(Today), fp );
   fclose(fp);
}

then you got the structs in an array
e.g. printf( "month: %d", d[5].month);
then do what you need to do on each element in the array then later write it back. Depends on how large your file is though

A: there is nothing about your code, i guess your file format is not as you think.
i also wander why you have to allocate memory for struct.
the code here is similar to that you provided. it just demonstrate the writing of the data in the format you described and then retrieving it without any lose.
#include <stdio.h>
#include <string.h>
typedef struct
{
    int year;
    int month;
} Today;

#define DataFile    "temp.bin"
int main(){
    Today d;
    printf("sizeof(Today)=%d\n",sizeof(Today));

    FILE  *fp = fopen(DataFile, "wb");
    for(int i=1;i<13;i++){
        d.month=i;
        d.year=2000+i;
         fwrite(&d, sizeof(Today), 1, fp);
    }
    fclose(fp);

    printf("write complete, press a key to read\n");
    _getch();

    fp = fopen(DataFile, "rb");

    while(fread(&d, sizeof(Today), 1, fp)){
         printf("Year = %i\t", d.year);
         printf("Month = %i\n", d.month);
    }
    fclose(fp);
    return 0;
}


text:
Q: Using SDL2 for Capturing Key strokes Have 2 questions related to using SDL2.

*

*I want to capture all the keyboard inputs in my C++ app. The app is a COM dll that will run in the background and will capture all the inputs. So this app doesn't have a window, in this case is it possible to capture keyboard inputs? If yes, how?

I have seen examples for SDL2 where they 1st create a SDL window and then capture keyboard inputs. But i don't want that. What i want is my app to be able to capture all keyboard inputs by its own.

*

*If i create my own window using MFC, is it possible to attach that to SDL2 and have it capture all keyboard inputs when my window is in focus. Again i don't want to create a SDL Window.

A: you can use GetAsyncKeyState it's simple and fast,
this code shows you how to use it.
if(GetAsyncKeyState('Q')){//if Q key has been clicked
   //Do something
}

and here is list of all key codes
http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx

A:
So this app doesn't have a window, in this case is it possible to capture keyboard inputs?

Not with SDL.

If i create my own window using MFC, is it possible to attach that to SDL2 and have it capture all keyboard inputs when my window is in focus.

It sounds like you might have some luck with SDL_CreateWindowFrom().

A: You could try to have an window with the SDL_WINDOW_HIDDEN flag. That way i would assume you could get he input with the sdl functions without having an window pop.
Not sure if this is what you want, but i hope it helps.


text:
Q: Bash: nested for loops on counters read from files, with decimal numbers I'm beginning bash script exercises. I am trying to do a nested loop reading variables from two different sources like this:
for f in $(<f.txt)
do
    for l in $(<l.txt)
    do
        echo "$f $l"
    done
done

read -p "Press [enter] to continue..."

Let f.txt and l.txt be files like the following:
25
26
26.8
26.9
27
27.1
27.2
27.3
27.4
27.5
28
29
30

and
0
0.5
1
1.5
2
2.5
3

I'm expecting two numbers separated by a white space, I'm getting a white space followed by what seems to be the second number. It only works as expected on the last iteration of the external loop.
As a beginner, is frustrating being unable to find out why this is happening. Can anybody please point me towards the correct direction?

EDIT: Unexpectedly, the DOS line ending was indeed the problem - and being a newbie I fall right into it.
I parsed my input files to get rid of the problem and got the expected output: two nested for loops printing two numbers separated by a space. I take the advantage of the edit to clarify:
expected output
25 0
25 0.5
25 1
25 1.5
25 2
25 2.5
25 3
26 0
26 0.5
26 1
26 1.5
26 2
26 2.5
26 3
26.8 0
etc...

I am willing to leave the thread open for people coming in - also to discuss what was said by chepner:

First, never use for loops like this; use while loops and the read command to read from a file.

A: First, never use for loops like this; use while loops and the read command to read from a file.
while IFS= read -r f; do
  ...
done < f.txt

Knowing that, it's a "simple" step forward to call read twice at each step, with each one reading from separate file descriptors.
while IFS= read -r f; IFS= read -r l <&3; do
  echo "$f $l"
done < f.txt 3< l.txt

read always reads from standard input, so <&3 redirects file descriptor 3 to the standard input of this read command. 3< opens l.txt for reading on file descriptor 3.
Your code does not run the two iterations in parallel; it iterates over all of l.txt separately for each line in f.txt. (Mathematically, your nested loops compute a cross product of the values in f.txt and l.txt instead of a dot product.)


text:
Q: ReactJS and Express with Axios returning 404 Not sure what's going on with my code, but I'm trying to just do a test run with axios console logging something out, but I'm getting a 404.
class SubscribeForm extends Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.emailChange = this.emailChange.bind(this);
    this.emailSubmit = this.emailSubmit.bind(this);
  }

  emailChange(e) {
    this.setState({value: e.target.value});
  }

  emailSubmit(e) {
    e.preventDefault();
    axios.post('/subscribe', {
      email: 'someemail@email.com',
      headers: {
        'Content-Type': 'application/json;charset=UTF-8',
        "Access-Control-Allow-Origin": "*",
      }
    }).then(res => {
      if(res.data.success) {
        this.setState({email: ''})
      }
    }).catch(error => {
      if (error.response) {
        // The request was made and the server responded with a status code
        // that falls out of the range of 2xx
        console.log(error.response.data);
        console.log(error.response.status);
        console.log(error.response.headers);
      } else if (error.request) {
        // The request was made but no response was received
        // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
        // http.ClientRequest in node.js
        console.log(error.request);
      } else {
        // Something happened in setting up the request that triggered an Error
        console.log('Error', error.message);
      }
      console.log(error.config);
    });
  }

  render() {
    const { classes } = this.props;
    return (

          Join the club, enter your email address

        <form method="post" className={classes.subFormWrap} onSubmit={this.emailSubmit}>
          <TextField
            value = {this.state.value}
            onChange = {this.emailChange}
          />
          <Button
            className={classes.button}
            type="submit"
          >
            Send
            <Icon className={classes.rightIcon}>send</Icon>
          </Button>
        </form>

    );
  }
}

I tried adding headers into axios to see if thats the issue, but i don't think it is (or perhaps I'm doing it wrong).
Also, I don't have a /subscribe file, I don't think I need one? Since, I'm capturing it with express here:
const cors = require("cors");

app.use(cors());

app.post("/subscribe", (req, res, next) => {
  console.log(req.body.email);
});

This file is within my server files, while the react portion is within client files. I have proxy set up, so when I have run the server, front end and back end is talking to each other.

Updated 404 status turned (pending)
I also have set up proxy middleware in my client folder setupProxy.js
const proxy = require("http-proxy-middleware");

module.exports = function(app) {
  app.use(proxy("/subscribe", {
    target: "http://localhost:5000"
  }));
};

I'm getting in the request header in my network request for /subscrib:
Provisional headers are shown

Is this causing it to be (pending)?

A: From what I can see, it seem your server and client app run on different ports. If that is the case you cannot do this:
axios.post('/subscribe', {
      email: 'someemail@email.com',
      headers: {
        'Content-Type': 'application/json;charset=UTF-8',
        "Access-Control-Allow-Origin": "*",
      }
})

You are using the path /subscribe without a host. Axios tries to use the host from which your client app is running and it doesn't find that path hence the 404 status code.
If this is the case, you can fix it by using the host and port of your server before the /subscribe path. See below:
axios.post('localhost:4000/subscribe', {
      email: 'someemail@email.com',
      headers: {
        'Content-Type': 'application/json;charset=UTF-8',
        "Access-Control-Allow-Origin": "*",
      }
})

Kindly change the port here localhost:4000 to your server port.

Note: This is for your local development only.

If you plan on deploying the app, you might want to use process.env.PORT instead.

A: You can use browser's inspect element to check if request is made properly(Inspect Element > Network).
By looking at code I think you are missing base url.
it should be like
axios.post(baseul + port + request url)

Example:
axios.post('http://localhost:3000/subscribe')


text:
Q: Handle Home button click event using DrawerLayout [UPDATE]
I've changed the activity_main.xml and the MainActivity.class as follows: Creating a Navigation Drawer, from the Android Developer Guide and now it works perfectly.

I'm using a DrawerLayout for my MainActivity, which contains a FrameLayout just to set different Fragments but I'm not able to handle its clicks. It works, the menu is opened and closed but I don't know how or where to manage them. This is my code:
toolbar.xml
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"/>

activity_main.xml
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:openDrawer="start">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/ll_main_layout"
        android:orientation="vertical">

        <include layout="@layout/toolbar"
            android:id="@+id/toolbar"/>

        <FrameLayout
            android:id="@+id/main_frameLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/navigation_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <include layout="@layout/lateral_menu_header" />

            <ListView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/lateral_menu_listView"
                android:layout_marginTop="16dp"
                android:divider="@android:color/transparent"
                android:dividerHeight="0dp"/>
        </LinearLayout>
    </android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>

MainActivity.class
public class MainActivity extends AppCompatActivity
        implements ListView.OnItemClickListener {

    private static final String LOG_TAG = MainActivity.class.getSimpleName();
    private static final String CURRENT_FRAGMENT = "mCurrentFragment";

    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;
    private ListView mDrawerList;
    private ArrayList<LateralMenuItem> lateralMenuItems;

    private Toolbar mToolbar;
    public ActionBar mActionBar;

    private FragmentManager mFragmentManager;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initToolbar();
        initLateralMenu();

        mFragmentManager = getSupportFragmentManager();
    }

    private void initLateralMenu() {
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (mDrawerLayout != null) {
            mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, 0, 0);
            mDrawerToggle.syncState();

            mDrawerLayout.addDrawerListener(mDrawerToggle);

            mDrawerList = (ListView) findViewById(R.id.lateral_menu_listView);
            if (mDrawerList != null) {
                lateralMenuItems = initLateralMenuList();

                LateralMenuListAdapter lateralMenuListAdapter = new LateralMenuListAdapter(MainActivity.this, lateralMenuItems);
                mDrawerList.setAdapter(lateralMenuListAdapter);

                mDrawerList.setOnItemClickListener(this);
            }
        }
    }

    private void initToolbar() {
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);

        mActionBar = getSupportActionBar();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(mDrawerToggle.onOptionsItemSelected(item)) {
            // THIS DOESN'T WORK, I'VE DEBUGGED AND IS UNREACHABLE
        }
        return super.onOptionsItemSelected(item);
    }
}

The thing is that onOptionesItemSelected(MenuItem item) is not working. I've also tried to set an mDrawerToggle.setToolbarNavigationClickListener(...), mToolbar.setOnMenuItemClickListener(...) and mToolbar.setNavigationOnClickListener() and none of them worked.
My objective is to handle when I am in one or another Fragment to set the Home button as up and can override onBackPressed().
Maybe the logic is different when you use the DrawerLayout, am I missing something?

A:   @SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {

    switch (item.getItemId()) {

        case R.id.nav_logout:
            logoutDialog();
            break;
    }
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

Try this

A: You are using NavigationView with custom list view and you gave setOnItemClickListener to the list view not NavigationView, so the call will come to
@Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

but I am not sure where is this piece of code in your class.
For your case callback will come to onItemClick not onNavigationItemSelected.
If you have any question, Please let me know.


text:
Q: How can I change language of URL to single language In Yii? I have website built in Yii 1 framework and I want to change some URLs of website to German language. No multi-language.
Sample URL:
http://mywebsite.com/products

to
http://mywebsite.com/Produkte


text:
Q: Creating Categories in Rails I'm looking to create simple categories in my Rails app, with a lot of searching through the internet and finding tutorials which are too abstract I am now posting on here for some guidance/help.
What I currently have is a Posts scaffold which belongs to a User which works perfectly. I think I need to setup a many to many relationship between categories and posts which allows a post to belong to multiple categories - Also creating a link to the category which lists the posts that belong to it.
Posts can belong to multiple categories
How would I go about adding this to my project or creating something on the lines of this?
Thanks,
Jonathan

A: Check out this link: Creating a many to many relationship in Rails 3
In your case, your code should probably look like this:
# app/models/post.rb
class Post < ActiveRecord::Base
  belongs_to :user
  has_and_belongs_to_many :categories
end

# app/models/category.rb
class Category < ActiveRecord::Base
  has_and_belongs_to_many :posts
end

# db/migrate/1213123123123_create_categories_posts_join_table.rb
class CreateCategoriesPostsJoinTable < ActiveRecord::Migration
  def change
    create_table :categories_posts, :id => false do |t|
      t.integer :category_id
      t.integer :post_id
    end
  end
end


text:
Q: Auto-generate a service, its DTOs, and a DAO I am using ServiceStack to connect my thick client to our API server, and I like it a lot. However, I find having to write three classes for every request (Foo, FooResponse, and FooService) to be somewhat of an annoyance.
In my project, I have a lot of DAO interfaces, that look something like this:
public interface ICustomerDao {
    public IList<Customer> FindCustomers(long regionId, string keyword);
}

I would like to be able to say something like this:
public interface ICustomerDao {

    [AutoApi("Loads customers for the given region whose names match the keyword")]
    [AutoRoute("/search/customer/{regionId}/{keyword}"]
    public IList<Customer> FindCustomers(long regionId, string keyword);
}

public class SomeBusinessLogic {

    [AutoService(typeof(ICustomerDao))]
    public IList<Customer> FindCustomers(long regionId, string keyword) {
        // lots of business logic here
    }
}

And then, I would like the following classes to be auto-generated for me:

*

*FindCustomers: a ServiceStack DTO request

*FindCustomersResponse: the response

*FindCustomersService: a Service that takes a FindCustomers DTO, then calls SomeBusinessLogic.FindCustomers(req.RegionId, req.Keyword) and wraps its return value in a FindCustomersResponse

*ApiServiceCustomerDao : Implements ICustomerDao by auto-generating methods that construct FooRequest and contact the appropriate service, then receive FooResponse and unpack it automatically.

Does something like this already exist ? If not, how hard would it be to implement ? Is there a better way ?

A: AutoQuery
I'd first recommend looking at AutoQuery to see whether it's suitable for quickly creating data-driven Services.
Dynamically generate and register Services
As ServiceStack promotes a code-first dev model and your Request and Response DTO's represent your Service Contract I'd strongly recommend against attempting dynamically generate them as you should retain full control of its definition, but you could use them as a template to dynamically generate your own Service implementations by following the same approach AutoQuery uses to generate your Services implementations and register them dynamically.
In AutoQuery you'd just need to define your Request DTO and the rest of the Service implementation are dynamically generated and registered. Since it returns a standard QueryResponse<T> Response Type no DTO's are dynamically generated and thanks to the code-first Request DTO, clients still retain an end-to-end Typed API, e.g:
var movies = client.Get(new FindMovies { Ratings = new[]{"G","PG-13"} });


text:
Q: How to define a mongoose Schema that have an array of ObjectId with boolean? For some reason I want to include booleans to an array of ObjectId lists this
todos: [{ObjectId:`6341610e8c18a2d32649346e`, isPublic: false}, {ObjectId:`1331610e8c18a2d32649346e`, isPublic: true} ]

How should I define the schema?
My current one that only can contain ObjectId is like this.
todoLists: [{ type: mongoose.Types.ObjectId, required: true, ref: "todoListsSchema" }]

I tried simply just define it as array but when storing it in database the ObjectId would expand to a real object which is not what I want, I want it like the previous just showing the ObjectId but in this format.
Thanks a lot


text:
Q: No attribute getstatusoutput I'm trying to ping a server using python subprocess but get the following error -
>>> import subprocess as sp
>>> sp.getstatusoutput('ping 127.0.0.1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'getstatusoutput'

A: subprocess.getstatusoutput() is only available in Python 3.x.
For Python 2.x, use the commands module.
By the way, note that getstatusoutput() is equivalent to check_output(..., universal_newlines=True, stderr=STDOUT) (available in both Python 2.x and 3.x).


text:
Q: put Overlay above InAppWebView video full screen mode my purpose is trying to put a widget above the video(e.g. youtube) full screen mode, now a solution is using OverlayEntry. But still video full screen will overlay everything else when onEnterFullscreen, is it possible to let OverlayEntry widget has higher priority?
If this way does not work, here is another solution I may try later, use another page above this youtube page... I am learning flutter, please let me know if there is a better solution, thank you!
How to make a full screen dialog in flutter?
Here is code:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  static final String title = 'Overlay test';

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  @override
  Widget build(BuildContext context) => MaterialApp(
        debugShowCheckedModeBanner: false,
        title: MyApp.title,
        theme: ThemeData(primarySwatch: Colors.blue),
        home: MainPage(),
      );
}
class MainPage extends StatefulWidget {
  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  late InAppWebViewController webViewController;
  OverlayEntry? entry;
  final focusNode = FocusNode();

  void showOverlay() {
    print('+++++++++showOverlay On+++++++++');
    final overlay = Overlay.of(context)!;
    final renderBox = context.findRenderObject() as RenderBox;
    final size = renderBox.size;

    entry = OverlayEntry(
      builder: (context) => Positioned(
        width: size.width,
        child: buildOverlay(),
      ),
    );

    overlay.insert(entry!);
  }

  Widget buildOverlay() {
    return Material(
        elevation: 8,
        child: Column(
          children: <Widget>[
            ListTile(
              leading: Image.network(
                'https://images.unsplash.com/photo-1554151228-14d9def656e4?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=333&q=80',
                fit: BoxFit.cover,
              ),
              title: Text('Sarah Abs'),
              subtitle: Text('OverlayEntry test'),
              onTap: () {},
            ),
          ],
        ),
      );
  }

  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: AppBar(
          title: Text(MyApp.title),
          centerTitle: true,
        ),
        body: Container(
          width: double.maxFinite,
          height: double.maxFinite,
          child: InAppWebView(
            initialUrlRequest:
            URLRequest(url: Uri.parse('https://www.youtube.com/watch?v=_kbWfoRQ-BY&ab_channel=ArminvanBuuren')),
            onEnterFullscreen: (controller) async {
              WidgetsBinding.instance!.addPostFrameCallback((_) => showOverlay());
            },
          ),
        ),
      );
}

--------------- update ----------------
Hi Олег Давиденко thanks a lot for the clue, I added this code but when I click fullscreen from youtube, still nothing above the screen as before, could you please let me know how to use this injection? thanks a lot!
                  onEnterFullscreen: (controller) async{
                    print('------------------');
                    controller.evaluateJavascript(source: """
  var button = document.createElement("Button");
  button.innerHTML = "Title";
  button.style = "top:0;right:0;position:absolute;z-index: 9999"
  document.body.appendChild(button);
""");
                  },

A: Try to use js injection
controller.evaluateJavascript(source: """
  var button = document.createElement("Button");
  button.innerHTML = "Title";
  button.style = "top:0;right:0;position:absolute;z-index: 9999"
  document.body.appendChild(button);
""");


text:
Q: Should I use the entity framework or linq to sql for new mvc project? I have a new project where I want to use MVC (I will be learning as I code), and I have never used linq or entity (or mvc).  Which should I use?  Does it matter?
edit:  I will be having a lot of different databases, from Oracle to FoxPro.

A: I was in the same position as you a few months back. I took on a project to be done in MVC after spending a lot of time in ASP.NET web forms and using (very happily and successfully) subsonic as the ORM.
I opted to use the Entity Framework and although MVC and the EF were completely new to me, I have not lived to regret it. I like the structure and separation it brings. It produces much cleaner code which in turn makes it easier to maintain too. In fact, when I have to go back to maintain older projects we have done in web forms, the benefits of MVC and the EF become even clearer. Linq to Entities is very quick to pick up too and becomes second natuire to you very quickly as well.
So in my opinion, use MVC and the Entity Framework, you'll thank yourself in the long run.

A: Linq2Sql and EF are ORMs, whereas MVC is a web framework. In other words, you can use MVC with either L2S or EF.
As far as which ORM to use, that depends mostly on whether or not you plan on switching from SQL Server to some other database software. Linq2SQL is, well, SQL-specific and is more tightly coupled to the datastore. EF allows you to de-couple your domain layer from your data access layer, and, thus, allows you to switch the underlying database at some point in the future without having to refactor up your application stack.
Just my 2 cents.

A:
lot of different databases

Entity framework because linq to sql supports only ms sql server

A: Depends what your requirements, but just a point that Linq2SQL team nolonger exists, the developers moved the EF team.
Cheers
Iain

A: Doesn't matter one bit.  Up to you.

A: I would honestly use a tool called EntitySpaces. It is similar to EntityFramework, but much much better. It allows for very natural sql like syntax while abstracting away all the DB stuff. You can use it on virtually all DB types and it also supports data access using sql commands or through stored procedures.
It is by far better than entity framework.


text:
Q: two ways to call the declared function with parameters in string I have a declaration of a function where each parameter is a string and I am trying to trigger the below method in at least 2 ways to call the function. I am new to Javascript and also went through few documentation to understand the logic but unable to figure out. If someone can please help me in this. Below is my declared function and I want to know how can I do it.
function displayValue(param1, param2, param3){

}

A: *

*Directly calling function providing strings as params

displayValue('hi', 'there', 'sir');

*Using variables as params and passing them into the function

const firstString = 'hi';
const secondString = 'there';
const thirdString = 'sir';
displayValue(firstString, secondString, thirdString);


text:
Q: regex not repeating dot character javascript I have come up my regex in javascript ^[a-zA-Z0-9.]+([.][a-zA-Z0-9]+)$ which I am trying to filter out string.

*

*No dot character at the begin nor end

*dot character can be middle of other Alphabet letter or numbers

*If dot character cannot be appear more than twice

These are my expected pass cases

*

*foo.bar

*f.o.o

*foo.bar.foo

*fo.123.321

These are my expected No-pass cases

*

*.foo

*.foo.

*foo.

*foo..bar

*.foo.bar

I feel like I am very close(or not at all). How can I filter out dot repeating dot characters? Thanks in advance!

A: I think that's what you looking for:
/^([a-zA-Z0-9]+\.)+([a-zA-Z0-9]+)$/

Tests
expected pass cases
/^([a-zA-Z0-9]+\.)+([a-zA-Z0-9]+)$/.test('foo.bar') // true
/^([a-zA-Z0-9]+\.)+([a-zA-Z0-9]+)$/.test('f.o.o') // true
/^([a-zA-Z0-9]+\.)+([a-zA-Z0-9]+)$/.test('foo.bar.foo') // true
/^([a-zA-Z0-9]+\.)+([a-zA-Z0-9]+)$/.test('fo.123.321') // true

Expected No-pass cases
/^([a-zA-Z0-9]+\.)+([a-zA-Z0-9]+)$/.test('.foo') // false
/^([a-zA-Z0-9]+\.)+([a-zA-Z0-9]+)$/.test('.foo.') // false
/^([a-zA-Z0-9]+\.)+([a-zA-Z0-9]+)$/.test('foo.') // false
/^([a-zA-Z0-9]+\.)+([a-zA-Z0-9]+)$/.test('foo..bar') // false
/^([a-zA-Z0-9]+\.)+([a-zA-Z0-9]+)$/.test('.foo.bar') // false


text:
Q: can't connect to kafka server I try to use Kafka with version 0.9.0 with port 9092.
If I use telnet, I successfully connect to this address,
but I fail to connect to Kafka server with Java API
Here is my Java example exactly use the official supplied documentation:
Properties props = new Properties();
props.put("bootstrap.servers", "192.168.174.128:9092");
props.put("acks", "all");
props.put("retries", 0);
props.put("batch.size", 16384);
props.put("linger.ms", 1);
props.put("buffer.memory", 33554432);
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

Producer<String, String> producer = new KafkaProducer(props);
for(int i = 1; i < 10; i++) {
  producer.send(new ProducerRecord<String, String>("test", Integer.toString(i), Integer.toString(i)));

}

producer.close();

I use vmware virtual machine to build my Kafka server and Zookeeper. My virtual machine IP address is 192.168.174.128. I successfully create and consume message with Kafka client.
And here is the exception full stack
2016-01-03 09:44:38.049 [kafka-producer-network-thread | producer-1] DEBUG [] [] Selector - Connection with localhost/127.0.0.1 disconnected
java.net.ConnectException: Connection refused: no further information
    at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method) ~[na:1.7.0_51]
    at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:739) ~[na:1.7.0_51]
    at org.apache.kafka.common.network.PlaintextTransportLayer.finishConnect(PlaintextTransportLayer.java:54) ~[kafka-clients-0.9.0.0.jar:na]
    at org.apache.kafka.common.network.KafkaChannel.finishConnect(KafkaChannel.java:79) ~[kafka-clients-0.9.0.0.jar:na]
    at org.apache.kafka.common.network.Selector.poll(Selector.java:274) ~[kafka-clients-0.9.0.0.jar:na]
    at org.apache.kafka.clients.NetworkClient.poll(NetworkClient.java:270) [kafka-clients-0.9.0.0.jar:na]
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:216) [kafka-clients-0.9.0.0.jar:na]
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:141) [kafka-clients-0.9.0.0.jar:na]
    at java.lang.Thread.run(Thread.java:744) [na:1.7.0_51]
2016-01-03 09:44:38.049 [kafka-producer-network-thread | producer-1] DEBUG [] [] NetworkClient - Node 0 disconnected.
2016-01-03 09:44:38.078 [kafka-producer-network-thread | producer-1] DEBUG [] [] NetworkClient - No node found. Trying previously-seen node with ID 0
2016-01-03 09:44:38.078 [kafka-producer-network-thread | producer-1] DEBUG [] [] NetworkClient - Give up sending metadata request since no node is available
2016-01-03 09:44:38.099 [kafka-producer-network-thread | producer-1] DEBUG [] [] NetworkClient - Initiating connection to node 0 at localhost:9092.
2016-01-03 09:44:38.681 [kafka-producer-network-thread | producer-1] DEBUG [] [] Metrics - Removed sensor with name connections-closed:client-id-producer-1
2016-01-03 09:44:38.681 [kafka-producer-network-thread | producer-1] DEBUG [] [] Metrics - Removed sensor with name connections-created:client-id-producer-1
2016-01-03 09:44:38.681 [kafka-producer-network-thread | producer-1] DEBUG [] [] Metrics - Removed sensor with name bytes-sent-received:client-id-producer-1
2016-01-03 09:44:38.681 [kafka-producer-network-thread | producer-1] DEBUG [] [] Metrics - Removed sensor with name bytes-received:client-id-producer-1
2016-01-03 09:44:38.682 [kafka-producer-network-thread | producer-1] DEBUG [] [] Metrics - Removed sensor with name bytes-sent:client-id-producer-1
2016-01-03 09:44:38.682 [kafka-producer-network-thread | producer-1] DEBUG [] [] Metrics - Removed sensor with name select-time:client-id-producer-1
2016-01-03 09:44:38.682 [kafka-producer-network-thread | producer-1] DEBUG [] [] Metrics - Removed sensor with name io-time:client-id-producer-1
2016-01-03 09:44:38.682 [kafka-producer-network-thread | producer-1] DEBUG [] [] Metrics - Removed sensor with name node--1.bytes-sent
2016-01-03 09:44:38.683 [kafka-producer-network-thread | producer-1] DEBUG [] [] Metrics - Removed sensor with name node--1.bytes-received
2016-01-03 09:44:38.683 [kafka-producer-network-thread | producer-1] DEBUG [] [] Metrics - Removed sensor with name node--1.latency
2016-01-03 09:44:38.683 [kafka-producer-network-thread | producer-1] DEBUG [] [] Metrics - Removed sensor with name node-0.bytes-sent
2016-01-03 09:44:38.683 [kafka-producer-network-thread | producer-1] DEBUG [] [] Metrics - Removed sensor with name node-0.bytes-received
2016-01-03 09:44:38.683 [kafka-producer-network-thread | producer-1] DEBUG [] [] Metrics - Removed sensor with name node-0.latency
2016-01-03 09:44:38.683 [kafka-producer-network-thread | producer-1] DEBUG [] [] Sender - Shutdown of Kafka producer I/O thread has completed.
2016-01-03 09:44:38.683 [main] DEBUG [] [] KafkaProducer - The Kafka producer has closed.

A: This happened to me due to a different issue:
The 0.10.1.0 Java API seems not to be compatible with a 0.10.0.1 server.
I hope that can solve someone else's problem.

A: I had this problem. To resolve this problem you should uncomment following config in server.properties file and fill it with IP of your zookeeper.
advertised.host.name = zookeeper IP
As kafka document says this config is

Hostname to publish to ZooKeeper for clients to use

Because in new kafka consumer (0.9) consumer asks zookeeper IP from broker.


text:
Q: Using the jquery UI icons locally I need to be able to use a jquery icon in my js file. I was importing the UI js like :
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>

But I need to have it locally in my folder, so I downloaded the js and now it is:
<script src="scripts/jquery-ui.min.js"></script>

But this cause my icon not to load at this part of my code:
icons: {primary: "ui-icon-folder-open"},

I need this ui-icon-folder-open icon, where do I get this jpg image, and how do I call this?

A: You need the resources (like icons) as well so download the entire package from here:
http://jqueryui.com
and then extract it into your local folder.

A: By default, the jQuery UI CSS is looking for the icon in images/[spriteName].png. (The images directory should be in the same directory as the css.)
You can download jQuery UI (inclusive of JS, CSS, images, and demos) at http://jqueryui.com/download/.
A list of icon classes can be found in the docs here: http://api.jqueryui.com/theming/icons/


text:
Q: Connect redmine and remote gitolite There are many similar topics (many of them very old) but I am still lost.
I have two servers, one has gitolite setup, and another has redmine setup.
User is pushing changes to the repository created on gitolite server.
Redmine is a user on this gitolite server and is pulling changes from it
and showing them in browser.
More precisely, I have used the following line on redmine server:
git clone --mirror ssh://gitolite3@gitoliteserver/testing

Then, I configured this repository (testing.git) as a known repository
to redmine - redmine can use bare and local repositories, only.
When user push changes to gitolite server, redmine does not automatically
show them. I have to do the following on redmine server:
cd testing.git
git remote update

I could use cron on redmine server for regular updating repository testing.git.
But many says this is inefficient and propose hooks. However, information are
very confusing. Can you help me by answering if cron is a viable solution and if
"git remote update" is a correct command for this cron? Or give me
a clean example how to use hooks for my problem.
Not directly connected to the question, but I have to say.
For me, non-native english, words as miror, mirrored, mirroring, etc. are
hard to follow, please use alice and bob and such more easy terms.
Even the word remote is confusing, if I am on A then B is remote for me,
but if I am on B then A is remote for me. Thus, it is hard to read
about git on the net, and the things are further complicated by
the facts, that some solutions are github or bitbucket only variants.

A: The first way that I would choose is to use Redmine + Gitolite integration via dedicated plugin, as explained here:
http://redmine-git-hosting.io/
Second way, is what you have attempted, so:
Pulling the changes via cron job or some other kind of scheduled task is legit thing to do, however then some delay exists between commit and a cron job, and also  unnecessary utilization of resources like networking and cpu for testing repository even if there is no change...
In order to properly utilize given resources, a recommended way are hooks, in both Redmine and git server.
So on your gitolite, you need to have post-receive hook, which would perform:

*

*update of your repo tracked by Redmine (you can do that in multiple ways, one of ways is to use sshpass or to use expect to login into Redmine server and perform git pull of changes)

*trigger the Redmine's repository update hook, which is described here:
https://www.redmine.org/projects/redmine/wiki/HowTo_setup_automatic_refresh_of_repositories_in_Redmine_on_commit
So for example, a git's post-receive hook would look like:
#!/bin/bash
/usr/bin/sshpass -pPassword ssh -o StrictHostKeyChecking=no user@server 'cd /home/user/repo/ && git pull origin master'
curl "http://<redmine url>/sys/fetch_changesets?key=<your service key>"

Redmine webservice key for updating repositories can be found in Administration | Settings | Repository tab

A: Here are details how I applied the accepted answer (solution with hooks).
Any comment is welcome.
I have two computers and I will refer to them as gitolite3 and redmine, respectively.

*

*On computer gitolite3, I have edited .gitolite.rc and uncommented the following line:
# allow repo-specific hooks to be added
'repo-specific-hooks',

*On computer gitolite3, I have created file local/hooks/repo-specific/deploy-redmine-testing.sh
#!/bin/bash
ssh -p 22 redmine@redmine '/home/redmine/gitrepo-update.sh'

*On computer gitolite3, I have edited .gitolite/conf/gitolite.conf
repo testing
    RW+     =   @all
    option hook.post-receive  =  deploy-redmine-testing.sh

*On computer redmine, I created /home/redmine/gitrepo-update.sh
#!/bin/bash
if [ -d /home/redmine/gitrepo/testing.git ]; then
  cd /home/redmine/gitrepo/testing.git
  git remote update
fi

*On computer gitolite3, if repository testing does not exist then after commit and push it will be automaticaly created

*On computer redmine, I have created bare mirror of the repository testing@gitolite3
git clone --mirror ssh://gitolite3@gitolite3:22/testing

*Any further commit into repository testing at gitolite3 will be replicated to repository at redmine

*If GUI on redmine is not showing all the content (e.g. it shows only the last revision) then you should delete the entry in GUI and recreate it.


text:
Q: createdon field date-time format Compiling the following coe always get the same frustrating mistake. I'm trying to compare a "createdon" field to a the present date. I've tried several date format but stil not working...
Error detail : "The date-time format for 23/05/2012 14:01:55 is invalid"
Code snippet:
DateTime d = DateTime.Now;
                String.Format("{0:dd/MM/YYYY HH:mm:ss}", d);

                FetchExpression fetch = new FetchExpression(@"
                    <fetch distinct='false' mapping='logical'>
                      <entity name='" + context.PrimaryEntityName + "'><filter type='and'><condition attribute='createdon' value='" + d + "' operator='ne'></condition></filter><link-entity name='new_contrats' alias='nombreligne' from='new_contratsid' to='new_contratsid'><filter type='and'><condition attribute='new_contratsid' value='" + contrats.Id + "' operator='eq'></condition></filter></link-entity></entity></fetch>");

Any help would be great !

A: My blog posting here might help. Basically, UTC format but originating user's local offset may effect the underlying value in the database.

A: It may be easier to work in either Linq to CRM or Query Expressions rather than Fetch XML.  You don't have to worry about the formatting since you're working with objects.


text:
Q: How to connect the angular to MongoDB I was not able to find a way to connect my database to my user interface which I make in angular. So anyone can suggest to me how to overcome my problem by the simpler way???
needed a simpler code to rectify the error

A: You cannot directly communicate to any database via angular.
You need to create middleware(server) using nodejs, python or any other.

A: the-modern-application-stack-part-4-building-a-client-ui-using-angular-2-formerly-angularjs-and-typescript

Use MongoDB Stitch

MongoDB Stitch
import { Component, OnInit } from "@angular/core";
import { StitchClientFactory } from "mongodb-stitch";

A: You can't connect the front-end directly to a database. You need a back-end for that.
Check out Node.js if you're looking for something in JavaScript.
There are a lot of courses for MEAN stack on Udemy. You could learn from those.


text:
Q: remoteMessage firebase expecting function invocation I'm learning firebase cloud messaging. I've implemented it in app run notification, but it seems that doesn't work. The problem is that, when I use the firebase keyword called remoteMessage, it says that it needs to be an invocation. Here's the code:
package com.example.fbtutorial

import android.os.Looper
import android.widget.Toast
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.google.firebase.messaging.ktx.remoteMessage

class MyFirebaseMessagingService : FirebaseMessagingService() {
    override fun onMessageReceived(p0: RemoteMessage) {

        Looper.prepare()

        Toast.makeText(baseContext, remoteMessage.notification?.title, Toast.LENGTH_LONG).show() // here at remoteMessage I have and error saying "Function invocation 'remoteMessage(...)' expected"

        Looper.loop()
    }
}

if you know why i get this error please tell me, thanks in advance.

A: Your RemoteMessage parameter to onMessageReceived is called p0, so to get its title you'd do:
p0.notification?.title

I recommend carefully reading and following the code in the Firebase documentation on overriding onMessageReceived, as using the parameter names that are used there makes it more likely that your other code will also compile without syntax errorss


text:
Q: How to download pdf using nodejs/express? I am trying to download pdf from a URL using the below code. example URL is https://www.tutorialspoint.com/cricket/cricket_tutorial.pdf

axios({method:'get',encoding:null, url: scraping_url, responseType: 'stream',headers: { "Content-type": "application/pdf"}}).then((response) => {
            res.set("Content-type", "application/pdf")
            response.data.pipe(fs.createWriteStream('12345678.pdf'))

          })

But I am getting

So, how should I download ans display it on chrome?

A: Write:
<iframe src="https://www.tutorialspoint.com/cricket/cricket_tutorial.pdf#toolbar=0" width="100%" height="500px"></iframe>

If you want to use backend server, use:
router.get('/pdfroute', (req, res) => {
    axios({
        method:'get',
        url: scraping_url,
        responseType: 'stream'
    })
    .then(response => {
        res.set('Content-type', 'application/pdf')
        res.set('Content-disposition', 'inline; filename="'+filename+'"'
        response.data.pipe(res)
    })
})


text:
Q: Prove that $(a+nb,b)=(a,b)$
Prove that $(a+nb,b)=(a,b)$ for any integer $n$.

Let $(a,b) = d$.
So $d = ax_1 + by_1$ where $x_1$ and $y_1 \in \mathbb{Z} $
Now consider,  $(a+nb)x_1 + b(y_1 -nx_1)$ . Now clearly $(y_1 -nx_1)$ and $x_1$ are $\in  \mathbb{Z}$
Also
$(a+nb)x_1 + b(y_1 -nx_1) = ax_1 + by_1 =  d $
Is this correct ?

A: If $d$ is a common divisor of $a$ and $b$ then it is also a divisor of $a+nb$.
If $d$ is a common divisor of $a+nb$ and $b$ then it is also a divisor of $a$ (because $a = (a+nb) -nb$).
Therefore the set of common divisors of $\{a,b\}$ is exactly the same as the set of common divisors of $\{a+nb,b\}$. So the maximum value in each set (i.e. the GCDs) are the same.

A: This proves one direction, but not the other. Remember that $d=(a,b)$ if and only if $d$ is the smallest positive integer expressible as $ax+by$. You've shown that if $d=(a,b)$ then there exist $x$ and $y$ such that $d=(a+nb)x+by$, but not that it's the smallest integer of this form.
You're nearly there, and there are several ways to complete the proof. One would be to assume $e=(a+bn,b)=x_2(a+bn)+y_2b$ and show that $e=xa+yb$ for some $x,y\in \mathbb Z$.
(What you did shows that $(a+nb,b)\leq(a,b)$, and doing it again in the other direction shows $(a+nb,b)\geq (a,b)$, so combining the two facts gives equality.)


text:
Q: Which is more characteristic of an element absorption or emission spectrum? Absorption and emission spectrum are used to reveal the identity of an element and even to find new elements. But, which of them is more characteristic?
The mission spectrum would have more lines than the no. of lines missing in the absorption spectra simply because de-excitation can occur from any higher energy level but excitation always starts from the first energy level. So is absorption spectrum more characteristic than emission spectrum?

A: Each element's emission spectrum is unique.
The absorption spectrum is the exact inverse of the emission spectrum.
As with the emission spectrum, each element has its own unique absorption spectrum.
http://en.wikipedia.org/wiki/Emission_spectrum
http://theory.uwinnipeg.ca/mod_tech/node152.html

A: Apart from a few special cases the absorption and emission spectra are the same. This is because for every absorption line taking from a lower state $\psi_i$ to a higher state $\psi_j$ there is a corresponding emission line when the atom decays from $\psi_j$ to $\psi_i$.
The difference tends to be more practical than theoretical. Traditionally new elements were identified in the lab by their emission lines, because it's easy to heat up a sample of your element in a flame to get them to emit light. However if you're identifying elements in the solar atmosphere you don't get to choose the experimental conditions so you use the absorption lines.


text:
Q: Keras Lambda Layer: can't pickle _thread.RLock objects I am trying to save the full keras model. I tried to replicate the following error in a smaller example but I failed, so here is the actual code causing the error in the full model.
The MaskRNN model for image segmentation has a lambda layer defined as:
gt_boxes = KL.Lambda(lambda x: norm_boxes_graph(x, K.shape(input_image)[1:3]))(input_gt_boxes)

This layer calls the method below:
def norm_boxes_graph(self, boxes, shape):
        """Converts boxes from pixel coordinates to normalized coordinates.
        boxes: [..., (y1, x1, y2, x2)] in pixel coordinates
        shape: [..., (height, width)] in pixels

        Note: In pixel coordinates (y2, x2) is outside the box. But in normalized
        coordinates it's inside the box.

        Returns:
            [..., (y1, x1, y2, x2)] in normalized coordinates
        """
        h, w = tf.split(tf.cast(shape, tf.float32), 2)
        scale = tf.concat([h, w, h, w], axis=-1) - tf.constant(1.0)
        shift = tf.constant([0., 0., 1., 1.])
        fin = tf.divide(boxes - shift, scale)
        return fin

When trying to save the full model(not only the weights) it throughs the error:
can't pickle _thread.RLock objects

Checking for serializability:
Checking Serializability of {'class_name': 'Lambda',
'config': {'name': 'norm_boxes_lambda', 'trainable': True, 'dtype': 'float32', 'function': ('4wEAAAAAAAAAAQAAAAQAAAATAAAAcw4AAACIAHwAiAGIAoMBgwJTACkBTqkAKQHaAXgpA9oPZ2V0\nX25vcm1fYm94ZXNf2hBnZXRfc2hhcGVfaW1hZ2Vf2gtpbnB1dF9pbWFnZXIBAAAA+lEvaG9tZS9p\nYWkvbWluaWNvbmRhMi9lbnZzL3B5dG9yY2gyL2xpYi9weXRob24zLjcvc2l0ZS1wYWNrYWdlcy9N\nYXNrX1JDTk4vbW9kZWwucHnaCDxsYW1iZGE+mwcAAPMAAAAA\n', None, (<function MaskRCNN.build.<locals>.get_norm_boxes_ at 0x7f272b8b59e0>, <function MaskRCNN.build.<locals>.get_shape_image_ at 0x7f270c4817a0>, <tf.Tensor 'input_image:0' shape=(None, None, None, 3) dtype=float32>)),
'function_type': 'lambda',
'module': 'Mask_RCNN.model',
'output_shape': None,
'output_shape_type': 'raw', 'output_shape_module': None,
'arguments': {}}}

!!! FAIL serialization: can't pickle _thread.RLock objects
WARNING: Did not find non-serializable object in {'class_name': 'Lambda', 'config': {'name': 'norm_boxes_lambda', 'trainable': True, 'dtype': 'float32', 'function': ('4wEAAAAAAAAAAQAAAAQAAAATAAAAcw4AAACIAHwAiAGIAoMBgwJTACkBTqkAKQHaAXgpA9oPZ2V0\nX25vcm1fYm94ZXNf2hBnZXRfc2hhcGVfaW1hZ2Vf2gtpbnB1dF9pbWFnZXIBAAAA+lEvaG9tZS9p\nYWkvbWluaWNvbmRhMi9lbnZzL3B5dG9yY2gyL2xpYi9weXRob24zLjcvc2l0ZS1wYWNrYWdlcy9N\nYXNrX1JDTk4vbW9kZWwucHnaCDxsYW1iZGE+mwcAAPMAAAAA\n', None, (<function MaskRCNN.build.<locals>.get_norm_boxes_ at 0x7f272b8b59e0>, <function MaskRCNN.build.<locals>.get_shape_image_ at 0x7f270c4817a0>, <tf.Tensor 'input_image:0' shape=(None, None, None, 3) dtype=float32>)), 'function_type': 'lambda', 'module': 'Mask_RCNN.model', 'output_shape': None, 'output_shape_type': 'raw', 'output_shape_module': None, 'arguments': {}}}. This may be an oversight.

========================
Variable:

    FailTuple(test [obj={'class_name': 'Lambda', 'config': {'name': 'norm_boxes_lambda', 'trainable': True, 'dtype': 'float32', 'function': ('4wEAAAAAAAAAAQAAAAQAAAATAAAAcw4AAACIAHwAiAGIAoMBgwJTACkBTqkAKQHaAXgpA9oPZ2V0\nX25vcm1fYm94ZXNf2hBnZXRfc2hhcGVfaW1hZ2Vf2gtpbnB1dF9pbWFnZXIBAAAA+lEvaG9tZS9p\nYWkvbWluaWNvbmRhMi9lbnZzL3B5dG9yY2gyL2xpYi9weXRob24zLjcvc2l0ZS1wYWNrYWdlcy9N\nYXNrX1JDTk4vbW9kZWwucHnaCDxsYW1iZGE+mwcAAPMAAAAA\n', None, (<function MaskRCNN.build.<locals>.get_norm_boxes_ at 0x7f272b8b59e0>, <function MaskRCNN.build.<locals>.get_shape_image_ at 0x7f270c4817a0>, <tf.Tensor 'input_image:0' shape=(None, None, None, 3) dtype=float32>)), 'function_type': 'lambda', 'module': 'Mask_RCNN.model', 'output_shape': None, 'output_shape_type': 'raw', 'output_shape_module': None, 'arguments': {}}}, parent=None])

was found to be non-serializable. There may be multiple other undetected variables that were non-serializable.
Consider either removing the instantiation/imports of these variables or moving the instantiation into the scope of the function/class.
If you have any suggestions on how to improve this error message, please reach out to the Ray developers on github.com/ray-project/ray/issues/

Useful related info:
Keras Custom Layer gives errors when saving the full model
I also used unsuccessfully the closure method described here:
Checkpointing keras model: TypeError: can't pickle _thread.lock objects
Any help is greatly appreciated!


text:
Q: Is there any way to split a string into two lines in R? I want to separate a string into 2 lines in R. I have found cat function, but it only prints to the screen. I need to assign the output to a variable.
For eg if my string is "Line1\nLine2", I need the output as following:
Seperate to two lines

A: If you are trying to display x, shown below, on the R console as two lines then use either of these:
x <- "Line1\nLine2"

writeLines(x)
## Line1
## Line2

cat(x, "\n")
## Line1
## Line2

or if you are trying to split it into a character vector having two components then use one of these:
strsplit(x, "\n")[[1]]
## [1] "Line1" "Line2"

readLines(textConnection(x))
## [1] "Line1" "Line2"

scan(text = x, what = "", quiet = TRUE)
## [1] "Line1" "Line2"

or if you just want just the first part or just the second part then if y is any of the last three then y[1] and y[2] or any of the following:
sub("\n.*", "", x)
## [1] "Line1"

sub(".*\n", "", x)
## [1] "Line2"


text:
Q: How to write an appropriate test for backpack admin crud functionality? I've implemented a laravel project which involves backpack admin, now I want to know is there any appropriate way to test its CRUD functionality (like the store, delete, etc actions)?
It doesn't matter what kind of test is needed (functional or unit test), I just want to test its functionality.

A: The easiest way I found was to create browser tests using Laravel Dusk - https://laravel.com/docs/8.x/dusk