text:
Q: How can cell phone towers transmit despite the rain? I once read that waves of higher frequency (such as around 1 GHz range and higher) have difficulty passing through water (or other liquids/solids).
Today, when I saw a cellphone tower, I wondered: "how are these towers able to transmit signals even when it's raining, or when its foggy?". I assume that when it's raining, a large surface area of the antenna will probably be covered with water. When it's foggy, there are lots of water droplets in the air that will block the path of the tower's waves.
My question is: what is the physics explanation of how electromagnetic waves of low vs high frequency are interacting with matter, and why higher frequency waves are better absorbed by matter than lower frequency (such as AM radio waves). I searched online for this, but had difficulty finding a well-explained physics explanation.
Then using that explanation, how are the high frequency cellphone tower waves still able to pass through the water? Is it just that the towers have a lot of power so although some energy is absorbed, a lot of energy is still able to pass through?

A: Cell links are affected a little by rain, but an electromagnetic wave is not significantly scattered by objects much smaller than its wavelength. Even frequencies such as $5\mathrm{GHz}$ have a wavelength of $60\mathrm{mm}$, while a raindrop might be a tenth the size. When wavelength and obstacle become comparable in scale, "Mie scattering" becomes significant. Millimeter wave links at $60\mathrm{GHz}$, for example, can suffer $20$ to $30\mathrm{dB/Km}$ (i.e. less than $1\text{%}$ makes it through a kilometer of rain) of loss in heavy rain.


text:
Q: prove that $2(\sqrt{n+1}-1)<1+\frac{1}{\sqrt{2}}+\cdots +\frac{1}{\sqrt{n}}< 2\sqrt{n}$ prove $2(\sqrt{n+1}-1)<1+\frac{1}{\sqrt{2}}+\cdots +\frac{1}{\sqrt{n}}< 2\sqrt{n}$ by mathematical indcution.
my attempt:
we prove for $n=1$
for $n=1$ than $0.828<1<2$ so true for $n=1$
we assume that this is true for $n=k$
ie  $2\sqrt{k+1}-1<1+\frac{1}{\sqrt{2}}+\cdots +\frac{1}{\sqrt{k}}< 2\sqrt{k}$
Now we have to prove for $n=k+1$
consider $\frac{1}{\sqrt{2}}+\cdots +\frac{1}{\sqrt{k}}+\frac{1}{\sqrt{k+1}}< 2\sqrt{k}+\frac{1}{\sqrt{k+1}}\leq 2\sqrt{k}+1<2\sqrt{k+1}$  Is this correct?
what about otherside

A: (Using mathematical induction),
(As you did) Now we assume that this is true for $n=k$, i.e.
$$2\sqrt{k+1}-1<1+\frac{1}{\sqrt{2}}+\cdots +\frac{1}{\sqrt{k}}< 2\sqrt{k}\tag 1$$
Now we have to prove for $n=k+1$. All you have to do is to prove
$$2\sqrt{k+2}-1<2\sqrt{k+1}-1+\frac{1}{\sqrt{k+1}}\tag 2$$
and
$$2\sqrt k+\frac{1}{\sqrt{k+1}}<2\sqrt{k+1}\tag 3$$
To prove $(2)$,
$$2\sqrt{k+2}-2\sqrt{k+1}=\frac{2}{\sqrt{k+2}+\sqrt{k+1}}<\frac{2}{\sqrt{k+1}+\sqrt{k+1}}=\frac{1}{\sqrt{k+1}}$$
Therefore $(2)$ is true.
To prove $(3)$,
$$2\sqrt{k+1}-2\sqrt k=\frac2{\sqrt{k+1}+\sqrt k}>\frac2{\sqrt{k+1}+\sqrt {k+1}}=\frac1{\sqrt {k+1}}$$
Therefore $(3)$ is true.
Now from $(1),(2)$ and $(3)$, the equation for $n=k+1$ also holds.

A: Use the condiction from $n=k$ and what we should get is that $$2\sqrt{k+2}-1<\underbrace{\frac{1}{\sqrt{2}}+\cdots +\frac{1}{\sqrt{k}}}_{>2\sqrt{k+1}-1}+\frac{1}{\sqrt{k+1}}$$     So we just have to compare $2\sqrt{k+2}-1$ with $2\sqrt{k+1}+\frac{1}{\sqrt{k+1}}-1 $
$$(2\sqrt{k+2} )^2=4(k+2)$$
$$(2\sqrt{k+1}+\frac{1}{\sqrt{k+1}})^2=4(k+1)+4+\frac{1}{k+1}=4(k+2)+\frac{1}{k+1}>(2\sqrt{k+2})^2 $$
$$\Rightarrow$$
$$ 2\sqrt{k+2}-1< 2\sqrt{k+1}+\frac{1}{\sqrt{k+1}}-1$$
So wir have
$$2\sqrt{k+2}-1< 2\sqrt{k+1}-1+\frac{1}{\sqrt{k+1}}<\frac{1}{\sqrt{2}}+\cdots +\frac{1}{\sqrt{k}}+\frac{1}{\sqrt{k+1}}$$

A: Consider the curve $y=\frac 1{\sqrt x}$ and divide the interval $(0,n+1)$ into rectangles of unit length. We have
$$\int_1^{n+1}\frac{1}{\sqrt{x}}\,dx\lt 1+\frac{1}{\sqrt{2}}+\frac{1}{\sqrt{3}}+\cdots+\frac{1}{\sqrt{n}}\lt \int_0^n \frac{1}{\sqrt{x}}\,dx$$
Evaluate the integrals, and we have tthe required proof
$$2(\sqrt{n+1}-1)<1+\frac{1}{\sqrt{2}}+\cdots +\frac{1}{\sqrt{n}}< 2\sqrt{n}$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: shape of a sparse tensor without invoking run() sparse tensor.shape method returns a tensor object which seems to be of no use to extract the actual shape of the sparse tensor without resorting to run function.
To clarify what I mean, first consider a sparse tensor:
a = tf.SparseTensor(indices=[[0, 0, 0], [1, 2, 1]], values=[1.0+2j, 2.0], shape=[3, 4, 2])
a.shape returns:
tf.Tensor 'SparseTensor_1/shape:0' shape=(3,) dtype=int64
This is kind of no use.
Now, consider a dense tensor:
a = tf.constant(np.random.normal(0.0, 1.0, (4, 4)).astype(dtype=np.complex128))
a.get_shape() returns:
TensorShape([Dimension(4), Dimension(4)])
I can use this output and cast it into a list or tuple of integers without ever invoking run(). However, I cannot do the same for sparse tensor, unless I first convert sparse tensor to dense (which is not implemented for complex sparse tensor yet) and then call get_shape() method on it, but this is kind of redundant, defeats the purpose of using a sparse tensor in the first place and also leads to error down the road if the input sparse tensor is complex.
Is there a way to obtain the shape of a sparse tensor without invoking run() or converting it to a dense tensor first?

A: tf.SparseTensor is implemented as a triple of dense Tensors under the hood. The shape of a SparseTensor is just a Tensor; if you want to know its value, your best bet is to evaluate it using session.run:
print(sess.run(a.shape))

In general, Tensorflow does not promise to compute an exact shape even for dense tensors at graph construction time; shapes are best effort and may not even have a fixed value. So even for a dense Tensor you may have to evaluate the Tensor using run to get a precise shape.


text:
Q: Dynamically creating Tab+DataGrid for binding with multiple different classes? I apologize for the crappy title, I wasn't quite sure how to summarize what I'm trying to do.
My scenario:
I am refactoring an existing WinForms application to WPF and MVVM. I'm currently working on a module that provides search functionality for a database comprised of many different tables such as Contact, User, Case, Product, etc. In code-behind there are classes which provide an Object for each. I have written wrapper classes for each of the searchable table Objects that expose only the properties a user would want/need to see in the search results for each type of Object, for binding to a DataGrid.
Once these search results exist, they need to be displayed in a combination of Tab Controls and Data Grids, like so:

Because of some use cases, I need to be able to create an individual display Tab+DataGrid for the results of every single search that is performed. I cannot have a single tab for each type of search that is shown/hidden as needed.
I'm not sure how to proceed from where I currently am to the goal pictured and described above. Thanks for any help anyone can provide.

A: Not sure I entirely understand your question, but it looks to me that it might be a candidate for datatemplateselector.
Basically, you use an ItemsControl bound to your result collection and then - using a datatemplateselector - you swap in the appropriate template to display the item based upon a code inspection.
That will let you present all the results in a single list.
If you want to display your results in a tabs, I would present a collection of each result type in your viewmodel. So you have a Users collection and a seperate Products collection. Then you can bind individual data grids to each template.
If you want to then hide the tabs when no results are present, add a data trigger using the expression.interactivity namespace to trigger the visibility of each tab page based on its respective collection count.
One more thing, if you want to create tab items dynamically, i.e. One tab for each search - the tab control has an ItemSource property. If you group each search result into an object an expose an observable collection of that object, you can bind that to your tab control and have it create tab items for each search result. Just make that object contain a collection of actual results and you should be able to create a itemscontrol as mentioned here already.
Sorry if this appears a bit of a mind dump, but like I said - not sure if I entirely get the question :)
Rather then chuck a load of code snippets in, there a plenty of samples just a google away if anything sounds helpful.


text:
Q: Question About Definition of Almost Everywhere I suppose I'm a bit confused about the definition in the following regard:
A property holds a.e. if it holds everywhere except for a set of measure $0$. Now, if the particular property is only defined for a set of measure $0$, is it a.e. by default?
Say I have two 'continuous' (standard topology) sequences $f,g: \mathbb{N} \to \mathbb{R}.$ Are we then allowed to say that $f = g$ a.e.? Or instead do the functions have to be defined on a set of non-zero measure and a.e. refers to some measure $0$ subset?
I ask because a homework exercise asks me if two real functions are continuous and agree a.e. on a subset of $\mathbb{R}$, are necessarily identically equal. Clearly this is true if the points are not isolated, since if continuous functions disagree at some point, they must disagree on a non-zero measure set since open sets have non-zero measure. Though it need not be if I just use sequences.
So, what are the requirements to use the phrase a.e.?
Wolfram definition: A property of $X$ is said to hold almost everywhere if the set of points in $X$ where this property fails is contained in a set that has measure zero.
This would seem to imply that it is a.e. by default.

A: To speak of a property holding a.e. on a set $X$ you first need a measure. If $P(x)$ is a property defined for every point $x \in X$, then $P$ is true $\mu$-almost everywhere if $$\mu(\{ x \in X \mid \neg P(x)\}) = 0.$$
Perhaps a bit more precisely, you might require that there is a $\mu$-measurable set $N$ with the property that $\mu(N) = 0$ and $\{ x \in X \mid \neg P(x)\} \subset N$ since the first set is possibly not $\mu$-measurable.
What does it mean for two functions $f,g : \mathbb N \to \mathbb R$ to be equal almost everywhere? Without a measure this question can't be answered. If you specify a measure $\mu$ on $\mathbb N$, they are equal $\mu$-a.e. if $$\mu(\{n \in \mathbb N \mid f(n) \not= g(n)\}) = 0.$$
For instance, if $\mu$ is the counting measure, this states the set of points where $f(n) \not= g(n)$ has zero elements - in this case $f(n) = g(n)$ for all $n$ so that $f$ and $g$ are the same function. On the other hand, if $\mu$ is Lebesgue measure restricted to $\mathbb N$, the fact that $\mu(\mathbb N) = 0$ implies that $\mu(\{n \in \mathbb N \mid f(n) \not= g(n)\}) = 0$ for any two functions $f$ and $g$, so that any two functions $f$ and $g$ are equal a.e.  Different measures yield totally different results.

A: Here's an example to show that your concern about isolated points is justified.
Let $f(x)=0$ for all $x\in{\Bbb R}$ and $g(x) = \max(x,0)$. These two functions are continuous and the are equal at (Lebesgue) a.e. point of $B:=(-\infty,0]\cup\{1\}$. But they are not identically equal on $B$.

A: If you have two functions $f$, $g$ that are defined and continuous on $\mathbb{R}$, then $f=g$ if the two agree a.e. with respect to Lebesgue measure. That may be how the question was meant to be interpreted, because that would be the default for a.e. on $\mathbb{R}$ if no measure is mentioned.
Assuming this interpretation: If the exceptional set is $E$, then you only have to note that $(x-\delta,x+\delta)$ contains a point of $\mathbb{R}\setminus E$ for every $\delta > 0$, which is enough to force $f(x)=g(x)$ for an arbitrary $x$ because $f$ and $g$ are continuous.


text:
Q: Some attributes get removed when fetching HTML files from Spring Boot API in Angular 5 app When fetching a HTML file from Spring Boot back-end via its API with Angular 4 app on the front-end, HTML tag attributes of type id, name, data-* are stripped away, but class attribute type remains. What's the reason for this, as I can't seem to find it?

A: If you mean the attrs are stripped when you bind to the innerHTML of an element in a template, it seems those attributes are not allowed by the sanitizer. Probably mostly because they're not presentionally useful in an Angular app. I don't know if id and data are considered potentially unsafe too. I know forms, inputs, buttons etc. are so name is useless.
The allowed attrs are listed in html_sanitizer.ts (full source):
const HTML_ATTRS = tagSet('abbr,accesskey,align,alt,autoplay,axis,bgcolor,border,cellpadding,cellspacing,class,clear,color,cols,colspan,'
+ 'compact,controls,coords,datetime,default,dir,download,face,headers,height,hidden,hreflang,hspace,' +   'ismap,itemscope,itemprop,kind,label,lang,language,loop,media,muted,nohref,nowrap,open,preload,rel,rev,role,rows,rowspan,rules,' +    'scope,scrolling,shape,size,sizes,span,srclang,start,summary,tabindex,target,title,translate,type,usemap,' +
    'valign,value,vspace,width');

If you really need id, name or data attributes (why would you really?) and can trust your html 110%, ie. it's not originated from any user input or you have already sanitized it serverside, you can call DomSanitizer.bypassSecurityTrustHtml() with it before binding (or in a pipe) to leave the html untouched.


text:
Q: Manter um site de um tamanho padrao mobile/desktop Estou a desenvolver um site e preciso que ele fique do mesmo padrao de css para desktop e mobile, sem se tornar responsivo. https://br.leagueoflegends.com/pt/game-info/champions/ como esse site, se voce fazer o teste no inspecionar e testar em diferente tipos de telas mobiles, as imagens so diminuem, porem, permanecem da mesma forma. Como faria isso?

A: Use a meta tag viewport para ajustar as dimensões da página para a largura e altura do dispositivo, prefira usar media queries no seu css para especificar diferentes estilos para diferentes telas, este link contém mais informações sobre a utilização do @media, escolha usar % em vez de px, pois px é uma medida fixa, enquanto % é uma medida relativa ao elemento pai.


text:
Q: TypeORM при создании миграции сбрасывает столбцы У меня есть существующая таблица пользователей в MySQL, к которой нужно сделать сущность.
При генерации миграции TypeORM сбрасывает все столбцы таблицы и пересоздаёт их.
Users DDL (существующая таблица)
create table if not exists users
(
    id                            int auto_increment primary key,
    login                         varchar(50)          not null,
    name                          varchar(255)         not null,
    surname                       varchar(50)          null,
    patronymic                    varchar(255)         null,
    mail                          varchar(255)         not null,
    phone                         varchar(255)         null,
    password                      varchar(255)         not null,
);

Entity
@Entity({
    name: 'users',
})
export class UserModel {
    @PrimaryGeneratedColumn()
    id: TUserID;

    @Column({ length: 50, nullable: true })
    login: string;

    @Column()
    name: string;

    @Column({ length: 50, nullable: true })
    surname: string;

    @Column({ length: 50, nullable: true })
    patronymic: string;

    @Column({ length: 50 })
    mail: string;

    @Column()
    password: string;
}

Сгенерированная миграция
await queryRunner.query(`ALTER TABLE \`users\` DROP COLUMN \`login\``);
await queryRunner.query(`ALTER TABLE \`users\` DROP COLUMN \`password\``);
await queryRunner.query(`ALTER TABLE \`users\` ADD \`login\` varchar(50) NOT NULL`);
await queryRunner.query(`ALTER TABLE \`users\` ADD \`password\` varchar(255) NOT NULL`);
...

Может кто сталкивался с такой проблемой или знает как её решить?


text:
Q: Localizing in WPF I am localizing a WPF application. The datagrid columns headers needs to be changed at runtime according to the specific UI culture in the XAML.
Though I am able to do the localization in the code behind and also in XAML by using the LocBaml tool. I am not able to achieve it with one particular scenario in the XAML. The scenario is that I am parsing XAML, as I am loading it in an XML file and parsing..
So now when I parse it like:
<dg:DataGridColumnHeader Header="{x:Static findlocale:My.Resources.String.anylocalword}"></dg:DataGridColumnHeader>

Where findlocale is the XAML namespace keyword, I am getting an error:

XAML parse error. Cannot find type My.Resources.String.localword in
  the xaml namespace.

Why is this not working in this scenario? How do I overcome it?

A: I'm willing to bet your findlocale XML namespace is incorrect. If you have something like:
namespace MyNameSpace.MySubNamespace {
    public class MyClass {
        public static string MyProperty { get; set; }
    }
}

Then your XML namespace must be declared like xmlns:findlocale="clr-namespace:MyNameSpace.MySubNamespace" in order to use {x:Static findlocale:MyClass.MyProperty}.
You cannot declare your XML namespace like xmlns:findlocale="clr-namespace:MyNameSpace" and use it like {x:Static findlocale:MySubNamespace.MyClass.MyProperty}.
Also, if you have any nested classes/enums, then you must use a + sign in place of the .. So if you had:
namespace MyNameSpace.MySubNamespace {
    public class MyClass {
        public class MyNestedClass {
            public static string MyProperty { get; set; }
        }
    }
}

To access MyProperty, you'd need to declare your XML namespace like xmlns:findlocale="clr-namespace:MyNameSpace.MySubNamespace" and access it like {x:Static findlocale:MyClass+MyNestedClass.MyProperty}.


text:
Q: On the Artin-Rees Lemma for non-commutative rings Consider a commutative noetherian ring $A$ with an ideal $I\subset A$. The Artin-Rees lemma implies that for f.g. modules $N\subset M$, the $I$-adic topology on $N$ agrees with the subspace topology coming from the $I$-adic topology on $M$. I wonder how much this can be generalized to the case where $A$ is not necessarily commutative. For example, let $\mathcal{R}$ be the valuation ring of a complete, discretely valued non-archimedean field $K$, and let $\pi$ be a uniformizer of $\mathcal{R}$. Assume you have a non-commutative algebra $A$ over $\mathcal{R}$ which is two-sided noetherian, and complete with respect to the $\pi$-adic topology.  Are there any conditions on $A$ which assure that the Artin-Rees lemma holds for the $\pi$-adic topology? Notice that the previous statement covers, for example,
the case where $A$ is the $\pi$-adic completion of the universal enveloping algebra of a finitely generated Lie algebra over $\mathcal{R}$.

A: There is some discussion of this in Rowen's "Ring Theory", volume I, Section 3.5, with additional references therein.
Exercise 19 on p. 462 in op. cit. states that a polycentral ideal $I$ of a noetherian ring $A$ has the Artin-Rees property, i.e., for every f.g. left module $M$ and a f.g. submodule $N\subseteq M$, there is $i\geq 1$ with $N\cap I^i M\subseteq IN$. (Applying this to $I^nN$ in place of $N$ shows that the $I$-adic topology on $N$ conicides with the topology induced from the $I$-adic topology of $M$.)
Here, an ideal $I$ is called polycentral if there is a chain of ideals $I=I_0\supseteq I_1\supseteq\dots\supseteq I_{t+1}=0$ such that $I_i = I_{i+1} +\sum_{r=1}^{s(i)} a_r A$ with $a_1,\dots a_{s(i)}\in A$ central modulo $I_{i+1}$. In particular, any ideal generated by central elements is polycentral.
In the context of your question, $I=\pi A$ is polycentral since it is generated by a central element, so it has the Artin-Rees property.
Actually, it is noted in op. cit. that the usual proof of the Artin-Rees lemma in the commutative case carries over in the non-commutative case for ideals generated by central elements.


text:
Q: Не верная логика программы для GridLayout Здравствуйте. Помогите разобраться в чем может быть проблема. Написал вот такой код и в нем есть описание действий:
    int countPosition = 0;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            GridLayout.Spec buttonRowSpec = GridLayout.spec(i);
            GridLayout.Spec buttonSpecColumn = GridLayout.spec(j);
            TouchAction actionListener = new TouchAction(gridLayout, buttons, gameController);
            ImageButton button = ButtonsFactory.createImageButton(this, bitmaps[i][j], countPosition, paddingImgBtn, actionListener);
            countPosition++;
            if (countPosition < 12)
                buttons.add(button); // добавляем кажду кнопку в коллекцию
            // добавляем каждую кнопку в GridLayout с указанными параметрами
            gridLayout.addView(button, new GridLayout.LayoutParams(buttonRowSpec, buttonSpecColumn));
        }
    }

    gridLayout.removeAllViewsInLayout(); // удаляем кнопки из GridLayout
    Collections.shuffle(buttons); // перемешиваем коллекцию с кнопками
    Bitmap lastImageBitmap = ImageProcessor.resizeImage(getResources(), R.drawable.locked,
            bitmaps[0][0].getWidth(), bitmaps[0][0].getHeight(), true);
    lastButton.setImageBitmap(lastImageBitmap);
    buttons.add(lastButton); // добавляем кнопку с картинкой замочка в самый конец коллекции

    for (int i = 0; i < 12; i++) {
        ImageButton button = buttons.get(i); // получаем кнопки из перемешанной коллекции
        gridLayout.addView(button); // добавляем их в GridLayout
    }
    // делаем валидацию что бы отобразилось корректно, но что то подсказывает мне, что этот метод тут не для этого!
    // в SWING есть у JPanel такой метод как validate(), решил, что и тут так же, но увы видимо нет
    gridLayout.invalidate();

Картинка на выходе не та, что ожидалась по логике, кнопки должны были перемешаться:

A: Оказывается, что позиции кнопок в GridLayout устанавливаются когда они создаются, их позиции в листе не влияют на макет layout.
Поэтому нам нужно будет создать еще одну коллекцию с параметризованым типом: List<GridLayout.LayoutParams> params = new ArrayList<>();
И только потом уже можно применять Collections.shuffle(params);
А метод gridLayout.invalidate() тут точно не нужен.


text:
Q: how to move SharePoint 2010 workflows build using sp designer how to move SharePoint 2010 workflows build using  sp designer 2010 from dev to production ? until now I have alwasy recreated that in prod environment , is there a better way to do it

A: Try to export to visio then import it to poruction by following the mentioned steps below :

*

*In SharePoint Designer 2010, click on your completed List Workflow.

*Click on "Save" and "Publish" for the completed List Workflow.

*Next, click on "Export to Visio". Save the file as CompletedWorkflow.vwi or any preferred name.

*Then create a new "similar" list on the current site or on a new site collection.

*There is no way to import the exported visio into this new list.

*In SharePoint Designer 2010, click on this new list and then click on "List Workflow" to create a new workflow for this new list.

*Please make sure that you do not add any workflow steps!

*Click on "Save" and "Publish" for this empty List Workflow.

*Then, click on "Export to Visio" and save this as EmptyWorkflow.vwi or any preferred name.

*Rename both the vwi files by adding ".zip" extension. The files should be CompletedWorkflow.vwi.zip and EmptyWorkflow.vwi.zip.

*The objective is to replace the "workflow.xoml.wfconfig.xml" file from the EmptyWorkflow.vwi.zip into the CompletedWorkflow.vwi.zip.

*It is likely that you cannot replace it directly. Copy the file out to the desktop and then copy the file into the other zipped folder.

*Remove the ".zip" extension from the CompletedWorkflow.vwi.

*With this, we have a working importable visio List Workflow.

*Back in the SharePoint Designer 2010, close all the workflow tabs.

*Click on the "Import from Visio" and select the CompletedWorkflow.vwi.

You have successfully export and import the List Workflow! Ref

A: There's not a simple way out of the box. There are articles about how to movie them with Visio. The answer to this question goes through moving it and then replacing the List GUIDs. This is the tutorial I usually refer to.
There are also 3rd party tools that make this easier. We've used DocAve.


text:
Q: Workflow to be run for every specific document or content type? I will need to look for the solution to implement the manual script initiation for specific file type in the document library (ex. force unlocking a document). Idea is that I will add additional column with the link to manually trigger a workflow to every item with appropriate content type (only MS Office file types). It should look like this:
User click on the link of workflow of specific document --> Workflow (param documentId) --> execute the script on the server (with documentId param).
Is that scenario possible, if not with workflows, how can I achieve that?

A: By design, SharePoint Workflow cannot call a customized powershell script. On the other hand, you can start SharePoint Workflows through PowerShell commands.
You could refer to this case:

*

*SP2013 Workflow to invoke Powershell


text:
Q: Google Foobar- Code works in my IDE but not in foobar. Static method? I am  doing one of the Google foobar challenges and my code returns the right values in my IDE, but not in foobar. I'm new to python and think I'm missing something on how foobar reads the code or calls the function. Help is much appreciated!
Here's my code:
def solution(area):
    totalarea=int(area)
    sq1calc=abs(totalarea ** 0.5)
    sq1 = int(sq1calc)
    sq1area = sq1 ** 2
    sq2calc=abs((totalarea - sq1area) ** 0.5)
    sq2 = int(sq2calc)
    sq2area = sq2 ** 2
    sq3calc=abs((totalarea - sq1area - sq2area) ** 0.5)
    sq3 = int(sq3calc)
    sq3area = sq3 ** 2
    sq4calc=abs((totalarea - sq1area - sq2area - sq3area) ** 0.5)
    sq4 = int(sq4calc)
    sq4area = sq4 ** 2
    print(sq1area,sq2area,sq3area,sq4area, sep=",")
solution()

Two test case input/outputs are provided and my code runs these fine in my IDE.
Test cases:
Input:
solution.solution(15324)
Output:
15129,169,25,1
Input:
solution.solution(12)
Output:
9,1,1,1
I've read that foobar used the 'static method' but I'm not quite sure what that means or how it applies.
No error information is provided by foobar.
I should at least be getting the test cases right...
If I enter this into foobar, it says Test 2 passes:
def solution(area):
   print ("""9,1,1,1""")


text:
Q: Как в список добавить элементы другого списка? Всем добрый день. Есть 2 списка. Как можно в один список засунуть другой список, но только по одному элементу?
sp_with_follow = ['one', 'two', 'three', 'four', 'five']
res_list = ['1', 2, '3', 4, 5]
for i in range(len(sp_with_follow)):
    for cv in sp_with_follow:
        res_list.insert(4, cv)

print(res_list)

Вывод:
['1', 2, '3', 4, 'five', 'four', 'three', 'two', 'one', 'five', 'four', 'three', 'two', 'one', 'five', 'four', 'three', 'two', 'one', 'five', 'four', 'three', 'two', 'one', 'five', 'four', 'three', 'two', 'one', 5]

Но как на выходе получить
['1', 2, '3', 4, 'one', 5, '1', 2, '3', 4, 'two', 5, '1', 2, '3', 4, 'three', 5, '1', 2, '3', 4, 'four', 5, '1', 2, '3', 4, 'five', 5]

A:
a = ['one', 'two', 'three', 'four', 'five']
b = ['1', 2, '3', 4, 5]

def very_strange_combine(a, b):
    res_list = []

    for i in a:
        for j in b:
            res_list.append(j)
        res_list.append(i)

    return res_list

print(very_strange_combine(a, b))


text:
Q: automatic brightness on 18.04 simply does not exist! I have been looking everywhere to make my dell XPS 13.3 running 18.04 LTS adjust the screen brightness automatically.
Initially I found that wildguppy which I did manage to install but it is not working.
Then I installed the dconf which does have an automatic brightness setting but flipping the switch, once again, does nothing!
Then I went to the BIOS and found a dynamic brightness adjustment sth option which was already enabled.... so nothing there too
How can this be possible? How can there be absolutely no way to automatically adjust the brightness on 18.04? I hear this feature exists in 20.04 but I cant upgrade, yet...


text:
Q: Kotlin :Wrapped into a reference object to be modified when captured in a closure I am implementing Firebase on android using kotlin.
as the FirebaseInstanceId.getInstance().token is depriciated, I am using the following function inside the companion object of my MyFirebaseMessageService class to get the token:
companion object
{
  fun grabFcmToken():String?
  {
    var s:String?=null
    FirebaseInstanceId.getInstance().
    instanceId.addOnCompleteListener {task ->
    if (task.isSuccessful)
     {
        s=task.result!!.token
        Log.i("token used is ", s)
     }
     else
      {
        throw Exception("Can't get firebase token")
      }
    }
    Log.i("To be returned token ", s)
    return s
  }
}

Android Studio highlights s as Wrapped into a reference object to be modified when captured in a closure
Upon the execution of grabFcmToken() the first log prints the token successfully, but the second log has a java.lang.NullPointerException: println needs a message indicating that s has the value null and hence it's value is unchanged.
how may i modify s such that the captured token is being reflected in it?

A: The thing here is that, the first log is inside a listener for an asynchronous. task. So it's probably going like this:

*

*Call grabFcmToken()

*FirebaseInstanceId.getInstance().instanceId is called. Here, the task to get the instanceId starts. So you also put in a listener. Since this is an asynchronous task, the code doesn't need to wait so it proceeds.

*Log.i("To be returned token ", s) runs where s is null. NPE here.

I would suggest altering the function to instead return the task or have a listener parameter (first one seems better). Like so:
companion object {
        fun requestPushToken(): Task<InstanceIdResult> {
            return FirebaseInstanceId.getInstance().instanceId
        }
}

Then call it from whichever class you need:
class SampleActivity: AppCompatActivity(){

    YourAppService.requestPushToken().addCompleteListener { task ->
        if (task.isSuccessful){
            // TODO: Handle
        } else {
            // TODO: Handle
        }
    }

}

A: So. I had some sort of epiphany after leaving this post. The current answer didn't actually help, but something clicked.
companion object {
  fun grabFcmToken():String? {
    var s:String? = null // !!!!! s is defined here

    FirebaseInstanceId.getInstance().
      instanceId.addOnCompleteListener {task ->
        if (task.isSuccessful) {
          s = task.result!!.token // !!!!!! s is redefined inside here

          Log.i("token used is ", s)
        } else {
          throw Exception("Can't get firebase token")
        }
      }

    Log.i("To be returned token ", s)

    // !!!!!! s is never changed after the redefine
    return s
  }
}

The third set of super excited !!!! is the important set. Because we never update the state of s anywhere else we get this issue. I say issue because I hate when my IDE tells me something isn't right. So I want to know why it thinks that. I almost fully agree with this. BUT. In your case there isn't a real simple way to change this return. I'm not 1000% you went the way I would have with this, but at the same time it looks like it works.
Overall the point is that if you can instead do something along these lines::
instanceId.addOnCompleteListener { task ->
  val newS = "s"
  if(task.isSuccessful) {
    newS = task.result!!.token // this might give errors, but I think you get the point
  }

  return newS
}

the insignificant warning will disappear.


text:
Q: don't execute a function again while its executing im currently making a game where you have to be able to walk, but when i hold down one of the walk buttons it keeps executing the function.
this is the code i have:

document.addEventListener("keydown", event => {
    if(event.key==="d") {startMoveLeft();}
    if(event.key==="a") {startMoveRight();}
});

document.addEventListener("keyup", event => {
    if(event.key==="d") {stopMoveRight();}
    if(event.key==="a") {stopMoveRight();}
});

document.addEventListener("keyup", event => {
    if(event.key==="d") {stopMoveLeft();}
    if(event.key==="a") {stopMoveLeft();}
});

function startMoveRight() {
    movingRight = setInterval(function(){
        let top =
        parseInt (window.getComputedStyle(floor).getPropertyValue("top"));
        let left =
        parseInt (window.getComputedStyle(floor).getPropertyValue("left"));
        left += 1;
            floor.style.left = left + "px";
    }, 1);
}

function startMoveLeft() {
    movingLeft = setInterval(function(){
        let top =
        parseInt (window.getComputedStyle(floor).getPropertyValue("top"));
        let left =
        parseInt (window.getComputedStyle(floor).getPropertyValue("left"));
        left -= 1;
            floor.style.left = left + "px";
    }, 1);
}

function stopMoveRight() {
    clearInterval(movingRight);
}

function stopMoveLeft() {
    clearInterval(movingLeft);
}

var movingRight = false;
var movingLeft = false;
var movingUp = false;
var movingDown = false;

when i hold down D or A it slowly goes realy fast. so i need to block the "startmoveleft" function when its executing.
does anyone know how to do this?

A: Delete this
document.addEventListener("keyup", event => {
    if(event.key==="d") {stopMoveRight();}
    if(event.key==="a") {stopMoveRight();}
});

document.addEventListener("keyup", event => {
    if(event.key==="d") {stopMoveLeft();}
    if(event.key==="a") {stopMoveLeft();}
});
function startMoveRight() {
    movingRight = setInterval(function(){
        let top =
        parseInt (window.getComputedStyle(floor).getPropertyValue("top"));
        let left =
        parseInt (window.getComputedStyle(floor).getPropertyValue("left"));
        left += 1;
            floor.style.left = left + "px";
    }, 1);
}

function startMoveLeft() {
    movingLeft = setInterval(function(){
        let top =
        parseInt (window.getComputedStyle(floor).getPropertyValue("top"));
        let left =
        parseInt (window.getComputedStyle(floor).getPropertyValue("left"));
        left -= 1;
            floor.style.left = left + "px";
    }, 1);
}

Copy paste this
var direction = "";
function currentDirection(movingToDirection){
    if(movingToDirection != direction){
        stopMoveLeft()
        stopMoveRight()
        return true;
    }
    else {
        return false
    }

}

function startMoveLeft() {

    if(currentDirection("left")){
        direction = "left";
    movingLeft = setInterval(function(){
        let top =
        parseInt (window.getComputedStyle(floor).getPropertyValue("top"));
        let left =
        parseInt (window.getComputedStyle(floor).getPropertyValue("left"));
        left -= 1;
            floor.style.left = left + "px";
    }, 1);
    }
}
function startMoveRight() {
    if(currentDirection("right")){
        direction = "right";
    movingRight = setInterval(function(){
        let top =
        parseInt (window.getComputedStyle(floor).getPropertyValue("top"));
        let left =
        parseInt (window.getComputedStyle(floor).getPropertyValue("left"));
        left += 1;
            floor.style.left = left + "px";
    }, 1);
    }
}

Have fun with the game.


text:
Q: longblob performance storage for lots of records app_files table
+-----------+--------------+------+-----+---------+----------------+
| Field     | Type         | Null | Key | Default | Extra          |
+-----------+--------------+------+-----+---------+----------------+
| file_id   | int(10)      | NO   | PRI | NULL    | auto_increment |
| file_name | varchar(255) | NO   |     | NULL    |                |
| file_data | longblob     | NO   |     | NULL    |                |
+-----------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

If I add 10,000 images to this table and lookup images based on file_id, will the performance
suffer?
I already know it is NOT recommend to store files in the database, but I need this to work with backups in one place.

A: No, the performance will be good, since you're querying on Primary Key, which is already indexed.
However, if you plan to do query on file_name, don't forget to create an index on that field.
And don't do queries on file_data :)


text:
Q: write unicode characters into a file in php I have a json array which is holding the correct string independent of language but when the json is encoded and wrriten into the file it doesnot have the correct values. Its has the the other value random english alphabets eg:(uuadb) I want to write a  string into a file  where the string could be in any language.Now i am testing with tamil language. But i found PHP doesn't support unicode. please help me how to write unicode charaters into the file using PHP.
I tried using pack function but how to use the pack function for any languages Or is there any other way of doing this.Please help me......

A: My guess is that you're seeing \uXXXX escapes instead of the non-ASCII characters you asked for.  json_encode appears to always escape Unicode characters:
<?php
$arr = array("♫");
$json = json_encode($arr);
echo "$json\n";
    # Prints ["\u266b"]

$str = '["♫"]';
$array = json_decode($str);
echo "{$array[0]}\n";
    # Prints ♫
?>

If this is what you're getting, it's not wrong.  You just have to ensure it's being decoded properly on the receiving end.
Another possibility is that the string you're passing is not in UTF-8.  According to the documentation for json_encode and json_decode, these functions only work with UTF-8 data.  Call mb_detect_encoding on your input string, and make sure it outputs either UTF-8 or ASCII.


text:
Q: Drawing by Windows GDI inside of Qt I am trying to use Windows GDI inside of QGraphicsView paintEvent but have noticed some drawing issues, for example the drawing disappear or blinking when I resize window or minimize and maximize. When I use Qt instead of GDI its working perfectly. Here is the code:
[UPDATED CODE]
#include "CustomView.h"

#include <QPainter>
#include <QPaintEngine>
#include <windows.h>
#include <objidl.h>
#include <gdiplus.h>
using namespace Gdiplus;
#pragma comment (lib,"Gdiplus.lib")

CustomView::CustomView(QWidget *parent)
    : QGraphicsView(parent)
{
    setAutoFillBackground(true);
    setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
    setAttribute(Qt::WA_NativeWindow, true);
}

CustomView::~CustomView()
{

}

void CustomView::paintEvent(QPaintEvent * event)
{
    QPainter painter(viewport());
    painter.beginNativePainting();
    // Drawing by Windows GDI
    HWND hwnd = (HWND)viewport()->winId();
    HDC hdc = GetDC(hwnd);

    QString text("Test GDI Paint");
    RECT rect;
    GetClientRect(hwnd, &rect);

    HBRUSH hbrRed = CreateSolidBrush(RGB(0, 255, 0));
    FillRect(hdc, &rect, hbrRed);

    Ellipse(hdc, 50, 50, rect.right - 100, rect.bottom - 100);
    SetTextAlign(hdc, TA_CENTER | TA_BASELINE);
    TextOutW(hdc, width() / 2, height() / 2, (LPCWSTR)text.utf16(), text.size());
    ReleaseDC(hwnd, hdc);
    painter.endNativePainting();

    QGraphicsView::paintEvent(event);

    // Drawing the same by Qt
    //  QPainter painter(viewport());
    //  painter.save() ;
    //  QBrush GreenBrush(Qt::green);
    //  QBrush WhiteBrush(Qt::white);
    //  QRect ViewportRect = viewport()->rect();
    //  painter.fillRect(ViewportRect, GreenBrush);
    //  painter.drawEllipse(50, 50, ViewportRect.right() - 100, ViewportRect.bottom() - 100);
    //  QPainterPath EllipsePath;
    //  EllipsePath.addEllipse(50, 50, ViewportRect.right() - 100, ViewportRect.bottom() - 100);
    //  painter.fillPath(EllipsePath, WhiteBrush);
    //  painter.drawText(ViewportRect.width() / 2, ViewportRect.height() / 2, "Test Qt Paint");
    //  painter.restore();
}

and here is the whole project(Visual Studio 2010 + Qt 5.4.1)[UPDATED ARCHIVE]
https://dl.dropboxusercontent.com/u/105132532/Stackoverflow/Qt5TestApplication.7z
Any ideas?
Solution(edited the code after Kuba Ober's answer)
#include "CustomView.h"

#include <QPainter>
#include <QPaintEngine>
#include <windows.h>
#include <objidl.h>
#include <gdiplus.h>

using namespace Gdiplus;
#pragma comment (lib,"Gdiplus.lib")

CustomView::CustomView(QWidget *parent)
    : QGraphicsView(parent)
{
    // This brings the original paint engine alive.
    QGraphicsView::paintEngine();
    setAttribute(Qt::WA_NativeWindow);
    setAttribute(Qt::WA_PaintOnScreen);
    setRenderHint(QPainter::Antialiasing);
}

CustomView::~CustomView()
{

}

QPaintEngine* CustomView::paintEngine() const
{
    return NULL;
}

bool CustomView::event(QEvent * event) {
    if (event->type() == QEvent::Paint)
    {
        bool result = QGraphicsView::event(event);
        drawGDI();
        return result;
    }
    else if (event->type() == QEvent::UpdateRequest)
    {
        bool result = QGraphicsView::event(event);
        drawGDI();
        return result;
    }
    return QGraphicsView::event(event);
}

void CustomView::drawGDI()
{
    // Drawing by Windows GDI
    HWND hwnd = (HWND)viewport()->winId();
    HDC hdc = GetDC(hwnd);

    QString text("Test GDI Paint");
    RECT rect;
    GetClientRect(hwnd, &rect);

    HBRUSH hbrRed = CreateSolidBrush(RGB(0, 255, 0));
    FillRect(hdc, &rect, hbrRed);

    Ellipse(hdc, 50, 50, rect.right - 100, rect.bottom - 100);
    SetTextAlign(hdc, TA_CENTER | TA_BASELINE);
    TextOutW(hdc, width() / 2, height() / 2, (LPCWSTR)text.utf16(), text.size());
    ReleaseDC(hwnd, hdc);
}

A: A QWidget that intends to paint via GDI only must:

*

*Reimplement paintEngine to return nullptr.

*Set the WA_PaintOnScreen attribute.

*Optionally set the WA_NativeWindow attribute. This only speeds up the first redraw of the widget.

*Reimplement QObject::event and catch Paint and UpdateRequest events. These events should result in calling a method that does the GDI painting. The events must not be forwarded to the base class.
Additionally, a QWidget that paints via GDI on top of contents painted through paintEvent/QPainter, must additionally:

*

*Call base class's paintEngine() method once in the constructor. This will instantiate the native paint engine for the widget.

*In the QObject::event implementation, the base class's event must be called before doing the GDI painting. This will draw the contents using the raster paint engine, and return control to you to overdraw some other contents on top of it.
The example below shows how to overpaint on top of the drawing done by Qt's paint system. Of course, since the painting is done on top contents already drawn by Qt, there's flicker.

Doing GDI painting on top of the Qt's backing store, avoiding the flicker, is also possible, but requires a somewhat different approach.
#include <QApplication>
#include <QGraphicsObject>
#include <QPropertyAnimation>
#include <QGraphicsView>
#include <QPainter>
#include <QPaintEvent>
#include <windows.h>

class View : public QGraphicsView {
public:
   View(QWidget *parent = 0) : QGraphicsView(parent)
   {
      // This brings the original paint engine alive.
      QGraphicsView::paintEngine();
      //setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
      setAttribute(Qt::WA_NativeWindow);
      setAttribute(Qt::WA_PaintOnScreen);
      setRenderHint(QPainter::Antialiasing);
   }
   QPaintEngine * paintEngine() const Q_DECL_OVERRIDE { return 0; }
   bool event(QEvent * event) Q_DECL_OVERRIDE {
      if (event->type() == QEvent::Paint) {
         bool result = QGraphicsView::event(event);
         paintOverlay();
         return result;
      }
      if (event->type() == QEvent::UpdateRequest) {
         bool result = QGraphicsView::event(event);
         paintOverlay();
         return result;
      }
      return QGraphicsView::event(event);
   }
   void resizeEvent(QResizeEvent *) {
       fitInView(-2, -2, 4, 4, Qt::KeepAspectRatio);
   }
   virtual void paintOverlay();
};

void View::paintOverlay()
{
   // We're called after the native painter has done its thing
   HWND hwnd = (HWND)viewport()->winId();
   HDC hdc = GetDC(hwnd);
   HBRUSH hbrGreen = CreateHatchBrush(HS_BDIAGONAL, RGB(0, 255, 0));

   RECT rect;
   GetClientRect(hwnd, &rect);

   SetBkMode(hdc, TRANSPARENT);
   SelectObject(hdc, hbrGreen);
   Rectangle(hdc, 0, 0, rect.right, rect.bottom);

   SelectObject(hdc, GetStockObject(NULL_BRUSH));
   Ellipse(hdc, 50, 50, rect.right - 100, rect.bottom - 100);

   QString text("Test GDI Paint");
   SetTextAlign(hdc, TA_CENTER | TA_BASELINE);
   TextOutW(hdc, width() / 2, height() / 2, (LPCWSTR)text.utf16(), text.size());

   DeleteObject(hbrGreen);
   ReleaseDC(hwnd, hdc);
}

class EmptyGraphicsObject : public QGraphicsObject
{
public:
    EmptyGraphicsObject() {}
    QRectF boundingRect() const { return QRectF(0, 0, 0, 0); }
    void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *) {}
};

void setupScene(QGraphicsScene &s)
{
    QGraphicsObject * obj = new EmptyGraphicsObject;
    QGraphicsRectItem * rect = new QGraphicsRectItem(-1, 0.3, 2, 0.3, obj);
    QPropertyAnimation * anim = new QPropertyAnimation(obj, "rotation", &s);
    s.addItem(obj);
    rect->setPen(QPen(Qt::darkBlue, 0.1));
    anim->setDuration(2000);
    anim->setStartValue(0);
    anim->setEndValue(360);
    anim->setEasingCurve(QEasingCurve::InBounce);
    anim->setLoopCount(-1);
    anim->start();
}

int main(int argc, char *argv[])
{
   QApplication a(argc, argv);
   QGraphicsScene s;
   setupScene(s);
   View view;
   view.setScene(&s);
   view.show();
   return a.exec();
}


text:
Q: JNI ERROR (app bug): accessed stale local reference 0x2d when delete a local reference in native method In a native method, I declare a jstring local reference, after finish with it, I use DeleteLocalRef to delete it ref, but it always reports an error. I've read many websites about JNI reference, but most topics suggest the error maybe cause by use local reference cross the method, but in my case, the jstring object is declared and in the same function, So I'm confusing what's wrong with my code.
Below is my code:
 //jObj is a global reference
 int GetStringField( JNIEnv *env,jobject& jObj, string strFieldName, string& strValue ){
    g_nTestTime++;
    LOGD("GetStringField  %d", g_nTestTime);
    strValue = "";

    jclass clazz = NULL;
    jfieldID fid;
    jstring j_str = NULL;
    const char *c_str = NULL;

    clazz = env->GetObjectClass(jObj);
    if (clazz == NULL) {
        LOGE("Get jObj class object failed in %s!", "GetStringField");
        return -1;
    }

    fid = env->GetFieldID(clazz, strFieldName.c_str(), "Ljava/lang/String;");
    if (fid == NULL) {
        env->DeleteLocalRef(clazz);
        LOGE("can not found %s ref in %s!", strFieldName.c_str(), "GetStringField");
        return -1;
    }

    j_str = (jstring)env->GetObjectField(jObj, fid);
    if (NULL == j_str)
    {
        LOGE("Get String object [%s] value failed in %s!", strFieldName.c_str(), "GetStringField");
        env->DeleteLocalRef(clazz);
        return -1;
    }

    c_str = env->GetStringUTFChars(j_str, NULL);
    if (c_str == NULL) {
        return -1;
    } else{
        strValue = c_str;
    }

    env->ReleaseStringUTFChars(j_str, c_str);

    LOGD("Before env->DeleteLocalRef(clazz)!");
    DumpReferenceTables(env);

    env->DeleteLocalRef(clazz);

    LOGD("After env->DeleteLocalRef(clazz)!");
    DumpReferenceTables(env); // the dump shows 'j_str' still in the local reference table

    env->DeleteLocalRef(j_str); //JNI ERROR (app bug): accessed stale local reference 0x2d (index 11 in a table of size 10)

    LOGD("After env->DeleteLocalRef(j_str)!");
    DumpReferenceTables(env);

    return  0;
}

DumpReferenceTables is a VMDebug class method to dump ReferenceTables,below is his code:
void DumpReferenceTables(JNIEnv *env)
{
    jclass vm_class = env->FindClass("dalvik/system/VMDebug");
    if(NULL == vm_class)
        return ;
    jmethodID dump_mid = env->GetStaticMethodID( vm_class, "dumpReferenceTables", "()V" );
    if(NULL == dump_mid)
        return ;
    env->CallStaticVoidMethod( vm_class, dump_mid );
    env->DeleteLocalRef(vm_class);
}

The logcat in here.


text:
Q: Haskell Diagrams: arrows with fixed orientation I need to draw arrows between two arbitrary "nodes". The arrow ends needs to enter or exit the nodes from one of the four cardinal directions: N, S, E, W.
data Dir = N | S | E | W
     deriving (Eq, Ord, Show)

cir, circles :: Diagram B
cir  = circle 0.3 # showOrigin # lw thick
circles = (cir # named "1") ||| strutX 3 ||| (cir # named "2")

ctrlPoint :: Dir -> V2 Double
ctrlPoint N = r2 (0, 1)
ctrlPoint S = r2 (0, -1)
ctrlPoint E = r2 (1, 0)
ctrlPoint W = r2 (-1, 0)

-- This function should specify an arrow shaft entering nodes from directions dir1 and dir2
shaft :: Dir -> Dir -> Trail V2 Double
shaft dir1 dir2 = trailFromSegments [bézier3 (controlPoint dir1) (controlPoint dir2) (r2 (3, 0))]

example = circles # connect' (with ... & arrowShaft .~ shaft N S ) "1" "2"

In the picture above, the arrow enters correctly from North in the first circle, and South in the second.
However, if I setup the points vertically, everything is rotated:
circles = (cir # named "1") === strutY 3 === (cir # named "2")

This is not correct, because I wanted the arrow to enter from North and South, respectively. It seems the shaft of the arrow is rotated altogether...
How to write my function shaft :: Dir -> Dir -> Trail V2 Double?
Thanks

A: I found an answer using arrowFromLocatedTrail' instead:
-- control points for bézier curves
control :: Dir -> V2 Double
control N = r2 (0, 0.5)
control S = r2 (0, -0.5)
control E = r2 (0.5, 0)
control W = r2 (-0.5, 0)

-- shaft of arrows
shaft :: (P2 Double, Dir) -> (P2 Double, Dir) ->  Located (Trail V2 Double)
shaft (p, d) (p', d') = trailFromSegments [bézier3 (control d) ((p' .-. p) - (control d')) (p' .-. p)] `at` p

-- create a single arrow
mkArrow :: (P2 Double, Dir) -> (P2 Double, Dir) -> Diagram B
mkArrow a b = arrowFromLocatedTrail' (with & arrowHead .~ dart
                                    & lengths .~ veryLarge
                                    & shaftStyle %~ lw thick) (shaft a b)

This version performs the necessary transformations:
bézier3 (control d) ((p' .-. p) + (control d')) (p' .-. p)

Here is the signature ofbézier:
bézier3 :: v n -> v n -> v n -> Segment Closed v n

It takes 3 vectors, named here V1, V2 and V3.
bézier curve are by default not located in Diagrams, they just specify how to move.

So, to draw the bézier curve, we set:
V1 = control d
V2 = (p' .-. p) + (control d')
V3 = p' .-. p

The resulting bézier curve will located at p.


text:
Q: How to Create a C# COM Object using Visual Studio 2019 I have upgraded from Windows 7/Visual Studio 2015 to Windows10/Visual Studio 2019.
I wish to create a C# COM object which I can call from Excel(365) VBA code.
Using Win 7/Visual Studio 2015 the following very simple code compiles as a C# class library and creates a COM object that I can call successfully from Excel 2013 VBA:-
using System.Runtime.InteropServices;
namespace TestLib {
    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.AutoDual)]
    public class C_Hello {
        public string Hello() {
            return "Hello";
        }
    }
}

In the Assembly Info I have ticked the checkbox "Make the Assembly COM Visible" and in the Build info I have ticked the checkbox "Register for COM interop"
The Excel 2013 VBA code is equally simple:
Sub Test()
    Dim x As TestLib.C_Hello
    Set x = New TestLib.C_Hello
    ActiveSheet.Range("C3").Value = x.Hello
End Sub

where TestLib is the C# COM module created in Visual Studio.
In the Win 7/VS2015/Excel 2013 environment everything works fine, but under after transferring and compiling under Win 10/ VS2019 the Excel 365 VBA code errors at the line:-
Set x = New TestLib.C_Hello

with the error message
Run Time error '-2147221164 (80040154)'
Class not registered
Can anyone tell me what I have to do to get this working in the Windows 10 / VS2019 / Excel 365 environment.? Is it Windows 10 or Visual Studio 2019 that is doing things differently?

A: Make sure the bitness of excel matches your build in VS. You will likely need to add an x86 or x64 build for your project.
It is possible to register an AnyCpu assembly, but visual studio does not do so with the "Register for COM interop" for both.  You can manually do so by running both the 32- and 64-bit versions of regasm manually or from a post-build script.
Failing that, you might use ProcMon to check what registration or file Excel is looking for and not finding. Warning, though, that unless you are familiar with the "normal" errors which occur when running it is easy to troubleshoot a red herring. I would recommend filtering by "Path" contains "TestLib.C_Hello" then chase it from there.

A: The solution in the Win10 / VS2019 environemnt was to change the Platform Target in VS's Build Tab from Any CPU to x64, and then it worked.
In the Win7 / VS2015 environment a Platform Target of Any CPU worked fine.


text:
Q: How do you save form data into database before submitting I am trying to save my form data into a wordpress database before submitting it. Please help. Heres my code and the php code to insert into database:
<form method="post" action="https://app.icontact.com/icp/signup.php" name="icpsignup"

id="icpsignup1030" accept-charset="UTF-8" onsubmit="return verifyRequired1030();">
<input type="hidden" name="redirect" value="http://www.123.com/thank-you.html">
<input type="hidden" name="errorredirect" value="http://www.123.com/error.html">
<input type="hidden" name="listid" value="16360">
<input type="hidden" name="specialid:16360" value="MA3A">

<input type="hidden" name="clientid" value="1259610">
<input type="hidden" name="formid" value="1030">
<input type="hidden" name="reallistid" value="1">
<input type="hidden" name="doubleopt" value="0">
<input type="text" name="fields_email" size="21" style="padding:5px;">
<input type="image" name="submit" src="signup button top.png" value="" height="32px">

</form>

And the code to insert into DB:
<?php
    require_once('../../../wp-config.php');
    global $wpdb;
    $table_name = "icontact_emails";
    $email = $_POST[fields_email];
    if (trim($email) != ""){
    $wpdb->insert($table_name, array('email' => $email, 'timestamp'=> date("Y- m-d h:i:s")));
    }
?>

A: "Submitting" is the only way to transfer it to the server, whether you submit the form via AJAX or traditional methods - no difference.
Remember, this is a client-server model. The form is on the client, the DB is on the server.

A: I can INFER from your question that you really mean: I am trying to save this form to a database before I submit it to ANOTHER SITE which I don't control.  Meaning you want to save it to your own database before you submit the data to a 3rd party.
If that's the case here's what I recommend:
Use the form's onSubmit event (<form onSubmit="YourJavasScriptMethod();">).  Use JQuery and $.ajax() to read all of your form inputs and submit them to your own script which can save the values to the database.  At the end of your onSubmit method be sure to return true so the browser will continue to submit the form.
Here's a pseudo-code example:
<form id="myForm" onSubmit="SaveToMyOwnDatabase();">

    <input />... //your inputs

</form>

and your javascript:
function SaveToMyOwnDatabase()
{
    // Create Json object by selecting each of the form inputs
    // Call $.ajax and submit the Json to your script which processes the json

    return true;
}

A: I would recommend using Contact Form 7 (WP plugin).  There is a PHP hook built in that you can use to do this called wpcf7_before_send_mail.  It will pass  an object with all of the contact form data to your custom function(s) which you can use to write to the database or do other server side stuff.  Here's a (really) short example (this goes in functions.php):
add_action( 'wpcf7_before_send_mail', 'save_contact_to_db' );
function save_contact_to_db( $cf7 ) {
    $email = $cf7->posted_data['fields_email'];
    // put database writing stuff here
}

There is a little more info to be had here.  Also this link should be helpful since it's people discussing how to do exactly the same thing you are asking.  There is also a plugin that will automatically write CF7 or Jetpack form submissions to the database for you but I've never used it so I can't comment on it.  In general though I recommend using contact form 7 for this, especially since you are sending the form post data to a php script that is not on your server.

A: I think the solution is simple : submit your form to a PHP page that will : 1) save it in your database and 2) send it wherever you want. By far the simplest and most used solution in your case!


text:
Q: zend framework auto switch production staging test .. etc What do I change to switch from production to staging.. etc.. and where.. Bootstrap ?
Also, Curious if anyone has configured their Zend Framework to automatically switch from
production, staging, test.. etc based on Host information..
example..
 if (hostname = 'prodServer') ... blah
 if (hostname = 'testServer') ... blah

I'm new to Zend but I typically configure my projects to automatically switch
run environments based on the host information.
thanks

A: That work for me in .htaccess
SetEnvIf Host dev.mydomain.ca APPLICATION_ENV=development
SetEnvIf Host mydomain.ca APPLICATION_ENV=production
SetEnvIf Host mydomain.localhost APPLICATION_ENV=production

Then in my application.ini
[development : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.frontController.params.displayExceptions = 1
; Database for development
resources.db.params.dbname = "mydabase-dev"

A: Assuming that you are using APPLICATION_ENV as part of Zend_Application, then you could add this in either your .htaccess or main Apache config (assuming Apache is in use - should still be possible with different Web servers too).
For example, in your .htaccess/config (assumes mod_setenv):
SetEnvIf HTTP_HOST abc.example.com APPLICATION_ENV=production
SetEnvIf HTTP_HOST def.example.com APPLICATION_ENV=staging
SetEnvIf HTTP_HOST ghi.example.com APPLICATION_ENV=development

Then ensure that APPLICATION_ENV is set in index.php by using:
// Define application environment
defined('APPLICATION_ENV') || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));

This is added by Zend_Tool if you use it to generate the project.

A: We define an environment variable (ENVPHP), and use this in our XML configuration files, so the correct DB parameters are loaded as long as you define the correct ENVPHP environment variable. Using XML you can extend (or override) your common parameters with those for the specific environments.
ie. the configuration looks as follows :
<?xml version="1.0" encoding="UTF-8"?>
<application>
    <common>
        <name>MyApp_name</name>
        MyApp_code
        <version>MyApp_version</version>
        <authentication>
            ... authentication specific parameters (ie. LDAP connection parameters)
        </authentication>
        ...
    </common>
    <dev extends="common">
        <database>
            ... DB connection parameters for development
        </database>
        ...
    </dev>
    <tst extends="common">
        <database>
            ... DB connection parameters for test
        </database>
        ...
    </tst>
    <prd extends="common">
        <database>
            ... DB connection parameters for production
        </database>
        ...
    </prd>
</application>

And to load the configuration, I have the following in my bootstrap (well, actually in an Application singleton class) :
public static function getEnv()
{
    if (self::$env === null) {
        self::$env = getenv('ENVPHP');
    } else {
        return self::$env;
    }
}

protected function initConfig ()
{
    $configFile = $this->appDir . '/config/application.xml';
    if (! is_readable($configFile)) {
        throw new Application_Exception('Config file "' . $configFile . '" is not readable');
    }
    if (false === self::getEnv()) {
        throw new Application_Exception('The environment variable "ENVPHP" is not defined');
    }
    $config = new Zend_Config_Xml($configFile, self::getEnv(), true);
    $config->setReadOnly();

    Zend_Registry::set('config', $config);
    $this->config = $config;
}

In PHP code if I want to do some things only for specific environments then I use Application::getEnv() to check what environment I'm in and execute the code I want according to it.
BTW The ENVPHP environment variable can be set in your apache configuration file using ie. SetEnv ENVPHP "dev" within your VirtualHost container. For CLI PHP scripts you should set it as an OS environment variable...

A: The best way that I saw is:
index.php - production
index_dev.php - dev, index_dev.php/controller/action

I also tried host named configs files:
base.ini - base config
localhost.ini - dev config
prod.host.com.ini - prod config

but the first approach is much better.


text:
Q: Which HTML5 tag should I use for a JS event trigger I want to add an element in the footer of my page that the user can click to scroll to the top of the page. So this element would exist without any kind href but would have a JS listener attached to it.
Something like this: <[tag_type]>scroll to top</[tag_type]>
However, I'm not sure what HTML5 tag would be most suitable for this purpose. And so I wondered:
Is there an agreed upon HTML5 tag that is suitable for use solely as an JS event trigger?
I should say, this question is intended to cover more broad cases other than just scrolling to the top, for example: showing/hiding elements, triggering animations etc.

A: It's still a link, and it can even have a href to the top (even though that's no more required in HTML5):
scroll to top
show more
start animation

If you don't like an anchor, you can still use other elements. HTML5 does not define any new ones that were suitable here, but you could e.g. use a plain  or a <button type="button">.

A: I think the best way tot do that is to use .  Your thing is basically a link to the top, so  i think this is semantically correct.


text:
Q: Write to 'text' property of HTTP response using Node HTTP module Is there a way in which I can write to the 'text' property of a HTTP response using the Node HTTP module?
Currently I have something like:
http.createServer((req, res) => {

   ...

   res.writeHead(/* some stuff here */);
   res.write(/* body stuff */);
});

Currently my response is like:
response: {
  ...
  text:{},
  body: { /* some stuff */ }
}

What I'm wanting to know is if I can write to 'text' instead of 'body'?
response: {
  ...
  text: { /* some stuff */ },
  body: {}
}

A: If you take a look at the http anatomy, you have the message header and message body.

Currently my response is like:
response: {
  ...
  text:{},
  body: { /* some stuff */ }
}

Assuming that you are trying to use vanilla Node JS, what the above statement mean is that you are going to have your own structure in the data you are going to send as the http body. (don't mistake this with the "body" of your own structure)
In this context, any data can come under any part of your structure - is the answer to your question. It is completely up to you to decide/interpret the structure of the http body you are going to send to a destination.

I can recommend you to use a framework like express to do most of these structuring automatically.
app.get('/', function (req, res) {
   res.status(200).json({text: 'foo', body: 'bar'})
})


text:
Q: which IP address connects to my server For some internal reasons, several people in our company are sharing the same USERNAME when connecting to SERVER, but they connect from different clients and machines.
We need to track what each IP address does on the server.
Can you suggest how to store the time history of the commands organized by IP address, and not by USERNAME (which would be much easier)? Is that even possible?
Specifics:
SERVER has Ubuntu 14.04.4 LTS installed, and people are connecting and doing operations on it from both Windows and Linux machines.


text:
Q: Error While creating a class whose object cant be created on stack but only on Heap? I tried writing a code to create a class, whose object can only be created on heap but not
stack. But During Compilation I got some linking error.
  # include<iostream>
  # include<stdio.h>
  # include<conio.h>

  using namespace std;

  class Rect
  {
      int length;
      int breadth;
      Rect();

       public :
       Rect & operator = (const Rect&);
       Rect(const Rect& abc)
       {
           cout<<"in copy const"<<"\n";
       }

       ~Rect();
       int area_rect()
       {
           return length*breadth;
       }

       void set_value(int a,int b);

       static Rect* instance()
       {
           Rect* ptr=NULL;
           ptr=new Rect ;
           return ptr;
       }
   };

   void Rect::set_value(int a,int b)
   {
       length=a;
       breadth=b;
   }

   int main()
   {

       Rect* a= Rect::instance();
       a->set_value(10,3);
       cout << "area realted to object a : "  << a->area_rect() <<"\n";
       Rect* b=a;
       b->set_value(10,4);
       cout << "area realted to object a : "  << a->area_rect() <<"\n";
       cout << "area realted to object b : "  << b->area_rect() <<"\n";
       delete b;
       getch();
       return 0;
   }

I got the following error:
ccUfbaaa.o(.text+0x24f) In function `main':   [Linker error] undefined reference to `Rect::~Rect()'
ccUfbaaa.o(.text$_ZN4Rect8instanceEv[Rect::instance()]+0x60) In function `ZN4Rect9area_rectEv':   [Linker error] undefined reference to `Rect::Rect()'
ccUfbaaa.o(.text$_ZN4Rect8instanceEv[Rect::instance()]+0x60) ld returned 1 exit status .

I know I can make destructor private that Will allow object to be crated only on heap . But in that case how can i delete the created object ? And How can we correct this above error?

A: You just have to implement the default constructor and the destructor somewhere:
Rect::Rect():length(0),breadth(0) {};
Rect::~Rect() {};

and then, making public Rect::instance(), Rect::set_value(int, int) and Rect::area_rect(), will help

A: The way you can enforce that your type can only be put on the heap but not on the heap is have a base class with a pure virtual destructor base and to make the destructr private: since the destructor isn't accessible to the full object, it can't be put on to the stack but it can be deleted through a pointer to the base. To prevent a derived class can be put on the stack (if this should be prevented, too) you want to make the type final (which is only available in C++2011, though):
struct A { virtual ~A() = 0; };
A::~A() {}

struct B final: A { private: ~B() {} };

int main()
{
    //B  berror; // ERROR: destructor not accessible
    B* b = new B;
    delete static_cast<A*>(b);
}

The fact some some of your members were declared but not defined was already mentioned in other answers to this questions.


text:
Q: Short sound file plays in Netbeans, but not in jar I am working on a lottery program that updates a list of names in a loop using varying intervals. For each update I want to play a short (300 ms) click.wav. When I run the program in Netbeans, everything works perfectly, but when I build the jar, it refuses to play. The weird thing is that if I lengthen the sound to a few seconds by adding silence at the end, it plays, but then the timing is all off, and it only starts playing after the loop has run 4-5 times.
I'm using thread.sleep() to initiate a pause between loops. While this may not be the best way to do it, it certainly is the easiest, and it doesn't matter for the scope of this program. I've tried using a timer, but the sound still wouldn't play.
This is my code to play the wav file.
private static void play(String filename) {
    URL url = VinLotteri.class.getResource(filename);
    try {
        Clip clip = AudioSystem.getClip();
        clip.open(AudioSystem.getAudioInputStream(url));
        clip.start();
    } catch (LineUnavailableException | UnsupportedAudioFileException | IOException fail) {
    }
}

And here's the loop code. Please ignore (or give constructive criticism) any bad code not related to the problem. I've only been programming for a few months, so there's probably a lot of that.
class StartTrekning extends SwingWorker<String, String> {

    private StartTrekning(List<String> navn, String vinner) {
    }

    @Override
    protected String doInBackground() {
        firstDraw = false;
        Random rnd = new Random();
        int v = 0;
        int vinnerID = -1;
        isRunning = true;
        int counterPluss = 0;
        int counterMinus = 0;

        int rand = rnd.nextInt(17) + 45; // Antall trekninger 45-61
        //Setter opp ulik pause mellom hver trekning
        for (int i = rand; i > 0; i--) {
            if (i > 40) {
                v = 100;
            } else if (i > 35) {
                v = 150;
            } else if (i > 25) {
                v = 200;
            } else if (i > 20) {
                v = 250;
            } else if (i > 15) {
                v = 300;
            } else if (i > 10) {
                v = 400;
            } else if (i > 6) {
                v = 550;
            } else if (i > 3) {
                v = 800;
            } else if (i > 1) {
                v = 1200;
            } else if (i > 0 && rand > 53) {
                v = 2000;
            }

            play(click);
            vinnerID++;//Øker vinnerID, som gir index for navnelisten navn

            //"Loop-kode" (starter listen på nytt når den når slutten)
            if (vinnerID > navn.size() - 1) {
                vinnerID = 0;
            }
            vinner = navn.get(vinnerID);
            int pluss10 = vinnerID;
            int pluss9 = vinnerID;
            int pluss8 = vinnerID;
            int pluss7 = vinnerID;
            int pluss6 = vinnerID;
            int pluss5 = vinnerID;
            int pluss4 = vinnerID;
            int pluss3 = vinnerID;
            int pluss2 = vinnerID;
            int pluss1 = vinnerID;
            int minus1 = vinnerID;
            int minus2 = vinnerID;
            int minus3 = vinnerID;

            if (vinnerID > navn.size() - 11) {
                pluss10 = -10 + counterPluss;
            }
            if (vinnerID > navn.size() - 10) {
                pluss9 = -10 + counterPluss;
            }
            if (vinnerID > navn.size() - 9) {
                pluss8 = -10 + counterPluss;
            }
            if (vinnerID > navn.size() - 8) {
                pluss7 = -10 + counterPluss;
            }
            if (vinnerID > navn.size() - 7) {
                pluss6 = -10 + counterPluss;
            }
            if (vinnerID > navn.size() - 6) {
                pluss5 = -10 + counterPluss;
            }
            if (vinnerID > navn.size() - 5) {
                pluss4 = -10 + counterPluss;
            }
            if (vinnerID > navn.size() - 4) {
                pluss3 = -10 + counterPluss;
            }
            if (vinnerID > navn.size() - 3) {
                pluss2 = -10 + counterPluss;
            }
            if (vinnerID > navn.size() - 2) {
                pluss1 = -10 + counterPluss;
                counterPluss = 0;
            }
            if (vinnerID < 3) {
                minus3 = navn.size() + counterMinus;
            }
            if (vinnerID < 2) {
                minus2 = navn.size() + counterMinus;
            }
            if (vinnerID < 1) {
                minus1 = navn.size() + counterMinus;
            }
            if (vinnerID < 3) {
                counterMinus++;
            }
            if (vinnerID == 3) {
                counterMinus = 0;
            }
            if (vinnerID > navn.size() - 11) {
                counterPluss++;
            }
            //Slutt på "loop-kode"

            // Lager "rulleteksten"
            lblVinner.setText(vinner);
            lblHighlight1.setText(navn.get(minus1 - 1));
            lblHighlight2.setText(navn.get(minus2 - 2));
            lblHighlight3.setText(navn.get(minus3 - 3));
            lblHighlight7.setText(navn.get(pluss1 + 1));
            lblHighlight8.setText(navn.get(pluss2 + 2));
            lblHighlight9.setText(navn.get(pluss3 + 3));
            lblHighlight10.setText(navn.get(pluss4 + 4));
            lblHighlight11.setText(navn.get(pluss5 + 5));
            lblHighlight12.setText(navn.get(pluss6 + 6));
            lblHighlight13.setText(navn.get(pluss7 + 7));
            lblHighlight4.setText(navn.get(pluss8 + 8));
            lblHighlight5.setText(navn.get(pluss9 + 9));
            lblHighlight6.setText(navn.get(pluss10 + 10));
            try {
                Thread.sleep(v);
            } catch (InterruptedException ex) {
                Logger.getLogger(VinLotteri.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        int rand1 = rnd.nextInt(100);
        //Legger inn en liten kunstpause
        if (rand1 < 50) {
            try {
                Thread.sleep(v);
            } catch (InterruptedException ex) {
                Logger.getLogger(VinLotteri.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        panelVinner.append(idVinn + ". Trekning: " + vinner + "\n"); //Skriver ut vinneren
        play(fanfare);
        flashText(lblVinner, Color.WHITE, Color.BLUE, 270, 1650);
        vinnere.add(vinner); //Lager vinnerliste
        idVinn++;
        nyListe(vinnerID, vinner);
        isRunning = false;
        return null;
    }

Any help would be greatly appreciated. Thank you.

A: Well, after (a lot) more troubleshooting it turns out there's not a problem with the code, although I still don't know exactly what is wrong. But I found that if I run the jar file from a command window, everything works fine. If I doubleclick the very same file in Windows, the sound problem is there. So it must be something with how the the file runs when start it in Windows.
At least I can now get it running in Windows by running "java -jar myfile.jar" from a batch file or a Windows shortcut.
Edit: It turns out that it works fine when run on another computer. So there's something with my setup. I'll try uninstalling and reinstalling the JDK.


text:
Q: Model Prediction Partial Least Square Model I am following the procedure explained Hair et al (2021) to run a partial least square model (seminR).
So far, it worked well. However, when using the predict function, I get the following error:
Parallel encountered this ERROR:
Must subset columns with a valid subscript vector.
x Subscript endogenous_items must be a simple vector, not a matrix.
r in summary.connection(connection) : invalid connection
I have recently started working with r. My dataset is an excel table with 579 obs. of 47 variables. How can I solve these problems? Thank you very much in advance.
That's my code:
  composite("EA", multi_items("EA_", 1:3))`
  composite("DB", multi_items("DB_", 1:5)),
  composite("LTB", multi_items("LTB_", 1:5)),
  composite("SN", multi_items("SN_", 1:3)),
  composite("PBC", multi_items("PBC_", 1:3)),
  composite("SE", multi_items("SE_", 1:8)),
  composite("INT", multi_items("INT_", 1:2)),
  composite("B", multi_items("B_", 1:2)))

Create structural model
`final_sm_ext <- relationships(
paths(from = c("DB", "LTB", "SN", "PBC", "SE", "INT"), to = c("B")),
paths(from = c("EA"), to = c("INT")))`

bike_final_model_ext <- estimate_pls('data = PLSdata,
                                 measurement_model = final_mm_ext,
                                 structural_model = final_sm_ext,
                                 inner_weights = path_weighting,
                                 missing = mean_replacement,
                                 missing_value = "-99")

summary_bike_final_model_ext <- summary(bike_final_model_ext)

predict_bike_final_model_ext <- `predict_pls( model = bike_final_model_ext,
  technique = predict_DA, noFolds = 10, reps = 10)```


text:
Q: How to repair corrupt package installation (mysql) After upgrading to Ubuntu 16.04, I noticed mysql was having mind-boggling errors. Convinced, it was a broken setup, I tried running a purge of mysql. That didn't seem to delete everything, so I tried doing it myself:
sudo rm -r /etc/mysql
sudo rm -r /usr/share/mysql-workbench
sudo rm -r /usr/share/mysql
sudo rm -r /usr/share/mysql-common

This was a mistake. Don't EVER try to do this. Now mysql won't even install correctly. I've tried reinstalling the dependancies:
sudo apt-get install --reinstall $(apt-cache depends mysql-server | grep -Po 'Depends:\s+\K[^ ]+$' | tr '\n' ' ' )

And the packages themselves:
sudo apt install mysql-workbench mysql-server --reinstall

But I get all sorts of cryptic errors, such as:
sudo apt-get install --reinstall mysql-server
Reading package lists... Done
Building dependency tree
Reading state information... Done
0 upgraded, 0 newly installed, 1 reinstalled, 0 to remove and 0 not         upgraded.
2 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
E: Internal Error, No file name for mysql-server:amd64

And uninstalling
sudo apt-get remove mysql-common
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 libmysqlclient20 : Depends: mysql-common (>= 5.5) but it is not going to be installed
 mariadb-client-core-10.0 : Depends: mariadb-common (>= 10.0.24-7) but it is not going to be installed
E: Error, pkgProblemResolver::Resolve generated breaks, this may be caused by held packages.

Or if I reconfigure
sudo dpkg --configure -a
Setting up mysql-server-5.7 (5.7.12-0ubuntu1) ...
/var/lib/dpkg/info/mysql-server-5.7.postinst: line 112: /usr/share/mysql-common/configure-symlinks: No such file or directory
dpkg: error processing package mysql-server-5.7 (--configure):
 subprocess installed post-installation script returned error exit status 1
dpkg: dependency problems prevent configuration of mysql-server:
 mysql-server depends on mysql-server-5.7; however:
  Package mysql-server-5.7 is not configured yet.

dpkg: error processing package mysql-server (--configure):
 dependency problems - leaving unconfigured
Errors were encountered while processing:
 mysql-server-5.7
 mysql-server

Or if I Force install:
sudo apt-get -f install
Reading package lists... Done
Building dependency tree
Reading state information... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
2 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
Setting up mysql-server-5.7 (5.7.12-0ubuntu1) ...
/var/lib/dpkg/info/mysql-server-5.7.postinst: line 112: /usr/share/mysql-common/configure-symlinks: No such file or directory
dpkg: error processing package mysql-server-5.7 (--configure):
 subprocess installed post-installation script returned error exit status 1
dpkg: dependency problems prevent configuration of mysql-server:
 mysql-server depends on mysql-server-5.7; however:
  Package mysql-server-5.7 is not configured yet.

dpkg: error processing package mysql-server (--configure):
 dependency problems - leaving unconfigured
No apport report written because the error message indicates its a followup error from a previous failure.
                                                                                Errors were encountered while processing:
 mysql-server-5.7
 mysql-server
E: Sub-process /usr/bin/dpkg returned an error code (1)

Or if I do a purge:
sudo apt-get -f purge mysql-server
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages will be REMOVED:
  mysql-server*
0 upgraded, 0 newly installed, 1 to remove and 0 not upgraded.
2 not fully installed or removed.
After this operation, 159 kB disk space will be freed.
Do you want to continue? [Y/n] y
(Reading database ... 348226 files and directories currently installed.)
Removing mysql-server (5.7.12-0ubuntu1) ...
Setting up mysql-server-5.7 (5.7.12-0ubuntu1) ...
/var/lib/dpkg/info/mysql-server-5.7.postinst: line 112: /usr/share/mysql-common/configure-symlinks: No such file or directory
dpkg: error processing package mysql-server-5.7 (--configure):
 subprocess installed post-installation script returned error exit status 1
Errors were encountered while processing:
 mysql-server-5.7
E: Sub-process /usr/bin/dpkg returned an error code (1)

Is apt unable to recover from a partial install? Do I have to reinstall the OS??

A: After purging mysql as has been shown above, you have to install mysql this way:
sudo apt-get install mysql-common
sudo apt-get install mysql-server

When you install this way you will not have an installation error.

A: I don't know the exact reason, but all these methods did not work for me.
In my case, the procedure that corrected the problem was:
sudo apt-get purge mysql-*
sudo apt-get autoremove
sudo apt-get autoclean
sudo apt-get dist-upgrade

sudo rm -rf /etc/mysql
sudo rm -rf /var/lib/mysql*

and reboot!
finally, I have been able to run
sudo apt-get install mysql-server!

A: Do the following to clean out the broken packages:
sudo apt-get clean
sudo apt-get update
sudo dpkg -r mysql-client-5.7
sudo dpkg -r mysql-server-5.7
sudo dpkg -r libmysqlclient20:i386
sudo dpkg -r libmysqlclient20:amd64
sudo dpkg -r libmysqlclient18:amd64
sudo dpkg -r mysql-common
sudo dpkg -r mysql

After that reinstall it with:
sudo apt-get install mysql mysql-client* mysql-server*

A: Thanks to @Videonauth
sudo dpkg -r mysql-client-5.7
sudo dpkg -r mysql-server-5.7
sudo dpkg -r libmysqlclient20:i386
sudo dpkg -r libmysqlclient20:amd64
sudo dpkg -r libmysqlclient18:amd64
sudo dpkg -r mysql-common

Then running:
sudo apt-get purge mysql\* mariadb\* libmysql\* libmariadb\*

If anything fails, just run sudo dpkg -r <failedpackage> and if THAT fails just remove the package that is dependent on it. If you repeat, eventually apt-get will work again.
See also What is the difference between dpkg and aptitude/apt-get?

A: Try this,
run this command to purge mysql, replace version 5.7 with your installed version
sudo apt purge mysql-client-5.7 mysql-client-core-5.7 mysql-common mysql-server-5.7 mysql-server-core-5.7 mysql-server

run this to clean up and update packages
sudo apt update && sudo apt dist-upgrade && sudo apt autoremove && sudo apt -f install

finally  install mysql
sudo apt install mysql-server

this worked for me.

A: This worked for me
sudo apt-get purge mysql*
sudo apt-get autoremove
sudo apt-get autoclean
sudo apt-get dist-upgrade

then after that I installed mysql again with
sudo apt-get install mysql-server
and now its working fine.

A: I'm also getting these kinds of error and wasted a lot of time. Run these commands
sudo apt-get remove --purge mysql-server
sudo /etc/init.d/mysql stop
sudo apt-get remove --purge mysql-common
sudo rm -rf /var/lib/mysql

sudo apt-get autoremove --purge
sudo apt-get autoclean
sudo apt-get clean

sudo apt update
sudo apt install mysql-server

I found solution on this website
Source of the solution

A: The command sudo dpkg -r does not work for me..
I used sudo apt-get purge mysql-* to uninstall all the releated pageage
and then reinstall them

A: This fixed it for me (MySQL 8.0 - Ubuntu 20.04)
sudo apt-get purge mysql\* libmysql\*
sudo apt autoremove

But the package "mysql-client-core-8.0" don't uninstall, so...
sudo apt --fix-broken install
sudo apt-get --reinstall install mysql-client-core-8.0
sudo apt-get purge mysql\* libmysql\*
sudo apt autoremove
sudo apt update
sudo apt install mysql-server

No more errors!


text:
Q: C# How can I Coppy All Things in RichTextBox? I have a richTextBox and I add text and image. Text are not the same color and font. I want to convert to all things for doc file. I am using this codes for this.
wordeaktar.Application wordapp = new wordeaktar.Application();
wordapp.Visible = true;
wordeaktar.Document worddoc;
object wordobj = System.Reflection.Missing.Value;
worddoc = wordapp.Documents.Add(ref wordobj);
wordapp.Selection.TypeText(richTextBox1.Text);
wordapp = null;

enter image description here
This is the image of my richTextBox. How can I do that?

A: @Gserg's Answer is right!
"richTextBox1.SelectAll(); richTextBox1.Copy(); worddoc.Range().Paste();. However if you simply richTextBox1.SaveFile("...", RichTextBoxStreamType.RichText), Word will be perfectly happy with that. – GSerg"


text:
Q: How do I enable auto code formatting for flake8 in PyCharm I use Tox to run unit tests, with a flake8 command that checks for code formatting errors. Each time I code in PyCharm, I run tox then realise I have a bunch of annoying formatting errors I have to back and manually fix. I would like PyCharm to automatically format the code (according to flake8 google for me each time it auto-saves after I stop typing.
my tox testenv looks like this:
[testenv:flake8]
commands=flake8 <my_code_directory>
deps =
  flake8==2.4.1
  flake8-import-order==0.11
  pep8-naming==0.4.1

[flake8]
max-line-length = 120
import-order-style = google

Is this possible? Do I have to download a specific plugin somewhere? If not with flake8, what about just PEP-8?

A: Flake8 and import ordering are not auto-fixable in a way that complies with what you're seeing. You can auto-fix pep8 with autopep8.
There are discussions here about implementing this for Flake8 though.

A: For automatically sorting import statements use isort. Consider using black to auto-format your Python code.
Edit: ruff can replace flake8 and isort and is also much faster because it's based on Rust. It also supports LSP, so PyCharm you should be able to use it from within PyCharm.

A: The tool you want is probably autopep8. This is especially because the warning codes it uses correspond to the flake8 ones.
For example, if you want to autofix all instances of E701 multiple statements on a single line warning, run the following
for f in `find . -name "*.py"`; do autopep8 --in-place --select=E701 $f; done


text:
Q: Change the customer password field Magento Can anybody explain how magento customer login works.
In fact, I have a bit weird situation. I need to copy all the customer from existing website to new magento website (I want my customers to use the same username password to login to new website). I know how the passwords have been encrypted in the old website (using normal php encrypt() function with salt) but I can't decrypt them. So I thought of adding a new field in customer account called 'oldpassword' (I followed this blog to create new field in customer account).
What I want now is, when importing the customers, save the old encrypted passwords in 'oldpassword' field. When customer tries to login, it should match the password with oldpassword field using the old encryption method. If password, matches, it should generate the standard magento password and save that in default password field. So next time when customer tries to log in, it should check if default password field is not empty, then just login normally.
ADDED
Still waiting for help
I have overwritten the customer->advanceContoller but not quite sure what changes to make in loginPostAction.

A: Please go to page:   app/code/core/Mage/Customer/Model/Customer.php
You can see function public function authenticate($login, $password)
Also you can see
 /**
     * Validate password with salted hash
     *
     * @param string $password
     * @return boolean
     */
    public function validatePassword($password)
    {
        if (!($hash = $this->getPasswordHash())) {
            return false;
        }
        return Mage::helper('core')->validateHash($password, $hash);
    }

    /**
     * Encrypt password
     *
     * @param   string $password
     * @return  string
     */
    public function encryptPassword($password)
    {
        return Mage::helper('core')->encrypt($password);
    }

    /**
     * Decrypt password
     *
     * @param   string $password
     * @return  string
     */
    public function decryptPassword($password)
    {
        return Mage::helper('core')->decrypt($password);
    }

Please check this file.


text:
Q: How to play or pause multiple instances of VLC simultaneously? I have 3 open VLC windows and whenever I see movement in one I need to pause all of them at once. Ideally I'd like a keyboard shortcut to do this. I tried AppleScript but I'm not familiar with the language and I can't see how to iterate through all processes of an application and tell each one individually.

A: This will check for all instances of VLC and pause any of the instances that are currently playing something. Let me know if something unexpected happens! To create the shortcut, follow these steps:

*

*Open Automator and create an Service, with a single Run AppleScript action, containing the following code:
tell application "System Events" to repeat with VLC_instance in (application processes whose name is "VLC")
    tell the menu "Playback" of the first menu bar of VLC_instance
        if the menu item "Pause" exists then
            click menu item "Pause"
        else if the menu item "Play" exists then
            click menu item "Play"
        end if
    end tell
end repeat

*Set the service to receive "no input" and to work in "VLC" or "any application", if you want to ensure you can use the shortcut from anywhere. Save it with a name of your choosing.

*Now, go into the Shortcuts tab in the Keyboard preferences in System Preferences, and click on Services. The newly created service should be at the bottom, under the name you chose. Click on the service, then click on "add shortcut", and specify a shortcut to your liking.

*You may have to allow Automator access in Accessibility in the Privacy tab of the Security and Privacy preferences.

That's it! You should now have a service set up, tied to the shortcut you chose that can be accessed from anywhere.

A: When you have one VLC "active" (in front of you) hit CMD+Q and it is ended.
And so with the next active one.


text:
Q: installing mysql2 gem errors I installed ruby and ruby gems through macport but the gem list does not include mysql2. So how would I get mysql2 gem installed inside my gem list which is inside "/opt/local/bin/gem"
Also, what is the mysql2 gem? I have mysql gem and only want to use mysql, not really sure what it means by mysql2. It gives my a mysql2 error when I try to launch webrick on an app.
UPDATE:
I ran sudo gem install mysql2 and got the following:

Building native extensions.  This
  could take a while... Successfully
  installed mysql2-0.2.7 1 gem installed
  Installing ri documentation for
  mysql2-0.2.7...
Enclosing class/module 'mMysql2' for
  class Client not known
Enclosing class/module 'mMysql2' for
  class Result not known Installing RDoc
  documentation for mysql2-0.2.7...
Enclosing class/module 'mMysql2' for
  class Client not known
Enclosing class/module 'mMysql2' for
  class Result not known

Assuming that mysql2 installed, even though the docs didn't I get the following error when I try to launch webrick in my app.
rails server:

/opt/local/lib/ruby/gems/1.8/gems/mysql2-0.2.7/lib/mysql2/mysql2.bundle:
  dlopen(/opt/local/lib/ruby/gems/1.8/gems/mysql2-0.2.7/lib/mysql2/mysql2.bundle,
  9): Library not loaded:
  libmysqlclient.18.dylib (LoadError)
  Referenced from:
  /opt/local/lib/ruby/gems/1.8/gems/mysql2-0.2.7/lib/mysql2/mysql2.bundle
  Reason: image not found -
  /opt/local/lib/ruby/gems/1.8/gems/mysql2-0.2.7/lib/mysql2/mysql2.bundle
    from
  /opt/local/lib/ruby/gems/1.8/gems/mysql2-0.2.7/lib/mysql2.rb:8
    from
  /opt/local/lib/ruby/gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:64:in
  require'     from
  /opt/local/lib/ruby/gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:64:in
  require'     from
  /opt/local/lib/ruby/gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:62:in
  each'    from
  /opt/local/lib/ruby/gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:62:in
  require'     from
  /opt/local/lib/ruby/gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:51:in
  each'    from
  /opt/local/lib/ruby/gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:51:in
  require'     from
  /opt/local/lib/ruby/gems/1.8/gems/bundler-1.0.7/lib/bundler.rb:112:in
  require'     from
  /Users/summer/Sites/simple_cms/config/application.rb:7
    from
  /opt/local/lib/ruby/gems/1.8/gems/railties-3.0.7/lib/rails/commands.rb:28:in
  require'     from
  /opt/local/lib/ruby/gems/1.8/gems/railties-3.0.7/lib/rails/commands.rb:28
    from
  /opt/local/lib/ruby/gems/1.8/gems/railties-3.0.7/lib/rails/commands.rb:27:in
  tap'     from
  /opt/local/lib/ruby/gems/1.8/gems/railties-3.0.7/lib/rails/commands.rb:27
    from script/rails:6:inrequire'
    from script/rails:6

A: In order to perform a search for remote gems that are available run the command
gem search mysql2 -r (note the -r at the end)
* REMOTE GEMS *
activerecord-mysql2legacydb-adapter (0.2.0)
activerecord-mysql2spatial-adapter (0.3.2)
em_mysql2_connection_pool (0.0.5)
ghazel-mysql2 (0.2.6.3)
mysql2 (0.2.7, 0.2.6 x86-mingw32 x86-mswin32-60)
mysql2_bigint (0.2.6.1)
mysql2_model (0.1.2)
mysql2mysql (0.0.2)
mysql2psql (0.1.0)
mysql2xxxx (0.0.4)
from the list of gems you should pick mysql2 and run
sudo gem install mysql2

A: As far as I know, one of the differences between the two gems (mysql and mysql2) is that mysql2 works better with UTF-8. Here is an article about it.
To install your mysql2 gem, just run:
gem install 'mysql2'


text:
Q: Concatenate NumPy 2D array with column (1D array) Suppose I have a 2D NumPy array values. I want to add new column to it. New column should be values[:, 19] but lagged by one sample (first element equals to zero). It could be returned as np.append([0], values[0:-2:1, 19]). I tried: Numpy concatenate 2D arrays with 1D array
temp = np.append([0], [values[1:-2:1, 19]])
values = np.append(dataset.values, temp[:, None], axis=1)

but I get:
ValueError: all the input array dimensions except for the concatenation axis
must match exactly

I tried using c_ too as:
temp = np.append([0], [values[1:-2:1, 19]])
values = np.c_[values, temp]

but effect is the same. How this concatenation could be made. I think problem is in temp orientation - it is treated as a row instead of column, so there is an issue with dimensions. In Octave ' (transpose operator) would do the trick. Maybe there is similiar solution in NumPy?
Anyway, thank you for you time.
Best regards,
Max

A: In [76]: values = np.arange(16).reshape(4,4)
In [77]: temp = np.concatenate(([0], values[1:,-1]))
In [78]: values
Out[78]:
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
In [79]: temp
Out[79]: array([ 0,  7, 11, 15])

This use of concatenate to make temp is similar to your use of append (which actually uses concatenate).
Sounds like you want to join values and temp in this way:
In [80]: np.concatenate((values, temp[:,None]),axis=1)
Out[80]:
array([[ 0,  1,  2,  3,  0],
       [ 4,  5,  6,  7,  7],
       [ 8,  9, 10, 11, 11],
       [12, 13, 14, 15, 15]])

Again I prefer using concatenate directly.

A: You need to convert the 1D array to 2D as shown. You can then use vstack or hstack with reshaping to get the final array you want as shown:
a = np.array([[1, 2, 3],[4, 5, 6]])
b = np.array([[7, 8, 9]])
c = np.vstack([ele for ele in [a, b]])
print(c)
c = np.hstack([a.reshape(1,-1) for a in [a,b]]).reshape(-1,3)
print(c)

Either way, the output is:
[[1 2 3] [4 5 6] [7 8 9]]

Hope I understood the question correctly


text:
Q: Call function from ascx to .cs of a user control and draw html I have a user control, I want to make if conditions in the ascx, and upon that call a function in the user control and return data from the method to be displayed as html in the ascx. Any ideas? I am still newbie to asp.

A: Just drop a literal onto your user control. Then in your code behind, it'll look something like this:
private void Page_Load(object sender, System.EventArgs e)
{
    // Make your IF conditions here

    MyFunction();
}

private void MyFunction()
{
    string myHtml = "
My Html Code!
";

    literal1.Text = myHtml;
}

That should render your HTML.


text:
Q: pywebkitgtk crashes application when certain page is loaded into web view I used Python 2.7.2 with py27-webkitgtk 1.1.8 on MacOs Lion.
When i launched my programm with following url: http://weefind.com/blwa/
i get error:
** Message: console message: http://connect.facebook.net/en_US/all.js#xfbml=1 @43: RangeError: Maximum call stack size exceeded.
Segmentation fault: 11
My code:
#!/usr/bin/env python

import gtk
import webkit

window = gtk.Window()
view = webkit.WebView()
view.open('http://weefind.com/blwa/')
window.add(view)
window.show_all()
window.connect('delete-event', lambda window, event: gtk.main_quit())

gtk.main()

Please help.

A: I uninstall py27-webkitgtk and webkit-gtk, installed with MacPorts, and
build webkitgtk1.3.1 and pywebkitgtk1.1.8 by myself.
Problem solved.


text:
Q: Is there a specific command to delete all elements of a list? I know that you can simply:
list = [a, b, c, d, e]

for index in list:
    list.remove(index)

but is there a faster way with a single command like:
list.remove(all)

or something along those lines?

A: You can use del and Explain Python's slice notation:
>>> lst = [1, 2, 3, 4]
>>> del lst[:]
>>> lst
[]
>>>
>>> lst = [1, 2, 3, 4]
>>> id(lst)
34212720
>>> del lst[:]
>>> id(lst)  # Note that the list object remains the same
34212720
>>>

A: Yes, you can do del myList[:].  (Don't use list as a variable name, it blocks access to the builtin type called list.)

A: One way I can think of:
myList[:] = []

Or another way can be assigning None to the list, the garbage collector will free up the memory eventually.
("list" is not a good name for a list in python, it's already a type)


text:
Q: Installing Offline Ubuntu 16.04 how to load apt-offline & install <14e4:43b1 system updates install I am installing Ubuntu 16.04. I'm looking for someone who knows that offline installer and update for driver's mainly system  updates and wireless drivers, perfered legacy since my wireless card is an ASUS PCE-AC56 card.
When offline to use command sudo apt-offline I get 'apt-offline command not found' I've tried to install the package for apt-offline and the package is not found.
And finding that I need an apt Sig file generated, I can find what packages I need to download that my system will use to update... Another note, though the apt-offline psckage is not found when I try to install apt-offline. How do I generate the file then download it online to create an update package to update an offline system running Ubuntu. Thank you work arounds welcome and info on this is a great help.

A: By using Ubuntu, You can install Apt-Offline using the following command:

sudo apt-get install apt-offline

If you need any more help, here is a guide in order to help you to Fully Update And Upgrade Offline Debian-based Systems