text:
Q: How to count how many times a variable is true in an hour/in a day? I am coding a motion detection app with React Native and I would like to count how many times the alarm has been triggered in an hour and in a day.
I get the state of the alarm (true/false) with redux toolkit with
    const alarmValue = useSelector((state) => state.alarm.active);

and want to output the number of times the alarm has been triggered in a text field but I can't figure out how to, especially in an hour or in a day. Any ideas are greatly appreciated!

A:     useEffect(() => {
       // This code will run when the alarm value changes and here you can check if it is changed to true

If (alarmValue) {
// Here you can just Crete a new state variable to store the count and increment it
}
    })

A: Hopefully it helps, but in React.js you could try having an array which keeps a record of the state of alarmValue, and then have another variable which keeps a record of how many times in the last 24 hours has the alarm been triggered:
const [alarmValue, setAlarmValue] = useState(false);
const [timesTriggered, setTimesTriggered] = useState(0);
let alarmArray = [];

Then you will need to use the useEffect hook:
useEffect(() => {
    const appendEveryMinute = setInterval(() => {
        alarmArray.append(alarmValue);
        console.log("This will be called every 60 seconds");
    }, 60000);
    // alternatively you should be able to do 60 * 1000

    const checkTimesTriggered = setInterval(() => {
        for (const alarm of alarmArray) { // for each alarm in the array
            if (alarm) { // if alarm is true
                setTimesTriggered(alarmTriggered + 1); // increment timesTriggered
           }
        }

        console.log("Alarm has been triggered " + timesTriggered + " times");

        setTimesTriggered(0)
        // we reset timesTriggered so it will recalculate every hour

        console.log("This will be called every hour");
    }, 3600000); // alternatively you should be able to do 3600 * 1000

    return () => {
        clearInterval(appendEveryMinute);
        clearInterval(checkTimesTriggered);
    };
});

Maybe this will give you a good start.


text:
Q: pip install conda==4.2.7 gives error on Command "python setup.py egg_info" failed with error code 1 Python version : Python 3.6.5
pip version : pip 9.0.1
Please help in installing coda using pip.
Is this the best practice ?
pip install conda gave me this error :
Collecting menuinst (from conda)
  Could not find a version that satisfies the requirement menuinst (from conda) (from versions: )
so according to forums i tried to resolve it using:
pip install conda==4.2.7
which resulted into following error:
Collecting conda==4.2.7
  Using cached https://files.pythonhosted.org/packages/76/7c/374bc72a16f71b51aaad570192438b9752604121dfea4cb0abc5d0b2c2ca/conda-4.2.7.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "", line 1, in
      File "C:\Users\P2858687\AppData\Local\Temp\pip-build-vh2vzjt0\conda\setup.py", line 32, in
        from conda._vendor.auxlib import packaging  # NOQA
    ModuleNotFoundError: No module named 'auxlib'
----------------------------------------

Command "python setup.py egg_info" failed with error code 1 in C:\Users\P2858687\AppData\Local\Temp\pip-build-vh2vzjt0\conda\
You are using pip version 9.0.1, however version 20.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

redpajama_set_name: RedPajamaStackExchange


text:
Q: make textbox axquire fullwidth using flexlayout angular enter code hereenter image description hereI am new designing with angularflex , I want to make the third field in popup to acquire maxwidth using flexdesigning not with standard css width property ,can anyone help me
enter image description here
popup works!

                        {{validationErrors.getError(form.controls['Description'])}}

                        {{validationErrors.getError(form.controls['Description'])}}

                    {{validationErrors.getError(form.controls['Description'])}}

        Submit
          Close

A: The issue is not with flex (your container is probably full width), but with the control itself. Its css does not instruct it to take all the available space.
So you have to put width: 100% in the css code for your control.


text:
Q: I want Prometheus metrics in a file instead of prometheus UI
I installed prometheus in kubernetes and its working fine.
But actually i want all metrics in a file instead of Prometheus UI.
please help me;


text:
Q: google map with route in blackberry how to use google map with route in blackberry . i tried blackberry map with route but in my device (Storm 2) cant display map .  i dont know what is the issue ?
any one have idea ragarding google map in blackberry application  than let me know.
i tried this http://maps.google.com/maps?saddr=23.4444,72.44445&daddr=23.55555,72.55555
and open this url in BB browser but it cant redirect to map site .
how can we handle google map or blackberry map with route in BB application ?

A: i have implemented Google Map with route in Blackberry via Google Map Installed App.
   public void invokeGoogleMap() {
     int mh = CodeModuleManager.getModuleHandle("GoogleMaps");
     if (mh == 0)
     {
          try
          {
            throw new ApplicationManagerException("GoogleMaps isn't installed");
          }
          catch (ApplicationManagerException e)
          {
            System.out.println(e.getMessage());
          }
          UiApplication.getUiApplication().invokeLater(new Runnable() {
            public void run() {
              stubDialog.inform("GoogleMaps isn't installed on your device.download it from m.google.com/maps.");
            }
          });
     }
     else
     {
         URLEncodedPostData uepd = new URLEncodedPostData(null, false);
         uepd.append("action", "ROUT"); // or LOCN
         uepd.append("start", "23.039568,72.566005");
         uepd.append("end", "23.02,73.07");
         String[] args = { "http://gmm/x?" + uepd.toString() };
         ApplicationDescriptor ad = CodeModuleManager.getApplicationDescriptors(mh)[0];
         ApplicationDescriptor ad2 = new ApplicationDescriptor(ad, args);
         try
         {
             ApplicationManager.getApplicationManager().runApplication(ad2, true);
         }
         catch (ApplicationManagerException e)
         {
             System.out.println(e.getMessage());
         }

     }
  }

A: Blackberry browser is not fully functional for java script to display route info in browser field.Instead you have to use Blackberry maps. for this the following link will help you.
How to find the route between two places in BlackBerry?


text:
Q: How to deploy local MySQL database to Heroku I'm new to using Heroku and I have a Ruby/Sinatra app in which I plan on using a MySQL database as the main data store.
However, I do not want to write results directly to the database on Heroku. Instead, I want to write the results to a local database, and then be able to easily deploy/update/copy my local DB to the "production" database on Heroku.
How do I do this?
Thanks.

A: Firstly Heroku natively uses postgres. Life will be easier for you if you use that locally.
You can import / export postgres dump files from heroku as described here: https://devcenter.heroku.com/articles/heroku-postgres-import-export
If you really want to use mysql, you have two paths to follow.
1) Run mysql locally, but convert to postgres when migrating to Heroku using the mysql2psql gem, as described here: https://devcenter.heroku.com/articles/heroku-mysql
2) Use a mysql addon like https://addons.heroku.com/cleardb
However my recommendation would be to use postgres end to end, as it is baked into Heroku, and you'll be working with the default ways of using Heroku, not against them.
Postgres is very good too!

A: I know nothing about Ruby & Sinatra, so feel free to comment and let me know how wrong I am if that's the case. However, I thought it might be pertinent to mention the JawsDB Plugin on Heroku, as the top answer here is from 2013 and may be a bit outdated.
Here is a link with info on the JawsDB plugin:
https://devcenter.heroku.com/articles/jawsdb
Provisioning the plugin is as simple as running the following command in the CLI:
heroku addons:create jawsdb

Then configure the host, username, password, & database with parameters from MySQL Workbench (or whatever GUI you use).

A: I wrote a short article
https://medium.com/@michaeltendossemwanga/import-mysql-database-to-heroku-with-one-command-import-db-sql-a932d720c82b
Here is a batch script to fasten the process
https://gist.github.com/MichaelTendoSsemwanga/f013963092e3abcce801834871d14b03
Save this batch script as import.bat
@echo off
heroku config | findstr CLEARDB > config.txt
set /p url=<config.txt

set "string=%url:?=" & set "x=%"
set "x=%string:/=" & set "dbname=%"
echo DB name:   %dbname%
echo DB name:   %dbname% >> config.txt

set "x=%string:@=" & set "substring=%"
set "host=%substring:/=" & set "x=%"
echo Host:      %host%
echo Host:      %host% >> config.txt

set "x=%string::=" & set "substring=%"
set "password=%substring:@=" & set "x=%"
echo Password:  %password%
echo Password:  %password% >> config.txt

set "x=%string:://=" & set "substring=%"
set "user=%substring::=" & set "x=%"
echo User:      %user%
echo User:      %user% >> config.txt

mysql -u %user% -p%password% -h %host% -D %dbname%  < %1

In the heroku app directory, run
import db.sql

Command line output


text:
Q: Caroufredsel showing partial images My caroufredsel carousel is showing 8 images at a time and then sliding across the screen to show another 8. However, for the first four times the carousel slides, a partial image on the right shows instead of a complete image. After four slides, the carousel snaps to where it is supposed to be and show all images correctly from then on. Am I doing something wrong? Is there a setting I need to use that I've missed?
Here is the link.
http://dev.mattresstime.co.uk/cheapbeds/mattresstime/index.php
This is the jQuery
$j("#manufacturer_list").carouFredSel({
    width:904,
    height: 81,
    items: {
        visible: 8,
        minimum: 1,
        width: 113,
        height: 81
    },
    scroll: {
        pauseOnHover: true
    },
    swipe: {
        onTouch  : true,
        onMouse  : true
    },
    prev : "#prev_button",
    next : "#next_button"
});


text:
Q: Make pyinotify daemon die after a certain amount of time I have a process which is writing .txt files to a directory. I use pyinotify to monitor the directory and count the number of files written the directory. There is a max number of txt files that will be written. After this limit is reached, the pyinotify process dies gracefully.
Now in case the file writing process fails and dies, and the number of files never reaches the limit, I want the pyinotify process to die after running for 1200 seconds. For this, I am setting up the notifier using the following statmeent
notifier = pyinotify.Notifier(wm,handler,0,0,1200)
now the 1200 here is the is the value of the timeout. In the pyinotify code the init function for the Notifier is as follows
def init(self, watch_manager, default_proc_fun=None, read_freq=0,
                 threshold=0, timeout=None):
I would like 1200 to be the timeout value. Unfortunately the process continues to run past 1200 seconds. Is there something I am doing wrong.
Please help.

A: So the 1200 there is the polling interval in msec : Polling Objects
It is not the amount of time the daemon will run for. I still need an elegant fix to this. I am thinking I will change the code of pyinotify to add this functionality.


text:
Q: Chrome CSS bug: image elements not showing up I'm having a CSS problem in Chrome (build: 17.0.9) with an image element that is not showing up. Please take a look at this link: http://next.lab501.ro/smartphone/nokia-n9-meego-to-go/3
In the top-right part of the main body you should see a list of pages with two image arrows acting as next and previous links. In Chrome only the next image arrow appears.
In any other browser (Firefox, IE9) everything shows up OK. What am I doing wrong?

A: You have to give .prev - float left [it will automatically make the element block].  is an inline element -> width, height, padding [top, bottom], margin[top, bottom] etc.. will not get applied unless its a block level element.

A: If you set float:left in your .prev element, it shows up, but you have to lower the right padding so it gets closer to the numbers.

A: In http://next.lab501.ro/wp-content/themes/new-theme/style.css, it says:
.prev {
background: url(img/nav-left.png) no-repeat scroll 0 0 transparent;
padding: 3px 12px 5px;
margin-right: 2px;
width: 23px;
height: 22px;
}

Add a float: left; to the end of that. I would also change the padding on the right side to move it closer to the numbers. I changed it to 0 in this case. The code now looks like this:
.prev {
background: url(img/nav-left.png) no-repeat scroll 0 0 transparent;
padding: 3px 0 5px;
margin-right: 2px;
width: 23px;
height: 22px;
float: left;
}


text:
Q: Not able to understand this SQL query This is a solution of one of the SQL problem on Hacerrank but I am not able to understand how this query works as I am new to this field. Can anyone explain this or give me link for good tutorials where I can learn this type of complex queries.
SET @d=0,@a=0,@p=0,@s=0;
SELECT MIN(Doctor),MIN(Professor),MIN(SINGER),MIN(Actor)
FROM
(SELECT IF(OCCUPATION='Actor',NAME,NULL) AS Actor,
        IF(OCCUPATION='Doctor',NAME,NULL) AS Doctor,
        IF(OCCUPATION='Professor',NAME,NULL) AS Professor,
        IF(OCCUPATION='Singer',NAME,NULL) AS SINGER,
    case OCCUPATION when 'ACTOR' THEN @a:=@a+1
                    when 'Doctor' THEN @d:=@d+1
                    when 'Professor' THEN @p:=@p+1
                    when 'Singer' THEN @s:=@s+1
    end
as idn FROM OCCUPATIONS ORDER BY NAME ) AS TMP GROUP BY TMP.idn ;

A: Splitting this up into sections
SET @d=0,@a=0,@p=0,@s=0;

This sets up 4 user variables, initialising them each to 0.
SELECT IF(OCCUPATION='Actor',NAME,NULL) AS Actor,
        IF(OCCUPATION='Doctor',NAME,NULL) AS Doctor,
        IF(OCCUPATION='Professor',NAME,NULL) AS Professor,
        IF(OCCUPATION='Singer',NAME,NULL) AS SINGER,
    case OCCUPATION when 'ACTOR' THEN @a:=@a+1
                    when 'Doctor' THEN @d:=@d+1
                    when 'Professor' THEN @p:=@p+1
                    when 'Singer' THEN @s:=@s+1
    end
as idn
FROM OCCUPATIONS
ORDER BY NAME

This is returning 5 columns. The first 4 columns return a name for that row if that row refers to a particular occupation. So if the occupation for that row is 'Doctor' then the 2nd column will contain the contents of the name field, while columns 1, 3 and 4 will be NULL.
The 5th column calculates the count of that occupation. This may or may not be done in the order of the names (where MySQL chooses to assign the values to the user variables is not defined) - it may well work now but maybe not in the future. But essentially if will contain a sequential count of the number of that occupation, with the first of that occupation containing 1 and the next 2, etc.
SELECT MIN(Doctor),MIN(Professor),MIN(SINGER),MIN(Actor)
FROM
(.....) AS TMP GROUP BY TMP.idn ;

This is taking the results of the earlier SELECT (used as a sub query) and GROUPing the result by the count. So for each count value (which will occur up to 4 times, once for each occupation) it will return the MIN (so first alphabetically) name for each occupation. The MIN aggregate function ignores NULL values normally, so will return the first used name.
Working that through with some dummy data. Using the following as an example:-
id  Name    Occupation
1   freda   Actor
2   fredb   Doctor
3   fredc   Professor
4   fredd   Actor
5   frede   Doctor
6   fredf   Actor
7   fredg   Professor
9   fredh   Singer
10  fredi   Actor
11  fredj   Doctor
12  fredk   Professor
13  fredl   Actor
14  fredm   Doctor
15  fredn   Professor
16  fredo   Professor
17  fredp   Singer
19  fredq   Doctor
20  fredr   Actor

The sub query gives:-
Actor   Doctor  Professor   Singer  idn
freda   NULL    NULL        NULL    1
NULL    fredb   NULL        NULL    1
NULL    NULL    fredc       NULL    1
fredd   NULL    NULL        NULL    2
NULL    frede   NULL        NULL    2
fredf   NULL    NULL        NULL    3
NULL    NULL    fredg       NULL    2
NULL    NULL    NULL        fredh   1
fredi   NULL    NULL        NULL    4
NULL    fredj   NULL        NULL    3
NULL    NULL    fredk       NULL    3
fredl   NULL    NULL        NULL    5
NULL    fredm   NULL        NULL    4
NULL    NULL    fredn       NULL    4
NULL    NULL    fredo       NULL    5
NULL    NULL    NULL        fredp   2
NULL    fredq   NULL        NULL    5
fredr   NULL    NULL        NULL    6

The outer query acts on this, giving one row per used count (ie, the number of rows will be the same as the max number of a occupation, whichever occupation has the most), and the name of the person for that occupation for that count:-
Doctor  Professor   Singer  Actor
fredb   fredc       fredh   freda
frede   fredg       fredp   fredd
fredj   fredk       NULL    fredf
fredm   fredn       NULL    fredi
fredq   fredo       NULL    fredl
NULL    NULL        NULL    fredr


text:
Q: Do users need the same software needed to develop the program? When I Make/Compile/Build a project, and then test it on someone else's computer, will all the items that I installed on my computer need to also be installed on the other persons computer as well? For example, I might be using GPU processing in my application, and for it to work on my computer I needed to download an Nvidia piece of software that was almost 1GB in size. The user that uses my application won't need to download that software will they? Here is the software that I needed to download: https://developer.nvidia.com/cuda-downloads
So will the end user need to have that installed as well? What if the end user doesn't have an Nvidia graphics card will the application still work?

A: Yes they need an Nvidia graphics card if you want to use cuda, as well as the software.
Also see: https://stackoverflow.com/questions/9022171/cuda-and-ati-graphic-card


text:
Q: Single predicate to test for "self-evaluating" atoms in Clojure At the home site of Clojure, there is the following statement:

Strings, numbers, characters, true,
  false, nil and keywords evaluate to
  themselves.

Is there a single combined predicate that tests for any of these, combining string?, number?, char?, true?, false?, nil?, and keyword?. Should I just use (complement symbol?)?

A: Maybe I'm missing something, but you could use the following to test for any of those conditions and return true if one is true:
(defn self-eval?
  [x]
  (or (string? x)
      (number? x)
      (char? x)
      (keyword? x)
      (true? x)
      (false? x)
      (nil? x)))

A: It's easy enough to write a macro that asks "does the given expression evaluate to itself". In fact this is a good example of tasks that can only be done with a macro because they need to see the argument both evaluated and unevaluated.
(defmacro selfp [a] `(= ~a (quote ~a)))
#'user/selfp
user> (selfp 1)
true
user> (selfp +)
false
user> (selfp [1 2])
true
user> (selfp '(+ 1 2 3))
false

While strings, numbers, characters, keywords, and the booleans are all self-evaluating, other things such as [1 2] are as well,so this may not be a useful test in general.

A: Another option is to create a function that uses a map:
(defn myclassifier? [x]
   (let [types-I-care-about #{java.lang.Sring ...}]
      (if (types-I-care-about (type x))
          true
          false)))

Another option which may have better performance is to use java's dynamism:
(extend-type Object
  IMyClassifier
  (myclassifier? [x]
            (let [c (.getClass x)]
             (if (types-I-care-about (type c))
               (do
                 (extend-type (.getClass x)
                   IMyClassifier
                   (myclassifier? [x] true))
                 true)
               false))))

where types-I-care-about is a set of types you care about.


text:
Q: Is there a way to get a non-null Principal/Authentication using Spring Security with anonymous access? I'm using Spring Security, and want to be able to run with a "local" profile with security off. I can do this by using a profile-controlled WebSecurityConfigurerAdapter which allows anonymous access, but the problem is that any Principal or Authentication arguments to controller methods are null.
The way I've solved this before is by passing the arguments through an adapter, which has a non-local pass-through implementation and a "local"-profile implementation that substitutes a configured value:
    @GetMapping()
    public ResponseEntity<List<Thing>> getThings(Principal principal) {

        Principal myPrincipal = securityAdapter.principal(principal);

        ...
    }

But this feels really clunky. Is there some way to configure Spring Security to make the substitution so that I can keep the code clean?

A: Unfortunately it is a SpringSecurity feature: the AnonymousAuthenticationToken is not injected in controller methods. I could find some references for that in this issue.
A possible workaround (from above issue) is to inject a custom trust resolver that pretends that the AnonymousAuthenticationToken is not anonymous...
@Bean
public AuthenticationTrustResolver trustResolver() {
    return new AuthenticationTrustResolver() {

        @Override
        public boolean isRememberMe(final Authentication authentication) {
            return false;
        }

        @Override
        public boolean isAnonymous(final Authentication authentication) {
            return false;
        }
    };
}

Rather ugly, but as it is intended to run in a profile where anonymous authentication is expected to be valid, it could be enough.


text:
Q: Jackson Java to JSON object mapper modifies field's name Using Jackson to convert a Java object to JSON
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
jsonMessage = mapper.writeValueAsString(object);

the result is that the field "participants" (which is part of the object instance)
participants    Arrays$ArrayList<E>

gets renamed to "participantsList"
participantsList":[{"userId":"c1f9c"}]

i.e. "List" is appended to the field name. I went through the Jackson documentation but haven't found a way to prevent this from happening. Is this possible? Testing the above code in a standalone project does not cause the same result (i.e. no renaming takes place). Why is Jackson behaving like this? Unfortunately, the object is third party and I cannot change it.
Using Jackson version 2.3.3 (same behaviour verified with 2.9.0).

A: Oleksandr's comment pointed in the right direction. Indeed there is a getParticipantsList() that Jackson seems to take into account when determining the JSON field name. However, as I wrote before, I am not able to make any changes there, considering it is a third party object.
But, with a better understanding of what causes the problem, I was able to come up with a solution:
mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.ANY).withGetterVisibility(Visibility.NONE).withIsGetterVisibility(Visibility.NONE));

or
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
mapper.setVisibility(PropertyAccessor.GETTER, Visibility.NONE);
mapper.setVisibility(PropertyAccessor.IS_GETTER, Visibility.NONE);

A: Maybe you can use USE_ANNOTATIONS to skip annotations like this:
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.configure(MapperFeature.USE_ANNOTATIONS, false);
    String jsonMessage = mapper.writeValueAsString(object);


text:
Q: Uncaught reference error prompt Estoy poniendo un código y no sale el prompt, asi que lo pongo en la consola y me salta un error, que esta pasando?
var pregunta = propmt("Pregunta")

A: El error

Uncaught ReferenceError: propmt is not defined

es debido a que has escrito mal el método, lo correcto sería:
var pregunta = prompt("pregunta")
Espero que te sirva!


text:
Q: I cant find the source of my code printing 'none' So I wrote this code and it works, however, I'm trying to find a way to make this code return the right output, as shown down below. Here is my code.
upto = 5
def original_num(upto:int):
    for x in range(1, upto+1):
        print (x, (7**x)%97)
def powerLoop(upto: int):
    upto = upto
    return original_num(upto)
print(powerLoop(upto))

But when I print the output, this is what I get...
1 7
2 49
3 52
4 73
5 26
None

But if I use print instead of return in the code,
upto = 5
def powerLoop(upto:int):
    for x in range(1, upto+1):
        print(x, (7**x)%97)
powerLoop(upto)

This is what I get,
1 7
2 49
3 52
4 73
5 26

How can I use return and then once I say print(powerloop(upto) the output will occur without printing 'none'?

A: Your original_num(...) function already prints the desired output and returns None which you ultimately print in print(powerLoop(upto)).
Just:
powerLoop(upto)

will not print the return value, but still "harvest" the side-effects of the function calls (the other prints).

A: If you want to write print(powerLoop(upto)) and don't get None you can use yield like below:
>>> upto = 5
>>> def powerLoop(upto:int):
...    for x in range(1, upto+1):
...        yield (x, (7**x)%97)
>>> print(*powerLoop(upto), sep='\n')
(1, 7)
(2, 49)
(3, 52)
(4, 73)
(5, 26)

>>> for ret in powerLoop(upto):
...    print(*ret)
1 7
2 49
3 52
4 73
5 26

If you want to use return you can use list and return list like below: (Edit answer base comment)
>>> upto = 5
>>> def powerLoop(upto:int):
...    out = []
...    for x in range(1, upto+1):
...        out.append([x, (7**x)%97])
...    return out

>>> print(*powerLoop(upto), sep='\n')
[1, 7]
[2, 49]
[3, 52]
[4, 73]
[5, 26]

>>> for ret in powerLoop(upto):
...    print(*ret)

1 7
2 49
3 52
4 73
5 26

A: Why you print again?
upto = 5
def original_num(upto:int):
    for x in range(1, upto+1):
        print (x, (7**x)%97)
def powerLoop(upto: int):
    return original_num(upto)

powerLoop(upto)

above, the last line, just cancel print, because your function original_num had already print the result.
and in python, if your function have nothing to return, it will return None, and then you print None.
def abc():
    a=100

print(abc())

above example will get None.


text:
Q: Calling an assembly function from another file I have the following code to compute square of a number which works perfectly:
        .section .data

        .section .text

        .globl _start
        .globl square

_start:
        pushl $10

        call square
        addl $4, %esp

        movl %eax, %ebx
        movl $1, %eax
        int $0x80

        .type square,@function

square:
        pushl %ebp
        movl %esp, %ebp
        movl 8(%ebp), %eax

        imull %eax, %eax

end_square:
        movl %ebp, %esp
        popl %ebp
        ret

I want to call the function square from another file named square_test.s. This is my attempt:
        .section .data

        .section .text

        .globl _start

_start:

        pushl $12
        call square
        addl $4, %esp

        movl %eax, %ebx
        movl $1, %eax
        int $0x80

But when linking it throws me this error:
$ as --32 square_test.s -o square_test.o
$ as --32 square.s -o square.o
$ ld -m elf_i386 square.o square_test.o -o square_test
square_test.o: In function `_start':
(.text+0x0): multiple definition of `_start'
square.o:(.text+0x0): first defined here

How should I fix this ?

A: You have two global symbols named "_start" (one in each file).  If you want to link the files together, you'll have to rename one of them to something other than "_start", or make one of them non-global (remove the .globl directive).

A: Thanks to the above comments, finally I made it work. These are the two files:
# file name: isolated_square.s

        .section .data

        .section .text

        .globl square

        .type square,@function

square:
        pushl %ebp
        movl %esp, %ebp
        movl 8(%ebp), %eax

        imull %eax, %eax

end_square:
        movl %ebp, %esp
        popl %ebp
        ret

And this is the other file:
        # file name: square_test.s
        .section .data

        .section .text

        .globl _start

_start:

        pushl $12
        call square
        addl $4, %esp

        movl %eax, %ebx
        movl $1, %eax
        int $0x80

And this is how you need to execute it:
$ as --32 isolated_square.s -o isolated_square.o
$ as --32 square_test.s -o square_test.o
$ ld -m elf_i386 isolated_square.o square_test.o -o square_test
$ ./square_test
$ echo $?
144


text:
Q: Start doxygen list at zero I am using doxygen and would like to create a zero-based list
I have tried:

 ...

and
0. 0-item
1. 1-item ...

with no luck... is there another way I can try?
Update: just noticed the first method works in the HTML output, but it is the LaTeX I am concerned with, and that doesnt work...

A: If you really need a zero numbered list, you could try
Zero list
\zerolist
\zeroitem{Zero}
\zeroitem{One}
\zeroitem{Two}
\endzerolist

in combination with the following alias definitions in the config file:
ALIASES                = zerolist="\latexonly\begin{enumerate}\setcounter{enumi}{-1}\endlatexonly\htmlonly
\endhtmlonly" \
                         zeroitem{1}="\latexonly\item \1\endlatexonly\htmlonly
\1
\endhtmlonly" \
                         endzerolist="\latexonly\end{enumerate}\endlatexonly\htmlonly
\endhtmlonly"

which works for the HTML and the LaTeX output.


text:
Q: Error: Can't resolve all parameters for (?, ?) I have written the following unit test for my Angular 10 component, which basically displays a tree view with some interactivity:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';
// import { MatFormFieldModule } from '@angular/material/form-field';
// import { MatInputModule } from '@angular/material/input';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { BrowserModule } from '@angular/platform-browser';
import { TreeviewModule } from 'ngx-treeview';
import { DocumentTreeService } from '../services/DocumentTreeService';

import { DocumentTreeviewComponent } from './document-treeview.component';

describe('DocumentTreeviewComponent', () => {
  let component: DocumentTreeviewComponent;
  let fixture: ComponentFixture<DocumentTreeviewComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ DocumentTreeviewComponent ],
      imports: [ TreeviewModule.forRoot(), ReactiveFormsModule, MatProgressBarModule,
         BrowserModule, MatProgressSpinnerModule, /* MatFormFieldModule, MatInputModule */ ],
      providers: [ DocumentTreeService ]
    })
    .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(DocumentTreeviewComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

My DocumentTreeService.ts:
import { HttpClient } from '@angular/common/http';
import { TreeviewItem } from 'ngx-treeview';
import { GlobalDataService } from './global-data.service';

interface TreeItem {
  name?: string;
  text: string;
  value: any;
  children?: String[];
  type: 'folder' | 'document';
}

/* tslint:disable no-string-literal prefer-for-of */
export class DocumentTreeService {

  constructor(public http: HttpClient, public DataService: GlobalDataService){}
  public treeviewmtextresponse;
  public docNames = [];

  public FolderItems = [];
  public treeviewItem = [];
  public finalTreeviewElements: TreeviewItem[] = [];

  getDocItems(): TreeviewItem[] {
    const docItems = [];

    // TEMPORARY SOLUTION (QUICKFIX) FOR 1 DOC
    if (!this.treeviewmtextresponse.length) {
      const element = this.treeviewmtextresponse['documentName'];
      this.docNames.push(element);
      const tempArray = element.split('!');
      if (!this.FolderItems.includes(tempArray[0])) {
        this.FolderItems.push(tempArray[0])
      }

      docItems[tempArray[0]] = this.docNames.filter(s => s.includes(tempArray[0] + '!'));
      for (let o = 0; o < docItems[tempArray[0]].length; o++) {
        docItems[tempArray[0]][o] = docItems[tempArray[0]][o].replace(tempArray[0] + '!', '');
        const documentItem: TreeItem = {
          text: docItems[tempArray[0]][o],
          type: 'document',
          value: docItems[tempArray[0]][o],
        }
        docItems[tempArray[0]][o] = documentItem;
      }
    }
    // TEMPORARY SOLUTION (QUICKFIX) FOR 1 DOC

    for (let m = 0; m < this.treeviewmtextresponse.length; m++) {
      const element = this.treeviewmtextresponse[m]['documentName'];
      this.docNames.push(element);
      const tempArray = element.split('!');
      if (!this.FolderItems.includes(tempArray[0])) {
        this.FolderItems.push(tempArray[0])
      }

      docItems[tempArray[0]] = this.docNames.filter(s => s.includes(tempArray[0] + '!'));
      for (let o = 0; o < docItems[tempArray[0]].length; o++) {
        docItems[tempArray[0]][o] = docItems[tempArray[0]][o].replace(tempArray[0] + '!', '');
        const documentItem: TreeItem = {
          text: docItems[tempArray[0]][o],
          type: 'document',
          value: docItems[tempArray[0]][o],
        }
        docItems[tempArray[0]][o] = documentItem;
      }
    }

    let jsonString;
    for (let p = 0; p < this.FolderItems.length; p++) {
      const element = this.FolderItems[p];
      const treeItem: TreeItem = {
        name: element + "!" + docItems[element][0]["text"],
        text: element,
        value: element,
        type: 'folder',
        children: docItems[element],
      }
      const DokData = treeItem["name"];
      this.DataService.SelectedDocumentList.push(DokData);

      jsonString = JSON.stringify(treeItem);
      const finalObject: TreeviewItem = new TreeviewItem(
        JSON.parse(jsonString));
      this.finalTreeviewElements.push(finalObject);
    }
    return this.finalTreeviewElements;
    }
}

My full error message:
Error: Can't resolve all parameters for DocumentTreeService: (?, ?).

I originally thought I messed up with placing the service in the correct category but with trial and error and some logic I determined it was set correctly. What's causing this issue?

Update 1
My current codebase looks like this:
 beforeEach(async () => {
    const httpSpy = jasmine.createSpyObj('HttpClient', ['get']); //funcName for any function name that you need to exist on the spy objects
    const dataSpy = jasmine.createSpyObj('GlobalDataService', ['funcName']);
    await TestBed.configureTestingModule({
      declarations: [ DocumentTreeviewComponent ],
      imports: [ TreeviewModule.forRoot(), ReactiveFormsModule, MatProgressBarModule,
         BrowserModule, MatProgressSpinnerModule, HttpClientTestingModule, MatDialogModule, MatInputModule
         /* MatFormFieldModule, MatInputModule */ ],
      providers: [ GlobalDataService, DatePipe,
        { provide: DocumentTreeService, useValue: mockDocumentTreeService },
        { provide: HttpClient, useValue: httpSpy },
        { provide: GlobalDataService, useValue: dataSpy }] // modify this line to provide a mock
    })
    .compileComponents();
       // To access the service from your tests
    documentTreeService = TestBed.inject(DocumentTreeService);
  });

Update 2
the document-treeview.component.ts:
import { Component, OnInit } from '@angular/core';
import { TreeviewItem, TreeviewConfig } from 'ngx-treeview';
import { GlobalDataService } from '../services/global-data.service';
import { DocumentTreeService } from '../services/DocumentTreeService';
import { environment } from 'src/environments/environment';
@Component({
  selector: 'app-document-treeview',
  templateUrl: './document-treeview.component.html',
  styleUrls: ['./document-treeview.component.scss']
})

export class DocumentTreeviewComponent implements OnInit {
  dropdownEnabled = false;
  items: TreeviewItem[];
  values: number[];
  config = TreeviewConfig.create({
    hasAllCheckBox: false,
    hasFilter: true,
    hasCollapseExpand: true,
    maxHeight: 435
  });

  constructor(public service: DocumentTreeService, public DataService: GlobalDataService) {
    this.getDocumentList(false);
   }

  public docAmount;

  ngOnInit(): void {
    setInterval(()  => {
      if (!this.items && this.service.treeviewmtextresponse) {
        if (this.service.finalTreeviewElements.length !== 0) {
          this.items = this.service.finalTreeviewElements;
        } else {
            this.items = this.service.getDocItems();
        }
      }
      if (this.DataService.newDocumentAdded === true || this.DataService.documentDeleted === true) {
        this.resetDocuments();
        if (this.service.treeviewmtextresponse.length > this.docAmount && this.DataService.newDocumentAdded === true || this.service.treeviewmtextresponse.length < this.docAmount && this.DataService.documentDeleted === true) {
          this.DataService.newDocumentAdded = false;
          this.DataService.documentDeleted = false;
          this.docAmount = this.service.treeviewmtextresponse.length;
        }
      }
    }, 1000);
  }

  public resetDocuments() {
    setTimeout(() => {
      // reset treeview arrays
      this.items = null;
      this.service.docNames = [];
      this.service.FolderItems = [];
      this.service.treeviewItem = [];
      this.service.finalTreeviewElements = [];
      // reset treeviewmtextresponse
      this.service.treeviewmtextresponse = null;
      this.getDocumentList(true);
  }, 1000);
  }

  onFilterChange(value: string): void {
    console.log('filter:', value);
  }

  public getFolderName(event) {
    // irrelevant for the unit test
  }

  openTonicUrl(event){
    // this.openDialog(event);
    if (this.DataService.SelectedDocumentName) {
      window.open(`${environment.APIUrl}/text/gui/open/%5Chome%5Ctestproject%5C` + this.DataService.SelectedDocumentName, '_blank');
    }
  }

  public getDocumentList(refresh: boolean) {
    return this.service.http.get(this.DataService.getDocumentUrl, this.DataService.httpOptions)
    .subscribe(
      documentResponse => {
        this.service.treeviewmtextresponse = documentResponse['soap:Envelope']['soap:Body'][
          'ns2:getDocumentsResponse'
        ]['return'];
        if (refresh === false) {
          this.docAmount = this.service.treeviewmtextresponse.length;
        }
        this.DataService.documentListLoaded = true;
       },
       error => {

        console.log('There was an error: ', error);
      });
  }
}

A: Your DocumentTreeService is using HttpClient and GlobalDataService and you're not providing them in the TestBed module. I would mock the DocumentTreeService and not provide the actual service when testing the component.
describe('DocumentTreeviewComponent', () => {
  let component: DocumentTreeviewComponent;
  let fixture: ComponentFixture<DocumentTreeviewComponent>;
  let mockDocumentTreeService = jasmine.createSpyObj('documentTreeService', ['getDocItems']); // add this line, also look into how to mock external dependencies such as a service
// !! Remove the <DocumentTreeService> on the above line !!

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ DocumentTreeviewComponent ],
      imports: [ TreeviewModule.forRoot(), ReactiveFormsModule, MatProgressBarModule,
         BrowserModule, MatProgressSpinnerModule, /* MatFormFieldModule, MatInputModule */ ],
      providers: [{ provide: DocumentTreeService, useValue: mockDocumentTreeService }] // modify this line to provide a mock
    })
    .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(DocumentTreeviewComponent);
    component = fixture.componentInstance;
    mockDocumentTreeService.getDocItems().and.returnValue([]); // we have mocked getDocItems to return an empty array. You can return anything you want for that function.
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

A: A service needs to use @Injectable() decorator for the class.
e.g.
@Injectable({providedIn: 'root'}) //if you want to provide it in a certain module scope. Remove the `providedIn`
export class DocumentTreeService {...

If that doesn't fix it on it's own. The following is another way to inject services that have dependencies.
let documentTreeService: DocumentTreeService;
beforeEach(async () => {
    for any function name that you need to exist on the spy objects
    const dataSpy = jasmine.createSpyObj('GlobalDataService', ['funcName']);
    await TestBed.configureTestingModule({
      //... removed for brevity
      imports: [HttpClientTestingModule, ...],
      providers: [
           DocumentTreeService,
      { provide: GlobalDataService, useValue: dataSpy }
      ]
    })
    .compileComponents();
   //To access the service from your tests
      documentTreeService = TestBed.inject(DocumentTreeService);
  });

A: Since you are writing a unit test, you only want to test the component and not any of its dependencies. Optimally, you can Mock all other components declared, as well as all providers.
A good library for this is ng-mocks. Then, instead of being forced to check your service along with your component, you can just mock it.
providers: [ DocumentTreeService ]

can then be changed to
providers: [ {
    provide: DocumentTreeService ,
    useValue: MockService(DocumentTreeService)
}]

That way you can separate the external service from your component's unit test


text:
Q: Untrustworthy Projects in Visual Studio? When opening a project you may have recently downloaded, Visual Studio 2013 briefly warns you to only open projects from trustworthy sources. What are some of the risks to opening projects? Can a project do any harm to your system before compilation, and what damage is possible? Are there any indicators you should be aware of before actually opening projects from "untrustworthy" sources? (Not that I can think of any)

A: Attack Surface within Visual Studio
There are many attack vectors within Visual Studio. All of them are by design. We developers want complete control over our systems within the build process. Unfortunately, when we say "I want to delete the contents of the cache directory on build", that also means malicious project files can delete just about anything from just about anywhere. Or worse. The compromise is the "Hey. We've given you the keys to the kingdom, but we don't recognize this project. Are you sure you want to open this? We're not responsible if it does something stupid" warning message that you mentioned.
Now consider that many developers run Visual Studio as an administrator.
Here are some of those attack vectors:
Pre- and Post-Build Events
In it's simplest form, untrusted projects could execute a Pre-Build event that would delete files. Or worse. Just about anything can be executed within a Build event. This is the 101 stuff that happens on Compile.
Executions on Project Open
Visual Studio project files are nothing more than big MSBuild configurations. There are a few MSBuild targets that Visual Studio executes when you open a project, all to support the tooling. These targets include Compile, ResolveAssemblyReferences, ResolveCOMReferences, GetFrameworkPaths, and CopyRunEnvironmentFiles. If any of these targets exist, the tasks within them are also executed. Delete files, or worse.
See: 'Design-Time Execution' at http://msdn.microsoft.com/en-us/library/ms171468.aspx
IntelliSense
Part of that tooling mentioned above includes IntelliSense, which executes the Compile task within MSBuild; the CSC/VBC must be executed to get all of the IntelliSense functionality. Because of the nature of IntelliSense, this task is repeatedly executed as you work, rather than the opportunities above that are just run once on open.
See: 'Design-Time IntelliSense' at http://msdn.microsoft.com/en-us/library/ms171468.aspx
Hidden Elsewhere in MSBuild
There is a sea of other routine MSBuild targets that you will manually execute throughout your day, including Build, Rebuild, Test, and Clean. Yes, keep in mind that even clean is a build target, so Clean could delete more than just your old \bin directories.
NuGet
Malicious projects may also expose systems via NuGet. Though Package Restore would not be an issue, the packages.config could specify a different Repository Source. Then, when you install a new package, such as install-package jquery, NuGet will retrieve the jQuery package from the untrusted alternate, rather than from nuget.org. This malicious jQuery package could have all sorts of other 'Goodies' within it that would be executed as a part of the package installation.
This is not a security vulnerability from NuGet, because "you" specified an alternate package source; this is by design, such as Corporations that have their own internal package repository.
What you can do?
At the end of the day, what can you do about this? The answer really is to just not open projects from untrusted sources. The project's packages.config file could be analyzed before you open it, but the big exposure is through MSBuild. Unless you are quite adept at reading through MSBuild schema, I would steer clear.


text:
Q: Matlab how to overcome nchoosek limitation which only allow up to 15 I have some problem in using nchoosek because this function is only practical for situations where v is less than about 15.
C = nchoosek(v, k);

Below is a line of code where I want to include more v but it returned me "Out of memory" error in matlab. This line of code give me different combination of items, it starts with combination of 3 items.
A = [2 1 3];
B = [4 2 1 3 3];
C = [1 3];
D = [3 2 4 2 1 1];
E = [4 1 1];
F = [...];
G = [...];
etc.

combs = arrayfun(@(x) nchoosek({A,B,C,D,E,...},x), 3:numel({A,B,C,D,E,...}), 'Uniform', 0);

I have A, B, C, D, E, ... up to 8000++ of them.
What other methods can I use to solve this issue? as well as prevent run out of memory issue. Thanks.


text:
Q: Keeping track of multiple index in ng-repeat Is there any way to keep multiple index in ng-repeat?
Eg. if having a list of fruits as such:
$scope.fruits = [
  {type: 'apple'},
  {type: 'orange'},
  {type: 'apple'},
  {type: 'banana'},
  {type: 'banana'}
];

In my template I have a ng-repeat going through the fruits.

{{fruit.type}}

Is it possible to keep an index for each fruit type such that I can add that index to the line in the template to get the following result
* apple - number 1
* orange - number 1
* apple - number 2
* banana - number 1
* banana - number 2

I can't see how $index will help me, as it looks at the overall list (right?). I have tried adding a tracking variable in the controller, but this triggers an infinite loop because of how $digest works and it keeps triggering a change.

A: It is option to do this.
use ng-repeat directive:
ng-repeat="(key, value) in fruits"

and you can use it in html:

{{key}}- {{value}}

Remember about not having spaces in this expression since is regexp processed, so
 (key, value ) wouldn't work, but (key, value) would.


text:
Q: Confluence page - get list of editors In Confluence, I'm trying to find (using the Java API) the list of users who have edited a page, and the number of edits, if possible.
Similarly, I want to find the number of watchers a page has.
Does anyone know how to do that?

A: I found that the easiest way to do get the history of page editors is with PageManager's API. Eventually I used a code like this:
Set<ConfluenceUser> users = new HashSet<ConfluenceUser>();
List<VersionHistorySummary> historySummary =   pageManager.getVersionHistorySummaries(page);
for (VersionHistorySummary version : historySummary) {
    users.add(version.getLastModifier());
}
return users.size();


text:
Q: How to manage lifetime of CString in a Vec? Is there a better or more idiomatic way to handle the lifetime of a CString in a Vec other than using into_raw()?
Here's my code:
// This fails because the CString gets dropped and then what is pointed to is invalid and invalidates required_layers
let required_layers: Vec<*const c_char> = vec!(
    CString::new("VK_LAYER_LUNARG_standard_validation").expect("CString err A").as_ptr(),
);

// This works because ss0 stays alive, but is going to be error-prone as dropping ss0 somewhere invalidates required_layers
let ss0 = CString::new("VK_LAYER_LUNARG_standard_validation").expect("CString err A");
let required_layers: Vec<*const c_char> = vec!(
    ss0.as_ptr(),
);

// This works, but now requires from_raw() to retake ownership to avoid leaks
let required_layers: Vec<*const c_char> = vec!(
    CString::new("VK_LAYER_LUNARG_standard_validation").expect("CString err A").into_raw(),
);

A: You can just store the actual CString objects:
let a = vec![
    CString::new("VK_LAYER_LUNARG_standard_validation").expect("CString err A")
];

And if what you actually need is a contiguous array of pointers, perhaps for passing to a C function that is expecting that sort of thing, you can create a second vector holding the pointers from the strings in the first.
let b: Vec<*const c_char> = a.iter().map(|cstr| {
    cstr.as_ptr()
}).collect();

The first vector will outlive the second, and it will properly drop the contained CString objects when it is dropped itself.


text:
Q: How to get the instance of the dialog (like DatePickerDialog, ProgressDialog, TimePickerDialog) after it pop up the precondition: I'm working on the android automated test, so we can not touch the source code of app, but just test it.
the question:
  How to get the instance of the dialog after it pop up?
  After we get the instance of it, it will be so convenient for the further operation, like directly set the value of it, instead of send the key event to the activity so many times.
Thanks.

A: It seems like you're doing "black box testing", which is the domain of such utilities as "Robotium" and "Robolectric". Check them out, they're specifically designed to press buttons, wait for dialogs, accept dialogs and so on.

A: Dollop, where I work, provides a black box, record-and-play-back tool for Android. It is not limited to running against a single application at a time. It's also easy to configure and use, requires no programming, runs against real devices (which do NOT have to be rooted) and automatically saves screenshots as it plays tests.


text:
Q: Wait accurate for 20 millisec I need to execute some function accurate in 20 milliseconds (for RTP packets sending) after some event. I have tried next variants:
std::this_thread::sleep_for(std::chrono::milliseconds(20));
boost::this_thread::sleep_for(std::chrono::milliseconds(20));
Sleep(20);

Also different perversions as:
auto a= GetTickCount();
while ((GetTickCount() - a) < 20) continue;

Also tried micro and nanoseconds.
All this methods have error in range from -6ms to +12ms but its not acceptable. How to make it work right?
My opinion, that +-1ms is acceptable, but no more.
UPDATE1: to measure time passed i use std::chrono::high_resolution_clock::now();

A: Briefly, because of how OS kernels manage time and threads, you won't get accuracy much better with that method.  Also, you can't rely on sleep alone with a static interval or your stream will quickly drift off your intended send clock rate, because the thread could be interrupted or it could be scheduled again well after your sleep time... for this reason you should check the system clock to know how much to sleep for at each iteration (i.e. somewhere between 0ms and 20ms).  Without going into too much detail, this is also why there's a jitter buffer in RTP streams... to account for variations in packet reception (due to network jitter or send jitter).  Because of this, you likely won't need +/-1ms level accuracy anyway.

A: In C we have a nanosleep function in time.h.
The nanosleep() function causes the current thread to be suspended from execution until either the time interval specified by the rqtp argument has elapsed or a signal is delivered to the calling thread and its action is to invoke a signal-catching function or to terminate the process.
This below program sleeps for 20 milli seconds.
int main()
{
   struct timespec tim, tim2;
   tim.tv_sec = 0;
   tim.tv_nsec =20000000;//20 milliseconds converted to nano seconds

   if(nanosleep(&tim , NULL) < 0 )
   {
      printf("Nano sleep system call failed \n");
      return -1;
   }

   printf("Nano sleep successfull \n");
 return 0;
}

A: Using std::chrono::steady_clock, I got about 0.1ms accuracy on windows 7.
That is, simply:
auto a = std::chrono::steady_clock::now();
while ((std::chrono::steady_clock::now() - a) < WAIT_TIME) continue;

This should give you accurate "waiting" (about 0.1ms, as I said), at least. We all know that this kind of waiting is "ugly" and should be avoided, but it's a hack that might still do the trick just fine.
You could use high_resolution_clock, which might give even better accuracy for some systems, but it is not guaranteed not to be adjusted by the OS, and you don't want that. steady_clock is supposed to be guaranteed not to be adjusted, and often has the same accuracy as high_resolution_clock.
As for "sleep()" functions that are very accurate, I don't know. Perhaps someone else knows more about that.


text:
Q: C# ListViewItems is not returning empty I am using this method and it keeps saying listView1 has items even though none appear in the listview?
        private void button8_Click(object sender, EventArgs e)
    {
        string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\test.txt";
        if (Directory.Exists(filePath))
        {
            listView1.Items.Clear();

            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                using (TextReader sr = new StreamReader(fs))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        string[] data = line.Split(new char[] { ',' });
                        ListViewItem lvi = new ListViewItem();

                        if (listView1.Items.Count > 0)
                        {
                            MessageBox.Show("ListViewCount#1: '" + listView1.Items.Count + "'.");
                        }

                        lvi.Text = data[0];
                        lvi.SubItems.Add(data[1]);
                        lvi.SubItems.Add(data[3]);
                        lvi.SubItems.Add(data[4]);
                        lvi.Tag = data[2];

                        listView1.Items.Add(lvi);

                        if (listView1.Items.Count > 0)
                        {
                            MessageBox.Show("ListViewCount#2: '" + listView1.Items.Count + "'.");
                        }
                    }
                }
            }
            if (listView1.Items.Count == 0)
            {
                MessageBox.Show("ERROR: ListView has no data to show.");
                return;
            }
        }
    }

The listView1.count is more than 0 after the "lvi" part, prior to that it is empty(tested with messagebox counting listView1 before and after this method), why is it saying it has a "listView1.count of 1" if all the "data" is empty? I have tried other ways to work around this using custom booleans in other methods but its just not practical referring back to them, all i want to do is if listview1 is 0 tell user there is no data.

A: You must have initialised you listview earlier in the code so as to not get a runtime error at:
listView1.Items.Add(lvi);

The instantiation of the listview will create an empty listview with a count of 0 thus passing your if declaration.


text:
Q: How to set path for sudo commands If I issue
sudo my-command

how does Linux look for that my-command?
The my-command is in my PATH. I can invoke it without any problem. However, when I invoke it with sudo, I'll get command not found.
How to overcome it?
EDIT: That "Possible duplicate"'s selected answer is wrong, well, at least not to the point. This answer, from terdon, is the correct one.

A: This is normally set by the secure_path option in /etc/sudoers. From man sudoers:
 secure_path   Path used for every command run from sudo.  If you don't
               trust the people running sudo to have a sane PATH environ‐
               ment variable you may want to use this.  Another use is if
               you want to have the "root path" be separate from the "user
               path".  Users in the group specified by the exempt_group
               option are not affected by secure_path.  This option is not
               set by default.

To run commands that are not in the default $PATH, you can either

*

*Use the full path: sudo ~/bin/my-command; or

*Add the directory containing the command to secure_path. Run sudo visudo and edit the secure path line:
Defaults        secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/youruser/bin/"

Save the file and next time you run sudo, the directory ~/bin will be in its $PATH.

A: This is what I used for a workaround:
sudo cp $(which my-command) /usr/bin
...

The which command is executed in a subshell that is non-root, so it is able to find my-command, then, sudo copies the executable to a path that the root user can access. Not great for security, but it was ok for me running a docker image that was being destroyed right after the command was run.

A: You can also use sudo env PATH=$PATH ...rest_of_command_here.... Since that's not so convenient to type, I've added an alias alias sudop='sudo env PATH=$PATH'. The sudop (rather than aliasing sudo itself) is a reminder to me to make me aware that I am preserving my current environment path.

A: How to symlink or copy an executable to a bin dir that sudo has access to
I'm using a text editor called micro. I ran sudo micro /etc/sysctl.conf and got this error:
sudo: micro: command not found

That's because micro is in my ~/bin dir, but that's a personal bin dir to my user only. To give sudo access to it, I can either symlink it or copy it to /usr/bin as well:
# symlink it (my preference)
# Create a symlink at /usr/bin/micro which points to my personal ~/bin/micro
# executable
sudo ln -si ~/bin/micro /usr/bin

# OR: copy it
sudo cp -i ~/bin/micro /usr/bin

Done. Now when I run sudo micro it works fine.


text:
Q: How can I convert a coloured icon to a monochrome one? I recently compiled goldendict from source. To my dismay I discovered that there were no monochrome appindicator icons included. At the moment I am stuck with this:

I tried converting the icons to B/W using GIMP, but it still doesn't look quite right:

How can I modify the icons to fit with the rest of the theme?
These are the icons in question:

A: Ok, I invested some time and did it myself. What I did was basically use GIMP's Alpha to Selection tool to select the non-transparent parts of the image. Then I chose the Bucket Fill tool to apply a homogenous grey colour to the icon. All other refinements I did manually with the Paintbrush tool.
These are the raw icons:
 (programicon_old.png)  (programicon_scan.png)
This is what the indicator now looks like:

In order to install the icons you will have to compile GoldenDict from source:

*

*Clone the GitHub repository
git clone https://github.com/goldendict/goldendict.git

*Navigate to ./goldendict/icons and replace programicon_old.png and programicon_scan.png with the updated icons

*Follow the instructions in README.md to compile and install GoldenDict


text:
Q: passing a sort direction to `arrange` in a `dplyr` data pipeline function I have a function that does a bunch of things with my data. But I want to add a sort order parameter allowing me to flip the data in one step in the opposite direction when a parameter is passed to the function. And I need the function to be compatible with SQL backends for dbplyr.
My current solution seems really inelegant. I have two complete data pipelines, one with a desc() and one without. This feels really clunky, but since I have to wrap desc() around my field in dplyr I can't think how else to do this. One idea might be to create a sort parameter that is either 1 or -1 and multiply that times my field before sorting. Is there an easier or simpler way to do this?
Here's a simple toy example showing how I'm creating two pipelines:
library(dplyr)

df <- data.frame(x = rnorm(10))

stupid_func <- function(df, sort_order = 'asc'){
  ## does many things in reality, this is a toy example

  if (sort_order == 'asc') {
    df %>% arrange(x) %>% return
  } else if (sort_order == 'desc') {
    df %>% arrange(desc(x)) %>% return
  }

}

stupid_func(df, 'desc')
#>             x
#> 1   1.6680607
#> 2   1.4853252
#> 3   1.1468913
#> 4   1.0447893
#> 5   0.5243115
#> 6   0.3784285
#> 7  -0.5693750
#> 8  -0.8744429
#> 9  -1.0346144
#> 10 -2.6256735

stupid_func(df)
#>             x
#> 1  -2.6256735
#> 2  -1.0346144
#> 3  -0.8744429
#> 4  -0.5693750
#> 5   0.3784285
#> 6   0.5243115
#> 7   1.0447893
#> 8   1.1468913
#> 9   1.4853252
#> 10  1.6680607

And here's using a sort parameter that gets mapped to a fac that is either 1 or -1
stupid_func2 <- function(df, sort_order = 'asc'){
  ## does many things in reality

  if (sort_order == 'asc') {
    fac <- 1
  } else {
    fac <- -1
  }

  df %>% arrange(fac * x) %>% return

}

A: To avoid control flow entirely, you can pass either desc or identity as function instead of a string and call it:
library(dplyr)
set.seed(47)

df <- data.frame(x = rnorm(2))

f <- function(data, sort_fun = identity){
    arrange(data, sort_fun(x))
}

f(df)
#>           x
#> 1 0.7111425
#> 2 1.9946963

f(df, desc)
#>           x
#> 1 1.9946963
#> 2 0.7111425

If you really want to input strings, you could use them to look up the appropriate function, which could be called the same way:
f2 <- function(data, sort_order = c('asc', 'desc')){
    sort_order <- match.arg(sort_order)
    sort_fun <- list(asc = identity, desc = desc)[[sort_order]]
    arrange(data, sort_fun(x))
}

f2(df)
#>           x
#> 1 0.7111425
#> 2 1.9946963

f2(df, 'desc')
#>           x
#> 1 1.9946963
#> 2 0.7111425

You can similarly look up expressions, which lets you avoid identity altogether:
f3 <- function(data, sort_order = c('asc', 'desc')){
    sort_order <- match.arg(sort_order)
    sort_expr <- list(asc = expr(x), desc = expr(desc(x)))[[sort_order]]
    arrange(df, !!sort_expr)
}

f3(df)
#>           x
#> 1 0.7111425
#> 2 1.9946963

f3(df, 'desc')
#>           x
#> 1 1.9946963
#> 2 0.7111425

A: How about moving the if / else statement into the arrange function:
stupid_func <- function(df, ascending=TRUE){
    ## does many things in reality, this is a toy example

    df %>% arrange(if(ascending) x else desc(x))
}

stupid_func(df)
#               x
#1  -1.4162465950
#2  -1.0428581093
#3  -0.3558181508
#4  -0.2366332875
#5   0.0003166344
#6   0.5146631983
#7   0.6390745275
#8   0.7459405376
#9   1.6161165230
#10  1.9243922633

stupid_func(df, ascending = FALSE)
#               x
#1   1.9243922633
#2   1.6161165230
#3   0.7459405376
#4   0.6390745275
#5   0.5146631983
#6   0.0003166344
#7  -0.2366332875
#8  -0.3558181508
#9  -1.0428581093
#10 -1.4162465950


text:
Q: How to run php script from jQuery - on button click I have a simple PHP script that sits in the home directory of my webserver. I also have a button called "campausebtn". I want to simply click the button and then call the php file using jquery. I've read many posts on SO and it seems simple, but I can't get it to work.
I've tried the following script:
<script>
jQuery(document).ready(function(){

    jQuery("#campausebtn").click(function(){

        alert("Paused Clicked!");

        $.ajax({
            url: 'camera_pause.php',
            success: function() {
                alert("Paused!");

            }
        });

    });

});
</script>

The "Paused Click" alert is working fine, so I know the jQuery and button are working. It just wond't run the script.
Please can someone help?
Thanks
Chris

A: Try it like this...
$.ajax({
  method: "POST",
  url: "camera_pause.php",
})
  .done(function( msg ) {
    console.log( msg );
  });

otherwise read the documentation on it: https://api.jquery.com/jquery.ajax/


text:
Q: JQuery DatePicker Highlight Date onSelect Hi I am trying to create a date range selector. below is the given code which I need to fill in. How do I highlight all the Selected date
 $(document).ready(function () {
        $("#fromCalendar").datepicker({
            numberOfMonths: [1, 6],
            stepMonths: 1,
            autoSize: true,
            dateFormat: 'dd/mm/yy',
            onSelect: function (date) {
                selectDate(date);
            }

        });
    });
function selectDate(date){
//Code
}

A: your_text_box.focus();
your_text_box.select();

should get your text selected I believe.

A:  $(document).ready(function () {
        numberOfMonths: [1, 6],
        stepMonths: 3,
        autoSize: true,
        changeMonth: true,
        changeYear: true,
        dateFormat: 'dd/mm/yy',
        onSelect: function (dateText, inst) {
            selectDate(dateText);
        },
        beforeShowDay: function (date) {
            var gotDate = $.inArray($.datepicker.formatDate($(this).datepicker('option', 'dateFormat'), date), dates);
            if (gotDate >= 0) {
                return [false, "ui-state-highlight ui-state-active ui-state-hover"];
            }
            return [true, ""];
        }
});

});


text:
Q: non-existent service "http_client" while upgrading symfony 4 to 6 I'm migrating a Symfony 4 app to Symfony 6. Symfony like change everything in next major version.
I'm supposing the problem come from api platform but not really sure.
!!
!!  In CheckExceptionOnInvalidReferenceBehaviorPass.php line 83:
!!
!!    The service "api_platform.http_cache.purger.varnish.ban" has a dependency o
!!    n a non-existent service "http_client".
!!

I tryed searching "api_platform.http_cache.purger.varnish.ban" or "varnish.ban" or "http_client" with grep command but no results, like if this line isn't in any file of the app.


text:
Q: Integral and Velocity - MIT Calculus problem PROBLEM: I can't understand how absolute value of velocity can be negative.
You drove 125 km on a straight road from your home to the border, but had to turn around when you arrive because you have forgotten to bring your passport. You drove 2 hours on the same road back home. Let $v(t)$ be your car's velocity (in km/hour) at time $(t)$ (in hours), and let $x(t)$ be your car's position (in km) at time.

Let $A > 0$ be the area of the blue region, and $B > 0$ be the area of the pink region. (These are geometric areas, hence positive numbers, not signed areas.)
Which of the following equals  $\int_0^4 \left\lvert v(t) \right\rvert dt = ?$

I chose $1,3,4$ as correct answer but it says $1,3,5$ are the correct options. And this reasoning is given:
We can see that the area under $y = \left\lvert v(t) \right\rvert$ between $t = 0$ and $t =4$ is the same as the sum of the areas of the blue and pink regions. Hence $$\int_0^4 \left\lvert v(t) \right\rvert dt = A + B $$ But since $$\int_0^2 \left\lvert v(t) \right\rvert dt = A, \int_2^4 \left\lvert v(t) \right\rvert dt = - B $$ Therefore, $$\int_0^4 \left\lvert v(t) \right\rvert dt = \int_0^2 \left\lvert v(t) \right\rvert dt - \int_2^4 \left\lvert v(t) \right\rvert dt $$
According to my reasoning, since it is an absolute function:
$$\int_2^4 \left\lvert v(t) \right\rvert dt = \left\lvert -B \right\rvert = B $$ Therefore, $$\int_0^4 \left\lvert v(t) \right\rvert dt = \int_0^2 \left\lvert v(t) \right\rvert dt + \int_2^4 \left\lvert v(t) \right\rvert dt $$
But that is wrong as per MIT answer, I wonder why.

A: Notice that $v(t)$ is negative for $t \in (2,4)$. Therefore we must subtract $$\int_2^4 v(t) dt$$ in order to compute $$\int_0^4 |v(t)| dt = \int_0^2 |v(t)| dt + \int_2^4 |v(t)| dt$$
$$\int_0^4 |v(t)| dt = \int_0^2 v(t) dt - \int_2^4 v(t) dt $$


text:
Q: swfobject flashes white before swf has loaded I have the following code, I have set the bgcolor and still my page flashes white prior to swf loading. Basically i want the background to always be black, my page body tag has a black background.
<script type="text/javascript">

var path = "/media/19519/la_03.swf";
var videowidth = "955";
var videoid = "swf1454";
var videoheight = "540";
var flashvars = {};
var attributes = {};
var params = {
wmode: "opaque",
bgcolor: "#000000",
  allowfullscreen: "true",
  allscriptaccess: "always"
};

swfobject.embedSWF(path, videoid, videowidth, videoheight, "9.0.0", flashvars, params, attributes);

        </script>

A: it's probably from your swf loading. I had a similar problem with a large swf and the way I got it to stop was to pause the swf in the first frame until it was done loading. Then just put an empty frame at 1 and make it the bg color. Once the swf is ready to go the animation starts

A: Make sure the html element containing the swf is black too.

A: I know this is an old post, but for people who stumble upon this post via search engines:
A flash of white is sometimes a byproduct of SWFObject's 'autohide' feature (CSS is used to hide the fallback content before the SWF loads). If you don't want to see the flash of white, try disabling SWFObject's autohide feature:
SWFObject documentation:

*

*What's new in 2.2: The option to switch off SWFObject's default show/hide behavior

*SWFObject 2.2 API docs: swfobject.switchOffAutoHideShow()
Of course, how you build your SWF will also impact whether you see a flash of white.

A: For me, the issue was in background color of the swf file.
When not explicitly set, it defaults to white until loaded. So just set it explicitly and you won't have a white flash.
var params = {bgcolor:"#000000"};
swfobject.embedSWF("my.swf", "flash", "100%", "100%", "10.0.0", false, {}, params);


text:
Q: Substitute R values Is there a faster way to do the following R substitution
for(i in 1:545082)
{
   index = i*33
   A[index,]$pred = B[index,]$pred
}

This loop seems to take forever in R.  Thanks

A: Assuming you have a data.frame you can use data.table's set function to replace values by reference.  That should be very fast since there are no copies being made.
library(data.table)
set(A, i=1:545082*33, j="pred", B[i:545082*33, "pred"])

A: Some benchmarks. data.table::set() is indeed a lot faster than regular data frame assignment, but the gigantic difference comes from vectorized assignment (avoiding the for loop).  You can get about a 15000-fold speed increased by using vectorized assignment, or a 200,000-fold increase using data.table::set() (again in a vectorized way).
updated: added set within a for loop, which is intermediate in speed (much faster than doing assignment within a loop, and only 50 times slower than doing a vectorized assignment).
 n <- 1e5
 m <- 30
 s <- as.integer(seq(1,n,by=m))
 set.seed(101)
 A <- B <- data.frame(x=runif(n),y=runif(n))

 library("data.table")
 library("rbenchmark")
 benchmark(for(i in s) { A[i,]$y <- B[i,]$y },
           for(i in s) { A[i,"y"] <- B[i,"y"] },
           for(i in s) { set (A,i=i,j="y",B[i,"y"]) },
           A[s,"y"] <- B[s,"y"],
           set(A, i=s, j="y", B[s,"y"]),
           replications=20,
        columns = c("test", "elapsed", "relative"))

##                                       test elapsed relative
##                     A[s, "y"] <- B[s, "y"]   0.027     13.5
##       for (...) {  A[i, "y"] <- B[i, "y"]}  94.797  47398.5
##        for (...) {   A[i, ]$y <- B[i, ]$y} 409.383 204691.5
##     for (...) { set(A,i=i,j="y",B[i,"y"])}   1.283    641.5
##          set(A, i = s, j = "y", B[s, "y"])   0.002      1.0

A: Try:
n = 545083*33
A$pred[1:n] = B$pred[1:n]


text:
Q: What will be if I use libaio + fsync()? I know that when I write files using write() + fsync() (or O_SYNC + write(), I think they are same ref #1 ref #2), it means I am using blocking synchronous I/O, and the if the write()(with O_SYNC) or fsync() returns, it means the data is safely on the device medium (e.g., TLC NAND for SSD) rather than the device cache (e.g., DDRAM in SSD).
While what if I use libaio? (because I want to make sure the write issued by libaio is on the storage medium rather than the device cache. i.e., I suppose when io_getevents() returns, it may not make sure the write is on the storage medium, and it may just on the device cache)

*

*Question 1: does fsync() exclusively works for synchronous I/O?

*Question 2:is fsync() after io_submit() an undefined behavior?

*Question 3: how to make asynchronous write safely persisted to the device medium rather than device cache (no battery-backed cache).

A: (This answer is only looking at things from Linux perspective. Other operating systems may have different behaviour/semantics)
So long as you wait for any outstanding asynchronous I/O to be completed you will be able to then send down your fsync() and know all previous I/O was written to stable storage to the best knowledge of the Linux kernel*.

does fsync() exclusively works for synchronous I/O?

This question doesn't make sense. fsync() works on I/O that Linux has agreed has been "sent" and then also flushes the device cache. If you asynchronously send an I/O to the kernel, has the kernel agreed it has been "sent"? Also see the answer to final question...

is fsync() after io_submit() an undefined behavior?

Technically undefined behaviour would mean from then on ANYTHING would be allowed to legally happen (e.g. so called nasal daemons). That's not the case here  but I think you are asking your first question so the answer there still holds.

how to make asynchronous write safely persisted to the device medium rather than device cache (no battery-backed cache).

If you're stuck using libaio you could manually build a barrier by waiting for all outstanding I/O to be completed and then sending an fsync() and waiting for that or (as mentioned in a comment). Another libaio technique is to set the RWF_SYNC flag during io_submit(). If you were using io_uring you would have another option because you can use its chaining and it has an asynchronous fsync operation (IORING_OP_FSYNC).

* I'm excluding the cases where errors happen because they are rather more complicated. See Writing programs to cope with I/O errors causing lost writes on Linux for a detailed explaintion.


text:
Q: Unable to loop through specific nodes with for each in xslt I have XML like this:
<?xml version="1.0" encoding="utf-16"?>
<MessageParts xmlns="http://schemas.microsoft.com/dynamics/2011/01/documents/Message">
  <BankPositivePay xmlns="http://schemas.microsoft.com/dynamics/2008/01/documents/BankPositivePay">
    <BankAccountTable class="entity">
      <AccountID>GBP</AccountID>
      <CurrencyCode>GBP</CurrencyCode>
      <LedgerDimension>
        <MainAccount xmlns="http://schemas.microsoft.com/dynamics/2008/01/sharedtypes">7500000</MainAccount>
      </LedgerDimension>
      <BankChequeTable class="entity">
        <AccountID>GBP</AccountID>
        <AmountCur>444.00</AmountCur>
        <ChequeNum>7</ChequeNum>
        <RecipientAccountNum>UKV-000716</RecipientAccountNum>
        <TransDate>2017-03-10</TransDate>
        <VendTable class="entity">
          <Currency>GBP</Currency>
          <VendGroup>Stock</VendGroup>
        </VendTable>
        <CompanyInfo xsi:type="AxdEntity_CompanyInfo_CompanyInfo" class="entity" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
          <DataArea>UK</DataArea>
        </CompanyInfo>
      </BankChequeTable>
      <BankChequeTable class="entity">
        <AccountID>GBP</AccountID>
        <AmountCur>11700.00</AmountCur>
        <ChequeNum>9</ChequeNum>
        <RecipientAccountNum>UKV-000716</RecipientAccountNum>
        <TransDate>2017-04-10</TransDate>
        <VendTable class="entity">
          <Currency>GBP</Currency>
          <VendGroup>Stock</VendGroup>
        </VendTable>
        <CompanyInfo xsi:type="AxdEntity_CompanyInfo_CompanyInfo" class="entity" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
          <DataArea>UK</DataArea>
        </CompanyInfo>
      </BankChequeTable>
      <BankChequeTable class="entity">
        <AccountID>GBP</AccountID>
        <AmountCur>6394.00</AmountCur>
        <BankNegInstRecipientName>this is a test address</BankNegInstRecipientName>
        <ChequeNum>12</ChequeNum>
        <RecipientAccountNum>UKV-000716</RecipientAccountNum>
        <TransDate>2017-05-10</TransDate>
        <VendTable class="entity">
          <Currency>GBP</Currency>
          <VendGroup>Stock</VendGroup>
        </VendTable>
        <CompanyInfo xsi:type="AxdEntity_CompanyInfo_CompanyInfo" class="entity" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
          <DataArea>UK</DataArea>
        </CompanyInfo>
      </BankChequeTable>
    </BankAccountTable>
  </BankPositivePay>
</MessageParts>

I wanted to generate the CSV, as below:
7,UKV-000716,444.00,2017-03-10,
9,UKV-000716,11700.00,2017-04-10,
12,UKV-000716,6394.00,2017-05-10,this is a test address
But the actual output is below:
7,UKV-000716,444.00,2017-03-10,this is a test address,
    7,UKV-000716,444.00,2017-03-10,this is a test address,
    7,UKV-000716,444.00,2017-03-10,this is a test address,
I am trying to loop the BankChequeTable tag, its looping in VS, but showing All the rows as first row only.
Below is the XSLT i have used:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" encoding="iso-8859-1"/>
  <xsl:strip-space elements="*" />
  <xsl:template match="/">
    <xsl:for-each select="//*[local-name() = 'BankChequeTable']">
      <xsl:value-of select="//*[local-name() = 'ChequeNum']"/>,<xsl:value-of select="//*[local-name() = 'RecipientAccountNum']"/>,<xsl:value-of select="//*[local-name() = 'AmountCur']"/>,<xsl:value-of select="//*[local-name() = 'TransDate']"/>,<xsl:value-of select="//*[local-name() = 'BankNegInstRecipientName']"/>,
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

I am a beginner in the XSLT, Could someone please help me with this?
Thanks in advance.

A: Here's how I would do it.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:ns1="http://schemas.microsoft.com/dynamics/2011/01/documents/Message"
    xmlns:ns2="http://schemas.microsoft.com/dynamics/2008/01/documents/BankPositivePay"
    version="1.0">

  <xsl:output method="text"/>

  <xsl:template match="/">
    <xsl:text>ChequeNum,RecipientAccountNum,AmountCur,TransDate,BankNegInstRecipientName</xsl:text>
    <xsl:text>
</xsl:text> <!-- Line Return -->
    <xsl:apply-templates select="ns1:MessageParts/ns2:BankPositivePay/ns2:BankAccountTable/ns2:BankChequeTable"/>
  </xsl:template>

  <xsl:template match="ns2:BankChequeTable">
      <xsl:value-of select="ns2:ChequeNum"/>
      <xsl:text>,</xsl:text>
      <xsl:value-of select="ns2:RecipientAccountNum"/>
      <xsl:text>,</xsl:text>
      <xsl:value-of select="ns2:AmountCur"/>
      <xsl:text>,</xsl:text>
      <xsl:value-of select="ns2:TransDate"/>
      <xsl:text>,</xsl:text>
      <xsl:value-of select="ns2:BankNegInstRecipientName"/>
      <xsl:text>
</xsl:text> <!-- Line Return -->
  </xsl:template>

</xsl:stylesheet>

See it working here : https://xsltfiddle.liberty-development.net/naZXVEY


text:
Q: create mysql view for many-to-many relationship MYSQL script to create a MYSQL view Table to show use id , email , and the assigned role/s name/s through many-to-many relationship
I wrote the script and joined tables to create the view table but it shows role name for the first record only the other users has null although they have roles!.
Tables
    users (id, email)
    roles (id, name)
    role_users (id, user_id, role_id)

My script
    DROP VIEW IF EXISTS users_view;
    CREATE VIEW users_view AS
       SELECT users.id AS user_id, users.email, roles_names.role_name
         FROM users
    LEFT JOIN(
        SELECT role_users.user_id AS roles_user_id,
               role_users.role_id AS roles_role_id
          FROM role_users
    ) AS user_roles ON (roles_user_id = users.id)
    LEFT JOIN(
           SELECT roles.id AS roleid, roles.name AS role_name
            FROM  roles
     ) AS roles_names ON (roleid = user_roles.roles_user_id)

view created success but it shows the role name for the first user only , other users has role_name  value of null although they have records at role_users table

A:     SELECT u.id AS user_id, u.email, IFNULL(u_roles.role_name,'') as role_name
      FROM users u
 LEFT JOIN
        (SELECT GROUP_CONCAT(DISTINCT r.name SEPARATOR ',') as role_name, ur.user_id
           FROM roles r INNER JOIN user_roles ur
              ON r.id = ur.role_id
       GROUP BY ur.user_id) u_roles
              ON  u.id = u_roles.user_id

Since role users will be having all only roles from roles table, inner join on roles and user_roles will be fine.
By this query all records which are having an entry in user_roles table will show role name and rest of the users will be having null as role name (adding IFNULL check to make null values an empty string)


text:
Q: Nativescript app keeps crashing on android after adding firebase plugin my nativescript app was working fine until i added firebase plugin. Now, when i run it on my device, it gives the error message 'app has stopped working' . Please help
this is the plugin i'm using
https://github.com/EddyVerbruggen/nativescript-plugin-firebase

A: I found out the issue was with the plugin when building for android on windows system. it doesn't occur when building on a macbook. i already logged a complaint on their github repository, some other people have the same issue as me. there are some answers there, you can check them out

A: The google-services.json should be in app/App_Resources/Android
Are you using tns run or suchlike? If so what is the whole error from the terminal? App stopped working doesn't sound like a complete output.

A: In my case my app (nativescript vue) was crashing after successfully copying the google-services.json, but at the time of rendering the app. I resolved it by adding  all required dependencies in App-level build.gradle (//build.gradle) file as shown below:
apply plugin: 'com.android.application'

// Add this line

apply plugin: 'com.google.gms.google-services'

dependencies {
  // add the Firebase SDK for Google Analytics

  implementation 'com.google.firebase:firebase-analytics:17.2.2'

  // add SDKs for any other desired Firebase products
  // https://firebase.google.com/docs/android/setup#available-libraries

Make sure to add all required dependencies based on the Firebase features you have enabled by referring to the Gradle dependency listed in the SDK link above. Keep in mind that Analytics requires several other dependencies to be included as well. After adding all required dependencies, my app started without crasing.
Also make sure that in Project-level build.gradle (/build.gradle) file:
buildscript {
repositories {
    // Check that you have the following line (if not, add it):

    google()  // Google's Maven repository

  }
  dependencies {
    ...
    // Add this line
    classpath 'com.google.gms:google-services:4.3.3'
  }
}

allprojects {
  ...
  repositories {
    // Check that you have the following line (if not, add it):
    google()  // Google's Maven repository
    ...
  }
}

I hope this helps anyone facing similar issue.


text:
Q: Setting custom response using JEditable I am using JEditable jquery plugin to update some data on my webpage. After the data is saved through the JEditable plugin on the server, I want to replace the old content in the container div with the new one which is actually different than the inserted data (application processed the data before saving it and adds some more information with it).
I have tried the below code to do the same, it works for the first time but once the data is replaced in the container div, the editable functionality is lost.
$(".editableComments").editable( function(value, settings) {
            selectedId = $(this).attr("id");
            $.ajax({
                url:'ajaxApproveRequests',
                type:'post',
                data:{
                        requestType: "Trans",
                        idList : $(this).attr("id"),
                        comment:  value
                    },
                success: function(data) {
                    if (data != "Error")
                        {
                            $("#"+selectedId).html(data);
                        }
                },
                error: function(req) {
                    alert("Error in request. Please try again later.");
                }
            });
        },
        {
            indicator : "Saving...",
            type   : 'textarea',
            submit : '<input type="button" id="okBtn" value="Ok" onMouseOver="rollOnAutoButton(this)" onMouseOut="rollOffAutoButton(this)" class="autobtn" >',
            cancel : '<input type="button" id="cancelBtn"  value="Cancel" onMouseOver="rollOnAutoButton(this)" onMouseOut="rollOffAutoButton(this)" class="autobtn" >',
            cssclass : "editableArea",
            rows: 5,
            cols: 25,
            onblur    : "ignore"
        });

The Html code is:

some data

Please suggest where am I doing wron? Thanks in advance.

A: The editable function needs a return value. and you cannot get one with an ajax function.
What I do is that I return some temporary value there in the meantime whilst I do my ajax function:
   $(".editableComments").editable( function(value, settings) {
        selectedId = $(this).attr("id");
        $.ajax({
            url:'ajaxApproveRequests',
            type:'post',
            data:{
                    requestType: "Trans",
                    idList : $(this).attr("id"),
                    comment:  value
                },
            success: function(data) {
                if (data != "Error")
                    {
                        $("#"+selectedId).html(data);
                    }
            },
            error: function(req) {
                alert("Error in request. Please try again later.");
            }
        });
        return value; //need the return
    }, ...


text:
Q: Using strong types with $ in Polymer Dart not working This is a problem that keeps cropping up for me with Polymer and Dart.
When using an element from the polymer_elements project, I find I can't access properties or methods on those elements without eliciting warnings in the Dart Editor. The code runs, but the warnings get annoying once there are lots of them.
$["header-collapse"].toggle();   // creates a warning (Element does not have method "toggle")

In the above line, the element with an ID of "header-collapse" is a PolymerCollapse element from the polymer_elements package. But if I import the appropriate Dart file and try to typecast it as such, I get exceptions. So this does not work:
PolymerCollapse headerCollapse = $["header-collapse"];   // does not work!

Setting breakpoints and examining what $["header-collapse"] returns has not been helpful so far. Anyone know how I could get this working?

A: I'm one of the contributors of the polymer_elements/polymer_ui_elements.
This is very annoying but we have no solution for this either. There is an open bug (I will add the link tomorrow - I'm on the phone now)
The best you can do is to not to import the elements in Dart, only in HTML and ignore the warnings otherwise pub build won't work.


text:
Q: How is the iPhone SMS compose view implemented? Regarding the SMS compose view as show in the picture below:
alt text http://www.kennethlund.dk/wordpress/wp-content/uploads/2008/08/iphone_sms.jpg
I have two questions:
1) How is the text entry box implemented? There are no standard control from the API and the box is smart enough to resize when you press enter OR when the text is too long. Also the bar resizes with it. How is this done with the least coding?
2) How to code it such that when the keyboard shows up the whole view shifts up? Typically when the keyboard shows, it goes over your current view.

A: Searching stackoverflow for "uitextView size" produces these results:
How do I size a UITextView to its content?
Resizing UITextView

Searching stackoverflow for "keyboard iPhone" produces this result:
Programmatically align a toolbar on top of the iPhone keyboard

A: TTTextEditor is an autosize text box, which is part of the three20 framework


text:
Q: Run Google Cloud Function at a specific time I'd like to schedule the execution of a Cloud Function to a specific time. It should be run only once.
I basically have a function "startTask" which modifies some data in the Firestore database. After X seconds (the time is passed to the startTask function), the "finishTask" function should be called.
I already tried messing around with Google Cloud Tasks but I feel like this isn't the right way to go.

A: Google Cloud does not have service that will do what you need that I am aware of. If you need X to happen N seconds after user does Y, you will need to code that service yourself.
You do not specify what services you are using for compute (App Engine, Compute Engine, Kubernetes, etc.) but writing a task secheduling service in just about any  language is not very hard. There are many ways to accomplish this (client side code / server side code). Many OS / language combinations support scheduling a function with a timeout and callback.

A: You can use Cloud Tasks. It will allow you to be alerted after x amount of seconds.
https://cloud.google.com/tasks/docs/creating-http-target-tasks

A: The easiest way is to create a pub/sub topic, cron-topic that your cloud function subscribes to.  Cloud Scheduler can push an event to cron-topic on a schedule
Create the Topic & Subscription
gcloud pubsub topics create cron-topic
# create cron-sub for testing.  Function will create it's own subscription
gcloud pubsub subscriptions create cron-sub --topic cron-topic

Create the Schedule
Command is below, but since it's beta, see the console guide here
# send a message every 3 hours. For testing use `0/2 * * * *` for every 2 min
gcloud beta scheduler jobs create pubsub --topic=cron-topic --schedule='0 */3 * * *'

Create a Function to Consume the cron-topic Topic
Put your function code in the current directory and use this command to deploy the function listening to the cron-topic topic
FUNCTION_NAME=cron-topic-listener
gcloud functions deploy ${FUNCTION_NAME} --runtime go111 --trigger-topic cron-topic

note pub/sub events are sent at least once. In some cases the event can be sent more than once.  Make sure your function is idempotent


text:
Q: console.log of BSON objects in NodeJS I'm confused about the way console.log displays ObjectId() objects from native MongoDB driver for NodeJS.
I print the adslot document from MongoDB with console.log:
db.collection('adslots').findOne({_id: adslotId}, (err, adslot)=>{
    console.log( adslot );
}

and the output is
adslot:
{ _id: 57ef0b9b26d1d77b606bf271,
  name: 'cspop',
  width: 1,
  height: 1,
  elemId: 'dummy',
  active: true,
  updated: 2016-10-01T01:04:27.597Z }

_id looks like a hex number. However, _id is ObjectId because:
console.log( "adslot:\n" + adslot._id.constructor.name );

gives
adslot:
ObjectID

In spite of adslot having constructor of ObjectId calling isValid() ( http://mongodb.github.io/node-mongodb native/2.2/api/ObjectID.html#.isValid ) on it gives an error:
console.log('adslot:');
console.log( adslot._id.isValid() );

results:
adslot:
/home/vlad/arbsrv/node_modules/mongodb/lib/utils.js:98
    process.nextTick(function() { throw err; });
                                  ^

TypeError: adslot._id.isValid is not a function

So, why does console.log() prints _id as a number and not as an object? Is toString() somehow called automatically on the _id?
And why if _id is instance of ObjectId, isValid() is not defined on it?

A: isValid is defined on the ObjectId itself and not its prototype. An instance of the ObjectId will not have this method. Try calling it as ObjectId.isValid()
Take the following for example:
function ObjectId(){}

ObjectId.isValid = function(){
    return true;
}

ObjectId.prototype.sayHi = function(){
    return 'hello';
}

var a = new ObjectId();
a.sayHi(); // hello
a.isValid(); // raises exception

ObjectId.isValid(); // true

why does console.log() prints _id as a number and not as an object?
Short answer, yes it calls the toString() on it. For more details check this SO answer. Also from what i understand, the ObjectId prototype has a toString method defined on it which return the _id value as a string.


text:
Q: Concatenate two double arrays into a n x 1 cell array using matlab I have an n x 1 double array.
A = [1234;
     1235;
     1236;
     1237;
     1238];

and a double Scalar.
B = [4567]

I want to combine (concatenate) these to make a n x 1 cell array that looks like this,
C = [1234 4567;
     1235 4567;
     1236 4567;
     1237 4567;
     1238 4567];

A: Try this one-liner:
out = mat2cell([A,repmat(B,numel(A),1)],ones(numel(A),1),2)

Sample run:
A = [1234; 1235; 1236; 1237; 1238];
B = [4567];

Results:
out =

[1x2 double]
[1x2 double]
[1x2 double]
[1x2 double]
[1x2 double]

If you want as 1xn cells, you could just transpose the output
out = out.'      %//'

out =

[1x2 double]    [1x2 double]    [1x2 double]    [1x2 double]    [1x2 double]


text:
Q: What is this space homeomorphic/homotopy equivalent to? Let $X \subset \mathbb{C}^2$ be given by the equation
$$|z|^2 + |w|^2=1$$ and let $A \subset X$ be given by $|z|=1,\ w=0$.
This question requires me to find the relative homology groups $H_n(X,A)$, but before I do that I would like to ask if my guess is correct.
Is $X$ homeomorphic/homotopy equivalent to $S^4$, and $A$ homeomorphic/homotopy equivalent to $S^2$?


text:
Q: Fetch set of images joining tables inside a while loop I just register to Stack Overflow, I looked for a post like this one but what I found was a group of different posts but I'm not smart enough(yet!) to put them together to answer my question.
I like to learn programming with, let's say "real" examples after I finish my online courses or books.

What I would like to achieve
As you can see in my link is what I want to achieve. Initially I had all the data in one table but I've been reading on this site that is not the best practice to store the images paths separated by commas in just one field. So right now I have:

*

*1 table with all the info.

*1 table (so far) with a collection of pictures for my first ad.

So, my question is, I don't know how exactly do I have to join the tables and use the while loop to be able to fetch as many pictures as I need per ad, to later on, use those pictures in a Lightbox gallery...
so far I was only able to put 1 picture per ad! :S
my 1st table is structured like this
| ID | HOUSE-TYPE | CITY | TITLE | DESCRIPTION | PICS | SQRMETER | PRICE | TELPHONE | EMAIL
my 2nd table is structured like this:
| ID | PATH | TITLE | ALT |
And my code so far:
    $result = mysqli_query($con,"SELECT * FROM t_test");

while($row = mysqli_fetch_array($result))
  {
    echo "
" .
             "
" .  "OFFER " . $row[offer] . $row[house-type] . " in " . $row[city] .
             "
" .
             "
" . $row[title] . "
" .
             "
" . $row[description] . "
" .
             "" .
             "
" . "TOTAL PICS" . "
" .
             "
" . $row[sqmeter] . " metros 2" . "
" .
             "
" . $row[price] . " Euros" . "
" .
             "
" . $row[telphone] . "
" .
             "
" . $row[email] . "
" .
        "
";

  }

mysqli_close($con);

Thanks for your time guys!

A: Each ad can have multiple pics, so you need to setup a "one-to-many" relationship in your database. You do this by using foreign keys.

*

*In the ads table, each ad has a unique ID already

*In the pics table, in addition to each one having it's own unique ID, there should be an additional field for the ads_ID which it belongs to.

*When you go to display ad ID x, then you query the db to get all pics with ads_ID x:

"SELECT * FROM pics WHERE ads_ID = x"

A: There are many solutions for what you are trying to achieve. I would suggest to keep this simple is to have another column in your pics table called linked, this would link your image to your ad.
Try and follow these steps below.

*

*Create a column in your pic table called 'linked'
ALTER TABLE ads ADD linked VARCHAR(255)

*create a foreign key relationship between your pics table and your ad's table.
(if your ad gets deleted or updated for example, it will also delete your image from the pics table)

*In your code join your tables by doing something like this.
$query = '
SELECT ads.*, pics.*  FROM ads
LEFT JOIN pics ON pics.linked = ads.id
';

$result = mysqli_query($con,$query);


text:
Q: React in WordPress plugin with split bundles for public and admin side I'm working on a WordPress plugin using React. I started off https://github.com/robicse11127/wp-react-kickoff as a base and everything works fine, except for the part where it generates one single bundle for the whole React app. Since my plugin consists in multiple separate apps for different parts of the dashboard and another distinct app for the front, it doesn't make much sense to use one single bundle file; I'd rather have each part bundled separately and loaded where needed: dashboard app in the dashboard, editor app in the edit posts pages, public app on the public pages, etc.
I tried using webpack chunks like described here, but couldn't make it work properly. It actually somewhat worked in the dedicated React app I created with create-react-app to build my components before moving to WordPress, but wp-react-kickoff seems to work quite differently (no public folder, no index.html, which is actually what I want) and I couldn't make it work.
Here's what I'd like to have:
my-plugin
|___admin
    |___css
        |___...
    |___js
        |___dashboard.js
        |___editor.js
        |___settings.js
|___includes
    |___... wp plugin stuff
|___public
    |___css
        |___...
    |___js
        |___app.js
|___src
    |___components
        |___ ...
    |___app.js
    |___dashboard.js
    |___editor.js
    |___settings.js
    |___index.js
|___package.json
|___webpack.config.js

Currently I use src/index.js to load my separate apps (dashboard, editor, settings and app, this last one being the public part) and all of them get bundled in a dist/bundle.js that is loaded by WordPress on both admin and front sides. How can I make it so that my different apps end up is separate files in public/js and admin/js like above? Bonus question, I'm currently using external CSS edited manually and I'm considering moving to SASS to be bundled with webpack along with the React apps, using the same separate files logic. Can this be done?