text:
Q: Does Swift support implicit conversion? For example, I have the following code:
    let numberOfBlocks = 3
    let blockWidth = SKSpriteNode(imageNamed: "image.png").size.width
    let padding = 20.0

    let offsetX : Float = (self.frame.size.width - (blockWidth * numberOfBlocks + padding * (numberOfBlocks-1))) / 2

I got the error:

'Double' is not convertible to 'UInt8'

Is there a way to implicitly convert the data type (maybe only for primitive data type)?
Edit:
I know how to do the explicit conversion by using constructor of particular type as Iducool suggested. But it's not a big help to my question because we even don't know where to add the conversions. I simplified my expression in playground:

The problem is in "padding" variable, the error message is

'Double' is not convertible to 'UInt8'.

So I did the conversion:

Then the problem is in "blockWidth" variable now.
I added the conversion again:

And error message is:

Type 'UInt8' does not conform to protocol 'FloatLiteralCovertible'

The final working expression is:

Is it simple and swift? I don't think so.

A: There is no implicitly cast in Swift.
Easy way of conversion in swift is using constructor of particular type.
Like if you want to get Float from double then you can use Float(doubleValue) and Same way if you want to convert float to integer then you can use Int(floatValue).
In your case:
let intValue = UInt8(doubleValue)

Beware that you will lose any value after the decimal point. So, choose a better way. Above conversion is just to help you in understanding.
Note that Swift always chooses Double (rather than Float) when inferring the type of floating-point numbers.

A: Swift doesn't support implicitly cast anymore in Xcode6 GM. Following answer only apply to Xcode6 beta version.

I don't want to talk about implicitly cast is good or bad, but you can have it if you really want with __conversion()
e.g. If you need UInt8 and Int be able to convert from Double
extension Double {
    func __conversion() -> UInt8 { return UInt8(self) }
    func __conversion() -> Int { return Int(self) }
    // add more if you need to
}

xcrun swift
Welcome to Swift!  Type :help for assistance.
  1> extension Double {
  2.     func __conversion() -> UInt8 { return UInt8(self) }
  3. }
  4> var d = 1.0
d: Double = 1
  5> var u8 : UInt8 = d
u8: UInt8 = 1
  6>

Note: I won't put this in my production code. I only want to point out it if possible but not recommending it.

A: using bridgeToObjectiveC() method you can call the methods provided in Objective - C to convert from one primitive data type to another for e.g.
variable_name.bridgeToObjectiveC().intValue

will convert that variable named variable_name to integer

A: Implicit conversion is possible but with literals only and some conversions are available from the box e.g. Int -> Double:
let a = 3 // Int
let b = 100.5 // Double

// Doesn't work with variables
let c = a * b // Error: Binary operator '*' cannot be applied to operands of type 'Int' and 'Double'

// But this works, because Int(3) literal converts to Double(3.0) implicitly
let d = 3 * b // 301.5

If you want to make backward conversion Double -> Int you should extend Int with ExpressibleByFloatLiteral:
extension Int: ExpressibleByFloatLiteral {
    public init(floatLiteral value: Double) {
        self.init(value)
    }
}

// Double(100.5) converts to Int(100)
let e = a * 100.5 // 300

Even more it's possible to implicitly convert to any type from literals, for instance String -> URLRequest:
extension URLRequest: ExpressibleByStringLiteral {
    public init(stringLiteral value: String) {
        self.init(url: URL(string: value)!)
    }
}

let request: URLRequest = "https://www.google.com"


text:
Q: Replace leading spaces in string with zero in Fortran I want to print a series of time periods in this format yyyymm, eg. 1970010600 to 1980010600 so I get the input as a string and convert the substring to integer, increment it and convert it again to string.
I concatenated these string variable as fln=yyyy//mm, but my output has leading blank spaces. I've used blank descriptors also its not working:
My output is 1971 1, but I need 197101. If it is a two digit month there is no problem.
How can I have a leading zero rather than a leading blank for the month?
A part of the code is:
integer:: m,j,n,k
character(len=12)::fln,st,et
character(len=4)::yy,tt
character(len=2)::mm,dd

 do j=0,k
 ma(j)=m+j
 write(mm,'(BZ,I2)')ma(j)
 fln=yy//mm
 write(19,121)fln
 121 format(A12)

A: Try replacing
write(mm,'(BZ,I2)')ma(j)

with
write(mm,'(I2.2)')ma(j)

then consult your Fortran reference material on the use of I edit descriptors of the form Iw.m.  The BZ edit control descriptor is useful for input only.

redpajama_set_name: RedPajamaStackExchange


text:
Q: jQuery toggle not toggling two divs I'm working on a navigation element where you click on a button and a menu bar slides open revealing the links to other pages. It currently hides the .links divs on load but won't toggle the .links divs and #menuTitle div. I also tried to manually change the css display properties but couldn't get that working either. Here's my code:

$(document).ready(function() {
  $(".links").hide()

  $("#hamburger").on("click", function() {
    $("i").toggle(function() {
      // Changes width of menu bar
      var menuWidth = $("#menu").width() == 700 ? "100px" : "700px";
      $("#menu").animate({
        width: menuWidth
      });

      $('#menuTitle, .links').toggle();
    })
  })
})
#menu {
  background-color: #000;
  width: 100px;
  height: 50px;
  color: #fff;
  overflow: hidden;
}

#hamburger {
  background-color: #000;
  width: 50px;
  height: 50px;
}

Menu

      Home
      Description
      Work Experience
      Projects
      Education
      Certifications


text:
Q: Func / Action delegates with reference arguments/parameters or anonymous functions I just wondered, how the exact syntax is for ref and out parameters for delegates and inline lambda functions.
here is an example
if a function is defined as
 public void DoSomething(int withValue) { }

a delegate in a function can be created by
 public void f()
 {
     Action<int> f2 = DoSomething;
     f2(3);
 }

how is that syntax, if the original function would be defined as
 public void DoSomething(ref int withValue) { withValue = 3; }

A: You can't use Action, Func<T>, or the built-in delegates, but need to define your own in this case:
delegate void ActionByRef<T>(ref T value);

Then, given this, you can have:
int value = 3;
ActionByRef<int> f2 = DoSomething;
f2(ref value);

A: You need to define a new delegate type for this method signature:
delegate void RefAction<in T>(ref T obj);

public void F()
{
    RefAction<int> f2 = DoSomething;
    int x = 0;
    f2(ref x);
}

The reason why the .NET Framework does not include this type is probably because ref parameters are not very common, and the number of needed types explodes if you add one delegate type for each possible combination.


text:
Q: (Socket.SendTo) How do I response/send back data to the client that my server began receive? C# I'm doing an UDP server, I can receive data fine but I don't know how to store the endpoint to send data back.
The commentary at the ultimate line of SetupServer() is where i dont know how to get the EndPoint.
This is my server code:
static private byte[] buffer = new byte[1024];
    static private Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    private const int port = 904;

    static void Main(string[] args) {
        SetupServer();
        Console.ReadLine();
    }
    static private void SetupServer() {
        Console.WriteLine($"{DateTime.Now}: Setting up server on {port}...");
        EndPoint remoteEP = new IPEndPoint(IPAddress.Any, port);
        serverSocket.Bind(remoteEP);
        Console.WriteLine($"{DateTime.Now}: Server created successfully");
        serverSocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref remoteEP,BeginReceive, null);
        //serverSocket.SendTo(buffer, 0, buffer.Length, SocketFlags.None, remoteEP);
    }
    static private void BeginReceive(IAsyncResult ar) {
        int recv = serverSocket.EndReceive(ar);
        byte[] dataBuf = new byte[recv];
        Array.Copy(buffer, dataBuf, recv);
        Console.WriteLine($"{DateTime.Now}: {Encoding.ASCII.GetString(dataBuf)}");

        EndPoint remoteEP = new IPEndPoint(IPAddress.Any, port);
        serverSocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref remoteEP, BeginReceive, null);
    }

A: I figure out how to do it. I replaced the serverSocket.EndReceive(ar) in the BeginReceive method to EndReceiveFrom(ar,ref epSender) and with that end point (epSender) i can call the BeginReceiveFrom method.
    static private void SetupServer() {
    Console.WriteLine($"{DateTime.Now}: Setting up server on {port}...");
    EndPoint remoteEP = new IPEndPoint(IPAddress.Any, port);
    serverSocket.Bind(remoteEP);
    Console.WriteLine($"{DateTime.Now}: Server created successfully");
    serverSocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref remoteEP,BeginReceive, serverSocket);
}
static private void BeginReceive(IAsyncResult ar) {
    EndPoint epSender = new IPEndPoint(IPAddress.Any, port);
    int recv = serverSocket.EndReceiveFrom(ar,epSender);
    byte[] dataBuf = new byte[recv];
    Array.Copy(buffer, dataBuf, recv);
    Console.WriteLine($"{DateTime.Now}: {Encoding.ASCII.GetString(dataBuf)}");

    serverSocket.SendTo(dataBuf,epSender)

    serverSocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref remoteEP, BeginReceive, serverSocket);
}


text:
Q: Is it necessary for a statement to have an inverse in propositional logic? I know that it may be rather self-evident that every statement must possess an inverse, however, is there a way to prove this in propositional calculus or is it considered an axiom?
(Note: By the inverse of a statement I mean its negation)

A: The fact that you can form a negation of every formula is simply a property of the logical language. It will be formally stated as part of the definition of "well-formed formula": Whenever $\varphi$ is a formula, $¬(\varphi)$ is a formula too. You could consider that an "axiom" (the distinction between axioms and definitions being somewhat fluid) if you want.

A: There's a related question, which I suspect might be part of what the OP intends to ask:

Is "logic without negation" a thing?

The answer is yes, in a variety of ways:

*

*In intuitionistic logics, we do have the symbol "$\neg$"; however, it does not behave the way we might expect negation to behave. For example, "$\varphi \vee \neg\varphi$" is usually not provable. Now, an intuitionistic logician may well argue that really, it's classical logic which has a weird notion of negation; however, I'm assuming the OP is coming from the perspective of classical logic, in which case I think intuitionistic logic is at least partially a "logic without negation" (but, don't push that too far!). A related class of examples is paraconsistent logics.

*Another example, without anything that even looks like negation, is dependence logic or its variants. Dependence logic is the logic of, well, dependence: it's the natural logical system you would use to express statements like "for each $x$ and $y$, there is a $z$ depending only on $x$ and a $w$ depending only on $y$ such that . . .". Such statements are in general not expressible in first-order logic; they correspond the $\Sigma^1_1$ assertions, which are not closed under negation. Perhaps surprisingly, if there are sentences $\varphi,\psi$ of dependence logic such that every structure satisfies exactly one of $\varphi$ and $\psi$, then $\varphi$ (and $\psi$) is actually a first-order sentence! So first-order logic captures the "negation-friendly" part of dependence logic.
There are other examples you may or may not find relevant - some many-valued logics might count, depending on what exactly you're asking for - but these are a good starting point.

A: More formal proofs exist, but basically:
Every atomic predicate always has a negation.   If $p$ is such a predicate, $\neg p$ is the negation.
Every logical connective will have a dual; thus every compound predicate has a negation through deMorgan style rules of dual negation.   If $\circ, \bullet$ are such duals, and $p, q$ are predicates, then $\;\neg(p \circ q) = \neg p \bullet \neg q\;$.
[Note: $\neg (p\to q) \;=\; \neg\neg p \wedge \neg q$]
Every quantifier will have a dual; thus every quantified statement has a negation.   If $\mathcal {Q, \bar Q}$ are dual quantifiers, and $p$ a predicate, then $\;\neg (\mathcal Q p) = \mathcal {\bar Q} (\neg p)\;$.
Thus every well formed statement will have a negation, which is a well formed statement.

A: In general science, there's a distinction between definitions and axioms that I think is important to recognize.

*

*A definition arbitrarily associates a linguistic symbol with an algorithm. Examples include "Let X = 5", "Let Red be 400-484 THz," "Let +(x,y) be the addition algorithm," &c.

*An axiom is a type of proposition utilizing definitions that is accepted as self-evident. An example is the commutative property of addition in $\mathbb{Z}$: "+(x,y) = +(y,x)".

Axioms are propositions that need not be proved; definitions are not propositions and thus cannot be proved or disproved.
I could point to a red house and say "I declare this color is called Moob." It's nonsensical and backwards to ask, "Can you PROVE that it's Moob?" The only "proof" to be given is the tautology that it meets the requirements of the definition I just gave.
Logical negation of a statement, in its rawest form, is arbitrarily defined as the statement that has opposite truth values to the original statement. The existence of a negation is implied by the presence of the elements of its definition, namely, the existence of a statement that HAS truth values upon which the definition can be applied.
As others have already suggested, if the logical inverse is defined in your branch of logic then there is no proof to be made.

A: Yes: given a quantified wff F, there is an algorithm to negate F: you start with the outermost quantifier, negate it, and do so until you are done with the quantifiers. Negation at each point preserves well-formedness. Negations are done like this:
1)~$(\forall x P_{xyz..})$ is $\exists x $ ~P
2)~$(\exists x P_{xyz..})$ is $\forall x$ ~$P_{xyz..}$
And this allows you to construct a negation.
EDIT: You can see propositional logic as having 0-predicates and being unquantified. It ultimately comes down to DeMorgan's rules:
$1)$ ~($A$ or $B$)=~A or ~B .
$2)$ ~(A and B)= ~ A or ~B . This gives you all you need. Expanding: We have that $ A \implies B$ is equivalent to ~$A$ or $B$.
We then have a finite collection of connctives like And, Or, and $\implies$ from which we can construct all formulas ( we also have the Prenex form , which I can expand on if you would like me to ), together with a finite collection of atomic formulas $A,B,C$. We then apply DeMorgan's rules to the formulas.
We then do something similar to the above case.


text:
Q: Evaluate $\int\frac{3\cot3x-\cot x}{\tan x-3\tan3x}\,dx$ To evaluate:

$$I= \int_{ }^{ }\frac{3\cot3x-\cot x}{\tan x-3\tan3x}dx$$

My approach:
Convert $\cot x$ and $\cot 3x$ terms into $\tan x$ and $\tan3x$ respectively and use $$\displaystyle \tan3x=\frac{\left(3\tan x-\tan^{3}x\right)}{1-3\tan^{2}x}$$
Further simplification gives me $$\displaystyle I=\int_{ }^{ }\frac{\tan x}{\tan3x}dx$$
How do I proceed further? Any hints are welcome!
Edit:
For anyone wondering how $\int{\tan x/\tan(3x)}dx=\int{(1-3\tan^2x)/(3-\tan^2x)}dx$ don't forget $$\displaystyle \tan3x=\frac{\left(3\tan x-\tan^{3}x\right)}{1-3\tan^{2}x}$$

A: $\int{\tan x/\tan(3x)}dx=\int{(1-3\tan^2x)/(3-\tan^2x)}dx$
Now, we express the numerator as $3-\tan^2x-2(1+\tan^2x)$ so that the integrand becomes
$\int{1-2(\sec^2x/(3-\tan^2x))}dx$.
Now, take $\tan x=t$ and simplify to get $\int{1-2/(3-t^2)}dt$. Now plugin the formulas to get the answer.

A: Lets take $\int\tan(x)\cot(3x)\, dx$.
We write $\tan(x) \cot(3 x)$ as $\frac{\sin(4 x)-\sin(2 x)}{\sin(2 x)+\sin(4 x)}$ which leads to $\int\frac{\sin(4 x)-\sin(2 x)}{\sin(2 x)+\sin(4 x)}\, dx$
Expanding the integrand leads to:
$$
\int\frac{\sin(4 x)}{\sin(2 x)+\sin(4 x)}-\frac{\sin(2 x)}{\sin(2x)+\sin(4 x)}\, dx
=
\int\frac{2\cos(2x)}{2\cos(2 x)+1}-\frac{\sin(2x)}{\sin(2x)+\sin(4x)}\, dx
$$
For the first integrand, we can substitute $u=2x$ and $du=2dx$ which leads to:
$$
\int\frac{\cos(u)}{2\cos(u)+1}\, du-\int\frac{\sin(2x)}{\sin(2x)+\sin(4x)}\, dx
$$
Then substituting for the first integrand $s=\tan\frac{u}{2}$ and $ds=\frac{1}{2}du\sec^2\frac{u}{2}$. Then $\sin u=\frac{2s}{s^2+1}$ and $\cos u=\frac{1-s^2}{s^2+1}$ and $du=\frac{2ds}{s^2+1}$. Then we have:
$
2\int\frac{s^2-1}{s^4-2s^2-3}\, ds-\int\frac{\sin(2x)}{\sin(2x)+\sin(4x)}\, dx=
\int\frac{1}{s^2+1}\, ds-\frac{1}{2\sqrt{3}}\int\frac{1}{s+\sqrt{3}}\, ds-\frac{1}{2\sqrt{3}}\int\frac{1}{\sqrt{3}-s}\, ds-\int\frac{\sin(2x)}{\sin(2x)+\sin(4x)}\, dx
$
The integral of $\frac{1}{s^2+1}$ is $\tan^{-1}(s)$ and for $\frac{1}{s+\sqrt{3}}$ we substitute $p=s+\sqrt{3}$ and $dp=ds$. Since the integral of $\frac{1}{p}$ is $\log p$ we have:
$$
\tan^{-1}(s)-\frac{\log(p)}{2\sqrt{3}}-\frac{1}{2\sqrt{3}}\int\frac{1}{\sqrt{3}-s}\, ds-\int\frac{\sin(2x)}{\sin(2x)+\sin(4x)}\, dx
$$
For the integrand $\frac{1}{\sqrt{3}-s}$ we substitute $w=\sqrt{3}-s$ and $dw=-ds$. Thus our resulting integral is so far:
$
\tan^{-1}(s)-\frac{\log(p)}{2\sqrt{3}}+\frac{\log(w)}{2\sqrt{3}}-\int\frac{\sin(2x)}{\sin(2x)+\sin(4x)}\, dx
=
\tan^{-1}(s)-\frac{\log(p)}{2\sqrt{3}}+\frac{\log(w)}{2\sqrt{3}}-\int\frac{1}{2\cos(2x)+1}\, dx
$
Now lets substitute $v=2x$ and $dv=2dx$:
$$
\tan^{-1}(s)-\frac{\log(p)}{2\sqrt{3}}+\frac{\log(w)}{2\sqrt{3}}-\frac{1}{2}\int\frac{1}{2\cos(v)+1}\, dv
$$
After simplifying the second integrand and perform the resubstitutions we obtain:
$$
x-\frac{2 \tanh ^{-1}\left(\frac{\tan (x)}{\sqrt{3}}\right)}{\sqrt{3}}
$$

A: Simplify the integrand ussin the formulae for triple and double angles to get
$$\frac{3 \cot (3 x)-\cot (x)}{\tan (x)-3 \tan (3 x)}=1-\frac{2}{1+2 \cos (2 x)}$$
Now, use $x=\tan^{-1}(t)$ and everything becomes simple.


text:
Q: Return MySQL error from CFQUERY statement Stupid problem, I have a function that runs a query several times in a  block & reports/emails if/when a query fails. I'm wondering if/how I can capture the actual MySQL error & return it as part of my email/report.
So far I see no way to do this.
Any thoughts?
-thanks
-sean
UPDATE
Thanks Charlie;
I never considered using the cfcatch structure [and truthfully didn't realize it returned so much useful stuff!!]
Unfortunately the host does not allow cfdump so I had to go about it like this:
<cftry>

    <some sql>

<cfcatch type="any">

    <cfscript>
        for (key in cfcatch) {
            try{
                variables.report = variables.report&"
"&key&"="&cfcatch[key]&"
";
            }
            catch(Any excpt) {
                variables.report = variables.report&"
"&key&"=??
";
            }
        }
    </cfscript>

<cfcatch>

<cftry>

A: Isn't the native database error returned as part of the cfcatch?
<cftry>
    (some sql here)
    <cfcatch type="any">
        <cfdump var="#cfcatch#" />
    </cfcatch>
</cftry>

If you run that on a page, and intentionally use some invalid SQL, what do you see in the cfdump?


text:
Q: Calculating the integral periodic functions times the heaviside function
$$\int_0^{t'}sin \left(2t-\frac{\pi}{4} \right)H(t)dt'$$

I tried integrating by parts:
$$dg = sin\left(2t-\frac{\pi}{4} \right) \rightarrow g = -\frac12cos\left(2t-\frac{\pi}{4} \right) $$
$$ f = H(t) \rightarrow df = \delta(t)$$
Plugging everything in:
$$ -H(t)\left(\frac12cos\left(2t-\frac{\pi}{4} \right)\right)|^{t'}_{0}+\int_0^{t'} \delta(t)\frac12cos\left(2t-\frac{\pi}{4} \right) dt'$$
What is the right most integral give me? It seems as though I can't apply any of the properties of the delta function to this integral

A: The Heaviside function is equal to 1 in the entire interior of the integral's domain (assuming $t'>0$).  So
$$\int_0^{t'}sin \left(2t-\frac{\pi}{4} \right)H(t)dt'=\int_0^{t'}sin \left(2t-\frac{\pi}{4} \right)dt'$$


text:
Q: BroadcastReceiver throwing out of memory error. What could be the cause and any solution? I have the use case where, I am trying to send like 20kb of string every second from foreground service to other foreground app using Broadcast Receiver for like 30 minutes. I've noticed that the receiver app is going blank after like 8-10 minutes. I wonder what could be the issue, is sending broadcast this frequently can cause any issue?
I registered the broadcast receiver dynamically in onResume() of fragment, like defined here.
responseReceiver = new ResponseReceiver();
    getApplicationContext().registerReceiver(responseReceiver, new IntentFilter("ACTION_DATA"));


text:
Q: send parameter to a modal and then deleting row After 2 days of researching i decided to ask for some help because i can't move on.
I display a users table in my site. Each row has user's data and a delete user button.
If you press on delete button, a modal has to show up asking you if you want to delete that certain user. That is why i have to send a parameter that is the username.
That modal is a confirm modal with the legend: Are you sure you want to delete //username//?
The thing is that i know how to send the parameter but can't integrate it with jquery deletion function. Also don't have a very clear idea of how to delete a row since i'm really newbie with js and jquery.
So far this is what i have (please notice that im using Smarty template engine):

    {foreach $frontusers as $frontuser}

    {if $frontuser->frontavatar_id eq null}

       {else}

    {/if}
    {$frontuser->username}
    {$frontuser->name}
    {$frontuser->lastname}
    {$frontuser->email}
    {$frontuser->state}
    {$frontuser->creation_date|date_format:"%Y/%m/%d"}

    {if $frontuser->status eq 2}
       Activo
    {else}
       No Activo
    {/if}

    id}">Modificar

    id}" class="btn mini red-stripe confirm-delete" role="button">Delete

       <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>

Delete

Are you sure you want to delete user ....?

       <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
       <button data-dismiss="modal" class="btn red" id="btnYes">Confirm</button>

    {foreachelse}

        No hay Usuarios cargados.

    {/foreach}

this is my js file (i got it from this link )
$('#myModal3').on('show', function() {
var id = $(this).data('id'),
    removeBtn = $(this).find('.red');
})

$('.confirm-delete').on('click', function(e) {
e.preventDefault();

var id = $(this).data('id');
$('#myModal3').data('id', id).modal('show');
  });

$('#btnYes').click(function() {
// handle deletion here
var id = $('#myModal3').data('id');
$('[data-id='+id+']').remove();
$('#myModal3').modal('hide');
   });

So, to sum up i need to adapt my code to do the following:

*

*Send the username as a parameter to the modal

*Delete entire row if confirm button is pressed

UPDATE:
The modal is working, i mean, it opens and closes. modal's Confirm button only deletes "delete button" from the row, not the entire row.

A: Finally could make it work. here a short version of this (without ajax and smarty and harcoded users) online and working:
http://bootply.com/97366
View:

{foreach $frontusers as $frontuser}

    {if $frontuser->frontavatar_id eq null}

    {else}

    {/if}
    {$frontuser->username}
    {$frontuser->name}
    {$frontuser->lastname}
    {$frontuser->email}
    {$frontuser->state}
    {$frontuser->creation_date|date_format:"%Y/%m/%d"}

    {if $frontuser->status eq 2}
    Activo
    {else}
    No Activo
    {/if}

    id}">Edit

    //here in data-title i store the username so later i can "catch it" in the jquery function
    username}" data-id="{$frontuser->id}">Delete

      <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>

Delete

      <button class="btn" data-dismiss="modal" aria-hidden="true">Cerrar</button>
      <button data-dismiss="modal" class="btn red" id="btnYes">Confirmar</button>

  {foreachelse}
  //no users are in the db

     No hay Usuarios cargados.

 {/foreach}

Js File:
//after first function is triggered, modal shows and this function runs
$('#myModal').on('show', function() {
 //catch the id for later deletion, and username to display on modal
 var id = $(this).data('id'),
 username = $(this).data('usern');

 $('#myModal .modal-body p').html("Do you want to delete user: " + '' + username + '' + ' ?');
 })

//when clicking "delete" button from a row, this is the first function that runs
$('.confirm-delete').on('click', function(e) {
 e.preventDefault();
 //catch the user id and username
 var id = $(this).data('id');
 var user = $(this).data('title');

 //assign to the modal id and username
 $('#myModal').data('id', id).modal('show');
 $('#myModal').data('usern', user).modal('show');
});

$('#btnYes').click(function() {
 var id = $('#myModal').data('id');

 //sending to php the row to be deleted from the db
 $.ajax({
  url: 'deleteFrontUser',
  type: 'POST',
  data: 'id='+id,
  success: function(html){

 //removing entire row
 $('[data-id='+id+']').parents('tr').remove();
 $('#myModal').modal('hide');
 }
 });
return false;
});


text:
Q: How to delete child entity after parent entity deleted in Room database? I have two class
@Entity
data class User(
    @PrimaryKey(autoGenerate = true) var uid: Int = 0,
    var name: String?
)

@Entity
data class Note(
    @PrimaryKey(autoGenerate = true) var nid: Int = 0,
    var title: String,
    var description: String?,
    var authorId: Int
)

There was one to many relationship between User and Note:
data class UserWithNotes(
    @Embedded val user: User,
    @Relation(parentColumn = "uid", entityColumn = "authorId")
    var notes: List<Note>
)

By default, if I delete the User, the authorId field in Note will be set to null. How can I delete all Note after User deleted?

A: Make authorId variable in Note as ForeignKey either by annotating variable with ForeignKey annotation or by setting foreignKey variable in Entity annotation.
@Entity(
   foreignKeys = [
        ForeignKey(
            entity = User::class,
            parentColumns = ["uid"],
            childColumns = ["authorId"],
            onDelete = ForeignKey.CASCADE
        )
    ]
)
data class Note(
    @PrimaryKey(autoGenerate = true) var nid: Int = 0,
    var title: String,
    var description: String?,
    var authorId: Int
)

refer this link for better understanding: Room-ForeignKey


text:
Q: PyGTK how to click button and open file in pop-up window I editted the code so that the 3 buttons now show up .Can someone please tell me how to make it so that when I click the button that says Helloworld and application called Helloworld.py will pop-up in another window.Same for the other 2 buttons
!/usr/bin/env python

#  menu.py

import pygtk
pygtk.require('2.0')
import gtk

class MenuExample:
    def __init__(self):
        # create a new window
        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        window.set_size_request(200, 100)
        window.set_title("GTK Menu Test")
        window.connect("delete_event", lambda w,e: gtk.main_quit())

        # Init the menu-widget, and remember -- never
        # show() the menu widget!!
        # This is the menu that holds the menu items, the one that
        # will pop up when you click on the "Root Menu" in the app
        menu = gtk.Menu()

        # Next we make a little loop that makes three menu-entries for
        # "test-menu".  Notice the call to gtk_menu_append.  Here we are
        # adding a list of menu items to our menu.  Normally, we'd also
        # catch the "clicked" signal on each of the menu items and setup a
        # callback for it, but it's omitted here to save space.
        for i in range(3):
            # Copy the names to the buf.
            buf = "Test-undermenu - %d" % i

            # Create a new menu-item with a name...
            menu_items = gtk.MenuItem(buf)

            # ...and add it to the menu.
            menu.append(menu_items)

        # Do something interesting when the menuitem is selected
        menu_items.connect("activate", self.menuitem_response, buf)

            # Show the widget
            menu_items.show()

        # This is the root menu, and will be the label
        # displayed on the menu bar.  There won't be a signal handler attached,
        # as it only pops up the rest of the menu when pressed.
        root_menu = gtk.MenuItem("Root Menu")

        root_menu.show()

        # Now we specify that we want our newly created "menu" to be the
        # menu for the "root menu"
        root_menu.set_submenu(menu)

        # A vbox to put a menu and a button in:
        vbox = gtk.VBox(False, 0)
        window.add(vbox)
        vbox.show()

        # Create a menu-bar to hold the menus and add it to our main window
        menu_bar = gtk.MenuBar()
        vbox.pack_start(menu_bar, False, False, 2)
        menu_bar.show()

        # Create a button to which to attach menu as a popup
        button = gtk.Button("HelloWorld")
        button.connect_object("event", self.button_press, menu)
        vbox.pack_end(button, True, True, 2)
        button.show()

        button2 = gtk.Button("Scrible")
        button2.connect_object("event", self.button_press, menu)
        vbox.pack_end(button2, True, True, 2)
        button2.show()

        button3 = gtk.Button("Final")
        button3.connect_object("event", self.button_press, menu)
        vbox.pack_end(button3, True, True, 2)
        button3.show()

        # And finally we append the menu-item to the menu-bar -- this is the
        # "root" menu-item I have been raving about =)
        menu_bar.append (root_menu)

        # always display the window as the last step so it all splashes on
        # the screen at once.
        window.show()

    # Respond to a button-press by posting a menu passed in as widget.
    #
    # Note that the "widget" argument is the menu being posted, NOT
    # the button that was pressed.
    def button_press(self, widget, event):
        if event.type == gtk.gdk.BUTTON_PRESS:
            widget.popup(None, None, None, event.button, event.time)
            # Tell calling code that we have handled this event the buck
            # stops here.
            return True
        # Tell calling code that we have not handled this event pass it on.
        return False

    def button2_press(self, widget, event):
        if event.type == gtk.gdk.BUTTON2_PRESS:
            widget.popup(None, None, None, event.button, event.time)
            return True
        return False

    def button3_press(self, widget, event):
        if event.type == gtk.gdk.BUTTON3_PRESS:
            widget.popup(None, None, None, event.button, event.time)
            return True
        return False

    # Print a string when a menu item is selected
    def menuitem_response(self, widget, string):
        print "%s" % string

def main():
    gtk.main()
    return 0

if __name__ == "__main__":
    MenuExample()
    main()

A: You could do something like this. I'm assuming you just want to execute your .py files, e.g. helloworld.py etc. I'm using Popen from subprocess to execute python (not assuming the py files are executable) scripts. Note that I've edited the script to only have one button, this is just to show you the idea.
import pygtk
pygtk.require('2.0')
import gtk

import subprocess

class Example:
    def __init__(self):
        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        window.set_size_request(200, 100)
        window.set_title("GTK Menu Test")
        window.connect("delete_event",
                       lambda w,e: gtk.main_quit())

        vbox = gtk.VBox(False, 0)
        window.add(vbox)
        vbox.show()

        button = gtk.Button("HelloWorld")
        button.connect("clicked", self.clicked_helloworld)
        vbox.pack_end(button, True, True, 2)
        button.show()

        window.show_all()

    def clicked_helloworld(self, widget):
        subprocess.Popen(["python", "helloworld.py"])

    def main(self):
        gtk.main()
        return 0

Example().main()


text:
Q: How to find a string inside a code construct (foreach loop) in a code file? I searched around for a similar question but could not find one.
Inside Visual Studio in my code files, I want to find all the foreach loops that contain a particular string of code?  I can easily do a find all foreach but that turns up hundreds and it would be too hard to double click each on to do a manual inspection?
eg.
foreach(var foo in foos)
{
Console.WriteLine("I need search for the string 'Console' inside the foreach.");
}

I thought of regular expressions but I have no idea how to write that.  Not sure if there is another way.

A: Hmm... I guess a regex would be a good way to go. I am not a visual studio user but here's a regex you could use:
foreach\([^\)]+\)[^}]+(YOUR SEARCH STRING HERE)[^}]+}


text:
Q: What is the hexadecimal part in the Documents folder's path? I have a file located in my app's Documents folder. When the app is terminated I save the file's URL in the AppDelegate's applicationWillTerminate method:
// archiver init code
[archiver encodeObject:file.URL forKey:kFileURL];
// finish encoding and write data to file system

But when trying to restore the file on the next app launch the file manager cannot locate the file: After calling
NSURL *fileURL = [unarchiver decodeObjectForKey:kFileURL];
NSString *filePath = fileURL.path;

the method
[[NSFileManager defaultManager] fileExists:filePath];

returns NO.
I tried to find the reason for this and I discovered that the path to the Documents folder changes with every app launch. The part that changes is the hexadecimal folder in the middle. Here are two examples:
/private/var/mobile/Applications/04083A4A-87AC-4E3C-8BA1-F002B97AE304/Documents/...
/private/var/mobile/Applications/65D136BA-42C3-887A-B947-7FE396978153/Documents/...

I always thought that the hexadecimal part is some sort of ID unique to every app. But as it changes: What exactly is that number?
And how can I relocate my file then after terminating and relaunching my app?

A: You should just get the directory for the document folder and then load your file.
+ (NSString *)documentDataPath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    if ([paths count] == 0) {
        return nil;
    }
    NSString *directory = [paths objectAtIndex:0];
    if (directory == nil) {
        NSLog(@"NSDocumentDirectory not found!");
    }
    return directory;
}


text:
Q: What would be the optimal way to replace the text in the project code with the t function from i18next? I was given a task to implement a localization for the whole mobile app on react native with i18next, react localize.
There is a lot of text in many files and so far the only way is to do it manually. Search through the files and then replace the text with the corresponding t reference to the translation file.
Is there actually another way of doing it faster and more convenient?
I made changes in quite many files to the moment. Sometimes thinking if there is a better way to optimize this process.

A: If by chance your original language isn't English - You can search for characters in that language (using a regex). That will surface all the strings that are user facing (otherwise the code is in English).
Aside from that, I think regex's are your friend. You can search for ".*?" and similar to catch strings.
If you already have a translation file, then you could write a simple script that pulls a translated string, searches for it in project source files, and replaces the occurence with the t() equivalent.
Hope this helps

A: Almost all visible text (exceptions are placeholder and accessibilityLabels) would be in <Text> so you can probably override it with a higher-order component to use the existing text value looked up via i18n-next.  It's not perfect but it would be a start.
This would do the reverse of what you want (in that it replaces text with i18n keys) https://github.com/trajano/spring-cloud-demo/blob/rework/expo-app/src/lib/native-unstyled/hoc/withI18n.tsx.  But I used that along with my hoc template
(note untested)
import {
  ComponentType,
  forwardRef,
  NamedExoticComponent,
  PropsWithoutRef,
  ReactElement,
  Ref,
  RefAttributes,
} from "react";

export function withChildrenAsI18n<P extends Q, Q extends TextProps, T>(
  Component: ComponentType<Q>,
  _options?: O
): NamedExoticComponent<PropsWithoutRef<P> & RefAttributes<T>> {
  function useWrapped({children, ...rest}: P, ref: Ref<T>): ReactElement<Q> {
    const translatedChildren = t(children);
    const componentProps: Q = {...rest, children: translatedChildren } as Q;
    return <Component {...componentProps} ref={ref} />;
  }
  const displayName = Component.displayName ?? Component.name;
  useWrapped.displayName = `withChildrenAsI18n(${displayName})`;
  return forwardRef(useWrapped);
}

then add something like
import {
  Text as RNText,
} from "react-native";
export const Text = withChildrenAsI18n(RNText);

Then do a search and replace the text import with this replacement.


text:
Q: Read Characteristic from rxBleDevice gives exception in Android, in iOS why it works fine using same UUID Currently i am working with an application where it involves reading data from the ble device. I am trying to read data from Andesfit Thermometer, Andesfit Blood Pressure, Andesfit Body Weight Scale.
For that i need to notify using Characteristic UUID. The notification stuff works fine and i am receiving data properly when any of the devices emits data.
Think about a situation where the user has already taken a measurement using the blood pressure machine. Then he picked up his device, got connected. I should be able to retrieve the last record and show it in the device.
In order to show the last record i need to read the characteristic using UUID
In iOS i am can retrieve the last record & notify using the same characteristic UUID and it is working fine.
 characteristic UUID is 2A1C

 peripheral.setNotifyValue(true, for: characteristic)
 peripheral.readValue(for: characteristic)

But in Android if i try to read using the characteristic UUID that used for notify it gives me exception.
rxBleDevice.establishConnection(false, Timeout(12000, TimeUnit.MILLISECONDS))
                .flatMapSingle { rxBleConnection ->

                    rxBleConnection.readCharacteristic(UUID.fromString("00002a1c-0000-1000-8000-00805f9b34fb"))
                        .subscribe({bytes ->

                    },{t: Throwable? ->
                        var mess = t!!.localizedMessage
                        t.printStackTrace()
                    })

Exception message is
GATT exception from MAC address F4:5E:AB:0D:7B:93, with type BleGattOperation{description='CHARACTERISTIC_READ'}
Here is my service discovery operation in Android
In my service discovery i can clearly see that this characteristic UUID is just meant for notify.
V/RxBle#ServiceDiscoveryOperation: Primary Service - Health Thermometer (00001809-0000-1000-8000-00805f9b34fb)
V/RxBle#ServiceDiscoveryOperation: Instance ID: 51
V/RxBle#ServiceDiscoveryOperation: -> Characteristics:
V/RxBle#ServiceDiscoveryOperation:  * Temperature Measurement (00002a1c-0000-1000-8000-00805f9b34fb)
V/RxBle#ServiceDiscoveryOperation:    Properties: [ INDICATE ]
V/RxBle#ServiceDiscoveryOperation:    -> Descriptors:
V/RxBle#ServiceDiscoveryOperation:      * Client Characteristic Configuration (00002902-0000-1000-8000-00805f9b34fb)
V/RxBle#ServiceDiscoveryOperation:      * Characteristic Presentation Format (00002904-0000-1000-8000-00805f9b34fb)
V/RxBle#ServiceDiscoveryOperation:  * Temperature Type (00002a1d-0000-1000-8000-00805f9b34fb)
V/RxBle#ServiceDiscoveryOperation:    Properties: [ READ ]
V/RxBle#ServiceDiscoveryOperation:  * Intermediate Temperature (00002a1e-0000-1000-8000-00805f9b34fb)
V/RxBle#ServiceDiscoveryOperation:    Properties: [ NOTIFY ]
V/RxBle#ServiceDiscoveryOperation:    -> Descriptors:
V/RxBle#ServiceDiscoveryOperation:      * Client Characteristic Configuration (00002902-0000-1000-8000-00805f9b34fb)
V/RxBle#ServiceDiscoveryOperation:  * Measurement Interval (00002a21-0000-1000-8000-00805f9b34fb)
V/RxBle#ServiceDiscoveryOperation:    Properties: [ READ WRITE INDICATE ]
V/RxBle#ServiceDiscoveryOperation:    -> Descriptors:
V/RxBle#ServiceDiscoveryOperation:      * Client Characteristic Configuration (00002902-0000-1000-8000-00805f9b34fb)
V/RxBle#ServiceDiscoveryOperation:      * Valid Range (00002906-0000-1000-8000-00805f9b34fb)
V/RxBle#ServiceDiscoveryOperation: Primary Service - Battery Service (0000180f-0000-1000-8000-00805f9b34fb)
V/RxBle#ServiceDiscoveryOperation: Instance ID: 65
V/RxBle#ServiceDiscoveryOperation: -> Characteristics:
V/RxBle#ServiceDiscoveryOperation:  * Battery Level (00002a19-0000-1000-8000-00805f9b34fb)
V/RxBle#ServiceDiscoveryOperation:    Properties: [ READ NOTIFY ]
V/RxBle#ServiceDiscoveryOperation:    -> Descriptors:
V/RxBle#ServiceDiscoveryOperation:      * Client Characteristic Configuration (00002902-0000-1000-8000-00805f9b34fb)
V/RxBle#ServiceDiscoveryOperation:      * Report Reference (00002908-0000-1000-8000-00805f9b34fb)
V/RxBle#ServiceDiscoveryOperation: --------------- ====== Finished peripheral content ====== ---------------

A:
why it works fine using same UUID (on iOS and on Android it does not)?

As you can see the characteristic you want to read has property [INDICATE] and not [READ]. Android OS checks permissions of the characteristic before performing an operation on it and does not allow to start one if the target characteristic does not have a corresponding property. iOS on the other hand executes the operation and the peripheral may (or may not) accept it regardless of this characteristic properties.


text:
Q: WebLogic REST API - stop/start a JDBC Data Source How can I start/stop/reset a JDBC datasource in the new (12.2.1+) WebLogic REST API under
/management/weblogic/latest?
The old management REST API (12.1.3) had this endpoint with start/shutdown/reset as operations, which worked fine:
/management/wls/latest/datasources/id/{id}
I just cannot find JDBC control capabilities anywhere, eg. not here:
/management/weblogic/latest/edit/JDBCSystemResources/{id}/
/management/weblogic/latest/serverRuntime/JDBCServiceRuntime/
The REST documentation from Oracle only gives examples for creating/editing JDBC datasources, which I am not looking for:
https://docs.oracle.com/middleware/1221/wls/WLRUR/examples.htm#WLRUR208
Are there control capabilities? Is there maybe better REST API documentation?

A: REST Dokumentation for JDBC-Actions:
[https://docs.oracle.com/en/middleware/fusion-middleware/weblogic-server/12.2.1.4/wlrsr/api-jdbc-data-source-runtime-jdbc-service-runtime-jdbc-data-source-runtime-mbeans-actions.html][1]
This works on my machine (with Managed Server):
-X POST
${wlUrl}/management/weblogic/latest/domainRuntime/serverRuntimes/${server}/JDBCServiceRuntime/JDBCDataSourceRuntimeMBeans/${datasource}/stop


text:
Q: Can't paste 'π' character into psql query I'm ssh'd into a redhat appliance using putty and from there I am running psql to query a postgres database. I have validated that my putty, redhat, and psql encoding are all set to utf8.
If I query a record that has π in it results display correctly, including π. I can also paste the character into the putty session and it appears correctly. For example:
hostname:~ # π

What I cannot do is paste the character into psql. When I try to paste the character nothing happens. Any ideas?


text:
Q: .Net Core Entity Framework Can't add http put method Prject.csproj, provides the following lines:
    <Project Sdk="Microsoft.NET.Sdk.Web">
      <PropertyGroup>
        <TargetFramework>netcoreapp3.0</TargetFramework>
     </PropertyGroup>
     <ItemGroup>
        <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.1"/>
        <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="3.0.0"/>
        <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.0.0"/>
        <PackageReference Include="Microsoft.IdentityModel.Tokens" Version="5.6.0"/>
        <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="5.6.0"/>
        <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.0.0"/>
        <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0"/>
        <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="7.0.0"/>
        <PackageReference Include="CloudinaryDotNet" Version="1.8.0"/>
        <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="3.1.1"/>
        <PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="3.1.0"/>
        <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.0.0"/>
        <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.1"/>
     </ItemGroup>
   </Project>

I'm using this model:
namespace Amaz.API.Models
{
    public class Cosa
    {
        public int Id {get; set;}
        public int UserId {get; set;}
        public string descripcion {get; set;}
    }
}

Which is designed this way in the DataContext.cs as far as EntityFramework is used:
using Amaz.API.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace Amaz.API.Data
{
    public class DataContext : IdentityDbContext<User, Role, int, IdentityUserClaim<int>,
    UserRole, IdentityUserLogin<int>, IdentityRoleClaim<int>, IdentityUserToken<int>>
    {
        public DataContext(DbContextOptions<DataContext> options) : base(options) {}

        public DbSet<Value> Values { get; set; }
        public DbSet<Photo> Photos { get; set; }
        public DbSet<Like> Likes { get; set; }
        public DbSet<Message> Messages { get; set; }
        public DbSet<Familiar> Familiars { get; set; }
        public DbSet<Situation> Situations { get; set; }

        public DbSet<Cosa> Cosas { get; set; }

          protected override void OnModelCreating(ModelBuilder builder)
         {
             base.OnModelCreating(builder);

             builder.Entity<UserRole>(userRole =>
             {
                 userRole.HasKey(ur => new {ur.UserId, ur.RoleId});

                 userRole.HasOne(ur => ur.Role)
                    .WithMany(r => r.UserRoles)
                    .HasForeignKey(ur => ur.RoleId)
                    .IsRequired();

                 userRole.HasOne(ur => ur.User)
                    .WithMany(r => r.UserRoles)
                    .HasForeignKey(ur => ur.UserId)
                    .IsRequired();
             });

             builder.Entity<Like>()
                 .HasKey(k => new {k.LikerId, k.LikeeId});

              builder.Entity<Like>()
                 .HasOne(u => u.Likee)
                 .WithMany(u => u.Likers)
                 .HasForeignKey(u => u.LikeeId)
                 .OnDelete(DeleteBehavior.Restrict);

              builder.Entity<Like>()
                 .HasOne(u => u.Liker)
                 .WithMany(u => u.Likees)
                 .HasForeignKey(u => u.LikerId)
                 .OnDelete(DeleteBehavior.Restrict);

             builder.Entity<Message>()
                 .HasOne(u => u.Sender)
                 .WithMany(m => m.MessagesSent)
                 .OnDelete(DeleteBehavior.Restrict);

              builder.Entity<Message>()
                 .HasOne(u => u.Recipient)
                 .WithMany(m => m.MessagesReceived)
                 .OnDelete(DeleteBehavior.Restrict);

              builder.Entity<Photo>().HasQueryFilter(p => p.IsApproved);

              builder.Entity<Familiar>()
                 .HasOne(u => u.Users)
                 .WithMany(m => m.Familiars)
                 .OnDelete(DeleteBehavior.Restrict);

              builder.Entity<Situation>();

              builder.Entity<Cosa>();

         }
    }
}

And the controller is:
    using System.Linq;
    using System.Security.Claims;
    using System.Threading.Tasks;
    using System.Collections.Generic;
    using AutoMapper;
    using CloudinaryDotNet;
    using CloudinaryDotNet.Actions;
    using Amaz.API.Data;
    using Amaz.API.Dtos;
    using Amaz.API.Helpers;
    using Amaz.API.Models;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Options;

    namespace Amaz.API.Controllers
    {
        [ServiceFilter(typeof(LogUserActivity))]
        [Authorize]
        [Route("api/[controller]")]
        [ApiController]
        public class CosaController : ControllerBase
        {
            private readonly IVVRepository _repo;
            private readonly IMapper _mapper;
            public CosaController(IVVRepository repo, IMapper mapper)
            {

                _mapper = mapper;
                _repo = repo;

            }

            [HttpPost]
            public async Task<IActionResult> PutCosa(CosaDto CosaDto)
            {
                var CosaToCreate = _mapper.Map<Cosa>(CosaDto);
                _repo.Add(CosaToCreate);

                return NoContent();
            }

            [HttpGet("{id}")]
            public async Task<IActionResult> GetCosa (int id)

            {

                  var cosareturn = await _repo.GetCosa(id);

                  if (cosareturn == null)
                     return NotFound();

                  return Ok(cosareturn);
            }

            [HttpPut("{id}")]
            public async Task<IActionResult> UpdateCosa(int id, CosaDto CosaDto)
            {

                var cosa = await _repo.GetCosa(id);

                _mapper.Map(CosaDto, cosa);
                return NoContent();
            }

            [HttpDelete("{id}")]
            public async Task<IActionResult> DeleteCosa (int id)

            {
                  var CosaFromRepo = await _repo.GetCosa(id);
                  _repo.Delete(CosaFromRepo);

                  return NoContent();
            }
        }
    }

But the main problem is that it is not possible to add a new register to the database through this "PutCosa" method. As Its tested in Postman:

What could be failing here and how to solve it?

A: In EF you actually need to Save your changes on the context so that EF will put the changes to the DB. See here https://learn.microsoft.com/en-us/ef/core/saving/basic
        [HttpPost]
        public async Task<IActionResult> PutCosa(CosaDto CosaDto)
        {
            var CosaToCreate = _mapper.Map<Cosa>(CosaDto);
            _repo.Add(CosaToCreate);
            _repo.SaveChanges();
            return NoContent();
        }


text:
Q: apache vhost redirect to https except a subdomain I have a domain with SSL: https://www.example.de
Here ist my redirect, which runs very well.
RewriteEngine On

RewriteCond %{HTTP_HOST} ^example\.de$
RewriteRule ^/(.*)$ https://www.example.de/$1 [L,R=301]

RewriteCond %{HTTPS} off
RewriteCond %{HTTPS_HOST} !^www.example.de$ [NC]
RewriteRule ^/(.*)$ https://www.example.de/$1 [L,R=301]

But now, I have a subdomain http://click.example.de , which should be running over HTTP and not HTTPS.
At this moment the rules above are redirecting everything, also click.example.com to https://www.example.de .
How to except this subdomain, so it can remain on HTTP and resolve?
Thanks
Nik

A: Use:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^click\. [NC]
RewriteRule ^ - [L]

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]

HTTPS_HOST does not exist. You must use HTTP_HOST.


text:
Q: Möbius function for posets and primes
Let the Möbius function $\mu_P : P \times P \rightarrow \mathbb{Z}$ for a poset $P$ be defined as $$\mu_P(x,y) = \begin{cases} 0 & x \not\leq y \\ 1 & x = y \\ - \sum\limits_{x \leq z < y}\mu_P(x,z) & x \leq y \end{cases} $$
  Let further $P_n$ be the set of divisors of $n \in \mathbb{N}$ with $P_n$ being ordered by the divisibility relation.
Show that $\mu_{P_n}(1,n) = (-1)^m$ if $n = p_1 \cdots p_m$  with $p_1,\cdots,p_m$ being pairwise different primes.

I am looking for a pure combinatorial proof without using other definitions of the Möbius function.
I thought about the relation of n being a product of different primes and the divisors of n, but don't really know how to start. Can you tell me how this can be shown?

A: Let us write $\mu(n) = \mu_{P_{n}}(1, n)$.
Using only the definition, prove that $\mu$ is multiplicative, that is,
$$
\mu(xy) = \mu(x) \mu(y)
$$
if $\gcd(x, y) = 1$.
Then show that $\mu(p) = -1$ if $p$ is prime.
This is all you need. But you may also want to prove that $\mu(p^{n}) = 0$ if $p$ is a prime, and $n > 1$. This gives a general formula (assuming factorization) for the Moebius function.

Try it out yourself, but you can read some of the details on p. 13 here.

In response to the comment below by OP. When the order relation $P$ is divisibility, and $x \ne 1$, we have
$$
\mu_{P} (1, x) = - \sum_{z \mid x, z \ne x} \mu_{P}(1, z),
$$
so that if we write $\mu(x) = \mu_{P} (1, x)$ we have
$$
\sum_{z \mid x} \mu(z) = 0
$$
for $x \ne 1$, as in the reference above.


text:
Q: Getting crontab on MAC to run anaconda installed python script (module not found) I am trying to set up crontab for a script written in python which is intalled via Anaconda. The simple .py runs (it just loads a module for a demo) and can be run in terminal with python a.py .
The problem is getting crontab the path for python and imported modules.
I have been trying to set the PATH and PYTHONPATh to the python directory and also where pandas is located. I think this is a env issue but have no idea what that means. Any ideas?
The crontab is:
SHELL=/bin/sh
PYTHONPATH=/Users/Esel/anaconda3/bin/python
* * * * *  cd /Users/Esel/Documents/x/y/z && python a.py

The python (test) script:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 18 21:36:34 2019

@author: Esel
"""

import pandas

print('hello kitty')
# This is a test

Crontab mails the following statement:
Traceback (most recent call last):
  File "a.py", line 3, in
    import pandas
ImportError: No module named pandas

A: You're setting an env.var, cd'ing to a directory, and calling an interpreter, all from crontab.
Under those circumstances, personally I'd find it more elegant to just create a small wrapper script (here called pyscript) that does all that, and call that script from crontab:
$> cat /home/me/bin/pyscript
#!/bin/bash
# a.py needs module pandas in /foo/bar
export PYTHONPATH=/foo/bar
cd /Users/Esel/Documents/x/y/z || exit
python a.py

$> chmod ug+rx /home/me/bin/pyscript

$> cat /var/spool/cron/crontabs/me
...
* * * * *  /home/me/bin/pyscript

A: With some ideas from a roadowl (thanx) and another SOverflow question (54564187) I think I got it running.
SHELL=/bin/sh
PATH=$PATH/Users/Esel/anaconda3/bin:/Users/Esel/anaconda3/condabin:/Applications/anaconda3/bin:/Applications/anaconda3/bin:/Users/Esel/anaconda3/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
* * * * *  cd /Users/Esel/Documents/x/y/z && python a.py

The path came from
echo $PATH


text:
Q: Arch Linux doesn't mount two USB drive? One is USB modem which is connected and working and problematic one is a plain vfat USB stick which contain data ....that is the fellow not mounting :(
I have tried to see it by fdisk ....it doesn't mount autometically...
Is there any UDEV rule for that?? Because I have put a udev rule to remove the usb-storage thing( I had to.. otherwise the usb modem wont get connected... it waits for storage to relase the port)
Any idea and solution would be greatly appreciated
PS: I am running Arch distribution.
Thanks

A: sorted out...usb-storage module was not loading.


text:
Q: Statusbar translucent and colored like Gmail Android app on Lollipop I would like to reproduce the Gmail app status bar behavior on 5.0 as a resume:

*

*When the Navigation Drawer is closed the status bar color is dark red

*When the navigation drawer is opened it opens under the status bar that is now translucent.

*The Toolbar (former ActionBar) is always under the status bar.

I'm using the compact library v21, and I have added a toolbar to my main activity.xml:
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"
    android:background="?attr/colorPrimaryDark"
/>

I'm using a theme based on Theme.AppCompat.NoActionBar
1) With that my statusbar is colored, but the navigation drawer is opened just below the status bar, and not under the status bar.
2) Then I make the statusbar translucent adding:
<item name="android:windowTranslucentStatus">true</item>

But this moves up the entire toolbar under the status bar hiding it partially. The navigation drawer is opened under the status bar.
3) To solve it have tried to move down the toolbar with a "margintop" with the size of the statusbar. With that change the statusbar is transparent without color.
4) So my last intent is to add another toolbar with the status bar height, on top of the "toolbar" that is acting as an ActionBar. I colored this toolbar with the darkcolor. The problem is that to make that work it needs to know the statusbar height on all devices.
Also the last one would not work on pre v21 so I would need to use the "new toolbar" only on v21.
All of this seems a little patchy for me so I would like to know if there are another way more "standard" to accomplish such "small" feature.
The solution given at https://stackoverflow.com/a/26440880/557179 only works if the navigation drawer is defined inside the drawerLayout or with an include. But in my case the Navigation drawer is defined as a Fragment on the DrawerLayout hierarchy, and the fitsystemWindows doesn't work.
Thank you!


text:
Q: Get tags of content on same page I am developing portlet for liferay portal. I need in my portlet to get tags of content in other portlet. All i have at this moment is portlet IDs of oll portlets on the page. For example, if I have portlet with ID 33 (blog) I need to get tags of blog entry? opened in blog portlet. Any ideas? Thatnks fore future answers!

A: I have found good solution:
I have writed hook-plugin for blog portlet.In this plugin I modify init-ext.jsp, where I add AssetEntry object to shared session parametres. In my custom portlet I just take this parameter and can use it in any way. The problem Im thinking about at this moment is the order of portlet execution. The order is not specified, so I can't be shure, that blog executes first and in my custom portlet I would be abl to access AssetEntry in public session parametres. Anyway it is working solution.


text:
Q: Nuget as a package manager I'm looking to work on an application, an internal toolbelt if you will.
Rather than having users messing around with DLL's for the differing tools (they plug in via MEF) I was wondering if it's possible to jump on the back of Nuget?
I'd build the tools, package them as nuget packages and host them internally and the toolbelt application would then query the catalog, retrieve and extract etc etc.
Does anybody know of a way this is possible?

A: Chocolatey uses nuget as an underlying package manager to install applications on your pc.
http://chocolatey.org/
So I'm sure it's possible, but I've not done it myself.
The nuget documentation discusses a command line and power shell reference: http://docs.nuget.org/
Also linqpad, does something similar (in the paid for version), where you can include dll's from nuget. There is a screen shot on this page: http://www.linqpad.net/purchase.aspx


text:
Q: convert hex codes to characters PHP Here are some examples:
\x2f
\x3f
\x253d
Is there a PHP function that can convert these types of characters? I can't seem to find anything.
Thanks in advance!

A: Use hexdec(). It should cover what you need.
Here's the link to the PHP manual on the subject


text:
Q: How to determine the type of a pointer indexed member How to determine the type of a pointer indexed member.
I intend to use:
TYPE DUT_DemoStruct :
STRUCT
        Member_1: BOOL;
        Member_2: INT;
END_STRUCT
END_TYPE

PROGRAM Prg_Main
VAR
        DemoStructPointer:
        Obj_DemoStruct1: DUT_DemoStruct ;
        Obj_DemoStruct2: DUT_DemoStruct ;
        Obj_DemoStruct3: DUT_DemoStruct ;
        Demo_INT: INT;
        Index: INT;
        _pointer: POINTER TO DUT_DemoStruct;
END_VAR

FOR Index:=0 TO 5 DO
        IF _pointer[Index] THEN  //whether the _pointer[Index] (pointer index member) is of type DUT_DemoStruct
            _pointer[Index].Member_1:=TRUE;
        END_IF;
END_FOR;

In addition, Do you have any application cases for CheckPointer?
EDIT:2022-06-05
This is to better implement the contracted part of the HMSD(Hierarchical Master-Slave Distribution) framework. For example, batch initialization of states. For example: if you want to implement batch initialization of objects of class Step, you only need to pass the pointer of the first Step to the initialization function, and the function will automatically search down according to the first pointer until it finds an object that is not of the Step class and stops searching. This process needs to be automated. To achieve such a function, you need the index of the pointer, and determine the type of the pointer index member. Ideal code:
FUNCTION_BLOCK Exe_PalletShuttle EXTENDS Frame.Base_LocalScope
VAR
    {attribute 'hide'}pointer_Step: POINTER TO Frame.Base_Step;
    {attribute 'hide'}step_Start: Frame.Base_Step;

    {attribute 'hide'}step_StartRecharg: Frame.Base_Step;

    {attribute 'hide'}step_LengthwaysMove_Start: Frame.Base_Step;
    {attribute 'hide'}step_LiftShuttleCyd_PutDown: Frame.Base_Step;
    {attribute 'hide'}step_LengthwaysMove_GoTarget: Frame.Base_Step;
    {attribute 'hide'}step_LengthwaysMove_End: Frame.Base_Step;

   {attribute 'hide'}step_WidthwaysMove_Start: Frame.Base_Step;
    {attribute 'hide'}step_LiftShuttleCyd_Uplift: Frame.Base_Step;
    {attribute 'hide'}step_WidthwaysMove_GoTarget: Frame.Base_Step;
    {attribute 'hide'}step_WidthwaysMove_End: Frame.Base_Step;

    {attribute 'hide'}step_UpliftPallet_Start: Frame.Base_Step;
    {attribute 'hide'}step_LiftPalletCyd_Uplift: Frame.Base_Step;
    {attribute 'hide'}step_UpliftPallet_End: Frame.Base_Step;

    {attribute 'hide'}step_PutdownPallet_Start: Frame.Base_Step;
    {attribute 'hide'}step_LiftPalletCyd_Putdown: Frame.Base_Step;
    {attribute 'hide'}step_PutdownPallet_End: Frame.Base_Step;

   {attribute 'hide'}step_End: Frame.Base_Step;

   {attribute 'hide'}VividerMark: BOOL;

   {attribute 'hide'}obj_PalletLiftCyd: Frame.Device_Actuator;
    {attribute 'hide'}obj_DiverterLiftCyd: Frame.Device_Actuator;
END_VAR

pointer_Step:= ADR(step_Start);
InitialStepScope(FirstAdr:=pointer_Step );
Feeling the current mechanism of pointer implementation, such a function seems to be difficult to achieve. Looking forward to the launch of the collection function.

A: You can't know the type of the data the pointer points to. When you create the pointer, you are explicitly telling the compiler to assume the data is of the specified type.
You could store the address of the first and last elements and iterate between them (haven't tested):
elem1: MY_STRUC;
elem2: MY_STRUC;
...
elemN: MY_STRUC;

pbegin: POINTER TO MY_STRUCT := ADR(elem1);
pend: POINTER TO MY_STRUCT := ADR(elemN);

WHILE pbegin <> pend DO
    // use pbegin^
    pbegin := pbegin + SIZEOF(pbegin^); // or pbegin := ADR(pbegin[1]);
END_FOR

However, the above assumes that:

*

*All of elemX are of the same size

*There are no other type of variables in between the elements

*Sequentially defined variables in CODESYS must also be placed in memory sequentially in the same order (don't know if this is true)

As such, the above is very error prone in my opinion. A better approach might be to "bundle" the elements in a dedicated structure (tested on a simulator):
TYPE MY_STRUC_BUNDLE:
STRUCT
    elem1: MY_STRUC;
    elem2: MY_STRUC;
    ...
    elemN: MY_STRUC;
END_STRUCT
END_TYPE

bundle: MY_STRUC_BUNDLE;
ptr: POINTER TO MY_STRUCT := ADR(bundle);
len: UDINT := SIZEOF(bundle) / SIZEOF(ptr^) - 1;
index: UDINT;

FOR index := 0 TO len DO
    // use ptr[Index]
END_FOR

Assuming that the bunle structure only contains the desired structs of the same type (and size), this should work as structures should have a continuous memory segment.
I still think that if you want to access normal variables with an index, the best, and least error prone, solutions is to bind them into an array:
elem1: MY_STRUC;
elem2: MY_STRUC;
...
elemN: MY_STRUC;

arr: ARRAY [1..N] OF POINTER TO MY_STRUC := [ADR(elem1), ADR(elem2), ..., ADR(elemN)];

FOR Index := 1 TO N DO
    // use arr[Index]^
END_FOR


text:
Q: Why does mailx send a previous version of its referenced file instead of the latest one? I've created a simple script that will automatically kill the top 2 processes. But before the restart, I write the top 10 list of processes to a text file and its memory status (free -h) before it kills the top 2 processes. However, when it sends the email, it doesn't take the latest file but the last updated file. The txt file overwrites every time the script is ran.
file=$aa_dir/tst_topprocess.txt #file for top processes
file_chk=$aa_dir/tst_membefore.txt #file for previous memory check
topproc=$(more "$file")
memchk=$(more "$file_chk")

 if [[ "$memtst" -le  "$threshold" ]]; then #for testing
    echo -e "`date` \n $top" > $file  #writes top processes before to a file
    echo -e "`date` \n $chk" > $file_chk #writes free -h results to a file
    #sleep 5
    #restart here
    echo "Killing PIDs..."
    #kill -9 $pid1 $pid2
    sleep 5
    echo -e  Memory check before restart: \n \n $memchk  \n \n Top processes before the restart: \n \n $topproc \n \n Processes after the restart: \n \n $top \n \n `date`" | mailx -s "$subject" -r "$mail_from" abc@gmail.com

The result is:
it does save the processes before killing the pid but when it sends the email, it doesn't get the latest file. It sends the contents from the previous run.
So for example, if the script runs via cronjob every 15 minutes, the file that would be displayed on the email body for the 11:00 pm run would be 10:45pm.
What am I missing? How do I tell the script to get the latest saved file?

A: Per @KamilCuk's suggestion, I changed this part of the code to fix the issue
topproc=$(echo -e "date \n $top" > "$file")
memchk=$(echo -e "date \n $chk" > "$file_chk")
topproc2=$(more "$file")
memchk2=$(more "$file_chk")


text:
Q: how to attach vehicles to my products in my database schema I made a basic vehicles year/make/model/submodel database diagram here. I'm having a hard time wrapping my head around how I need to further set up my database so products know vehicles they belong to.
I'm thinking that I need to make another table that serves as a many to many relationship between Products and VehicleYears.
Essentially I want to be able to choose a vehicle on the front end and only show products that fit the currently selected vehicle.
This then brings up another possible issue. If vehicle years has a many relationship to products, would I still be able to filter out categories and/or sub categories based on the currently selected vehicle? (products belong to sub categories which then belong to categories)
I'm sure there is a way to write a query to handle categories and sub categories, but is there a better way to construct the database so that performance isn't an issue? My categories/item diagram is here.

*

*After getting feedback here is my revised design here

A: Yes, theoretically you need an intermediate table from VehicleYears to Products.
But I don't understand your VehicleYears and VehicleYears_VehicleMakes tables. What does the VehicleYears_VehicleMakes relationship mean? That the vendor made any cars in that year?
I think the relationship is rather a submodel-to-year one and if it is, you don't even need a table for your years, just put two columns into the submodel table.

A: Nick, the first thing that hits me is that you need to forget about modelling year as a separate table. So remove VehicleYears and VehicleYears_VehicleMakes. You just need add a year field to your VehicleSubModels table. I think year is better tied to the submodel of vehicle rather than a make of vehicle.
I think the link you are struggling to find between vehicles and products is a many:many between VehiclSubmodels and Items. Your new table VehicleProducts would have two fields ( a compound primary key) comprising of VehicleSubModelId and ItemId.
Modelling it this way you have a very granular way to relate products with vehicles. And you could easily achieve your goal of choosing a vehicle and getting all the relevant items listed.
Your design for categories and sub categories is fine but I wonder if you'll ever get to a point where you need a third level of categorisation - a SubSubCategory :) if so it may be wise to bite the bullet now and get that in your design.

A: I've done something like this for publisher trying to attach repair procedures to a product.  The product is identified by a four-part primary key: Year, Make, Model, Engine, or YMME, and the vehicles table looked like this (simplified):
VEHICLES
year  integer
make   varchar
model  varchar
engine varchar

The PARTS table has to be linked to an entity in the VEHICLES table. A part might work with a specific year and make and model, but not when a specific engine was installed.
In your case, you have to decide what constellation of attributes uniquely identifies a bicycle. If you're tracking bikes from multiple makers, you need MAKE.  If things change from year to year, you need YEAR.  If there is a difference from model to model, you need MODEL.  If, say, a part will work if the frame is aluminum but not if the frame is steel, you'd need FRAME_MATERIAL or FRAME_GAUGE as well, in place of ENGINE, or you'd need a separate model one for aluminum, the other for steel.
VEHICLES
year
make
model
frame

Then you could simply have an intermediary table:
VEHICLE_PARTS
partid  integer foreign key references PARTS
year
make
model
frame
...

or
VEHICLE_PARTS
partid  integer foreign key references PARTS
year
make
model   (frame material is handled by a separate model)

Your structure has to answer the question: Will this part work with that bike?  The mere presence of the partid in the VEHICLE_PARTS table should imply, Yes it does.  You really want to avoid having an Exceptions field in the VEHICLE_PARTS table where there is some human-readable notation that says the part is incompatible with the bike in question when rams-horn handlebars are used.   You should really create a separate model to handle things like that.


text:
Q: Missing attribute name in Visual Studio I am working on a project using ASP.NET CORE with MVC and when I want to use bootstrap (i think?) I get this warning, on a video on youtube he could see the B from bootstrap (autofill thing) when he used the div class name... but I don't get it and I see that bootstrap is loaded into my project.. I don't understand I followed the exact same instructions of the guy but mine just don't work.. I am beginner to visual studio and programming so I struggle with it.. thanks in advance..

A: The tag name should be div, instead of div-class.
<div class="row>
</div>


text:
Q: Configure Windows to use 32-bit JRE instead of 64-bit JRE In my system, I have 64-bit Java 1.7 installed here: C:\Program Files\Java\jdk1.7.0_40
And
I have 32-bit Java 1.7 installed here: C:\Program Files (x86)\Java\jdk1.7.0_02
When I issue java -version command in CMD, it shows me this:
C:\Users\Meraman>java -version
java version "1.7.0_40"
Java(TM) SE Runtime Environment (build 1.7.0_40-b43)
Java HotSpot(TM) 64-Bit Server VM (build 24.0-b56, mixed mode)

I want to change Java version to 32-bit.
I have tried the following:

*

*Removed path to 64-bit installation from path variable, but still CMD shows same output for java -version command.

*I have specified only 32-bit installation path in path variable, but still CMD shows same output for java -version command.

*Then added JAVA_HOME variable with value C:\Program Files (x86)\Java\jdk1.7.0_02, but still CMD shows same output.

*In Java Control Panel->Java->Java Runtime Environment Settings->User, I have completed wizard to find 32-bit Java and enabled that only, with disabling 64-bit installation, but still CMD shows same output.
Please help me on this, I want to change Java to 32-bit without un-installing 64-bit.
More info:
I have restarted CMD after every changes to path or Java Control Panel.
I have path and JAVA_HOME as system variables only, no any such user variables.
EDIT
I have removed all java paths setting in path variable, removed JAVA_HOME variable, and still CMD shows 64-bit.
C:\Users\Meraman>echo %PATH%
C:\oraclexe\app\oracle\product\10.2.0\server\bin;C:\Python33\;C:\Program Files (
x86)\AMD APP\bin\x86_64;C:\Program Files (x86)\AMD APP\bin\x86;C:\Windows\system
32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.
0\;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;C:\Program Files
(x86)\Microsoft SQL Server\80\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL S
erver\90\Tools\binn\;C:\Program Files (x86)\Microsoft SQL Server\90\DTS\Binn\;C:
\Program Files (x86)\Microsoft SQL Server\90\Tools\Binn\VSShell\Common7\IDE\;C:\
Program Files (x86)\Microsoft Visual Studio 8\Common7\IDE\PrivateAssemblies\;

C:\Users\Meraman>javac -version
'javac' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\Meraman>java -version
java version "1.7.0_40"
Java(TM) SE Runtime Environment (build 1.7.0_40-b43)
Java HotSpot(TM) 64-Bit Server VM (build 24.0-b56, mixed mode)

C:\Users\Meraman>echo %JAVA_HOME%
%JAVA_HOME%

C:\Users\Meraman>

EDIT - This worked:
Setting very first path in path variable to 32-bit java worked.
Here is output from CMD:
C:\Users\Meraman>echo %PATH%
C:\Program Files (x86)\Java\jdk1.7.0_02\bin;C:\oraclexe\app\oracle\product\10.2.
0\server\bin;C:\Python33\;C:\Program Files (x86)\AMD APP\bin\x86_64;C:\Program F
iles (x86)\AMD APP\bin\x86;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wb
em;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\ATI Techno
logies\ATI.ACE\Core-Static;C:\Program Files (x86)\Microsoft SQL Server\80\Tools\
Binn\;C:\Program Files (x86)\Microsoft SQL Server\90\Tools\binn\;C:\Program File
s (x86)\Microsoft SQL Server\90\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL S
erver\90\Tools\Binn\VSShell\Common7\IDE\;C:\Program Files (x86)\Microsoft Visual
 Studio 8\Common7\IDE\PrivateAssemblies\;

C:\Users\Meraman>javac -version
javac 1.7.0_02

C:\Users\Meraman>java -version
java version "1.7.0_02"
Java(TM) SE Runtime Environment (build 1.7.0_02-b13)
Java HotSpot(TM) Client VM (build 22.0-b10, mixed mode, sharing)

C:\Users\Meraman>echo %JAVA_HOME%
%JAVA_HOME%

C:\Users\Meraman>where java
C:\Program Files (x86)\Java\jdk1.7.0_02\bin\java.exe
C:\Windows\System32\java.exe

C:\Users\Meraman>

A: I have the same problem!
Please look into C:\Windows\System32...
you will find a java.exe, javaw.exe and javaws.exe digital signed by Oracle America, Inc.
Because PATH includes C:\Windows\system32 at the beginning, windows will find this java.exe before your 32 bit java.exe
Timm from Hamburg (Germany)

A: Make sure to have C:\Program Files (x86)\Java\jdk1.7.0_02\bin in the PATH environment variable before the other paths (and in particular, before c:\windows...).
Also, make sure to restart your command line window after you've changed the PATH.

A: Delete the same files (java.exe, javaw.exe and javaws.exe) at:
 C:\ProgramData\Oracle\Java\javapath

A: on our estate we have the latest Java 8 x86 and x64 installed. Experienced the same problem above
PATH was referencing C:\Program Files (x86)\Common Files\Oracle\Java\javapath
Changing the path above to C:\Program Files (x86)\Java\jre1.8.0_xxx\bin  resolved the problem


text:
Q: How to implement $SetIsSubset in mongoTemplate aggregation of Java Spring? I am trying to use the $setIsSubset in mongoTemplate aggregation class. But couldn't find any solution.
My Mongo Query is:
db.events.aggregate([
    { $match: { $and: [
        { "event_state" : {$in : ["live","scheduled"]} },
        { "schedule.end_time" : {$gt : ISODate("2016-12-12T06:30:00.000Z")} }
        ]
      }
    },
    {$project:
        {
            "name" :1,
            "category" :1,
            "schedule":1,
            "celebrity" :1,
            "online_moderator" :1,
            "offline_moderator" :1,
            "region" :1,
            "status" :1,
            "event_state" :1,
            "recorder_id" :1,
            "webcast_url":1,
            "replay_url":1,
            "registered_users":1,
            registeredUsers: { $size:"$registered_users" },
            is_registered:
            { $setIsSubset: [[ObjectId("584e6253e17ed10f0a8cba1d"),ObjectId("583e9719e17e8c1bf80da2fe")], "$registered_users.user_id"]}
        }
    },
    { $sort : {
            "schedule.start_time": 1
        }
    }
]);

I have converted the most of the code like below. But struck with the $setIsSubset condition.
matchCondition = Aggregation.match(Criteria.where("event_state")
                    .in(listEventStates).and("schedule.end_time").gt(d));

AggregationOperation projectValues = Aggregation.project()
                .and("registered_users").size().as("registered_users_count")
                .and("name").as("name").and("category").as("category")
                .and("schedule").as("schedule").and("online_moderator")
                .as("online_moderator").and("offline_moderator")
                .as("offline_moderator").and("region").as("region")
                .and("status").as("status").and("event_state")
                .as("event_state").and("recorder_id").as("recorder_id")
                .and("webcast_url").as("webcast_url").and("replay_url")
                .as("replay_url");

sortCondition = Aggregation.sort(Sort.Direction.ASC,
                    "schedule.start_time");

Aggregation aggrigation = Aggregation.newAggregation(matchCondition,
                sortCondition, projectValues);

EDIT:
As per the request from @user_531. I am updating my question with the possible solution that worked for me. I don't know whether it will work or not as it's been 2 years since I used the solution. After that, I have changed the code a few more times, and I am not maintaining this project anymore. But it's worth give a shot.
AggregationOperation projectValues = Aggregation.project().and("registered_users").size()
            .as("registered_users_count").and("event_image").as("event_image")
            .and("name").as("name").and("category").as("category").and("schedule").as("schedule")
            .and("region").as("region").and("status").as("status").and("event_state").as("event_state")
            .and("recorder_id").as("recorder_id").and("webcast_url").as("webcast_url").and("replay_url")
            .as("replay_url").and("registered_users").as("registered_users").and("room_details").as("room_details")
            .and("live_stream_url").as("live_stream_url")
            .and(new AggregationExpression() {
                public DBObject toDbObject(AggregationOperationContext context) {
                    return new BasicDBObject("$setIsSubset", Arrays.<Object> asList(
                    Arrays.<Object> asList(new ObjectId("58528314e17edbb252692815")),
                        "$registered_users.user_id"));
                }
            }).as("is_registered");

    Aggregation aggrigation = Aggregation.newAggregation(matchCondition, sortCondition, projectValues);

    AggregationResults<Events> results = mongoTemplate.aggregate(aggrigation, "events", Events.class);

A: Make use of AggressionExpression. Include below projection in project. Use 1.8.5 spring mongo data version.
and(new AggregationExpression() {
    @Override
    public DBObject toDbObject(AggregationOperationContext context) {
        return new BasicDBObject("$setIsSubset",
                Arrays.<Object> asList(
                        Arrays.<Object> asList("584e6253e17ed10f0a8cba1d",
                                "583e9719e17e8c1bf80da2fe"),
                        "$registered_users.user_id"));
    }
}).as("is_registered"));

You can wrap the expression as a lambda for Java 8
and(context -> new BasicDBObject("$setIsSubset",
        Arrays.<Object> asList(
                Arrays.<Object> asList("584e6253e17ed10f0a8cba1d",
                         "583e9719e17e8c1bf80da2fe"),
                "$registered_users.user_id")))
.as("is_registered"));

A: You can work with the Mongodb api for project (com.mongodb.client.model.Aggregates.project) also for match (com.mongodb.client.model.Aggregates.match(Bson filter))
you can use the code I just finish like example for the use of $setIsSubset
with this query
db.getCollection('collection').aggregate(
 {    $match : {"_id" : "dff26f9c-350b-4bd5-bc62-62c19f21100c"}   },
{ "$project": {
       "sensorId": 1,   "sensorModel": 1,
   "attachments": {
     "$filter": {
   "input": "$attachments",
   "as": "attachment",
   "cond": {
     "$setIsSubset": [
       ["$$attachment.type"],
       ["StructAttachment", "BlobAttachment"]
     ]
   }    }   } }})

and the java code is like :
List <Bson> aggregationInput = new ArrayList <Bson> ();
aggregationInput.add(match(eq("_id",id)));
HashMap<String, Integer> fieldsMap=new HashMap<String, Integer>();
fieldsMap.put("sensorId", 1);
fieldsMap.put("sensorModel", 1);

ArrayList< ArrayList<String>> isSubset = new ArrayList< ArrayList<String>>();
ArrayList<String> isSubsetParameter1 = new ArrayList<String>();
isSubsetParameter1.add("$$attachment.mimeType");

ArrayList<String> isSubsetParameter2 = new ArrayList<String>();
isSubset.add(isSubsetParameter1 );
isSubset.add(isSubsetParameter2 );

Document docFields = new Document();
if (mimeTypes == null || mimeTypes.isEmpty()) {

//mimeTypes is a Set
    isSubsetParameter2.addAll(mimeTypes);
Document filter = new Document();
filter.put("input", "$attachments");
filter.put("as", "attachment");
filter.put("cond", new  Document("$setIsSubset", isSubset));

docFields.put("attachments", new Document("$filter",filter));
docFields.putAll(fieldsMap);
aggregationInput.add(project(docFields));

AggregateIterable<Document> resultIteratr = mongo.getDatabase("db").getCollection("collection")
.aggregate(aggregationInput);

I hope this works for you!


text:
Q: WPF MediaElement Opacity is not set after executing Storyline I'm using DoubleAnimation and Storyboard to control Opacity of MediaElement. The animation itself works fine, but if I call Disappear and playVid after several seconds, the Opacity of the player remains 0! What's the problem?
public void playVid(string source, bool isMainVid)
{
    player.Opacity = 1;
    player.Play(); //player.Opacity is 0 here!
}

public void Disappear()
{
    DoubleAnimation fadeOut = new DoubleAnimation
    {
        To = 0,
        Duration = new Duration(TimeSpan.FromMilliseconds(1000))
    };
    fadeOut.Completed += (s, e) =>
    {
        player.Stop();
    };
    var storyboard = new Storyboard();
    storyboard.Children.Add(fadeOut);
    Storyboard.SetTargetName(fadeOut, player.Name);
    Storyboard.SetTargetProperty(fadeOut, new PropertyPath(OpacityProperty));
    storyboard.Begin(mainGrid, HandoffBehavior.SnapshotAndReplace); //mainGrid is player's parent
}

A: Use FillBehavior equal to Stop, but also set the Opacity of your player to the final opacity value (in the Completed handler). Otherwise, it will be reset to its value before the animation.
var fadeOut = new DoubleAnimation
{
    To = 0,
    Duration = new Duration(TimeSpan.FromMilliseconds(1000)),
    FillBehavior = FillBehavior.Stop
};

fadeOut.Completed += (s, e) =>
{
    player.Stop();
    player.Opacity = 0;
};

See this post for other approaches.


text:
Q: How can I write a pivot that takes this form of data to the result desired? I have a table that looks like this
CREATE TABLE foo (id, name, category)
AS VALUES
  ( 1, 'name1.1', 'cat1.1.1'),
  ( 1, 'name1.2', 'cat1.1.1'),
  ( 1, 'name1.3', 'cat1.2.1'),
  ( 2, 'name2.1', 'cat2.1.1'),
  ( 2, 'name2.2', 'cat2.1.1'),
  ( 3, 'name3.1', 'cat3.1.1')
;

I'm trying to get a result that looks like this,

Id
name1
name2
name3

1
name1.1
name1.2
name1.3

2
name2.1
name2.2

3
name3.1

A: First you'll need to add the tablefunc module which provides this ability.
CREATE EXTENSION tablefunc;

Now you need a query like this,
SELECT *
FROM crosstab(
    -- here we normalize this into `id | cat | value`
    -- where the category is [1-3]
    $$SELECT id, RIGHT(name,1)::int AS cat, name AS value FROM foo ORDER BY 1,2;$$,
    -- For just the cat 1,2,3
    $$VALUES (1),(2),(3);$$
) AS ct(id text, name1 text, name2 text, name3 text);

Which will return this,
 id |  name1  |  name2  |  name3
----+---------+---------+---------
 1  | name1.1 | name1.2 | name1.3
 2  | name2.1 | name2.2 |
 3  | name3.1 |         |
(3 rows)

Notice the big gotcha here, your catagory is actually a function of your data RIGHT(name,1)::int. That was probably your hold up. Conversely, the actual data you provided in category is seemingly safe to ignore entirely unless I'm missing something.
Also note that I hardcoded the catagory names in two places,
$$VALUES (1),(2),(3);$$

And,
ct(id text, name1 text, name2 text, name3 text);

This is required, as PostgreSQL doesn't allow you to return a query where the result set is not known when you run the command. This will support only [name1 - name3]If you want it truly dynamic the scope of the program grows a lot and it's off topic on this question.

A: I would aggregate all names into an array, then extract the array elements as columns:
select id,
       names[1] as name1,
       names[2] as name2,
       names[3] as name3
from (
   select id,
          array_agg(name order by name) as names
   from foo
   group by id
) t

If the names could contain things like name10.11 then the order of the columns won't be numerical because the string '10' is lower than the string '2'. If you want the order to reflect the numbers, the sorting gets a bit more complicated:
array_agg(name order by string_to_array(replace(name, 'name', ''), '.')::int[]) as names

This removes the name prefix and converts the numbers to an integer array which then sorts properly. Another option is to remove everything that's not a digit or dot:
array_agg(name order by string_to_array(regexp_replace(name, '[^0-9.]', '', 'g'), '.')::int[]) as names


text:
Q: Argument in a for loop Pls help me im stuck
def printdata(something):
    for i in something + "_raw":
        something + "_raw_names" = i.findAll("div",{"itemprop":"name"})
        something + "_name" = something + "_raw_names"[0].text
        print("Name: " + something + "_name")

I want that printdata(bodies) is doing this:
for i in bodies_raw:
    bodies_raw_names = i.findAll("div",{"itemprop":"name"})
    bodies_name = bodies_raw_names[0].text
    print("Name: " + bodies_name)

If u have a solution pls tell me because im struggling with this way too long

A: You shouldn't try and create / access / modify variable names dynamically like that. If you have a lot of similarly named variables, consider storing them in a dict. e.g:
raws = {'bodies': bodies_raw, 'other': other_raw}

and then your function can be:
def printdata(something):
    for i in raws[something]:
        raw_names = i.findAll("div", {"itemprop": "name"})
        raw_name = raw_names[0].text
        print("Name: " + raw_name)


text:
Q: matplotlib does not upgrade beyound 3.2.1 I am using Notebook on Azure Machine Learning Studio and I am trying to install latest version of matplotlib, but it continues using version 3.2.1 I tried conda, pip, and also tried to uninstall and install again, nothing works.
sample commands tried:
!pip install matplotlib
!conda install matplotlib

Am I missing sth? thanks

A: The version of Matplotlib will depend on the version of python. There is no support for the latest version of matplotlib library for python version 3.8. The latest version of matplotlib can be available only up to 3.7 version of python. Even though we tried to upgrade it with pip, conda , by default version of python program, it will take the supporting version of matplotlib.
For the current version of matplotlib in the current case of the situation, it is 3.2. It is suggestable to check the version of python, whether it is 3.6 or not. Python version 3.6 supports 3.2 and 3.1 versions of matplotlib.
If still the python version is showing the latest version of python, try to degrade the version and check.


text:
Q: Why after moving a .js script from html to .js file, it does not load the values? I have a dropdown box which whenever I change its values, a js script forwards its responses to another dropdown. This script works when is inside the .html file, but once I move it to a seprate .js file it does not work. this is the code:
$("#id_subtag-tags").change(function () {
  var tagId = $(this).val();  // get the selected tag ID from the HTML input
  console.log(tagId);

  $("#displaytags").html('');

  $.ajax({                       // initialize an AJAX request
    url: '{% url "ajax_load_subtags" %}',                    // set the url of the request (= localhost:8000/app/ajax/load_subtags/)
    data: {
      'tags': tagId       // add the tag id to the GET parameters
    },
    success: function (data) {   // `data` is the return of the `load_subtags` view function
      $("#id_subtag-subtags").html(data);  // replace the contents of the subtags input with the data that came from the server
    }
  });
});

There is another function in the same file which is properly is being loaded to that html file, so I think problem is not in loading. I don't know what is causing this bug.
The error I receive is:
GET failed, ajax_load_subtags 404 (Not Found),

url.py:
path('myapp/post/ajax/ajax_load_subtags', load_subtags, name='ajax_load_subtags'),

My guess is that the problem is in loading the url, as in html I had {% load static %} but I don't know what is the equivalent in .js files!!

A: In the AJAX url, you are trying to use Django template syntax inside JS with {% url "ajax_load_subtags" %}. This means you will be doing a request to an empty url and therefore receive a 404.
I would recommend adding the url to a data attribute like below:
HTML
<div id="someElement" data-subtags-url="{% url 'ajax_load_subtags' %}">

JS
$.ajax({
    url: $('#someElement').data('subtags-url'),
    ...,
});

A: For those working with django and have the same issue. I just used directly the url rather than the name of url and it works:
$("#id_subtag-tags").change(function () {
  var tagId = $(this).val();  // get the selected tag ID from the HTML input
  console.log(tagId);

  $("#displaytags").html('');

  $.ajax({                       // initialize an AJAX request
    url: "/myapp/post/ajax/ajax_load_subtags",                     // set the url of the request (= localhost:8000/app/ajax/load_subtags/)
    data: {
      'tags': tagId       // add the tag id to the GET parameters
    },
    success: function (data) {   // `data` is the return of the `load_subtags` view function
      $("#id_subtag-subtags").html(data);  // replace the contents of the subtags input with the data that came from the server
    }
  });
});

A: The best way is putting a static folder on the main directory. Then on your .html file on the top you could just add {% load static %}. Then go to your settings.py and on the bottom paste this
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]

Now on your .html file since the <script> work properly at the bottom then just do this
{% static 'filename.js' %}

This should work


text:
Q: Atom namespace with php simplexml This is my RSS template that I load into my simplexml object. I want to change the
<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
    <channel>
        <atom:link href="link" rel="self" type="application/rss+xml" />
        <title></title>
        <link></link>
        <description></description>
        <lastBuildDate></lastBuildDate>
    </channel>
</rss>

I'd like to change the href attribute in atom:link but I have no clue how to access it. I scoured through SO and found a bunch of information on how to access different namespaces but I can't figure out how to apply any of them to this specific example (mostly because I am pretty dense :)
I can modify my link attribute with the line of code below but how would I modify the attribute mentioned above?
$rss->channel->link = $rssLink;

Any help would be appreciated!

A: $attrs = $rss->channel->children("atom", true)->link->attributes();
$attrs["href"] = "href_value";

Example here.


text:
Q: Apache and NodeJS on the same server. Can they talk to each other? I've got Apache (running PHP and serving static content) and NodeJS (for websockets) running on the same server under the same domain (different ports).  I'm not using nginx.  I've already got the webclient communicating to both successfully, but now I want to close the communication loop and have Apache and NodeJS talk to each other.
It makes sense that they should be able to talk to each other, but I'm not entirely sure the best way to make it happen.  What methods are there, and which way do you suggest?

A: If you are talking about the communication of the app running on apache and node app, yes it is possible. You just have to write the interfaces of your applications as services, then you can just use standard HTTP methods for communication.