text:
Q: Create docker file for client and server I have a folder structure like this:
root/server
root/frontend
root/start.sh
where start.sh is somethins like this:
#!/bin/sh

cd server
npm run build;

cd ../client;
npm run build;
mv -R build ../server/client;

cd ../server
npm run start;

so I build the server, then the client, I move the client built file inside my server app and I run the app...is there a way to do something like this with a docker image?

A: Yes, most of the thing that you can do with a .sh script could be done building a docker image. Howerver, docker images follow often the Single Responisbility Principle, so i would not couple FE and BE in a single image (if they are two different applications) but instead i would do 2 different, then using docker compose, you will be able to manage your multi-container application
let's see a very simple example
Backend: (Dockerfile in server directory)
FROM node:xxx (use your development version)
WORKDIR /server
COPY . /server/
RUN npm run build

EXPOSE 3000

CMD npm start

Frontend: (Dockerfile in client directory)
FROM node:xxx (use your development version)
WORKDIR /client
COPY . /client/

RUN npm run build
EXPOSE 80

CMD npm start

docker compose (in the parent directory of server and client
version: 3
services:
  server:
    build: ./server
    container_name: server
    ports:
      - 3000:3000
  client:
    build: ./client
    container_name: client
    ports:
      -80:80

then with docker-compose up --build you can build and run your containers in any moment, see the documentation for other commands (stop, kill, remove ecc)
NOTE: i've written all "by hand", there could be some typo or wrong syntax. Sorry, i will fix!

A: this is probably similar to the problem your facing:
FROM node:alpine as buildjob_frontend
COPY web/package.json .
COPY web/yarn.lock .
RUN yarn install
COPY web/ .
RUN yarn build

FROM golang:alpine as buildjob_go
RUN mkdir -p /go/src/github.com/marhaupe/go-react-bootstrap && \
  mkdir -p /src/bin/ && \
  apk update && \
  apk add git && \
  apk add make
WORKDIR /go/src/github.com/marhaupe/go-react-bootstrap/
COPY . .
RUN GOOS=linux make build-server && mv serverbin /src/bin/app

FROM alpine:latest
RUN apk update && apk add ca-certificates && rm -rf /var/cache/apk/* && \
  mkdir -p /src/web/build
COPY --from=buildjob_frontend /build /src/web/build
COPY --from=buildjob_go /src/bin/app /src/
WORKDIR /src
EXPOSE 3000
CMD ["./app"]

Builds frontend, builds backend, and copies backend binary and frontend build folder into an alpine image. I can link you the full repo if you need to see how things are linked with eachother

A: In Docker to change directory use the WORKDIR keyword , you need to specify the full path in this section

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install

COPY . .

WORKDIR /usr/src/app/client

RUN npm install

RUN npm run build

WORKDIR /usr/src/app

EXPOSE 5000

CMD ["node", "server.js"]


text:
Q: visual studio 2019 c++ - concept identifier is undefined I have tried to use concepts in my cpp project which I write using visual studio 2019 version 16.4.1 but I get and error message: "identifier conecpt is undefined".
As far as I know concepts have support in visual studio 2019 since version 16.3 so I cant understand why it still doesn't work for me.
Here is the code I have written, Is there any foolish syntax error in it?
#include<concepts>
template<typename T>
concept has_type_member = requires { typename T::type; }

If not has anyone have had such a problem and have managed to overcome it?

A: C++20 Concepts are now supported for the first time in Visual Studio 2019 version 16.3 Preview 2.
According to the blog:

First, we're debuting the feature via /std:c++latest mode and once we
have all C++20 features implemented across all Visual Studio products
(compiler, library, IntelliSense, build system, debugger, etc.), we'll
provide them through a new /std:c++20 mode. IntelliSense support is
not currently available and our implementation doesn't yet include
recent changes in the ISO C++ standards meeting in Cologne.

I suggest you should try to use /std:c++latest mode.
You can set this at Project > Properties > Configuration Properties > C/C++ > Language > C++ Language Standard > Preview - Features from the Latest C++ Working Draft (/std:c++latest)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Random numbers in c# i use
Random rnd = new Random();
x=rnd.Next(10);

but every time i get the same number.
how to fix it and get different numbers? Tell me easy method.
thanks. sorry for bad english.

A: MSDN explicitly addresses this "problem" in the remarks section of the MSDN docs for the Random class, including a sample!
http://msdn.microsoft.com/en-us/library/system.random.aspx

A: Random's default constructor uses the current time as its seed. Therefore, if you initialize multiple Random objects in rapid succession (such as in a loop, for instance), they will share the same seed.
Create your Random object once and use it multiple time, or create a seed beforehand and use it to initialize your generators.

A: Obligatory XKCD reference:

http://xkcd.com/221/

A: Make sure you use the constructor only once. You can add a seed.
Random rnd  = new Random(DateTime.Now.Millisecond);

Then you can make calls to as you actually did it.
x=rnd.Next(10);

But make sure you don't have the constructor and the call to the Next() method inside a loop or something similar...


text:
Q: `markdown.extensions.def_list` not rendering correctly I tried inserting a definition list in my contents.lr file.
Tables are working fine but the definition lists are not handled correctly.
Example taken from https://pythonhosted.org/Markdown/extensions/index.html
Apple
:   Pomaceous fruit of plants of the genus Malus in
    the family Rosaceae.
Orange
:   The fruit of an evergreen tree of the genus Citrus.

Rendering the string directly with markdown works:
markdown.markdown(s, extensions=['markdown.extensions.def_list'])

A: I couldn't find it documented anywhere, but with a quick look at the source code, it appears that Lektor uses the Mistune Markdown parser, which does not support definition lists.
I'd suggest filing a bug report with Lektor, asking them to document what Markdown features they support and how to alter them.


text:
Q: How to transfer charged amount to a connected stripe account? I am using stripe in test mode and I can't transfert the amount charged to a connected account.
After a successful payment, stripe send the wehook event checkout.session.completed, so my backend tries to handle this and transfert the collected amount to the connected account but nothing happens and my platform end up to receive the whole amount. I don't know what's wrong :
await stripe.paymentIntents.update(
                    eventData.object.payment_intent,
                    {application_fee_amount: Math.round(0.05 * price),transfer_data: {
                      destination: stripe_connected_account,amount:Math.round(0.95 * price)
                    }}
                  );

The above operation is not executed and my connected account receive nothing.
Any suggestion ?

A: In order to transfer the funds captured through this Checkout Session to a connected account, you'll need to include the transfer_data.destionation and application_fee_amount as payment_intent_data when creating the Checkout Session:
https://stripe.com/docs/api/checkout/sessions/create#create_checkout_session-payment_intent_data


text:
Q: jQuery Ignore Undefined variable I'm making an advice tool that works on adding up variables in jQuery.
Some multiple choice answers have a specific data attribute, which needs to be saved to a specific variable. If the user clicks on the same data attribute later on, the value must be added up to the previous value (that's stored in a var).
The problem: not every answer has a data attribute. Every time a user clicks on an answer without a data attribute, the variable changes to "Undefined" and it becomes unusable.
I converted a short version of my code to a jsfiddle to demonstrate the problem:

// The default is 0
var count_health = 0;
var count_fat = 0;

$('.question div').click(function(){

  // I want to get the data from the answer
  var gather_health = $(this).attr("data-health");
  var gather_fat = $(this).attr("data-fat");

  // And add it up to the variable
  count_health = +count_health + +gather_health;
  count_fat = +count_fat + +gather_fat;

  // And show it
  $('.health').text('Your health is: ' + count_health);
  $('.fat').text('Your fat is: ' + count_fat);
});
.question div {
  background-color: #f4f4f4;
  padding: 5px;
  cursor: pointer;
  width: 50px;
  margin-top: 5px;
}

.health {
  display: block;
  clear: both;
}

Do you run?

Yes

No

Do you eat fruit?

Yes

No

Do you eat chips?

Yes

No

I don't know if there's a more efficient way to calculate the variables. If you know one, I'd be happy to see it! But please be gentle, I'm not a jQuery wizzard like you guys :-)

A: You can use OR || operator like this works:
var gather_health = $(this).attr("data-health") || 0; // or "" or any default set

// The default is 0
var count_health = 0;
var count_fat = 0;

$('.question div').click(function(){

  // I want to get the data from the answer
  var gather_health = $(this).attr("data-health") || 0;//<=== if attribute value is NaN set value to be 0
  var gather_fat = $(this).attr("data-fat") || 0;//the same here

  // And add it up to the variable
  count_health = +count_health + +gather_health;
  count_fat = +count_fat + +gather_fat;

  // And show it
  $('.health').text('Your health is: ' + count_health);
  $('.fat').text('Your fat is: ' + count_fat);
});
.question div {
  background-color: #f4f4f4;
  padding: 5px;
  cursor: pointer;
  width: 50px;
  margin-top: 5px;
}

.health {
  display: block;
  clear: both;
}

Do you run?

Yes

No

Do you eat fruit?

Yes

No

Do you eat chips?

Yes

No

A: you can just count it as zero like this (I used a ternary operator but you could have just easily used an if/else statement):
// The default is 0
var count_health = 0;
var count_fat = 0;

$('.question div').click(function(){

  // I want to get the data from the answer
  var gather_health = (typeof $(this).attr("data-health") != "undefined") ? $(this).attr("data-health") : 0;
  var gather_fat = (typeof $(this).attr("data-fat") != "undefined") ? $(this).attr("data-fat") : 0;

  // And add it up to the variable
  count_health = +count_health + +gather_health;
  count_fat = +count_fat + +gather_fat;

  // And show it
  $('.health').text('Your health is: ' + count_health);
  $('.fat').text('Your fat is: ' + count_fat);
});


text:
Q: What is the practical advantage of a higher refresh rate and what should I be looking for when looking for a monitor for FPS gaming? I have some questions regarding gaming monitors.
My PC is a Corsair One with an GTX 1080ti
I've been looking at the Alienware aw3418dw with a 100hz refresh rate and a cheaper alienware that's 25 inch that has 240hz and is less then half price.These differ primarily in terms of refresh rate.
I primarily play FPSes like rainbow 6 seige. What is the practical advantage of a higher refresh rate and what should I be looking for when looking for a monitor for FPS gaming?

A: Here's a more generalized answer:
The 60, 120, or 240 Hz refresh rate on your TV or monitor measures the maximum speed at which that gadget can flash new images, independent from the media you're trying to watch on that screen.
The thing is, say you're playing a game at 60fps on a 240fps monitor, that means that your game is delivering only 60 frames per second whereas your monitor has a refresh rate four times that. So what happens is that the same frame gets flashed four times, instead of just one.
So to answer your question "What is the practical advantage of a higher refresh rate and what should I be looking for when looking for a monitor for FPS gaming?", A higher frame rate is generally better (video appears to be smoother, but many people claim it's not noticeable), but a 240fps monitor is not going to do much for you unless the game delivers that and you have the hardware to support it.
References:
http://blog.logicalincrements.com/2015/04/does-fps-matter-decide-for-yourself/
https://gizmodo.com/why-frame-rate-matters-1675153198

A: The AW3418DW is an ultra-widescreen monitor. It uses a 21:9 panel with a higher pixel count (3440x1440) than a traditional monitor of similar size. Running this monitor at higher frame rates may be difficult as a result. The AW2518H is a conventional Full HD (1920x1080) display capable of running at 240 Hz, and a GeForce GTX 1080 Ti should not have much trouble pushing towards the high end of the refresh rate range at this lower resolution.
For competitive (eSports) gaming, higher refresh rates at moderate resolutions are generally preferable over high resolutions at lower refresh rates. Curved ultra-wide monitors are great for immersive gaming experiences, but for eSports, it's more important that you can react quickly to your opponents. The higher refresh rate helps you respond faster and gives you smoother motion, making it easier to keep track of the action. (More technically, a higher refresh rate means there's less time between each frame displayed, so the action appears on the screen faster.)
Furthermore, the AW3418DW uses an IPS panel with slower response times than the TN-based AW2518H. Although TN displays suffer from narrower viewing angles and lower color accuracy especially when viewed off-axis, they have faster response times, which results in less ghosting and motion blur. That, too, will make it easier to follow fast action during intensive gaming. IPS panels are great for color-critical professional applications like photography, and while though there are gaming-oriented IPS displays (including the AW3418DW), they can't achieve the sorts of response times the best TN panels can deliver. (Trust me, I know this first-hand after upgrading from a cheap IPS display to a Dell S2417DG. The faster response time is something you notice right away, even if viewing angles do suffer a bit.)
If yoy're looking at the Alienware 25 monitor, make sure you're buying the G-SYNC version (AW2518H) and not the FreeSync version (AW2518HF). The former is more expensive but since you have a GeForce card and not a Radeon, you'll need the G-SYNC display for the best experience.
Ultimately, while your choice of monitor is a major factor in overall latency, it is not the only thing that matters. This answer has more information about how different sources of latency can add up. In short, latencies from your processor, graphics card, the monitor's internal processing ("monitor input lag"), display response time and refresh rate, and even your mouse, can all add up.

A:
What is the practical advantage of a higher refresh rate

Objectively? You get more frames per second. Which means a shorter duration between frames. That is, if you go from 60 Hz to 100 Hz, you're going from 16.7 ms between frames to 10 ms between frames. Whether that 6.7 ms difference actually matters for gameplay is not possible to answer objectively. From 100 to 240 Hz is a further drop to 4.2 ms, a 5.8 ms difference.
Subjectively? Some people say it feels smoother (this is something you could test in-store). Some people say it lets you react faster. Some people like bigger numbers. I wouldn't subscribe to higher display refresh rates magically making you "play better", but if it makes you feel better that could also help.
The "feels smoother" part may be the most important (again: you really should see if you can find one in-store to physically try out). Any marginal benefit in reaction time in games is heavily outweighed by other latencies in the system (network, mouse input, processing), never mind that human reaction times are measured in the hundreds of milliseconds.
All of this only applies, of course, if your computer hardware is actually capable of outputting at these rates (in the games you play).

Aside from time between frames, another factor to look out for is input lag. That is the delay between the signal reaching the monitor and when it's actually visible on the screen, which includes decoding the signal and any post-processing the monitor may apply. This can be a couple times larger than the inter-frame time (we're talking from  under 10 ms to over 40 ms depending on the monitor). This is not the "response time" of the panel that you may see in specs.


text:
Q: .DrawImage with opacity? g.DrawImage

To.. yeah, draw an image in my picturebox. Is it possible to give it an opacity attribute? I have been looking at the other versions of DrawImage but couldn't find such thing!

A: You have to use a ColorMatrix to blend images.  Here's a C# control I wrote a while ago, it shows you the basic code you'll need.  Not VB.NET code but, hey, you didn't try real hard either:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;

public class BlendPanel : Panel {
    public BlendPanel() {
        DoubleBuffered = true;
    }
    public Image Image1 {
        get { return mImg1; }
        set { mImg1 = value; Invalidate(); }
    }
    public Image Image2 {
        get { return mImg2; }
        set { mImg2 = value; Invalidate(); }
    }
    public float Blend {
        get { return mBlend; }
        set { mBlend = value; Invalidate(); }
    }
    protected override void OnPaint(PaintEventArgs e) {
        if (mImg1 == null || mImg2 == null)
            e.Graphics.FillRectangle(new SolidBrush(this.BackColor), new Rectangle(0, 0, this.Width, this.Height));
        else {
            Rectangle rc = new Rectangle(0, 0, this.Width, this.Height);
            ColorMatrix cm = new ColorMatrix();
            ImageAttributes ia = new ImageAttributes();
            cm.Matrix33 = mBlend;
            ia.SetColorMatrix(cm);
            e.Graphics.DrawImage(mImg2, rc, 0, 0, mImg2.Width, mImg2.Height, GraphicsUnit.Pixel, ia);
            cm.Matrix33 = 1F - mBlend;
            ia.SetColorMatrix(cm);
            e.Graphics.DrawImage(mImg1, rc, 0, 0, mImg1.Width, mImg1.Height, GraphicsUnit.Pixel, ia);
        }
        base.OnPaint(e);
    }
    private Image mImg1;
    private Image mImg2;
    private float mBlend;
}

A: Thanks Hans Passant
It is very useful! It saved my time
I've converted you code into VB
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Windows.Forms

Public Class BlendPanel
    Inherits Panel
    Public Sub New()
        DoubleBuffered = True
    End Sub
    Public Property Image1() As Image
        Get
            Return mImg1
        End Get
        Set
            mImg1 = value
            Invalidate()
        End Set
    End Property
    Public Property Image2() As Image
        Get
            Return mImg2
        End Get
        Set
            mImg2 = value
            Invalidate()
        End Set
    End Property
    Public Property Blend() As Single
        Get
            Return mBlend
        End Get
        Set
            mBlend = value
            Invalidate()
        End Set
    End Property
    Protected Overrides Sub OnPaint(e As PaintEventArgs)
        If mImg1 Is Nothing OrElse mImg2 Is Nothing Then
            e.Graphics.FillRectangle(New SolidBrush(Me.BackColor), New Rectangle(0, 0, Me.Width, Me.Height))
        Else
            Dim rc As New Rectangle(0, 0, Me.Width, Me.Height)
            Dim cm As New ColorMatrix()
            Dim ia As New ImageAttributes()
            cm.Matrix33 = mBlend
            ia.SetColorMatrix(cm)
            e.Graphics.DrawImage(mImg2, rc, 0, 0, mImg2.Width, mImg2.Height, _
                GraphicsUnit.Pixel, ia)
            cm.Matrix33 = 1F - mBlend
            ia.SetColorMatrix(cm)
            e.Graphics.DrawImage(mImg1, rc, 0, 0, mImg1.Width, mImg1.Height, _
                GraphicsUnit.Pixel, ia)
        End If
        MyBase.OnPaint(e)
    End Sub
    Private mImg1 As Image
    Private mImg2 As Image
    Private mBlend As Single
End Class


text:
Q: Maven-shade tika-app returning empty string I was using tika-app-1.20.jar to extract metadata and content from files. Reason why I shaded Tika, was to remove dependencies clashing with each other in the project which was built already.
The shaded jar works fine no import problem with the new shaded-names ,but then its returning "EmptyParser" for all files leading to no content being parsed.
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.test1.tika</groupId>
  <artifactId>tika-app</artifactId>
  <version>1.20</version>
  <packaging>jar</packaging>

  <name>tika-app</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.tika</groupId>
        <artifactId>tika-app</artifactId>
        <version>1.20</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3</version>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>3.2.1</version>
            <configuration>
                <createSourcesJar>true</createSourcesJar>
        <relocations>
          <relocation>
            <pattern>org.apache.tika</pattern>
            <shadedPattern>com.test1.tika</shadedPattern>
          </relocation>
        </relocations>

        <filters>
          <filter>
              <artifact>*:*</artifact>
              <excludes>
                  <exclude>META-INF/*.SF</exclude>
                  <exclude>META-INF/*.RSA</exclude>
                  <exclude>META-INF/*.DSA</exclude>
              </excludes>
          </filter>
      </filters>
            </configuration>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

</project>

I removed the .SF,.RSA,*DSA to remove invalid signature digest error. My intuition is that , some property file is getting removed in this process that maps the parser with filetype.


text:
Q: Firebase Notification and Cloud Messaging I have a question about Firebase. I've developed an app with GCM implementation service and I'll be updating it to Firebase. What I would like to know is if there is any limit for sending notifications to my client?
What is the limit number of notifications in a day and for clients in a day? Google says the service is free, but there isn't any documentation of license to use it. Does anyone know about it? Thanks in advance.

A: There is no limit to the number of notifications you can push with fire base daily, or at least I haven't had any issues with it and Google sure didn't mention push notifications as a limited feature


text:
Q: Trigger Module Lazy Load Manually Angular 7 Official documentation has quite a lot of information about how to load angular modules lazily. [link here]
const routes: Routes = [
  {
    path: 'customers',
    loadChildren: './customers/customers.module#CustomersModule'
  },
  {
    path: 'orders',
    loadChildren: './orders/orders.module#OrdersModule'
  },
  {
    path: '',
    redirectTo: '',
    pathMatch: 'full'
  }
];

This basically makes the module load when user visits /customers or /orders routes.
However, I can't figure out how do I load a module when from another module.
In my application I have these modules:

*

*auth

*core

*events

*flash messages

One route of my auth module (profile page) has to use ngrx store from events module.
My code looks like this:
import { Observable } from 'rxjs';

import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';

import { AppState } from '../../app.store';
import { IUser } from '../auth.api.service';
import { selectUser } from '../store/auth.selectors';
import { IEvent } from '../../events/events.api.service';
import { selectAllEvents, selectIsLoading } from '../../events/store/events.selectors';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.scss'],
})
export class ProfileComponent implements OnInit {
  isLoading$: Observable<boolean>;
  events$: Observable<IEvent[]>;
  user$: Observable<IUser>;

  constructor(
    private store: Store<AppState>,
  ) {
    this.user$ = this.store.select(selectUser);
    this.isLoading$ = this.store.select(selectIsLoading);
    this.events$ = this.store.select(selectAllEvents);
  }

  ngOnInit() {
  }

}

However, as you can expect this code does not work. Because ../../events is not loaded yet. How do I load the module manually? Something like:
constructor(
  private store: Store<AppState>,
) {
  this.user$ = this.store.select(selectUser);
  this.loadModule('../../events/events.module.ts').then(() => {
    this.isLoading$ = this.store.select(selectIsLoading);
    this.events$ = this.store.select(selectAllEvents);
  })
}

A: The Angular CLI bundler bundles up the modules based on two things:
1) If you have the modules set up for lazy loading (loadChildren), it will bundle the module up separately and provide it lazily.
2) HOWEVER, if there are any references to a lazy loaded module in any other module (by adding it to its imports array), it instead bundles the module with the referenced component.
So what should be happening is that if your events module is referenced from a component, it should be bundled with that component.
Do you have the module referenced in the imports array for the module containing the component that references it?
What error are you getting exactly?
BTW - I cover this in the "lazy loading" part of this talk: https://www.youtube.com/watch?v=LaIAHOSKHCQ&t=1120s

A: You need not worry about loading the ../../events. Since you have the import statement, the class/interface would be available in the module. If for some reason, you want to use features of other modules, you can add the module name in the imports array in the @NgModule declaration.


text:
Q: binding a command object with ValueConverter In my Grails 2.3.7 app, I have the following command object
class UpdateThresholdsCommand {
    Double threshold_1
    Double threshold_2
}

The parameters I'm trying to bind to these properties are formatted currency values, e.g. threshold_1=$2,459.04&threshold_2=$1,459.04
I've defined the following implementation of ValueConverter to perform this binding
class CurrencyStringToDoubleConverter implements ValueConverter {

    FormatService formatService

    @Override
    boolean canConvert(Object value) {
        value instanceof String
    }

    @Override
    Object convert(Object value) {
        formatService.parseCurrency((String) value)
    }

    @Override
    Class<?> getTargetType() {
        Double
    }
}

and registered it in resources.groovy
currencyStringToDoubleConverter(CurrencyStringToDoubleConverter) {
    formatService = ref('formatService')
}

But when a request with params such as those shown above is sent to the action, CurrencyStringToDoubleConverter is never invoked, so the threshold_1 and threshold_2 properties of the command object are null. Why isn't CurrencyStringToDoubleConverter being invoked?

A: The approach you describe does work.  See the app at https://github.com/jeffbrown/donalconverter.  Run that app and click the link on the main index page.  The FormatService is hardcoded to return 21.12 (see https://github.com/jeffbrown/donalconverter/blob/7a01031deceeea0d857af23f58686b4f1f824e1d/grails-app/services/demo/FormatService.groovy#L7) but the app demonstrates that the converter is being invoked and that the converter is delegating to the service.
You have not shown what your FormatService is doing.  It may be that there is something wrong in that code and that is throwing an exception, in which case your command object should have a corresponding binding error associated with it.
It is difficult to say what is going wrong without seeing your code or seeing any relevant errors, but the linked app should demonstrate that the converter is being invoked, at least in that app.
The relevant files in the app:

*

*grails-app/conrollers/demo/DemoController.groovy

*grails-app/services/demo/FormatService.groovy

*src/groovy/demo/CurrencyStringToDoubleConverter.groovy

*grails-app/conf/spring/resources.groovy
I hope that helps.

A: If anyone finds their way here, you may have to put this annotation on your converter to give it a higher precedence than the built in Grails converters:
import org.springframework.core.annotation.Order
import org.springframework.core.Ordered

@Order(value=Ordered.HIGHEST_PRECEDENCE)
class DateTimeValueConverter implements ValueConverter  {
    // blah blah
}


text:
Q: .htaccess RewriteRule with form parameter www.example.com/Search.php?q=mySearchString this is my search link. I want to change it to
www.example.com/Search/mySearchString
Then I tried below rule in my .htaccess file but it looks like -> Search/?q=mySearchString
How I can eliminate ?q= from address
in .htaccess file I add a rule like this;
RewriteRule ^Search/(.*)$ Search.php?q=$1 [L,NC]

Also I send search query with a form and form's method is 'GET'
 <form class="navbar-search pull-left" method="GET" action="Search/">
    <input name="q" type="text" />
 </form>

How can I fix it?

A: If you rename your search input to:
<input name="query" type="text" />

Then use these two rules:
# If someone searches /Search/?query=search+string
RewriteCond %{QUERY_STRING} query=([^&]+)
# Redirect to /Search/search+string
RewriteRule ^Search/$ Search/%1 [L,R=301,NC]

# Match the redirect from the rule above and serve up results
RewriteRule ^Search/(.*)$ Search.php?q=$1 [L,NC]


text:
Q: How can I fix a Ubuntu upgrade when it was interrupted by a power outage? I hope someone can point me in the right direction. I was upgrading to Ubuntu 12, then the
power died and I fixed the broken packages. The system asked to reboot but now I am unable to boot (hangs during boot sequence).
I am able to get into terminal and have mc to view files.
I have tried previous versions under the advanced boot, but all fail to load.
Can someone point me in the right direction to find out what went wrong?
Thanks in advance.

A: It has happened to me before. No fix seems to work 100%, because your repositories are probably mixed between old and new. I sugest you to back up your home and do a Fresh, Clean install.

A: You can run Ubuntu 12.10 as a LIVE-CD/DVD/USB.
Try to click on "Upgrade" then, when it's up or just make a whole new and fresh install!

A: I had the same experience. I had power go out while it was upgrading. I booted in safe mode of an earlier version. At that point, it automatically asks for fixing broken packages. I waited for it to finish and was able to bring it to command-line mode. The boot sequence seems to hang, but press Ctrl+Alt+F2 and enter user/password. After that enter startx on command line - it brings up GUI.
I am still looking how to bring it straight to the gui mode rather than Ctrl+Alt+F2 and then startx.


text:
Q: Enabling sort of Notes embedded view in Notes classical Web UI I need to modify a Notes legacy web view in the existing application. The view is embedded in a page and accessed by web browser. It looks the column sorting is not available in this case. I confirmed it is available in pure view(not embedded view).
In this case, is there any good solution? I think one of solution is simply to prepare two sorting views and a user chooses from outline or clicking button to change the view. But I'd like to know if there is more good solutions.

A: What version of Notes/Domino is this web legacy application running on?  That will help us give you the best answer based on the version  you're running.
Since you're running 9.0.1 you do have a variety of options including XPages.  Since XPages is not an option for you, please explore the other available options from the link below on IBM's site:
https://www.ibm.com/support/knowledgecenter/SSVRGU_8.5.3/com.ibm.designer.domino.main.doc/H_EMBEDDING_A_VIEW_OR_NAVIGATOR.html
I think that you'll find embedding the Java view applet a very simple and effective alternative that requires very little development skill.  It also gives the sorting options that you are needing. Here's a link with additional info on this option:
https://www.ibm.com/support/knowledgecenter/SSVRGU_8.5.3/com.ibm.designer.domino.main.doc/H_VIEW_APPLET.html


text:
Q: this.props.createNewBook is not a function. How to add new prop? Header.js
 class header extends React.component {
{
  render(
<CreateBook bookType= { createBookType } closeModal= { this.closeModal } />
)
}
}

CreateBook.js
  class CreateBook extends React.Compoent {
      showResult() {
        const errors = this.validate();
        if (errors.length === 0) {
          this.props.createNewBook(JSON.stringify(this.state.model));
        } else {
          this.setState({
            errorList: errors,
          });
        }
      }

  render() {
    console.log(this.props)
    return (
.
.
.
<Button id= "save" onClick= {() => this.showResult()
  }> Save </Button >
}
CreateBook.propTypes = {
  createNewBook: PropTypes.func,
  bookType: PropTypes.string.isRequired,
  closeModal: PropTypes.func,
};

Now I created a container which has
    const mapDispatchToProps = (dispatch) => ({
      createNewBook: (data) => dispatch(createBookAction(data)),
    });

export default connect(null, mapDispatchToProps)(CreateBook);

In the above code, I can't get createNewBook prop value . So, I cant call dipatch function.
When i am trying to get log, I only get bookType and closeModal.
Please help me resolve this issue.

A: To use this in showResult, you need to bind it in the constructor:
this.showResult = this.showResult.bind(this)


text:
Q: Discriminant vs. generatve functions In the context of machine learning, does anyone know what is the difference betweeen the above?

A: A good reference is "On Discriminative vs. Generative classifiers: A comparison of logistic regression and naive Bayes" by Andrew Ng and Michael Jordan. The basic gist is if y is your output and x is your input, then a discriminative classifier will model P(y|x) (so the probability of y given x) while a generative classifier will model P(y,x).
There are several consequences of this difference, and the paper by Ng and Jordan discusses many of them. One is that asymptotically (i.e. for very large sample sizes) discriminative classifiers will perform better, but for smaller samples generative classifiers can perform better. Another difference is you can generate a synthetic dataset from a trained generative classifier if you can sample from the probability distribution, but for a discriminative classifier you can only sample outputs y for a given x.


text:
Q: SpringBoot's DataJpaTest with Flyway I'm using flyway in my project to setup the DB schema. When I try using the @DataJpaTest annotation to test some JPA layer I get this error upon startup:
> Caused by:
> org.flywaydb.core.internal.command.DbMigrate$FlywayMigrateSqlException:
> Migration V1__init.sql failed
> ----------------------------- SQL State  : 42581 Error Code : -5581 Message    : unexpected token: AUTO_INCREMENT : line: 2 Location   :
> db/migration/V1__init.sql
> ..../target/classes/db/migration/V1__init.sql) Line       : 1
> Statement  : CREATE TABLE mytable (    id INT NOT NULL AUTO_INCREMENT
> PRIMARY KEY,

It looks like it is trying to use HSQL instead of the regular SQL
Is there a way I can use @DataJpaTest with flyway ?

A: It's trying to use HSQLDB to execute the scripts. What you can do is create a database schema for tests and use it in a different profile. Assuming that you're using MySQL, you could have an application-test.properties inside your resources source folder like this:
spring.datasource.url=jdbc:mysql://localhost/test_db
spring.datasource.username=your_user
spring.datasource.password=your_pass
spring.jpa.hibernate.ddl-auto=create

And then, in your test class you need to activate this profile with the annotation @ActiveProfiles and disable HSQLDB with the annotation config in @AutoConfigureTestDatabase:
@DataJpaTest
@ActiveProfiles("test")
@AutoConfigureTestDatabase(replace = Replace.NONE)
public class DBTest { ... }


text:
Q: Pandas - manipulate dataframe to create multi-level columns Here is the dataframe:
A  B     val  val2  loc
1  march 3    2     NY
1  april 5    1     NY
1  may   12   4     NY
2  march 4    1     NJ
2  april 7    5     NJ
2  may   12   1     NJ
3  march 1    8     CA
3  april 54   6     CA
3  may   2    9     CA

I'd like to transform this into:
       march march april april may  may
       val1  val2  val1  val2  val1 val2
A  B
1  NY  3     5     12   2     1     4
2  NJ  4     7     12   1     5     5
3  CA  1     54    2    8     6     9

I'm looking into pivot tables and stacking and unstacking but im truly stuck. I'm not sure where to start

A: With pd.pivot_table, and some swapping of levels:
new_df = (pd.pivot_table(df,['val','val2'],['A','loc'],['B'])
          .sort_index(axis=1, level=1)
          .swaplevel(0, axis=1))

>>> new_df
B     april      march      may
        val val2   val val2 val val2
A loc
1 NY      5    1     3    2  12    4
2 NJ      7    5     4    1  12    1
3 CA     54    6     1    8   2    9

If the ordering of your columns is important (as in you need it as march, april and may), you can set it to a ordered categorical:
new_df = (pd.pivot_table(df,['val','val2'],['A','loc'],
                         [pd.Categorical(df.B, categories=['march','april','may'],
                                         ordered=True)])
          .dropna(how='all')
          .sort_index(axis=1, level=1)
          .swaplevel(0, axis=1))

>>> new_df
B     march      april        may
        val val2   val val2   val val2
A loc
1 NY    3.0  2.0   5.0  1.0  12.0  4.0
2 NJ    4.0  1.0   7.0  5.0  12.0  1.0
3 CA    1.0  8.0  54.0  6.0   2.0  9.0


text:
Q: EXC_BAD_ACCESS, Could not access memory I have code doing numerical optimization (large program). In gdb it exits with
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: 13 at address: 0x0000000000000000
[Switching to process 8673 thread 0x1203]
0x00007fff95d2a9fb in small_malloc_from_free_list ()

During backtrace I am told that the following line contains the error, but can't figure out what's wrong.
177     U  = calloc(cols*cols,sizeof(double));

The code containing that line is
int fcn_invXX(double *X, int rows, int cols, double *invXX)
{
    //---------------------------------------------------------------
    // Declarations
    //---------------------------------------------------------------

    // Counters and info
    int i, j, info;

    // Upper triangular placeholder, U, and X'X
    double *U, *XX;

    // Indicator for upper triangular
    char s;

    // Alpha and beta for matrix multiplication - see dgemm documentation
    double alpha, beta;

    //---------------------------------------------------------------
    // Memory Allocation
    //---------------------------------------------------------------
    U  = calloc(cols*cols,sizeof(double));
    XX = calloc(cols*cols,sizeof(double));

    //---------------------------------------------------------------
    // Compute inverse of X'X
    //---------------------------------------------------------------
    alpha = 1.0;
    beta  = 0.0;

    // Get X'X
    cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, cols, cols, rows, alpha, X, rows, X, rows, beta, XX, cols);
    // CblasColMajor means that data are ordered in columns first, so if X is 4x4, X[0] and X[1] are first column
    // CblasTrans means that the matrix should be transposed before multiplication. Here first matrix is transposed
    // CblasNoTrans means that matrix should not be transposed. Here second matrix is not transposed
    // X is the first matrix, and here, also the second
    // XX stores the product

    for (i = 0; i < cols*cols; i++)
    {
        U[i] = XX[i];
    }

    // Upper Cholesky factorization
    s = 'U'; // upper
    dpotrf_(&s, &cols, U, &cols, &info);
    // info = LAPACKE_dpotrf(LAPACK_COL_MAJOR, s, cols, U, cols);

    for (i = 0; i < cols*cols; i++)
    {
        invXX[i] = U[i];
    }

     // Get inverse
    dpotri_(&s, &cols, invXX, &cols, &info);
    // info = LAPACKE_dpotri(LAPACK_COL_MAJOR, s, cols, invXX, cols);

    for (i = 0; i < cols; i++)
    {
        for (j = 0; j < cols; j++)
        {
            if (i > j)
            {
                invXX[i + j * cols] = invXX[j + i * cols];
            }
        }
    }

    //---------------------------------------------------------------
    // Free Memory
    //---------------------------------------------------------------
    free(U);
    free(XX);

    return info;

}

Hope you can help.


text:
Q: Developing a Git library project that's also a submodule of another project I have an Android application under development which makes use of a separate library project of my own. These two projects are stored in separate Git repositories. The application project references the library project by means of the .gitmodules file.
I'm now trying to work on both of these projects together (the application and the library) on a new machine. I cloned the application project, which resulted also in the library project being automatically cloned into my ~/git/ directory as well. So far so good.
I notice also that in Eclipse Package Explorer, the library project root has a commit hash within brackets (e.g. [MyLibraryName 0123ABC]). This presumably means that the library clone is from a certain commit point, and I understand that I could update this (i.e pull in the latest commits for this library) using git submodule foreach git pull.
Question is, what is the best way for me to continue separately developing the library project now? I tried to modify a file and stage it, but when using Team->commit, the dialogue didn't list the modified file. I assume this might be something to do with it being a submodule, pointing at a particular commit.
Should I clone my library project again, completely separately into a different subdirectory, and import as a separate project into Eclipse in order for me to do work on that library?

A: Having read various other SO questions, it seems apparent that there's no elegant solution for this. The steps I eventually took to solve this are:

*

*Assuming not done so already, clone the application repository that makes use of submodules. Import all projects into Eclipse workspace, including the submodule repository (or repositories). Note that the submodule repository is a repository within the main application repository, and it's not on a particular branch; it's a reference to a particular commit (detached head).

*In the Package Explorer, rename the submodule project that was imported. I gave it a name that relates to the application repo it's inside of. For instance, for an application project called ABCD, rename it from SomeLibrary to SomeLibrary_ABCD.

*Next, clone the library separately from its own Git repository. Now, the point of renaming the submodule project is that it's now possible to import the Eclipse project from the standalone clone of the library repository, without Eclipse giving the "Some or all projects can not be imported because they already exist in the workspace" error.
Having done this, we have SomeLibrary_ABCD project which is not on a branch but points to a particular commit, and is a submodule of project ABCD. That submodule is updated using git submodule foreach git pull. Then, we have project SomeLibrary, which is on a branch (e.g. master).
My planned workflow is to locally switch the application project to point at my 'standalone' project of the library instead of the submodule version when I want to do development on the library. I then commit changes to SomeLibrary.
Any better suggestions than this (or corrections to anything I've stated) would be appreciated - but for now this is my own answer to the problem.


text:
Q: Monosyllabic triphthongs with R are distinguished from sequences with disyllabic realizations
In British Received Pronunciation, and most other non-rhotic
(r-dropping) varieties of English, monosyllabic triphthongs with R are
optionally distinguished from sequences with disyllabic realizations:
[aʊ̯ə̯] as in hour (compare with disyllabic "shower" [aʊ̯.ə]) [aɪ̯ə̯]
as in fire (compare with disyllabic "higher" [aɪ̯.ə]) [ɔɪ̯ə̯] as in
"loir" (compare with final disyllabic sequence in "employer" [ɔɪ̯.ə])
As [eɪ̯] and [əʊ̯] become [ɛə̯] and [ɔː] respectively before /r/, most
instances of [eɪ̯.ə] and [əʊ̯.ə] are words with the suffix "-er".
Other instances are loanwords, such as boa.
[aʊ̯ə̯, aɪ̯ə̯, ɔɪ̯ə̯] are sometimes written with ⟨awə, ajə, ɔjə⟩, or
similarly.
https://en.wikipedia.org/wiki/Triphthong#English

Do they mean actually acoustically or just notationally?
Secondly, why is the letter r capitalized ?


text:
Q: Generate float Random number between [0,1] and restricting decimal I want to generate Random Float numbers between Interval [0,1]. The generated Random values will be compared with an input from a file. The content of the File is a probability (float values) and hence they are in range[0,1] and it looks like:
0.55
0.14
0.005
0.870
0.98
0
1
I am reading this File and storing probability values into a DoubleList. Now I want to generate a float Random Number between [0,1]. As you see the file have probability values upto 1 digit, 2 digits decimal and 3 digits decimal as well.
I am using following Code:
public static double randomNumberGenerator()
{
    double rangeMin = 0.0f;
    double rangeMax = 1.0f;
    Random r = new Random();
    double createdRanNum = rangeMin + (rangeMax - rangeMin) * r.nextDouble();
    return(createdRanNum);
}

The random float value generated should be also be like Probabilities values (like generated upto the maximal decimal digits as in the file). How can I restrict the generated decimal digits?
I checked the following Link: Java random number between 0 and 0.06 . People suggested Int number generation and then did the double division by 100. Is this the good way? Can't we restrict the decimal generated directly?
PS: If I compare the random generated number from the above code with the double values from File, would there be some memory fall issues in the DoubleList?

A: You could just use Java Random class :
Random rand = new Random();
float f = rand.nextFloat()

which returns the random float number between 0.0f (inclusive) and 1.0f(exclusive).
To round the result of the nextFloat() you could just use an helper method like the following :
public static float round(float d, int decimalPlace) {
    BigDecimal bd = new BigDecimal(Float.toString(d));
    bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
    return bd.floatValue();
}


text:
Q: Explicit example of Integral de Rham cohomology I want to see an explicit example of integral de Rham cohomology to gain some intuition that how it work really. More precisely (if I am not mistaken)
A $k$-form $\omega$ is integral (i.e. $[\omega]\in\mathbf{H}^k_{\text{dR}}(M,\Bbb Z)$) iff its integral over all (smooth) singular $k$-cycles is an integer; i.e. $$\forall\ \Sigma\subset M,\ \partial\Sigma=0, \text{and compact}\qquad\int_\Sigma\omega\in\Bbb Z.$$
I need an example that have more choices for $\Sigma$, not like sphere that all $\Sigma$ (I think all of them are $k$-spheres) are homotopic to each other. Obviously not tricky example using Stokes' theorem.


text:
Q: oracle 10g submit job function error I'm trying to schedule a job in oracle 10g  but it says:
ORA-01846: not a valid day of the week.
Heres my code:
declare
    v_job_id1 number(19,0);
    v_job_id2 number(19,0);
begin
    dbms_job.submit(v_job_id1, 'CTX_DDL.OPTIMIZE_INDEX(''PSO_KEYWORD_SEARCH_IDX'', ''FULL'', 45);', NEXT_DAY(TRUNC(SYSDATE), 4) + 13/24, NEXT_DAY(TRUNC(SYSDATE), 4) + 13/24 + 7 );
     commit;
end;
/

But this work as intended:
select NEXT_DAY(TRUNC(SYSDATE - 1), 4) + 13/24 from dual;

ANy ideas?
Thank you!
Udo

A: Interval parameter must be a string with SQL expression, executed by Oracle when calculating date and time of next run.
Therefore expression must be quoted:
dbms_job.submit(
  JOB       =>  v_job_id1,
  WHAT      => 'CTX_DDL.OPTIMIZE_INDEX(''PSO_KEYWORD_SEARCH_IDX'', ''FULL'', 45);',
  NEXT_DATE => NEXT_DAY(TRUNC(SYSDATE), 4) + 13/24,
  INTERVAL  => 'NEXT_DAY(TRUNC(SYSDATE), 4) + 13/24 + 7'
);

A: I'm posting this as an answer instead of a comment to allow better code formatting.  ThinkJet's comment about the interval parameter is a valid point, and I still think your problem is related to the '4' arg to NEXT_DAY - for example, this code works:
SQL> declare
  2      v_job_id1 number(19,0);
  3      v_job_id2 number(19,0);
  4  begin
  5      dbms_job.submit(v_job_id1,
  6        'begin null; end;',
  7        NEXT_DAY(TRUNC(SYSDATE), 'Thursday') + 13/24,
  8        'NEXT_DAY(TRUNC(SYSDATE), '||chr(39)||'Thursday'||chr(39)||') + 13/24 + 7' );
  9       commit;
 10  end;
 11  /

PL/SQL procedure successfully completed.

A: I can't explain why it happens, but Oracle accepts invalid NEXT_DAY(...) call syntax  in plain SQL.
But not in PL/SQL code. Try this:
declare
  d date;
begin
  d := NEXT_DAY(TRUNC(SYSDATE), 4) + 13/24 + 7;
end;

and you got perfect ORA-01846 error.
Oracle suggests workaround with switching NLS_DATE_LANGUAGE session parameter before calling NEXT_DAY to 'AMERICAN' and return it back after calculation.
Example:
DECLARE
FUNCTION get_next_day(dn IN VARCHAR2,ln IN VARCHAR2) RETURN DATE IS
CURSOR cr1 IS
SELECT value
  FROM nls_session_parameters
 WHERE parameter = 'NLS_DATE_LANGUAGE';
CURSOR cr2(dn1 IN VARCHAR2) IS
SELECT next_day(SYSDATE,UPPER(dn1))
  FROM dual;
day DATE;
old_date_lang varchar2(128);
BEGIN
  OPEN cr1;
  FETCH cr1 INTO old_date_lang;
  CLOSE cr1;
  dbms_session.set_nls('NLS_DATE_LANGUAGE',ln);
  OPEN cr2(dn);
  FETCH cr2 INTO day;
  CLOSE cr2;
  dbms_session.set_nls('NLS_DATE_LANGUAGE', old_date_lang);
  RETURN (day);
END;
BEGIN
  dbms_output.put_line(TO_CHAR(get_next_day('MONDAY','AMERICAN'),'DAY dd/mm/yyyy'));
END;

From my point of view better to avoid using NLS-aware functions at all, but day-of-a-week NLS-depended by definition: at some countries week starts from Sunday, at other countries - from Monday ...
You can try to use TRUNC() function with 'D' option to lower NLS effect:
select
  NEXT_DAY(TRUNC(SYSDATE), 4)          as D1,
  NEXT_DAY(TRUNC(SYSDATE), 'THU')      as D2,
  case
    -- next Thursday on this week
    when (TRUNC(SYSDATE,'D') + 4) > trunc(sysdate) then (TRUNC(SYSDATE,'D') + 4)
    -- next Thursday on next week
    else (TRUNC(SYSDATE,'D') + 4) + 7
  end                                  as D3
from dual

In your case this looks like that:
dbms_job.submit(
  JOB       =>  v_job_id1,
  WHAT      => 'CTX_DDL.OPTIMIZE_INDEX(''PSO_KEYWORD_SEARCH_IDX'', ''FULL'', 45);',
  NEXT_DATE => (
                 case
                   -- next Thursday on this week
                   when (TRUNC(SYSDATE,'D') + 4) > trunc(sysdate) then (TRUNC(SYSDATE,'D') + 4)
                   -- next Thursday on next week
                   else (TRUNC(SYSDATE,'D') + 4) + 7
                 end
               ),
  INTERVAL  => '
      case
        when (TRUNC(SYSDATE,''D'') + 4) > trunc(sysdate) then (TRUNC(SYSDATE,''D'') + 4)
        else (TRUNC(SYSDATE,''D'') + 4) + 7
      end
  '
);

Update:
Perfect workaround is to get name of the day from current NLS settings and use as day name.
Because Aug-12-2010 definitely Thursday you can use it as base date to get day-of-the-week name:
select to_char(to_date('20100812','yyyymmdd'), 'DAY') from dual

Then add name to function call instead of 4 constant:
dbms_job.submit(
  JOB       =>  v_job_id1,
  WHAT      => 'CTX_DDL.OPTIMIZE_INDEX(''PSO_KEYWORD_SEARCH_IDX'', ''FULL'', 45);',
  NEXT_DATE => NEXT_DAY(TRUNC(SYSDATE), to_char(to_date('20100812','yyyymmdd'), 'DAY')) + 13/24,
  INTERVAL  => 'NEXT_DAY(TRUNC(SYSDATE), to_char(to_date(''20100812'',''yyyymmdd''), ''DAY'')) + 13/24 + 7'
);

A: Make sure that you are using the day according to the locale.
For Ex:-
the day 'Sunday' should be written as 'Sonntag' in German.
I had faced the similar issue.. :p


text:
Q: Python tkinter : how to resize widgets when i resize the screen I'm beginner...
When the code below is executed, how do I make the widgets inside increase when the screen size is increased to width? but, it couldn't resized..
Does it matter if I use either pack or grid?
i can't solve it....
  from tkinter import *
  from tkinter import ttk

  class program:
      def __init__(self):
          self.root = Tk()
          self.root.title("Python")
          self.root.resizable(True, True)
          self.create_project()

      def create_project(self):
          Topic_Label = ttk.Label(self.root, text="program")
          Topic_Label.pack(side="top")

          Record_LabelFrame = LabelFrame(self.root, text="Record information")
          Record_LabelFrame.pack(side="top", anchor=W, padx=10)

          date = ttk.Label(Record_LabelFrame, text="date")
          date.grid(column=0, row=0, sticky=W)

          Topic_Label_Entry1 = ttk.Entry(Record_LabelFrame)
          Topic_Label_Entry1.grid(column=0, row=1)

          time = ttk.Label(Record_LabelFrame, text="time")
          time.grid(column=1, row=0, sticky=W)

          Topic_Label_Combo1 = ttk.Combobox(Record_LabelFrame)
          Topic_Label_Combo1.grid(column=1, row=1)

          recorder = ttk.Label(Record_LabelFrame, text="record")
          recorder.grid(column=2, row=0, sticky=W)

          Topic_Label_Entry2 = ttk.Entry(Record_LabelFrame)
          Topic_Label_Entry2.grid(column=2, row=1)

          loc = ttk.Label(Record_LabelFrame, text="location")
          loc.grid(column=0, row=2, sticky="W")

          RadioVar = IntVar()

          Radio_Frame = Frame(Record_LabelFrame)
          Radio_Frame.grid(column=0, row=3, sticky=W)

          Topic_Label_Radio1 = ttk.Radiobutton(Radio_Frame, text="A", variable=RadioVar, value=1)
          Topic_Label_Radio1.grid(column=0, row=0)

          Topic_Label_Radio2 = ttk.Radiobutton(Radio_Frame, text="B", variable=RadioVar, value=2)
          Topic_Label_Radio2.grid(column=1, row=0)

          Topic_Label_Radio3 = ttk.Radiobutton(Radio_Frame, text="C", variable=RadioVar, value=3)
          Topic_Label_Radio3.grid(column=2, row=0)

          count = ttk.Label(Record_LabelFrame, text="count")
          count.grid(column=1, row=2, sticky="W")

          Topic_Label_Combo2 = ttk.Combobox(Record_LabelFrame)
          Topic_Label_Combo2.grid(column=1, row=3)

          seed_name = ttk.Label(Record_LabelFrame, text="seed")
          seed_name.grid(column=2, row=2, sticky="W")

          Topic_Label_Entry4 = ttk.Entry(Record_LabelFrame)
          Topic_Label_Entry4.grid(column=2, row=3)

  mt = program()
  mt.root.mainloop()

I want to print like this that widget resize automatically when i resize the screen

https://i.stack.imgur.com/iSbaJ.png
https://i.stack.imgur.com/mzv9R.png


text:
Q: find out hexadecimal literal Anyone tell me what the hexadecimal literal for #419ddc or let me know how I can go about finding out?

A: The hexadecimal literal #419ddc is the same as the RGB literal rgb(65,157,220) or rgb(25%,62%,86%).
The format is #rrggbb, so red is 41 (= decimal 65), green is 9d (= decimal 157) and blue is dc (= decimal 220).


text:
Q: Why doesn't strace report that the parent shell fork() a child process before execve() a command? strace runs a specified command until it exits.  It intercepts and records the system calls which are called by a process and the  signals  which are received by a process.
When running an external command in a bash shell, the shell first fork() a child process, and then execve() the command in the child process. So I guess that strace will report fork() or something similar such as clone()
But the following example shows it doesn't. Why doesn't strace report that the parent shell fork() the child process before execve() the command? Thanks.
$ strace -f time
execve("/usr/bin/time", ["time"], [/* 66 vars */]) = 0
brk(0)                                  = 0x84c000
access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7efe9b2a5000
access("/etc/ld.so.preload", R_OK)      = -1 ENOENT (No such file or directory)
open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=141491, ...}) = 0
mmap(NULL, 141491, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7efe9b282000
close(3)                                = 0
access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
open("/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\320\37\2\0\0\0\0\0"..., 832) = 832
fstat(3, {st_mode=S_IFREG|0755, st_size=1840928, ...}) = 0
mmap(NULL, 3949248, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7efe9acc0000
mprotect(0x7efe9ae7b000, 2093056, PROT_NONE) = 0
mmap(0x7efe9b07a000, 24576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1ba000) = 0x7efe9b07a000
mmap(0x7efe9b080000, 17088, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7efe9b080000
close(3)                                = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7efe9b281000
mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7efe9b27f000
arch_prctl(ARCH_SET_FS, 0x7efe9b27f740) = 0
mprotect(0x7efe9b07a000, 16384, PROT_READ) = 0
mprotect(0x602000, 4096, PROT_READ)     = 0
mprotect(0x7efe9b2a7000, 4096, PROT_READ) = 0
munmap(0x7efe9b282000, 141491)          = 0
write(2, "Usage: time [-apvV] [-f format] "..., 177Usage: time [-apvV] [-f format] [-o file] [--append] [--verbose]
       [--portability] [--format=format] [--output=file] [--version]
       [--quiet] [--help] command [arg...]
) = 177
exit_group(1)                           = ?
+++ exited with 1 +++

A: The fork in question is part of the mechanism which launches strace; it has concluded by the time tracing begins.

A: $ strace -f time
execve("/usr/bin/time", ["time"], [/* 66 vars */]) = 0
brk(0)                                  = 0x84c000
...

Strace directly invokes the program to be traced. It doesn't use the shell to run child commands, unless the child command is a shell invocation. The approximate sequence of events here is as follows:

*

*The shell executes strace with arguments "strace", "-f", "time".

*Strace starts up, parses its command line, and eventually forks.

*The original (parent) strace process begins tracing the child strace process.

*The child strace process executes /usr/bin/time with the argument "time".

*The time program starts up.

After step 1, the original shell process is idle, waiting for strace to exit. It's not actively doing anything. And even if it were doing something, it's not being traced by strace, so its activity wouldn't appear in the strace output.


text:
Q: Posting base64 encoded files to an asp.net 1.1 page We are making an automated patching application and would like to post files on production server through asp.net page (or maybe a web service), since we can only access production server via http. The page should accept files and store them to appropriate location. The path to files will be declared in external XML file.
So, is it possible posting a base64 encoded files within body tag and HOW? maybe even any better approach?

A: If you plan to use Base64 encoding.
Take a look at
        System.Convert.ToBase64String()
        System.Convert.FromBase64String()
        System.Convert.ToBase64CharArray()
        System.Convert.FromBase64CharArray()

A: See Using XML CDATA nodes to send files via a Web Service

A: why not create a webservice which accepts an object like:
class postfile
{
 public byte[] fileByte;
 public string fileName;
}

Then add a web reference in your client app.
.net will serialize the object for you.
You will need to secure this using wse security and might require the service use impersonation to write the file on the server.


text:
Q: Search for factors of integers and how many of them I have a homework to make a program using the VBA in excel (using the Command Button (ActiveX Control). I need to make a code to show how many factors are there and what are the factors of an integer.
I'm a total beginner. I only know how to use "For... to..." and "If... then..." just a few hours ago.
I knew if I want to search for the factors then n as the integer we input and i as number from 1 to n.
If n mod i = 0 then
  //all the i are the factors.

I don't know how to write it in VBA.

A: You are in the right direction
Sub factors()
N = Range("A1").Value ' number in cell A1
r = 1
For i = 1 To N - 1
  If N Mod i = 0 Then
    Cells(r, 2) = i
    r = r + 1
  End If
Next
End Sub


text:
Q: Submit Button on Razor View doesn't call Action Result - MVC I have an issue with my submit button not calling the actionresult. I have set the breakpoint in the action result itself so i know that the actionResult is not even being called.  Thank you in advance for your guidance.
View:
@model CCQAS.WebApp.Areas.Credentialing.Models.TransferCustodyViewModel
@using CCQAS.API.Model.Enums
@{var PersonId = ViewBag.SessionPersonId;}
@{ViewBag.Title = "Transfer Custody ";
ViewBag.HelpText = "When this record transfer becomes effective, responsibility for updating and maintaining this credentials record will be transferred to the gaining UIC";}

@using (Html.BeginForm("CreateCustodyTransfer", "TransferCustody", FormMethod.Post, new { @id = "transfer-custody-form", @role = "form" }))
{
@Html.AntiForgeryToken()

                    Transfer Custody for @Html.DisplayFor(model => model.LastNameCommaFirstName)
                    @Html.Partial("_SectionHelp", (string)ViewBag.HelpText)

                            @Html.LabelFor(model => model.UIC, "Transfer Record To")

                                @Html.EditorFor(model => model.UIC, "Uic", new { serviceLevel = true })

                            @Html.ValidationMessageFor(model => model.UIC)

                            @Html.LabelFor(model => model.ReasonId)
                            @Html.EnumDropDownListFor(model => model.ReasonId, new { @class = "form-control" })
                            @Html.ValidationMessageFor(model => model.ReasonId)

                            @Html.LabelFor(model => model.OtherReasonTxt)
                            @Html.TextBoxFor(model => model.OtherReasonTxt, new { @class = "form-control" })
                            @Html.ValidationMessageFor(model => model.OtherReasonTxt)

                            @Html.LabelFor(model => model.EffectiveDateString)
                            @Html.TextBoxFor(model => model.EffectiveDateString, new { @class = "form-control", @disabled = "disabled" })
                            @Html.ValidationMessageFor(model => model.EffectiveDate)

               <input type="submit" value="Submit" data-loading-text="Submitting..." class="btn btn-primary" autocomplete="off" id="submitButton" />
                <button type="button" onclick="goBack()" class="btn btn-default">Cancel</button>

}

@section scripts{

}

Controller:
[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult CreateCustodyTransfer(TransferCustodyViewModel viewModel)
    {
        string serviceCode = null;
        var result = mtfService.GetMtfId(viewModel.UIC, serviceCode, null);
        viewModel.MTFId = (long)result;

        var model = new CredCustody();
        {
            model.UIC = viewModel.UIC;
            model.ReasonId = viewModel.ReasonId;
            model.OtherReasonTxt = viewModel.OtherReasonTxt;
            model.UserMtfId = CurrentUser.PrimaryMtfId;
            model.UserText = CurrentUser.Name;
            model.CredProviderId = this.CredProvider.CredProviderId;
            model.AuditUserId = CurrentUser.UserId;
            model.MTFId = viewModel.MTFId;
        };

        long credCustodyId = this.credCustodyService.CreateCredCustody(model);
        SetPageMessage(PageMessageType.Success, String.Format("Custody Transferred"));
        return RedirectToAction("SearchResults", "ProviderSearch");
    }


text:
Q: Enviar correo Según Fecha Espero alguien pueda ayudarme, proporcionándome consejos, tips, o bien guiarme para lograr lo siguiente:
Necesito enviar un correo a la persona que creo la solicitud cuando faltan 2 semanas para que comience la fecha inicial del curso, hasta ahora solo tengo la siguiente consulta en mi base de datos pero realmente no se como lograr lo que necesito, en mi servidor ya tengo PHPMailer y envío correos en otros casos y funciona sin problemas.
SELECT dd_mm_inicio, if((dd_mm_inicio - INTERVAL 2 WEEK) = CURDATE(), "TRUE", "FALSE")
  FROM servicio where id_formulario_1=7

Cuando falten exactamente 2 semanas para la fecha de inicio se envíe correo a las 9:00 am, solo ese día.

A: puedes hacerlo asi:
SELECT * FROM servicio where (dd_mm_inicio - INTERVAL 2 WEEK) = CURDATE()

ya que lo unico que necesitas es validar que sea antes de las 2 semanas
si deseas validar otro campo bastaria con agregarselo con:
SELECT * FROM servicio where
(dd_mm_inicio - INTERVAL 2 WEEK) = CURDATE() and id_formulario_1=7

ahora para ejecutarlo solo bastaria con:
$consulta ="SELECT * FROM servicio where (dd_mm_inicio - INTERVAL 2 WEEK) = CURDATE()";

if ($resultado = $mysqli->query($consulta)) {
    while ($fila = $resultado->fetch_assoc()) {
         $mail->isHTML(true);
         $mail->Subject = 'inica el curso el dia: '.$fila["dd_mm_inicio"];
         $mail->Body    = 'incia el curso!';
         $mail->send();
         // limpiamos la direcciones si no enviara nuevamente a los anteriores
         $mail->clearAddresses();
         $mail->clearAttachments();
    }

    /* liberar el conjunto de resultados */
    $resultado->free();
}

ahora solo bastaria agregarlo a un crontab o al programador de tareas de windows
para que se ejecute 1 o 2 veces al dia.

A: Prueba la función de fecha:
<small>Este email fue enviado a: **[<?php echo date("dd/M/YY HH:i:s");]**</small>

puedes consultar los diferentes formatos en
https://www.w3schools.com/php/func_date_date.asp

A: Lo que necesitas es hacer una tarea programada que se ejecute todos los días a las 9:00am y que revise si existen en tu tabla de cursos alguno que falte 2 semanas para empezar y así notificar.
La forma mas común de hacer esto es usando crontab, te dejo un enlace con todo lo que necesitas saber para montarlo:
https://geekflare.com/es/crontab-linux-with-real-time-examples-and-tools/
Resumiendo:

*

*crontab -e

*Agregar esta linea: 0 9 * * * /scripts/job.sh <- es el script que busca los casos y envía los emails necesarios.

*crontab -l (para verificar que se ha creado)

Espero haber ayudado.
Saludos


text:
Q: Your pool's capacity exceeds your workspace's total vcore quota I work now for almost a year with Azure Synapse and from the beginning also with notebooks running on Spark pools. Only since a few months, I get this error message:
Operation on target Load Delta Lake failed: Exception: Failed to create Livy session for executing notebook. Error: Your pool's capacity (3200 vcores) exceeds your workspace's total vcore quota (50 vcores). Try reducing the pool capacity or increasing your workspace's vcore quota. HTTP status code: 400.
What's happening here?

A: So Microsoft limits the workspace's total vcores at 50. So although you have the possibility to assign up to 200 nodes, you shouldn't assign more than 11 nodes (if you have a small pool).
11 you might think? That's because a small pool has 4 vcores per node, but there's also always 1 executor overhead that's added to that total.
So, that's another term to add up to the complexity. You have a number of executors available per pool. The formula to calculate the maximum number of vcores is:
maximum_number_of_vcores = (number_of_executors + 1) * number_of_vcores_consumed_by_each
and then the number of executors:
number_of_executors = executor_per_node * number_of_nodes_configured
The variables you can play around with, are:

*

*the pool size (small, medium, large, etc)

*number of nodes

*the number of executors (only on session level).
If you like to increase the number of vcores available for your workspace pools, you can create a service request for that. I would suggest this especially for production environments.
Much of this is knowledge I have from Microsoft support requests, but also combined from logical thinking. So there can be come errors in here.


text:
Q: Setting anchor link to an address in Laravel, gives error In my Laravel application, when I am trying to link the username of the person who has posted in the website with his profile page, with the code:

@{{ post.user.name }}

It is giving the error:

Sorry, the page you are looking for could not be found.
1/1 NotFoundHttpException in RouteCollection.php line 161:

But, when I am trying to print @{{ post.user.profileUrl }} it is giving the right address, also in the json response, it is giving the right address, and going to the address is also reaching the specific location.
So, I don't think it is some problem with post.user.profileUrl, as it seems to work fine, it seems to be some problem with using it with href, the address of the error in Google Chrome is:
http://localhost:8000/%7B%7B%20post.user.profileUrl%20%7D%7D
and the address should have been
http://localhost:8000/users/2 where 2 refers to the id of the user, which I am passing to the user through Vue.js

A: The problem is @{{ post.user.profileUrl }} is not parsing. %7B%7B%20post.user.profileUrl%20%7D%7D is ASCII representation of {{ post.user.profileUrl }}
Check if the code is in .blade.php file. If it is, you should look into JS template engine if you're using any.
https://laravel.com/docs/5.3/blade#blade-and-javascript-frameworks

The @ symbol will be removed by Blade; however, {{ name }} expression will remain untouched by the Blade engine, allowing it to instead be rendered by your JavaScript framework

A: I think you have a $post model in your view. When you setup relationships between the model Post and User you can link to them through the following:
user->profileUrl) }}">@{{ $post->user->name }}

This will turn the users profileUrl into a valid link. But therefor you had to setup relationships in the Models.
Post model:
public function user() {
    return $this->hasMany('App\Users', 'id', 'user_id');
    //first parameter is the Model class
    //send is the id of the user table
    //thirth is the user_id in the post table
}

And in the User model:
public function posts() {
    return $this->hasMany('App\Posts', 'user_id', 'id');
}

Hope this works!

A: Try this... this should definitely work for you
@verbatim

      {{ post.user.name }}

@endverbatim

A: I got my problem, the issue is with the javascript library, I am using, known as vue.js, it used to allow usage inside quotes, but in vue 2, they don't, so there is a turnaround for this,
@{{ post.user.name }}

and this works fine.
Thanks to all the people who contributed by answering...


text:
Q: Traces for request not aggregated when using cloud trace with micronaut I'm trying to setup distributed tracing for my micronaut service with GCP cloud trace.
Service is written in kotlin with coroutines and micronaut version is 1.3.7.
When I make a request to my application I can see the traces in the gcp-console. But any http call made by my application to subsequent services ends up as different traces instead of spans within one trace. If I look at the trace headers I can see that it seems to switch trace id when switching threads.
How do I get micronaut to use the same trace-id across threads for the duration of a request?
Sample application:
https://github.com/bjor-joh/micronaut-distributed-tracing
This is what it looks like in GCP

The one at the top and the two to the right of that is the same request but end up as three individual traces instead of spans within the same one.


text:
Q: sql select permission with conditions Is it possible to grant select permission on sql table with some conditions.
For example grant select where table.id = < 50
supplemented: i am talking about ms sql

A: It's not possible directly.
Though to achieve this task, you can create a View initially with required conditions and then Grant select permission to that particular view.
For more details:
mysql GRANT + WHERE

A: Aer, you haven't said anything about DB engine (which one you are using: Oracle / MS SQL Server / MySQL etc.).
In Oracle for instance you are Granting / Revoking privileges to specific object, and there is no way to limit the output result (with out of the box GRANT statement).
In SQL Server you are able to grant row-level permissions for individual users with some additional effort: https://msdn.microsoft.com/en-us/library/bb669076(v=vs.110).aspx
Example:
CREATE SCHEMA Security
GO

CREATE FUNCTION Security.userAccessPredicate(@UserName sysname)
    RETURNS TABLE
    WITH SCHEMABINDING
AS
    RETURN SELECT 1 AS accessResult
    WHERE @UserName = SUSER_SNAME()
GO

CREATE SECURITY POLICY Security.userAccessPolicy
    ADD FILTER PREDICATE Security.userAccessPredicate(UserName) ON dbo.MyTable,
    ADD BLOCK PREDICATE Security.userAccessPredicate(UserName) ON dbo.MyTable
GO
    enter code here

CREATE VIEW vw_MyTable
AS
    RETURN SELECT * FROM MyTable
    WHERE UserName = SUSER_SNAME()
GO

In general from the concept perspective if you want to limit users to only certain amount of rows you should do the following:
The basic way would be :

*

*Prevent users (or group) from accessing the base table.

*Define a view on top of that table that shows only the rows these users are supposed to see.

*Give users SELECT permission on the view.


text:
Q: OpenJson in SQL server 2017 : The multi-part identifier could not be bound In the [DB_DW].[dbo].DIM_DW_MEETINGS I have a Json Column called Individuals :
[
   {
      "Activity_id":1787040082,
      "IndividualID":52528443
   },
   {
      "Activity_id":1787040082,
      "IndividualID":99312125
   }
]

I now want to execute this query in sql :
SELECT DISTINCT
    *
FROM [DB_DW].dbo.DIM_DW_FACT_ACTIVITIES Fact
INNER JOIN [DB_DW].[dbo].DIM_DW_MEETINGS dimMeetings
    ON Fact.Activity_TECH_KEY = dimMeetings.MEETING_TECH_KEY
LEFT JOIN (SELECT
        *
    FROM OPENJSON(
    (dimMeetings.Individuals)
    ) WITH (
    IndividualID INT '$.IndividualID',
    Activity_id INT '$.Activity_id'
    )) query
    ON query.Activity_id = dimMeetings.Meeting_ID

but I always have this error :

The multi-part identifier "dimMeetings.Individuals" could not be
  bound.

A: Use outer apply to the OPENJSON function
    SELECT DISTINCT
    *
    FROM DIM_DW_FACT_ACTIVITIES Fact
    INNER JOIN DIM_DW_MEETINGS dimMeetings
    ON Fact.Activity_TECH_KEY = dimMeetings.MEETING_TECH_KEY
    OUTER APPLY OPENJSON(
    (dimMeetings.Individuals)
            ) WITH (
    IndividualID INT '$.IndividualID',
    Activity_id INT '$.Activity_id'
    ) query


text:
Q: Sql Query Working in Management Studio but not in program Consider the following query.
SELECT     LP.project_id, LP.title, LP.type, LU.NAME, LP.reference, LP.status, LP.correspondence, LP.source, LP.deadline, LP.mstat, LP.num_pages, LP.done,
                      LP.ss_notes
FROM         LogiCpsProjects AS LP LEFT OUTER JOIN
                      LogiCpsProjectAssignments AS LPA ON LP.project_id = LPA.project_id LEFT OUTER JOIN
                      LogiCpsUsers AS LU ON LPA.writer_id = LU.ID
WHERE     (LP.status <> 'Closed') AND (LP.status <> 'Cancelled') AND (LP.type LIKE '%' + @type + '%') AND (LP.status LIKE '%' + @status + '%') AND
                      (LP.source LIKE '%' + @source + '%') AND (CAST(LP.mstat AS VARCHAR(50)) LIKE '%' + @mstat + '%')
ORDER BY LP.project_id

In this query I am trying to carry out a search that is based on four parameters namely @type, @status, @source and @mstat. The problem is this query works exactly as it should in Sql Server Management Studio for example if I enter 'Article' in type parameter and leave others blank then it returns all the records with type = 'Article' and if I enter type = 'Article' and status = 'Working' then it returns all records with type = 'Article' and status = 'Working' and so on... In simple words the search is dynamic as user can enter leave all parameters blank or put values in all four. It is working fine in MS but not in actual program.
I am using an SqlDataSource, with same query if I leave all parameters blank it does not return anything, if I enter 1 parameter it still does not return anything, it only return records if I enter all four parameters which means it is not working on blank parameters. To send parameters I am using four drop down lists. All of them look like this one.
        <asp:DropDownList ID="ddlStatus" runat="server" Width="220px">
<asp:ListItem Selected="True" Value="" Text="">All</asp:ListItem>
<asp:ListItem>Details Pending</asp:ListItem>
<asp:ListItem>Working</asp:ListItem>
<asp:ListItem>Awaiting Feedback</asp:ListItem>
<asp:ListItem>Project Complete (AFB)</asp:ListItem>
<asp:ListItem>Revision Required Client</asp:ListItem>
<asp:ListItem>Revision Required Editor</asp:ListItem>
<asp:ListItem>To be Cancelled</asp:ListItem>
<asp:ListItem>Cancelled</asp:ListItem>
<asp:ListItem>Requirements Not Clear</asp:ListItem>
<asp:ListItem>Hold</asp:ListItem>
<asp:ListItem>Closed</asp:ListItem>
    </asp:DropDownList>

The first item is defined as ALL and it has value and text set to "" (Empty string) so when user select ALL it means all records for that particular parameter.
What I am doing wrong ?

A: Pay attention to whether you're sending null or a blank string for all parameters.  If you run the sql statement "select '%' + null + '%'" in management studio you'll find the result is null, which is not what you're looking for.


text:
Q: SQLite calls the same INSERT command twice I was trying to insert multiple data based on two arrays. Both contains different value. And I want to insert them into one same table.
In my DBHandler I wrote INSERT statement as below
public void addData(Foto foto) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_TGL, foto.getDate());
    values.put(KEY_SITEID, foto.getSiteid());
    values.put(KEY_KATEGORI, foto.getKategori());
    values.put(KEY_FILENAME, foto.getFilename());
    values.put(KEY_PATH, foto.getPath());

    db.insert(TABLE_SHOPS, null, values);
    db.close();
}

And in my activity. I wrote like this
for(int i=0;i<=namefile.length;i++){
            Bitmap[] bitmap = new Bitmap[namefile.length];
            FileOutputStream outputStream = new FileOutputStream(String.valueOf(namefile[i]));
            bitmap[i] = BitmapFactory.decodeByteArray(decodedString[i],0,decodedString[i].length);
            bitmap[i].compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            outputStream.close();

            MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), namefile[i].getAbsolutePath(), namefile[i].getName(), namefile[i].getName());

            db.addData(new Foto(fDate,siteid,"genset_progres",namefile[i].getName(),namefile[i].getAbsolutePath()));
        }

        for(int a=0;a<=var.length;a++){
            db.addData(new Foto(fDate,siteid,"genset_progres","",var[a]));
        }

I intended to insert the data of namefile and the data of var into same table. So I wrote like above...But when I call them only namefile got inserted into database. I'm sorry I'm not quite understand about how looping and SQLITE works on android since this is my first time trying it. Maybe u guys can help me. I'd appreciate it a lot.
If there's anything I should provide...dont hesitate to ask.

A: replace
for(int i=0;i<=namefile.length;i++)

to
for(int i=0;i<namefile.length;i++)

and also
for(int a=0;a<=var.length;a++)

to
for(int a=0;a<var.length;a++)

so that you could run the code without ArrayOutOfBoundsException.


text:
Q: Call C++/CLI function with Nullable datetime paramter using Nullable datetime return from C# I have C# class (this class is hosted in a net core dll)
public class class1
{
  public DateTime? MyDateTime {get; set;}
}

Two functions in C++/CLI
public ref class class2
{
   public:
  class2(class1^ one)
  {
      _one = one;
   }
  function1(System::Nullable<System::DateTime> dateTime)
  {
  }
  function2()
  {
   function1(_one->MyDateTime);
  }
  private:
  class1 ^ _one;
}

My calling function is C# (this calling function is hosted in a .net 4.6.2 DLL)
class1 one = new class1();
class2 two = new class2(one)
two.function2();

I got an error message saying the argument list doesn't match when calling function2. The compiler complains that the type for   "one.MyDateTime" is System:Nullable while the function1 requires "System::Nullable <System::DateTime>".


text:
Q: Select or highlight data on map by click on legend Is there any way to select or highlight data on a leaflet map in by clicking on the legend in Rshiny?
example code:
library(shiny)
library(leaflet)
library(RColorBrewer)
library(leafletGeocoderRshiny)

ui <- fluidPage(
  leafletOutput("map"),
  p(),
  actionButton("recalc", "New points")
)

server <- function(input, output, session) {

  df = data.frame(x = rnorm(100), y = rexp(100, 2), z = runif(100))
  pal = colorBin('PuOr', df$z, bins = c(0, .1, .4, .9, 1))

  output$map <- renderLeaflet({ leaflet(df) %>%
    addCircleMarkers(~x, ~y, color = ~pal(z)) %>%
    addLegend(pal = pal, values = ~z)
  })

}

shinyApp(ui, server)

A: The recent updates (0.2) to the mapedit package may help: http://r-spatial.org/r/2017/06/09/mapedit_0-2-0.html

A: I got close, but ran out of time now. But i decided to share anyway, maybe someone else sees a solution to the last step.
So far it works for the first click on any of the rectangles in the legend. It doesnt work for any following clicks as the map is redrawn and with it the onclick listeners are deleted. I didnt find a way to add them again so far,...
Its a hacky aprroach: I add onclick listener to the boxes and decided to update the colors via R as i didnt see a good way in JS.
library(shiny)
library(leaflet)
library(RColorBrewer)
library(leafletGeocoderRshiny)
library(shinyjs)

colors <- c("#000000", "#222222", "#888888", "#FFFFFF")

ui <- fluidPage(
  useShinyjs(),
  leafletOutput("map"),
  p(),
  actionButton("recalc", "New points")
)

server <- function(input, output, session) {
  global <- reactiveValues(colors = colors,
                           bins = c(0, .1, .4, .9, 1))

  observe({
    print(input$interval)
    isolate({
      if(!is.null(input$interval)){
        lowerBound <- as.numeric(unlist(input$interval))
        global$colors <- colors
        global$colors[which(global$bins == lowerBound)] <- "#FF0000"
      }
    })
  })

  session$onFlushed(function() {
    runjs("
      var legendButton = document.getElementsByTagName('i')
      var elem; var interval;
      for (nr = 0; nr < legendButton.length; nr++) {
        elem = legendButton[nr]
        elem.onclick = function(e){
            console.log(e.target)
            interval = e.target.nextSibling.nodeValue.split(' ');
            Shiny.onInputChange('interval', interval[1]);
        }
      }
    ")
  })

  df = data.frame(x = rnorm(100), y = rexp(100, 2), z = runif(100))
  pal = reactive({
    colorBin(global$colors, df$z, bins = global$bins)
  })

  output$map <- renderLeaflet({ leaflet(df) %>%
      addCircleMarkers(~x, ~y, color = ~pal()(z)) %>%
      addLegend(pal = pal(), values = ~z)
  })

}

runApp(shinyApp(ui, server), launch.browser = T)


text:
Q: How to store and read an array from an INI file? How do I write an array of something into one Ident in an ini file and lately How do I read from it and store the value in an array?
This is how I'd like the ini to look like:
[TestSection]
val1 = 1,2,3,4,5,6,7

Problems I have:

*

*I don't know the functions I have to use

*The size is not static.It may be more than 7 values,it may be less.How do I check the length?

A: You do not need length specifier. The delimiter clearly delimits the parts of the array.
if you have a section in INI file defined like this
[TestSection]
val1 = 1,2,3,4,5,6,7

then all you have to do is
procedure TForm1.ReadFromIniFile;
var
  I: Integer;
  SL: TStringList;
begin
  SL := TStringList.Create;
  try
    SL.StrictDelimiter := True;
    SL.CommaText := FINiFile.ReadString('TestSection', 'Val1', '');
    SetLength(MyArray, SL.Count);

    for I := 0 to SL.Count - 1 do
      MyArray[I] := StrToInt(Trim(SL[I]))
  finally
    SL.Free;
  end;
end;

procedure TForm1.WriteToIniFile;
var
  I: Integer;
  SL: TStringList;
begin
  SL := TStringList.Create;
  try
    SL.StrictDelimiter := True;

    for I := 0 to Length(MyArray) - 1 do
      SL.Add(IntToStr(MyArray[I]));

    FINiFile.WriteString('TestSection', 'Val1', SL.CommaText);
  finally
    SL.Free;
  end;
end;

A: You can do it like this,
uses inifiles

procedure ReadINIfile
var
  IniFile : TIniFile;
  MyList:TStringList;
begin
    MyList  := TStringList.Create();
    try
        MyList.Add(IntToStr(1));
        MyList.Add(IntToStr(2));
        MyList.Add(IntToStr(3));

        IniFile := TIniFile.Create(ChangeFileExt(Application.ExeName,'.ini'));
        try
            //write to the file
            IniFile.WriteString('TestSection','Val1',MyList.commaText);

            //read from the file
            MyList.commaText  := IniFile.ReadString('TestSection','Val1','');

            //show results
            showMessage('Found ' + intToStr(MyList.count) + ' items '
                            + MyList.commaText);
        finally
            IniFile.Free;
        end;
    finally
        FreeAndNil(MyList);
   end;

end;

You will have to save and load the integers as a CSV string as there is no built in function to save arrays direct to ini files.


text:
Q: imagick multiple pdfs to jpg with php I need to convert all PDFs file of a directory into jpgs.
Like:
1.pdf
2.pdf
3.pdf
into
1.jpg
2.jpg
3.jpg
With this script I can find all PDFs.
$dir_name = "";
$pdfs = glob($dir_name."*.pdf");
foreach($pdfs as $pdf) {
   echo $pdf;
}

But how can I convert multiple files?
$imagick = new Imagick();
$imagick->setResolution(300, 300);
$imagick->readImage('???');
$imagick->writeImages('???', false);


text:
Q: What is the meaning of "[*.]" in the Chrome cookie exceptions dialog?
Screenshot of the add-to-cookie-whitelist pop up (chrome://settings/cookies?search=cookies)
I am always entering the metacharacters [*.] here, what is their meaning? Do i correctly guess that [] means zero or one, * means one or more letters from "a" to "z", and . means the literal "."?
(some 300+ points owner: would you be so kind to append metacharacter to the tags of this question and then delete this paragraph?)

A: Although you're mostly correct about * and . on their own (but note that domain names are not limited to just letters a-z), this doesn't quite apply to the [ ] part.
The pattern is meant to look like "zero or one", as in the common convention of using […] to mark something as "optional". However, within Chrome, only the exact string [*.] is recognized by the pattern parser, and only if it's located at the beginning of the "host" part. The brackets have no meaning in any other case; e.g. [abc.]def will not be recognized.
If the prefix [*.] is present at the beginning of the "host" part of the URL, the pattern will match both the specified domain and its subdomains. In other words, it's as if you had the two patterns:
example.com
*.example.com


text:
Q: doxyrest command returns "duplicate member id group..." I'm generating documentation for my code using doxygen, doxyrest and sphinx-build commands.
No warnings while using doxygen Doxyfile, but when I type in doxyrest -c doxyrest-config.lua to generate rst, based on the xml made by Doxygen, my screen gets full of errors like this one:

warning: duplicate member id group___my_example_group_commands_1gaaa56d9b... (function: ExampleFunction)

I'm using \addtogroup to group more functions at a time, like this:
/** \addtogroup MyGroup
* @{ */

   /** \addtogroup SomeSubgroup
   * @{ */

      void someFunctionHere(int param1, int param2, ...) {
         ... // some stuff here
      }

      void someOtherFunction(char *param1, ...) {
         ... // some other stuff here
      }

   /** @} */

/** @} */

My question is: where does that duplicate member id ... error come from? Do you have any idea?
Thank you.


text:
Q: clojure rest and next related I was following The Joy of Clojure and I am puzzled with these 2 statements
(def very-lazy (-> (iterate #(do (print \.) (inc %)) 1) rest rest rest))

(def less-lazy (-> (iterate #(do (print \.) (inc %)) 1) next next next))

accordingly, the output was
(println (first very-lazy)) ; .4

(println (first less-lazy)) ; 4

The book continued to explain that

Grabbing the first element in a lazy seq built with rest causes a
  realization as expected. But the same doesn't happen for a seq built
  with next because it's already been previously realized. Using next
  causes a lazy seq to be one element less lazy, which might not be
  desired if the cost of realization is expensive.

My burning question is why there is an extra dot for 'very-lazy'? My thought was 'print' would print its argument when invoked regardless if next or rest.
Thanks

A: Print actually did exactly the same thing in both cases, it printed only the number. The extra . was printed by the code inside the list, it just happened to occur at the same time as the printing of the 4 and so it ended up next to it on the screen.
the extra dot is a side effect of the lazy sequence being created on the fly. I would propose a more verbose example to clarify this:
start with two identical lists, both fully-lazy:
esc.core=> (def a (iterate #(do (print "making new element") (inc %)) 1))
#'esc.core/a
esc.core=> (def b (iterate #(do (print "making new element") (inc %)) 1))
#'esc.core/b

then make two more identical lists that start on the fourth element of a and b respectively
esc.core=> (def a-partially-realized (-> a rest rest rest))
making new elementmaking new element#'esc.core/a-partially-realised
esc.core=> (def b-more-fully-realized (-> b next next next))
making new elementmaking new elementmaking new element#'esc.core/b-more-fully-realised
esc.core=>

the first three elements of a-partially-realized have been pre-computed
while the first four elements of b-more-fully-realized have been pre-computed.
when we read the first element (the fourth in the original list) of a-partially-realized it has not yet been computed so we will see it being computed.
esc.core=> (print (first a-partially-realized))
making new element4nil

when we do the same to b-more-fully-realised it will already have the value cached so we just get the result immediately.
esc.core=> (print (first b-more-fully-realized))
4nil

A: You're missing something important. Count the dots:
user> (def very-lazy (-> (iterate #(do (print \.) (inc %)) 1) rest rest rest))
..#'user/very-lazy

user> (def less-lazy (-> (iterate #(do (print \.) (inc %)) 1) next next next))
...#'user/less-lazy

It always helps to run the code for real instead of just reading a book.

A: As Joost points out, the magic happens when you define very-lazy and less-lazy.
The point is, rest just has to return a sequence.  That sequence is lazy.  Therefore, (-> x rest rest rest) needs to process two values of x and then return the lazy sequence.  Hence, two dots.
next, on the other hand, has to return nil if there are no more elements in the sequence, so it's got to evaluate x a third time to determine whether or not the sequence was empty.  So three dots.
When you actually ask for the value, any remaining laziness needs to be discarded.  So, you get one more dot for rest.  The next version is done, so no more dots.

A: What is unanswered so far is why next is more eager than rest which is at the heart of the difference you describe. next returns nil for any list less than 2 in length. In contrast, rest returns the empty list in these scenarios. This suggest that when calling next on a list of 1 element we are implicitly done handling our sequence (in recursion for example) and thus we can safely assume it is time to realize the first element. That accounts for the early versus late realization of the final dot.

A: next executes the #() function as soon as it is called, whereas rest does not because it does not have to yet - it waits as long as possible - so no realization/execution occurs in this example until another rest is called, or the value needs to be returned, which is the case when printing.
I too missed the dots on first reading. Only two dots for rest because there hasn't been a good enough reason (yet) for the last rest to be realized.


text:
Q: WebComponents: how to get the resolved value of a slot in shadow DOM? I have a web component and I want to adjust the value of its slot.
Unfortunately, I am unable to get the resolved value from it.
How can I do that?

const template = document.createElement('template');
template.innerHTML = `

<slot></slot>

`;

class MyComp extends HTMLElement {
    constructor() {
        super();
        this.root = this.attachShadow({mode: 'open'});
        this.root.appendChild(template.content.cloneNode(true));
    }

    connectedCallback() {
        const slot = this.shadowRoot.querySelector('slot');
        console.log('VALUE:', slot.innerText);  // always empty
    }
}

customElements.define('my-comp', MyComp);
<my-comp>abc</my-comp>

A: You can assign an EventListener to watch for SLOT changes
MDN Documentation

*

*slotchange event

*assignedNodes

*::slotted

*How do I style the last slotted element in a web component

customElements.define('my-element', class extends HTMLElement {
    constructor() {
      super();
      this.attachShadow({
        mode: 'open'
      }).appendChild(document.getElementById(this.nodeName).content.cloneNode(true));
    }

    connectedCallback() {
      this.listeners = [...this.shadowRoot.querySelectorAll("SLOT")].map(slot => {
        let name = "slotchange";
        let func = (evt) => {
          let nodes = slot.assignedNodes();
          console.log(`Slot ${slot.name} changed to ${nodes[0].outerHTML}`)
        }
        slot.addEventListener(name, func);
        return () => slot.removeEventListener(name, func); // return cleanup function!!!
      })
    }
    disconnectedCallback() {
      this.listeners.forEach(removeFunc => removeFunc());
    }
  });
<template id="MY-ELEMENT">

    <slot name=title></slot>

  <slot name=content></slot>
</template>

<my-element>
  Hello World

What a wonderful day!

</my-element>
<my-element>
  Hello Tomorrow

What will you bring?

</my-element>

A: Less code, easier to understand. For simple templates I'd rather create the elements programmatically, then add a slotchange listener:

class MyComp extends HTMLElement {
    p = document.createElement('p');
    slot = document.createElement('slot');

    constructor() {
        super();
        this.p.append(this.slot);
        this.attachShadow({mode: 'open'}).append(this.p);
        this.slot.addEventListener('slotchange', () => console.log('VALUE:', this.slottedValue))
    }

    get slottedValue() { return this.slot.assignedNodes()[0].wholeText }
}

customElements.define('my-comp', MyComp);

console.log(document.querySelector('my-comp').slottedValue);
<my-comp>abc</my-comp>


text:
Q: Using class method as callback wtih addEventListener fails after 1 event fire I am trying to create my own product card carousel.
Using JavaScript to enhance scrolling from the user.
I created the class for the slider, and inside the class I set up a bunch of addEventListeners on the slider.
Ever since I moved the code to a class, the mousedown, mouseup and mousemove event only seem to fire once.
After they fire, the next even causes a ...
Uncaught TypeError: this.mouseDown is not a function

On line
// Mouse drag
this.slides.addEventListener("mousedown", (e) => { this.mouseDown(e); }, false);

I've tried doing the whole
let self = this;
this.slides.addEventListener("mousedown", self.mouseDown, false);

Which did not work either.
When I console.log here:
this.slides.addEventListener("mousedown", (e) => { console.log(this); this.mouseDown(e); }, false);

The this reference looks correct.

How can I correctly bind these listeners to methods in the object they were declared in, correctly?
Relevant code below...
class Slider {
    id = "";
    slides = null;

    posRefx = 0;
    posRefy = 0;
    mousedown = false;

    constructor(sliderID) {
        this.id = sliderID;
    }

    init() {
        this.slides = document.getElementById(this.id).getElementsByClassName('slides')[0];

        this.slides.style.cursor = 'grab';

        if (this.slides.addEventListener) {
            // IE9, Chrome, Safari, Opera
            this.slides.addEventListener("mousewheel", (e) => { this.onMouseMove(e); }, false);

            // Firefox
            this.slides.addEventListener("DOMMouseScroll", (e) => { this.onMouseMove(e); }, false);

            // Touch devices
            this.slides.addEventListener("touchstart", (e) => { this.touchStart(e); }, false);
            this.slides.addEventListener("touchmove", (e) => { this.touchMove(e); }, false);

            // Mouse drag
            this.slides.addEventListener("mousedown", (e) => { this.mouseDown(e); }, false);
            this.slides.addEventListener("mouseup", (e) => { this.mouseUp(e); }, false);
            this.slides.addEventListener("mousemove", (e) => { this.mouseMove(e); }, false);
        }

    mouseDown(event) {
        ...
    }

    mouseUp(event) {
        ...
    }

    mouseMove(event) {
        ...
    }
}

var mySlider = new Slider("my-slider-id");
jQuery(document).ready(function() {
    mySlider.init();
});