text:
Q: Somthing wrong btween the a+ and the r+ replaces lines OK so when i use the a+ everything works fine, creates new line and writes the code but when i use the r+ it replaces the first line instead of creating the new line. how can i make it to add a line without replacing it?
When i decided to add the \n (add new line). it would just replace the new line as well, so there is no point adding the \n or \r\n.  Look at thie code
$demo = $_POST['demo'];
$text = $_POST['text '];
$name = $_POST['name'];
$address = $_POST['address'];

$fp = fopen('../../include/item.accessory.php', 'r+') or exit("Unable to open file!");
 fseek($fp, 0, SEEK_SET); //MOVES THE CURSOR 0 PLACES FROM START OF THE FILE
 fwrite($fp, $_POST["demo"]);
 fwrite($fp, $_POST["text"]);
     fwrite($fp, $_POST["name"]);
     fwrite($fp, $_POST["address"]);
fclose($fp);

Any Idea what i might be doing rung?

A: Please see the docs at http://us3.php.net/manual/en/function.fopen.php, specifically:

'r+' Open for reading and writing; place the file pointer at the beginning of the file.

and

'a+' Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

This tells you this is standard behaviour.
If you wish to add content at the beginning of the file, do:
$content = $newcontent.file_get_contents($path_to_file);
file_put_contents($path_to_file, $content);

In your specific case you might do:
$newcontent = "$_POST[demo] $_POST[text] $_POST[name] $_POST[address]";
$content = $newcontent.file_get_contents($path_to_file);
file_put_contents($path_to_file, $content);


text:
Q: Equivalent to LEFT() function in Google cloud data fusion data pipeline wrangler? I need to port recipes from dataprep recipe into data fusion pipeline wrangler.
derive type: single value: LEFT(column3, 3) as: 'column3'
When I enter custom transform it gives me an error:
io.cdap.wrangler.expression.EL.compile@1:6 unsolvable function/method 'LEFT'

A: The equivalent to LEFT() in Cloud Data Fusion and CDAP is the following Directives called "cut-character".
Here is the syntax:
cut-character <source> <destination> <type> <range|indexes>
Here is a sample snippet that takes the first three characters from the SKU column values and transposes it to a new column named NewSKu:
cut-character SKU NewSku 1-3
This also can be achieved through the UI, by selecting Extract fields - using positions

Reference docs: https://docs.cask.co/cdap/current/en/user-guide/data-preparation/directives/cut-character.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to check if a value exist in table column? Below is the scenario and table structure:

For a given token there can be 3 values assigned

*

*Cash

*Cheque

*Draft

I was trying out a query which can fetch me the Token_Id of records for which there is no Draft value in Field_Value column.
From the above image i need the value 1. As it is the only records which has no draft values.
If i am firing the below query is it correct.
select * from cash_memo where field_value not in ('Cash')

Please guide.

A: This could be a way:
select token_id
from yourTable
group by token_id
having count (case when field_value = 'Draft' then 1 end) = 0

Here I count the rows with field_value = 'Draft' and only get the token_id for which this count gives 0.

A: A simple NOT EXISTS should do it:
SELECT * -- or DISTINCT token_id
FROM cash_memo
WHERE field_value <> 'draft'
AND NOT EXISTS (
    SELECT 1
    FROM cash_memo AS x
    WHERE token_id = cash_memo.token_id
    AND field_value = 'draft'
)

A: you can use not in
select c.* from cash_memo c
    where  token_id not in (  select token_id
                             from cash_memo
                             where field_value = 'Draft')

A: Oracle Setup:
CREATE TABLE cash_memo ( token_id, field_value ) AS
SELECT 1, 'Cash'   FROM DUAL UNION ALL
SELECT 2, 'Draft'  FROM DUAL UNION ALL
SELECT 2, 'Cheque' FROM DUAL UNION ALL
SELECT 3, 'Cash'   FROM DUAL UNION ALL
SELECT 3, 'Draft'  FROM DUAL UNION ALL
SELECT 3, 'Cheque' FROM DUAL UNION ALL
SELECT 4, 'Draft'  FROM DUAL UNION ALL
SELECT 4, 'Cheque' FROM DUAL UNION ALL
SELECT 5, 'Cash'   FROM DUAL UNION ALL
SELECT 5, 'Cheque' FROM DUAL;

Query 1: If you want all the columns for the rows where there is no 'Draft' value for that token_id then you can use an analytic function:
SELECT token_id,
       field_value
FROM   (
  SELECT token_id,
         field_value,
         COUNT( CASE field_value WHEN 'Draft' THEN 1 END ) OVER ( PARTITION BY token_id )
           AS numDraft
  FROM   cash_memo c
)
WHERE numDraft = 0;

Output:

TOKEN_ID | FIELD_VALUE
-------: | :----------
       1 | Cash
       5 | Cash
       5 | Cheque

Query 2: If you just want a list of the token_id which have no 'Draft' values:
SELECT token_id
FROM   cash_memo
GROUP BY token_id
HAVING ( COUNT( CASE field_value WHEN 'Draft' THEN 1 END ) = 0 );

Output:

| TOKEN_ID |
| -------: |
|        1 |
|        5 |

db<>fiddle here

A: This is simple using FIND_IN_SET , you can try this
SELECT token_id FROM yourTable WHERE FIND_IN_SET('{Draft}', field_value )

Here search key in {}


text:
Q: i am trying to make a rect move when i push a button in html5 i am trying to make a blue square move across the X axis when i click the button i made.
When i push the button nothing happens. I dont know what im doing wrong.
Here is the code:
<html>
<head>
    <canvas id="myCanvas" width="600" height="600"></canvas>
    <title>tilte</title>
</head>
<body>
<button onclick="draw">/button>
    <script>
        onload = function() {
            var canvas = document.getElementById("myCanvas")
            var ctx = canvas.getContext("2d")
            var recX = 250
            var recY = 500
            var speedX = 5;
            draw()
            move()
            function draw() {
                ctx.fillStyle = "red"
                ctx.fillRect(0, 0, 600, 600)

                ctx.fillStyle = "blue"
                ctx.fillRect(recX, recY, 50, 50)
            }
        }
    </script>
</body>
</html>

A: change the onload function into onClick, and call "onClick();" from the button...
<canvas id="myCanvas" width="600" height="600"></canvas>
<button onclick="onClick();">click to draw</button>

<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
function onClick()
   {
   let recX = 250;
   let recY = 500;
   let speedX = 5;
   draw(recX,recY);
   move();
}
function draw(recX,recY)
   {
   ctx.fillStyle = "red";
   ctx.fillRect(0, 0, 600, 600);
   ctx.fillStyle = "blue";
   ctx.fillRect(recX, recY, 50, 50);
}
</script>

is all you need


text:
Q: Importing methods from a Python package I'm having an issue importing all methods from a file so that I can use it as a package. I have the following:
myapp.py
mypackage/
mypackage/__init__.py
mypackage/mypackage.py

Inside of mypackage.py I have method1() and method2(). Inside of myapp.py I want to do this:
import mypackage
mypackage.method1()

However this doesn't work. Instead I need to do mypackage.mypackage.method1() and I'm not sure what to do to fix that. The only way I found was to delete __init__.py and rename mypackage.py to __init__.py which doesn't seem right.
What do I need to put in the init file to import all methods so I don't have to always type the package name twice?

A: In your example you have a mypackage package (a directory with an __init__.py) and a mypackage module in that package. You've just posted a strawman example of course, but you risk making import mistakes if you name a module the same as your package. And calling non-package things "package" is certainly confusing!
To get the methods from mypackage.py into mypackage, you can do package-relative imports in mypackage/__init__.py:
from .mypackage import method1, method2

...or
from .mypackage import *

The reason you should rename mypackage.py to something else is that a small mistake like missing that dot causes the wrong thing to be imported.


text:
Q: Transversality for algebraic spaces $\DeclareMathOperator\dim{dim}$I want to apply EGA IV 4, Proposition 17.13.2 to a cartesian diagram

of algebraic spaces over a fixed scheme $S$.
I know the relative dimensions $\dim(\mathfrak{X}'/S)$, $\dim(\mathfrak{Y}/S)$ and $\dim(\mathfrak{X}/S)$ and I want to use the Proposition to determine the relative dimension of $\mathfrak{Y}'$ by showing that the map on tangent spaces is surjective.
The motivation for my question is L. Lafforgue, Proposition 1, page 29 where he obviously applies the Proposition from EGA to a diagram of algebraic spaces.
The problem that I am concerned about is, that the Proposition is formulated and proven only for the case of schemes, so a priori it is not immediately applicable to the diagram.
I expect at least one of the following ideas to work:

*

*State and prove the Lemma for algebraic spaces.  (If it still holds?)
How is the tangent space of an algebraic space even defined? Is this the tangent space of a functor as defined in deformation theory?

*Use the fact that every algebraic space has an atlas and apply the lemma to the resulting diagram.
I could not figure any of these ideas out yet and would appreciate, if someone could explain me what the author had in his mind.


text:
Q: If else with rm Shell linux I need help whith my problem.
I need make a shell script...
this it's my idea
if [ rm -r -f /directorie ]; then
  code
else
  code
fi
...

how I can?

A: This code may achieve what you want:
#!/bin/bash

rm -r /directorie > /dev/null 2>&1; rc="$?"
if [ "$rc" -eq "0" ]; then
   # code here
else
   # code here
fi

Note: rm -rf /directorie (with the option f) would always return a return code = 0 (true), thus it is not suited for an if test.
Edit:  this answer can be condensed into a bash one-liner:
rm -r /home/owner/scripts > /dev/null 2>&1 && code here (true) || code here (false)

A: dir=/directory
test -d "${dir}" && rm -rf "${dir}" && ! test -d "${dir}" && echo OK || echo NOK


text:
Q: Intersection of Vectors The vector $A=3 i + j - k$ is normal to the plane $M_1$, and the vector $B=2i - j + k$ is normal to a second plane $M_2$. Do the two planes necessarily intersect if they are both extended indefinitely?
Justify answer and also validate the answer.
My thoughts on this is to use dot product and cross product, where the lines will meet but it can be showed that it is not parallel to each other.

A: Hint:
M1 has  equation $3x+y-z=a$ for some $a$.Likewise, M2 has equation $2x-y+z=b$. All you have to do is to show the system of these two equations has a solution.


text:
Q: Optimal strategy in a coin game has unexpected symmetry? The game:
I am going to toss a fair coin and you are trying to determine if I tossed a Head or Tail.
You do this using the rule I follow when I toss my coin:
I have before me $2$ $\color{red}{\text{red}}$ boxes each with a $\color{red}{\text{red}}$ marble inside them, I also have $2$ $\color{blue}{\text{blue}}$ boxes each with a $\color{blue}{\text{blue}}$ marble inside of them. Finally, there are two empty white boxes.
If I toss a Head I must move a $\color{red}{\text{red}}$ marble from a $\color{red}{\text{red}}$  box into an empty white box. Similarly, if I toss a Tail I must move a $\color{blue}{\text{blue}}$  marble from a $\color{blue}{\text{blue}}$ box into an empty white box.
To aid you in your guess of my toss, once I have moved a marble, you are then permitted to open and examine the contents of a single $\color{red}{\text{red}}$, $\color{blue}{\text{blue}}$ or white box.
The strategy:
In this primitive instance of two boxes of each color, we are actually indifferent between what box we peek into. We have 75% probability of correctly guessing the toss.
Consider now we have $R$, $\color{red}{\text{red}}$ boxes, $B$ $\color{blue}{\text{blue}}$ boxes and $W$ white boxes. The optimal strategy is to peak into min{ $R,B,W$ }.
I was curious as to why we have symmetry between the colored and white boxes and simply follow the heuristic of the minimum number of boxes, is there a nice transformation of the game that makes this symmetry more obvious? Thanks

A: Here's a transformation that clearly doesn't change the game, but makes the analysis simpler: have the first player privately distinguish three boxes, one of each color, in advance before flipping the coin.  They then proceed as before, but must move the marble from the distinguished red or blue box to the distinguished white box.
We now reason as follows.

*

*If the second player happens to examine a non-distinguished box, they gain no information and every strategy will win 50% of the time.

*If the second player happens to examine a distinguished box, they will win 100% of the time with optimal play:

*

*If they examine a white box and find a red or blue marble, they know that marble was moved.

*If they examine a red or blue box and find it empty, they know a marble of that color was moved.

*If they examine a red or blue box and find it full, and they assume it was one of the distinguished boxes, they will correctly guess that a marble of the other color was moved.  They can and should make this assumption, since we established above that it will not hurt.

Therefore, the second player should maximize their chance of examining a distinguished box, which means they should examine a box with the fewest number of boxes of the same color.


text:
Q: how to get all attribute using php xpath I have one XML file:-
<products>
   <product_id value="1">
       <tab_id value="251">
            <dist_region value="5" />
            <dist_region value="10066" />
            <dist_region value="10069" />
       </tab_id>
   </product_id>
</products>

I am use this xpath:-
list($prid) = $product->xpath("//dist_region[@value]/@value");
    $prid=(string)$prid;
    if(strlen(trim($prid))==0)
    {
        echo ' Is not Match In Product';
        exit;
    }
    echo $prid;

and get the output:-
5

I want to output like:-
all dist_region like:-
5,10066,10069

how can I get this?

A: You have to loop through your results:
$result = $product->xpath('//dist_region[@value]/@value');
$result_arr = array();

if(!empty($result)) {
    foreach($result as $prid) {
        $prid = (string) $prid;
        if(strlen(trim($prid)) > 0) {
            $result_arr[] = $prid;
        }
    }
}

echo implode(',', $result_arr);

A: According to the answer you had accepted, it looks like you're looking for all non-empty value-attributes. But different to what was answered, you can actually spare the loop by formulating the xpath expression differently:
$expression = '//dist_region/@value[normalize-space(.)]';
$values     = $product->xpath($expression);

echo implode(',', $values);

That xpath expression means: Query all value-attribute-nodes of any dist_region-element-nodes which have a non-empty (non-zero-length) normalized string value (that is similar to trim() in PHP and perfectly fitting here if you would have needed trim).
As this example shows, there is no need to actually loop through the results, in SimpleXML you can return attribute-nodes from an xpath query in form of an array and easily use them in string context (cast them to string), for example by using the implode() function.


text:
Q: sDNA file error I still failed to run sDNA on my computer. I tried to do the same thing with another computer and it succeeded. I believe there is a problem with my computer. Here is the error message popped up after I used sDNA in ArcGIS Pro.
Running external command: "C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\python.exe" "C:\Program Files (x86)\sDNA_GIS\bin\\sdnaprepare.py" --im "net=C:/Dissertation/GIS-dissertation/GIS-dissertation.gdb/Central_Route" --om "net=C:/Dissertation/GIS-dissertation/GIS-dissertation.gdb/Central_prepare;errors=C:/Dissertation/GIS-dissertation/GIS-dissertation.gdb/Central_prepare" "start_gs=;e
nd_gs=;xytol=0.001;ztol=0.001;action=REPAIR;nearmisses;duplicates;isolated;island=;data_absolute=;data_unitlength=;data_text="

Using XYTolerance of input feature class: 0.001000

Using ZTolerance of input feature class: 0.001000

sDNA sdnaprepare config: start_gs=;end_gs=;xytol=0.001;ztol=0.001;action=REPAIR;nearmisses;duplicates;isolated;island=;data_absolute=;data_unitlength=;data_text=;arcxytol=0.001000;arcztol=0.001000;

Loading DLL C:\Program Files (x86)\sDNA_GIS\\x64\\sdna_vs2008.dll

ERR: Traceback (most recent call last):
ERR:   File "C:\Program Files (x86)\sDNA_GIS\bin\\sdnaprepare.py", line 4, in <module>
ERR:     commandline_integral_prepare("sdnaprepare")
ERR:   File "C:\Program Files (x86)\sDNA_GIS\commandline_integral_prepare.py", line 103, in commandline_integral_prepare
ERR:     dll = options.dll)
ERR:   File "C:\Program Files (x86)\sDNA_GIS\runcalculation.py", line 58, in runcalculation
ERR:     tablecollection1d = TableCollection()
ERR:   File "C:\Program Files (x86)\sDNA_GIS\sdnapy.py", line 229, in __init__
ERR:     self.dll=_dll()
ERR:   File "C:\Program Files (x86)\sDNA_GIS\sdnapy.py", line 44, in _dll
ERR:     __initialize_dll()
ERR:   File "C:\Program Files (x86)\sDNA_GIS\sdnapy.py", line 84, in __initialize_dll
ERR:     __dll_instance = windll.LoadLibrary(str(__sdna_dll_path))
ERR:   File "C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\Lib\ctypes\__init__.py", line 442, in LoadLibrary
ERR:     return self._dlltype(name)
ERR:   File "C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\Lib\ctypes\__init__.py", line 364, in __init__
ERR:     self._handle = _dlopen(self._name, mode)
ERR: OSError: [WinError 14001] The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log or use the command-line sxstrace.exe tool f
or more detail

External command completed
Process did not complete successfully
Failed to execute (sDNAPrepare).


text:
Q: JNA Windows Service Startup Type I've been playing around with JNA and am able to return the status of a Windows Service (i.e. started or stopped) using the code below. I'm not sure how to return the startup type of the service though. I'm sure there are ways outside of JNA, but I would like to continue to use JNA if possible.
import com.sun.jna.*;
import com.sun.jna.Library.Handler;
import com.sun.jna.platform.win32.*;
import com.sun.jna.platform.win32.Advapi32Util.*;
import com.sun.jna.platform.win32.WinNT.*;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.win32.*;

public class WindowsService {

public static void main(String[] args) {

    W32ServiceManager serviceManager = new W32ServiceManager();
    serviceManager.open(Winsvc.SC_MANAGER_ALL_ACCESS);
    W32Service service = serviceManager.openService("W32Time", Winsvc.SC_MANAGER_ALL_ACCESS);
    System.out.println(service.queryStatus().dwCurrentState);
    service.close();

     }
}

A: The problem here is that while the JNA platform-specific code provides handling for querying a service's status, it does not provide support for querying the service's configuration. That means that to do so, you'll need to provide a JNA mapping for the function in question.
The function you'd want, in this case, is QueryServiceConfig() defined in Advapi32. This function fills in a QUERY_SERVICE_CONFIG structure, which has a dwStartType property which corresponds to the various start-up type values.
Fortunately, mapping a native function is really straight-forward with JNA: you just declare an interface like so (The code examples I'm providing are written in Groovy; the transformation to Java should be pretty straight-forward):
interface MyAdvapi32 extends StdCallLibrary {
    MyAdvapi32 INSTANCE = (Advapi32) Native.loadLibrary("Advapi32", MyAdvapi32.class, W32APIOptions.UNICODE_OPTIONS);

    boolean QueryServiceConfig(
        SC_HANDLE hService,
        QUERY_SERVICE_CONFIG lpServiceConfig,
        int cbBufSize,
        IntByReference pcbBytesNeeded
    )
}

(I derived this using the definition for QueryServiceStatusEx() in the JNA source, whose parameters closely mirror the parameters for QueryServiceConfig(). Note that QueryServiceStatusEx() is ultimately the function called by W32Service#queryStatus()).
However, our function requires a QUERY_SERVICE_CONFIG structure, which is not defined anywhere in JNA. Working from the model of the JNA's SERVICE_STATUS_PROCESS definition we end up with something like:
class QUERY_SERVICE_CONFIG extends Structure {
    public DWORD dwServiceType
    public DWORD dwStartType
    public DWORD dwErrorControl
    public char[] lpBinaryPathName
    public char[] lpLoadOrderGroup
    public DWORD dwTagId
    public char[] lpDependencies
    public char[] lpServiceStartName
    public char[] lpDisplayName

    QUERY_SERVICE_CONFIG() {}
    QUERY_SERVICE_CONFIG(int size) {
        lpBinaryPathName   = new char[256]
        lpLoadOrderGroup   = new char[256]
        lpDependencies     = new char[256]
        lpServiceStartName = new char[256]
        lpDisplayName      = new char[256]

        allocateMemory(size)
    }
}

(Note that this structure is quite a bit more involved than SERVICE_STATUS_PROCESS, as SERVICE_STATUS_PROCESS only has DWORD parameters. The allocation sizes I provided in the second constructor, while required for JNA, are probably not the right size.)
Armed with our structure and new interface, we can create a method to call QueryServiceConfig:
QUERY_SERVICE_CONFIG queryServiceConfig(W32Service service) {
    IntByReference size = new IntByReference()

    MyAdvapi32.INSTANCE.QueryServiceConfig(
        service.handle,
        null,
        0,
        size
    )

    QUERY_SERVICE_CONFIG config = new QUERY_SERVICE_CONFIG(size.value)

    if (!MyAdvapi32.INSTANCE.QueryServiceConfig(
        service.handle,
        config,
        config.size(),
        size
    )) {
        throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
    }

    return config
}

Once we've got all that, using it is pretty simple:
QUERY_SERVICE_CONFIG config = queryServiceConfig(service)
System.out.println(config.dwStartType)

A: Using JNA 4.2.2:
The problem I was having with this structure was the lpDependencies defined as a doubly null terminated array of strings:

lpDependencies
A pointer to an array of null-separated names of services or load ordering groups that must start before this service. The  array is doubly null-terminated .

So I solved this issue by customizing the type mapping:
public class QUERY_SERVICE_CONFIG extends Structure
    {

        public QUERY_SERVICE_CONFIG(Pointer p)
        {
            super(p, ALIGN_DEFAULT, new MyTypeMapper());
        }

        public int dwServiceType;
        public int dwStartType;
        public int dwErrorControl;
        public String lpBinaryPathName;
        public String lpLoadOrderGroup;
        public int dwTagId;
        public TypeMappers.DoubleNullString lpDependencies;
        public String lpServiceStartName;
        public String lpDisplayName;

       @Override
        protected List<String> getFieldOrder()
        {
            return Arrays
                    .asList("dwServiceType", "dwStartType", "dwErrorControl", "lpBinaryPathName", "lpLoadOrderGroup",
                        "dwTagId", "lpDependencies", "lpServiceStartName", "lpDisplayName");
        }

        public static class MyTypeMapper implements TypeMapper
        {

            @Override
            public FromNativeConverter getFromNativeConverter(Class javaType)
            {
                FromNativeConverter result = null;
                if (javaType.equals(TypeMappers.DoubleNullString.class))
                {
                    result = TypeMappers.DoubleNullString.FROM_NATIVE_CONVERTER;
                }
                return result;
            }

            @Override
            public ToNativeConverter getToNativeConverter(Class javaType)
            {
                ToNativeConverter result = null;
                if (javaType.equals(TypeMappers.DoubleNullString.class))
                {
                    result = TypeMappers.DoubleNullString.TO_NATIVE_CONVERTER;
                }
                return result;
            }
        }

    }

I really only cared for the "FromNativeConverter" (DoubleNullString is just a Type marker that has a String[] field):
public class MyFromNativeConverter implements FromNativeConverter
{
    @Override
    public Object fromNative(Object nativeValue, FromNativeContext context)
    {
        DoubleNullString result = new DoubleNullString();
        Pointer p = (Pointer) nativeValue;
        int offset = 0;
        List<String> doubleNullList = new ArrayList<>();
        while (!(p.getByte(offset) == 0))
        {
            String s = p.getString(offset);
            doubleNullList.add(s);
            offset += s.length() + 1;
        }
        result.lpDependencies = doubleNullList.toArray(new String[doubleNullList.size()]);
        return result;
    }

    @Override
    public Class nativeType()
    {
        return Pointer.class;
    }
}

For reference the ToNativeConverter should just return a Pointer.class type and if needed, could return a Memory block with the String[] converted to a doubly null terminated array of bytes. For JNA's sake, it just needs to know the "type" and a default "null" value (just so it can initialize the structure).
My method signature then becomes:
Memory memory = new Memory(required.getValue());
Advapi32Ex.QUERY_SERVICE_CONFIG query = new Advapi32Ex.QUERY_SERVICE_CONFIG(memory);
Advapi32Ex.INSTANCE.QueryServiceConfigA(session.getHandle(), query, (int) memory.size(), required);

A: Here is the program from the previous answer as a java class.
IMPORTANT - needs exactly JNA 3.3.0
import com.sun.jna.Native;
import com.sun.jna.Structure;
import com.sun.jna.platform.win32.*;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.win32.StdCallLibrary;
import com.sun.jna.win32.W32APIOptions;

import java.util.Arrays;
import java.util.List;

public class ServiceUtil {

    interface MyAdvapi32 extends StdCallLibrary {
        public MyAdvapi32 INSTANCE = (MyAdvapi32) Native.loadLibrary("Advapi32", MyAdvapi32.class, W32APIOptions.UNICODE_OPTIONS);
        public boolean QueryServiceConfig(
                Winsvc.SC_HANDLE hService,
                QUERY_SERVICE_CONFIG lpServiceConfig,
                int cbBufSize,
                IntByReference pcbBytesNeeded
        );
    }

    public static class QUERY_SERVICE_CONFIG extends Structure {
        public WinDef.DWORD dwServiceType;
        public WinDef.DWORD dwStartType;
        public WinDef.DWORD dwErrorControl;
        public char[] lpBinaryPathName;
        public char[] lpLoadOrderGroup;
        public WinDef.DWORD dwTagId;
        public char[] lpDependencies;
        public char[] lpServiceStartName;
        public char[] lpDisplayName;

        public QUERY_SERVICE_CONFIG() {}
        public QUERY_SERVICE_CONFIG(int size) {
            lpBinaryPathName = new char[256];
            lpLoadOrderGroup = new char[256];
            lpDependencies = new char[256];
            lpServiceStartName = new char[256];
            lpDisplayName = new char[256];
            allocateMemory(size);
        }

        @Override
        protected List getFieldOrder() {
            return Arrays.asList("lpBinaryPathName","lpLoadOrderGroup","lpDependencies","lpServiceStartName","lpDisplayName");
        }
    }
    public static QUERY_SERVICE_CONFIG queryServiceConfig(W32Service service) {
        IntByReference size = new IntByReference();
        MyAdvapi32.INSTANCE.QueryServiceConfig(
                service.getHandle(),
                null,
                0,
                size
        );
        QUERY_SERVICE_CONFIG config = new QUERY_SERVICE_CONFIG(size.getValue());
        if (!MyAdvapi32.INSTANCE.QueryServiceConfig(
                service.getHandle(),
                config,
                config.size(),
                size
        )) {
            throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
        }
        return config;
    }

    public static String checkService(String serviceToCheck) {
        W32ServiceManager serviceManager = new W32ServiceManager();
        serviceManager.open(Winsvc.SC_MANAGER_ALL_ACCESS);
        W32Service service = serviceManager.openService(serviceToCheck, Winsvc.SC_MANAGER_ALL_ACCESS);

        IntByReference size = new IntByReference();
        MyAdvapi32.INSTANCE.QueryServiceConfig(
                service.getHandle(),
                null,
                0,
                size
        );

        QUERY_SERVICE_CONFIG config = queryServiceConfig(service);
        String result = config.dwStartType.toString();
        service.close();
        return result;

    }

}


text:
Q: how to get the response xml from request xml in wcf soap web service in android Below is my request xml which i want to send to wcf service with basichttpbinding. Please help me to execute this request and get the response.
Is there any other way to get the response result with same request.
Request XML :-
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/ISiplService/GetXMLForOrders</Action>
  </s:Header>
  <s:Body>
    <GetXMLForOrders xmlns="http://tempuri.org/">
      <orderList xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <pOrdersList xmlns="">
          <Order>
            <Address>sd 321</Address>
            <CityName>hosiyarpur</CityName>
            <CreatedOn>2013-08-29T11:25:00</CreatedOn>
            <DeliveryCharges>0</DeliveryCharges>
            <EMail>ramandeep@test.com</EMail>
            <FirstName>ramn</FirstName>
            <LastName>deep</LastName>
            <Mobile>9999999999</Mobile>
            <ModeOfPayment>COD</ModeOfPayment>
            <OrderDetailsList>
              <OrderDetails>
                <CampaignId>11799</CampaignId>
                <OrderDetailId>11799</OrderDetailId>
                <Price>399</Price>
                <Qty>1</Qty>
                <SkuIds>1270</SkuIds>
                <SkuSizeIds>0</SkuSizeIds>
              </OrderDetails>
            </OrderDetailsList>
            <OrderId>11799</OrderId>
            <Phone>9999999999</Phone>
            <PinCode>123456</PinCode>
            <PromoCode i:nil="true" />
            <PromoSiteId>23</PromoSiteId>
            <PurchaseFrom>Hello</PurchaseFrom>
            <ShoppingPoints>0</ShoppingPoints>
            <SourceSite>Hello.com</SourceSite>
            <Status>ordered</Status>
            <TotalPrice>399</TotalPrice>
            <VerifiedOn>2013-08-29T11:25:00</VerifiedOn>
          </Order>
        </pOrdersList>
      </orderList>
    </GetXMLForOrders>
  </s:Body>
</s:Envelope>


text:
Q: virtual hosts overlapping in debian apache2 I have a domain domain.com and a subdomain sub.domain.com .
In apache2/sites-available I have 2 vhosts files: domain and sub.
When I do a2ensite sub the subdomain overwrites the domain, so when I go to see the main domain I see the content for the subdomain. WHen the subdomain is added both the domain and the subdomain point to the subdomain.
What am I doing wrong?
Here are the vhosts
DOMAIN
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName www.domain.com

    DocumentRoot /var/www/domain/
    <Directory />
            Options FollowSymLinks
            AllowOverride None
    </Directory>
    <Directory /var/www/domain/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
            # This directive allows us to have apache2's default start page
# in /apache2-default/, but still have / go to the right place
#            RedirectMatch ^/$ /apache2-default/
    </Directory>

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
            AllowOverride None
            Options ExecCGI -MultiViews +SymLinksIfOwnerMatch
            Order allow,deny
            Allow from all
    </Directory>

    ErrorLog /var/log/apache2/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog /var/log/apache2/access.log combined
    ServerSignature On

Alias /doc/ "/usr/share/doc/"
<Directory "/usr/share/doc/">
    Options Indexes MultiViews FollowSymLinks
    AllowOverride None
    Order deny,allow
    Deny from all
    Allow from 127.0.0.0/255.0.0.0 ::1/128
</Directory>

SUBDOMAIN
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName sub.domain.com

    DocumentRoot /var/www/sub/
    <Directory />
            Options FollowSymLinks
            AllowOverride None
    </Directory>
    <Directory /var/www/sub/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
            # This directive allows us to have apache2's default start page
# in /apache2-default/, but still have / go to the right place
#            RedirectMatch ^/$ /apache2-default/
    </Directory>

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
            AllowOverride None
            Options ExecCGI -MultiViews +SymLinksIfOwnerMatch
            Order allow,deny
            Allow from all
    </Directory>

    ErrorLog /var/log/apache2/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog /var/log/apache2/access.log combined
    ServerSignature On

Alias /doc/ "/usr/share/doc/"
<Directory "/usr/share/doc/">
    Options Indexes MultiViews FollowSymLinks
    AllowOverride None
    Order deny,allow
    Deny from all
    Allow from 127.0.0.0/255.0.0.0 ::1/128
</Directory>

</VirtualHost>

A: I have not read the configuration files yet. But I would like you to definitely go and check /etc/apache2/sites-enabled
Is sub-domain linked with a number before the domain.com?
example 010-sub links to /etc/apache2/subdomain.conf
and 020-sub links to /etc/apache2/domain.conf
so that Apache will parse first subdomain.conf given a request.


text:
Q: stuck in while loop python I am creating a chat server in python and got quite far as a noob in the language. I am having 1 problem at the moment which I want to solve before I go further, but I cannot seem to find how to get the problem solved.
It is about a while loop that continues..
in the below code is where it goes wrong
while 1:
    try:
        data = self.channel.recv ( 1024 )
        print "Message from client: ", data
        if "exit" in data:
            self.channel.send("You have closed youre connection.\n")
            break
    except KeyboardInterrupt:
        break
    except:
        raise

When this piece of code get executed, on my client I need to enter "exit" to quit the connection. This works as a charm, but when I use CTRL+C to exit the connection, my server prints "Message from client: " a couple of thousand times.
where am I going wrong?

A: You're pressing Ctrl-C on the client side. This causes the server's self.channel to get closed.
Since calling recv() on a closed channel immediately returns a blank string, your server code gets stuck in an infinite loop.
To fix this, add the following line to your server code:
data = self.channel.recv ( 1024 )
if not data: break # <<< ADD THIS

Or, as suggested by @sr2222, you can combine both this and your current check into one:
if not data or 'exit' in data:

This will exit the loop if the channel has been closed.


text:
Q: Not able to run next commands in Tkinter once a button command is triggered I am creating a python scripts which will open a new JIRA URL every time i click on the Next button by changing the JIRA Case Id embedded in the URL. But when I click the Next Button first time to execute the command, the window stops responding and i am not able to click again in the Tkinter window. If i close the opened Browser, then only it lets me do other actions.
The code below will read the URL from the Entry widget and increment/decrement the case Id PROJ-T00 if clicked on Next or Prev button and open the updated URL.
When i click on any one button, the URL opens, but i cannot click on these buttons again until I close the opened Browser Window.
Using lambda also did not solve the problem
import webbrowser
from tkinter import *
import os

root = Tk()
root.wm_attributes("-topmost", 1)
root.geometry("600x150")

newTab = IntVar()
newBrowser = IntVar()
input_url = StringVar()
chrome_path = 'C:/Program Files/Google/Chrome/Application/chrome.exe %s'
initURL = 'https://jira.****.***/../testCase/PROJ-T01'

def nextUrl():
    url = input_url.get()
    baseUrl = url.rsplit('T', 1)[0] + 'T'
    curentCaseId = int(url.rsplit('T', 1)[-1])
    caseId = curentCaseId + 1
    url = baseUrl + str(caseId)
    print(url)
    name_entry.delete(0,"end")
    name_entry.insert(0, url)
    webbrowser.get(chrome_path).open(url,new=0)

def prevUrl():
    url = input_url.get()
    baseUrl = url.rsplit('T', 1)[0] + 'T'
    curentCaseId = int(url.rsplit('T', 1)[-1])
    caseId = curentCaseId - 1
    url = baseUrl + str(caseId)
    print(url)
    name_entry.delete(0,"end")
    name_entry.insert(0, url)
    webbrowser.get(chrome_path).open(url,new=0)

def openUrl():
    print(input_url.get())
    webbrowser.get(chrome_path).open(input_url.get(),new=0)

select_msg = Label(root, text = "Current URL")
name_entry = Entry(root, textvariable = input_url, font=('calibre',10,'normal'), width=83)
name_entry.insert(0, initURL)
l1 = Checkbutton(root, text='Open in New Tab', variable=newTab, onvalue=1, offvalue=0)
l2 = Checkbutton(root, text='Open in New Browser', variable=newBrowser, onvalue=1, offvalue=0)
prev = Button(root, text = 'Prev Case', command= prevUrl)
open = Button(root, text = 'Open Case', command= openUrl)
next = Button(root, text = 'Next Case', command= nextUrl)

select_msg.grid(row=0,column=0, columnspan=3)
name_entry.grid(row=1,column=0, columnspan=3,padx = 5)
l1.grid(row=2,column=0)
l2.grid(row=2,column=2)
prev.grid(row=3,column=0)
open.grid(row=3,column=1)
next.grid(row=3,column=2)

root.mainloop()

`


text:
Q: React component updates holds other component to update I am new to React and Redux, and I have the following sample code.
```
<React.Fragment>
    <Spinner />
    <TableWrapper
      onClick={
               ()=>{sendActionToToggleIsLoading();
                    sendActionToChangeTableData()}
              }
    />
</React.Fragment>

```
Two components, a Spinner and a Table, they both use its own container to connect to the redux store.
The Spinner connects to a isLoading props and the TableWrapper connects to an array [tableData] in store.
The onClick event on TableWrapper will send two actions to change isLoading and [tableData] in the store and cause two components to update.
My problem is TableWrapper will take a bit time to update, and Spinner doesn't. However the Spinner won't update until TableWrapper finishes componentDidUpdate.
So the behavior now is after onClick, the two components both stuck for a while and then both update to the new state.
My goal is to let the Spinner to update as soon as onClick is triggered and the TableWrapper updates itself.
Am I doing something wrong?

A: Maybe try to dispatch the loading action inside sendActionToChangeTableData(), I cant tell you why, but it works for me


text:
Q: JVM performance metrics I was thinking about capturing some metrics from a JVM like max/min/used memory, cpu consumption and maybe more later on.
I did some research but couldn't find anything that would be suitable.
Could one please direct me to the right reading, where to start ?
Please note, I am not looking for any kind of software which is out there on the market rather about reading materilas how to programatically get metrics via JMX so, I am able to store these in DB or a file.

A: There is a very nice article from IBM: http://www.ibm.com/developerworks/library/j-rtm1/index.html?ca=dgr-jw22javaruntime1&S_TACT=105AGX59&S_CMP=GR
It has three parts and containing detail information and explanation.
Part 1:

Explores attributes of application performance management (APM) systems
Describes common antipatterns for system monitoring
Presents methods for monitoring the performance of JVMs
Offers techniques for efficiently instrumenting application source code

Part 2 will focus on methods of instrumenting Java classes and resources without modification of the originating source code.
Part 3 will address methods for monitoring resources outside the JVM, including hosts and their operating systems and remote services such as databases and messaging systems. It will conclude with a discussion of additional APM issues such as data management, data visualization, reporting, and alerting.

A: Check out the JMX stats available and how to monitor them using JConsole. Lots of stats are available by default (garbage collection info, memory pools, thread-stats). CPU is a little trickier but check out this SO question for more details.
Note that you don't have to use just JConsole. You can easily write your own monitor to collate these stats.


text:
Q: 'This constraint cannot be enabled as not all values have corresponding parent values.' I want to create a nested XML DataTable but for some reason, it keeps throwing me the error: This constraint cannot be enabled as not all values have corresponding parent values.
This is the XML result that I am hoping for:
<Annotation>
  <Information>
    <folder>Kangaroo</folder>
    <filename>00001.JPG</filename>
  </Information>
  <size>
    <width>1024</width>
    <height>1024</height>
    <depth>3</depth>
  </size>
  <object>
    <bndbox>
      <ID>1</ID>
      <xmin>143</xmin>
      <ymin>163</ymin>
      <xmax>332</xmax>
      <ymax>335</ymax>
    </bndbox>
  </object>
</Annotation>

I have tried setting the id in bndbox as a primary key, creating a foreign key constraint, and setting the createConstraints parameter in the Relations.Add method to false. The latter of the three created an XML file but it did not create the object container at all which looks like this:
<Annotation>
  <Information>
    <folder>Kangaroo</folder>
    <filename>00001.JPG</filename>
  </Information>
  <size>
    <width>1024</width>
    <height>1024</height>
    <depth>3</depth>
  </size>
  <bndbox>
    <ID>1</ID>
    <xmin>143</xmin>
    <ymin>163</ymin>
    <xmax>332</xmax>
    <ymax>335</ymax>
  </bndbox>
</Annotation>

My current code:
//create object table
DataTable tableObj2 = new DataTable();
tableObj2.TableName = "object";

//add column id
DataColumn objIdColumn = new DataColumn();
objIdColumn.DataType = System.Type.GetType("System.Int32");
objIdColumn.ColumnName = "ID";
tableObj2.Columns.Add(objIdColumn);
tableObj2.PrimaryKey = new DataColumn[1] { objIdColumn };
DataRow row = tableObj2.NewRow();
row["ID"] = 1;

//create binding box table
DataTable tableBb2 = new DataTable();
tableBb2.TableName = "bndbox";
DataRow dataRow4 = tableBb2.NewRow();

//add column id and coordinates
tableBb2.Columns.Add("ID", typeof(int));
tableBb2.Columns.Add("xmin", typeof(int));
tableBb2.Columns.Add("ymin", typeof(int));
tableBb2.Columns.Add("xmax", typeof(int));
tableBb2.Columns.Add("ymax", typeof(int));

//insert values
dataRow4["ID"] = 1;
dataRow4["xmin"] = dataGridView1.Rows[0].Cells[1].Value;
dataRow4["ymin"] = dataGridView1.Rows[0].Cells[2].Value;
dataRow4["xmax"] = dataGridView1.Rows[1].Cells[1].Value;
dataRow4["ymax"] = dataGridView1.Rows[1].Cells[2].Value;
tableBb2.Rows.Add(dataRow4);

//add tables to Annotation dataset
ds.Tables.Add(tableBb2);
ds.Tables.Add(tableObj2);

//create data relation
DataRelation relation = ds.Relations.Add("relation", ds.Tables["object"].Columns["ID"], ds.Tables["bndbox"].Columns["ID"]);
relation.Nested = true;

Any direction or help with this is greatly appreciated!

A:
This constraint cannot be enabled as not all values have corresponding parent values.

You made a new row for the parent table here:
DataRow row = tableObj2.NewRow();

But you don't seem to have added it to the parent table. I would expect to see code like this somewhere before you attempt to add rows to a child table that references this new row:
tableObj2.Rows.Add(row);

Because you never added this row your code succeeds all the way up to the moment you tell the DataSet these tables are related at which point it says "one or more rows in your child table don't have a corresponding parent row in the parent table"
Remember; calling NewRow gives you a new Detached row. It has to be added to a table to function as part of a relationship

In other news, your life will get a lot nicer if you right click your project, add a new item, category Data, type DataSet.. open the DataSet, right click the design surface, choose Add.. Datatable. Specify your columns by right clicking it and choosing add..column. Specify your relation by clicking the grey part of the row next to the column name in the parent ID so that the whole row goes blue then dragging the blue row onto the child id in the other datatable and dropping it. This makes a typed DataSet. They're a lot nicer to work with in intellisense because they have typed  properties for columns etc so none of this row["ID"] = 1 or var x = (int)row["ID"]  - the row will have an ID property that is integer so it's row.ID = 1 or var x = row.ID - strongly typed, not stringly typed :)
If you do make a strongly typed DataSet remember this simple rule: if you're accessing the .Rows or .Columns collections (or putting a column name in a string) you're probably doing it wrong. These collections return base DataRow/DataColumn objects, which put you back in stringly typed world
//no
dt.Rows[0]

//yes
dt[0]

//no
dt.Columns["Colname"]

//yes
dt.ColnameColumn

//no
dt[0].IsNull("Colname")

//yes
dt[0].IsColnameNull()


text:
Q: not able to apply impulse to SKPhysicsbody so im working on a kind of side scroller, first game with Xcode and swift but here is what i have:
    import SpriteKit
import GameplayKit

let jumpButton = SKSpriteNode(imageNamed: "jumpButton")
var jumpButtonPosition = CGPoint(x: 500, y: -250)
var selectedButton = "nodeName"

let background1 = SKSpriteNode(imageNamed: "Woods_Background")
let background2 = SKSpriteNode(imageNamed: "Woods_Background")
let background3 = SKSpriteNode(imageNamed: "Woods_Background")

let player = SKSpriteNode(imageNamed: "player")
var playerColor = UIColor.red
var playerSize = CGSize(width: 50, height: 100)
var playerPhysicsBody = player.physicsBody
let playerJumpVector = CGVector(dx: 0, dy: 50)

let ground = SKSpriteNode()

var camPosition = CGPoint()
var playerPosition = camPosition
let cam = SKCameraNode()

var anchorpoint = CGPoint(x: 0.5, y: 0.5)
let endPoint = CGPoint(x: 100000, y: 0)

class GameScene: SKScene {

    override func didMove(to view: SKView) {

        super.didMove(to: view)
        self.camera = cam
        self.addChild(cam)

        spawnPlayer()
        spawnBackground()
        spawnJumpButton()
    }

    func spawnGround(){
        scene?.addChild(ground)
        ground.size = CGSize(width: size.width * 1, height: size.height * 0.1)
        ground.position = CGPoint(x: size.width * 0.5, y: size.height * 0.05)
        ground.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: size.height, height: size.height * 0.1))
        ground.physicsBody?.isDynamic = false
    }

    func spawnPlayer() {
        scene?.addChild(player)
        player.position = camPosition
        player.zPosition = 1
        player.size = playerSize
        player.physicsBody = playerPhysicsBody
        playerPhysicsBody?.affectedByGravity = false
        playerPhysicsBody?.mass = 50
    }

    func spawnJumpButton() {
        scene?.addChild(jumpButton)
        jumpButton.position = jumpButtonPosition
        jumpButton.zPosition = 0.5
        jumpButton.size = CGSize(width: 100, height: 100)
        jumpButton.name = "jumpButton"
        jumpButton.isUserInteractionEnabled = false
    }

    func jumpPlayer() {
        playerPhysicsBody?.applyImpulse(playerJumpVector)
    }

    func spawnBackground() {
        scene?.addChild(background1)
        background1.anchorPoint = CGPoint(x: 0.5, y: 0.5)
        background1.position.x = 0
        background1.zPosition = 0
        background1.size = CGSize(width: 3240, height: 1080)

        scene?.addChild(background2)
        background2.anchorPoint = CGPoint(x: 0.5, y: 0.5)
        background2.position.x = 3240
        background2.zPosition = 0
        background2.size = CGSize(width: 3240, height: 1080)

        scene?.addChild(background3)
        background3.anchorPoint = CGPoint(x: 0.5, y: 0.5)
        background3.position.x = 6480
        background3.zPosition = 0
        background3.size = CGSize(width: 3240, height: 1080)
    }

    override func update(_ currentTime: TimeInterval) {

        if cam.position.x > background2.position.x {
            background1.position.x = background3.position.x + 3240
        }
        if cam.position.x > background3.position.x {
            background2.position.x = background1.position.x + 3240
        }
        if cam.position.x > background1.position.x {
            background3.position.x = background2.position.x + 3240
        }
        camPosition.x = playerPosition.x
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            if let touch = touches.first {
                if selectedButton == "nodeName" {
                    if jumpButton.contains(touch.location(in: self)) {
                       jumpPlayer()
                    }
                }
            }
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        selectedButton = "nodeName"
    }
}

Im trying to get the player to jump with use of the button, when clicked the player should jump about 20 pixels in the air. same applies for the running motion of the player, cant get it to run forever without animations, with which you cant do other stuff at the same time.

A: The player.physicalBody is nil and need to handle!
   func spawnPlayer() {
    scene?.addChild(player)
    player.position = camPosition
    player.zPosition = 1
    player.size = playerSize

    //Here adding two lines
    player.physicsBody =  SKPhysicsBody()
    playerPhysicsBody?.linearDamping = 1

     playerPhysicsBody?.affectedByGravity = false
    playerPhysicsBody?.mass = 50
     }

     func jumpPlayer() {
    //Here changing one line
    playerPhysicsBody?.applyImpulse(playerJumpVector)
     }


text:
Q: Common function for calling debugger; in Javascript How can I make a common function in my global.js to for calling debugger; in JS. I'll basically set a value whether to debug or not. I tried the following but it's not working. Any lead will be appreciated.
<script type="text/javascript">
var debugModeVal = 1;
debugMode = function()
{
  if(debugModeVal)
  {
    debugger;
  }
  return;
}
</script>

I am calling from my html file like this
<script type="text/javascript">
function callAnotherFunction()
{
   debugMode;
}
</script>

A: use debugMode() instead of debugMode; in callAnotherFunction().
For debugging, use step out of the debugMode function to find yourself in the caller. Thanks to Jan Dvorak.


text:
Q: PostgreSQL: How to modify values in view I have a table I don't want to touch, but from this table I want to create many views that will serve different purposes/analyses.
In one case, I need to change a value based on a condition (-1 become some positive value).
Is it even possible to do that in PostgreSQL?
For example, -1 in the table will become 1 in the view if Col3='B':
+------+------+------+    +------+------+------+
| Col1 | Col2 | Col3 |    | Col1 | Col2 | Col3 |
+------+------+------+ >  +------+------+------+
|    1 |  3.5 | A    | >  |    1 |  3.5 | A    |
|    2 |   -1 | B    | >  |    2 |    1 | B    |
|    3 |   -1 | A    |    |    3 |   -1 | A    |
+------+------+------+    +------+------+------+

A: You need to modify the view an put the logic in the query:
select col1,
       (case when col3 = 'B' and col2 = -1 then 1 else col2 end) as col2,
       col3
from . . .


text:
Q: C++ // Trying to rewrite a working code to include my function My code is supposed to print an "a" amount of numbers (1 < a < n < 100000) which are simultaneously divisible by "x" and indivisible by "y" - all this for "t" amount of data sets.
I've written a code which does just that using only the main() function, but - as I'm learning about functions - I'm trying to rewrite this code to include my own function. For example, if I enter t=1, n=35, x=5 and y = 14, the output should be: "5 10 15 20 25 30".
Code 1 is the code which works fine, only with the main function. Code 2 is the code I'm currently working on which is supposed to include my function "check"
I've managed to rewrite the code 2 to a point where it returns the ASCII symbols corresponding to the numbers I'm supposed to obtain, but I'm having problems converting these symbols into numbers fulfilling my requirements.
When entering "1 7 2 4" as input data, the code returns two symbols instead of "2 6".
Any help with fixing this issue would be very appreciated...
Code 1:
#include <iostream>

using namespace std;

int main()
{
    int t, n, x, y;
    cin >> t;

    for (int i=0; i<t; i++)
    {
        cin >> n >> x >> y;

        for (int a=0; a<n; a++)
        {
            if ((a%x==0)&&(a%y>0))
                cout << a << " ";
        }
        cout << endl;
    }
    return 0;
}

Code 2:
#include <iostream>

using namespace std;

string check (int n, int x, int y)
{
    string result;
    for (int a=0; a<n; a++)
    {
        if ((a%x==0)&&(a%y>0))
        {
            result += a;
            result += " ";
        }
    }
    return result;
}

int main()
{
    int t, n, x, y;
    cin >> t;

    for (int i=0; i<t; i++)
    {
        cin >> n >> x >> y;
        cout << check (n, x, y) << endl;
    }
    return 0;
}

A: What's the problem ?
This is because the following statement is understood by the compiler as if you wanted to add a single char to the string (so the char corresponding to the ascii code of a, if the string encoding is ascii):
result += a;

You may test this behavior of operator+= by trying:
result += 64;   // ascii code for @

How to solve it ?
To get the result you expect, you need to convert a explicitly into a string.  So change the line to:
result += to_string(a);

Isn't there an easier way ?
Alternatively, if you have a lot of formatting, and if you're comfortable with streams,  you may want to consider stringstream:
string check (int n, int x, int y)
{
    stringstream result;
    for (int a=0; a<n; a++)
    {
        if ((a%x==0)&&(a%y>0))
        {
            result << a << " ";
        }
    }
    return result.str();
}

The stringstreams behave as ordinary streams (e.g. cout), except that they write the result into memory.  You can then easily transform the end result using the str() member function.


text:
Q: Exporting table to Excel file using javascript I was able to create the XLS file using JavaScript using Active X controls.
For IE I did the following :
    var objExcel = new ActiveXObject("Excel.Application");
    objExcel.visible = false;
    var objWorkbook = objExcel.Workbooks.Add;
    var objWorksheet = objWorkbook.Worksheets(1);
    objWorksheet.Paste;
    objExcel.visible = true;

But to use ActiveX controls I need to go to Internet Option -> Security ->Custom Level ->Enable  Initialize and script ActiveX controls not marked as safe for scripting . After enabling this only I am able to create the XLS file.
Is there any other way to create the XLS file in IE-11 apart from active X
I tried to use the following
var vDiv = document.getElementById('dvData');
                    vDiv.innerHTML = vTable;
                    var url='data:application/vnd.ms-excel,' + encodeURIComponent($('#dvData').html()) ;

but its not working in IE-11. I need to use pure javascript.
Thanks in advance

A: First you need to convert the table to a way that excel can understand it.
Expecting a html code to work out of the box in excel is wrong.
Once you got the data in the right format you should create a Blob and download that, one good lib to help out with saving blob is FileSaver.js
var chunk = '<?xml version="1.0"?>...'
var blob = new Blob([chunk], {type: 'application/vnd.ms-excel'})
saveAs(blob, 'filename.xls') // using FileSaver.js


text:
Q: Displaying Same Result-Set Hierarchical Data in SQL I have 3 tables, Let's say TierOne, TierTwo, TierThree
TierTwo has a foreign key to TierOne and TierTwo has a foreign key to TierThree
So I could have data like the following:
TierOne
ID        title
1         Tier1 Item1
2         Tier1 Item2
3         Tier1 Item3

TierTwo
ID        ParentID        title
1         1               Tier2 Item1
2         1               Tier2 Item2
3         2               Tier2 Item3
4         2               Tier2 Item4
5         3               Tier2 Item5

TierThree
ID        ParentID        title
1         1               Tier3 Item1
2         1               Tier3 Item2
3         2               Tier3 Item3
4         2               Tier3 Item4
5         3               Tier3 Item5
6         4               Tier3 Item6
7         5               Tier3 Item7

Now, the problem: Over the three tables I have 15 rows, I need to display each tier and it's children one by one. Desired output: *Note I have tabbed the change in tiers for easier viewing.
title
Tier1 Item1
  Tier2 Item1
    Tier3 Item1
    Tier3 Item2
  Tier2 Item2
    Tier3 Item3
    Tier3 Item4
Tier1 Item2
  Tier2 Item3
    Tier3 Item5
  Tier2 Item4
    Tier3 Item6
Tier1 Item3
  Tier2 Item5
    Tier3 Item7

I have tried using CTE with tier1 and tier2 but the result set was huge.


text:
Q: How to use a multiple criteria Alerts in tradingview is it possible to make multi alerts criteria for the deal to start ?
for example, when it's >50 RSI & MACD is Green (ONLY then the trade opens) and the two or more conditions to the sell order to be fulfiled.
i tried making two criteria's but it opens when it's meet any of the two alerts.
HOW to make the 2 or 3 alerts to work together ?
thanks a lot for your help beforehand

A: Sure, just use the and operator and combine your conditions together.
longCondition = (rsi > 50) and (macd_hist > 0) and (close > open)

if longCondition
    strategy.entry("Long", strategy.long)


text:
Q: Abelian image of l-adic representation For a number field F, let E/F be an elliptic curve with CM by a quadratic field K. Let $\rho_\ell: \text{Gal}_F \to \text{Aut}(T_{\ell}E)$ be the $\ell$-adic representation associated to E for some prime $\ell$, and let $\mathcal{G}_{\ell}$ denote its image. According to Theorem 5 in Serre's "Groupes de Lie $\ell$-adiques attaches aux courbes elliptiques" (1966), $\mathcal{G}_{\ell}$ is abelian if and only if K $\subset$ F.
Is it always the case that $\mathcal{G}_{\ell}$ being abelian forces K $\subset$ F, or are there some restrictions on $\ell$ that I haven't been able to find in the paper?

A: There are no restrictions on $l$. What's going on is that if the $CM$ endomorphisms are defined over $KF$ but not over $F$, there must be elements in the $\operatorname{Gal}(KF|F)$ that conjugate these endomorphisms to different endomorphisms. Since the endomorphisms act faithfully on the Galois representation, the only missing piece is to find an element of the Galois group that has the same action on the Galois-representation as one of the CM endomorphisms. One can check that the Frobenius elements of primes of $F$ that split in $KF$ act this way.


text:
Q: Unity2D Snake Game So I made a snake game in unity but whenever the snake grows the segment that should be added to the snake dissappears when i change the direction and idk why.
Here's the code:
    private void FixedUpdate()
    {
        for (int i = _segments.Count - 1; i > 0; i--)
        {
            _segments[i].position = _segments[i - 1].position;
        }

        this.transform.position = new Vector2(
            Mathf.Round(this.transform.position.x) + sobolan.x,
            Mathf.Round(this.transform.position.y) + sobolan.y
            );

    }

    private void Grow()
    {
        Transform segment = Instantiate(this.segmentPrefab);
        segment.position = _segments[_segments.Count - 1].position;
        _segments.Add(segment);
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.tag == "Food")
        {
            Grow();
        }
    }


text:
Q: Highcharts error 13 in dynamic id I have a DIV with id defined in a variable, in this DIV should be loaded a Highcharts graphic, however, when I define a variable ID it does not load but when I put a fixed ID it loads, when it does not load from ERROR 13 of the Highcharts (print this in console: Error: Highcharts error #13: www.highcharts.com/errors/13 ....).
How should I do to with Dynamic ID?
The DIV:

The function in controller that generates the graph:
vm.chartModalClass = "chartPM";
vm.loadChart = loadChart;

function loadChart(){
    vm.chartPM = new Highcharts.chart(vm.chart);

};

How do I set the renderTo of the chart:
vm.chart = {
        chart: {
            type: 'column',
            renderTo: vm.chartModalClass,
            backgroundColor: 'rgba(255, 255, 255, 0)'
        },....


text:
Q: is TFX (Tensorflow Extended) being used in big companies I've recently stumbled upon tensorflow extended, and I've finally started to understand the need and uses of it. It makes the whole machine learning pipeline a lot easier and looks like it can be used to automate the tasks. I wanted to ask seniors in this field, are big companies using it, is it extensively being used or will it get obsolete
Thank you

A: From the article Towards ML Engineering: A Brief History Of TensorFlow Extended (TFX)

TFX is used by thousands of users within Alphabet, and it powers hundreds of popular Alphabet products, including Cloud AI services on Google Cloud Platform (GCP). On any given day there are thousands of TFX pipelines running, which are processing exabytes of data and producing tens of thousands of models, which in turn are performing hundreds of millions of inferences per second.

From the presentation TensorFlow Extended An End to End Machine Learning Platform for TensorFlow:

On the TFX case studies page, you can see companies like:

*

*Airbnb

*Airbus

*ARM

*Coca Cola

*Intel

*Lenovo

*PayPal

*Spotify

*Twitter

*...


text:
Q: Are my calculations concerning the growth rate of $f(n) = \sum_{k=0}^n \min(2^k, 2^{2^{n-k}})$ correct? Having $$f(n) = \sum_{k=0}^n g_n(k), \; g_n(x) = \min(2^x, 2^{2^{n-x}})$$
I want to know whether $\mathcal O(f(n)) \subsetneq \mathcal O(2^n)$. Since $g_n(x) \le 2^x$ it is at least $f(n) \in \mathcal O(2^{n+1}-1) = \mathcal O(2^n)$.

Let $x_n$ be the maximum point of $g_n(x)$, which is where $2^x = 2^{2^{n-x}}$. We get
$$f(n) = \sum_{k=0}^{\lfloor x_n \rfloor} 2^k + \sum_{k=0}^{n - \lfloor x_n \rfloor} 2^{2^k}$$
Since $x_n$ solves $x + \log_2(x) = n$ we get for the second sum
$$\sum_{k=0}^{n - \lfloor x_n \rfloor} 2^{2^k} = \sum_{k=0}^{ \lfloor \log_2(x_n) \rfloor} 2^{2^k} \le \sum_{k=0}^{ \lfloor x_n \rfloor} 2^k$$
Therefore $f(n) \in \mathcal O \big( \sum_{k=0}^{\lfloor x_n \rfloor} 2^k\big) = \mathcal O \big(2^{\lfloor x_n \rfloor} \big)$.
I'm quite unsure about the following lines, especially since this is the first time I've come across the Lambert-W-function, which is needed to solve $x + \log_2(x) = n$ (according to WolframAlpha):
$$x_n = {W(2^n \log(2)) \over\log(2)}$$
From this paper, section 2.8, I've got
$$ W(x) \in \mathcal O \Bigg(\log(x)-\log(\log(x))+{\log(\log(x)) \over \log(x)}\Bigg)$$
And plugging everything together (omitting constants):
$$ f(n) \in  \mathcal O\big(2^{ W(2^n)}\big) = \mathcal O\Bigg(2^{ \log(2^n)-\log(\log(2^n))+{\log(\log(2^n)) \over \log(2^n)}}\Bigg) = \mathcal O\Big(2^n \cdot 2^{-\log(n)}\cdot \sqrt[n]{2^{\log(n)}}\Big) = \mathcal O\Big(2^n \cdot {1 \over n} \cdot 1\Big) = \mathcal O\Big({2^n \over n}\Big)$$
Is this correct? Is there some easy way to do it without Lambert-W?


text:
Q: Android service- how to communicate with activities I'm wondering which is the best way to communicate between a Service and an activity..

*

*Broadcast intent

*Callback

*others?...

Bye

A: I've been running into pretty much the same problem. Take a look at my question, answers turned out extremely useful for me.
In fact I haven't directly used a service in the end but switched to the AlarmManager. Worked out as I initially wanted it to be. Good luck


text:
Q: how to convert special characters to html data in xml? I am creating dynamic xml file to mysql data.
In that, Mysql data so many special character and &,<>...etc are there.
If you display these all things in browser,there is no problem it will display properly.
Coming to the xml, If you display in xml  it's showing errors.not displaying properly.In that content,so many special chars and unknown symbols are coming.If i display content in xml, i want to get pure content(human readable) same like as a html data.
can you please solve this problem...

A: use cdata in your xml
<xmltag><![CDATA[]]></xmltag>

<xmltag><![CDATA[" and ends with "]]></xmltag>

this will help you to solve your problem


text:
Q: Cell elements as comma separated input arguments for varargin function Imagine a function with a variable number of input arguments, alternately asking for a string and a value.
myfunction('string1',value1,'string2',value2,...)

e.g.
myfunction('A',5,'B',10)

I want to keep the ability to call the function like that and I dont want to change the evaluation of varargin inside the function. (Except ('string1','string2',...,value1,value2,...) if that helps)
But I also have my input strings and values stored in a cell array inputvar <4x1 cell>:
inputvar =

'A'    [5]    'B'    [10]

Also this cell array has a variable length.
My intention is to call my function somehow as follows:
myfunction( inputvar )

which is obviously not working. Any ideas how I could transform my cell to a valid input syntax?

I already tried to generate a string like
''string1',value1,'string2',value2'

and use eval to use it in the function call. But it didn't worked out. So alternatively is there a way to transfor a string to code?

A: You should be able to do it like this:
myfunction(inputvar{:})

{:} creates a comma separated list

EDIT:
For example:
function val = myfunction(string1,value1,string2,value2)
    if string1 == 'A'
      val = value1;
    else
      val = value2;
end

myfunction('A',5,'B',10)
myfunction('B',5,'B',10)
A = {'A',5,'B',10};
myfunction(A{:})
A = {'B',5,'B',10};
myfunction(A{:})

returns:
ans =  5
ans =  10
ans =  5
ans =  10


text:
Q: ios : Displaying a simple 3D model with GLEssentials sample code My goal is to display a simple 3D model and apply a texture on it.
I've downloaded the GLEssentials ios sample project to learn how to develop this (i'm new in ios OpenGL-ES API)
But the example model is a .model file, which I never heard about and which never appear in model bank websites.

*

*What is this kind of file?

*is the sample code compatible with other common model types (.obj, .c2d, .3ds)?

*is it a good idea to start from this project?

A: Have a look at this question:

*

*How to convert Blender blend (or obj) file to Qualcom Vuforia .h file
In my answer, I describe a script and accompanying Xcode project that converts .obj/.mtl files to header files suitable for OpenGL ES on iOS [link].
In response to your questions:

*

*I believe the .model file is only appropriate for the sample project and is a proprietary Apple extension. It most likely contains simple data such as vertex positions.

*I think you'd struggle to fit other model types into the sample code, which is very complex for OpenGL ES beginners. You might want to have a look at .pod files on Cocos2D here. I've seen and heard great things about it.

*I wouldn't recommend it :)


text:
Q: Spring Connect to Jboss Topic remotely I am working on Spring3.1 in a standalone env.
I am trying to consume messages remotely from a jboss4 machine(having Jboss messaging 1.4 as a the jms provider)
After searching in the net I am kind of lost.
what I have done so far is to config my applicationContext with this:
<bean id="tgwTopic" class="org.springframework.jndi.JndiObjectFactoryBean"
    depends-on="jmsServerManagerImpl">
    <property name="jndiName" value="/topic/feedTopicRealTime" />
    <property name="jndiEnvironment">

        <props>
            <prop key="java.naming.provider.url">remove.server.url:1099</prop>
            <prop key="java.naming.factory.initial">org.jnp.interfaces.NamingContextFactory</prop>
            <prop key="java.naming.factory.url.pkgs">org.jboss.naming:org.jnp.interfaces</prop>
            <!-- other key=values here -->
        </props>
    </property>
</bean>

and this is my java bean:
   @Service("TGWMDB")
public class TGWMDB implements MessageListener
{
       @Autowired   Topic tgwTopic;

      public void onMessage(Message message)
      {
      }

}

thanks,
ray.

A: You need a message listener container; it's all explained here...
http://static.springsource.org/spring-framework/docs/3.1.1.RELEASE/spring-framework-reference/html/jms.html#jms-asynchronousMessageReception


text:
Q: Laravel 5.2 redirect in AuthController create method I'm trying to redirect user to the homepage if hidden input field has been changed to an invalid value, but since create method must return user instance i can't do that here. So what are my options?
 /**
 * Create a new user instance after a valid registration.
 *
 * @param  array  $data
 * @return User
 */
protected function create(array $data)
{
    $role = Role::where('name', $data['role'])->first();

    // Hidden role field has been tampered with! Redirect to homepage.
    if(!$role){
        return redirect('/');
    }

    $user = new User();
    $user->email = $data['email'];
    $user->password = bcrypt($data['password']);
    $user->save();
    $user->roles()->attach($role);
    return $user;
}

Fatal error with above code:
FatalThrowableError in SessionGuard.php line 418:
Type error: Argument 1 passed to Illuminate\Auth\SessionGuard::login() must be an instance of Illuminate\Contracts\Auth\Authenticatable, instance of Illuminate\Http\RedirectResponse given, called in E:\xampp\htdocs\taskie\vendor\laravel\framework\src\Illuminate\Foundation\Auth\RegistersUsers.php on line 63

A: In the AuthController generated with artisan make:auth, the register user request is handled by the method register, not create. This method is implemented in the trait Illuminate\Foundation\Auth\RegistersUsers. You may overload this method in your controller and change its behaviour.
/**
 * Handle a registration request for the application.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function register(Request $request)
{
    $data = $request->all();
    $role = Role::where('name', $data['role'])->first();

    // Hidden role field has been tampered with! Redirect to homepage.
    if(!$role){
        return redirect('/');
    }

    return parent::register($response);
}

A: I solved the problem by creating a custom validation.
'email' => ['required','max:255','unique:users','regex:/(@org.co.uk)$/',],

and now no need of Redirects.


text:
Q: java.lang.NoSuchMethodError: after adding constructor in a class Could someone please help me understand why after adding a new constructor to a class which takes two parameters, the project compiles but my test now cannot create a new instance of this class?
I get this exception:

java.lang.NoSuchMethodError:
  pidac.workflow.TestClass.(Lcom/pidac/infrastructure/core/service/CrudService;Lcom/pidac/infrastructure/core/service/AuditService;)V
at
  pidac.workflow.SomeTests.shouldAuditCompletedIdentityRequestItemsAgainstConnectedSources(SomeClass.java:115)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)     at
  org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at
  org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at
  org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at
  org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at
  org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)    at
  org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at
  org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)  at
  org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)   at
  org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)     at
  org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)   at
  org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)  at
  org.junit.runners.ParentRunner.run(ParentRunner.java:363)     at
  org.junit.runner.JUnitCore.run(JUnitCore.java:137)    at
  com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at
  com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at
  com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at
  com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

I am using IntelliJ 2018 professional.
More Info Dec 29:
I have deleted the maven local snapshot for this project and rebuilt.
When I debug the test, I can see that the class has this new constructor.  However, there is obviously a mismatch between what the debugger is executing and what I see in IntelliJ.

A: NoSuchMethodError occurs when a method that was present at compile time is no longer present at runtime.
Your compiled class files are out of date. Rebuild your project.

A: I had to manually delete the gradle output folder currently configured in [module]/out/production/classes.
My project has this folder configured for output so when I looked at the compiled classes in there, the new changes were not reflected.  So I figured this compiled classes were not being updated and just deleted them.
Re-assembled the project and my tests are now able to see the changes even though I do not see the compiled classes in the location above....

A: Your class loses its default constructor (no args) when you declare one with 2 args. The test you are writing probably expects a default constructor to get an instance.
Build another explicit no-args constructor or if you're using the excellent Lombok library, annotate the class with @NoArgsConstructor to get your tests working. Alternatively, change your test to initialize the class with 2 attributes in the constructor.
As mentioned by Nicholas, a code sample from you will help.
Default constructor is explained in another SO question here: Java default constructor


text:
Q: C# lock single line (if statement) Is this code locking only on if statement, or for both lines of code?
lock (LockObject)
    if (instance == null)
        instance = Instance();

A: if statement can't be executed alone, it needs block after it for the true-case of expression, so, as @Mureinik already said, lock locks your entire initialization block. You can even write it like this:
lock (LockObject) if (instance == null) instance = Instance();

However, this is not recommended to write your code without curly braces in such cases as it is very confusing and hard to debug. Also note that lock statement is a syntax sugar for Monitor class usage, and your code is compiled into this:
try
{
    Monitor.Enter(LockObject);
    if (instance == null)
    {
        instance = Instance();
    }
}
finally
{
    Monitor.Exit(LockObject);
}

And I want to note that for initialization logic you can use a Lazy<T> class, which is thread-safe, and uses not so heavy constructures as Monitor, and can perform faster than your code. Code will be like this:
// field in class
Lazy<Instance> lazyInstance = new Lazy<Instance>(() => Instance());

//usage in code
var instanceValue = lazyInstance.Value;

A: Lock is translated by the C# compiler to Monitor.Enter and Monitor.Exit. This C# code
static void Main(string[] args)
{
    lock (LockObject)
        if (instance == null)
            instance = Instance();
    Console.WriteLine(instance == null);
}

gives the IL code below, which clearly shows that Monitor.Exit (L_0036) is called after instance is assigned (L_0026).
Both lines of code are locked.
.method private hidebysig static void Main(string[] args) cil managed
{
  .entrypoint
  .maxstack 2
  .locals init (
    [0] bool flag,
    [1] object obj2,
    [2] bool flag2)
  L_0000: nop
  L_0001: ldc.i4.0
  L_0002: stloc.0
  L_0003: ldsfld object TestLock.Program::LockObject
  L_0008: dup
  L_0009: stloc.1
  L_000a: ldloca.s flag
  L_000c: call void [mscorlib]System.Threading.Monitor::Enter(object, bool&)
  L_0011: nop
  L_0012: ldsfld object TestLock.Program::instance
  L_0017: ldnull
  L_0018: ceq
  L_001a: ldc.i4.0
  L_001b: ceq
  L_001d: stloc.2
  L_001e: ldloc.2
  L_001f: brtrue.s L_002b
  L_0021: call object TestLock.Program::Instance()
  L_0026: stsfld object TestLock.Program::instance
  L_002b: leave.s L_003d
  L_002d: ldloc.0
  L_002e: ldc.i4.0
  L_002f: ceq
  L_0031: stloc.2
  L_0032: ldloc.2
  L_0033: brtrue.s L_003c
  L_0035: ldloc.1
  L_0036: call void [mscorlib]System.Threading.Monitor::Exit(object)
  L_003b: nop
  L_003c: endfinally
  L_003d: nop
  L_003e: ldsfld object TestLock.Program::instance
  L_0043: ldnull
  L_0044: ceq
  L_0046: call void [mscorlib]System.Console::WriteLine(bool)
  L_004b: nop
  L_004c: ret
  .try L_0003 to L_002d finally handler L_002d to L_003d
}

A: lock locks an entire block. Since it's not followed by curly braces ({}), it locks an implicit block - the if statement. Here, the same logic applies - if executes a block if the condition is met. Since it is also not followed by curly braces, it implicitly has a block that contains a single statement. In other words, the given code is equivalent to:
lock (LockObject) {
    if (instance == null) {
        instance = Instance();
    }
}

A: It's locking all of the code. Here { and } for if are just omitted.

A: The if statement includes a statement for the "then" case. So the lock applies to both lines.
A simple rule of thumb is: if there's a { it applies until the matching }, otherwise it applies until the first ;. That does not cover all situations, but certainly the most common ones.

A: It is locking the whole statement. Consider the following example:
 lock (LockObject)
 {
     if (instance == null) {
 }

If it is only locking the if condition when using braces, then it will result to compiler error since it is not properly arranged/matched.

A: This code snippet is locking both lines of code.
Lock on LockObject won't be released until if statement has finished execution. It means, if your condition in line 2 is true then it's going to execute line 3 before releasing the lock in line 1
Hope that helps :)


text:
Q: Permission denied error when running simple c++ program I get this error almost everytime i try to run a simple code on CLion.
I'm not trying to save the project in c drive.

c:/mingw/bin/../lib/gcc/mingw32/6.3.0/../../../../mingw32/bin/ld.exe: cannot open output file A__IQ_test.exe: Permission denied
  collect2.exe: error: ld returned 1 exit status
  CMakeFiles\A__IQ_test.dir\build.make:95: recipe for target 'A__IQ_test.exe' failed
  mingw32-make.exe[3]: * [A__IQ_test.exe] Error 1
  mingw32-make.exe[2]:  [CMakeFiles/A__IQ_test.dir/all] Error 2
  CMakeFiles\Makefile2:66: recipe for target 'CMakeFiles/A__IQ_test.dir/all' failed
  mingw32-make.exe[1]:  [CMakeFiles/A__IQ_test.dir/rule] Error 2
  CMakeFiles\Makefile2:78: recipe for target 'CMakeFiles/A__IQ_test.dir/rule' failed
  mingw32-make.exe: * [A__IQ_test] Error 2
  Makefile:117: recipe for target 'A__IQ_test' failed

A: This usually means your program is already running. You can't replace it with a new one while it's running. Ensure you've closed your program before you try to rebuild it. If you think you've done so, there may be a bug where it is hanging — attach your debugger to find out.


text:
Q: Get command line arguments as string I want to print all command line arguments as a single string. Example of how I call my script and what I expect to be printed:
./RunT.py mytst.tst -c qwerty.c

mytst.tst -c qwerty.c

The code that does that:
args = str(sys.argv[1:])
args = args.replace("[","")
args = args.replace("]","")
args = args.replace(",","")
args = args.replace("'","")
print args

I did all replaces because sys.argv[1:] returns this:
['mytst.tst', '-c', 'qwerty.c']

Is there a better way to get same result? I don't like those multiple replace calls

A: An option:
import sys
' '.join(sys.argv[1:])

The join() function joins its arguments by whatever string you call it on.  So ' '.join(...) joins the arguments with single spaces (' ') between them.

A: None of the previous answers properly escape all possible arguments, like empty args or those containing quotes. The closest you can get with minimal code is to use shlex.quote (available since Python 3.3):
import shlex
cmdline = " ".join(map(shlex.quote, sys.argv[1:]))

EDIT
Here is a Python 2+3 compatible solution:
import sys

try:
    from shlex import quote as cmd_quote
except ImportError:
    from pipes import quote as cmd_quote

cmdline = " ".join(map(cmd_quote, sys.argv[1:]))

A: You're getting a list object with all of your arguments when you use the syntax [1:] which goes from the second argument to the last.  You could run a for each loop to join them into one string:
args = sys.argv[1:]
result = ''

for arg in args:
    result += " " + arg

A: The command line arguments are already handled by the shell before they are sent into sys.argv.  Therefore, shell quoting and whitespace are gone and cannot be exactly reconstructed.
Assuming the user double-quotes strings with spaces, here's a python program to reconstruct the command string with those quotes.
commandstring = '';

for arg in sys.argv[1:]:          # skip sys.argv[0] since the question didn't ask for it
    if ' ' in arg:
        commandstring+= '"{}"  '.format(arg) ;   # Put the quotes back in
    else:
        commandstring+="{}  ".format(arg) ;      # Assume no space => no quotes

print(commandstring);

For example, the command line
./saferm.py sdkf lsadkf -r sdf -f sdf -fs -s "flksjfksdkfj sdfsdaflkasdf"

will produce the same arguments as output:
sdkf lsadkf -r sdf -f sdf -fs -s "flksjfksdkfj sdfsdaflkasdf"

since the user indeed double-quoted only arguments with strings.


text:
Q: The fixed top:0 right:0 item is not correctly showed on mobile when virtual keyboard is there, how to fix? Here is my code:

body {}
#holder {
transform: translate3d(0,0,0);
      position:fixed;top:0; right:0;opacity:.5;background:black;width:60px;height:30px}

<svg version='1.1' id='L9' xmlns='http://www.w3.org/2000/svg' x='0px' y='0px' viewBox='-18 40 100 100' enable-background='new 0 0 0 0' xml:space='preserve'><rect x='20' y='50' width='4' height='10' fill='#fff' transform='translate(0 13.1135)'><animateTransform attributeType='xml' attributeName='transform' type='translate' values='0 0; 0 20; 0 0' begin='0' dur='0.6s' repeatCount='indefinite'></animateTransform></rect><rect x='30' y='50' width='4' height='10' fill='#fff' transform='translate(0 13.5532)'><animateTransform attributeType='xml' attributeName='transform' type='translate' values='0 0; 0 20; 0 0' begin='0.2s' dur='0.6s' repeatCount='indefinite'></animateTransform></rect><rect x='40' y='50' width='4' height='10' fill='#fff' transform='translate(0 0.219867)'><animateTransform attributeType='xml' attributeName='transform' type='translate' values='0 0; 0 20; 0 0' begin='0.4s' dur='0.6s' repeatCount='indefinite'></animateTransform></rect></svg>

dummy

dummy

dummy

dummy

dummy

dummy

dummy

dummy

dummy

dummy

dummy

dummy

dummy

dummy

dummy

dummy

dummy

dummy

dummy

dummy

dummy

dummy

<textarea></textarea>

I am adding a loading effect to my page. The effect is an SVG contained in a div, and I put the div on the top:0, right:0 with position:fixed.
However, the loading div is not showing up on my iPhone if the virtual keyboard is there.
I find it very hard to view the snippet on StackOverflow so I made a picture to demonstrate this:

When the user invokes the keyboard, the loading div is "pushed" up. However, this doesn't happen every time. In a few attempts, there would be likely 20% chance to get it right (the loading not going above).
Is there any fix to this?

A: You could use a media query in CSS to write specific code that when the height is X amount (X being equal to the screen height, minus the keyboard height, on a phone). You may have to write some more CSS but it would fix the issue. let me know if that works.


text:
Q: java.lang.IllegalStateException: Replacing an existing task that may have already been used by other plugins is not supported I am using gradle6.7 and ml-gradle 4.1.0 version in my my project but i am getting error given below at the the time of Deployment:
"java.lang.IllegalStateException: Replacing an existing task that may have already been used by other plugins is not supported.  Use a different name for this task ('mlLoadSchemas')."

A: Gradle 6 does not allow for tasks to be replaced. ml-gradle declares a task named mlLoadSchemas. So either another plugin (DHF?) or something in your build.gradle file is trying to replace that task with another task, which Gradle 6 disallows.


text:
Q: How to execute an external process in VisualWorks? How do you execute an external process in VisualWorks Smalltalk?

A: Use ExternalProcess fork. e.g. ExternalProcess fork: 'date'..
However, fork will only take one program and the arguments have to be passed separately in an array. If you want a more complex command you can use the shOne: method: ExternalProcess  shOne: 'test -d data || mkdir data && cd data'.


text:
Q: Runtime error 91 - When using Range.Find and String from TextBox I'm facing a problem with a function I'm trying to create.
The function should do the following:
- Ask for the values
- Return True or False if the value exists or not in the B:B column.
This is what I have so far...
Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Dim Ret As Boolean
Dim FindText As String
If KeyCode = 13 Then
    With Sheets("Dados")
        Columns("B:B").Select
        FindText = TextBox1.Text
        Ret = Selection.Find(What:=FindText, After:=.Cells(1, 1), LookIn:=xlValues, LookAt _
        :=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase _
        :=False, SearchFormat:=False).Activate
        MsgBox "Hy " & FindText & " > " & Ret
        If FindText Is Nothing Then Exit Sub
    End With
End If End Sub

This works great when the value is true, but gives me the runtime error 91 - Object variable or With block variable not set if the value is false :(

A: FindText is a String Variable not an Object variable. Only Objects can be set to or have the Value Null. So when the False is executed. It is looking for an Object, since it is not set it throws the error.
You do not even need the line of code as it computes afters getting into the Selection. You need to validate the Data before going for checking, so try this maybe.
Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    Dim Ret As Boolean
    Dim FindText As String

    If Len(TextBox1.Text & vbNullString) = 0 Then Exit Sub

    If KeyCode = 13 Then
        With Sheets("Dados")
            Columns("B:B").Select
            FindText = TextBox1.Text
            Ret = Selection.Find(What:=FindText, _
                                 After:=.Cells(1, 1), _
                                 LookIn:=xlValues, _
                                 LookAt:=xlWhole, _
                                 SearchOrder:=xlByColumns, _
                                 SearchDirection:=xlNext, _
                                 MatchCase:=False, _
                                 SearchFormat:=False).Activate
            MsgBox "Hy " & FindText & " > " & Ret
        End With
    End If

End Sub

A: First off stop using .select.  Secondly, you are missing a period before Columns to refer to your With...
Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Dim Ret As Boolean
Dim FindText As String
If KeyCode = 13 Then
    If TextBox1.Text = "" Then Exit Sub
    FindText = TextBox1.Text
    With Sheets("Dados")
        If .Columns("B:B").Find(What:=FindText, After:=.Cells(1, 1), LookIn:=xlValues, LookAt_
            :=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase_
            :=False, SearchFormat:=False) is Nothing Then
            Ret = False
        Else
            Ret = True
        End If
    End With
    MsgBox "Hy " & FindText & " > " & Ret
End If
End Sub


text:
Q: Modbus slave count limitation I have two questions:

*

*Why does Modbus allow only 247 slaves to be connected to the same network?

*How it this limitation overcome by Modbus TCP/IP?

A: 1) The address field in the Modbus-defined frame is only 8 bits wide. This would provide for 256 possible slave addresses.  Address 0 is reserved as a "broadcast" address.
I can't find a specific reason, but there are presumably eight other "reserved" addresses that are not valid for a slave. 256 - 9 = 247.
2)  Modbus TCP/IP is implemented atop standard IPv4 addressing, which is limited only to the size of the local subnet (e.g. 10.10.0.0). Each "gateway" on the network will have its own IP address, so there can be many more than 247 gateways.
In addition, each gateway can have multiple Modbus devices behind it. The number of devices behind such a gateway is limited by the same 8-bit address field, here called the "Unit Identifier".
Reference:

*

*Modbus Protocol Reference Guide

*"Modbus" (Wikipedia)


text:
Q: How to call the overloaded aligned new and delete operators in `C++17`? From cppreference we can see several new overloads of new and delete, as well as new[] and delete[] were added. I can't find any examples of usage with the new aligned overloads, neither on cppreference nor anywhere else. I've experimented with them for quite some time now and I can't find out how to trigger these aligned dynamically allocated calls. Anyone has any idea, kindly share an example.

A: You need to specify the align as keyword on your type and then just call new and delete as normal.  I have put together an article with examples about it here: https://github.com/Twon/Alignment/blob/master/docs/alignment_in_C%2B%2B.md.  An example is:
#include <memory>

int main() {
    class alignas(16) float4 {
        float f[4];
    };

    std::unique_ptr<float4 > aligned_vec4(std::make_unique<float4 >());
}

And an example with the Intel compiler which currently make this feature available via the aligned_new extension header: https://software.intel.com/en-us/articles/aligned-operator-new-support-in-intel-c-compiler

A: I guess the question was how to call an overloaded new explicitly, whereas all answers so far advised how to do it implicitly.
My solution (floats aligned to 256-byte boundaries):
auto q = new (std::align_val_t(256)) float;
auto p = new (std::align_val_t(256)) float[10];

Explanation
We go to https://en.cppreference.com/w/cpp/language/new ("new expression') and navigate to section "Placement new":

If placement_params are provided, they are passed to the allocation function as additional arguments

That's it!
Well, almost. Here: https://en.cppreference.com/w/cpp/memory/new/operator_new we read:

These allocation functions are called by new-expressions to allocate memory in which new object would then be initialized. They may also be called using regular function call syntax.

I was intrigued by the possibility of calling operator new using function call syntax. I don't think anyone does it like this. Let's try:
auto r = operator new (sizeof(float), std::align_val_t(256));
auto s = operator new[] (sizeof(float)*10, std::align_val_t(256)); // don't do it!!!

Ugly and dangerous, especially in the array-like version, as it does not have a place for the argument corresponding to the number of requested elements --  all it needs is the number of bytes to allocate, which may require taking into account some alignment overhead.

A: It's on cppreference, just buried a few links deep:
https://en.cppreference.com/w/cpp/language/new
new(2,f) T; // calls operator new(sizeof(T), 2, f)
        // (C++17) or operator new(sizeof(T), std::align_val_t(alignof(T)), 2, f)

More information on it:
https://www.bfilipek.com/2017/06/cpp17-details-clarifications.html
Looks like you actually use the alignas keyword and it will automatically call the new new.


text:
Q: How can I hide/show an element when a button is pressed? I'm trying to learn how to develop Android using the Eclipse IDE. What I'm trying to do right now is make a hidden TableLayout visible when a button is pressed. However, I have no idea as to what I need to put in the button's OnClick property.
Also, are there any tutorials online that could help me learn how to develop Android apps in Eclipse?
Thanks!

A: Try:
TableLayout table;
Button button;
table = (TableLayout) findViewById (R.id.tablelayout1);
button = (Button) findViewById(R.id.button1);

button.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {

        // View list = (View)findViewById(R.id.myviewId);
        tbleview.setVisibility(View.INVISIBLE);

    }
});

Hope this works.

A: well just take the reference of the TableLayout by using findViewById(int) in the onClickListener(). once you have the object of TableLayout, call setVisibility(View.VISIBLE)

A: TableLayout tl = (TableLayout)findeViewById(R.id.yourtablelayout);

tl.setVisibility(View.VISIBLE);

Something like that within your onClick() method should do the trick.

A: Try this in MainActivity class :
  TextView textview;

/* onClick method of show button */
  public void show(View view){
    textview.setVisibility(View.VISIBLE);

}

/* onClick method of hide button */
public void hide(View view){
    textview.setVisibility(View.INVISIBLE);
}

and try this in onCreate method :
    textview = (TextView) findViewById(R.id.textview);