text:
Q: Sort a spreadsheet by one column while keeping the contents of every 4 rows together? The last column is a total of the second-to-last column. I want to sort by the last column in units of 4 rows. That is, each pack of four rows should be considered one item and should not be broken up.

A: Short of someone having a better way to sort you could do the following.
You will need two sort columns, the first to sort your totals column "H" and the second for your identifier column "A". So that you can sort you need to populate the missing data.
For column "I" the formula is in the below pic and for column "J" it's essentially the same except your changing column "H" for "A" in the formula. All this is doing is automating the task of filling in the blanks.
=IF((H2=""),I1,H2)

Once all your data is in the two sort columns it would probably be best to copy and past to values the two support columns to remove formulas, then you can do a normal sort using "Sort Col 1" and then adding a level for "Sort Col 2) This only works with column "A" being unique.


text:
Q: Iteration speed of unordered_set vs vector I have an application where I need to store various subsets of different customers. The order of the customers in the container does not matter.
Since the order does not matter, I was hoping that storing and iterating through this set of customers would be faster on an std::unordered_set<int> as compared to std::vector<int>.
CPPREference, however, states:

unordered_set containers are faster than set containers to access individual elements by their key, although they are generally less efficient for range iteration through a subset of their elements.

To test this out, I evaluated the time it takes to iterate through std::unoredered_set and std::vector.
#include <vector>
#include <unordered_set>
#include <chrono>
#include <stdio.h>

static const int NoElements = 100000000;

int main()
{
    std::vector<int> VecofElems;
    VecofElems.reserve(NoElements);

    std::unordered_set<int> SetofElems;
    SetofElems.reserve(NoElements);

    for (int i = 0; i < NoElements; i++)
        VecofElems.push_back(i);
    for (int i = 0; i < NoElements; i++)
        SetofElems.insert(i);

    auto VecIterStartTime = std::chrono::steady_clock::now();
    long vec_cumulative_sum = 0;
    for (std::vector<int>::const_iterator viter = VecofElems.begin(); viter != VecofElems.end(); ++viter)
        vec_cumulative_sum += *viter;
    auto VecIterEndTime = std::chrono::steady_clock::now();
    std::chrono::duration<double, std::milli> VecTime = VecIterEndTime - VecIterStartTime;

    auto SetIterStartTime = std::chrono::steady_clock::now();
    long set_cumulative_sum = 0;
    for (std::unordered_set<int>::const_iterator uositer = SetofElems.begin(); uositer != SetofElems.end(); ++uositer) {
        set_cumulative_sum += *uositer;
    }
    auto SetIterEndTime = std::chrono::steady_clock::now();
    std::chrono::duration<double, std::milli> SetTime = SetIterEndTime - SetIterStartTime;

    printf("Vector Sum %ld, Size %ld, Time Taken %f\n", vec_cumulative_sum, VecofElems.size(), VecTime);
    printf("Set Sum %ld, Size %ld, Time Taken %f\n", set_cumulative_sum, SetofElems.size(), SetTime);

    getchar();
}

The output on my machine, when the above is compiled in Release Mode of MSVC compiler is:
Vector Sum 887459712, Size 100000000, Time Taken 51.340000
Set Sum 887459712, Size 100000000, Time Taken 4772.139100

indicating that iterating through a vector is many orders of magnitude faster than an unordered_set.
In my application, since the order of the elements in a container do not matter, and since an std::vector preserves order (unnecessarily in this case), is there any other container that can be faster than even std::vector in iterating through various elements of the container?

A: std::vector is the fastest STL container for linear iterations like in your scenario. This is simply because memory is contiguously allocated and therefore can benefit of caching mechanisms. A vector iterator just increments a pointer internally.
You might improve performance further by trying to use a smaller type than int when possible.
In your case I think parallelization/SIMD would give largest performance boost for reduction. This might be achieved by auto vectorization (check project compiler settings).
You could also try OMP to do this like this (not tested)
size_t end = VecofElems.size();
#pragma omp parallel for shared(vec_cumulative_sum ) reduction(+: vec_cumulative_sum )
for (size_t i = 0; i < end; ++i) {
    vec_cumulative_sum += VecofElems[i];
}

This would run multiple threads in parallel. Therefore it's important to declare vec_cumulative_sum as being shared amongst the threads.
std::for_each provides some simple way to make use of parallelism including vectorization. This allows to simply use any STL container like std::vector (and any other container providing iterators) like this
std::for_each(std::execution::par, VecofElems.begin(), VecofElems.end(),
    , []() {
        // have some fun using a lambda, or function
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: What tracing events I should use to use to recreate cpu statemap dtrace script I want to recreate Brian Cantrills statemap scripts to analyze scheduling behavior of a machine (what cpu is doing at any given moment in this particular case) with eBPF.
But it's not clear which tracing  events correspond to the ones used in dtrace script (for bsd I guess).
Tracepoints used there:
interrupt-start
interrupt-complete
sched::on-cpu


text:
Q: Can't post values of radio buttons using jQuery and php I'm trying to get the selected value of two radio buttons by posting via jQuery and processing it in PHP. Here's my code:
HTML:
<input type="radio" name="purch" value="goods" checked>Goods<br>
<input type="radio" name="purch" value="services">Services

jQuery:
$("#addDoc").click(function(){
    $.post("manual.php",
    {
        invoice: $("#invoiceBox").val(),
        supplierName: $("#supplierBox").val(),
        refNo: $("#refBox").val(),
        vatReg: $("#vregBox").val(),
        vatPurch: $('input[name=purch]:checked', '#addForm').val()
    },
    function(data){
      alert(data);
    });
});

PHP:
<?php
    $vatPurch = $_POST['vatPurch'];

    echo $vatPurch;
?>

However I try to post it, I always get an 'Notice: Undefined index: vatPurch' error when submitting the form.

A: You are using 'vatPurch' instead of 'purch'
Give a try to this and (I hope) it will work
<?php
    $vatPurch = $_POST['purch'];
    echo $vatPurch;
?>


text:
Q: undefined property error when using muodules::run in codeigniter I try use modules::run in my custom library to get all new messages received from contact us form and display it in the header ..
modules run is called fine as i tested it by echo something but when i call some method from the model of the module i get this error

This is the code of my library
 <?php

if (!defined("BASEPATH"))
    exit("No direct script access allowed");

class back extends CI_Controller {

    public function __construct() {
        parent::__construct();

        $this->load->helper("form");
        $this->load->library("form_validation");
        $this->lang->load("back", "arabic");
    }

    public function view($page_name, $data = NULL) {
        $h_data["username"] = $this->get_username();
        $h_data["new_cases_reports_count"] = Modules::run('cases/admin_cases/count_new_cases_reports');

        $this->load->view("back/header", $h_data);
        $this->load->view($page_name, $data);
        $this->load->view("back/footer");
    }

}

The code of controller
    <?php

if (!defined("BASEPATH"))
    exit("No direct script access allowed");

class Admin_cases extends back {

    private $c_name = "admin_cases_";

    public function __construct() {
        parent::__construct();
        $this->lang->load("cases_back", "arabic");
        $this->load->model("cases_back_model", "cases");
        $this->load->library("form_validation");
        $this->form_validation->set_error_delimiters("", "");

        $this->_is_logged_in();
    }

    public function count_new_cases_reports() {
        echo 1;
        echo $this->cases->count_new_cases_reports();

    }

}

The code of the model
    <?php

if (!defined("BASEPATH"))
    exit("No direct script access allowed");

class Cases_back_model extends CI_Model {

    public function __construct() {
        parent::__construct();
    }

    public function count_new_cases_reports() {
        $this->db->where("care_status", 0);
        return $this->db->count_all_results("cases_reports");
    }

}

it echoes 1 nicely but when calling method in the model i get undefined property error
help please!

A: As you are using HMVC you should extends your controller from MX_Controller. Also your controller name should Camel case (assuming you are using version 3+)
Try this
//File name should be Back.php
class Back extends MX_Controller {
...

and
class Admin_cases extends MX_Controller {
....


text:
Q: AFNetworking responseObject alternates between NSArray and NSDictionary in AFHTTPRequestOperation I have a problem using AFNetworking in AFHTTPRequestOperation. The responseObject alternates between NSArray and NSDictionary. Here is how I do a GET request:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:requestURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
      NSLog(responseObject[@"NotAvailableKey"];
    }
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];

The problem is when I'm trying to access a field which is not set in the NSArray object I get the following error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI length]: unrecognized selector sent to instance 0xc1afaa0'

If the responseObject is of the type NSDictionary it works perfectly. Here is my JSON which I get:
(
        {
        "food_id" = 15;
        "food_name" = "fish";
        "user_admin_id" = 3;
        ingredients =         (
                        {
                "ingredients_id" = 3;
                "ingredients_name" = "salt";
            }
        );
    }
)

A: You can check if the responseObject is an NSDictionary or an NSArray before using it.
if ([responseObject isKindOfClass:[NSDictionary class]]) {
    NSLog([responseObject valueForKey:@"error"]);
}else if ([responseObject isKindOfClass:[NSArray class]]){
    //This is an NSArray, you cannot call 'valueForKey' on this responseObject
}

UPDATE
As pointed out by @Sausages in the comments, this should be used as a recovery for bad server response. You shouldn't handle multiple object types coming from a single server call has a normal behaviour or use the same methods to handle multiple server calls return an do the response handling according to its type.

A: AFNetworking is just a pipe between your app and the server, you give the impression you think its results should always be the same.
Using isKindOfClass is not the solution either. Your code should know what the expected format and content is when  baseurl.com/methodOne is called and how that differs when  baseurl.com/methodTwo is called and how that differs when  baseurl.com/methodN is called.
If you are calling baseurl.com/methodA you should know that the server is returning the data as an array and what it contains, if you are calling baseurl.com/methodB you should know now its a dictionary and what that contains. Doing it otherwise is the wrong way round.


text:
Q: Как реализовать множественный поиск в PosgreSQL оптимальным способом? Есть таблица в базе Postgres, в которой штук 20 столбцов. И есть задача делать выборку базы по подстроке, не зная, к какому столбцу эта подстрока может относиться.
То есть, пользователь вводит в поиск любую подстроку, а мне нужно перебрать все данные в таблице, так как подстрока может относиться к чему угодно, к любому из 20 столбцов.
Если же приходит две подстроки, нужно делать выборку, где каждая запись содержит в любом столбце хотя бы одно вхождение каждой из подстрок. И так до пяти подстрок в одном запросе.
Как грамотно организовать выборку из базы в данном случае? Какие паттерны существуют для решения такой проблемы?

A: Допущения:

*

*все 20 столбцов текстовые

*поиск на вхождение подстроки в любом месте строк

*искомая подстрока хотя бы 3 символов длиной

*вам всё равно, в каком из полей нашли искомое

Генерируете условия where
(f1 like '%подстрока1%'
  or f2 like '%подстрока1%' ...)
and
(f1 like '%подстрока2%'
  or f2 like '%подстрока2%' ...)

Чтобы не было скучно перебирать всё seqscan'ом понадобится штатный модуль pg_trgm
create extension pg_trgm;

И индекс по полям:
create index concurrently on tablename using gin(f1 gin_trgm_ops, f2 gin_trgm_ops, f3 gin_trgm_ops, f4 gin_trgm_ops);

Для gin индекса порядок полей в индексе значения не имеет.

При дополнительном допущении что допустимо по поисковому запросу "с пробелом" вывести результат, где одно слово попало в одно поле, а второе - в другое - то можно заметно упростить запрос.
create index on tablename using gin((f1 || ' ' || f2 || ' ' || f3 || ' ' || f4) gin_trgm_ops);

where (f1 || ' ' || f2 || ' ' || f3 || ' ' || f4) like '%подстрока1%'
 and (f1 || ' ' || f2 || ' ' || f3 || ' ' || f4) like '%подстрока2%'
 ...

Длинную портянку склеивания полей можно заменить на immutable функцию:
create function test_idx_support(tablename) returns text immutable language sql as $$ select (($1).f1 || ' ' || ($1).f2 || ' ' || ($1).f3 || ' ' || ($1).f4); $$;

create index on tablename using gin(test_idx_support(tablename) gin_trgm_ops);

И затем искать по этой функции:
where test_idx_support(tablename) like '%подстрока1%'
  and test_idx_support(tablename) like '%подстрока2%'
  ...


text:
Q: Magnetic Field and Induced Current in a rod So, I know that a changing magnetic flux will create an e.m.f. And since magnetic flux is dependent on the magnetic field strength and area, a changing area will induce current. However, if I have a rotating rod in a magnetic field, why is current induced? I mean, it's not like the rod changes in area or volume. And since the magnetic field is uniform and constant, the magnetic flux shouldn't be changing as I rotate the rod in the magnetic field right?

A: There is a concept called motional emf which says motion in magnetic field (in specific configuration)  induces a voltage. The voltage induced across the ends of element of length dl is given by $dV=(\vec v × \vec B).\vec{ dl}$. Here $\vec v$ the velocity . So you can integrate the result for a rotating rod.

A: Let's consider what happens to charged particles in the conducting rod. I'll use a cylindrical (r, z, theta) coordinate system, with the origin located at the rod's fixed point, and the magnetic field pointing in the z-direction.
The charges in the conductor experience a $q \vec{v} \times \vec{B}$ force moving positive charges in one direction towards one end of the rod, and negative charges to the other. This charge separation sets up an electric field, and an equilibrium is reached where the net force on a given charged particle:
$\vec{F} = q \left(\vec{E} + \vec{v} \times \vec{B}\right) = 0$
Or,
$E = - \omega r B$ (where r radial position along the rod)
This results in a potential difference along the rod of:
$V = \int \vec{E} \cdot d\vec{l} = -\frac{B\omega L^2}{2}$
As this potential difference is a result of the motion of the conductor, it is referred to as a motional emf.
Now, perhaps the source of your confusion is in understanding the application of Faraday's law. You're quite right in saying the emf in any closed circuit can be related to the change of magnetic flux through that circuit according to:
$\epsilon = - \frac{d \phi}{dt}$.
I added my emphasis as in your original question there is no close circuit (loop). If we create a loop that is formed by the a line along the rod in its current position, the rod's original position, and the chord that the far end of the rod follows, then the area of that loop as a function of time is given by:
$A(t) = \frac{1}{2}L^2 \theta(t)$,
Therefore
$\epsilon = - \frac{d \phi}{dt} = -\frac{1}{2}L^2\omega B$.
Alternatively, one can calculate the motional emf as the integral around that loop of the force per unit charge (work done per unit charge):
$\epsilon = \oint \left(\vec{v} \times \vec{B}\right) \cdot d \vec{l}$,
which due to the fact the only section of the loop with non-zero velocity is the rod itself gives the same answer.


text:
Q: How can I randomly select an item from a list? How do I retrieve an item at random from the following list?
foo = ['a', 'b', 'c', 'd', 'e']

A: This is the code with a variable that defines the random index:
import random

foo = ['a', 'b', 'c', 'd', 'e']
randomindex = random.randint(0,len(foo)-1)
print (foo[randomindex])
## print (randomindex)

This is the code without the variable:
import random

foo = ['a', 'b', 'c', 'd', 'e']
print (foo[random.randint(0,len(foo)-1)])

And this is the code in the shortest and smartest way to do it:
import random

foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))

(python 2.7)

A: As of Python 3.6 you can use the secrets module, which is preferable to the random module for cryptography or security uses.
To print a random element from a list:
import secrets
foo = ['a', 'b', 'c', 'd', 'e']
print(secrets.choice(foo))

To print a random index:
print(secrets.randbelow(len(foo)))

For details, see PEP 506.

A: Random item selection:
import random

my_list = [1, 2, 3, 4, 5]
num_selections = 2

new_list = random.sample(my_list, num_selections)

To preserve the order of the list, you could do:
randIndex = random.sample(range(len(my_list)), n_selections)
randIndex.sort()
new_list = [my_list[i] for i in randIndex]

Duplicate of https://stackoverflow.com/a/49682832/4383027

A: You could just:
from random import randint

foo = ["a", "b", "c", "d", "e"]

print(foo[randint(0,4)])

A: I propose a script for removing randomly picked up items off a list until it is empty:
Maintain a set and remove randomly picked up element (with choice) until list is empty.
s=set(range(1,6))
import random

while len(s)>0:
  s.remove(random.choice(list(s)))
  print(s)

Three runs give three different answers:
>>>
set([1, 3, 4, 5])
set([3, 4, 5])
set([3, 4])
set([4])
set([])
>>>
set([1, 2, 3, 5])
set([2, 3, 5])
set([2, 3])
set([2])
set([])

>>>
set([1, 2, 3, 5])
set([1, 2, 3])
set([1, 2])
set([1])
set([])

A: This may already be an answer, but you can use random.shuffle. Example:
import random
foo = ['a', 'b', 'c', 'd', 'e']
random.shuffle(foo)

A: foo = ['a', 'b', 'c', 'd', 'e']
number_of_samples = 1

In Python 2:
random_items = random.sample(population=foo, k=number_of_samples)

In Python 3:
random_items = random.choices(population=foo, k=number_of_samples)

A: Use random.choice():
import random

foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))

For cryptographically secure random choices (e.g., for generating a passphrase from a wordlist), use secrets.choice():
import secrets

foo = ['battery', 'correct', 'horse', 'staple']
print(secrets.choice(foo))

secrets is new in Python 3.6. On older versions of Python you can use the random.SystemRandom class:
import random

secure_random = random.SystemRandom()
print(secure_random.choice(foo))

A: NumPy solution: numpy.random.choice
For this question, it works the same as the accepted answer (import random; random.choice()), but I added it because the programmer may have imported NumPy already (like me)
And also there are some differences between the two methods that may concern your actual use case.
import numpy as np
np.random.choice(foo) # randomly selects a single item

For reproducibility, you can do:
np.random.seed(123)
np.random.choice(foo) # first call will always return 'c'

For samples of one or more items, returned as an array, pass the size argument:
np.random.choice(foo, 5)          # sample with replacement (default)
np.random.choice(foo, 5, False)   # sample without replacement

A: If you want to randomly select more than one item from a list, or select an item from a set, I'd recommend using random.sample instead.
import random
group_of_items = {'a', 'b', 'c', 'd', 'e'}  # a sequence or set will work here.
num_to_select = 2                           # set the number to select here.
list_of_random_items = random.sample(group_of_items, num_to_select)
first_random_item = list_of_random_items[0]
second_random_item = list_of_random_items[1]

If you're only pulling a single item from a list though, choice is less clunky, as using sample would have the syntax random.sample(some_list, 1)[0] instead of random.choice(some_list).
Unfortunately though, choice only works for a single output from sequences (such as lists or tuples).  Though random.choice(tuple(some_set)) may be an option for getting a single item from a set.
EDIT: Using Secrets
As many have pointed out, if you require more secure pseudorandom samples, you should use the secrets module:
import secrets                              # imports secure module.
secure_random = secrets.SystemRandom()      # creates a secure random object.
group_of_items = {'a', 'b', 'c', 'd', 'e'}  # a sequence or set will work here.
num_to_select = 2                           # set the number to select here.
list_of_random_items = secure_random.sample(group_of_items, num_to_select)
first_random_item = list_of_random_items[0]
second_random_item = list_of_random_items[1]

EDIT: Pythonic One-Liner
If you want a more pythonic one-liner for selecting multiple items, you can use unpacking.
import random
first_random_item, second_random_item = random.sample({'a', 'b', 'c', 'd', 'e'}, 2)

A: The recommended numpy way is now to use an explicit RNG:
from numpy.random import default_rng

rng = default_rng()
rng.choice(foo)

A: If you also need the index, use random.randrange
from random import randrange
random_index = randrange(len(foo))
print(foo[random_index])

A: If you need the index, just use:
import random
foo = ['a', 'b', 'c', 'd', 'e']
print int(random.random() * len(foo))
print foo[int(random.random() * len(foo))]

random.choice does the same:)

A:
How to randomly select an item from a list?
Assume I have the following list:
foo = ['a', 'b', 'c', 'd', 'e']

What is the simplest way to retrieve an item at random from this list?

If you want close to truly random, then I suggest secrets.choice from the standard library (New in Python 3.6.):
>>> from secrets import choice         # Python 3 only
>>> choice(list('abcde'))
'c'

The above is equivalent to my former recommendation, using a SystemRandom object from the random module with the choice method - available earlier in Python 2:
>>> import random                      # Python 2 compatible
>>> sr = random.SystemRandom()
>>> foo = list('abcde')
>>> foo
['a', 'b', 'c', 'd', 'e']

And now:
>>> sr.choice(foo)
'd'
>>> sr.choice(foo)
'e'
>>> sr.choice(foo)
'a'
>>> sr.choice(foo)
'b'
>>> sr.choice(foo)
'a'
>>> sr.choice(foo)
'c'
>>> sr.choice(foo)
'c'

If you want a deterministic pseudorandom selection, use the choice function (which is actually a bound method on a Random object):
>>> random.choice
<bound method Random.choice of <random.Random object at 0x800c1034>>

It seems random, but it's actually not, which we can see if we reseed it repeatedly:
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')

A comment:

This is not about whether random.choice is truly random or not. If you fix the seed, you will get the reproducible results -- and that's what seed is designed for. You can pass a seed to SystemRandom, too. sr = random.SystemRandom(42)

Well, yes you can pass it a "seed" argument, but you'll see that the SystemRandom object simply ignores it:
def seed(self, *args, **kwds):
    "Stub method.  Not used for a system random number generator."
    return None

A: I usually use the random module for working with lists and randomization:
import random
foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))

A: In short, use random.sample method
The sample method returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples.
import random
lst = ['a', 'b', 'c', 'd', 'e']
random.seed(0)  # remove this line, if you want different results for each run
rand_lst = random.sample(lst,3)  # 3 is the number of sample you want to retrieve
print(rand_lst)

Output:['d', 'e', 'a']

here is a running code
https://onecompiler.com/python/3xem5jjvz

A: We can also do this using randint.
from random import randint
l= ['a','b','c']

def get_rand_element(l):
    if l:
        return l[randint(0,len(l)-1)]
    else:
        return None

get_rand_element(l)


text:
Q: Python: run a process inside a windows host I need to run a process inside a windows host from a linux host using python.
I saw WMI python library but seems to work only from a windows host, not linux, how can I do?
I neeed something like PSEXEC, but it works only for windows.

A: Since you cannot install anything on the windows host, does it have openoffice, or libreoffice installed?
You coult then use the Python interpreter bundled with it to create a python script that listens to xmlrpc and get you job done, controling this script remotely.
If there is no Python installed on the windows side, and yur remote host is Linux, there is this recipe here: http://code.activestate.com/recipes/577945-execute-remote-commands-on-windows-like-psexec/
It does depend on windows - as it imports win32wnet - in my experience, these windows specific modules will run fine in a Windows python installed on a Wine configuration on a Linux machinne.

A: An easy solution is to run a SSH server on the windows box and use the paramiko library on the client side.


text:
Q: Warning while using strlen in C I am new to C programming.I am trying to take input from a file line by line and print length of each line.
This is my code-
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main()
 {

    char name[100];
    printf("Enter file name\n");
    scanf("%s",name);

    FILE * input;
    input=fopen(name,"r");

    char line[100];
    fscanf(input,"%s",line);

    while(!feof(input))
    {

        printf("%d\n",strlen(line));
        fscanf(input,"%s",line);
    }

    return 0;
 }

This is my input file-
172.24.2.1
172.24.2.225
172.17.4.41
172.24.4.42
202.16.112.150
172.24.152.10

This  is correctly printing the length of each line.But during compilation I get this warning-
In function 'main':
main.c:24:4: warning: format '%d' expects argument of type 'int', but argument 2 has type 'size_t' [-Wformat=]
    printf("%d\n",strlen(line));

So my question is why am I getting this warning although my output is correct and how can I fix this?
Thanks in advance.

A: The function strlen returns an object of type size_t (cf. ISO 9899:2011§7.24.6.3). You need to specify that the argument you pass to printf has type size_t, as opposed to int. You can do that by adding a z length modifier (cf. ISO 9899:2011§7.21.6.1/7) specifying an object of type size_t. You should also use the u formatting specifier as size_t is an unsigned type.
printf("%zu\n",strlen(line));


text:
Q: Admob shows test ads but not real ads in beta version? i uploaded my app in beta version, my app is showing test interstitial ads instead of real ads but banner ads working fine. please anyone tell me is there any rule BETA show test ads instead of real ads whether banner is showing real.

A: No, look for "ca-app-pub-3940256099942544/1033173712" in your code, this is the id for a test ad. It must be there somewhere.
See https://developers.google.com/admob/android/test-ads


text:
Q: how to create a git repo with subfolders that contain files? when pushing my local repo (which is composed of multiple subfolders that contain my files) to github, the names of the folders are listed on the github repo but they aren't designated as folders/don't have any files in them that I can access... How can I get this to work?

A: Check if your subfolder (that you are pushing) include a .git/ in them.
That would make them nested git repo (or even submodule, if you have a .gitmodule in your main repo)
As such, their gitlink (special entry in the index) would be shown on GitHub as an empty gray folder.


text:
Q: Using linq to find an object which contains any values I am currently having an issue with extracting the desired car, which has a tire and engine combinations, which is part of the list tires and list of engines.
I have this setup:
using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public class EngineType
    {
        public string engineName;
    }

    public class Tire
    {
        public string tireName;
    }

    public class Car
    {
        public EngineType enginetype;
        public Tire tire;
    }

    public static void Main()
    {
        List<Car> cars = new List<Car>();
        cars.Add(new Car{enginetype = new EngineType{engineName = "enginea"}, tire = new Tire{tireName = "tirea"}});
        cars.Add(new Car{enginetype = new EngineType{engineName = "engineb"}, tire = new Tire{tireName = "tireb"}});
        cars.Add(new Car{enginetype = new EngineType{engineName = "enginec"}, tire = new Tire{tireName = "tirec"}});

        List<Tire> tires = new List<Tire>();
        tires.Add(new Tire{tireName = "tirea"});
        tires.Add(new Tire{tireName = "tired"});
        tires.Add(new Tire{tireName = "tiree"});

        List<EngineType> engineTypes = new List<EngineType>();
        engineTypes.Add(new EngineType{engineName = "enginea"});
        engineTypes.Add(new EngineType{engineName = "engined"});
        engineTypes.Add(new EngineType{engineName = "enginec"});

        var selectedcars = cars.Where(x=> engineTypes.Contains(x.enginetype) && tires.Contains(x.tire));

        Console.WriteLine(selectedcars.Count);
    }
}

this though gives me an error, since selectedcars dont contain the cars which
why not?
fiddle: https://dotnetfiddle.net/WcVcnr

A: You compare differents objects having the same value so it cannot works.
You have multiple options to solve that :
First option : Use the values
   IEnumerable<Car> selectedcars = cars.Where(x => engineTypes.Select(e => e.engineName).Contains(x.enginetype.engineName) && tires.Select(t => t.tireName).Contains(x.tire.tireName));

This line will extract the value to compare them so no matter if it's the same object or not.
Obviously if you don't care at all about the objects you could simply not use them :
        var tires = new []
        {
            "tirea",
            "tired",
            "tiree"
        };

        var engineTypes = new []
        {
            "enginea",
            "engined",
            "enginec"
        };

        IEnumerable<Car> selectedcars = cars.Where(x => engineTypes.Contains(x.enginetype.engineName) && tires.Contains(x.tire.tireName));

By the way, if just a string is enough for you and you don't care to really have a "Tire" or "EngineType" class you can just enum.
Second option : Records
If you're in C# 9 or above and you only care about the value inside Tire and EngineType (so only the value of the inner fields, no matter if those are differents objects) you can use the "record" feature. With that mechanism when comparing two objects only the values will be taken into account, not the reference :
    public record EngineType
    {
        public string engineName;
    }

    public record Tire
    {
        public string tireName;
    }

Third option: Implement the Equals (Proposed by @Tim Schmelter in the comment)
If you love the previous solution but you cannot use the "record" feature, you can ensure your class implement the "IEquatable" interface. That way you can indicate how you want think to be compared (instead of the reference):
        public class EngineType
    {
        public string engineName;

        public bool Equals(EngineType other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return engineName == other.engineName;
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;
            return Equals((EngineType) obj);
        }

        public override int GetHashCode()
        {
            return (engineName != null ? engineName.GetHashCode() : 0);
        }
    }

    public class Tire
    {
        public string tireName;

        protected bool Equals(Tire other)
        {
            return tireName == other.tireName;
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != this.GetType()) return false;
            return Equals((Tire) obj);
        }

        public override int GetHashCode()
        {
            return (tireName != null ? tireName.GetHashCode() : 0);
        }
    }

(This code has been generated so I assumed it's correct)
And your query can still the same :
var selectedcars = cars.Where(x => engineTypes.Contains(x.enginetype) && tires.Contains(x.tire));

Fourth option: Implement a comparer (Proposed by @Tim Schmelter in the comment)
If you still like the previous options but you cannot modify the objects itself (maybe it has been generated or is part of a nuget package, ...) you can implement outside of them a comparer :
    public class EngineTypeComparer : IEqualityComparer<EngineType>
    {
        public bool Equals(EngineType x, EngineType y)
        {
            return x.engineName == y.engineName;
        }

        public int GetHashCode(EngineType obj)
        {
            return obj.x.engineName.GetHashCode(); }

    }

    public class TireComparer : IEqualityComparer<Tire>
    {
        public bool Equals(Tire x, Tire y)
        {
            return x.tireName == y.tireName;
        }

        public int GetHashCode(Tire obj)
        {
            return obj.tireName.GetHashCode();
        }
    }

(The null check are not implement in those comparer but obviously it should be);
And in the query you have to specify wich comparer you want to use :
   var selectedcars = cars.Where(x => engineTypes.Contains(x.enginetype, new EngineTypeComparer()) && tires.Contains(x.tire, new TireComparer()));


text:
Q: Design-Time drag and drop I'm currently working of a project where my part is to design a Design Surface where the end user can add/remove/move controls at run-time.
I followed this tutorial "Hosting Windows Forms Designers, by Tim Dawson", and almost have implemented all the features I need.
Short story for those who don't want to read the tutorial : I implemented IDesignerHost, IContainer, ISelectionService, IToolboxService and some other interface, to create my design surface. I didn't use the System.ComponentModel.Design.DesignSurface already in the framework, mainly beacause I need a really custom design surface.
Question :
I want to allow user to drag & drop new Control from the IToolboxService to the IDesignerHost/IContainer. In this tutorial, you clic on a Control in the toolbox, the click on the design surface to add the control.
What i've found :

*

*There is a built-in feature that
automagically does drag & drop from
IToolboxService to
System.ComponentModel.Design.DesignSurface but it is clearly not working if you implement IDesignerHost from nothing.

*When you use the
Control.DoDragDrop(ToolboxItem)
method, to initiate a drag & drop :

*

*IToolboxService.SerializeToolboxItem(ToolboxItem)
is called to serialize the item

*IToolboxService.IsToolboxItem(object)
and
IToolboxService.IsSupported(object)
are called to evaluate if the
serialized ToolboxItem can be allowed
to be droped on the design surface

*When you drop the control : IToolboxService.DeserializeToolboxItem(object serializedObject) is called by the design surface to deserialize the controldropped.

*IToolboxService.SetCursor() is called to know if you define a custom cursor, or let the standard windows cursor.
Problem :
I implemented all mentionned above, in the "What i've found", but the drag & drop is buggy :

*

*I drag, everything's fine, but when
hovering the design surface, my
cursor blink a little between
standard cursor and the
"DragDropEffects.Copy" style.

*When I drop, nothing happens, and when my cursor leave the design surface (after I dropped), then the new Control is created and added where I dropped it.

Has anyone ever tried to do what I'm doing, and if so, how did you manage it ?
Is there anyone that has any pointer/link/good advices ?
Thank you =)

A:
Is there anyone that has any
  pointer/link/good advices?

Your issue seems to be addressed by the Microsoft Connect issue Mouse Events Consumed / Not Raised in 2.0 Designers. This issue is all but easy to grasp though, but apparently the upgrade from .NET Framework 1.1 (2003) to 2.0 (2006) implied a change in drag & drop behavior - given that the article you mentioned stems from 2003 this could well be related. Specifically you should scroll ahead to section Issue 2, citation:

You will now notice constant
  flickering when dragging over the
  form. This is partially caused by the
  new drag-drop behavior in 2.0.

I'm unable to dig deeper into this right now myself but you might also be able to figure something from Customize Drag & Drop in the Designer, which addresses changed behavior regarding drag & drop between Visual Studio versions 2003 and 2005; quite likely this might be related and one of the accepted answers does in fact specifically reference the Microsoft Connect issue above, plus it offers more hints towards possible solutions too.

A: Me to worked on this questions for one day ago. This is my solution that found for my project like yours.

*

*I drag, everything's fine, but when hovering the design surface, my cursor blink a little between standard cursor and the "DragDropEffects.Copy" style.
This is my toolboxservice.
class EasyAccordionToolboxService : AccordionControl, IToolboxService
{
    EasyAccordionControlElement _SelectedElement;
    public Control DesignPanel { get; set; }

    public EasyAccordionToolboxService()
    {
        AddAccordions();
        AllowItemSelection = true;
        base.ElementClick += EasyAccordionToolboxService_ElementClick;
    }

    private void EasyAccordionToolboxService_ElementClick(object sender, ElementClickEventArgs e)
    {
        if (e.Element.Level == 1) this._SelectedElement = e.Element as EasyAccordionControlElement;
    }

    public ToolboxItem GetSelectedToolboxItem()
    {
        if(_SelectedElement != null)
        {
            var selectedToolboxItem = this._SelectedElement.ToolBoxItem;
            this._SelectedElement = null;
            return selectedToolboxItem;
        }
        else
        {
            return null;
        }
    }

        public bool SetCursor()
    {
        if(this._SelectedElement == null)
        {
            this.DesignPanel.Cursor = Cursors.Default;
        }
        else
        {
            this.DesignPanel.Cursor = Cursors.Hand;
        }

        return true;
    }

There are "DesignPanel" property and "SetCursor" methods. DesignPanel property is control referred to view of root designer.

*When I drop, nothing happens, and when my cursor leave the design surface (after I dropped), then the new Control is created and added where I dropped it.
There is GetSelectedToolboxItem method in EasyAccordionToolBoxService implemented from IToolboxService. GetSelectedToolboxItem is your answer.
Finally,
        designer = new EasyDesignSurface(propertyGrid);

        var rootForm = (Form)designer.CreateComponent(typeof(Form));
        rootForm.Name = "rootForm";
        rootForm.Text = "BELGE";
        rootForm.TopLevel = false;
        rootForm.Size = new Size(600, 600);
        designer.ComponentContainer.Add(rootForm);

        var view = (Control)designer.View;
        view.Dock = DockStyle.Fill;
        designPanel.Controls.Add(view);

        easyAccordionToolboxService1.DesignPanel = view;
        designer.AddService(typeof(IToolboxService), easyAccordionToolboxService1);


text:
Q: Hide files & folders in jQuery File Tree I am using jQuery File Tree to display a directory listing, toghether with the standard PHP connector provided with the File Tree code.
Everything works fine, but I need to filter the listing to avoid the inclusion of hiden files and not desired folders. My skills in PHP or JS doesn't allow me to go futher than pasting here the code, with the hope I can get some extra lines to hide unwanted files according to certain pattern/s.
Thanks!
The HTML code:

<link rel="stylesheet" href="../../js/ft/jqueryFileTree.css">

And the PHP code:
<?php
$_POST['dir'] = urldecode($_POST['dir']);

if( file_exists($_POST['dir']) ) {
   $files = scandir($_POST['dir']);
   natcasesort($files);
   if( count($files) > 2 ) { // The 2 accounts for . and ..
      echo "
";
      // All dirs
      foreach( $files as $file ) {
         if( file_exists($_POST['dir'] . $file) && $file != '.' && $file != '..' && is_dir($_POST['dir'] . $file) ) {
            echo "
" . htmlentities($file) . "
";
         }
      }
      // All files
      foreach( $files as $file ) {
         if( file_exists($_POST['dir'] . $file) && $file != '.' && $file != '..' && !is_dir($_POST['dir'] . $file) ) {
            $ext = preg_replace('/^.*\./', '', $file);
            echo "
" . htmlentities($file) . "
";
         }
      }
      echo "
";
   }
}

?>

PS: original source comming from here

A: I am not familiar with jQuery File Tree but I believe that the key to your issue lies inside the loops.
The only thing you need to do is create a blacklist, an array with the name of the folders/files you dont want to show.
$blacklist = array('namefile1', 'namefolder1', 'namefile2');

And then implement a check inside the loop, so that it skips the name if the file/folder name matches one that is inside the blacklist (case sensitive).
foreach( $files as $file )
{
     if (in_array($file, $blacklist))
         continue;

     .... the rest of the code ...
     .... goes here ..............
}

That is basically what you need to do. You could also use regular expressions and the preg_match function, to make it more flexible..


text:
Q: Alternative of AbpSession.Use() in abp framework (abp.io) In asp.net boilerplate, we can use IAbpSession.Use(userId, tenantId) to override current session.
When I upgraded to abp framework (abp.io), I don't know how to migrate it.
I found only CurrentTenant.Change(tenantId) to override current tenant, but I can't find any way to change current user.

A: I found that
https://docs.abp.io/en/abp/latest/CurrentUser#changing-the-current-principle
It seems that, the CurrentUser in abp framework works with principal instead of UserId only.

If you don't make sense about pricipal, please reference Claims-based authentication, the principal is an identity that contains several claims.

So if we want impersonating an user, we should replace the whole principal.
There is an open issue about it: https://github.com/abpframework/abp/issues/1082


text:
Q: PC whirring sound, until physically touched (Video included) When I turn on my PC, it starts making a whirring sound.
This noise sometimes stops on its own after 15-30 minutes, but sometimes it doesn't until I physically touch it.
Turn up your volume a bit if you need to: VIDEO
I had my PC without a side panel for a week, and the problem did not occur during this time.
(Yes I am aware it was a bit dusty at the time of recording, but that is no longer the case, and it occurs regardless)
If it helps, I am running Linux Mint 17
Edit
If I were to reboot my computer after the noise is over, the noise does not come back up. Because of this, I feel like something is "warming up".

A: There are two things I noticed:

*

*The little figurine sitting on top of the case may be causing sound from vibrations.

*With the PC sitting on the floor, it may need a good cleaning. It is possible fan has dirt stuck to the blades. This can cause the fan to spin off balance causing vibration and premature bearing failure.
I know you said you cleaned it, but should pay special attention to the fan(s) and use a small brush to break loose an caked on dirt from the blades. If that was done and sound is still an issue, replace the fan. Either way, the cleaning won't hurt.


text:
Q: In iPhone devices, how can I download Video and photo both via a single click from web? I have one web page, where I am displaying the live photos(Combination of photo and video). I would like to download both photo and video after clicking on the download button.
I got succeed to download it in Chrome and Mozilla browser of the desktop but it gets to fail in iPhone devices.
Please suggest.
Thank you in advance.
Here is my code:
Download Image


text:
Q: How to use Map[List[String], String]? I have a map:
val m: Map[List[String], String] = Map (
    List("banana", "melon", "apple") -> "fruit",
    List("chair", "table", "wardrobe") -> "furniture")

How to check, what is e.g. banana? This ofc doesn't work:
scala> m("banana")

I could split the lists into single entries String -> String, but there are lots of them, so I prefer List[String] -> String.

A:
I could split the lists into single entries String -> String, but there are lots of them, so I prefer List[String] -> String.

That doesn't sound like a very good reason to me. The whole point of using a map is easy and quick access to values. Using a list as the key type when you'll be looking up values by elements of that list just makes it hard to use the map, while giving almost no advantages.
I suggest you "flatten" your map, so one key maps to one value with possibly duplicate values:
val m: Map[List[String], String] = Map(
  List("banana", "melon", "apple") -> "fruit",
  List("chair", "table", "wardrobe") -> "furniture"
)

val flattenedMap = m.flatMap { case (keys, value) =>
  keys.map(_ -> value)
}

flattenedMap("banana")

If you're not yet comfortable with using flatMap, you can use a for-comprehension instead, which works very nicely on this example:
val m: Map[List[String], String] = Map(
  List("banana", "melon", "apple") -> "fruit",
  List("chair", "table", "wardrobe") -> "furniture"
)

val flattenedMap: Map[String, String] = for {
  (keys, value) <- m // for each list of keys and value in your map
  key <- keys        // and for each key from the list of keys
} yield (key, value) // create a pair of key and value

This yields the same result as the example with flatMap above.
Or you could just initialize your Map as a "flattened" map immediately:
val flattenedMap: Map[String, String] = Map(
  "banana" -> "fruit",
  "melon" -> "fruit",
  "apple" -> "fruit",
  "chair" -> "furniture",
  "table" -> "furniture",
  "wardrobe" -> "furniture"
)

flattenedMap("banana")

A: Ok, got it. I can use foreach to check every key:
m foreach (x => println(x._1.contains("banana")))

A: You could also use this:
 map.keys.flatten.exists(s => s == "banana")

The flatten maps all lists of lists to a single list. exists checks if banana is in that list.

A: If it's a one-off lookup, then any lazy (the one that does not create unnecessary container copies) combo would do (I normalized them all to return Option):
m.withFilter(_._1.contains("banana")).map(_._2).headOption
// or
m.find(_._1.contains("banana")).map(_._2)
// or
(for ((k, v) <- m.toStream if k.contains("banana")) yield v).headOption

Otherwise, if this query needs to run often you might want to change this data structure for faster lookups with
val mm: immutable.Map[String, String] = m.flatMap{ case (k,v) => k.map(_ -> v)}
...
print(mm["banana"])


text:
Q: python to Java checksum calculation I received this python script that generates a file checksum:
import sys,os

if __name__=="__main__":
#filename=os.path.abspath(sys.argv[1])
#filename=r"H:\Javier Ortiz\559-7 From Pump.bin"
cksum=0
offset=0
pfi=open(filename,'rb')
while 1:
  icks=0
  chunk=pfi.read(256)
  if not chunk:  break     #if EOF exit loop

  for iter in chunk:
    icks+=ord(iter)
    print ord(iter)
  cksum=(cksum+icks) & 0xffff
pfi.close()
print "cksum=0x%4.4x"%cksum

And I'm trying to convert it to Java but I'm not geting the same results.
Here's my Java code:
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ChecksumCalculator {

private ChecksumCalculator() {
}

public static int getChecksum(File file) {
    int cksum = 0;
    FileInputStream fis = null;
    BufferedInputStream bis = null;
    DataInputStream dis = null;
    try {
        fis = new FileInputStream(file);

        // Here BufferedInputStream is added for fast reading.
        bis = new BufferedInputStream(fis);
        dis = new DataInputStream(bis);
        byte[] buffer = new byte[256];
        // dis.available() returns 0 if the file does not have more lines.
        while (dis.read(buffer) != -1) {
            int icks = 0;
            for (byte b : buffer) {
                icks += b & 0xff;
                System.out.println(b & 0xff);
            }
            cksum = (cksum + icks) & 0xffff;
            System.out.println("Checksum: " + cksum);
        }

        // dispose all the resources after using them.
        fis.close();
        bis.close();
        dis.close();
        return cksum;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return -1;
    } catch (IOException e) {
        e.printStackTrace();
        return -1;
    }
}

static public void main(String[] s) {
    System.out.println("0x" + getChecksum(new File("H:\\Javier Ortiz\\559-7 From Pump.bin")));
}

}
But I get different results on a file. For example if I run it on a plain txt file containing only the word test it gives out the following result:
python: cksum=0x01c0
java: cksum=0x448
Any idea?

A: Your Python version prints the checksum in hex, while your Java version prints it in decimal. You should make your Java version print in hex, too. 0x1c0 == 448.
To use the cksum=0x%4.4x format string as you had in your Python version, use this:
System.out.printf("cksum=0x%4.4x%n", ...);

or even better
System.out.printf("cksum=%#04x%n", ...);

Also, you don't need a DataInputStream for this. Just use bis.read(buffer) instead of dis.read(buffer).

A: 1C016 = 44810
I think that's your problem.

A: *

*dis.read(buffer) returns the number of bytes that was actually read. For the last chunk, it will probably be less than 256. So the for loop shouldn't always be performed 256 times - it should be performed as many times as the actual byte count that was read from the stream.

*I'm not a Python developer, but it doesn't look like ord(icks) in Python does the same as b & 0xff in Java.

*Keep in mind that all Java types are signed; this might affect the calculation.
Also, although this doesn't affect correctness - it's a good practice to clean all the resources (i.e. to close the streams) in a finally block.


text:
Q: Connecting an FM radio receiver circuit to a speaker via 3.5 mm audio jack? As an experiment and for educational purposes, I wanted to build and connect an FM receiver to some old computer speakers via a 3.5 mm audio jack.
So I tried building a circuit like this on a bread board
My FM receiver circuit with pre-amp to 3.5 mm audio jack
Note: The 22pf capacitor on the far left is actually a variable capacitor that I can adjust between 8pf and 40pf.  And hopefully, I used falstad correctly to depict my actual circuit.
The circuit on the left consisting of the two transistors is something I found in most FM receiver tutorials.  And I figure I couple it to a NPN transistor pre-amplifier circuit on the right.  I then connect the output to the tip of a 3.5mm jack.
When I power up the circuit, my speakers are silent.  If I touch the antenna with my fingers, my speakers produce a low frequency hum.  I disconnected the 3.5 mm jack and hooked up an oscilloscope probe to the output and confirmed there is no signal...in fact I don't even see any noise waveform unless I touch the antenna with my fingers.
Does anyone have suggestions on what I might do next to receive an FM radio signal or at least noise from a blank FM channel?


text:
Q: Show P is linear if it is convex and positive homogenious functional it might be too simple but I couldnt show the second part
L linear real space
$P:L\rightarrow \Bbb R$ is called positive homogenious functional if for every $x\in L$ and $\alpha\ge 0$ , $P(\alpha x)=\alpha P(x)$
$P(x+y)=P(2\frac{(x+y)}2)=2P(\frac x2+\frac y2)\le2(\frac12P(x)+\frac 12P(y))=P(x)+P(y)$
so $P(x+y)\le P(x)+ P(y)$
(should'nt it be homogenious only? I mean for all $\alpha \in \Bbb R, P(\alpha x)=\alpha P(x) $)
edit: my second trying is:
$P(x+y)=-2\frac 12P(-x+(-y))$
$\frac 12P(-x+(-y))+\frac 12P(y)\ge \frac12 P(-x)$ (because it is convex function)
when we choose $-x-y=x_1$ and $y=x_2$
it follows that
$\frac 12P(x_1)+\frac 12P(x_2)\ge \frac12 P(x_1+x_2)$
so
$P(x+y)=-2\frac 12P(-x-y))\ge -2\Bigg(\frac 12 P(-x)+\frac 12 P(-y)\Bigg)=-\Bigg(P(-x)+P(-y)\Bigg)=P(x)+P(y)$
thus
$P(x+y)\ge P(x)+P(y)$  and $P(x+y)=P(x)+P(y)$
I'm not sure $-x-y=x_1$ and $y=x_2\in L $ is this correct?


text:
Q: Is there a name for a application structure or design pattern for multilayer UI Is there a name for a application structure or design pattern for a multi-layer UI?
For exemple, lets say I have a web application using multiple layers of <div>:
Layer0 = background image,
Layer1 = Left button "<-",
Layer2 = Center button "*",
Layer3 = Right button "->"
All layers are the same size but they have different transparencies.
Layer0 would be 100% in size and all black,
Layer1 would be 100% in size but transparent with a "<-" arrow pointing left on one third of the screen,
Layer2 would be the same as Layer1 but with an "*" (dot) in the middle third of the screen
Layer3 would have the same as layer1 but arrow point right "->".
And by interacting with the screen, the client would change the layers order with, lets say javascript, the layers would change position to "bring up" certain element or even hide some by "bringing them down".
So layers order could be 1, 3, 0, 2 or it could even have more layer with static content inside them so the order could be 0, 5, 6, 1, 3, 25, 36, 19, 10, 8, 9... etc.
So is there a name for those application? or design pattern? or application structure?
And is this bad practice? (Ok, this is probably a matter of likes or dislikes) so lets change this for:
Is there a best case scenario where this would theoretically work best, or is there a case where this is not a good idea?
Thanks!

A: This is a good question.
The whole idea of using layers in design is to achieve separation. However, in ui frameworks, layers often literally just mean layers, as in what gets drawn on top of what.
Sounds like what you want to do is have a way to dynamically reorder the layers. So yeah, there are some possible design patterns you could consider.
The main one would be Chain of Responsibility. If you look at the section in the Gang of Four on this pattern, they in fact talk about many ui frameworks, including NextStep, which had the notion of a Responder Chain (which is now the backbone of iOS and MacOS).
In general, CoR is implemented with each member of the chain holding a reference only to its successor. So if you were going to allow people to reorder the elements, that would most likely be done through one more more splice operations. So you could easily define such an operation that would insert a layer in between two existing ones: it would have to put itself as the successor of the link it was going to follow and then set the next item as its own successor.
The other Design Pattern that might apply would be Decorator. Sometimes, you want to add something to what is being painted, but you still want to have the basic painting occur, for instance, scrolling is often added with a Decorator because the main panel can be unchanged, and the logic for which bars appear, where the thumbtacks are and how to respond to them, are completely isolated from the original drawing code.
The general point that covers both cases: separate the components by responsibility.


text:
Q: Why is jquery's .data() method needed In the following  getElementsByTagName("p")[0] and getElementById("demo") access the same element.
Both of the following work, so I can't figure out why the jquery data function is even needed. Is the second not portable to all browsers.
$(document.getElementsByTagName("p")[0]).data("funcZ", function() {console.log("ZZZZZ")})

$(document.getElementById("demo")).data("funcZ")()

document.getElementsByTagName("p")[0].funcX = function() {console.log("XXXXX")}

document.getElementById("demo").funcX()

A: According the the jQuery website:

The jQuery.data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore free from memory leaks. jQuery ensures that the data is removed when DOM elements are removed via jQuery methods, and when the user leaves the page.

It's possible that by attaching random fields to a DOM element, when the DOM element disappears, the fields remain in memory. It looks like jQuery handles that for you.

A: The $.data() method is perfect for hiding data as opposed to attaching it to a data-attribute. It's easily accessed by key/value, great for storing state information when creating plugins, or really anything.


text:
Q: \textbullet in Same font If I use any font as my base font, e.g., AGaramond, then if I use the tag \textbullet then the bullet should come from AGaramond family only, how can I achieve this. Note that I am using MikTeX V2.9 and converted fonts from OTF to MikTeX compatibility using autoinst option.
Hope this may not require MWE, if requires I'll post it...

A: T1 encoding does not have a bullet, so in that case you need to use the TS1 symbol companion font encoding (which \textbullet will do by default) so you just need to ensure that you have a TS1 encoded subset of your OTF font.
Alternatively you could use LY1 encoding instead of TS1 in which case there is a bullet, which again \textbullet will use by default.


text:
Q: How should I get API token before executing Unit Test cases? Within my unit test cases, I'm trying to do unit tests against some data in the API therefore an API token is required. I'm hoping to find a way to call token API and store it in Redux before firing any API.
I'm aware of setup.js in Jest, tried calling my API there and store in Redux didn't work well. I don't think the setup.js waited the method to finish completely before starting the unit test.
// Within the Setup.js, I was calling method directly
const getAPItoken = async() => {
     await getToken();
}
getAPItoken();

Currently I'm getting the API token in 1 of the Unit Test files. Upon the method completion, rest of the Unit Tests will run fine since they are getting the API token from Redux.
Sample of what I'm doing now
describe('Get API token', () => {
  test('it should return true after getting token', async () => {

    // Within the method itself, it actually store the token to redux upon receiving from API, also it will return TRUE upon success
    const retrievedToken = await getToken();

    expect(retrievedToken).toBeTruthy();
  });

Is there a better way to handle this?

A: You can use globalSetup. It accepts an async function that is triggered once before all test suites.
So you can optain the API key and set it on node global object so you can access if from anywhere.
// setup.js
module.exports = async () => {
  global.__API_KEY__ = 'yoru API key';
};

// jest.config.js
module.exports = {
    globalSetup: './setup.js',
};


text:
Q: Texture Altas for UIImage, about CGImageCreateWithImageInRect() performance My app has many graphics for the UI.
There is always 1-2 seconds lag when loading so many png files (with [UIImage imageWithContentsOfFile:]).
So I am trying to pack them up into one big 2048*2048 image as a texture altas, like wt I did in rendering texture in OpenGL, to prevent the overhead of file I/O.
Then use CGImageCreateWithImageInRect() to make the sub-images one by one.
The whole process is fast before the images are drawn.
From loading, making sub-images, to adding the UIImageView to my mainview.
But after adding those imageview, it need to wait for a large delay before the animation of my UI starts.
I used the Instrument Time Profiler and found that "png_do_read_transformations" should be the cause.
As I read the documentation, CGImageCreateWithImageInRect() created images only make reference to the data of the original image.
Does this cause the bad performance when I first drawn the image since transformation is needed?
Any approach can solve this problem?
p.s. the delay only appear when I first time add the image. no delay after the first appearance.


text:
Q: Using JCalendar in a JDialog My program uses JDialogs to open up forms and in the form I want to use JCalendar for the user to select a date and for me to use it for other methods afterwards.
I have downloaded JCalendar library. I read some example codes but still not sure how to do it. I have an idea that in the form you press a button (Select Date) and like a small window opens with that JCalendar and when the date is selected it is displayed in the form as a TextField.
Can someone recommend me some method of doing this with the least trouble?

A:
I have an idea that in the form you press a button (Select Date) and
  like a small window opens with that JCalendar and when the date is
  selected it is displayed in the form as a TextField.

You may want to try JDateChooser class present in JCalendar library, which allows selecting a date or type it manually. About the second part, you need to provide a PropertyChangeListener to the date chooser in order to listen the "date" property change and update the text field's text accordingly. For instance something like this:
final JTextField textField = new JTextField(15);

JDateChooser chooser = new JDateChooser();
chooser.setLocale(Locale.US);

chooser.addPropertyChangeListener("date", new PropertyChangeListener() {
    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        JDateChooser chooser = (JDateChooser)evt.getSource();
        SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
        textField.setText(formatter.format(chooser.getDate()));
    }
});

JPanel content = new JPanel();
content.add(chooser);
content.add(textField);

JDialog dialog = new JDialog ();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.getContentPane().add(content);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);


text:
Q: Connection appears accepted server-side but appears to be refused in my python script I have a python script I am running to add a document to a collection for a remote mongodb database. The file is as follows:
from pymongo import Connection
ip    = 'x.x.x.x' #edited out

conn  = Connection()
db    = conn['netmon']

users = db.users
print 'number of users: ' + str(users.count())
if users.count() == 0:
  print 'Please create a new account.'
  t_user = raw_input('Username:')
  users.insert({'username':unicode(t_user)})
conn.close()

When I run this script, I have some interesting behavior. In the server logs, it appears that the connection is accepted, the query is run, and then the connection is closed.
# Mongodb logs
14:27:18 [initandlisten] connection accepted from 108.93.46.75:39558 #1
14:27:18 [conn1] run command admin.$cmd { ismaster: 1 }
14:27:18 [conn1] command admin.$cmd command: { ismaster: 1 } ntoreturn:1 reslen:71 0ms
14:27:18 [conn1] run command netmon.$cmd { count: "users", fields: null, query: {} }
14:27:18 [conn1] Accessing: netmon for the first time
14:27:18 [conn1] command netmon.$cmd command: { count: "users", fields: null, query: {} } ntoreturn:1 reslen:58 10ms
14:27:18 [conn1] end connection 108.93.46.75:39558

However, this is what I get from the python script:
# Python error
> python testmongo.py
Traceback (most recent call last):
  File "testmongo.py", line 7, in <module>
    conn  = Connection()
  File "/usr/local/lib/python2.7/dist-packages/pymongo-2.2.1-py2.7-linux-x86_64.egg/pymongo/connection.py", line 290, in __init__
    self.__find_node()
  File "/usr/local/lib/python2.7/dist-packages/pymongo-2.2.1-py2.7-linux-x86_64.egg/pymongo/connection.py", line 586, in __find_node
    raise AutoReconnect(', '.join(errors))
pymongo.errors.AutoReconnect: could not connect to localhost:27017: [Errno 111] Connection refused
charles@charles-mbp:~/Desktop$ python testmongo.py
Traceback (most recent call last):
  File "testmongo.py", line 7, in <module>
    conn  = Connection()
  File "/usr/local/lib/python2.7/dist-packages/pymongo-2.2.1-py2.7-linux-x86_64.egg/pymongo/connection.py", line 290, in __init__
    self.__find_node()
  File "/usr/local/lib/python2.7/dist-packages/pymongo-2.2.1-py2.7-linux-x86_64.egg/pymongo/connection.py", line 586, in __find_node
    raise AutoReconnect(', '.join(errors))
pymongo.errors.AutoReconnect: could not connect to localhost:27017: [Errno 111] Connection refused
charles@charles-mbp:~/Desktop$ python testmongo.py
Traceback (most recent call last):
  File "testmongo.py", line 7, in <module>
    conn  = Connection()
  File "/usr/local/lib/python2.7/dist-packages/pymongo-2.2.1-py2.7-linux-x86_64.egg/pymongo/connection.py", line 290, in __init__
    self.__find_node()
  File "/usr/local/lib/python2.7/dist-packages/pymongo-2.2.1-py2.7-linux-x86_64.egg/pymongo/connection.py", line 586, in __find_node
    raise AutoReconnect(', '.join(errors))
pymongo.errors.AutoReconnect: could not connect to localhost:27017: [Errno 111] Connection refused

Some useful information:
The remote server is a VPS running on OpenVZ. I know there are compatibility problems related to count() and iterators, but I (assumingly) fixed them by using the --smallfiles option, as well as limiting my nssize to 100. My firewall on both sides are completely open.
I've also noticed that in the errors, autoreconnect is trying to connect to localhost, even though I specified a different IP address.

A: You need to pass the IP - conn = Connection(ip)


text:
Q: Visual Studio Code Remote-SSH Windows 10 ssh-agent.exe issue I installed the Remote-SSH add-on in VS code.  I was able to connect to my server which uses key encrypted login with a passphrase.  This included using Windows 10 ssh-agent as described here:
https://code.visualstudio.com/docs/remote/troubleshooting#_setting-up-the-ssh-agent
# Make sure you're running as an Administrator
Set-Service ssh-agent -StartupType Automatic
Start-Service ssh-agent
Get-Service ssh-agent

After rebooting, I opened VS Code back up and only to find out that I was able to log back into my server without having to enter my passphrase.  To me, this was terribly disturbing. I shutdown and restarted – same thing.
My understanding of agent is that you authenticate once at the beginning of a session and your passphrase should be held (encrypted) in memory and should not persist after the program closes; like how PuTTY, MobaXterm, and any terminal in Linux or Mac operates.
I immediately began cussing out Windows developers for being so stupid, muttering VS code, WSL, open-ssh for windows is a nice try to attract developers, but again a total fail.  ...but maybe I'm missing something or my understanding is incorrect?
It just seems painfully obvious that if you guarded a private key with a passphrase, you would not want that passphrase to persist because that defeats the whole purpose of the passphrase in the first place.  If my client is compromised, so is my server.  Why would one just not just create a private key without a passphrase if they NEVER wanted to enter the password?  I guess if sshd requires both and the person is lazy..?
I came back to my computer 8 hours later and powered it on, very curious to see if agent is still holding my passphrase and key.  I opened up VS code to connect to my remote server and got the following error:

warning: agent returned different signature type ssh-rsa (expected rsa-sha2-512)
mkdir: cannot create directory '/home/myname/.vscode-server': Permission denied
bash: line 48: /home/myname/.vscode-server/bin/
  6129338/vscode-remote-lock.: No such fil
  e or directory
  flock: 99: Installation already in progress...

  Bad file descriptor
  flock: 99: Bad file descriptor
  flock: 99: Bad file descriptor
"install" terminal command done Received install output: flock: 99:
  Bad file descriptor Failed to parse remote port from server output:
  flock: 99: Bad file descriptor

(where  looks like a hex number but I removed it because I'm not sure what I'm dealing with here.)
It looks like there's a manual fix: https://github.com/PowerShell/Win32-OpenSSH/issues/1263 but I'm not even sure I trust Windows now (not that I did before).
How could my key persist across reboots? Is it because of the terrible Windows 10 Cortana Startup "feature" that reopens all your opened programs?  I haven't been able to figure out how to turn this off yet, but I hate it.
 I assume to make this possible, Windows must have to dump memory onto disk, so it's available at startup?  Does this mean my passphrase was stored on disk?
Please tell me I'm wrong.


text:
Q: Get rendered html as text, including newlines I have a page with some html rendered into it.
I want to get the rendered page as text, but somehow also include the  newlines. In addition, if relevant, I'm looking for an extended solution that will also support lists (using spaces and •), tables (using spaces, but with no borders) and similar cases.
I'm looking for Javascript solution, either on client or server side.
Please mind: not every element in the page equals to new line (e.g: some divs can be inline and some can create new lines).
For exapmle, this snippet below will be the html, and the output will be the text itself as you can see below (after running).

#inline{
display:flex;
flex-direction:row;
}

#inline div{
margin-right:5px;
}

#notInline{
display:flex;
flex-direction:column;
}

some

divs

inline

some

divs

on top of each other

A: You can try this. First inline text second "on top of each other" text:
var inlineOutput = '';
document.querySelector('#inline').childNodes.forEach(e=>{inlineOutput += e.textContent + ' '}) + "\n";
console.log(inlineOutput);

var noInLineOutput = '';
document.querySelector('#notInline').childNodes.forEach(e=>{noInLineOutput += e.textContent + " \n"});

console.log(noInLineOutput);

A: There's a js scraper called Cheerio that could extract all the text out for you, I've never used it though. It gives you access to the DOM and you can gather parts of whichever page you need. here's a tutorial that uses it with node.
Not sure if this is what you're looking for, if they're your own pages you can probably make a function that calls everything in the dom and delimits at the open close carats and grabs in the text inbetween, and maybe make a switch if it sees the notInLine class


text:
Q: How to grant dynamodb access to another root account on aws? How to grant dynamodb access to another root account on aws?
My situation: I have a dynamodb filled with some tables created by one root account. This root account is a member of an organization, created by another root account.
The problem: Neither the other root account [organization owner] nor the IAM with Admin permissions created by this root [organization owner] cannot access this dynamodb created by the other root.
Question: Is there a way to grant access to dynamodb from one root to another / to organization created by another root? If so, how to do it?

A: Yes, AWS services owned by one account can be shared with other accounts.
For example it can be done using IAM role. See this tutorial for details.
Please note that working under root account is against of best practises.


text:
Q: Confused about a Javascript closure case I am writing some node.js code using the node-mongodb driver. I decided to cache the collection objects when I obtain them like this:
var db = connectionObject;

function getCollection(collectionName) {
    return function(callback) {
        var cache;

        if (cache) return callback(null, cache);

        db.collection(collectionName, function(err, collection) {
            return err ? callback(err) : callback(null, cache = collection);
        });
    }
}

var usersCollection = getCollection('users');
usersCollection(function(err, collection) {
    collection.find({}); // Rest of code here ...
});

Repeated calls of the usersCollection function should use the cached collection object, except that it doesn't - the cache variable is always undefined. Changing the code to this fixes the problem:
return function(callback) {
    var cache = arguments.callee;

    if (cache.cached) return callback(null, cache.cached);

    db.collection(collectionName, function(err, collection) {
        return err ? callback(err) : callback(null, cache.cached = collection);
    });
}

I am still confused about why the 'cache' variable goes out of scope. What am I doing wrong?

A: I think you want this:
function getCollection(collectionName) {
    var cache;
    return function(callback) {

instead of what you have right now:
function getCollection(collectionName) {
    return function(callback) {
        var cache;

A: Nothing closes over cache after the function returned from getCollection (usersCollection) executes. There is no function that is returned from that scope.
cache needs to be defined outside of the usersCollection function for any reference to it to be captured.


text:
Q: Form data submit to external sheet (google script) I have created a data entry form in google sheets, now I am having trouble saving said entry to an external sheet so far this is what I have, I do not know if I am using the right method to  reference sheet.
please look at comments, thank you
Everytime I am trying to submit the form it is giving lastRow Null

function submitData() {

  //variable declaration for referenceing the active google sheet

  var myGoogleSheet = SpreadsheetApp.getActiveSpreadsheet();
  var shUserForm = myGoogleSheet.getSheetByName('MasterSheet');

  //open external sheet
   var extSS = SpreadsheetApp.openById("1U9SmfPCH9v8maqh6XL0dmRL85TJZfckUV7SAEGM3pQo");
  var datasheet= extSS.getSheetByName("Mastersheet");

  var srcData = shUserForm.getDataRange().getValues();

  //to create the instance of the ui environment to use the alert features

  var ui = SpreadsheetApp.getUi();

  var response = ui.alert("Submit", "Do you want to submit the data?", ui.ButtonSet.YES_NO);

  //checking the user response

  if ( response == ui.NO) {

  return; // to ext from this function

  }

  if ( validateEntry()== true) {

    var blankRow =datasheet.getLastRow() + 1; //identify the next blank row

    //'code to update the database sheet ( write data entry to DB sheet)

    datasheet.getRange(blankRow,1).setValue(srcData.getRange("C7").getValue()); //input number
    datasheet.getRange(blankRow,2).setValue(srcData.getRange("C9").getValue()); //Department
    datasheet.getRange(blankRow,3).setValue(srcData.getRange("C11").getValue()); //Agent Name
    datasheet.getRange(blankRow,4).setValue(srcData.getRange("C13").getValue()); //Hub location
    datasheet.getRange(blankRow,9).setValue(srcData.getRange("C15").getValue()); //order ID
    datasheet.getRange(blankRow,10).setValue(srcData.getRange("C20").getValue()); //type of entry
    datasheet.getRange(blankRow,5).setValue(Session.getActiveUser().getEmail()); //Submitted By, this will automatically get user email
    datasheet.getRange(blankRow,7).setValue(new Date()).setNumberFormat('yyyy-mm-dd h:mm:');
    datasheet.getRange(blankRow,8).setValue(new Date()).setNumberFormat('yyyy-mm-dd h:mm:');
    datasheet.getRange(blankRow,6).setValue(srcData.getRange("C17").getValue()); //comments

    ui.alert(' "New Data Saved - Input #' + shUserForm.getRange("C7").getValue() + '"');

    shUserForm.getRange("C7").clear();
    shUserForm.getRange("C9").clear();
    shUserForm.getRange("C11").clear();
    shUserForm.getRange("C13").clear();
    shUserForm.getRange("C15").clear();
    shUserForm.getRange("C17").clear();

    }

}

A: To save data to another Spreadsheet, You need to open it first by using either openById("insert sheet id here") or openByUrl("insert sheet URL here"). This will return a Spreadsheet class which has getSheetByName("sheet name") method you can use to access the Sheet.
ID of the spreadsheet can be found in the url. This can be found after /d/ or before /edit
Example ID:
https://docs.google.com/spreadsheets/d/12345/edit#gid=0

12345 is the Spreadsheet ID
Example:
Code:
function saveData() {
  //open current sheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = ss.getSheetByName("Sheet1");

  //open external sheet
  var extSS = SpreadsheetApp.openById("Insert External Spreadsheet ID here");
  var extSH = extSS.getSheetByName("Sheet1 External");

  //get data from current Sheet.
  var srcData = sh.getDataRange().getValues();

  //write to external sheet
  extSH.getRange(extSH.getLastRow()+1, 1, srcData.length, srcData[0].length).setValues(srcData);
}

This script will paste the values from Sheet1 to Sheet2
Before:
Sheet1 Data:

Sheet2 Data:

After:
Sheet1 Data:

Sheet2 Data:

*

*SpreadsheetApp.openByID()

*SpreadsheetApp.openByURL()

*Spreadsheet.getSheetByName()

*Class Sheet

*Class Range


text:
Q: How to fix brightness on Ubuntu 14-04 LTS installed on macbook pro 2012 13" I installed Ubuntu 14.04.02 as dual boot in a macbook pro 2012 13  I noticed that all function buttons works but except those that regulate the brightness of the screen.How do I fix this problem?

A: I found an answer to this. However I have an iMac 2011, so it could solve your problem.
You need to edit the grub file /etc/default/grub change the line
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"

to
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash acpi_backlight=vendor acpi_osi=Linux"

Then run:
sudo update-grub

Rebooot your computer and voilà.


text:
Q: order_by intermediate table for given relation in SQL with Django ORM class Nutrient(models.Model):
    tagname = models.CharField(max_length=10)

class FoodNutrientAmount(models.Model):
    nutrient = models.ForeignKey(Nutrient)
    food = models.ForeignKey(Food)
    amount = models.FloatField()

class Food(models.Model):
    nutrients = models.ManyToManyField(
        Nutrient,
        through=FoodNutrientAmount,
    )

So, I can get the Foods ordered by the amount of tagname=FOL Nutrient with a list comprehension:
ordered_fnas = FoodNutrientAmount.objects.filter(
    nutrient__tagname="FOL"
).order_by('-amount')
ordered_foods_by_most_fol = [fna.food for fna in ordered_fnas]

Can I get such an iterable as a queryset without taking the whole thing into memory?
Maybe there is a different approach using Food.objects.annotate or extra? I can't think of a great way to do it at the moment.
I can get close with values_list; but, I get the ordered list of pks and not the queryset of Food objects that I want.
FoodNutrientAmount.objects.filter(
    nutrient__tagname='FOL'
).order_by('-amount').values_list('food', flat=True)

A: Edit:
This is a Many-to-many relationship. So you can probably leverage that. How about adding default ordering to FoodNutrientAmount and then you can just do normal manytomany queries.
class FoodNutrientAmount(models.Model):
    nutrient = models.ForeignKey(Nutrient)
    food = models.ForeignKey(Food)
    amount = models.FloatField()

    class Meta:
        ordering = ('-amount',)

Then you can just call -
nutritious_foods = Food.objects.filter(nutrients__tagname='FOL').order_by('foodnutrientamount')


text:
Q: Is the project's name available in the Unit Output Directory Option using Delphi XE2? I would like to create an common Option Set to set basic settings for the many projects we have, and I would like to direct each project's dcus to separate folder.
I would like to set the "Unit output directory" to something like Build\dcu\$(Platform)\$(Config)\$(ProjectName)
Now there is no such variable as $(ProjectName). Is there somethine else?

A: I had the same problem.
Try \$(Platform)\$(Config)\$(MSBuildProjectName)
That does the job for me.


text:
Q: Using Sync Framework to sync individual rows I have a requirement to sync remote databases to a central database, but the customer wants to be able to choose with rows of data is synched.  For example, if there is a table with 5 rows, the user wants "checkbox functionality" to say only sync rows 1, 4, and 5.
I don't believe Sync Framework does this out of the box. I have only seen where the entire table is synched with a central database.
Is there a way to tell the Sync Framework to sync individual rows of a table?

A: There are ways to filter rows, this is built into all of the sync framework's SQL providers. This MSDN page covers filtering: http://msdn.microsoft.com/en-us/library/ff928701(v=sql.110).aspx.
If it will be as simple as a checkbox to turn rows on/off you can probably just add a bit/boolean field to the table and use that column in the filter clause. Otherwise, you can use data that is relevant to your application - such as the MSDN sample where only sales data for a particular region will be synced.


text:
Q: Infinite loops seemingly not working in NASM? I'm trying to make a DOS program in NASM that uses interrupt 10h to display a pixel cycling through the 16 available colors in the top left corner. I also use interrupt 21h to only make the program run every 1/100 seconds (100 fps).
segment .data
    pixelcolor: db 0
    pixelx: dw 100
    pixely: dw 100
    timeaux: db 0 ; used later on to force the program to run at 100fps
segment .text
    global _start

_start:
    mov ah,00h
    mov al,0dh
    int 10h

    mov ah,0bh
    mov bh,00h
    mov bl,00h
    int 10h

    .infinite:
        mov ah,2ch
        int 21h ; get system time
        cmp dl,timeaux ; if 1/100 seconds haven't passed yet...
        je .infinite ; ...skip current frame
        ; else, continue normally
        mov byte[timeaux],dl

        mov ah,00h
        mov al,0dh
        int 10h
        mov ah,0bh
        mov bh,00h
        mov bl,00h
        int 10h

        mov ah,0ch
        mov al,pixelcolor
        mov cx,pixelx
        mov dx,pixely
        int 10h
        inc byte[pixelcolor]

        jmp .infinite

However, when I actually run the program in DOSBox, the pixel just stays red. Does anyone know why my infinite loops aren't working? (Note: I'm very new to NASM, so honestly I'm not even suprised my programs only work 15% of the time.)

A: The problem isn't actually the loop itself. What the loop is doing each iteration is the problem. Some issues and observations I have are:

*

*Since this is a DOS COM program you will need an org 100h at the top since a COM program is loaded by the DOS loader to offset 100h of the current program segment. Without this the offsets of your data will be incorrect leading to data being read/written to from the wrong memory locations.

*You have a problem with mov al,pixelcolor. It needs to be mov al,[pixelcolor]. Without square brackets1 the offset of pixelcolor is moved to AL, not what is stored at offset of pixelcolor. The same goes for pixelx and pixely. Your code prints the same pixel color (red in your case) to the wrong place2 on the screen repeatedly. This code:
  mov ah,0ch
  mov al,pixelcolor
  mov cx,pixelx
  mov dx,pixely
  int 10h
  inc byte[pixelcolor]

should be:
  mov ah,0ch
  mov al,[pixelcolor]
  mov cx,[pixelx]
  mov dx,[pixely]
  int 10h
  inc byte[pixelcolor]

*It should be noted that the resolution of the timer by default will only be 18.2 times a second (~55ms). This is less resolution than the 1/100 of a second you are aiming for.

*Some versions of DOS may always return 0 for the 1/100 of a second value.

*Use of the BIOS to write pixels to the screen may make coding simpler (it abstracts away differences in the video modes) but will be quite slow compared to writing pixels directly to memory.

*I would recommend Borland's Turbo Debugger (TD) for debugging DOS software. Turbo Debugger is included in a number of Borland's DOS C/C++ compiler suites.

Footnotes

*

*1The use of brackets [] in NASM differs from MASM/TASM/JWASM.

*2Although your question says you want to write to the upper left of the screen, the code suggests you really intended to write the pixel at coordinate 100,100.


text:
Q: Are TF-IDF and BoW techniques incompatible? I have studied the difference between TF-IDF and BoW methods but I have a big doubt about it. I thought that the two methods could be combined, I will explain better. I have a csv file (MY_DATA) with thousands of comments from a social network, I would like to use this dataset to create my BoW for the creation of a classification model of the sentiment of comments (the sentiment of comments is the other variable of MY_DATA and is of three types: positive, negative and neutral)
tf = TfidfVectorizer()
text_tf = tf.fit_transform(MY_DATA['comments'])
X_train, X_test, y_train, y_test = train_test_split(text_tf, MY_DATA['sentiment'], test_size=0.2)

#Classification model Multinomial Naive Bayes
clf = MultinomialNB().fit(X_train, y_train)
predicted = clf.predict(X_test)

Now that you have seen my script I would like to know if I am using the TF-IDF method correctly. How could I apply the BoW method in my case? Do the two methods inevitably remain incompatible?


text:
Q: How to check if all the extendend stored procedures (xp_) are enabled or disabled? These are the stored procedures that I want to check if they are enabled or disabled.

*

*xp_availablemedia

*xp_cmdshell

*xp_deletemail

*xp_dirtree

*xp_dropwebtask

*xp_enumerrorlogs

*xp_enumgroups

*xp_findnextmsg

*xp_fixeddrives

*xp_getnetname

*xp_logevent

*xp_loginconfig

*xp_makewebtask

*xp_regread

*xp_readerrorlog

*xp_readmail

*xp_runwebtask

*xp_sendmail

*xp_servicecontrol

*xp_sprintf

*xp_sscanf

*xp_startmail

*xp_stopmail

*xp_grantlogin

*xp_revokelogin

*xp_logininfo

*xp_subdirs

*xp_regaddmultistring

*xp_regdeletekey

*xp_regdeletevalue

*xp_regenumkeys

*xp_regenumvalues

*xp_regremovemultistring

*xp_regwrite

I found a code for xp_cmdshell which works perfectly but not sure on how to use it on the other xp_
SELECT CONVERT(INT, ISNULL(value, value_in_use)) AS config_value
FROM  sys.configurations
WHERE  name = N'xp_cmdshell'

It will output zero if it is disabled and 1 if it is enabled. How can I use this on the other xp_ ?


text:
Q: Type 'URL' is not assignable to type 'string' I'm getting this error. No idea from where.
theultimateprepper-api | Warning Implicitly using master branch https://deno.land/std/node/_fs/_fs_readlink.ts
theultimateprepper-api | Check file:///app/app.ts
theultimateprepper-api | error: TS2345 [ERROR]: Argument of type 'string | URL' is not assignable to parameter of type 'string'.
theultimateprepper-api |   Type 'URL' is not assignable to type 'string'.
theultimateprepper-api |   return new URL(url).pathname
theultimateprepper-api |                  ~~~
theultimateprepper-api |     at https://deno.land/std@v0.50.0/path/win32.ts:911:18
theultimateprepper-api |
theultimateprepper-api | TS2345 [ERROR]: Argument of type 'string | URL' is not assignable to parameter of type 'string'.
theultimateprepper-api |   Type 'URL' is not assignable to type 'string'.
theultimateprepper-api |   return new URL(url).pathname;
theultimateprepper-api |                  ~~~
theultimateprepper-api |     at https://deno.land/std@v0.50.0/path/posix.ts:433:18
theultimateprepper-api |
theultimateprepper-api | Found 2 errors.

A: You might be using a new version of Deno that has updated the URL constructor.
Compare implementation of fromFileUrl in std@v0.50.0 and std@master:
// v0.50.0
export function fromFileUrl(url: string | URL): string {
  return new URL(url).pathname; // <---- this line
}

// master
export function fromFileUrl(url: string | URL): string {
  url = url instanceof URL ? url : new URL(url); // <---- and this line
  if (url.protocol != "file:") {
    throw new TypeError("Must be a file URL.");
  }
  return decodeURIComponent(url.pathname);
}

Handling has changed.
Please use a more recent version of Deno standard modules that is compatible with the Deno release you are using (e.g. std@v0.62.0). You can find release versions at https://github.com/denoland/deno/tags
(This is understandably frustrating to find the right version, but since standard modules are still tagged with 0.x this means they are not yet fully stabilized, so released in a separate manner as the Deno binary itself)


text:
Q: Does "apt-get purge" remove config files stored in user home dir? I used
sudo apt-get purge [package_name]

and
sudo apt-get autoremove --purge

to remove an application so that on reinstalling it gets back to default configuration. But it didn't work, all previous modified configuration were still there.
On searching I found a dir in "/root/.[package_name]". Does apt-get purge remove config files stored in user home dir? If not then how to remove them?

A: No, it only removes  shared configuration files, like those in the /etc directory.
That's because only those are installed with the package by dpkg(part of the archive).
The ones in the home folders of the users are usually created at runtime by the application(eg. wine creating the initial WINEPREFIX).

A: No , it doesn't usually.
It will remove things in /etc (that belongs to the package) if your purge the package. that's where usually configuration files are stored.
Read document here


text:
Q: Emulating keyboard enter key in C# I am trying to emulate various tasks in Win7 and i have some problems with this function :
LeftMouseClick(Cursor.Position.X - 720, Cursor.Position.Y - 45);
System.Threading.Thread.Sleep(1000);

// Simulate each key stroke
InputSimulator.SimulateKeyDown(VirtualKeyCode.RETURN);
InputSimulator.SimulateKeyUp(VirtualKeyCode.RETURN);

InputSimulator.SimulateTextEntry("cmd");
System.Threading.Thread.Sleep(1000);

InputSimulator.SimulateKeyDown(VirtualKeyCode.RETURN);
InputSimulator.SimulateKeyUp(VirtualKeyCode.RETURN);

All i want to do is to press START, write cmd, hit enter. All works smooth except hitting the enter key.
All of this are happening on a RDP ActiveX, here is the code :
var client = (IMsRdpClient7)rdp.GetOcx();
    // client.RemoteProgram2.RemoteProgramMode = true;
((MSTSCLib.IMsRdpClientAdvancedSettings5)rdp.AdvancedSettings).DisplayConnectionBar = true;
((MSTSCLib.IMsRdpClientAdvancedSettings5)rdp.AdvancedSettings).ConnectionBarShowPinButton = true;
((MSTSCLib.IMsRdpClientAdvancedSettings5)rdp.AdvancedSettings).BitmapVirtualCache32BppSize = 48;
((MSTSCLib.IMsRdpClientAdvancedSettings5)rdp.AdvancedSettings).ConnectionBarShowRestoreButton = false;
((MSTSCLib.IMsRdpClientAdvancedSettings5)rdp.AdvancedSettings).ConnectionBarShowMinimizeButton = true;

((MSTSCLib.IMsRdpClientAdvancedSettings5)rdp.AdvancedSettings).EnableWindowsKey = 1;
((MSTSCLib.IMsRdpClientAdvancedSettings5)rdp.AdvancedSettings).GrabFocusOnConnect = true;
((MSTSCLib.IMsRdpClientAdvancedSettings5)rdp.AdvancedSettings).RedirectDrives = true;
((MSTSCLib.IMsRdpClientAdvancedSettings5)rdp.AdvancedSettings).RedirectClipboard = true;
((MSTSCLib.IMsRdpClientAdvancedSettings5)rdp.AdvancedSettings).RedirectPrinters = true;
((MSTSCLib.IMsRdpClientAdvancedSettings5)rdp.AdvancedSettings).RedirectPOSDevices = true;

rdp.Server = "1.2.3.4";
rdp.UserName = "Rmlabuser2";
IMsTscNonScriptable secured = (IMsTscNonScriptable)rdp.GetOcx();
secured.ClearTextPassword = "Rmlabuser2";
// rdp.FullScreenTitle = "Full Screen";
// rdp.SecuredSettings.FullScreen = 1;
// rdp.SecuredSettings.StartProgram = "calc";
rdp.Connect();

I repeat, keys works, i cannot hit enter.
Thanks.

A: You could try P/Invoking Windows's keybd_event method instead.
[DllImport("user32.dll")]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags,
int dwExtraInfo);

const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
const uint KEYEVENTF_KEYUP = 0x0002;

Then when you want to press it:
keybd_event((byte)System.Windows.Forms.Keys.Enter, 0x45, KEYEVENTF_EXTENDEDKEY, 0); //Key down
keybd_event((byte)System.Windows.Forms.Keys.Enter, 0x45, KEYEVENTF_EXTENDEDKEY |KEYEVENTF_KEYUP, 0); //Key up


text:
Q: What's the limit for the size of iPhone apps? I have an app which is quite huge. It has tons of images and sounds. In total it's 30 MB in size.
1) Is there an official limit for the app size?
2) Are there other "practical" limits I should consider?

A: Reading around, there are reports that the absolute maximum size for an application is 2GB (http://discussions.apple.com/thread.jspa?threadID=1605342).
Other than that, if your app is over 10MB, users will only be able to download it over a wifi connection, having the impact that users won't be able to download your application easily when they are out and about.

A: This might sound obvious, but there are two size limits to keep in mind here - neither are absolutely defined.
One is the limit for the application bundle. I don't know if there is a real limit (other than the device's flash storage limit), but this should rarely be an issue. Keep in mind the 10Mb threshold that the other Phil mentions though. There may be something in the 2GB limit too, I don't know.
The more important limit is on the size of the loaded binary image and it's runtime memory usage. The iPhone is obviously a constrained device in this area. The original iPhones and iPod touches had 128Mb of total RAM, with no paging. Current models have 256Mb, but it's a bit early to limit yourself to that subset of the installed base if you can help it.
Assuming 128Mb, of that a fair chunk is used by the system itself and its background tasks (and people want user background tasks too!?!).
In a conversation with an Apple Engineer he said that apps should be written to use no more than about 25-30Mb! Up to 60Mb may be available but cannot be counted on (but you could use this extra for caching stuff that you can purge as necessary).

A: 1) I believe that you shouldn't ask for maximum size, as you have to aim for minimum possible size for your apps. As iPhone has limited memory (both storage & RAM), you should not create a huge app. (I doubt an app > 200MB can pass through Apple's app check.)
Yeah, Phil is right, when you app is over 10MB, it can only be downloaded via wifi or iTunes. Quite a lot users may want to download anywhere they like using 3G networks, so >10MB is not recommended.
Also, take care those users with iPhone 2G. If you produce a >10MB app, it takes them a day to download your app (if they are lucky enough to have no disconnection at the middle of download...)
2) practical limit ... K.I.S.S = Keep It Simple and Small.
That's it. Hope it helps.


text:
Q: Which filter/action hook gets triggered after a query has been performed? Is there an action or filter that gets called after an instance of WP_Query performs a query?

A: Yes there is, the_posts gets called just after the posts have been selected from the database and it passes an array of $posts as a first parameter and the $wp_query object as second parameter to your hooked function.


text:
Q: How can I output TIMESTAMP_TRUNC(started_at, month) as string, such as "JAN" My query works fine, and will output the month as "2021-06-01 00:00:00 UTC" How can I change this query to output the month as a string value, such as "JAN" instead?
SELECT
    COUNT(distinct ride_id) as total_rides,
    rideable_type,
    member_type,
    TIMESTAMP_TRUNC(started_at, month) AS month,
 FROM `data.table`
 GROUP BY    rideable_type,
             member_type,
             month;

A: UPPER(MONTHNAME("2021-06-01 00:00:00 UTC"))
--will give JUNE

so you'll need to wrap the value you get UPPER(MONTHNAME(TIMESTAMP_TRUNC(started_at, month)))

A: Use below
format_timestamp('%Y-%b', started_at)

Example:
select format_timestamp('%Y-%b', current_timestamp())

outputs

If yo need month only - use
format_timestamp('%b', started_at)

with output