Q: Cloud callout with large aspect ratio I'm trying to use a cloud callout to remember people in a beamer presentation on a previous equation. Since the equation is long, I have to use a large aspect ratio for the callout, which results in a strange shape. Is there a way to change the shape of the cloud callout apart from changing the aspect ratio (i.e. changing height and width separately?).
Here is a MWE:
\documentclass[8pt]{beamer}
\usepackage[utf8]{inputenc}
\usepackage[OT1]{fontenc}
\usepackage[USenglish]{babel}
\usepackage{amsmath,amsthm,amssymb}
\usepackage{tikz}
\usetikzlibrary{shapes.callouts,tikzmark}

\begin{document}
\begin{frame}
Frame with some text, some items and a long formula, part of which should remind people on a previous formula
\begin{itemize}
\item first item
\item second item
\item third item
\item fourth item
\item fifth item
\item sixth item
\end{itemize}

\begin{equation}
\begin{split}
\dot{f}(x,y)=&a \sin(x) \frac{\partial f(x,y)}{\partial y}-\left(2xy+b+\frac{y}{\sqrt{x^2-y^2}}\cos(y)\right) \frac{\partial{f}(x,y)}{\partial y} +x^3-y^2\\
&\alert{-\frac{y}{2}\left(y-\frac{x^2}{y^2}\right)\frac{\partial^2{f}(x,y)}{\partial x \partial y}}
\end{split} \nonumber
\end{equation}
\pause
\begin{tikzpicture}[overlay,remember picture]
\pgftransformshift{\pgfpointanchor{current page}{center}}
\node[cloud callout,draw,thick,fill=cyan,cloud puffs=50,cloud puff arc=100,callout relative pointer=(270:2cm),align=center,anchor=center,aspect=8] at (0,3) {$\dot g(x,y)=a \sin(x) \frac{\partial g(x,y)}{\partial y}-\left(2xy+b+\frac{y}{\sqrt{x^2-y^2}}\cos(y)\right) \frac{\partial{g}(x,y)}{\partial y} +x^3-y^2$};
\end{tikzpicture}
\end{frame}
\end{document}

As you can see the cloud is larger than the frame, even though the equation fits into the frame. Can I make the left and right sides of the cloud callout somehow steeper? Would it also be possible to make the two little ellipses (the pointer?) more round?
Edit: my goal would be like this:

A: Like this?

\documentclass[8pt]{beamer}
\usepackage[utf8]{inputenc}
\usepackage[OT1]{fontenc}
\usepackage[USenglish]{babel}
\usepackage{amsmath,amsthm,amssymb}
\usepackage{tikz}
\usetikzlibrary{shapes.callouts,tikzmark}

\begin{document}
\begin{frame}
\frametitle{Title}
Frame with some text, some items and a long formula, part of which should remind people on a previous formula
\begin{itemize}
\item first item
\item second item
\item third item
\item fourth item
\item fifth item
\item sixth item
\end{itemize}

\begin{equation}
\begin{split}
\dot{f}(x,y)& = a \sin(x)
                \frac{\partial f(x,y)}
                     {\partial y} -
                \left(2xy+b+\frac{y}{\sqrt{x^2-y^2}}\cos(y)\right)
                \frac{\partial{f}(x,y)}
                     {\partial y} +x^3-y^2  \\
            &\qquad \alert{-\frac{y}{2}
                    \left(y-\frac{x^2}{y^2}\right)
                    \frac{\partial^2{f}(x,y)}
                         {\partial x \partial y}}
\end{split} \nonumber
\end{equation}
\pause
\begin{tikzpicture}[overlay,remember picture]
\pgftransformshift{\pgfpointanchor{current page}{center}}
\node[cloud callout,cloud puffs=50,cloud puff arc=100,
      callout relative pointer=(240:3cm),
      callout pointer segments=3, % added
      draw,thick, fill=cyan,
      %fill opacity=0.9, text opacity=1, % if you like to see background text
      align=center, anchor=center,
      aspect=7, % changed
      inner xsep=-4em % <--- negative inner ysep
      ] at (1,3) {$\dot g(x,y)=a \sin(x) \frac{\partial g(x,y)}{\partial y}-\left(2xy+b+\frac{y}{\sqrt{x^2-y^2}}\cos(y)\right) \frac{\partial{g}(x,y)}{\partial y} +x^3-y^2$};
\end{tikzpicture}
\end{frame}
\end{document}


Q: PowerShell executing exe with arguments I wrote a PowerShell script to execute exe with arguments which has spaces but it keeps failing, not reading the full path.
$now     = Get-Date -format "MM_dd_yyyy"
$onepath ="C:\Program Files (x86)\GoFileRoom\IWMUploadDocuments\logs\"
$scpath  = "F:\Program Files\NSClient++\scripts\"
$onefile = "IWMUploadDocumentsLog$now.txt"
$script  = "check_log3.exe"

& "$scpath$script" -p "Error Logging into GFR" -l "$onepath$onefile" -c 1
Write-Output "$onepath$onefile"

Here is the output:

PS C:\Windows\system32> F:\Program Files\NSClient++\scripts\onesource.ps1
    Cannot read 'C:\Program'
    C:\Program Files (x86)\GoFileRoom\IWMUploadDocuments\logs\IWMUploadDocumentsLog10_22_2018.txt

A: Looks to me like you need an additional set of quotes around the argument for the parameter -l:
& "$scpath$script" -p "Error Logging into GFR" -l "`"$onepath$onefile`"" -c 1

Or try splatting the arguments:
$params = '-p', 'Error Logging into GFR',
          '-l', "$onepath$onefile",
          '-c', 1

& "$scpath$script" @params


Q: CSS displaying elements when thumbnails are hovered over i am attempting to display images when the corresponding thumbnail is hover over using only css and am having trouble with the logic and don't know if it is even possible. i can do it in javascript if absolutely necessary.
Here is my latest attempt.

And the CSS
#img-container{
    position:relative;
    top:0px;
    left:0px;
    height:950px;
}
.slide-images{
    position:absolute;
    top:0px;
    left:0px;
 }
 .thumbnail > img{
    margin-left:auto;
    margin-right:auto;
    display: inherit;
}
img#thumb4:hover ~ #img4>#image4{
    display:none;
}

A: I believe this is possible using CSS alone, however it is not very scaleable and it might end up being easier and more appropriate to use Javascript for this. For example:
img#thumb1:hover ~ #img4>#image4{
    display:none;
}

Your selector here is incorrect. The general sibling selector selects only elements after the first match. In this case, your image thumb is after your image, but this selector is looking for an image after an image thumb. This is the opposite of what you have. There is no 'sibling before' selector in CSS.
An easier solution, rather than fiddling around with CSS selectors, would just be to bind each thumbnail to a click event that changes the source of a single image tag each time (or alternatively, scrolls across/fades, whatever animation you're looking for). This way, you save on markup, don't need to worry about positioning as much, and can dynamically generate the image display.
For example, to get the ID of an image, you could bind a click event to each thumbnail and then grab the ID of the image which could stored in a data attribute:
$('.thumbnail').on('hover', function() {
    var activeImg = $(this).data('imgid');
    // From here, set the main image to have the associated image source
}

A: This is very possible to achieve with just CSS. The layout of your HTML is what needs to change. In this example:

*

*Each thumbnail and full-size image is placed inside a div container

*The full-size image is hidden with opacity: 0;

*When the div container is hovered, the full-size image is given opacity: 1 and will fade-in thanks to the transition

*z-index: 1 keeps the full-size images above the thumbnails
Full Example

.item {
  float: left;
  position: relative;
}
img {
  display: block;
  cursor: pointer;
  margin: 5px;
}
.fullsize {
  position: absolute;
  opacity: 0;
  transition: opacity 0.6s;
  z-index: 1;
  top: 0;
  left: 0;
  pointer-events: none;
}
.item:hover .fullsize {
  opacity: 1;
}


Q: Linux boot fails after install I got an hp pavilion 15 e070sl laptop, bought a week ago and i wanted to install ubuntu alongside windows, (then the installer erased the whole HDD for a bug, but that's another story)
The fact is, once disabled fastboot/secureboot/everything needed i installed ubuntu linux with 13.04, allok but wifi wasn't working.
I switched to a newer version:13.10, during the install process wifi is detected and worked good.
But boot didn't work(Freeze on Gnome logo), using livecd in try mode also didn't work.
How to get errors prompted so i can understand what's not working?
Somebody else had the same problem?


Q: Apply type projection to a refined type Consider the following example:
trait T3

trait T2{
  type TT4
  type TT3 <: T3
}

trait T1{
  type TT2 <: T2
}

now I want to write a function the roughly speaking looks as
def test[T <: T1](t: T#TT2{type TT4 = Int}#TT3) = println(t)  //invalid syntax

which unfortunately is not a valid syntax. It is perfectly possible to write a function like this
def test[T <: T1](t: T#TT2#TT3) = println(t)

But I'd like to add a bit stricter restriction on T#TT2 making it to be a refined type T#TT2{ type TT4 = Int}.
Is there any workaround?

A: Try wrapping type T#TT2 { type TT4 = Int } in parenthesis before the final projection like so
def test[T <: T1](t: (T#TT2 { type TT4 = Int })#TT3) = ???

Types can always be wrapped in parentheses
SimpleType        ::=  SimpleType TypeArgs
                      |  SimpleType ‘#’ id
                      |  StableId
                      |  Path ‘.’ ‘type’
                      |  Literal
                      |  ‘(’ Types ‘)’      <======= note the parentheses

for example
scala> val xs: (List[(Int)]) = List(42)
val xs: List[Int] = List(42)


Q: How to add a folder Jetty will run a site from? I have Jetty running on an Oracle VBox VM (Win7) Guest. I need Jetty to run a site from a shared folder, so I can edit it on the host. How can I do that?
Edit: The site is HTML/JS, not a war file. I see from the docs I can copy a war to $JETTY_HOME. What I'm wondering is if I can add a path to $JETTY_HOME for Jetty to look in?
The path is \\VBOXSVR\MyCoolSite


Q: ¿Cómo poder seguir con la musica si cierro app y no al cambiar de Activity? Me explico... he leído mucho sobre esto pero no consigo entender ni tener el código sobre cómo hacer que mi aplicación tenga una cancion todo el rato y cuando pulse el "Home button" se me vaya la cancion y no siga la app ni muestre nada, es decir, yo pongo una cancion y que mientras esté dentro suene al cambiar de Activity y si salgo de la app, sea en la activity que sea, se me salga sin sonar nada.
He conseguido hacer mediante :
public class MainActivity extends Activity {

    public MediaPlayer mp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_activity2);

        mp = MediaPlayer.create(MainActivity.this,R.raw.musica);
        mp.start();
    }

     public void onStop()
     {
        super.onStop();
       if(mp.isPlaying())
         mp.stop();
       else
       return;
     y también:
 o ...

     public void onFinish()
     {
        mp.stop();
        finish();
}

Pero SIEMPRE SIEMPRE consigo o que: al salir de la app se me vaya el sonido  ( que es lo que busco muy bien pero TAMBIÉN SE ME VA EL SONIDO AL CAMBIAR DE ACTIVITY) pues android creo que no diferencia entre home button y pasar de activity entonces me lleva loco... he leido mucho en inglés sobre esto y nada.. Necesito ,resumiendo, una ayuda sobre como hacer que si tengo 5 activitys y voy cambiando entre ellas esté 1 misma cancion y que al cerrar la App se me vaya el sonido y todo.

A: Te sugiero revises primeramente el ciclo de vida de la Activity

https://developer.android.com/training/basics/activity-lifecycle/stopping.html
Puedes notar que cuando abres otra Activity, se ejecuta onPause() y posteriormente onStop().
Por lo tanto el problema es que al ejecutarse el metodo onStop() estas deteniendo la reproduccion, te recomiendo eliminarlo si es que deseas que al cambiar de Activity, continue la reproduccion.
public void onStop()
 {
    super.onStop();
   if(mp.isPlaying()) //Si se esta reproduciendo.
     mp.stop();  //Detiene la reproduccion.
   else
   return;
}

En cuanto al metodo onFinish() este es llamado cuando ejecutas finish() deseando cerrar la Activity y la reproduccion en el MedioPlayer se detiene.
 public void onFinish()
 {
    mp.stop(); //Detiene la reproduccion.
    finish();
}


Q: VBA for altering PowerPoint 2003 Presentations- Active not new If I set up a template on PowerPoint slides, that contain all the text boxes I need, the what Visual Basic do I use to enter text that I want into those text boxes?
It is easier for me to use a template, because these ppt briefs contain (or need to contain) a lot of data:

*

*how do I enter text into those text boxes

*how do you alter the font, size, fontbold, etc of a particular text box?

*is there a way for determining the "name" of a text box/shape ("text box 52") other than recording macros after macros and selecting the text box, just to get the object name from selection?

*if I use a macro to determine the vba, why will it not work to use that as vba? the vb I get from a macro seems to have active.selection which just doesn't seem to work as a vba procedure because it doesn't know what to select???? i think

what i am looking to do is create the end game ppt from access, using the template. on an access form I want to have multiple text boxes that relay the information into the ppt text boxes on the slide.
i know how to launch a template (or new presentation) from access, and how to add new items (slides, graphs, charts, text) but I do not know how to alter pre-existing text boxes!!
Please help....my work is needing this like yesterday!
Thanks as always!

A: You can access shapes by name, as in:
Dim oSlide As Slide
Set oSlide = ActivePresentation.Slides(1)

Dim oShape As Shape
Set oShape = oSlide.Shapes(strShapeName)

Dim oTextRange As TextRange
Set oTextRange = oShape.TextFrame.TextRange

oTextRange.Text = "this is some text"

oTextRange.Font.Bold = msoTrue

Note that whatever you're looking to do, just record a macro of you doing it via the UI, and copy that. You're right that the recorded macro will use the Selection object a lot, but that's easily fixed - just get a reference to the appropriate Shape object (or whatever) and then subsitute that in the generated code.
So, for example, if the recorded macro for changing the fill color of a shape is this:
With ActiveWindow.Selection.ShapeRange
    .Fill.Visible = msoTrue
    .Fill.Solid
    .Fill.ForeColor.RGB = RGB(255, 0, 0)
    .Fill.Transparency = 0#
End With

... and you want to apply the fill color to a shape which you already have a reference to as oShape, then change the code to this:
With oShape
    .Fill.Visible = msoTrue
    .Fill.Solid
    .Fill.ForeColor.RGB = RGB(255, 0, 0)
    .Fill.Transparency = 0#
End With

To get the current name of a shape, you can enter this in the "immediate" window in the VBA editor:
?ActiveWindow.Selection.ShapeRange(1).Name

You could turn that into a (single) macro very easily:
Sub ShowMeTheName()
    MsgBox ActiveWindow.Selection.ShapeRange(1).Name
End Sub

Note that I would personally rename the shapes to something meaningful rather than using the default names. Simply turn do this in the immediate window:
ActiveWindow.Selection.ShapeRange(1).Name = "MyName"

...or create a macro to prompt for a name.

A: When I need to automate Word or Excel (nobody I know or work with has any use for PowerPoint), I open the app in question, turn on Macro recording and do the task I want to automate. Then I use the generated code as the basis for my Access code. It's often a pretty straightforward process, sometimes as simple as copying and pasting and then prefacing each line with the application object I'm using from Access.
If I had to do what you're doing, that's exactly how I'd start, by doing recording the task being performed interactively, and then experimenting with what part of the code is essential.


Q: How to compound a series of consequential subscriptions in RxJS I have approach according to the below.
this.service1.info
  .subscribe(a => this.service2.getDetails(a.id)
    .subscribe(b => {
      this.doStuff(b);
    })
  );

Recently, I noticed that we're going to have quite a few steps that gradually push more details to the client, so I'm anticipating the following atrocious pattern emerge.
this.service1.info
  .subscribe(a => this.service2.getDetails(a.id)
    ...
            .subscribe(z => {
              this.doStuff (z);
            })
  );

Is there a nice trick in RxJS to handle such situations? I only need to perform an operation once all the steps in the consequential chain have been emitted/received. I've browsed through the docs but didn't find something that felt quite right. I suspect that it's there, just that my ignorance confuses me so I'm missing it.

A: Yes, you are right. It is indeed an anti-pattern within RxJS to chain multiple subscribes.
A more elegant way of chaining these observable calls would be to make use of pipeable operators. In this scenario, the switchMap() operator would suffice.
As stated on the documentation, switchMap() will

Map to observable, complete previous inner observable, emit values.

this.service1.info
  .pipe(
    switchMap((a) => this.service2.getDetails(a.id)),
    switchMap((a) => this.service3.getDetails(a.id)),
    // switchMap((a) => this.service4.getDetails(a.id)),
    // subsequent chained methods
  ).subscribe(z => {
    // handle the rest when observables are returned
    this.doStuff(z);
  });

As you can see from the above pipe statement, we only call subscribe() once, and that will return the observable values. That is when we call the doStuff method.


Q: TransactionScope not rolling back although no complete() is called I'm using TransactionScope to rollback a transaction that fail
bool errorReported = false;
Action<ImportErrorLog> newErrorCallback = e =>
{
    errorReported = true;
    errorCallback(e);
};

using (var transaction = new TransactionScope())
{
    foreach (ImportTaskDefinition task in taskDefinition)
    {
        loader.Load(streamFile, newErrorCallback, task.DestinationTable, ProcessingTaskId);
    }
    if (!errorReported)
        transaction.Complete();
}

I'm sure there is no TransactionScope started ahead or after this code.
I'm using entity framework to insert in my DB.
Regardless the state of errorReported the transaction is never rolled back in case of error.
What am I missing ?

A: TransactionScope sets Transaction.Current. That's all it does. Anything that wants to be transacted must look at that property.
I believe EF does so each time the connection is opened for any reason. Probably, your connection is already open when the scope is installed.
Open the connection inside of the scope or enlist manually.
EF has another nasty "design decision": By default it opens a new connection for each query. That causes distributed transactions in a non-deterministic way. Be sure to avoid that.


Q: multiple pages are overlapping in ngx-extended-pdf-viewer I am using ngx-extended-pdf-viewer for my angular app and looks like multiple pdf pages are overlapping during viewing. here is my viewer code
<ngx-extended-pdf-viewer
        *ngIf="isVisible"
        [src]="pdfData"
        useBrowserLocale="true"
        [textLayer]="true"
        [showPrintButton]="true"
        [showDownloadButton]="true"
        [showOpenFileButton]="false"
        [showBookmarkButton]="false"
        [showPresentationModeButton]="false"
        height='90%'
        [zoom]="'100%'">
</ngx-extended-pdf-viewer>

I tried setting stylesheets for page and viewer classes but no luck.

A: Sounds like you've got CSS rules interfering with the CSS rule of ngx-extended-pdf-viewer. Create a greenfield project to check if it's a general problem:

*

*Open a terminal and navigate to the root folder of your project.

*Run this command and accept the defaults:

ng add ngx-extended-pdf-viewer

*Add the new component <app-example-pdf-viewer> to your <app-component> to display the PDF file.

Now you've got a working project that almost certainly does not suffer from your bug. Use the developer tools of your browser to compare the CSS code of the two projects to hunt down the bug.


Q: no sound in a push notification on Android(Ionic capacitor) I have a problem when i implemented a plugin PushNotification in capacitor, the problem is that when te phone receive a push notification don´t make any sound.
This is my code.
PushNotifications.addListener('pushNotificationReceived',
  (notification: PushNotification) => {
    console.log('Push received: ',JSON.stringify(notification));

  }

this is the settings in capacitor.config.json
"PushNotifications": {
  "presentationOptions": ["badge", "sound", "alert"]
}

thanks for your help.

A: show me the created the Notification channel Details.  Then don't test in Redmi or mi Phones.
addListenersForNotifications = async () => {
   await PushNotifications.addListener('registration', 'registration Name');
await PushNotifications.addListener('registrationError', 'error');
await PushNotifications.createChannel({
  id: 'fcm_default_channel',
  name: 'app name',
  description: 'Show the notification if the app is open on your device',
  importance: 5,
  visibility: 1,
  lights: true,
  vibration: true,
});
await PushNotifications.addListener('pushNotificationReceived', this.pushNotificationReceived);
await PushNotifications.addListener('pushNotificationActionPerformed', this.pushNotificationActionPerformed);

};


Q: Pandas Regression Model Replacing Column Values I have a data frame "df" with columns "bedrooms", "bathrooms", "sqft_living", and "sqft_lot".

I want to create a regression model by filling the missing column values based on the values of the other columns. The missing value would be determined by observing the other columns and making a prediction based on the other column values.
As an example, the sqft_living column is missing in row 12. To determine this, the count for the bedrooms, bathrooms, and sqft_lot would be considered to make a prediction on the missing value.
Is there any way to do this? Any help is appreciated. Thanks!

A: import pandas as pd
from sklearn.linear_model import LinearRegression

# setup
dictionary = {'bedrooms': [3,3,2,4,3,4,3,3,3,3,3,2,3,3],
              'bathrooms': [1,2.25,1,3,2,4.5,2.25,1.5,1,2.5,2.5,1,1,1.75],
              'sqft_living': [1180, 2570,770,1960,1680,5420,1715,1060,1780,1890,'',1160,'',1370],
              'sqft_lot': [5650,7242,10000,5000,8080,101930,6819,9711,7470,6560,9796,6000,19901,9680]}
df = pd.DataFrame(dictionary)

# setup x and y for training
# drop data with empty row
clean_df = df[df['sqft_living'] != '']
# separate variables into my x and y
x = clean_df.iloc[:, [0,1,3]].values
y = clean_df['sqft_living'].values

# fit my model
lm = LinearRegression()
lm.fit(x, y)

# get the rows I am trying to do my prediction on
predict_x = df[df['sqft_living'] == ''].iloc[:, [0,1,3]].values

# perform my prediction
lm.predict(predict_x)
# I get values 1964.983 for row 10, and 1567.068 row row 12

It should be noted that you're asking about imputation. I suggest reading and understanding other methods, trade offs, and when to do it.
Edit: Putting Code back into DataFrame:
# Get index of missing data
missing_index = df[df['sqft_living'] == ''].index
# Replace
df.loc[missing_index, 'sqft_living'] = lm.predict(predict_x)


Q: How to interpret low R^2 value when we have the whole population I am predicting the performance in a subject given the percentage of a gender that is in a group, for example, a group might be 70% female and 30% male. There is a significant relationship (p < 0.01) between more females and worse performance for this particular subject, but the R^2 value is very low (0.01, i.e. % of females in the class explains 1% of the variance).
I have the whole population for this dataset, does this make a difference when interpreting R^2? Should I still report these figures?

Putting this into a graph looks impressive and makes me think I should be reporting it, as -1 grade is a substantial difference here.

A: If you have the whole population, the use of P-values and CIs is questionable because these are used for inference and estimation, but you don't need to do those things if you have the population. R-squared would have it's usual interpretation as far as I am aware (percentage of variation in the DV explained by the multiple regression model with x1, x2,...xn).


Q: Replace all characters in a regex match with the same character in Vim I have a regex to replace a certain pattern with a certain string, where the string is built dynamically by repeating a certain character as many times as there are characters in the match.
For example, say I have the following substitution command:
%s/hello/-----/g

However, I would like to do something like this instead:
%s/hello/-{5}/g

where the non-existing notation -{5} would stand for the dash character repeated five times.
Is there a way to do this?
Ultimately, I'd like to achieve something like this:
%s/(hello)*/-{\=strlen(\0)}/g

which would replace any instance of a string of only hellos with the string consisting of the dash character repeated the number of times equal to the length of the matched string.

A: As an alternative to using the :substitute command (the usage of
which is already covered in @Peter’s answer), I can suggest automating
the editing commands for performing the replacement by means of
a self-referring macro.
A straightforward way of overwriting occurrences of the search pattern
with a certain character by hand would the following sequence of
Normal-mode commands.

*

*Search for the start of the next occurrence.
/\(hello\)\+

*Select matching text till the end.
v//e

*Replace selected text.
r-

*Repeat from step 1.
Thus, to automate this routine, one can run the command
:let[@/,@s]=['\(hello\)\+',"//\rv//e\rr-@s"]

and execute the contents of that s register starting from the
beginning of the buffer (or anther appropriate location) by
gg@s

A: %s/\v(hello)*/\=repeat('-',strlen(submatch(0)))/g


Q: Create menu in main layout like in action bar I want to know is it possible to create menu like this?

A: Most likely, your screenshot is of an ExpandableListView, or possibly a RecyclerView that uses a library to add expandable contents.

A: Yes, and it's called Expandable List View.


Q: Не получается из метода сделать Task Есть метод он  получает данные из базы, сохраняет их в Datatable и еще я через linq делаю отбор нужного мне количества строк.
Но  возникает ошибка, делать еще один метод как о не эффективно. Где я не прав.
 public Task <DataTable> GetDataFromBase(string _connectionString, string qwery,int? _stringout)
        {

           Task<DataTable>  rezulTable = null;

            string connectionString = _connectionString;

            try
            {

                using (SqlConnection connection = new SqlConnection(connectionString))

                if (connection.State != ConnectionState.Open)
                {
                    connection.Open();
                }

            }
            catch (Exception e)
            {
               MessageBox.Show("Ошибка соединения "+e);
                throw;
            }

            var dt = new DataTable();

            //получаем результат запроса в DataTable...
            using (var adapter = new System.Data.SqlClient.SqlDataAdapter(qwery, connectionString))
            {
                adapter.Fill(dt);
            }

            // выбираем количество записей

            if (_stringout!=null&&_stringout!=0)// проверяем, что строка не пустая, и не равна 0
            {
             int countRows=(int)_stringout;
             var t = dt.AsEnumerable().Take(countRows);
                // вот тут ошибка
                rezulTable = t.CopyToDataTable();

            }
            else
            {
             rezulTable=dt;
            }

            return rezulTable;

        }

A: У вас в коде определена переменная rezulTable типа Task<DataTable>. А далее вы пытаетесь присвоить ей значение типа DataTable:
var dt = new DataTable();
...
rezulTable = t.CopyToDataTable();
...
rezulTable = dt;

Чтобы ошибка исчезла можно использовать метод Task.FromResult:
rezulTable = Task.FromResult(t.CopyToDataTable());
...
rezulTable = Task.FromResult(dt);

Однако, в данном случае это не имеет большого смысла, т. к. ваш код принципиально синхронный. Нужно просто возвращать DataTable, изменив сигнатуру метода:
public DataTable GetDataFromBase(...)
{
    var resultTable = new DataTable();
    ...
    return resultTable;
}

Вероятно, у вас возникли проблемы с долгим выполнением этого метода (обращение к БД, загрузка данных), из-за чего, например, подмерзает GUI.
Что можно предпринять?
Первый вариант: запустить внутри метода отдельный поток (задачу) и вернуть её.
public Task<DataTable> GetDataFromBase(...)
{
    return Task.Run(() =>
    {
        Task<DataTable> resultTable = null;
        ...
        return resultTable;
    });
}

После чего вызывать этот метод следует с async:
await GetDataFromBase(...);

Но такой способ не рекомендуется: Task.Run Etiquette. (Хотя здесь автор статьи сам использует такой способ - как после этого верить людям?..) Оставьте метод синхронным, а Task.Run используйте там, где вызываете этот метод.

Другой вариант. Сделаем метод действительно асинхронным. Дело в том, что запуск отдельного потока/задачи следут использовать только для CPU-bound нагрузки, т. е. когда именно процессор занят длительными вычислениями. А у вас идёт IO-bound нагрузка: долго выполняются запросы к БД.
Обший шаблон метода будет выглядеть примерно так:
public async Task<DataTable> GetDataFromBaseAsync(string connectionString, string query)
{
    using (var connection = new SqlConnection(connectionString))
    {
        await connection.OpenAsync();

        using (var cmd = new SqlCommand(query, connection))
        using (var reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false))
        {
            var resultTable = new DataTable();
            // здесь должен быть код создания колонок в DataTable
            // ...

            while (await reader.ReadAsync().ConfigureAwait(false))
            {
                var dataRow = resultTable.NewRow();
                for (int i = 0; i < resultTable.Columns.Count; i++)
                {
                    dataRow[i] = reader[i];
                }
                resultTable.Rows.Add(dataRow);
            }
            return resultTable;
        }
    }
}

И вот ещё что. Вы выбираете заданное количество строк уже на клиенте (с помощью параметра _stringout) - это неэффективно. Это нужно делать непосредственно в sql-запросе (используя ключевое слово TOP или LIMIT в зависимости от диалекта).
Примечание: у nullable-типов есть свойства HasValue и Value - научитесь их использовать.

Перед написанием ответа я поискал решения асинхронного заполнения дататейбла. Я разочарован. Часто предлагается использовать Task.Run. Иногда асинхронно создаётся DataReader, а далее загрузка данных выполняется простым вызовом dataTable.Load(reader) - то есть синхронно. И такие ответы приняты и заплюсованы. Моя в печали...
Нормальное решение находится по этой ссылке (её уже приводили в комментариях).


Q: Converting object to Integer equals null I am trying to convert an object from an object to an integer in java. These are the results I get with the following methods:
Object intObject = 50;
intObject: 50
intObject.toString(): 50
Integer.getInteger(intObject.toString()): null

I have no idea why I would get a null when converting the string of the object to an integer.
Here is the code that I am using:
    final Object temp = mCloudEntity.get(SaveAndLoadManager.TAG_TEST_INT);
    Log.i(TAG, "intObject: " + temp );
    Log.i(TAG, "intObject.toString(): " + temp.toString());
    Log.i(TAG, "Integer.getInteger(intObject.toString()): " + Integer.getInteger(temp.toString()));

A: You should use
// Parses the string argument as a signed decimal integer
Integer.parseInt(intObject.toString());

instead of
// Determines the integer value of the system property with the specified name.
// (Hint: Not what you want)
Integer.getInteger(...)


Q: How to SELECT with several conditions? (WHERE ... AND ... IN (...)) For example: in my database I have 3 tables: COMPANY, COUPON and COMPANY_COUPON.
COMPANY table has fields: ID and NAME, COUPON table has: ID, TITLE and TYPE, COMPANY_COUPON table has: ID of the COMPANies and ID of the COUPONs that they own.
So, in java to get all coupons of the company I use command:
SELECT coupon_id FROM company_coupon WHERE company_id = ?

And put it into Collection.
But I need something to get all coupons of the company by the type,
something like:
SELECT * FROM company_coupon WHERE company_id = 1 AND coupon_id = (SELECT * FROM coupon WHERE type = camping)

of course this one is not working, but I'm looking for something like that.
I know that i can get all coupons of the company and put them into Collection and then just delete all coupons that not equals to the specified type, but is there any way to do this process in database by SQL commands?

A: Use only one column with an IN operator
SELECT *
  FROM COMPANY_COUPON
 WHERE COMPANY_ID = 1
   AND COUPON_ID IN (SELECT COUPON_ID FROM COUPON WHERE TYPE = CAMPING)

A: I think you just want a join:
SELECT cc.COUPON_ID
FROM COMPANY_COUPON cc JOIN
     COUPON c
     ON cc.COUPON_ID = c.ID
WHERE cc.COMPANY_ID = ? AND c.TYPE = ?;

A: You might want to use WHERE IN here:
SELECT *
FROM COMPANY_COUPON
WHERE COMPANY_ID = 1 AND COUPON_ID IN (SELECT ID FROM COUPON WHERE TYPE = 'CAMPING');

You could also use EXISTS, which is probably the best way to write your logic:
SELECT cc.*
FROM COMPANY_COUPON cc
WHERE
    cc.COMPANY_ID = 1 AND
    EXISTS (SELECT 1 FROM COUPON c WHERE c.TYPE = 'CAMPING' AND c.ID = cc.COUPON_ID);

Using EXISTS might outperform doing a join between the two tables, because the database can stop as soon as it finds the very first match.


Q: Problem showing image from a database with JSF via a Servlet EDIT: The reason for this issue was due to bug unrelated to the servlet.
I'm working on a JSF2/JPA/EJB3 project that enables users to upload photos of themselves and stores them in a database. Loading images from the database is made possible with a servlet. There is however a problem; when changing the picture and posting the page, the image goes blank. The servlet doesn't seem to be called.
Web page:
<h:form>
    <h:graphicImage value="image?fileId=#{bean.currentUser.photo.id}"/>
    <3rd party file upload component (primeFaces)/>
    <h:commandButton value="post"/>
</h:form>

Servlet mapping:
<servlet>
    <servlet-name>imageServlet</servlet-name>
    <servlet-class>com.xdin.competence.jsf.util.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>imageServlet</servlet-name>
    <url-pattern>/image/*</url-pattern>
</servlet-mapping>

Servlet:
@ManagedBean
public class ImageServlet extends HttpServlet {
    private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB.
    @EJB private UserBean userBean;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    {
        Long fileId = Long.parseLong(request.getParameter("fileId"));
        if (fileId == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
        return;
        }
        UserFile photo = userBean.findUserFile(fileId);
        // Init servlet response.
        response.reset();
        response.setBufferSize(DEFAULT_BUFFER_SIZE);
        response.setContentType("image/png");
        response.setHeader("Content-Length", String.valueOf(photo.getFileData().length));
        response.setHeader("Content-Disposition", "inline; filename=\"" + photo.getFilename() + "\"");

        // Prepare streams.
        BufferedInputStream input = null;
        BufferedOutputStream output = null;

        try {
            // Open streams.
            input = new BufferedInputStream(new ByteArrayInputStream(photo.getFileData()), DEFAULT_BUFFER_SIZE);
            output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

            // Write file contents to response.
            byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
            int length;
            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
        } finally {
            // Gently close streams.
            close(output);
            close(input);
        }
    }

    private static void close(Closeable resource) {
        if (resource != null) {
            try {
                resource.close();
            } catch (IOException e) {
                // Do your thing with the exception. Print it, log it or mail it.
                e.printStackTrace();
            }
        }
    }

My guess is that doGet in ImageServlet is only called on Get. Forcing a new GET with faces-redirect=true works, but is it possible to make the servlet work on POST aswell?

A: You seem to think that images are downloaded as part of the HTTP response containing the HTML page containing the <img> elements. This is not true. The browser obtains the HTML page, parses the HTML structure, encounters the <img> element and fires separate HTTP requests for each of them. It is always GET. The same applies to CSS/JS and other resources. Install a HTTP request debugger tool like Firebug and check the Net panel.
The actual problem is likely that the URL as definied in src attribute is wrong. You're using a context-relative path (i.e. no leading slash and no domain in the src attribute, it's fully dependent on the current request URL -the one in browser address bar). Probably the HTML page get posted to a different context/folder which caused that the image becomes unreachable from that point. Try using an absolute path or a domain-relative path.
<h:graphicImage value="#{request.contextPath}/image?fileId=#{bean.currentUser.photo.id}" />

If still in vain, then have a closer look at Firebug's analysis.


Q: I want to make an Script in python which will calculate Beneish M Score in python Table 1 – Financials (standalone)
Year                            2014              2013            2012            2011            2010
Net Sales                       8,020.35          9,754.50        8,433.48        6,447.24        4,827.47
Cost of Goods                   5,524.76          7,416.64        6,299.72        4,494.74        3,176.16
Net Receivables                 2,045.70          2,807.26        1,689.88        1,109.29        693.33
Current Assets                  4,000.61          4,894.15        4,228.61        2,747.23        2,236.16
Property, Plant and Equipment   1,848.27          2,177.22        1,948.19        1,834.23        1,552.22
Depreciation                    199.02            219.18          203.06          194.05          180.10
Total Assets                    13,994.40         13,215.16       12,186.17       10,201.72       8,480.00
SGA Expense                     588.25            495.77          451.73          347.35          338.63
Net Income                      673.95            423.05          345.39          379.69          283.40
Cash Flow from Operations       988.18            1.17            406.65          340.06          1,069.19
Current Liabilities             4,301.49          4,697.45        4,868.32        3,087.15        889.03
Long-term Debt                  1,492.06          1,503.40        1,475.46        1,534.03        3,640.02

Table 2 – Financials (consolidated)
Year                            2014        2013        2012        2011        2010
Net Sales                       26,111.94   26,003.67   21,840.29   18,187.77   15,523.34
Cost of Goods                   10,323.87   11,543.19   9,156.12    6,872.80    5,519.23
Net Receivables                 2,642.69    3,358.56    2,220.68    1,530.03    1,083.42
Current Assets                  17,581.22   17,393.72   13,317.96   10,932.59   5,528.21
Property, Plant and Equipment   17,998.98   15,444.53   12,490.63   8,847.56    6,544.69
Depreciation                    1,608.86    1,295.49    1,092.33    940.90      866.48
Total Assets                    63,034.10   57,105.27   45,157.00   39,600.52   28,988.86
SGA Expense                     1,730.27    1,625.98    1,347.43    1,231.69    1,640.42
Net Income                      1,221.80    1,183.89    1,010.15    907.97      154.56
Cash Flow from Operations       47.62       -993.70     153.47      1,263.04    4,235.99
Current Liabilities             14,515.48   15,660.07   11,881.23   9,106.74    3,206.53
Long-term Debt                  12,460.74   9,392.73    5,641.57    4,680.65    7,432.40

Here from the above table I need to calculate different Indexes:
Index 1: Days Sales in Receivables Index (DSRI) = Net Receivable [CY]/ Net Sales [CY] Divided by Net Receivable [CY-1]/ Net Sales [CY-1]
So I thought storing all the Table 1 data in dictionary like this:
Net_Sales = {2014: 8020.35, 2013:9754.50, 2012:8433.48, 2011:6447.24, 2010:4827.47}
Cost_Goods = {2014: 5524.76, 2013:7416.64, 2012:6299.72, 2011:4494.74, 2010:3176.16}
Net_Receivables = {2014:2045.70, 2013:2807.26, 2012:1689.88, 2011:1109.29, 2010:693.33}
Current_Assets = {2014:4000.61, 2013:4894.15, 2012:4228.61, 2011:2747.23, 2010:2236.16}
Property_Plant_Equipment = {2014:1848.27, 2013:2177.22, 2012:1948.19, 2011:1834.23, 2010:1552.22}
Depreciation = {2014:199.02, 2013:219.18, 2012:203.06, 2011:194.05, 2010:180.10}
Total_Assets = {2014:13994.40, 2013:13215.16, 2012:12186.17, 2011:10201.72, 2010:8480.00}
SGA_Expense = {2014:588.25, 2013:495.77, 2012:451.73, 2011:347.35, 2010:338.63}
Net_Income = {2014:673.95, 2013:423.05, 2012:345.39, 2011:379.69, 2010:283.40}
Cash_Flow_Operations = {2014:988.18, 2013:1.17, 2012:406.65, 2011:340.06, 2010:1069.19}
Current_Liabilities = {2014:4301.49, 2013:4697.45, 2012:4868.32, 2011:3087.15, 2010:889.03}
Long_Deb = {2014:1492.06, 2013:1503.40, 2012:1475.46, 2011:1534.03, 2010:3640.02}

But then again I need to make lots of dictionary for Table 2 also.
And again I need to display the output in a table like this:
#Index 1 using the formula 1.
Net Receivable [CY-1]/ Sales [CY-1]
Year                            2014    2013    2012    2011
As per Standalone Financials    0.886   1.436   1.165   1.198
As per Consolidated Financials  0.784   1.270   1.209   1.205

I calculated the 1st value using the following formula:
DSRI = (Net_Receivables[2014]/Net_Sales[2014]) / (Net_Receivables[2013]/Net_Sales[2013])

And I got the only one value. So it would be very hectic and unplanned way to do the above calculation. As I need to do lots of calculation on the above data. So can someone help me how to store these data if not in dictionary then where. And how should I plan to calculate all the required values. As I need to calculate 8 indexes and maybe in the future I can reuse it for different set of years. Thanks. Please tell me if you need more information.


Q: How to schedule a MySQL database backup in a remote Ubuntu server to a Dropbox folder in Windows PC? I have a MySQL database that I want to daily backup to my Dropbox folder on my Windows PC.
How can I do that automatically from Windows 7?

A: One of the simplest ways to backup a mysql database is by creating a dump file. And that is what mysqldump is for. Please read the documentation for mysqldump.
In its simplest syntax, you can create a dump with the following command:
mysqldump [connection parameters] database_name > dump_file.sql

where the [connection parameters] are those you need to connect your local client to the MySQL server where the database resides.
mysqldump will create a dump file: a plain text file which contains the SQL instructions needed to create and populate the tables of a database. The > character will redirect the output of mysqldump to a file (in this example, dump_file.sql). You can, of course, compress this file to make it more easy to handle.
You can move that file wherever you want.
To restore a dump file:

*

*Create an empty database (let's say restore) in the destination server

*Load the dump:
mysql [connection parameters] restore < dump_file.sql

There are, of course, some other "switches" you can use with mysqldump. I frequently use these:

*

*-d: this wil tell mysqldump to create an "empty" backup: the tables and views will be exported, but without data (useful if all you want is a database "template")

*-R: include the stored routines (procedures and functions) in the dump file

*--delayed-insert: uses insert delayed instead of insert for populating tables

*--disable-keys: Encloses the insert statements for each table between alter table ... disable keys and alter table ... enable keys; this can make inserts faster

You can include the mysqldump command and any other compression and copy / move command in a batch file.

A: My solution to extract a backup and push it onto Dropbox is as below.
A sample of Ubuntu batch file can be downloaded here.
In brief

*

*Prepare a batch script backup.sh

*Run backup.sh to create a backup version e.g. backup.sql

*Copy backup.sql to Dropbox folder

*Schedule Ubuntu/Windows task to run backup.sh task e.g. every day at night

Detail steps

*

*All about backing up and restoring an MySQL database can be found here.

Back up to compressed file
mysqldump -u [uname] -p [dbname] | gzip -9 > [backupfile.sql.gz]

*How to remote from Windows to execute the 'backup' command can be found here.

plink.exe -ssh -pw  -i "Path\to\private-key\key.ppk" -noagent username@server-ip

*How to bring the file to Dropbox can be found here

Create a app
  https://www2.dropbox.com/developers/apps
Add an app and choose Dropbox API App. Note the created app key and app secret
Install Dropbox API in Ubuntu; use app key and app secret above
$ wget https://raw.github.com/andreafabrizi/Dropbox-Uploader/master/dropbox_uploader.sh
$ chmod +x dropbox_uploader.sh

Follow the instruction to authorize access for the app e.g.
http://www2.dropbox.com/1/oauth/authorize?oauth_token=XXXXXXX

Test the app if it is working right - should be ok
$ ./dropbox_uploader.sh info

The app is created and a folder associating with it is YourDropbox\Apps\<app name>
Commands to use
List files
$ ./dropbox_uploader.sh list

Upload file
$ ./dropbox_uploader.sh upload <filename> <dropbox location>
e.g.
$ ./dropbox_uploader.sh upload backup.sql .

This will store file backup.sql to YourDropbox\Apps\<app name>\backup.sql
Done

*How to schedule a Ubuntu can be view here using crontab

Call command
sudo crontab -e

Insert a line to run backup.sh script everyday as below
0 0 * * * /home/userName/pathTo/backup.sh

Explaination:
minute (0-59), hour (0-23, 0 = midnight), day (1-31), month (1-12), weekday (0-6, 0 = Sunday), command

Or simply we can use
@daily /home/userName/pathTo/backup.sh

Note:

*

*To mornitor crontab tasks, here is a very good guide.


Q: How can i modulo a big integer value     #include <string>
    #include <iostream>

    using namespace std;

    #include "md5.h"

    int main()
    {
        MD5 md5;

        string message = "secretU";
        char arr[message.size()];
        strcpy(arr, message.c_str());

        //encrypting the message "secretU", it will return a string of hexadecimals
        string result = md5.digestString(arr);

        //print the result of the encrypted message.
        cout << result;
        return 0;
    }

Result of the output in hexadecimals
1853c517b0e1095a341210f1a4b422e6

Once i tried to convert to Decimal, it needs 125 bit size? However, unsigned long long can only contain up to 64 bits, is there a way to store this long integer so that i can modulo it with the value i want?
Convert hexadecimals to decimal
32336430049777443053240099092194140902

A: You can do it by hand or use a library that provides big integers like https://mattmccutchen.net/bigint/

A: Take the modulo by breaking them into pieces.. say for example you want to take modulo of 37^11 mod 77 in which 37^11 gives answer 1.77917621779460E17 so to get this .. take some small number in place of 11 which gives an integer value.. break it into pieces... 37^11 mod 77 can be written as (37^4 x 37^4 x 37^3 mod 77) so solve it as.. {(37^4 mod 77)(37^4 mod 77)(37^3 mod 77)} mod 77. So, in general xy mod n = {(x mod n)(y mod n)} mod n


Q: Jhipster - production build failure I cannot generate my JHipster application war by running mvnw -Pprod. Here's the error I get in a console:
https://pastebin.com/3wLwy2x4
And my package.json dependencies:
https://pastebin.com/txnATG6M
The solution from:
Webpack failure during JHipster Prod Package
doesn't work for me, only the error changes to:
[INFO] ERROR in ./src/main/webapp/app/app.main.ts
[INFO] Module not found: Error: Can't resolve './app.module.ngfactory' in 'D:\Programy\Web\softdog2\src\main\webapp\app'
[INFO]  @ ./src/main/webapp/app/app.main.ts 2:0-62
[INFO] MergetJsonsWebpackPlugin emit starts...
[INFO] MergetJsonsWebpackPlugin emit completed...
[ERROR] error Command failed with exit code 2.
[INFO] info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
[ERROR] error Command failed with exit code 1.
[INFO] info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
[ERROR] error Command failed with exit code 1.
[INFO] info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:48 min
[INFO] Finished at: 2018-06-13T23:29:58+02:00
[INFO] Final Memory: 50M/532M

Also, I get following warnings from yarn:
[ERROR] warning " > angular-particle@1.0.4" has incorrect peer dependency "@angular/core@^4.0.0".
[ERROR] warning " > ng2-page-scroll@4.0.0-beta.12" has incorrect peer dependency "@angular/core@>=4.2.6 <5.0.0".
[ERROR] warning " > ng2-page-scroll@4.0.0-beta.12" has incorrect peer dependency "@angular/common@>=4.2.6 <5.0.0".
[ERROR] warning " > ng2-page-scroll@4.0.0-beta.12" has incorrect peer dependency "@angular/platform-browser@>=4.2.6 <5.0.0".
[ERROR] warning " > ng2-page-scroll@4.0.0-beta.12" has incorrect peer dependency "@angular/router@>=4.2.6 <5.0.0".

A: The answer to this problem is to update Angular libraries versions (in my case from 5.1.0 to 5.1.1).


Q: Image request from URL fails I have the following code:
func getImage(urlString: String, completionHandler: UIImage -> Void) -> NSURLSessionTask {

    let request = NSMutableURLRequest(URL: NSURL(fileURLWithPath: urlString)!)

    println("Executing image request: \(urlString)")

    return session.dataTaskWithRequest(request) {
        data, response, error in
        if error != nil {
            println("\tGET request failed: \(error!)")
        } else {
            println("\tGET request succeeded!")
            let response = response as NSHTTPURLResponse
            if response.statusCode == 200 {
                let image = UIImage(data: data)
                dispatch_async(dispatch_get_main_queue()) { // dispatch naar main thread (main_queue is thread# van main thread van app)
                    completionHandler(image!)
                }
            }
        }
    }
}

But when I execute it, I get the following output:
Executing image request: http://i.imgur.com/rfw7jrU.gif
GET request failed: Error Domain=NSURLErrorDomain Code=-1100
"The operation couldn’t be completed. (NSURLErrorDomain error -1100.)"
UserInfo=0x14e9b200 {NSErrorFailingURLKey=file:///http:/i.imgur.com/rfw7jrU.gif,
NSErrorFailingURLStringKey=file:///http:/i.imgur.com/rfw7jrU.gif,
NSUnderlyingError=0x14d8d600 "The operation couldn’t be completed.
(kCFErrorDomainCFNetwork error -1100.)"}

I have no idea why this happens, as my nearly identical code that gets a .json file does work. I have tested this on both my device and the simulator.
This fails on all urls, not only imgur links. It also crashes before I put it into a UIImage, so that is also not the problem.

A: From the error message one can see that your URL is a file URL:
file:///http:/i.imgur.com/rfw7jrU.gif

and error -1100 is kCFURLErrorFileDoesNotExist (see CFNetwork Error Codes Reference).
You should replace
NSURL(fileURLWithPath: urlString)

by
NSURL(string: urlString)
// Swift 3+:
URL(string: urlString)


Q: how to fix update error i want to update all row's alternativegroups with $id value.
the action getting error: coldchain can not be null.
when i search the db for pk = $a, It's coldchain value is boolen(false). and db is postgresql
how can i set $q->attributes without posting other values?
public function actionUpdate($id){

    if (isset($_POST['forms'])){

        $arr = explode(',', $_POST['forms']);

        foreach ($arr as $a){

            $q = MedicineDrugform::model()->findbypk($a);
            $q->alternativegroup = $id;
            if ($q->save()){
                echo $q->id."q saved
";
            }
            else {
                echo "
";
                print_r($q->getErrors());
            }

            die();

            $qu = MedicineDrugformUpdate::model()->findbyattributes(array('drug_form_id'=>$a));
            $quu = MedicineDrugformUpdate::model()->findbypk($qu->id);
            $quu->alternativegroup = $id;
            if ($quu->save()){
                echo $quu->id."qu saved
";
            }

        }
        die();
        $this->render('/site/messages', array('message'=>'formsaved'));

    }

    $this->render('add', array('id'=>$id));
}

A: maybe it cant find the corresponding record for
$q = MedicineDrugform::model()->findbypk($a);


Q: .Net MVC4 updating database I am struggling to update a database. All i need to do is update a column called balance
In my controller i have this
     public void updateBalance(int account, double amount)
    {
        var accounnt = db.Accounts.FirstOrDefault(u => u.AccountNumber == account);

        if (accounnt == null)
        {

        }
        else
        {
           //   update the balance column in account table
        }

    }

can some one please assist?

A: Once you have loaded your entity, you simply need to update its properties and call SaveChanges on your DbContext.
  if (accounnt == null)
    {

    }
    else
    {
       account.balance = 1000;
    }
  db.SaveChanges();


Q: Render Flash (SWF) frame as image (PDF,PNG,JPG) I would like to write a python script that takes a bunch of swf files and renders them to individual image files.
Each swf file has just one frame (text, pictures etc.) and no animations at all. I have already tried the render command from the swftools toolset (The windows version), but the resolution of the resulting image is too low.
So what I need is:
A command line tool (Windows/Linux) or a python library which renders one frame from a swf to a bitmap or better to something like a PDF (It would be cool if the text data could be retained). It would be great if the target resolution/size could be set manually.
Thanks in advance!

A: Sometimes SWFRender is stuck at very heavy files, especially when producing 300dpi+ images. In this case Gnash may help:
gnash -s<scale-image-factor> --screenshot last --screenshot-file output.png -1 -r1 input.swf

here we dump a last frame of a movie to file output.png disabling sound processing and exiting after the frame is rendered. Also we can specify the scale factor here or use
-j width -k height

to specify the exact size of resulting image.

A: You could for example build an AIR app that loads each SWF, takes the screenshot and writes it to a file.
The thing is you'll need to kick off something to do the render and, as far as i know, you can't do that without the player or some of its Open Source implementation.
I think your best bet is going AIR, the SDK is free and cross-platform. If you are used to python, the AS3 necessary should be easy enough to pick up.
HTH,
J

A: I'm sorry to answer my own question, but I found an undocumented feature of swfrender (part of the swftools) by browsing through the sources.
swfrender path/to/my.swf -X<width of output> -Y<height of output>
-o<filename of output png>

As you might have guessed the X option lets you determine the width (in pixels) of the output and Y does the same for the height. If you just set one parameter, then the other one is chosen in relation to the original height-width-ratio (pretty useful)
That does the trick for me but as Zarate offered a solution that might be even better (I'm thinking of swf to PDF conversion) he deserves the credits.
Cheers


Q: sum of table with join on joined table gives wrong total I have three tables:

*

*users_timings_log

*projects_tasks

*projects_modules

I want to calculate the total hours spent on a task with module_ id 2 for example
I use the following query for it:
SELECT SEC_TO_TIME(SUM(TIMESTAMPDIFF(SECOND, `start_date`, `end_date`)))
AS `total_hours`
FROM `users_timings_log`
INNER JOIN `projects_tasks` ON users_timings_log.type_id = projects_tasks.id
LEFT JOIN `projects_modules` ON projects_tasks.module_id = '2'
WHERE `type` = '0'

This is the structure of my users_timings_log table
+-------+---------------------+---------------------+------+---------+
|   ID  | start_date          | end_date            | type | type_id |
+-------+---------------------+---------------------+------+---------+
|   1   | 2015-09-17 09:00:00 | 2015-09-17 19:00:00 | 1    | 28      |
|   2   | 2015-09-17 07:00:00 | 2015-09-17 12:00:00 | 1    | 24      |
|   3   | 2015-09-17 08:00:00 | 2015-09-17 16:15:00 | 1    | 18      |
|   4   | 2015-09-17 10:00:00 | 2015-09-17 17:00:00 | 1    | 24      |
+-------+---------------------+---------------------+------+---------+

Here's the structure of my projects_tasks table
+-------+---------------+-----------------------------+-----------+
|   ID  | name          | description                 | module_id |
+-------+---------------+-----------------------------+-----------+
|   18  | First task    | Some useless description    | 1         |
|   24  | Second task   | Another useless description | 2         |
|   28  | Third task    | NULL                        | 3         |
+-------+---------------+-----------------------------+-----------+

Structure of projects_modules table
+-------+---------------+
|   ID  | name          |
+-------+---------------+
|   1   | Module 1      |
|   2   | Module 2      |
|   3   | Module 3      |
+-------+---------------+

What I need is the total of hours of a specific module, but for some reason It is giving me for each module the same amount of time.
I'm stuck on it. What am I doing wrong?
Thanks in advance

A: You need a GROUP BY and proper JOIN:
SELECT pt.module_id,
       SEC_TO_TIME(SUM(TIMESTAMPDIFF(SECOND, ul.`start_date`, ul.`end_date`)))
AS `total_hours`
FROM `users_timings_log` ul INNER JOIN
     `projects_tasks` pt
     ON ul.type_id = pt.id
WHERE `type` = '0'
GROUP BY pt.module_id;

If you only want one module, then add a WHERE clause for that purpose.
I also added table aliases, so the query is easier to write and to read.
I should add, the problem with your query is that it did not have proper JOIN conditions for projects_modules.  You don't seem to need that table, so removing the table is fine.  If you need columns from that table, add the appropriate JOIN conditions.


Q: With a user specified by IP address, why I can't connect to mysql server remotely? I am trying to set mysql server on an office computer to allow only for my computer at home to be able to connect to the mysql server.
I created a user on the mysql server. The user is specified by IP address(XXX.XXX.XXX.XXX) of my home computer.
Login name: myname

Limit to Hosts Matching: XXX.XXX.XXX.XXX

and also, in Administrative Roles tab, I added DBManager to this user.
and then, I tested this connection from my home computer using mysql workbench, and I got this error:
Failed to Connect to MySQL at ---.---.---.---:3306 with user myname

Host '???-???-???-???-???.abc.defg.hi.jk' is not allowed to connect to this MySQL server

---.---.---.---: IP address of the computer that has mysql server.
???-???-???-???-???.abc.defg.hi.jk: I am not sure about this. Looks like some gate way name.


Q: JMeter Network distribution in load testing How can i distribute networks while load testing in JMeter?
Suppose my load test is of 1 hr. and i have 100 users. I want to distribute network like-
              20% users - 2G speed
              40% users - 3G speed
              rest      - 4G speed.
OR, other scenario like throughout the whole test of 1hr. 20% traffic will on 2G speed, 40% traffic on 3G and rest on 4G speed.
Can anyone tell me that how to mimic this network behavior in JMeter?

A: *

*You will need to kick off 3 JMeter instances in Distributed Mode

*For 1st JMeter instance add the next lines to user.properties file to mimic 2G network:
httpclient.socket.http.cps=6400
httpclient.socket.https.cps=6400

*For 2nd JMeter instance add the next lines to user.properties file to mimic 3G network
httpclient.socket.http.cps=2688000
httpclient.socket.https.cps=2688000

*For 3rd JMeter instance add the next lines to user.properties file to mimic 4G network:
httpclient.socket.http.cps=19200000
httpclient.socket.https.cps=19200000

More information: How to Simulate Different Network Speeds in Your JMeter Load Test


Q: root user renamed as qroot - unable to su or sudo Mysteriously, on our public SSH server, root user is now showing up as qroot. All the files owned by root are now owned by qroot.
id qroot shows qroot is UID 0
/etc/passwd file is owned by qroot
/etc/shadow is readable only by qroot
su - says su: user root does not exist
su qroot says password is wrong (probably because shadow file mismatches)
What can I do to recover root user?
Fedora 14, plain /etc/passwd file based auth.

A: Use the following command:
sudo -u \#0 vi /etc/passwd

Then change the user name back to root.
For the explanation please visit: https://aslamlatheef.blogspot.com/2015/09/why-cant-i-sudo-unknown-user-root.html


Q: OpenLayers 6 how to add line breaks to text labels? I'm trying to add simple line breaks to my text labels in ol 6 using \n but somehow both text line drift far apart as soon as I zoom out. It's weird. I created a simple fiddle, just click on the button "set style".
The relevant part:
var createTextStyle = function (feature, resolution) {

  return new ol.style.Text({
    text: 'first line' + '\n' + 'second line'
  });
};

function polygonStyleFunction(feature, resolution) {
  return new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: 'blue',
      width: 1,
    }),
    text: createTextStyle(feature, resolution),
  });
}

The first line should be above the second text line but it's not.
https://jsfiddle.net/a7cbgtd9/
The \n should not be a problem here because it works in this example:
https://openlayers.org/en/latest/examples/vector-labels.html
Im even using the same ol version.

A: In the code above there is definitely not all the relevant code, but looking into your JSFiddle it was easy to find the culprit, which is the following CSS:
div {width:100px; height:100%;}

It interferes with all the OpenLayers <div> sections and the consequence is mangled map display.


Q: URL rewrite in IIS6 - Third party tools I have collected the following api/sdk/whatever which provide modules for doing url rewriting in IIS 5/6/7. Some are free-open source and some require $.
I haven't tried any of them. I would like to know if anyone is currently using or used or have any kind of experience with these tools (website listed).
UrlRewritingNet.UrlRewrite - http://www.urlrewriting.net/159/en/downloads.html

IIS Mod-Rewrite Pro ($) -http://www.iis.net/downloads/default.aspx?tabid=34&g=6&i=1469

Open Source - http://urlrewriter.net/

Helicon Tech (Full $)- http://www.isapirewrite.com/

ISAPI_ Rewrite 3.0 ($) - http://www.seoconsultants.com/windows/isapi/3/

Open Source Ionics Isapi Rewrite Filter - http://iirf.codeplex.com/

Any help would be greatly appreciated.
Thanks.
Murali

A: I have personal experience with IIRF from the codeplex site, and I liked it and found it good.

A: I use UrlRewrite from UrlRewriting.Net
Very easy to use for the simple thing I'm doing: send .pdf requests to an aspx page to generate the pdf.


Q: googleVis datatype conversion in R does not seems to work I have been working with 'googleVis' and R in order to produce a Line chart using Google charts APIs.
On Google API's tutorial I found that data conversion in Javascript is used to determine if the axes will be "continuous"(using Numeric Javascript type) and "discrete" (using String).
I believe with googleVis is the same, since datatypes are derived from R.
Problem is, in the following example (which I modified after taking it from the R demo function), the X axis values are equally spaced (hence, still discrete), despite they seem to be "Numeric"
library(googleVis)
df=data.frame(val1=c(10,13,100), val2=c(23,12,32))
Line <- gvisLineChart(df)
plot(Line)

Could someone please me help to understand this? Thank you very much!

A: Full disclosure: I love the googleVis package.
I see the same behavior you do, even after updating to the latest version of googleVis (not yet on CRAN). I don't know if this is a bug or not; the googleVis documentation for gvisLineChart mentions continuous data, but nothing I tried allows me to plot the X axis as numerical.
You can get clues as to what's happening when you change aspects of your code in generating googleVis charts and graphs if you right-click on the web page that gets displayed with the plot, and choose "View Page Source." This page is where the magic happens, and is the HTML output from the googleVis package.
The problematic line in this case is the one that reads "data.addColumn('string','val1');
In this line, the word 'string' should be 'number', and the val1 values should not be in quotes in the data section.
You can get the results you want, though, by using gvisScatterChart instead:
library(googleVis)
df=data.frame(val1=c(10,13,100), val2=c(23,12,32))
Line <- gvisScatterChart(df, options=list(lineWidth=2, pointSize=0))
plot(Line)


Q: Android NetworkOnMainThreadException when calling Url.OpenStream I get this exception  when running my code on emulator (Android 4.0.3 / API 15). While opening a stream it will throw an exception. Error-message is null.
try {
    String adress        = "xxx";
    URL url              = new URL(adress);
    InputSource source   = new InputSource(url.openStream());

} catch (Exception e) {
    (new TextView).setText("Error: "+e.getMessage());
}

URL is still working with the emulator (in browser).
I have cleaned the project.
Also Internet connection is allowed:
<uses-permission android:name="android.permission.INTERNET" />

Exception : android.os.NetworkOnMainThreadException

A: Please never run a networking operation on the main (UI) thread .
Main thread is used to:

*

*interact with user.

*render UI components.

any long operation on it may risk your app to be closed with ANR message.
Take a look at the following :

*

*Keeping your application Responsive

*NetworkOnMainThreadException
you can easily use an AsyncTask or a Thread to perform your network operations.
Here is a great tutorial about threads and background work in android: Link

A: Works for me:
Manifest.xml:
<uses-permission android:name="android.permission.INTERNET" />

.java:
private static boolean DEVELOPER_MODE = true;
...
protected void onCreate(Bundle savedInstanceState) {

     if (DEVELOPER_MODE) {
         StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                 .detectDiskReads()
                 .detectDiskWrites()
                 .detectNetwork()   // or .detectAll() for all detectable problems
                 .penaltyLog()
                 .build());
         StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                 .detectLeakedSqlLiteObjects()
                 .detectLeakedClosableObjects()
                 .penaltyLog()
                 .penaltyDeath()
                 .build());
     }
...

hope it helps.
see also : http://developer.android.com/reference/android/os/StrictMode.html


Q: Reply Kafka Template - Exception handling I am using ReplyingKafkaTemplate to establish a synchronous call between two microservices.
The receiver of the event is annotated with SendTo as below:
@KafkaListener(topics = "${kafka.topic.prefix}"
        + "${kafka.topic.name}", containerFactory = "customEventKafkaListenerFactory")
@SendTo
public CustomResponseEvent onMessage(
        @Payload @Valid CustomRequestEvent event, @Header(KafkaHeaders.CORRELATION_ID) String correlationId,
        @Header(KafkaHeaders.REPLY_TOPIC) String replyTopic) {

   //Making some REST API calls to another external system here using RestTemplate
}

The REST API call can throw a 4xx or 5xx. There are multiple such calls, some to internal systems, and some to external systems. It may be a bad design, but let's not get into that.
I would like to have a global exception handler for the RestTemplate where I can catch all the exceptions, and then return a response to the original sender of the event.
I am using the same replyTopic and correlationId as received in the consumer to publish the event.
But still the receiver of the response throws No pending reply exception.

*

*Whatever approach I have above, is it possible to achieve such a central error response event publisher?

*Is there any other alternative that is best suited for this exception handling?

A: The @KafkaListener comes with the:
/**
 * Set an {@link org.springframework.kafka.listener.KafkaListenerErrorHandler} bean
 * name to invoke if the listener method throws an exception.
 * @return the error handler.
 * @since 1.3
 */
String errorHandler() default "";

That one is used to catch and process all the downstream exceptions and if it returns a result, it is sent back to the replyTopic:
public void onMessage(ConsumerRecord<K, V> record, Acknowledgment acknowledgment, Consumer<?, ?> consumer) {
    Message<?> message = toMessagingMessage(record, acknowledgment, consumer);
    logger.debug(() -> "Processing [" + message + "]");
    try {
        Object result = invokeHandler(record, acknowledgment, message, consumer);
        if (result != null) {
            handleResult(result, record, message);
        }
    }
    catch (ListenerExecutionFailedException e) { // NOSONAR ex flow control
        if (this.errorHandler != null) {
            try {
                Object result = this.errorHandler.handleError(message, e, consumer);
                if (result != null) {
                    handleResult(result, record, message);
                }
            }
            catch (Exception ex) {
                throw new ListenerExecutionFailedException(createMessagingErrorMessage(// NOSONAR stack trace loss
                        "Listener error handler threw an exception for the incoming message",
                        message.getPayload()), ex);
            }
        }
        else {
            throw e;
        }
    }

See RecordMessagingMessageListenerAdapter source code for more info.


Q: MySQL Auto increment skipping number which is deleted I want to generate Bill No From mySQL Auto Increment. I have column ID (Primary Key & Auto Increment). Now From This column ID I am generating Bill No As requested by user. Problem is If I delete some record in between then It should not skip the deleted ID when new record gets entered.
e.g. 1001,1002,1003,1004 etc In this if I delete record Id 1002 & next time If I enter any new record then How can I assign 1002 back to the new record.

A:
It should not skip the deleted ID when new record gets entered

Yes it should.  You're just relying on the system to do something that it was never designed to do and never claimed to do.
AUTOINCREMENT is not designed to generate your "Bill No".  It's designed to generate an ever-incrementing identifier and guarantee uniqueness by never re-using a value.  And it's doing exactly that.
You can manually generate your "Bill No" using whatever logic you like and store it in another column.  It would be strange to re-use values though.  Imagine if you issue a bill to someone, later delete the record, and then issue another bill to someone else with the same number.
Uniqueness is important with identifiers.

A: From a financial control point of view being able to delete and reuse invoice numbers damages your audit trail and leaves you open to risk. Also from a database integrity point of view, reusing primary keys is not allowed as it would lead to unexpected results,such as records in other tables appearing wrongly in a join. There are consequences to naturalising your primary keys (excellent discussion of natural and surrogate primary keys). The database is protecting its referential integrity by not allowing the reuse of the primary key. Indeed, as @David says in his response, part of the function of autoincrement on a primary key is to maintain the uniqueness of the key.
Now to solutions, from a financial aspect invoices should never be deleted so there is an audit trail, an incorrect invoice should have a contra through a credit note. On the database side if you must 'delete' a record and reuse the invoice number, I would suggest having a different field for the invoice number, not actually deleting, but using a field to flag active or deleted, and maintaining a separate incrementing invoice number. Although not advised, this will at least help maintain the integrity of your records.


Q: Which credentials and tooling do I use to authenticate to the HERE geofencing/fleet APIs? I have been trying to apply some geofencing to my Here map, but continually get 401 and 403 responses from the geofencing endpoints no matter what I do.
I was originally using the node module '@here/maps-api-for-javascript' but I saw indicators that it was not possible to do geofencing with that tool, and so I have switched to pulling down scripts (v3.1) from CDN and making direct REST calls to fill in any gaps as outlined in this SO post, I have created a test project using the exact code provided at that SO post with my api key, and the map does not render at all, let alone the geofencing (but the triangle and marker are rendered). In the console I see 403s for all calls to the APIs.
I have tried:

*

*JS API key from developer account

*REST API key from developer account

*platform API key from platform account

*oauth API token from platform account

*app_id and app_code params with my JS app id and JS API key

*app_id and app_code params with my REST app id and REST app key

My keys work to render my map, calculate routes, and update routehandles in my app, so I'm not sure why they are not working for these two calls - one to upload the fences, and one to check position against them.
Additionally in my app I had tried to do geofencing as outlined in this tutorial from here but when I try to access the platform.ext.getGeoFencingService (line 163 in view source at that link) I get an error that platform.ext is undefined.
Adding to my confusion, one part of the docs says that apikeys are read only, and another part of the docs says that starting with JS api v3.1 that you no longer need app_id and app_code.


Q: How to position a view in Android constraint layout outside the screen at the beginning I have a View in a Constraint Layout and I would like that at the very beginning it should be outside of the screen (and then later slowly move into the scree from right to left). Now, I kind of need something like negative bias or margins.
I had a look at this question How to achieve overlap/negative margin on Constraint Layout?. The accepted answer using android:layout_marginTop="-25dp"  does not have any effect (altough the top of the view is constrained and I use"androidx.constraintlayout:constraintlayout:2.1.3").
I tried the second most upvoted answer and used the code:
view.setTranslationX(view.getWidth() - 20);

This actually works. However, the problem is that when the Fragment is created you first see that the view is not on the left for a short period of time. This is not what I want. I would like to have the view beyond the right rim of the layout at the very very beginning such that it can later move into the layout.
Do you have any idea how I can do that? Ideally I would like to do this programmatically.
Update: Here is the code of the XML layout where a negative margin does not have any effect:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/game_test_background"
    tools:context=".MainActivity"
    android:id="@+id/constraintLayout">

    <ImageView
        android:id="@+id/imageView_RedRectange_Test"
        android:layout_width="0dp"
        android:layout_height="30dp"
        android:layout_marginTop="-1250dp"

        app:layout_constraintWidth_percent="0.25"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.048"
        app:srcCompat="@drawable/red_rectangle" />

    <Button
        android:id="@+id/button"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHeight_percent="0.102"
        app:layout_constraintHorizontal_bias="0.373"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.745"
        app:layout_constraintWidth_percent="0.12" />

</androidx.constraintlayout.widget.ConstraintLayout>

A: Okay so to have a negative margin you can use translateX, translateY or TranslationZ.
in xml like so:
<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    android:translationX="-60dp"
    android:translationY="-90dp"
    android:translationZ="-420dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

or programmatically like so:
View view = ...;
view.setTranslationX(-60);
view.setTranslationY(-90);
view.setTranslationZ(-420);

Then in order to slowly bring it in from right to left you can use the animate() method like so:
View view = ...;
view.animate().setDuration(1000).translationX(-600).start();

A: There is a problem with setting the width of the button using app:layout_constraintWidth_percent when the ImageView has a negative margin. The problem should go away if you can set a definite width to the button (instead of 0dp).
The problem should also resolve if you set app:layout_constraintWidth_percent to a value such that the text of the button shows completely on one line.
Here is a simplified layout to demonstrate this issue. The ConstraintLayout has two views that are simply constrained to the parent to appear in vertical center of the layout. These two views have no dependencies on each other. In addition, the ImageView has a top margin of -250dp, so it should appear above the layout's vertical center.
<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_green_light">

    <ImageView
        android:id="@+id/redRectangle"
        android:layout_width="100dp"
        android:layout_height="30dp"
        android:layout_marginTop="-250dp"
        android:layout_marginEnd="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/red_rectangle" />

     <Button
            android:id="@+id/button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="Button"
            android:textSize="18sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintWidth_default="percent"
            app:layout_constraintWidth_percent="0.12" />

</androidx.constraintlayout.widget.ConstraintLayout>

Here is what happens then the width of the ImageView is changed from 0dp to a non-zero value of 1dp. When the width is set to 0dp, the negative margin seems to be ignored. It is only when the width is set to a non-zero value that the ImageView is correctly placed.

Changing the width of the button should have no effect on the placement of the ImageView; however, the button only appears in the proper position when the button has a non-zero width.
Here is what happens when the app:layout_constraintWidth_percent is increased so that the word "Button" is not cutoff.

Again, the placement of the ImageView should be independent of the width of the button. Instead, the button only appears in the correct position when the app:layout_constraintWidth_percent is set such that the word "Button" is not cutoff.
This is only an issue with negative margins. Positive margins work as expected.
This is a strange problem, so you may want to use one of the other solutions mentioned.
(ConstraintLayout version 2.1.3)


Q: Бот запускается, но не работают стейты, что исправить в коде? Подскажите пожалуйста, бот запускается, но не работают стейты, нажимаешь посмотреть анкету, но ничего не происходит, что исправить в коде?
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import FSMContext

import config
import random

from on_startup_notify import on_startup_notify

from memorystate import Test

from aiogram import types, Bot, executor, Dispatcher

bot = Bot(token=config.BOT_TOKEN, parse_mode=types.ParseMode.HTML)
dp = Dispatcher(bot)
storage = MemoryStorage()

async def on_startup(dispatcher):
    await on_startup_notify(dispatcher)

@dp.message_handler(commands=['start'])
async def startpg(message: types.Message, state: FSMContext):
    startmenu = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
    markup1 = types.KeyboardButton("Посмотреть анкету")
    startmenu.add(markup1)
    await bot.send_message(chat_id=message.chat.id, text='Добро пожаловать!\nНаш бот познакомит Вас с девушками с Вашего города!         Жми на посмотреть анкету!',reply_markup=startmenu)
    await state.set_data(Test.N1)

@dp.message_handler(text=['Посмотреть анкету'], state=Test.N1)
async def osnova(message: types.Message, state: FSMContext):
    await bot.send_message(message.chat.id, 'Введите своё имя:')
    answer = message.text
    await state.update_data(answer1=answer)
    await Test.N2.set()

A: Вот полностью рабочии ваш код. Я убрал не нужные импорты а также добавил memory_storage в диспечер, чтобы он сохранял состояние FSM. Также я написал в некоторых местах коментарии-пояснении к коду, чтобы было вам понятно
from aiogram import types, Bot, executor, Dispatcher
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.state import State, StatesGroup

import random
import logging

# Configure logging
logging.basicConfig(level=logging.INFO)

# Initialize FSM storage
memory_storage = MemoryStorage()

# Initialize bot and dispatcher
bot = Bot(token="BOT TOKEN HERE", parse_mode=types.ParseMode.HTML)
dp = Dispatcher(bot, storage=memory_storage)

class QuestionnaireState(StatesGroup):
    step_1 = State()

@dp.message_handler(commands=['start'])
async def startpg(message: types.Message, state: FSMContext):
    startmenu = types.ReplyKeyboardMarkup(resize_keyboard=True)
    markup1 = types.KeyboardButton("Посмотреть анкету")
    startmenu.add(markup1)
    await message.reply('Добро пожаловать!\nНаш бот познакомит Вас с девушками с Вашего города!\nЖми на посмотреть анкету!', reply_markup=startmenu)

@dp.message_handler(text='Посмотреть анкету')
async def osnova(message: types.Message, state: FSMContext):
    await message.reply('Введите своё имя:', reply_markup=types.ReplyKeyboardRemove()) # types.ReplyKeyboardRemove() здесь нужен для того чтобы удалить reply_markup с надписью "Посмотреть анкету" от глаз пользывателя
    await QuestionnaireState.step_1.set()

@dp.message_handler(state=QuestionnaireState.step_1, content_types=types.ContentTypes.TEXT)
async def questionnaire_state_1_message(message: types.Message, state: FSMContext):
    async with state.proxy() as user_data:
    # Здесь user_data является хранилищем (а точнее словарем), куда можно сохранять определенные данные и вытаскивать если нужно в любой момент
        user_data['name'] = message.text.replace('\n',' ') # Вы возможно спросите - для чего нужен здесь replace, он нужен в случае если юзер умудрится написать свое имя на двух строках, у меня на практике такое было несколько раз

    await message.reply(f"Ваше имя: {user_data['name']}")

    await state.finish() # Оканчиваем наш FSM опрос от пользывателя

if __name__ == '__main__':
    executor.start_polling(dp, skip_updates=True)

RTFM и Удачи Вам!


Q: ¿El hijo se sale del padre en react native en css? Quiero que el hijo no salgo del padre, que se recorte en los bordes del padre sin mover la posición.
En HTML y CSS si pones un div dentro de otro y le pones un left de -50 aunque el número es negativo, el hijo se recorta en los bordes del padre, pero en react native no funciona de la misma manera.

const {width, height}= Dimensions.get('window');

   return (
       <View style={{ flex: 1 }}>
           <View style={Headers.two}>
               <Text style={{
                   left: 50,
                   fontSize:28,
                   color:colors.Primary00,

               }}>
                   Hola
               </Text>
           </View>
           <View style={Bobys.two}>

               <View style={{
                   backgroundColor: '#ea2565',
                   width:width*0.8,
                   height:height*0.7,
                   borderRadius:16,
                   position:'relative'
               }}>

                <LinearGradient
                colors={['#f37032','rgba(234, 37, 101, 0.6)']} style={{
                    width:width*0.8,
                    height:width*0.8,
                    borderRadius: (width*0.8)/2,
                    opacity:0.8,
                    left:-60,
                    bottom:30,
                    position:'absolute'
                }}
                start={{x:0.8, y:1}}
                end={{x:0.2, y:0}}
                >
                </LinearGradient>

               </View>
           </View>
       </View>
   )
}

const style = StyleSheet.create({

});
export default HomeScreen;   ```

A: Al padre se le asigna overflow:hidden y lo recorta


Q: Layout PrimeFaces I have a layout file as follows

            <ui:insert name="Middle top">

This is a Center

            </ui:insert>

            <ui:insert name="Middle center">

This is a Center

            </ui:insert>

But when I run the layout file, nothing is displayed!
I use primefaces 3.5, jsf 2.1.

A: Except center layoutUnit, other layout units must have dimensions defined via size option.
Like this:

        <h:outputText value="Top content." />

        <h:outputText value="Bottom content." />

        <h:outputText value="Left content" />

        <h:outputText value="Right Content" />

        <h:outputText value="Center Content" />

A: If you are going with a layout concept in your project, it should handle like this.
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <f:view contentType="text/html" id="fview">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

        <f:metadata>
            <ui:insert name="metadata" />
        </f:metadata>
        <meta  name="selectedLanguage" content="Lang" lang="#{menuBean.selectedLanguage}"/>
        <h:head>

        <h:body behavior: url(PIE/PIE.htc);">

                       //enter your code

                      //enter your code

                      //enter your code

                     //enter your code

       </h:body>
   </f:view>


Q: How to generate HTML code using Javascript and JSON? I need to create a quiz by parsing a JSON file. The checked answers must be stored in the local storage.
The JSON code:
{
    "quiz": {
        "q1": {
            "question": "Which one is correct team name in NBA?",
            "options": [
                "New York Bulls",
                "Los Angeles Kings",
                "Golden State Warriros",
                "Huston Rocket"
            ],
            "answer": "Huston Rocket"
        },
        "q2": {
            "question": "'Namaste' is a traditional greeting in which Asian language?",
            "options": [
                "Hindi",
                "Mandarin",
                "Nepalese",
                "Thai"
            ],
            "answer": "Hindi"
        },
        "q3": {
            "question": "The Spree river flows through which major European capital city?",
            "options": [
                "Berlin",
                "Paris",
                "Rome",
                "London"
            ],
            "answer": "Berlin"
        },
        "q4": {
            "question": "Which famous artist had both a 'Rose Period' and a 'Blue Period'?",
            "options": [
                "Pablo Picasso",
                "Vincent van Gogh",
                "Salvador Dalí",
                "Edgar Degas"
            ],
            "answer": "Pablo Picasso"
        }
    }
}

The code is below:

    <input type ="submit" name ="submit" value = "Submit answers" onclick = "results()">

I should get this:
enter image description here
Instead I got this, no matter how many times I rewrite the code:
enter image description here
Whay am I doing wrong?
Thank you very much for your help,
Mary.

A: You have a small error with document.createElement("node") - there is no tag node so appending other elements to that is also incorrect. The code could be simplified though as below ( the add to local storage will throw an error in the snippet though )

let data = {
  "quiz": {
    "q1": {
      "question": "Which one is correct team name in NBA?",
      "options": ["New York Bulls", "Los Angeles Kings", "Golden State Warriros", "Huston Rocket"],
      "answer": "Huston Rocket"
    },
    "q2": {
      "question": "'Namaste' is a traditional greeting in which Asian language?",
      "options": ["Hindi", "Mandarin", "Nepalese", "Thai"],
      "answer": "Hindi"
    },
    "q3": {
      "question": "The Spree river flows through which major European capital city?",
      "options": ["Berlin", "Paris", "Rome", "London"],
      "answer": "Berlin"
    },
    "q4": {
      "question": "Which famous artist had both a 'Rose Period' and a 'Blue Period'?",
      "options": ["Pablo Picasso", "Vincent van Gogh", "Salvador Daly", "Edgar Degas"],
      "answer": "Pablo Picasso"
    }
  }
};

// utility prototype to shuffle an array
Array.prototype.shuffle=()=>{
  let i = this.length;
  while (i > 0) {
    let n = Math.floor(Math.random() * i);
    i--;
    let t = this[i];
    this[i] = this[n];
    this[n] = t;
  }
  return this;
};

let list = document.createElement("ul");

Object.keys(data.quiz).forEach((q, index) => {
  // the individual record
  let obj = data.quiz[q];

  // add the `li` item & set the question number as data-attribute
  let question = document.createElement("li");
      question.textContent = obj.question;
      question.dataset.question = index + 1;
      question.id = q;

  // randomise the answers
  obj.options.shuffle();

  // Process all the answers - add new radio & label
  Object.keys(obj.options).forEach(key => {
    let option = obj.options[key];
    let label = document.createElement('label');
        label.dataset.text = option;

    let cbox = document.createElement('input');
        cbox.type = 'radio';
        cbox.name = q;
        cbox.value = option;

    // add the new items
    label.appendChild(cbox);
    question.appendChild(label);
  });

  // add the question
  list.appendChild(question);
});

// add the list to the DOM
document.getElementById('container').appendChild(list);

// Process the checked radio buttons to determine score.
document.querySelector('input[type="button"]').addEventListener('click', e => {
  let score = 0;
  let keys = Object.keys(data.quiz);

  document.querySelectorAll('[type="radio"]:checked').forEach((radio, index) => {
    if( radio.value === data.quiz[ keys[index] ].answer ) score++;
  });

  console.log('%d/%d', score, keys.length);
  localStorage.setItem("answers", score);
})
#container>ul>li {
  font-weight: bold
}

#container>ul>li>label {
  display: block;
  padding: 0.1rem;
  font-weight: normal;
}

#container>ul>li>label:after {
  content: attr(data-text);
}

#container>ul>li:before {
  content: 'Question 'attr(data-question)': ';
  color: blue
}

<input type="button" value="Submit answers" />

A: You need to make minor changes to your nest loop so that the option labels are inserted in the correct location.  See the code snippet where it is marked "remove" and "add" for the changes you need to make.
As @ProfessorAbronsius noted, there isn't an html tag called "node", though that won't stop your code from working.

let data = {"quiz": {"q1": {"question": "Which one is correct team name in NBA?", "options": ["New York Bulls", "Los Angeles Kings", "Golden State Warriros", "Huston Rocket"], "answer": "Huston Rocket"}, "q2": {"question": "'Namaste' is a traditional greeting in which Asian language?", "options": ["Hindi", "Mandarin", "Nepalese", "Thai"], "answer": "Hindi"}, "q3": {"question": "The Spree river flows through which major European capital city?", "options": ["Berlin", "Paris", "Rome", "London"], "answer": "Berlin"}, "q4": {"question": "Which famous artist had both a 'Rose Period' and a 'Blue Period'?", "options": ["Pablo Picasso", "Vincent van Gogh", "Salvador Daly", "Edgar Degas"], "answer": "Pablo Picasso"}}};

let list = document.createElement("ul");
for (let questionId in data["quiz"]) {
  let item = document.createElement("node");
  let question = document.createElement("strong");
  question.innerHTML = questionId + ": " + data["quiz"][questionId]["question"];
  item.appendChild(question);
  list.appendChild(item);
  let sublist = document.createElement("ul");
  item.appendChild(sublist);

  // The problem is here in this nested loop

  for (let option of data["quiz"][questionId]["options"]) {

    item = document.createElement("input");
    item.type = "radio";
    item.name = data["quiz"][questionId];
    var label = document.createElement("label");
    label.htmlFor = "options";

    // remove 1
    // label.appendChild(document.createTextNode(data["quiz"][questionId]["options"]));

    // add 1
    label.appendChild(document.createTextNode(option));

    var br = document.createElement('br');
    sublist.appendChild(item);

    // remove 2
    //document.getElementById("container").appendChild(label);
    //document.getElementById("container").appendChild(br);

    // add 2
    sublist.appendChild(label);
    sublist.appendChild(br);

  }

}
document.getElementById("container").appendChild(list);

function results() {
  var score = 0;
  if (data["quiz"][questionId]["answer"].checked) {
    score++;
  }
}

// Removed because snippets don't allow localStorage
// localStorage.setItem("answers", "score");

<input type="submit" name="submit" value="Submit answers" onclick="results()">

A: Here's the answer to your question. Please let me know if you have any issues.

<input type="submit" name="submit" value="Submit answers" onclick="results()">