text:
Q: Grid Not Taking Full Width I recently got a new computer and installed android studio on it. Now my grid is not taking the full width of the screen. I am almost certain it was taking the full width on my other install of android studio. I do not have a device to test on but on the emulators it is not working.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
    tools:context="io.musicschool.app.NoteTrainerActivity">

    <ImageView
        android:id="@+id/intervalNoteImage"
        android:layout_width="0dp"
        android:layout_height="200dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:scaleType="fitXY"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/c4" />

    <ScrollView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="30dp"
        android:clipToPadding="false"
        android:fillViewport="false"
        android:scrollbars="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/intervalNoteImage"
        app:layout_constraintVertical_bias="0.0">

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

            <GridLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:columnCount="3"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/noteImage"

                >

                <Button
                    android:id="@+id/unison_btn"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_columnWeight="1"
                    android:text="Unison"
                    android:textAllCaps="false"

                    />

                <Button
                    android:id="@+id/min2nd_btn"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_column="1"
                    android:layout_columnWeight="1"
                    android:layout_row="0"
                    android:text="Min 2nd"
                    android:textAllCaps="false"/>

                <Button
                    android:id="@+id/maj2nd_btn"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_column="2"
                    android:layout_columnWeight="1"
                    android:layout_row="0"
                    android:text="Maj 2nd"
                    android:textAllCaps="false" />

                <Button
                    android:id="@+id/min3rd_btn"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_column="0"
                    android:layout_columnWeight="1"
                    android:layout_row="1"
                    android:text="Min 3rd"
                    android:textAllCaps="false"

                    />

                <Button
                    android:id="@+id/maj3rd_btn"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_column="1"
                    android:layout_columnWeight="1"
                    android:layout_row="1"
                    android:text="Maj 3rd"
                    android:textAllCaps="false" />

                <Button
                    android:id="@+id/per4th_btn"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_column="2"
                    android:layout_columnWeight="1"
                    android:layout_row="1"
                    android:text="Per 4th"
                    android:textAllCaps="false"
                    />

                <Button
                    android:id="@+id/aug4th_btn"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_column="0"
                    android:layout_columnWeight="1"
                    android:layout_row="2"
                    android:text="Aug 4th"
                    android:textAllCaps="false"
                    />

                <Button
                    android:id="@+id/dim5th_btn"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_column="1"
                    android:layout_columnWeight="1"
                    android:layout_row="2"
                    android:text="Dim 5th"
                    android:textAllCaps="false" />

                <Button
                    android:id="@+id/per5th_btn"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_column="2"
                    android:layout_columnWeight="1"
                    android:layout_row="2"
                    android:text="Per 5th"
                    android:textAllCaps="false"
                    />

                <Button
                    android:id="@+id/min6th_btn"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_column="0"
                    android:layout_columnWeight="1"
                    android:layout_row="3"
                    android:text="Min 6th"
                    android:textAllCaps="false"
                    />

                <Button
                    android:id="@+id/maj6th_btn"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_column="1"
                    android:layout_columnWeight="1"
                    android:layout_row="3"
                    android:text="Maj 6th"
                    android:textAllCaps="false"
                    />

                <Button
                    android:id="@+id/min7th_btn"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_column="2"
                    android:layout_columnWeight="1"
                    android:layout_row="3"
                    android:text="Min 7th"
                    android:textAllCaps="false"
                    />

                <Button
                    android:id="@+id/maj7th_btn"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_column="0"
                    android:layout_columnWeight="1"
                    android:layout_row="4"
                    android:text="Maj 7th"
                    android:textAllCaps="false"
                    />

                <Button
                    android:id="@+id/oct_btn"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_column="1"
                    android:layout_columnWeight="1"
                    android:layout_row="4"
                    android:text="Octave"
                    android:textAllCaps="false"
                    />
            </GridLayout>
        </LinearLayout>
    </ScrollView>

</android.support.constraint.ConstraintLayout>


text:
Q: How to find the last day of each quarter in a given date period in Python? Now I have a dataframe like this:
(Ticker and date are indexes)
Ticker  Date        Open    Low High    Close   Adj. Close  Shares Outstanding
A       2007-01-25  34.99   34.05      35.48    34.30       NaN
        2007-01-26  34.30   33.46      34.60    34.41       NaN
        ....
        2007-06-27  34.30   34.00      34.40    34.09       NaN
        2007-06-28  33.98   33.68      34.08    33.97       NaN
        2007-07-01  34.08   33.63      34.32    34.01       NaN
B       2007-01-12  34.99   34.05      35.48    34.30       NaN
        ...
        2007-08-27  34.30   33.46      34.60    34.41       NaN
        2007-08-28  34.30   34.00      34.40    34.09       NaN
        2007-09-01  33.98   33.68      34.08    33.97       NaN
        2007-09-02  34.08   33.63      34.32    34.01       NaN
C       2007-03-28  34.99   34.05      35.48    34.30       NaN
        2007-03-29  34.30   33.46      34.60    34.41       NaN
        2007-04-01  34.30   34.00      34.40    34.09       NaN
        2007-04-02  33.98   33.68      34.08    33.97       NaN
        2007-04-03  34.08   33.63      34.32    34.01       NaN

For each ticker, there are stock prices for each day for many years. However, I only want the quarter end prices for each company, and get a dataframe of all companies' quarterly ending price. I also want to separate each quarter for all companies into different dataframe.
For example:
Ticker  Date        Open    Low High    Close   Adj. Close  Shares Outstanding
A       2007-06-30  34.99   34.05      35.48    34.30       NaN
B       2007-06-30  34.30   33.46      34.60    34.41       NaN
        ....
c       2007-06-30  34.30   34.00      34.40    34.09       NaN

Once problem is, due to the fact that the stock market won't open on weekend. So the quarter end for each ticker might not be calendar quarter end. For example, Q2 ends on 6/30, but stock quarter end might be on 6/29. Is there a way I can find the last day of the given date range for each quarter?

A: A simple GroupBy is all you need:
quarter = pd.PeriodIndex(df['Date'], freq='Q', name='Quarter')
result = df.groupby(['Ticker', quarter]).last()

To get data for a specific quarter:
result.loc[('A', '2019Q1')]

A: I would first compute the last row for each ticker in each quarter through groupby and last into a temporary dataframe, then extract the individual dataframes per quarter from it:
tmp = df.groupby(['Ticker', pd.PeriodIndex(df['Date'], freq='Q',   name='Quarter')]

).last().reset_index(level=0)
individual_df = {str(i): df.reset_index(drop=True) for i, df in tmp.groupby(['Quarter'])}

With your example data, it gives:
>>> pprint.pprint(individual_df)

{'2007Q1':   Ticker       Date   Open  Low High  Close  Adj. Close  Shares Outstanding
0      A 2007-01-26  34.30     33.46  34.60       34.41                 NaN
1      B 2007-01-12  34.99     34.05  35.48       34.30                 NaN
2      C 2007-03-29  34.30     33.46  34.60       34.41                 NaN,
 '2007Q2':   Ticker       Date   Open  Low High  Close  Adj. Close  Shares Outstanding
0      A 2007-06-28  33.98     33.68  34.08       33.97                 NaN
1      C 2007-04-03  34.08     33.63  34.32       34.01                 NaN,
 '2007Q3':   Ticker       Date   Open  Low High  Close  Adj. Close  Shares Outstanding
0      A 2007-07-01  34.08     33.63  34.32       34.01                 NaN
1      B 2007-09-02  34.08     33.63  34.32       34.01                 NaN}

redpajama_set_name: RedPajamaStackExchange


text:
Q: In cross_val_score, how is the parameter cv being used differently? I'm trying to figure how to do k-fold cross validation. I was hoping someone could tell me the difference between my two print statements. They give me largely different data and I thought they would be the same.
##train is my training data,
##target is my target, my binary class.

dtc = DecisionTreeClassifier()
kf = KFold(n_splits=10)
print(cross_val_score(dtc, train, target, cv=kf, scoring='accuracy'))
print(cross_val_score(dtc, train, target, cv=10, scoring='accuracy'))

A: DecisionTreeClassifier derives from ClassifierMixin, and so as mentioned in the docs (emphasis mine):
Computing cross-validated metrics

When the cv argument is an integer, cross_val_score uses the KFold or StratifiedKFold strategies by default, the latter being used if the estimator derives from ClassifierMixin.

So here when you are passing cv=10 you are using the StratifiedKFold strategy, whereas when passing cv=kf you are using the regular KFold strategy.
In classification, stratification generally attempts to ensure that each test fold has approximately equal class representation. See Understanding stratified cross-validation on Cross-Validated for some more info.


text:
Q: Using Python, how can I turn a text file list into a 5 column data set where some groups of data have less than 5 lines? Most days, I get a list of jobs that look a little like this:
 1   Group type 1                       # filename = "280321_AnonymisedTestData.txt"
 2   Job Title A
 3   Employer
 4   Location
 5   Z hours per week
 6   Job Title B
 7   Employer
 8   Location
 9   Y hours per week
10   Group type 1
11   Job Title C
12   Employer
13   Location
14   Y hours per week
15   Group type 1
16   Job Title D
17   Employer
18   Location
19   X hours per week

As you can see, most groupings or sets of text have 5 lines or elements, but some, (lines 6 - 9) have only four elements in their set.
I'd like to put this data into a table and to do this I have decided to put the word "General" on a line on it's own in front of the sets with four elements in them.
So far my 'code' looks like this:
with open('280321_AnonymisedTestData.txt') as mylines:
x = 6
while (x < 7):
  for l in mylines:
    if not (l.startswith("Group type 1") or l.startswith("Group type 2") or l.startswith("Group type 3)") l = "General" + "\n" + l

and the Output shows a syntax error at line 5 at the point "l = "General" + ..."
I've got to work out the flow of the program so that the next 3 lines don't get "General" inserted in between them and I intend to put the sets in a data-set, but for now, can I get some advice on where I'm going wrong here?
Thanks for reading.

A: I despair that people can't reason through tasks like this.  Just do it logically, one step at a time.  What data do I HAVE, what data do I NEED, how do I get there?
dataset = []
with open('280321_AnonymisedTestData.txt') as mylines:
    accum = []
    for line in mylines:
        if not accum and not line.startswith("Group"):
            accum = ["General"]
        accum.append( line.strip() )
        if len(accum) == 5:
            dataset.append(accum)
            accum = []

from pprint import pprint
pprint(dataset)

Output:
[['Group type 1', 'Job Title A', 'Employer', 'Location', 'Z hours per week'],
 ['General', 'Job Title B', 'Employer', 'Location', 'Y hours per week'],
 ['Group type 1', 'Job Title C', 'Employer', 'Location', 'Y hours per week'],
 ['Group type 1', 'Job Title D', 'Employer', 'Location', 'X hours per week']]


text:
Q: Parametrization of a sphere such that distances are separable Question
Is there a parameterization $(u, v)$ of a 2-sphere -- i.e. a map projection -- such that the geodesic (great-circle) distance function $d$ is "separable"? By separable I mean that the distance between two points $\mathbf{r}_1=(u_1,v_1)$ and $\mathbf{r}_2=(u_2,v_2)$ can be expressed as
$$d(\mathbf{r}_1, \mathbf{r}_2) = q(f(u_1, u_2) + g(v_1, v_2)),$$
where $q$, $f$, and $g$ are functions.
Motivation
I am working with a numerical technique that exploits this "separability" property of the Euclidean metric with Cartesian coordinates, which I want to extend to spheres.

A: \begin{align}d(r_1,r_2)&=\cos^{-1}(r1\cdot r2), \\
             &=\cos^{-1}(u_1v_1+u_2v_2), \end{align}


text:
Q: C++ Alternative way for: "Incomplete type is not allowed" I already know what this error means and what is causing it. But I need a way to around actually. I need an object to pass in the constructors of other classes, but I need to define the object in its class.
Code what gives the error:
#pragma once
#include "Smash.h"
#include "Window.h"
#include "Input.h"
#include "Game.h"
#include "Render.h"

class Smash {
public:
    Smash smash; ///I NEED THE smash OBJECT TO PASS IN THE OTHER CLASSES, ERROR APPEARS HERE.
    Game game(smash);
    Window win(smash);
    Render render(smash);
    Input input(smash);
};

The smash object is causing the error because it is in the header class itself.
I just need a way to go around or something.
Sorry for bad English, thanks in advance.


text:
Q: How to read from text file and add into an array? I am currently creating a quiz and am trying to get the data in my text file to be read using a quiz but I have hit a stumbling block in seeing how to get it to display the data ?
My Folder :
Windows.Storage.StorageFolder QuestionsFolder =
    Windows.Storage.ApplicationData.Current.LocalFolder;

My Array :
String[] Questions = new String[10];

My Read Questions async function :
async Task ReadQuestions()
{
    try
    {
        StorageFile sampleFile = await QuestionsFolder.GetFileAsync("ms-appx:///Assets/Questions/myFile.txt");
        String Questions = await FileIO.ReadTextAsync(sampleFile);

        // Data is contained
    }
    catch (Exception)
    {

    }
}

Sample Data:
"questions_id","questions"
1,"What is the correct element for Gold ?"
2,"What is the correct element for Hydrogen?"
3,"What is the correct element for Oxygen?

Any ideas on how to complete this so that it loads the questions from the text file and into the array?

A: string[] questions = File.ReadAllLines("ms-appx:///Assets/Questions/myFile.txt");


text:
Q: tikz: arrow with two heads, why? why do i get two heads with this code? how can i get rid of that one at the end?
\documentclass[a4paper,10pt]{article}
\usepackage[latin1]{inputenc}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
  [
    important line/.style={thick,shorten <=4pt,->}
  ]

  \draw[important line] (8.5,1.5) coordinate (A)  edge node[above,sloped] {\tiny text}  (7,2.7)
        coordinate (B) node[] {};

\end{tikzpicture}
\end{document}


text:
Q: Challenging CDF of $\sup_t|B_t|$ ($B_t$ is a Brownian Bridge) Question 1: Let $W_t$ be a Brownian motion. Then how could we prove that $$\Pr\left\{\sup_t|W_t|<b\right\}=1-\frac{4}{\pi}\sum_{j=1}^\infty \frac{(-1)^j}{2j+1} \exp\left\{-\frac{\pi^2(2j+1)^2}{8b^2}\right\}.$$
Question 2: Let $B_t$ be a Brownian Bridge. Then how could we prove that $$\Pr\left\{\sup_t|B_t|<b\right\}=1+2\sum_{j=1}^\infty (-1)^j \exp\left\{-2j^2b^2\right\}.$$
I appreciate any hint!

For question 2: I worked on the distribution of a standard Brownian motions, $W_t$, with $W_1=0$. No success so far.


text:
Q: Can we convert embedded envelope to Emailed Envelope and vise versa in DocuSign We are working on the assignment to optimize the envelope generation process.
We found out that our users are creating Emailed envelope and Embedded Envelope of same documents - Is there any way we can convert Emailed Envelopes to Embedded and vise versa ?

A: At the time of Envelope creation, each recipient is specified as either Embedded (will access the envelope via your application) or Remote (will access the Envelope via link in an Email that DocuSign sends).  [This is specified via the presence or absence of the clientUserId property on each recipient in the Create Envelope API request.] Once an Envelope has been sent, it is not possible to change an Embedded recipient to a Remote recipient, or vice versa.

A: You can delete a recipient and add them back as the different type.  You can also make a recipient BOTH remote and in-person by setting the EmbeddedRecipientStartURL of the signer to "SIGN_AT_DOCUSIGN".


text:
Q: How can I get the value of a T-student distribution? I have been reviewing the documentation of apache commons math and I find that it also calculates distributions, but I can not understand how it works.
I have two values

*

*degrees of freedom = 13

*confidence interval = 0.95

My problem is that it does not yield the value I need,
The objective is:
result = 1.771
import org.apache.commons.math3.distribution.TDistribution

fun calculo(a:Double, b:Double): Double {
    val distf = TDistribution(a,b)
    return distf.getNumericalMean()
}

fun main(args: Array<String>) {
    val ko = calculo(13,0.95)
    println(ko)
}
```

A: You can use the following:
new org.apache.commons.math3.distribution.TDistribution(deg_freedom).
    inverseCumulativeProbability(probability)

Where deg_freedom=13, and probability=0.95.


text:
Q: How to change css read more button I want to change read more button style by adding hover.
I tried some CSS like:
a:hover{
  background-color: #077fad;
  color: #ffffff;
}

or
div.blmore.rmbutton-center.rmbutton-medium:hover{
  background-color: #077fad;
  color: #ffffff;
}

But the first approach changes also  inside the
 paragraph and the other one adds hover to the whole read more button section, except the read more button.
My question is how to select the  inside
 paragraph and how to apply hover effect only to that section?

    Title

Short text

        Read more

A: /* gets applied to any hovered  on the page */
.a:hover {}

/* gets applied to an hovered  on the page
   within the given class combination */
.blmore.rmbutton-center.rmbutton-medium a:hover {}

/* gets applied to any  within an hovered
   element of the given class combination */
.blmore.rmbutton-center.rmbutton-medium:hover a {}

The key is the whitespace between two classes or elements, which allows you to represent the nesting of the markup.


text:
Q: Poco+Entity Framework 4. Where should I add my methods for working with Poco classes? I've tried to use Entity Framework 4 and POCO for my MVC 3 project. May be, I don't understand the main idea of this ORM, but the problem is following:

*

*I added ADO .NET Entity Data Model and make model according to database.

*I clicked Add Code Generation Item and added ADO .NET POCO Entity Generator.

*It makes classes for every database table.

*I want to add some methods to work with data (Add, Update, Delete, GetAll etc) to appropriate models.
For LINQTOSQL I added partial classes and placed them to Models. But now I can't do it because:

a) Models folder has classes with the same names, which was created by POCO.
b) If I place my partial class in the another folder, it will be another namespace - so, such classes won't be partial one.
c) If I place my code in POCO classes, it can be destroyed during update POCO.
How can I use it? Where sould I place my methods for data working?
Is the best way to make for POCO and EF the other project - http://blogs.msdn.com/b/adonet/archive/2010/01/25/walkthrough-poco-template-for-the-entity-framework.aspx?

A: You can place the partial classes in another folder and modify the namespace.

A: First of all you don't have to write your CRUD inside POCO,
There are many places where you can do it like in edmx.cs file or write one more layer which is called as CRUD Services which handles the Database operations using context object.
Now coming to your questions,

*

*Create separate Models folder and place the Model classes in there.
Your Model class may like this,
EmployeeDepartmentModel
{
 prop EmpList List(Emp);
 prop DeptList List(Dept);
 //Emp and Dept are my POCOs
}

*So now I have to fill both of these list(Your CRUD question),
For that, I will Create one method in Controller class(its better to write such logic in some another library, but for time being I suggest you to create in Controller),
FillTheModel()
{
  EmployeeDepartmentModel.EmpList = EDMX.GetAllEmployees;
  EmployeeDepartmentModel.DeptList = EDMX.GetAllDepartments;
}

*Now you can bind this model with your view.

A: I agree with allisewell, but if you really want to add parts to partial classes, give files another name,
e.g. MyPoco.Part2.cs or modify t4 template to name generated files
e.g. Poco.Generated.cs


text:
Q: Using telnetlib - backslash is doubled in 'tn.write' (but not in 'print') - how to send single backslash in my write string I'm trying to telnet a string to a server using Python 2.7 (in Windows).
The application requires backslashes in the string like this: 'E\myMacro\\', so it needs a single backslash within it, and ends with double backslash.
I have been successful using the cmd module but have failed in Python 2.7.
Here's the code:
import telnetlib
host = "myHost"
tn = telnetlib.Telnet(host)
tn.set_debuglevel(100)
data = tn.read_until("server")

myLine = r'E\myMacro'+'\\\\'

tn.write(myLine)
tn.close()

print myLine

This is my output:
Telnet(myHost,23): recv 'Welcome to the server'
Telnet(myHost,23): send 'E\\myMacro\\\\'
E\myMacro\\

I've tried every permutation I can think of to create the string but without success.
Can anyone explain what I'm doing wrong? Why is there a difference between tn.write and print?

A: I've solved my problem, in the end it proved to be a very simple fix:
import telnetlib
host = "myHost"
tn = telnetlib.Telnet(host)
myLine = 'E\myMacro'
tn.write(myLine+'\\\\\r\n')
tn.write("exit\n")


text:
Q: Lubuntu VM broken - X does not start and tty's do not allow commands I'm running Lubuntu 12.04 in a VM under VMWare on Windows 7. After the last reboot, my X does not start, and any attempts to log in to tty's result in no command prompt being opened.
Is there anyway I can get a tty running to start troubleshooting? I'm quite stumped here as I cant really interact with the operating system at all.

A: Since someone decided to vote this question up, I can answer what the problem was:
I had recently installed xmonad and messed with its config, rendering certain keybindings unusable (which I interpreted as X being broken). The problem with tty's malfunctioning still stands, however.


text:
Q: Implementation of two-dimensional integer programming I have a 2x2 integer matrix A and 2d integers vectors b, c. I want to maximize c∙x under the constrains x≥0 and Ax≤b when x ranges over 2d integer vectors. This is a canonical form of two-dimensional integer linear program.
Is there an implementation of an efficient algorithm solving this problem with clear documentation/explanation?
It is easy to find some academic papers but I find it challenging to implement the pseudocode from those papers.


text:
Q: Запись в битов файл Каким образом можно записать последовательность битов (кодов Хаффмана) в файл, чтобы потом можно было однозначно считать их?
Например, при вот такой последовательности битов:
1100000001010

При делении по 8 бит, в файл записывается:
11000000 1010

Тоесть теряется старший бит. На Python у меня имеется такой код, который разбивает строку с "1" и "0", на числа по 8 бит
l = []
for i in range(0, len(s), 8):
    l.append(int(s[i:i+8], 2))

fout = open("otput.txt", "wb")
fout.write(bytearray(l))
fout.close()

A: Чтобы преобразовать строку из нулей и единичек в байты, которые можно записать в файл:
>>> bitstring = '1100000001010'
>>> n = int(bitstring, 2)
>>> n.to_bytes((n.bit_length() + 7) // 8, 'big')
b'\x18\n'

Также легко можно обратно преобразовать (байты в биты) и/или использовать код, который работает на Питоне 2/3 одновременно.

A: Проблема решилась добавлением "0" в начало строки битов, пока длина строки не будет кратна 8.
00011000 00001010

При считывании просто читаем числа и добавляем в начало те же 0, пока количество не достигнет 8


text:
Q: Ignore null values of entity bean while updating the table using Hibernate Stuck on the same problem Is there any method to ignore null values when updating the database in Hibernate?
Whenever you call update(); of Session, it will also update the null values found in the object.
Example:
User user = new User();
user.setUserId(5);
user.setUserName("Maarten");
user.setUserFirstName(null); // but in database this value is not null

session.update( user);

OR
session.saveOrUpdate( user);

The DB will now update the user, but will set the user firstname to null (because it is null in the object).
Is there any way or method in Hibernate to avoid this (I don't want to fire a select/ update query to set the bean)? that it will ignore the null value?

A: hibernate-dynamic-update

The dynamic-update attribute tells Hibernate whether to include unmodified properties in the SQL UPDATE statement.

A: It depends on the abstraction level you wish to control, and the business rules of the object:

*

*Is the field really nullable, or are you simply using it as a DTO? perhaps you need an intermediate object to control null values

*What happens with new users (as in the example)? I should ignore the null value, then which value should be persisted, the default one?

If, anyway, you define your requisites in a lower level, e.g. "do not include null values in update queries", you can use the following:

*

*sql-update annotation here. You can use a custom sql query or procedure to control values

*dynamicUpdate is about changes, not values, so I think it's not really suitable

*Use a EntityListener, and an auxiliary transient field to revert changes if desired.

*Other options: use an interceptor or even create a custom dialect

A: One of the options is, load the bean using get(object) method from the session and then set/change the values. But this comes with an overhead of one extra call to the database. Or you can create a custom query if making an extra call is crucial.
Edit: if bean is cached then get(object) will not be a performance hit.


text:
Q: Define a macro expanding into quotes I need a macro that expands an argument into the string { "argument"}. The following macro seems to do the trick:
\newcommand{\myquote}[1]{\{ "{#1}"\}}

This macro produces for the input xyzzy{\myquote{fubar}} the output xyzzy{ "fubar"} which is what I expect.
However, the macro seizes to work properly once I add the package ngerman to my document by writing in the header \usepackage{ngerman}. Now the input xyzzy{\myquote{fubar}} no longer produces the expected output, but instead results in an error when running latex:
! ngerman: The command "fubar is undefined.

I have tried to modify the macro with
\newcommand{\myquote}[1]{\{ \noexpand"{#1}\noexpand"\}}

This gets rid of the error, but the quotes " are not displayed at all anymore. The observed output becomes xyzzy{ fubar} instead of the expected one (the quotes are simply missing).
How do I need to write the macro that produces the expected output even in the presence of the ngerman package?
[Edit] Clarification: The macro is needed as a marker for a post-processor. Thus, there must not be typographical quotes, but regular double quotes.[/Edit]

A: The ngerman package is obsolete and should be replaced with the babel package loaded with the ngerman option.
As the default font Computer Modern creates still not the up-quotes " but the English closing quotes " you should us the T1 font encoding (you should use it anyway for a German text) and the lmodern fonts (or whatever font you prefer).
Code
\documentclass{article}
\usepackage[ngerman]{babel}
\usepackage{lmodern}% or libertine …
\usepackage[T1]{fontenc}
\newcommand{\myquote}[1]{\{"{#1}"\}}
\begin{document}
\myquote{fubar}
\end{document}

Output

A: The excellent csquotes package provides a convenient interface to all kinds of quotation problems. Main purpose is typographically correct quotation, but it also provides commands to directly access all kinds of quotation characters.
 \documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[ngerman]{babel}
\usepackage{csquotes}

\newcommand{\myquote}[1]{\{\textquotedblleft{#1}\textquotedblleft\}}

\begin{document}

  Text in \enquote{typographischen Anführungsstrichen} oder \myquote{anderen Anführungsstrichen}.

\end{document}


text:
Q: How to display nvarchar datatype image to SSRS Image control? Actually I am new in SSRS(SQL Server Reporting Service). I have to display signature image in SSRS Image Control.The signature image is stored in nvarchar datatype.If you required in other information then ask me.
Thanks in advance.
Danish

A: SSRS Image Control displays string image data fine, with no extra settings.
Just Drag an Image control in the Report and in Image Properties General tab,
choose Select the image source: as Database

and select the appropriate field in the Use this field: option. i.e the db field which holds the image data.
and select proper MIME in  Use this MIME type:. Though any of them should work for you.


text:
Q: Filling textboxes with strings I have a windows form application that has a slew of textboxes that I fill using a bunch of strings. My question is...the code works fine but it seems like a lot of wasteful typing. Can you fill the textboxes from the strings in a loop functions? Matching up the textbox with the approriate string?
Here is what I have.
  var client = new WebClient { Credentials = new NetworkCredential(username, password) };
        var financials = client.DownloadString("https://api.intrinio.com/data_point?identifier="+conver+"&item=beta,marketcap,52_week_high,52_week_low,adj_close_price,short_interest,analyst_target_price,next_earnings_date,percent_change,yr_percent_change,implied_volatility, dividendyield,listing_exchange,sector,average_daily_volume");
        var jss = client.DownloadString("https://api.intrinio.com/companies?identifier=" + conver + "");
        JObject rss = JObject.Parse(jss);
        JObject fin = JObject.Parse(financials);
        string RRSTITLE = (string)rss["legal_name"];
        string beta = (string)fin.SelectToken("data[0].value");
        string marketcap = (string)fin.SelectToken("data[1].value");
        string weekhigh = (string)fin.SelectToken("data[2].value");
        string weeklow = (string)fin.SelectToken("data[3].value");
        string adj_close = (string)fin.SelectToken("data[4].value");
        string short_interest = (string)fin.SelectToken("data[5].value");
        string analyst_target = (string)fin.SelectToken("data[6].value");
        string earnings = (string)fin.SelectToken("data[7].value");
        string percent_change = (string)fin.SelectToken("data[8].value");
        string yr_percent_change = (string)fin.SelectToken("data[9].value");
        string implied = (string)fin.SelectToken("data[10].value");
        string divyield = (string)fin.SelectToken("data[11].value");
        string exchange = (string)fin.SelectToken("data[12].value");
        string sector = (string)fin.SelectToken("data[13].value");
        string volume = (string)fin.SelectToken("data[14].value");
        company_textbox.Text = RRSTITLE;
        beta_box.Text = beta;
        marketCap_box.Text = marketcap;
        wekhighbox.Text = weekhigh;
        weklowbox.Text = weeklow;
        adjclosebox.Text = adj_close;
        shortbox.Text = short_interest;
        targetestbox.Text = analyst_target;
        next_earnings.Text = earnings;
        Close_box.Text = percent_change;
        percentytd.Text = yr_percent_change;
        implivolbox.Text = implied;
        divyieldbox.Text = divyield;
        exchangebox.Text = exchange;
        sectorbox.Text = sector;
        daily_Volume_text.Text = volume;

A: Like @Jacky said, the straight forward answer is no. But a really hacky way would be to create two Dictionaries. Something like this
Dictionary<string, TextBox> TextBoxLookup = new Dictionary<string, TextBox>();
Dictionary<string, string> ValueLookup = new Dictionary<string, string>();

TextBoxLookup["beta"] = beta_box;
TextBoxLookup["marketcap"] = marketCap_box;
TextBoxLookup["weekhigh"] = wekhighbox;

ValueLookup["beta"] = beta;
ValueLookup["marketcap"] = marketcap;
ValueLookup["weekhigh"] = weekhigh;

foreach(string key in TextBoxLookup.Keys)
{
   TextBoxLookup[key].Text = ValueLookup[key];
}

You'll have to add each textbook and its value to their respective dictionaries with the same key and iterate through the assignment foreach block everytime you need to assign.
Does this help?


text:
Q: How to convert key:value pair in json as key = value in mule I am trying to form where clause from the JSON file. I want to fetch the key:value pair from the where part of below input and convert it into key = value
Input:
{
   "Table":{
      "TableName":"Employee",
      "Columns":[
         "ID",
         "Name"
      ],
      "Where":{
         "ID":"A-0001",
         "Name":"xyz"
      }
   }
}

Expected Output:
I want to get where ID = 'A-0001' and Name = 'xyz'
I am using mule 4. Please help.
Thanks in advance

A: Building dynamic SQL? I would suggest avoiding that and sticking to parameterized queries.
I would strongly urge you to use this path: https://docs.mulesoft.com/connectors/db/database-connector-examples#use-input-parameters-to-protect-database-queries
It would be really easy to make this parameterized because all you'd have to do is passing in payload.Table.Where as your parameterized object.
If you're pulling this from some kind of trusted source and have to do things this way I suppose you could ignore the columns array and do it this way pretty easily:
%dw 2.0
output application/json
---
if (payload.Table.Where?)
    "where " ++ ((payload.Table.Where pluck "$($$) = '$($)'") reduce ($$ ++ " and " ++ $))
else
    ""

I'm sure there is a better way to do this, but if you wanted to still use the columns array you could also do this.
%dw 2.0
output application/json
---
"where " ++ (
    payload.Table.Columns reduce ((col, wClause="") ->
        if (not payload.Table.Where[col]?) wClause
        else wClause ++ (if (wClause != "") " and " else "") ++ ("$(col) = '$(payload.Table.Where[col])'")
    )
)

A: Another take at a similar approach.
%dw 2.0
output application/json
---
"where " ++ ((payload.Table.Where mapObject {
     ($$): (($$) ++ "=" ++ "'" ++ ($) ++ "'")
}) pluck ($) joinBy " and ")


text:
Q: How to get current touch point and previous touch point in UIPanGestureRecognizer method? I am new to iOS, I am using UIPanGestureRecognizer in my project. In which I have a requirement to get current touch point and previous touch point when I am dragging the view. I am struggling to get these two points.
If I use touchesBegan method Instead of using UIPanGestureRecognizer, I could get these two points by the following code:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    CGPoint touchPoint = [[touches anyObject] locationInView:self];
    CGPoint previous=[[touches anyObject]previousLocationInView:self];
}

I need to get these two points in UIPanGestureRecognizer event fire method. How can I achieve this? please guide me.

A: When you link an UIPanGestureRecognizer to an IBAction, the action will get called on every change. The gesture recognizer also provides a property called state which indicates if it's the first UIGestureRecognizerStateBegan, the last UIGestureRecognizerStateEnded or just an event between UIGestureRecognizerStateChanged.
To solve your problem, try it like the following:
- (IBAction)panGestureMoveAround:(UIPanGestureRecognizer *)gesture {
    if ([gesture state] == UIGestureRecognizerStateBegan) {
        myVarToStoreTheBeganPosition = [gesture locationInView:self.view];
    } else if ([gesture state] == UIGestureRecognizerStateEnded) {
       CGPoint myNewPositionAtTheEnd = [gesture locationInView:self.view];
       // and now handle it ;)
    }
}

You may also have a look at the method called translationInView:.

A: If you don't want to store anything you can also do this :
let location = panRecognizer.location(in: self)
let translation = panRecognizer.translation(in: self)
let previousLocation = CGPoint(x: location.x - translation.x, y: location.y - translation.y)

A: You can use this:
CGPoint currentlocation = [recognizer locationInView:self.view];

Store previous location by setting current location if not found and adding current location everytime.
previousLocation = [recognizer locationInView:self.view];

A: You should instantiate your pan gesture recognizer as follows:
UIPanGestureRecognizer* panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];

Then you should add panRecognizer to your view:
[aView addGestureRecognizer:panRecognizer];

The - (void)handlePan:(UIPanGestureRecognizer *)recognizer method will be called while the user interacts with the view. In handlePan: you can get the point touched like this:
CGPoint point = [recognizer locationInView:aView];

You can also get the state of the panRecognizer:
if (recognizer.state == UIGestureRecognizerStateBegan) {
    //do something
} else if (recognizer.state == UIGestureRecognizerStateEnded) {
   //do something else
}

A: There is a function in UITouch to get the previous touch in the view

*

*(CGPoint)locationInView:(UIView *)view;

*(CGPoint)previousLocationInView:(UIView *)view;


text:
Q: Performing path animation in custom view So I have a custom view where I am trying to perform a drawing animation using the Path methods of moveto() and lineto(). I have an array of Points that I iterate through and call invalidate() at every iteration. In onDraw the path is drawn with drawPath(). Of course onDraw is not called until the loop is done.  I believe I need to perform the iterations in a background thread. But at the same time I have read that it is bad practice perform UI changes in background thread. How can I can I redraw in every iteration?
@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawPaint(mBackgroundPaint);
    canvas.drawPath(mPath, mStrokePaint);
}

public void drawPoints(){

    mPath = new Path();
    for (Stroke stroke : mStrokes){

        mDuration = stroke.getStrokeDuration();
        mInitialX = stroke.getInitialX();
        mInitialY = stroke.getInitialY();
        mPath.moveTo(mInitialX, mInitialY);
        invalidate();

        mPoints = new ArrayList<Point>();
        mPoints = stroke.getStrokePoints();
        int s = mPoints.size();

        long delayTime = mDuration / (long) s;

        for(Point point : mPoints){
            mX = point.getX();
            mY = point.getY();

            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mPath.lineTo(mX, mY);
                    // want to call invalidate to redraw canvas
                    invalidate();
                }
            }, delayTime);

        }

    }

}

A: I had the same prob, put this into your onDraw:
((Main) context).runOnUiThread(new Runnable() {
    @Override
    public void run() {
        CustomView.this.invalidate();

    }
});


text:
Q: TestCafe cant find a  element if the text contains a space I have the next code that asserts if I can find a bank account in a cell. I found out that it's not working when the text in the cell contains a space after the text.
    this.bankAccounts = Selector('td[data-cy="listAccountNumber"]');

async checkBankAccount(accountNumber, currencyCode, name){
    const formatedAccount = formatBankAccount(accountNumber, currencyCode);
    const bankCell = Selector(this.bankAccounts).withText(formatedAccount);

    await t
        .expect(bankCell.exists).ok("Should create: " + name +
            " bank. Could not find bank: " + formatedAccount);
}

For example, the previous method won't find the next cell if given accountNumber "CY25 7121 9716 3791 8645 3263 6242"
CY25 7121 9716 3791 8645 3263 6242

But it will find it if my cell was like:
CY25 7121 9716 3791 8645 3263 6242


text:
Q: Android: Failed to resolve: com.github.vpotvin:caldroidx:1.0 I am trying to integrate the CaldroidX library in my app (https://github.com/vpotvin/CaldroidX). However, I receive the below error:

Failed to resolve: com.github.vpotvin:caldroidx:1.0

This seems strange, as I believe I have followed the instructions correctly:

*

*Specified maven { url 'https://jitpack.io' } in the project-level build.gradle.

*Specified implementation 'com.github.vpotvin:caldroidx:1.0' in the app-level build.gradle.

Below is my project-level build.gradle:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        mavenCentral()
        maven { url 'https://jitpack.io' }
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.2.2"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
        jcenter() // Warning: this repository is going to shut down soon
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Below is my app-level build.gradle:
plugins {
    id 'com.android.application'
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.example.hijriconversioncalendar"
        minSdkVersion 26
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation 'com.github.vpotvin:caldroidx:1.0'
    implementation 'androidx.appcompat:appcompat:1.3.0'
    implementation 'com.google.android.material:material:1.4.0'

    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

A: You have added the maven repository at wrong place, change your project level gradle file like,
// Top-level build file where you can add configuration options common to all
sub-projects/modules.
buildscript {
repositories {
    google()
    mavenCentral()

}
dependencies {
    classpath "com.android.tools.build:gradle:4.2.2"

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    google()
    mavenCentral()
    maven { url 'https://jitpack.io' }
    jcenter() // Warning: this repository is going to shut down soon
    }
  }

task clean(type: Delete) {
delete rootProject.buildDir
}


text:
Q: minidlna and samsung tv file format doesn't support I have PC with XUbuntu 12.04 and Samsung 27A950, so I want to use my PC like dlna server.
But I can run file of any format on my TV, get error: "File format doesn't support". I try to open *.avi, *.mkv and *.jpg files the same result.
In error log I can see:
[2013/06/27 12:34:03] upnphttp.c:1907: error: Error opening /home/family/media/file1.mkv
[2013/06/27 12:34:06] upnphttp.c:1907: error: Error opening /home/family/media/file2.avi

So, I have no idea why it doesn't work. Any suggestions?
miniDLNA version:
Version 1.24.1-stedy

Config file is default, only few directories added.
With version of the default Ubuntu repository was the same. Some time ago I tried mediatomb, had the same error.

A: Here are the settings of our /etc/minidlna.conf to stream audio, video, or pictures without issue to our Samsung UE40ES6100 smart TV:
Port
Make sure you stream on the port your TV listens to. You may also have to make sure that this port is accessible for your TV from your router. In case the port is wrong your TV may not see miniDLNA at all.
port=9500

Media directories
Put here the directories to add to miniDLNA's media library. These directories may need consideral time for scanning on the first run. Unfortunately there is no feedback from miniDLNA when it is finished with scanning. Make sure the group minidlna has read acess to these directories. Replace the full path and directory name with your's.
media_dir=V,/<path>/<Videos>
media_dir=A,/<path>/<Music>
media_dir=P,/<path>/<Pictures>

Data base and log directory
This is where miniDLNA stores it's database and log files. It's crucial to give the group minidlna write permission to the path you give here.
db_dir=/home/<user>/.config/minidlna # or any other directory
log_dir=/home/<user>/.config/minidlna # or any other directory

Model number
This may not be needed, but our TV did not recognize miniDLNA unless we gave it the model number AllShare here.
serial=
model_number=AllShare1.0

Other settings
These settings were set per default but I will post them here just in case they are not.
network_interface=eth0 # change appropriately, e.g. wlan0 if you stream from wireless
friendly_name=miniDLNA # how miniDLNA is named on the TV
enable_tivo=no
strict_dlna=no
notify_interval=900

A: While .jpg worked fine for me (with an UE55ES TV), most movie/video files do not via DLNA (but only if served locally, e.g. using an USB stick). This seems to be a limitation of the TV device, as you find it reported frequently.
So miniDLNA is not really an option if you want to serve most videos (moreover, it sometimes manages to almost bring the entire system down by completely filling up the partition /var/log is located on: opening too many http connections and then complaining about it in its logs, it reached almost 50 GB log file size on my machine, so I had to stop it).

You might want to take a look at a different DLNA server, like e.g. Serviio, which uses FFMpeg to transcode media files to a format understood by the device. I just tried to set this up on my machine yesterday: unfortunately, Canonical decided to drop FFMpeg from the repositories (you can still do an apt-get install ffmpeg successfully, but that delivers a different software including some "ffmpeg compatibility" stuff, which seems incompatible with Serviio. On their site, however, they explain how to build FFMPeg from the sources − if that's an option for you. Looks like too much pain for the normal user to me, though.
Edit: Serviio seems to work fine with my UE55ES out-of-the-box, even with the Generic profile. I followed this German HowTo to install it. As for FFMPeg, there are static binaries available for download. Simpy downloading the tarball, and extracting the two files to /usr/local/bin did it for me.
Other possible alternatives to take a look at (none of them I tested yet):

*

*Rygel (can at least be installed via PPA, transcoding supported). According to a German Howto, it also seems to be available in the regular repos, so you should be able to simply apt-get install rygel (plus optionally rygel-preferences for a management frontend and rygel-mediathek as well as rygel-tracker for some more plugins). But as the support for Samsung TVs seems to have been added only recently, the version in Precise's repository does not work for you − the "official PPA" might to be favored.

*Mediatomb: As Samsung TVs (at least those of 2012) are not complying with RFC2396, this requires a manual installation as well to be used with them. May sound a big deal at first, but as described at gnulnx.net it seems to be quite straight-forward. (A simpler method is described here, if you want to test it: it just involves editing a text file)

*PS3MediaServer (aka PMS) you already mentioned to be working fine, so I probably will have to take a closer look at it, too ;)

Other solutions like e.g. XBMC seem to heavy-weighted to me for the purpose. An interesting overview for other alternatives can be found e.g. at MakeUseOf.
To check whether your uPnP server works in general, you can e.g. use eezUPnP on your Ubuntu workstation.

A: Know this an old post, but someone might search it and help them with MiniDLNA
I run Ubuntu 1204lts.
Had minidlna working sweet.
Then installed owncloud and it broke my minidlna install - TV said file not supported - XBMC similar errors.  Would just list media, not play anything.
Once i removed owncloud, I also removed, libav-tools, libavfilter2, libavdevice53 - miniDLNA working again.


text:
Q: Basic concept of ideal Let $I$ be an ideal of commutative ring $R$ which is not $R$ ($I \neq R$).
Then there exist an element $r$ such that in $R$, but not in $I$.
However, $I$ is closed under multiplication, so $rI$ is in $I$.
Then $r*1_R$ is also in $I$, then $I$ contains $r$.
Where am I wrong? I think it is very basic concept, but I'm confused..
Ring should not be include $1$, but in my book, assumed to be included by default..
Can you give me some hint..? haha

A: $I$ is closed under multiplication with all of $R$, so for any $i\in I$, we have $ri\in I$ (in other words, $rI\subseteq I$).
However, $1_R\notin I$, so there is no reason to assume that $r1_R\in I$; the above statement doesn't cover this case. In fact, this calculation proves that $1_R\in I\iff I=R$.

A: You're confusing the ideal and its elements.
Indeed if $I \subsetneq R$, it exists an element $r \in R$ with $r \notin I$. But then $rI$ is an ideal namely $rI = \{r i \mid i \in I\}$ not and element of $I$.
Note: you may even be confusing $I$ with the identity element $I_R$ for the multiplication of $R$.


text:
Q: Connect to MariaDB server fails although port seems to be open Hello I am trying to connect to an external MariaDB server. The configurations files on this installations are in a different place but I managed to find my way around.
The installation im using is:
Server version: 10.1.41-MariaDB-0ubuntu0.18.04.1 Ubuntu 18.04

I have added the external user:
MariaDB [(none)]> select user, host from mysql.user;
+---------+---------------+
| user    | host          |
+---------+---------------+
| username| my-ip         |
| username| localhost     |
| root    | localhost     |
+---------+---------------+

And I have found the bind-address in a very strange directory configuration file in /etc/mysql/mariadb.conf.d/50-server.cnf along with other strangely named configuration files. But it was the only file in the /etc/mysql/ directory with a [mysqld] section. In previous mysql installations I found it in the /etc/init.d/ directory. There is no my.cnf in the etc or home directory.
50-client.cnf  50-mysql-clients.cnf  50-mysqld_safe.cnf  50-server.cnf
# localhost which is more compatible and is not less secure.
#bind-address       = 127.0.0.1
bind-address = my-ip
port = 3306

Here are my defaults:
$ mysqld --print-defaults
mysqld would have been started with the following arguments:
--user=mysql --pid-file=/var/run/mysqld/mysqld.pid --socket=/var/run/mysqld/mysqld.sock --port=3306 --basedir=/usr --datadir=/var/lib/mysql --tmpdir=/tmp --lc-messages-dir=/usr/share/mysql --skip-external-locking --bind-address=my-ip --port=3306 --key_buffer_size=16M --max_allowed_packet=16M --thread_stack=192K --thread_cache_size=8 --myisam_recover_options=BACKUP --query_cache_limit=1M --query_cache_size=16M --log_error=/var/log/mysql/error.log --expire_logs_days=10 --max_binlog_size=100M --character-set-server=utf8mb4 --collation-server=utf8mb4_general_ci

I enabled port using ufw command:
sudo netstat -plutn | grep 3306
[sudo] password for username:
tcp        0      0 myip:3306      0.0.0.0:*               LISTEN      15696/mysqld
And port is visible from outside though the server seems to block ping based port scanning so I hade to use a specific nmap option:
$ nmap -p 3306 -Pn server-ip

Starting Nmap 7.60 ( https://nmap.org ) at 2019-11-11 13:04 CET
Nmap scan report for no-reverse-yet.local (server-ip)
Host is up.

PORT     STATE    SERVICE
3306/tcp filtered mysql

Nmap done: 1 IP address (1 host up) scanned in 2.14 seconds
mycomputer:~$ nmap -p 3306 server-ip

Starting Nmap 7.60 ( https://nmap.org ) at 2019-11-11 13:06 CET
Note: Host seems down. If it is really up, but blocking our ping probes, try -Pn
Nmap done: 1 IP address (0 hosts up) scanned in 3.14 seconds
So I dont see why when I try to connect to it, it still does not work?
pi@raspberrypi:~ $ mysql -h server-ip -P 3306 -u username -p
Enter password:
ERROR 2002 (HY000): Can't connect to MySQL server on 'server-ip' (115)
Using tcpdump during the attempt to connect gives me this:
$ sudo tcpdump -i eth0 port 3306
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth0, link-type EN10MB (Ethernet), capture size 262144 bytes
13:29:42.998728 IP myipaddress > no-reverse-yet.local.mysql: Flags [S], seq 2240116053, win 29200, options [mss 1460,sackOK,TS val 785971424 ecr 0,nop,wscale 7], length 0
It shouldnt by UFW filtering my ports:
$ sudo ufw status
Status: active

To                         Action      From
--                         ------      ----
3306/tcp                   ALLOW       Anywhere
3306                       ALLOW       my-ip
3306/tcp (v6)              ALLOW       Anywhere (v6)
solution:
just like @oxfn suggested i put host as % and I also put bind address to 0.0.0.0. This allowed me to connect to the server. What I believe the problem was is that the previous version of mysql verified my by IP and this version verified me by any given URL which you can see below the IP on this page https://myip.is/ . In my case, my ISP gave my router for some reason a URL.
Thank you guys for your suggestions I would not have done it otherwise!


text:
Q: How to sort objects by a property in C language I need to know how to change a property of each object in an array and sort that objects according to that property value. highest to lowest.
this is the program
typedef struct
{
    char name[100];
    int comp, math, phys, rank;
    int total;

} student;

and created an array of students
student student1 ={"student1", 1, 1, 1, 0, 3}
student student ={"student2", 1, 2, 1, 0, 4}

student studentList[0] = student1;
student studentList[1] = student2;

now I have an array of students
how to change the "rank" of each object in the array, the highest total should has a rank of 1,
the code should be dynamic, means if the array length was 2 or 100, it doesn't matter
// change rank property of each object in a list

// print all students sorted by rank

A:
change a property of each object in an array

Assuming this is your array: studentList[NUM_OF_STUDENTS] you do studentList[student_you_want_to_change].rank = new_rank;

sort that objects according to that property value. highest to lowest.

Simplest way would be bubble sort:
  for(i = 0; i < NUM_OF_STUDENTS; i++){
     for(j = 0; j < NUM_OF_STUDENTS; j++){
          if(studentList[i].rank > studentList[j].rank){
                // swap
                tmp = studentList[j].rank;
                studentList[j].rank = studentList[i].rank;
                studentList[i].rank = tmp;
           }
       }
   }

note that bubble sort is the simplest to implement but it is not the fastest (you can use qsort or merge-sort instead if you would like

the code should be dynamic, means if the array length was 2 or 100, it doesn't matter

If so, use a pointer and after you get the size - create your array: `
scanf("%d",&NUM_OF_STUDENTS);    /* get size of array */
studentList = malloc(sizeof(student) * NUM_OF_STUDENTS);


text:
Q: ColdFusion: Passing a variable from an include back up to the parent page I'm using Mura CMS 7.1, which uses ColdFusion. On a page template I have some markup and am including a template file that has code for displaying calendar events from an outside source. When there are no events, I'm currently displaying a message as such. Instead however, I'd like to hide this entire section on the page template itself. Problem is I need to pass some sort of value from the include file back to the page template so I can set inline CSS to either display block/none for this section, and I'm not sure how to do this. My page template code is:

What's coming up?

                <cfinclude template="inc/homeEvents.cfm" />

And the calendar code is all inside of the 'homeEvents.cfm' file. I need to be able to alter that inline css 'display' property with a value that I set in 'homeEvents.cfm'. How would I go about doing this so that the value is accessible from the page template?

A: I'm not suggesting this is good practice, but you could use a style block from code inside your included cfm. eg:
<cfsavecontent variable="variables.styleBlock">

</cfsavecontent>
<cfhtmlhead text="#variables.styleBlock#" />

You could also use javascript to change the style afterwards, but with that there's more chance of a delay where the user sees the 'wrong' layout before the style is eventually applied.

A: This is a formatted comment.
I know that variables in the calling page are available in the included page.  This leads me to believe that variables in the included page are available to the calling page.  Here is a simple test of that theory.
CallingPage.cfm
<cfinclude IncludedPage.cfm>
<cfdump var = "#x#">

IncludedPage.cfm
<cfset x = 1>

Browse CallingPage.cfm and see what happens.  If you get an error for an undefined variable, there is always to good old session scope.

A: Please see the comment from @haxtbh. I was able to accomplish the desired task using JS directly within the include.


text:
Q: MassTransit bypass retry policy when non transient error occurs What is the guidance to short circuit retry policy on a non transient error.
Scenario.
Using MassTransit v3 attached to RabbitMq.
A simple retry policy try 5 times setup in the pipeline.
In the Consume for the message, a non recoverable error occurs,  rather than throwing an exception and retrying another 4 times I'd like to  move this message to the error queue.

A: You can use:
Retry.Except<BadException>().Immediate(5);

A: The solution from Chris did not work for me for some reason. Maybe I was making this call from the wrong context. The only thing that worked was to make two UseRetry calls:
            configurator.ReceiveEndpoint(host, _config.QueueName, ec =>
            {
                ...

                // Configure retries to immediately fail on permanent consumer faults
                ec.UseRetry(r => r.None().Handle<ConsumerPermanentFaultException>());

                // Configure all other retries as incremental
                ec.UseRetry(r =>
                {
                    r.Incremental(_config.RetryCount, _config.RetryInterval, _config.RetryIntervalIncrement)
                        .Ignore<ConsumerPermanentFaultException>();
                });

                // Load consumers from the container
                ec.LoadFrom(consumerContainer);
            });


text:
Q: Is the behaviour of if(++i) ++i defined? Suppose I have this code:
int main(void)
{
    int i = rand();
    if (++i) ++i;
    return i;
}

Is the behaviour defined here? I know that i = ++i is undefined and the second line in main contains a similar thing.  The rand() call is there to stop the compiler from optimising out what I think is the offending line.

A: From C standard
The following are the sequence points described in:-

....
  Between the evaluation of a full expression and the next full expression to be evaluated. The following are full expressions: an initializer that is not part of a compound literal (6.7.9); the expression in an expression statement (6.8.3); the controlling expression of a selection statement (if or switch) (6.8.4); the controlling expression of a while or do statement (6.8.5); each of the (optional) expressions of a for statement (6.8.5.3); the (optional) expression in a return statement.

So yes this is valid. I am just showing you the standard quote so that you feel satisfied that rule is stated somewhere.

A: Yes, this is well-defined.
There's a sequence point after the evaluation of the expression ++i in the if condition.

A: This is well defined.
The condition of the if is first evaluated.  The side effect of incrementing i happens, then the incremented value of i is used as the controlling expression of the if.  In the event this evaluates to true, there is a sequence point before evaluating the statement in the body of the if, which is ++i.


text:
Q: UITableView footerView with button, button doesn't work I'm trying to create a custom view for my UITableView footerView that has a button in it.  I can see it there, but when I touch it, nothing happens... can you see what's wrong here:
- (void)viewDidLoad {
    [super viewDidLoad];

    if(self.tableView.tableFooterView == nil) {
        //allocate the view if it doesn't exist yet
        UIView *footerView  = [[UIView alloc] init];

        //create the button
        UIButton *addNewBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        //the button should be as big as a table view cell
        [addNewBtn setFrame:CGRectMake(0, 0, 320, [AddMerchantTVC cellHeight])];

        //set title, font size and font color
        [addNewBtn setTitle:@"Add New" forState:UIControlStateNormal];
        [addNewBtn.titleLabel setFont:[UIFont boldSystemFontOfSize:20]];
        [addNewBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [addNewBtn addTarget:self action:@selector(addNew:) forControlEvents:UIControlEventTouchUpInside];

        UIImageView *cellGradient = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cellGradient.png"]];
        cellGradient.frame = CGRectMake(0, 54, 320, 16);
        [footerView addSubview:cellGradient];

        //add the button to the view
        [footerView addSubview:addNewBtn];
        footerView.userInteractionEnabled = YES;
        self.tableView.tableFooterView = footerView;
        self.tableView.tableFooterView.userInteractionEnabled = YES;

        [footerView release];
        [cellGradient release];
}

- (void)addNew:(id)sender {
    // This is never called
    NSLog(@"Touched.");
}

A: - (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 50.0f;
}

put this method in your class your problem will solve.....

A: You're not setting the footerView's frame.  Set the frame of the footerView to be at least as high as the button otherwise the touches don't get passed down to the button.

A: its worked for me i just add
footerView.frame =CGRectMake(0, 300, 100, 100);

A: You need to set the tableView's sectionFooterHeight property before the call to viewForFooterInSection occurs (can't do it inside the viewForFooterInSection method).

A: Create a subclass of UIView and include these methods:
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    return [super hitTest:point withEvent:event];
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    return [super pointInside:point withEvent:event];
}


text:
Q: Cannot induce exit code 3 from psql The docs page states (emphasis mine)

Exit Status
psql returns 0 to the shell if it finished normally, 1 if a fatal error of its own occurs (e.g. out of memory, file not found), 2 if the connection to the server went bad and the session was not interactive, and 3 if an error occurred in a script and the variable ON_ERROR_STOP was set.

However, I seem to be unable to induce exit code 3.
bash-4.2$ uname -a
Linux mvpg-centos-76.vagrantup.com 3.10.0-957.21.3.el7.x86_64 #1 SMP Tue Jun 18 16:35:19 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
bash-4.2$ psql --version
psql (PostgreSQL) 10.12
bash-4.2$ psql -v ON_ERROR_STOP=1 -c 'select 1/0;'
ERROR:  division by zero
bash-4.2$ echo $?
1
bash-4.2$

I've also reproduced this behaviour on FreeBSD 11.3 and Darwin 19.3. Am I misunderstanding the documentation or using a faulty syntax?

A: Got it to work a few ways:
postgres@ironforge:~$ cat onerrorstop.sql
\set ON_ERROR_STOP on
select * from gurumeditationerror;
postgres@ironforge:~$ psql -f 'onerrorstop.sql'
psql:onerrorstop.sql:2: ERROR:  relation "gurumeditationerror" does not exist
LINE 1: select * from gurumeditationerror;
                  ^
postgres@ironforge:~$ echo $?
3
postgres@ironforge:~$

and:
postgres@ironforge:~$ echo "\set ON_ERROR_STOP on
> select * from smellyfarts;" | psql
ERROR:  relation "smellyfarts" does not exist
LINE 1: select * from smellyfarts;
                  ^
postgres@ironforge:~$ echo $?
3
postgres@ironforge:~$

and:
postgres@ironforge:~$ cat onerrorstop.sql
select * from gurumeditationerror;

postgres@ironforge:~$ psql -v ON_ERROR_STOP=on -f 'onerrorstop.sql'
psql:onerrorstop.sql:1: ERROR:  relation "gurumeditationerror" does not exist
LINE 1: select * from gurumeditationerror;
                      ^
postgres@ironforge:~$ echo $?
3
postgres@ironforge:~$

Version:

    postgres@ironforge:~$ psql --version
    psql (Post greySKULL) 9.5.19
    postgres@ironforge:~$


text:
Q: Specialize a Template Function to Generate a Compile-Time Error How does one specialize a template function to generate an error at compile-time if a user attempts to call said function with a given template parameter?
I was able to get this behavior for a template class by using the following idiom...
template <typename T>
class MyClass< std::vector<T> >;

The basic signature of the function which I am trying to modify is...
template <typename T>
T bar(const int arg) const {
  ...
}

If I use the same paradigm that I used to disallow certain template classes...
template<>
std::string foo::bar(const int arg) const;

I can generate a linker error, which I suppose is more desirable than a runtime error, but still not really what I'm looking for.
Since I am not able to use C++11, I cannot use static_assert, as described here. Instead, I am trying to use BOOST_STATIC_ASSERT like so...
template<>
std::string foo::bar(const int arg) const {
  BOOST_STATIC_ASSERT(false);
  return "";
}

However, this generates the following compile-time error, even when I am not trying to call an instance of the function with the template parameter I am attempting to disallow...
error: invalid application of 'sizeof' to incomplete type 'boost::STATIC_ASSERTION_FAILURE<false>'

I found this post, but it doesn't really offer any insight that I feel applies to me. Can anyone help?

A: Use boost::is_same to generate a compile-time boolean value that can then be used with BOOST_STATIC_ASSERT to perform the check.
template <typename T>
T bar(const int)
{
  BOOST_STATIC_ASSERT_MSG((!boost::is_same<T, std::string>::value),
                          "T cannot be std::string");
  return T();
}

bar<int>(10);
bar<std::string>(10);  // fails static assertion

Live demo

A: It seems C++ don't allow specialize template member function. So if you want to use same interface, you should use other technology. I'd like to use trait_type to implement this.
template <class T>
struct is_string : false_type {};
template <>
struct is_string<string> : true_type {};

template <typename T>
class MyClass {
 private:
  T bar(const int arg, false_type) const {
    return T();
  }

  std::string bar(const int arg, true_type) const {
    return "123";
  }
 public:
  T bar(const int arg) const {
    return bar(arg, is_string<T>());
  }
};

If you can not use C++11, you must implement false_type and true_type yourself. Or you can use specialize template class.


text:
Q: validate_on_submit fails on POST when attributes of form fields modified in view function I have a simple wtforms.RadioField to accept user selection in a form in my app defined as:
class VoteForm(FlaskForm):
    vote_option = RadioField("Choices", coerce=int)
    submit = SubmitField('Submit')

And my view function is:
@main.route('/poll/<poll_id>/vote', methods=["GET", "POST"])
def vote(poll_id):
    poll = Poll.query.filter_by(id=poll_id).first()
    form = VoteForm()
    form.vote_option.choices = [(o.id, o.option) for o in poll.options]
    form.vote_option.default = poll.options[0].id
    form.process()

    if form.validate_on_submit():
        print(form.vote_option.data)

    return render_template("vote.html", form=form)

And the template is simply:
{% extends "base.html" %}
{% import "bootstrap/form.html" as wtf %}

{% block page_content %}
    {{ wtf.render_form(form) }}
{% endblock %}

When I post from the form, however, it is not validated and nothing is printed to the console.
If I instead remove the modifications to the form in the view function and define the vote_option field as:
vote_option = RadioField("Choices", choices=[("ONE", "ONE"), ("TWO", "TWO")])

The form can be validated as expected. What is going wrong by modifying the attributes of the form in the view function?

A: Removing the call to form.process() in the view function solved the problem. Although I am not entirely sure why. I will accept an answer which can explain why.


text:
Q: NIntegrate fails in a very strange way I found a strange behavior in Mathematica when trying to evaluate the integral
$$f(n) = \int_{1}^2 \frac{\Gamma(n)\Gamma(x)}{\Gamma(x+n)}{\rm d}x$$
I evaluate this using F[n_] := NIntegrate[(Gamma[x] Gamma[n])/Gamma[x + n], {x, 1, 2}] For large values of $n$ the two terms $\Gamma(n)$ and $\Gamma(x+n)$ will be huge, but the integrand itself is monotonely decreasing and contained in $[0,\frac{1}{n}]$.
Mathematica (10.3.1.0) is able to evaluate this integral for all values  $n\in[1,1000]$ however for $n=171$ the integration breaks down with NIntegrate::izero and gives $0$ as the result:
F[170]  -> 0.00103244
F[171]  -> 0.0 (NIntegrate::izero)
F[172]  -> 0.00105424

If I try non-integer $n$ then I find that it breaks down for all $n \in [170.6,171.6]$ Increasing MinRecursion or AccuracyGoal does not help. The strange part is that Mathematica is able to evaluate the function perfectly well for $x\in[1,2]$ and the plot of the function over this interval looks just like it should. The plot below is $n\cdot\frac{\Gamma(n)\Gamma(x)}{\Gamma(x+n)}$ for $n=171$:
$~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~$

My questions are as follows:

*

*What is going on here?

*Is there any settings that I can turn on to fix this?

A: A bit speculative, but I think we can see why 171 is a magic number, if we factor the Gamma[n] from the integral:
 Table[ {n, NIntegrate[Gamma[x] /Gamma[x + n], {x, 1, 2}]} , {n, 168, 173}]

{{168, 7.20924*10^-304}, {169, 4.26119*10^-306}, {170,
    2.41873*10^-308}, {171, 0.}, {172, 0.}, {173, 0.}}

171 is where the integral fails as you can see the result is smaller than $MinMachineNumber.  I'd guess NIntegrate factors the constant, but stops factoring when the factored value is too large.
note if we hide the structure the problem ( at this n ) goes away:
f[n_?NumericQ, x_?NumericQ] := Gamma[x] Gamma[n]/Gamma[x + n]
Table[{n, NIntegrate[f[n, x], {x, 1, 2}]}, {n, 168, 175}]

{{168, 0.00108399}, {169, 0.00107641}, {170, 0.00106892}, {171,
    0.00106153}, {172, 0.00105424}, {173, 0.00104704}, {174,
    0.00103993}, {175, 0.00103291}}

This actually (surprisingly) works even for much larger n.

A: Fixing it ...

Is there any settings that I can turn on to fix this?

Does using larger working precision produce results you expect?
F[n_] :=
 NIntegrate[(Gamma[x] Gamma[n])/Gamma[x + n], {x, 1, 2},
  WorkingPrecision -> 60, MinRecursion -> 6, MaxRecursion -> 20]

In[10]:= F[170]

Out[10]= 0.00106892313424594316124137429342057472552302576793438553998338

In[11]:= F[171]

Out[11]= 0.00106153418172547954471366095844979404173963460222797906864894

In[12]:= F[172]

Out[12]= 0.00105424004229628467250748022777662650942896871502716627259853

UPDATE:
Following J.M.'s advice of using Beta we can see that using larger working precision fixes the issue when using Gamma:
FB[n_] :=
 NIntegrate[Beta[x, n], {x, 1, 2}, WorkingPrecision -> 60,
  MinRecursion -> 6, MaxRecursion -> 20]

Grid[{#, FB[#]} & /@ Range[170, 172]]

What is going on ...
Following george2079's answer and using the option "IntegrationMonitor" we can see what is going on.
With[{n = 171},
 Reap@NIntegrate[(Gamma[x] Gamma[n])/Gamma[x + n], {x, 1, 2},
   IntegrationMonitor -> (Sow[
       Map[{#1@"Integrand", #1@"Boundaries", #1@"Integral", #1@
           "Error", #1@"GetValues"} &, #1]] &)]
 ]

f[n_?NumericQ, x_?NumericQ] := Gamma[x] Gamma[n]/Gamma[x + n];
With[{n = 171},
 Reap@NIntegrate[f[n, x], {x, 1, 2},
   IntegrationMonitor -> (Sow[
       Map[{#1@"Integrand", #1@"Boundaries", #1@"Integral", #1@
           "Error", #1@"GetValues"} &, #1]] &)]
 ]


text:
Q: What language can be compiled for both iOS and Android? I'm looking to develop an app for both iOS and Android, and I would like to be able to compile to both without having to actually write in two different languages.
GUI will be simple: buttons, drop down menus, textboxes. Although it would be a bonus to have these in a pre-made library or as part of the phone utils, I can and will write my own if needed. However, I will need access to phone hardware such as GPS and location, internet access, notifications, running in background and possibly vibration.
I'd like to program in C++ or similar in preference, but any language that will cross-compile should do. Any help would be appreciated!
EDIT: I'm asking about what frameworks I can use for this, and what languages they use.

A: There are plenty of engines you could use. Xamarin is one of the bests(programms are written in c#)

A: I know what you mean. Try Eqela. Check this out for a quick overview: https://www.youtube.com/watch?v=WcWf7SXGBv0

Eqela, a programming language translator that enables software
  developers to create software applications for several operating
  systems using a single set of source code, makes it possible to deploy
  applications on mobile, desktop and the web simultaneously. It is
  based on application source code conversion technology.

The language is OOP so you will feel comfortable programming with it. Since it is based on source code conversion, the target source code is native to your target platform. Eqela can be translated to Android, iOS, and a lot of other popular platforms. HTML5 is also part of the target source code!
Access to your target platform's native code is also available. Let's say one of your target is Android, you could include Android-specific codes inside Eqela source code.
I've used this first hand and I think this is a great tool. However, since this is not popular language, community support is limited.
For more info:
http://eqdn.tech/

A: Use Ionic(design) + Cordova. But you should know HTML, CSS and Javascript.


text:
Q: Does the generator polynomial in Golay-23 divide the $(x^5+x+1)^k$ for any $k$? I choose one of the two generator polynomials in binary Golay code with 23-length.
For instance $g(x) = (x^{11} + x^{10} + x^6 + x^5 + x^4 + x^2 + 1)$ .
Does there exist any $k \in N$ such that $g(x)$ divide $(x^5 + x + 1)^k$ over $\frac{Z_2(x)}{ \langle x^{23} -1 \rangle}$ ?
 If there is, find one.
P.S.-I hope that I've written the commands right and you can easily read what I wanted to. My apologies in case I haven't.

A: Unless I misunderstood the question the answer is negative for a rather simple reason.
Over $\Bbb{Z}_2$ we have the factorization
$$
x^{23}-1=(x+1) \left(x^{11}+x^9+x^7+x^6+x^5+x+1\right) \left(x^{11}+x^{10}+x^6+x^5+x^4+x^2+1\right).
$$
This means that $x^5+x+1=(x^2+x+1)(x^3+x^2+1)$ has no common factors with $x^{23}-1$, and is therefore a unit in the quotient ring $R=\Bbb{Z}_2[x]/\langle x^{23}-1\rangle$. The units form a group, so we can immediately conclude that $(x^5+x+1)^k$ is a unit of $R$ for all $k\in\Bbb{N}$.
But $g(x)$ is a factor of $x^{23}-1$ so its (polynomial) multiples form a proper ideal $G$ of $R$ ($G$ is the Golay code, really). Obviously the ideal $G$ cannot contain any units of $R$ proving the claim.


text:
Q: error code #1064 while Declaring Cursor in MySQL It's my first time working with cursors on MySQL, and I am having some problems, it doesn't accept the declaration of my cursor, what's wrong with my code? it shows me this error messagae:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
  near 'DECLARE @MyCursor CURSOR' at line 1

and my code is:
DECLARE @MyCursor CURSOR;
DECLARE @MyField varchar2(255);

BEGIN
    SET @MyCursor = CURSOR FOR
    SELECT codeMaint from affectationmc where iduser=29;

    OPEN @MyCursor
        FETCH NEXT FROM @MyCursor
        INTO @MyField

        WHILE @@FETCH_STATUS = 0
        BEGIN
          delete from mcorr where codemaint=@MyField ;
          FETCH NEXT FROM @MyCursor
          INTO @MyField
        END;

    CLOSE @MyCursor ;

    DEALLOCATE @MyCursor;
END;

A: here is the template I use for cursors.  It just taking the items from the select and maps them into the variables declared up top and executes your statement.  Once it processes the statement in the section --Actions to Loop Here, it changes the variables by selecting the next row from your select statement. This repeats until it process all of the rows in the select.
DECLARE

 @variable_A AS varchar(15)
,@variable_B AS INT
,@variable_C AS INT
,@variable_D AS VARCHAR(255)

DECLARE Process_Name CURSOR LOCAL FAST_FORWARD FOR
            SELECT
                        T.Col_A,T.Col_B,T.Col_C,T.Col_D
            FROM
                        tab.my_table AS T;

OPEN Process_Name
FETCH NEXT FROM Process_Name INTO @variable_A,@variable_B,@variable_C,@variable_D

WHILE @@FETCH_STATUS = 0
BEGIN

--Actions to Loop Here

FETCH NEXT FROM Process_Name INTO @variable_A,@variable_B,@variable_C,@variable_D
END

CLOSE Process_Name
DEALLOCATE Process_Name

A: You're attempting to declare your cursor in one statement, then associate the query with it in a second statement. While some databases will allow this, I'm fairly sure MySQL isn't one of them. Also, MySQL is quite strict about not declaring cursors until after all variables have been declared.
Here's how I would do it:
BEGIN  -- note all declarations are inside the BEGIN/END
  DECLARE done INT DEFAULT FALSE;  -- Good practice is to avoid global variables whenever possible
  DECLARE MyField varchar(255); -- varchar2 is Oracle, not MySQL

  DECLARE MyCursor CURSOR FOR
    SELECT codeMaint
      FROM affectationmc
      WHERE iduser = 29;

  DECLARE CONTINUE HANDLER FOR NOT FOUND
    SET done = TRUE;  -- this will detect end-of-result-set

  OPEN MyCursor;
  read_loop: LOOP
    FETCH NEXT
      FROM MyCursor
      INTO MyField;
    IF done THEN
      LEAVE read_loop;
    END IF;

    DELETE FROM mcorr
      WHERE codemaint = MyField ;
  END LOOP;

  CLOSE MyCursor;
END;


text:
Q: Display notification if search is not found using Rails 3 I am using will_paginate gem for searching data from table as per two date.Here my requirement is If no search data is found there should be one notification to user i.e-"No record found in between these two date.".Mu code files are given below.

view_report.html.erb:

            To

           <%= text_field_tag :search1, params[:search1], :class => "form-control" %>

    <%= submit_tag "Search",:class => "btn btn-info btn-lg" %>

    <% end %>

            <colgroup>
                <col class="col-new-md-1">
                <col class="col-new-md-1">
                <col class="col-new-md-1">
                <col class="col-new-md-1">
                <col class="col-new-md-1">
                <col class="col-new-md-1">
                <col class="col-new-md-1">
                <col class="col-new-md-1">
                <col class="col-new-md-1">
                <col class="col-new-md-1">
                <col class="col-new-md-1">
                <col class="col-new-md-1">
                <col class="col-new-md-1">
                <col class="col-new-md-1">
                <col class="col-new-md-1">
                <col class="col-new-md-1">
            </colgroup>

                Sl. No
                Receipt
Number
                Date
                Deceased
Name
                Doner
Name
                Doner
Mobile No
                Doner's
Relationship
                Donation
Amount
                Date of
death
                HCSY
Status
                Brahmin
                Action

            <% @sdf.each do |sdf| %>
            <% @count=@count+1 %>

            <%= @count %>
             <%= sdf.Receipt_No %>
            <%= sdf.Created_On %>
            <%= sdf.Deceased_Name %>
            <%= sdf.Doner_Name %>
            <%= sdf.Doner_MobileNo %>
            <%= sdf.Doner_Relationship_Other %>
            <%= sdf.Donation_Amount %>
            <%= sdf.Date_Of_Death %>
            <%= sdf.HCSY_Status %>
            <%= sdf.Brahmin %>

            <a href="/homes/home/?receipt_no=<%= sdf.Receipt_No %>" data-toggle="tooltip" title="" class="btn btn-xs btn-success" data-original-title="View">

            <% end %>

             <%= will_paginate @sdf %>

reports_controller.rb:

class ReportsController < ApplicationController
     helper_method :sort_column, :sort_direction
    def view_report
        @count=0
        @sdf =TSdf.all
        @sdf = TSdf.search(params[:search],params[:search1]).order(sort_column + ' ' + sort_direction).paginate(:per_page => 10, :page => params[:page])
    end
    def sort_column
     TSdf.column_names.include?(params[:sort]) ? params[:sort] : "Created_On"
  end

  def sort_direction
    %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
  end
end

t_sdf.rb:

class TSdf < ActiveRecord::Base
  # attr_accessible :title, :body
  self.table_name = 'T_SDF'
  def self.search(search,search1)
    if search && search1
      #where('Created_On LIKE ?', "%#{search}%")
      where("Created_On >= ? AND Created_On <= ?", search, search1 )
    else
      scoped
    end
  end
end

Please help me to add this notification as per the  requirement.

A: Try this:
 <% if @sdf.blank? %>

No record found in between these two date.

 <% else %>

     ....

       ....

       <% @sdf.each do |sdf| %>
         ....
       <% end %>

   <%= will_paginate @sdf %>
 <% end %>


text:
Q: virtualbox bridged networking requires ip protocol on windows host So here is the challenge, take one computer (named host) running windows with virtualbox and more than one network card and the same number of administratively separated subnets. Add a policy requirement that the windows box must have an ip address on one and only one subnet and that the guest must have an ip address, but it must not be on the subnet that the host is on. bridged networking is prefered as running vpn to the guest across the host's network is real overkill given that the wire is right there.
The naive solution (does not work) would be to configure an ip address on the first network card (static or dhcp as normal) and disable the ip binding on the second network card. Then when configuring the virtual machine, to select bridged networking and the second network adaptor. This utterly fails as bridged networking only lists network cards that are bound to ip (either 4 or 6, both also works fine, it may work with ipx or netbeui but they are not available for recent versions of windows).
A workaround is to enable an ip protocol on the second adaptor and misconfigure it so that the address it uses is on a subnet that is not reachable, but the second shift sysop keeps trying to fix it.
Is there a better solution?


text:
Q: Receiving HTTP 404 when validating a Double property with min constraint in Grails For a simple class like,
class Person {

    String Name

    Double incomeFromWork = new Double(0.0)

    static constraints = {
        incomeFromWork(min:0d)
    }
}

However on the GSP page I get an "HTTP ERROR: 404" error when I enter alphabets for incomeFromWork value. What constraints should I use to accept a valid Double value as an income?
Thanks,
BT

A: Your constraints don't have any problems; they will correctly validate a Double property.
It's likely that your problem is in your controller. You're probably either redirecting to an undefined action or rendering a view that doesn't exist.
As an aside, you should probably rename Name to name to meet standard member naming conventions.


text:
Q: WebView does not display popup
I had a scenario where I need to display an url in Webpage .  The url contains a popup which does not show and an empty screen is displayed instead of popup.  plz find below my implementation:
     webView = (WebView) instamedWebView.findViewById(R.id.webView);<br>
     WebSettings settings = webView.getSettings();
    settings.setBuiltInZoomControls(true);
    settings.setUseWideViewPort(true);
    settings.setJavaScriptEnabled(true);
    settings.setSupportMultipleWindows(true);
    settings.setJavaScriptCanOpenWindowsAutomatically(true);
    settings.setLoadsImagesAutomatically(true);
    settings.setDomStorageEnabled(true);
    settings.setLoadWithOverviewMode(true);
     settings.setAllowFileAccess(true);
    settings.setJavaScriptCanOpenWindowsAutomatically(true);

try {
    String url = "https://ppay-dev.com/Payment/abc.aspx";
    String postData = String postData = "amount=" + URLEncoder.encode(userName, "UTF-8") + "&FirstName=" + URLEncoder.encode(password, "UTF-8");
        webView.setWebViewClient(new WebViewClient() {
            public void onPageFinished(WebView view, String url) {

            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {

            }
        });
        webView.postUrl(url,postData.getBytes());
        webView.setWebChromeClient(new WebChromeClient(){
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }
        });
   catch (Exception e){
        e.printStackTrace();
    }

Can anyone suggest me how to display popups  in Android WebView

A: Maybe you can try to override web alert to native alert. It works for me.
webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                Log.i("TITLE", title);
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }

            // OVERRIDE WEB CONFIRM ALERT TO NATIVE ALERT
            @Override
            public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
                new AlertDialog.Builder(VideoTutorial.this)
                        .setTitle("DOMINOS SAYS:")
                        .setMessage(message)
                        .setPositiveButton(android.R.string.ok, (dialog, which) -> result.confirm())
                        .setNegativeButton(android.R.string.cancel, (dialog, which) -> result.cancel())
                        .create().show();

                return true;
            }

            // OVERRIDE WEB ALERT TO NATIVE ALERT
            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {

                new AlertDialog.Builder(VideoTutorial.this)
                            .setTitle("DOMINOS SAYS:")
                            .setMessage(message)
                            .setPositiveButton(android.R.string.ok,
                                    (dialog, which) -> result.confirm())
                            .create().show();
                return true;
            }

            // OVERRIDE WEB PROMPT ALERT TO NATIVE ALERT PROMPT
            @Override
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, final JsPromptResult result) {
                new MaterialDialog.Builder(VideoTutorial.this)
                        .title("DOMINOS SAYS:")
                        .content(message)
                        .inputType(InputType.TYPE_CLASS_TEXT)
                        .inputRangeRes(2, 20, R.color.dominoRed)
                        .input("No 1 Pizza Fav", "", (dialog, input) -> result.confirm(input + ""))
                        .positiveText("OK")
                        .negativeText("CANCEL")
                        .onNegative((dialog, which) -> result.cancel())
                        .show();

                return true;
            }
        });

A: It is said to use WebChromeClient and Override method onJsAlert(). Here is a sample code.
WebView wv=new WebView(this);
wv.setWebChromeClient(new WebChromeClient() {
    @Override
    public boolean onJsAlert(WebView view, String url, String message,JsResult result) {
                //Required functionality here
                return super.onJsAlert(view, url, message, result);
       }

This is link for more info.

A: Instead of overriding onJsAlert, just use:
WebView wv = new WebView(this);
wv.setWebChromeClient(new WebChromeClient());


text:
Q: how to find the basis of a plane or a line? Find a basis for the plane $x-2y+3z=0$ in $R^3$. Then find a basis for the intersection of that plane with the $xy$ plane.
Is there a proper/algebraic way of finding the basis of a plane?
Just by looking at it a basis could be $(2, 1, 0)$ because any multiple of that will give you $0$ when you substitute, but how do I find this without guessing?
would I use the same process when finding the basis of a line?
Any hints on how to figure out the second part of the question?

A: One thing you can identify is that $z = \frac{2y-x}{3}$, then the points that are going to satisfy the equality will be of the form
$$
\left(x, y, \frac{2y-x}{3}\right).
$$
For you to be able to cover all of such points, you would need to have two different vectors satisfying above such that they are not a multiple of each other.
You can see that indeed we can decompose the above vector as
$$
\left(x, y, \frac{2y-x}{3}\right)=x\left(1,0,-\frac{1}{3}\right)+y\left(0,1,\frac{2}{3}\right).
$$
which gives you an obvious basis
$$
(v_1,v_2)=\left(1,0,-\frac{1}{3}\right)+\left(0,1,\frac{2}{3}\right).
$$
There are many different ways of constructing a vector given in the first characterization, which would result in how the basis vector are aligned with respect to each other.


text:
Q: populate after object has been saved i'm updating my object and after the update has finished i'd like to display a success message which says sth. like "Success - Your Object at address: 123 was saved". Therefore i'd like to populate a property after the save has been done.
terminal.save(function (err, updatedTerminal) {
     if (err) return handleError(err);

     updatedTerminal.populate('installedAt');

     res.send(updatedTerminal);
});

but installedAt will not be populated - why?

A: populate is a function of Mongoose model and here updatedTerminal is not a Mongoose model.
functions like find, findOne returns Mongoose Object a special kind of object which has all the functions available like Model but save method only returns pure Javascript object after saving the document.


text:
Q: MSG Google Calendar adding a Feed I know I must be brain-dead, and I had a solution about a month ago, but accidentally deleted it (oops)!
From the this page you can create a small widget calendar. With the date picker AND agenda (yes both are needed)
It produces some code like so:
<script src="http://www.gmodules.com/ig/ifr?url=http://www.google.com/ig/modules/calendar3.xml&up_calendarFeeds=&up_calendarColors=&up_firstDay=0&up_dateFormat=0&up_timeFormat=1%3A00pm&up_showDatepicker=1&up_hideAgenda=0&up_showEmptyDays=0&up_showExpiredEvents=1&synd=open&w=320&h=165&title=__MSG_Google_Calendar__&lang=en&country=ALL&border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>

However it doesn't specify the calendar, and always loads the local calendar. I see there is the variable up_calendarFeeds in there, and that got me thinking I should try to add a feed. I searched and found google's page on feeds. The says the feed url is in the format of:
https://www.google.com/calendar/feeds/userID/private-magicCookie/full

full over basic is for machine readable, of which I assume the gadget uses. However when I set the up_calenderFeeds variable with my data, It loads nothing. What am I missing? This being my final code:
<script src="http://www.gmodules.com/ig/ifr?url=http://www.google.com/ig/modules/calendar3.xml&up_calendarFeeds=https://www.google.com/calendar/feeds/ohmusama@gmail.com/private-0b7544f4b5f2198fc76c96e59f285dad/full&up_calendarColors=&up_firstDay=0&up_dateFormat=0&up_timeFormat=1%3A00pm&up_showDatepicker=1&up_hideAgenda=0&up_showEmptyDays=0&up_showExpiredEvents=1&synd=open&w=195&h=500&title=Portland+IPA+Calendar&lang=en&country=ALL&border=%23ffffff%7C3px%2C0px+solid+%23999999&output=js"></script>

A: Alright, since no one was able to help me. I searched and searched and found some answers.
There are a variety of different variables in the get string with many characters that need escaping. First for what ever reason, up_calendarFeeds must be set to ({}) which url encoded ends up being up_calendarFeeds=%28%7B%7D%29
Then you need to set 2 variables for your calendar to work properly (I think you need both), up_c0u and up_c0c both to your feed path. Note that It seems this can be in an array form, so you can add many feeds by incrementing 0, so up_c1u up_c2u up_c3u etc


text:
Q: Phone Number Validation with Regex I have a web form and want to accept the following phone numbers in the following format:
1234567890
123-456-7890
123.456.7890
123-4567890
The first number cannot be a 0 or a 1.
How can I do this with regex/javascript? I found a few regex formulas online but none are specific to my needs

A: null !== thenumber.match(/^[2-9][0-9]{2}[.-]?[0-9]{3}[.-]?[0-9]{4}$/);
(Edited to give slightly better answer with boolean result)

A: Consider the following Regex...
[\d-[01]]\d{2}[-\.]?\d{3}[-\.]?\d{4}

Note: You examples start with a 1 which will not satisfy the above regex.

A: The user-provided format should be irrelevant. It makes more sense to store phone numbers as, well, numbers, i.e. digits only, and add uniform formatting when displaying them back. Otherwise you end up wit a mess in your database and you're going to have a hard time searching for numbers (if you wanted to find if given number is already in your DB then how'd you know the format it was typed in?), and you will have inconsistent formatting of numbers when displaying them.
So you'd store any of your example numbers as 1234567890, no matter what the user has typed into the form. Which means you can validate your input by stripping any non-digits, then checking the length and other conditions, like this:
function validPhone( num ){
   var digits = num.replace(/\D/g,'');
   // assuming 10 digits is a rule you want to enforce and the first digit shouldn't be 0 or 1
   return (parseInt(digits[0],10) > 1 && digits.length == 10);
}

You could also use return parseInt(digits, 10) >= 2000000000 to validate that the number doesn't start with 0 nor 1 and has at least 10 digits.