text:
Q: CATransform3D no perspective I have done this before but I somehow don't get this to work. I have googled a bit but none of the answers I have found solve it.
I am just trying to add a small view to my self.view and would like to rotate this added subview on its y-axis with perspective.
Here is the code:
UIView *rotatingView = [[UIView alloc] initWithFrame:(CGRect){{40.0f, 50.0f}, 50.0f, 50.0f}];
rotatingView.backgroundColor = [UIColor lightGrayColor];
CATransform3D transform = CATransform3DIdentity;
transform.m34 = 1.0 / -500.0;

transform = CATransform3DMakeRotation(DEGREES_RADIANS(20.0f), 0.0f, 1.0f, 0.0f);
rotatingView.layer.transform = transform;
[self.view addSubview:rotatingView];

It is plain simple. But there is absolutely no perspective whatsoever. I expect to see a "skewed" view so that it gives the perspective that it is rotated on the y-axis, but to no avail.
I have even tried setting zPosition and the anchorPoint but none helps.
I have a feeling that I am just missing just something very simple. How I did it before has slipped out of my mind.

A: You are overwriting the transform that has perspective with the rotation transform
// Define the "transform" variable here
CATransform3D transform = CATransform3DIdentity;
transform.m34 = 1.0 / -500.0;

// assign a new transform to it here
transform = CATransform3DMakeRotation(DEGREES_RADIANS(20.0f), 0.0f, 1.0f, 0.0f);

You should probably be using CATransform3DRotate instead:
transform = CATransform3DRotate(transform, DEGREES_RADIANS(20.0f), 0.0f, 1.0f, 0.0f);


text:
Q: Can I read data faster from Cassandra using Spark? I am using cassandra database and I have a python script for reading data from cassandra database. Script is doing well. I wonder this if I use spark, can I read data faster from Cassandra ( using cql )?

A: Yes definitely,  spark is made processing huge amount of data , but if the data is less you will not gain anything than to take more time to read.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I create a CSV in Lambda using Python? I would like to create a report in Lambda using Python that is saved in a CSV file. So you will find the code of the function:
import boto3
import datetime
import re

def lambda_handler(event, context):

    client = boto3.client('ce')

    now = datetime.datetime.utcnow()
    end = datetime.datetime(year=now.year, month=now.month, day=1)

    start = end - datetime.timedelta(days=1)
    start = datetime.datetime(year=start.year, month=start.month, day=1)

    start = start.strftime('%Y-%m-%d')
    end = end.strftime('%Y-%m-%d')

    response = client.get_cost_and_usage(
        TimePeriod={
            'Start': "2019-02-01",
            'End':  "2019-08-01"
        },
        Granularity='MONTHLY',
        Metrics=['BlendedCost'],
        GroupBy=[
            {
                'Type': 'TAG',
                'Key': 'Project'
            },
        ]
    )

How can I create a CSV file from it?

A: Here is a sample function to create a CSV file in Lambda using Python:
Assuming that the variable 'response' has the required data for creating the report for you, the following piece of code will help you create a temporary CSV file in the /tmp folder of the lambda function:
import csv
temp_csv_file = csv.writer(open("/tmp/csv_file.csv", "w+"))
# writing the column names
temp_csv_file.writerow(["Account Name", "Month", "Cost"])

# writing rows in to the CSV file
for detail in response:
    temp_csv_file.writerow([detail['account_name'],
                            detail['month'],
                            detail['cost']
                            ])

Once you have created the CSV file, you can upload it S3 and send it as an email or share it as link using the following piece of code:
client = boto3.client('s3')
client.upload_file('/tmp/csv_file.csv', BUCKET_NAME,'final_report.csv')

Points to remember:

*

*The /tmp is a directory storage of size 512 MB which can be used to store a few in memory/ temporary files

*You should not rely on this storage to maintain state across sub-sequent lambda functions.

A: The above answer by Repakula Srushith is correct but will be creating an empty csv as the file is not being closed. You can change the code to
f = open("/tmp/csv_file.csv", "w+")
temp_csv_file = csv.writer(f)
temp_csv_file.writerow(["Account Name", "Month", "Cost"])

# writing rows in to the CSV file
for detail in response:
    temp_csv_file.writerow([detail['account_name'],
                            detail['month'],
                            detail['cost']
                            ])
f.close()


text:
Q: Telnet / Terminal commands Got a problem with a proxy telnet server that I am trying to debug, it appears that a set of characters being sent are causing it a problem .... does anybody know where I can get a list of teminal commands (Along the lines of [40m)?

A: You have to do telnet negotiation, did you checked RFC-1091 and RFC-854?  Afterwards, what will be accepted depends on the terminal type of course.

A: For telnet protocol, you could lookup RFC854. But from your description, you are probably looking for specifications of some terminal emulators. There are a lot of different terminal types, each having its own specifications.


text:
Q: Java/eclipse Error: A JNI error has occurred When running the main of my code. I don't have such problem with the separate projects.
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.UnsupportedClassVersionError: CloudSimPhD_paper2/CloudSimExampleApproximate has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:756)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:468)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:601)


text:
Q: Remove unsupported tags of html (Simple HTML Dom) I would like to remove unsupported tags of html inserted by users (system define which tag is supported), example system is only supported "div" tag:

Hello World

will convert to:

Hello World

This is my code with Simple HTML DOM:
function main()
{
    $content = '
Hello World
';

    $html = str_get_html($content);

    $html = htmlParser($html);
}

function htmlParser($html)
{
    $supportedTags = ['div'];

    foreach ($html->childNodes() as $node) {
        // Remove unsupported tags
        if (!in_array($node->tag, $supportedTags)) {
            $node->parent()->innertext = str_replace($node->outertext, $node->innertext, $node->parent()->innertext);
            $node->outertext = '';
        }

        if ($node->childNodes()) {
            htmlParser($node);
        }
    }

    return $html;
}

But thing get wrong if contain multiple nested unsupported tags, eg:

Hello World !!

it will be converted to

Hello World !!

but expected result is

Hello World !!

What is the solution? Should I continue to use Simple HTML DOM or find another way to solve this issue?
Thanks for solving my problem in advanced.

A: You can do this with as much as I understand. strip_tags($html, '
');
Example : https://3v4l.org/p4nLV

Reference : http://php.net/strip_tags

A: After some struggles, I found out I should not edit $node->parent() as it's in a loop and should load the childNodes first. The code should be like this:
function htmlParser($html)
{
    $supportedTags = ['div'];

    foreach ($html->childNodes() as $node) {
        if ($node->childNodes()) {
            htmlParser($node);
        }

        // Remove unsupported tags
        if (!in_array($node->tag, $supportedTags)) {
            $node->outertext = $node->innertext;
        }
    }

    return $html;
}


text:
Q: ListView items sort/reorder and saving changes? I have a ListView and I can reorder items, but every time I exit from the app and start it again the order goes back to default. I'd appreciate if someone can give me answer and maybe a little snippet of how I can do that.
Example: I have two items and two links. Google and Yahoo. I use drag and drop and ArrayList with that. Everything is fine except I don't know how to save the new order.
I don't know if there is some other way to reorder those items.
I use CWAC-TOUCHLIST to do this.
Here is how far I have got:
    private static String[] items={"Google", "Yahoo"};

    private static String[] links={"http://google.com", "http://yahoo.com"};

    private IconicAdapter adapter=null;

    private IconicAdapter1 adapter2=null;

    ArrayList<String> array= new ArrayList<String>(Arrays.asList(items));

    private ArrayList<String> array2=
        new ArrayList<String>(Arrays.asList(links));

   /** Called when the activity is first created. **/
   @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        TouchListView tlv=(TouchListView)getListView();
        adapter=new IconicAdapter();
        adapter2=new IconicAdapter1();
            setListAdapter(adapter);
        setListAdapter(adapter2);

        tlv.setOnItemClickListener(itemclick);
        tlv.setDropListener(onDrop);

   }

    private TouchListView.DropListener onDrop =
        new TouchListView.DropListener() {
            @Override
            public void drop(int from, int to) {
                String item=(String) adapter.getItem(from);

                adapter.remove(item);
                adapter.insert(item, to);

                String link=(String) adapter2.getItem(from);
                adapter2.remove(link);
                adapter2.insert(link, to);
            }
        };

    private TouchListView.OnItemClickListener itemclick =
        new TouchListView.OnItemClickListener(){
            public void onItemClick(AdapterView<?> parent, View view,
                int from, long id) {

                String item = adapter.getItem(from);

            Toast.makeText(getBaseContext(), "you pick: "+item,
                        Toast.LENGTH_SHORT).show();

                String link = adapter2.getItem(from);
                Intent showContent = new Intent(getApplicationContext(),
                        Web.class);
                showContent.setData(Uri.parse(link));
                startActivity(showContent);
            }
        };

Is there a smarter way to do it?

A: You have to save the lists with their order either to a file or a DB.
When the application starts you have to initialize the ListViews from the saved lists.
When you drag & drop an item, you have to save the changes.
The method you need to change :
Your drop method should, in addition to what it already does, store the changes in a file or a DB.
Instead of the arrays that you pass in the IconicAdapter and IconicAdapter2 constructors (array & array2), you should pass the saved arrays.
You can read in many places how to store data to a file or a SQLite DB. For example, you can find a good tutorial for SQLite here - http://www.vogella.com/articles/AndroidSQLite/article.html#android_requisites (only the first four sections are relevant, since you don't have to use a ContentProvider).
If you choose to use a DB, you can create a table that contains the following columns : item, link & order. In the drop method you'll have to update the order column of all the rows whose order is between from and to (or if the lists are not too big, you can simply update all the rows and set the order to be the index in the array that holds the list).
When you load the table from the DB you should order it by the order column.


text:
Q: Текст и картинка единая ссылка Как сделать картинку и текст под ней единой ссылкой ?

A:

a {
width:250px;
display:flex;
flex-direction:column;
background:grey;
text-decoration:none;
color:orange;
text-align:center;
}

  Я ссылка


text:
Q: How to split an application containing 10 Spring batch jobs into 10 tasks in Spring data flow server? I have a spring boot batch job application which has around 10 jobs(Number may increase based on requirement). I have been trying out Spring cloud data flow server with local server setup for launching and monitoring those jobs.
But the issue I'm facing here is, after the app registration in SCDF, I create the task for the registered app and the single task itself launches all 10 jobs from the application. Though I could see separate job-id's created for each job inside the single task execution, I'm wondering if it's possible to have separate task for each job that's available inside the single jar. If so how can I achieve it?
I need this because few of the job executions relies on the execution status of a job ran previously. Below is my snippet of job class configuration. And several of my jobs would run at different time intervals. So even if'm using cloud foundry or kubernates for scheduling jobs I would be able to schedule on task level only, where the same scheduling intervals would be applied for all jobs. I may not be able to apply different schedules for each job inside the task. I'm not sure about the cloud foundry and kubernates scheduling part, but I guess that's how it'd work.
    //Job Config
    @Configuration
    @EnableBatchProcessing
    @EnableTask
    public class Job1Loader {
    @Bean
        public Job loadJob1()
        {
            return jobBuilderFactory().get("JOb1Loader")
                .incrementer(new RunIdIncrementer())
                .flow(job01_step01())
                .end()
                .build();;//return job
    }

//Job Config
    @Configuration
    @EnableBatchProcessing
    @EnableTask
    public class Job2Loader {
    @Bean
        public Job loadJob2()
        {
            return jobBuilderFactory().get("JOb2Loader")
                .incrementer(new RunIdIncrementer())
                .flow(job02_step01())
                .end()
                .build();;//return job
    }

Same goes for other 8 jobs.

Thanks.

A:
I'm wondering if it's possible to have separate task for each job that's available inside the single jar. If so how can I achieve it?

Even though I do not recommend packaging all jobs in a single jar, nothing prevents you from using this approach with SCDF. You can create a task definition for each job and configure each task with a property to run a specific job, for example:
--spring.batch.job.names=job1


text:
Q: In C#, what data type should I use to store a list of numbers with standard deviation? I'm performing some tests and I have a list of values with errors of the form:
12.7 ± 0.3
14.2 ± 0.1
70.8 ± 0.5

I need to keep the standard deviation alongside the value, as I need to use it for various calculations later on.
At the moment I'm just using
List<KeyValuePair<double, double>>

But are there any better solution?

A: If the values are not going to change I would go with struct.  You can add logic (but you can do that with a class also). Go decimal unless you specifically need double.
public struct StdDev
{
    public decimal Val { get; }
    public decimal Dev { get; }
    public decimal Max { get { return Val + Dev; } }
    public decimal Min { get { return Val - Dev; } }
    public bool IsInDev (decimal val)
    {
        return val >= Min && val <= Max;
    }
    public override string ToString()
    {
        return $"{Val} +- {Dev}";
    }
    public StdDev (decimal val, decimal dev)
    {
        Val = val;
        Dev = dev;
    }
}

You could override Equals and GetHashCode.

A: Here are some other options to what you currently have:
It's up to you to choose and use what is convinient. Don't know if performance is what you are looking for.
Option 1 (if you are using C# 7.0 or later):
How about Tuples?
You won't have key value pair in tuple but rather items.
Option 2:
Like Dan wilson mentioned in the comment to your question make a class with value and error
public class ValueWithDeviation
{
    public double Value {get; set;}

    public double Deviation {get; set;}
}

Then you could have IEnumerable<ValueWithError>

A: As DanWilson and Cybercop suggest, I'd say that creating a dedicated type (a class or a struct) is the way to go, because the value with the deviation can be seen together as a logical object. Also, that will make your life easier when you want to display the values, as you will just need to override the ToString method in your type.
As for the underlying type, it might be more convenient for you to use decimal instead of double, but that depends on your specific project/needs.


text:
Q: Will points intersect with path with width I want to be able to check if a list of points will hit a screwed rectangle (rhombus I think).
I start out with 2 point P and T, I want to create a rectangle between the 2 points. I have used https://stackoverflow.com/questions/7854043/drawing-rectangle-between-two-points-with-arbitrary-width to do this. This gives me 4 points A, B, C and D of the new rectangle.
I then want to check if the point M is withing this rectangle.

The two black dots are my points P and T, the black box is the rectangle I want to generate between the two dots, being X wide.
I then want to test if the red dots are withing the black box.

A: Once you got the coordinates of the vertices of your rectangle,
you can proceed here


text:
Q: Handling innoDB deadlock I've been getting a Deadlock found when trying to get lock; try restarting transaction error on my InnoDB tables. Here is the query:
UPDATE views
SET visit_cnt = visit_cnt + 1
WHERE visit_day = DATE(NOW())
AND article_id = '4838'

This query also triggers this via ON UPDATE trigger:
UPDATE articles
SET views = views + 1
WHERE id = NEW.article.id

Here is how I tried to fixed it:
$attempts_left = 5;
do
{
    mysql_query ($query);

    // if we found a deadlock, we will try this query 4 more times
    if (mysql_errno () == 1213) { // 1213 - deadlock error
        $deadlocked = true;
        $attempts_left --;
    }
    else{
        $deadlocked = false;
    }
}
while($deadlocked && $attempts_left > 0);

My question: is this the only way to handle a deadlock? I mean this is quite ugly and deadlocks happen time to time anyway. Is there any recommended way to fix deadlocks?

A: Here is good documentation about handling InnoDB deadlocks.
PS: I didn't have anything more to add so just gave you the link.

A: You may have to play some games with the Transaction Isolation/MVCC features
Option 1) You may want to surround the query in a begin commit block
BEGIN;

UPDATE views
SET visit_cnt = visit_cnt + 1
WHERE visit_day = DATE(NOW())
AND article_id = '4838';

< Any actions in the trigger would be part of the transaction >

COMMIT;

Option 2) You may want to disable autocommit for your session
SET autocommit = 0;

Option 3) Change the transaction isolation before launching the query to expose dirty reads
This one is a stretch !!!
SET tx_isolation = READ_COMMITTED;

or
SET tx_isolation = READ_UNCOMMITTED;

Give it a Try and let us all know !!!

A: That's the proper way, as the documentation states:

Normally, you must write your applications so that they are always prepared to re-issue a transaction if it gets rolled back because of a deadlock.

If you want to reduce the occurrence of deadlocks, you must show us the tables DDL and indexes.


text:
Q: Excel COUNTIF with ID groups I have in my Excel column A the IDs, each ID stands for a blog post, in column B the language of the blog and column C if it should be migrated. IDs can be the same up to 3 times because a blog post can be created in 3 different languages.

ID  Language    Migration
44021   German  Yes
44021   French  No
44021   Italian No
44014   German  No
44014   French  Yes
44014   Italian No
43999   German  No
43999   French  Yes
43999   Italian Yes
44001   French  Yes
55504   German  No
55504   French  No

At the end I must be able to say if the ID group should be migrated and declare if ist due on the german version or another language version.
Output should look like this:

ID  Language    Migration   Result
44021   German  Yes Due to german
44021   French  No  Due to german
44021   Italian No  Due to german
44014   German  No  Due to other lang
44014   French  Yes Due to other lang
44014   Italian No  Due to other lang
43999   German  Yes Due to german
43999   French  Yes Due to german
43999   Italian Yes Due to german
44001   French  Yes Due to other lang
55504   German  No  No Migration
55504   French  No  No Migration

In itself very simple. I just don't know how to do this in an Excel formula if it has groups of maximum 3 entries with same IDs. In other words, the formula must respect the same IDs and compare their details.

A: In D2:
=IF(COUNTIFS(A:A,A2,C:C,"Yes"),IF(COUNTIFS(A:A,A2,B:B,"German",C:C,"Yes"),"Due to German","Due to other lang"),"No Migration")

Note your end result data does not resemble your input data on ID 43999.


text:
Q: How to use less in a script without getting ESC escape characters? When I use less at the command line the output is like

but when I use less from within a bash script I get:

How can I use less in a bash script and not get all the escape characters and have it work like it does at the interactive command line?

A: Use -R flag:

-r or --raw-control-chars
Causes "raw" control characters to be displayed.  The default is to
  display control characters using the caret notation; for example, a
  control-A (octal 001) is displayed as "^A".  Warning: when the -r
  option is used, less cannot keep track of the actual appearance of the
  screen (since this depends  on  how  the  screen responds to each type
  of control character).  Thus, various display problems may result,
  such as long lines being split in the wrong place.
-R or --RAW-CONTROL-CHARS
Like -r, but only ANSI "color" escape sequences are output in "raw"
  form.  Unlike -r, the screen appearance is maintained correctly in
  most cases.  ANSI "color" escape sequences are sequences of the form:
           ESC [ ... m

where the "..." is zero or more color specification characters For the
  purpose of keeping track of screen appearance, ANSI color escape
  sequences are assumed to not  move  the  cursor.   You can make less
  think that characters other than "m" can end ANSI color escape
  sequences by setting the environment variable LESSANSIENDCHARS to the
  list of characters which can end a color escape sequence.  And you can
  make less think that characters other than the standard ones may
  appear between the ESC and the m by setting the environment variable
  LESSANSIMIDCHARS to the list of characters which can appear.

From less man page.


text:
Q: How to write query in ormlite when the condition generated using for loop I'm writing a query in ormlite as below
Where<Advertisement, Integer> where = queryBuilder.where();
where.and(
    where.between("latitude", pLatitude - APPOXIMATION_FACTOR,
        pLatitude + APPOXIMATION_FACTOR),
    where.between("longitude", pLongitude - APPOXIMATION_FACTOR,
        pLongitude + APPOXIMATION_FACTOR)
      .and().between("width", pWidth - APPOXIMATION_FACTOR,
        pWidth + APPOXIMATION_FACTOR),
);

and also one more and with this
for (int iterator = 0; iterator < moduleList.size(); iterator++) {
    where.eq("id", moduleList.get(iterator).getmId());
    if (iterator != advertisementList.size() - 1){
        whereForModuleID.or();
    }
}

but i am stuck how to write query in this case
Looking for help

A: In the 2nd case I'd use instead the where.in(String, Iterable) method.  You should do something like this:
List<Integer> idList = new ArrayList<Integer>();
for (Module module : moduleList) {
    idList.add(module.getmId());
}
where.in("id", idList);

This turns into a SQL query like:
SELECT * `foo` WHERE `id` IN (7, 17, 1, 34)

Here are the docs on where.in():

http://ormlite.com/docs/where-in

In terms of the original question, see this answer about the where.and(int) and or(int) methods.

A: To create a query which looks up an account by name and password you would do the following:
 QueryBuilder<Account, String> qb = accountDao.queryBuilder();
 Where where = qb.where();
 // the name field must be equal to "foo"
 where.eq(Account.NAME_FIELD_NAME, "foo");
 // and
 where.and();
 // the password field must be equal to "_secret"
 where.eq(Account.PASSWORD_FIELD_NAME, "_secret");
 PreparedQuery<Account, String> preparedQuery = qb.prepareQuery();

This is my code which i am using in my project to get PropertyModel from SQLite using ORMLite
public ArrayList<PropertyPicModel> selectArgumentQueryPropertyModel(int property_id, Dao<PropertyPicModel, Integer> dao)
{
    try {
        QueryBuilder<PropertyPicModel, Integer> queryBuilder = dao.queryBuilder();
                Where<PropertyPicModel, Integer> where = queryBuilder.where();
                SelectArg selectArg = new SelectArg();
                // define our query as 'property_id = ?'

                where.eq(ORMLiteConfig.PROPERTY_ID, selectArg);
                // prepare it so it is ready for later query or iterator calls
                PreparedQuery<PropertyPicModel> preparedQuery = queryBuilder.prepare();
                selectArg.setValue(property_id);
                // later we can set the select argument and issue the query

                ArrayList<PropertyPicModel> picList = (ArrayList<PropertyPicModel>) dao.query(preparedQuery);
                return picList;
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        MyLog.e("Excep selectArgumentQuery " +e.toString());
    }
    catch (Exception e) {
        MyLog.e("Excep selectArgumentQuery " +e.toString());
    }
    return null;
}

In this example, the SQL query that will be generated will be approximately:
 SELECT * FROM account WHERE (name = 'foo' AND passwd = '_secret')

https://github.com/AshishPsaini/ormlite-examples/tree/master/android/HelloAndroid
http://ormlite.com/docs/in


text:
Q: Observable sequence that polls repository until a valid value is returned I have to poll a database until it contains valid data.
To do it, I have a repository that should queried every n seconds in order to get a my very own entity, called DestinationResponse.
class DestinationResponse
{
     bool HasDestination { get; set; }
     bool Destination { get; set; }
}

When the DestinationResponse has its property HasDestination to true, the Destination is returned.
So, my observable sequence should get all the responses waiting for one to have HasDestination=true. It basically awaits for a response that HasDestination set to true. When this happens, it returns it and the sequence completes. It will only push one element at most!
My current approach is this:
var pollingPeriod = TimeSpan.FromSeconds(n);

var scheduler = new EventLoopScheduler(ts => new Thread(ts) {Name = "DestinationPoller"});

var observable = Observable.Interval(pollingPeriod, scheduler)
    .SelectMany(_ => destinationRepository.GetDestination().ToObservable())
    .TakeWhile(response => !response.HasDestination)
    .TakeLast(1)
    .Select(response => response.Destination);

I know I's wrong, mainly because the Interval call will keep generating even if the last call to GetDestination hasn't finished.
NOTE:
repository.GetDestination() returns a Task<DestinationResponse> and it actually queries the database.

A: Merging the answer from Database polling with Reactive Extensions with your example code, I think gives you what you want.
var pollingPeriod = TimeSpan.FromSeconds(n);

var scheduler = new EventLoopScheduler(ts => new Thread(ts) {Name = "DestinationPoller"});

var query = Observable.Timer(pollingPeriod , scheduler)
    .SelectMany(_ => destinationRepository.GetDestination().ToObservable())
    .TakeWhile(response => response.HasDestination)
    .Retry()    //Loop on errors
    .Repeat()  //Loop on success
    .Select(response => response.Destination)
    .Take(1);

A: This code may be the query I want. What do you think?
private IObservable<Destination> CreateOrderDestinationObservable(string boxId, int orderId)
{
    var pollingPeriod = TimeSpan.FromSeconds(DestinationPollingDelay);
    var scheduler = new EventLoopScheduler(ts => new Thread(ts) {Name = "DestinationPoller"});

    var observable = Observable.Timer(pollingPeriod, scheduler)
        .SelectMany(_ => externalBridgeRepository.GetDestination(boxId, orderId).ToObservable())
        .Where(response => response.HasDestination)
        .Retry()
        .Repeat()
        .Take(1)
        .Select(response => response.Destination);

    return observable;
}


text:
Q: How to download the newest build from the universal artifacts packages I have a universal artifacts package feed named 'TWI-NORA/twi-cci' How can I download the package with the newest version without hard coded style
 - task: DownloadPackage@1
    inputs:
      packageType: 'upack'
      feed: 'TWI-NORA/twi-cci'
      definition: '$(packageName)'
      version: '1.0.0' # something like $(latestVersion)
      extract: true
      downloadPath: '$(System.ArtifactsDirectory)''

A: So the actual answer to this question to use
version: "latest"

This can be found in the Official Documentation

A: You could use * as the version of the package. Then the "download package" task will download the latest version of the package.
For example:
- task: DownloadPackage@1
    inputs:
      packageType: 'upack'
      feed: '1'
      definition: '$(packageName)'
      version: '*'
      extract: true
      downloadPath: '$(System.ArtifactsDirectory)'

Here is a doc about Downloading the latest version of package.
Hope this helps.


text:
Q: How to efficiently create and use the builder pattern On our last project we ended up with a shared test fixture for our unit tests which gave a lot of problems. So on our current project I've looked into the builder pattern. We run our unit tests in memory on the development machines and against the database on the build server.
Currently I have a T4 template which produces for example the following builder for a Student:
public class StudentBuilder : Builder<Student, StudentBuilder>
{
    public StudentBuilder()
    {
        IsMale = true;
    }

    public StudentBuilder WithFirstName(string firstName)
    {
        this.FirstName = firstName;
        return this;
    }

    public StudentBuilder WithLastName(string lastName)
    {
        this.LastName = lastName;
        return this;
    }

    public StudentBuilder WithIsMale(bool isMale)
    {
        this.IsMale = isMale;
        return this;
    }

    internal override Student Construct()
    {
        Student result = new Student()
        {
            FirstName = FirstName ?? "FirstName:" + id.ToString(),
            LastName = LastName ?? "LastName:" + id.ToString(),
            IsMale = IsMale,
            Id = id,
        };

     /   return result;
    }
}

Trough the base classes I can use this in the following way:
Student wouter = StudentBuilder.Build()
    .WithFirstName("Wouter")
    .WithLastName("de Kort");
List<Student> students = StudentBuilder.Build().Multiple(10, (builder, index) => builder.WithFirstName("FirstName" + index));

We run integration tests on our build server to make sure everything works against the database. This means we have to make sure that all referential constrains are met.
But then the problems begin.
For example, a student is required to have a mentor, a mentor belongs to a school, a school to a city, a city to a ....
This would result in code like:
StudentBuilder.Build().WithMentor(MentorBuilder.Build().WithSchool(SchoolBuilder.Build().WithCity(CityBuilder.Build()))

How should I optimize this? I've thought about doing the 'default building' in the Construct method of each Builder but if I would build 10 students then it would lead to 10 mentors in 10 schools in 10 cities in 10....
Or maybe creating methods like WithAllCity(..), WithAll(School)
Any ideas? Am I actually using the Builder Pattern the right way? Could a Director class help? Or should I have inherited classes from StudentBuilder which solve these different cases?
Or another idea, should I add more validation in my service layer before sending the data to the database? Then I would catch more errors in my unit tests against the in memory database.

A: If your unit test is going to be using the student's mentor, the mentor's school, and the school's city, I think it is reasonable for the unit test to have code to build all of that, but I suggest your unit test might not be testing just one thing. Make your unit tests more specific so that they are not drilling down through so many properties.
If the problem is not your unit tests, but that your student class demands a mentor to be fed into its constructor, and that mentor cannot be null, consider relaxing that requirement to allow a null mentor (my preference I suppose), or make the builder fill in a "default" object as you say. You could even make your default objects throw exceptions if you try to access their properties, prompting you that your unit test needs you to build an "actual" object.

A: If you are going to building lists of students you can make a list builder class - StudentsBuilder. By default the builder class will generate a list of Students will psuedo-random properties defined by you. This is similar to the approach of AutoPoco.
I find that making your own list builder class is more flexible in terms of defining the creation behavior and supporting any type of class. I make a builder class with IList<T> fields (similar to a data-oriented structure of arrays (SoA) approach).
public class StudentsBuilder
{
    private int _size;
    private IList<string> _firstNames;
    private IList<string> _lastNames;
    private IList<MentorBuilder> _mentors;

    public StudentsBuilder(int size = 10)
    {
        _size = 10;
        _firstNames = new RandomStringGenerator(size).Generate();
        _lastNames = new RandomStringGenerator(size).Generate();
        _mentors = Enumerable.Range(0, size).Select(_ => new MentorBuilder()).ToList();
    }

    public StudentsBuilder WithFirstNames(params string[] firstNames)
    {
        _firstNames = firstNames;
        return this;
    }

    public IList<Student> Build()
    {
        students = new List<Student>();
        for (int i = 0; i < size; i++)
            students.Add(new Student(_firstNames[i], _lastNames[i], _mentors[i].Build());
        return students;
    }
}

Each field list is overridden using a separate method taking a params array argument. You could also make field lists public in order to use a fancier With(Action<StudentsBuilder> action) syntax for overriding values. Test code looks like:
var students = new StudentBuilder(size: 4)
    .WithFirstNames("Jim", "John", "Jerry", "Judy")
    .Build();


text:
Q: Unable to compile a simple application I'm trying to compile this for Linux Arch x64, I'm trying:
section .text
global _start
_start:
        mov edx, len
        mov ecx, msg
        mov ebx, 1
        mov eax, 4
        int 0x80

        mov eax, 1
        int 0x80

section .data
msg db 'hi123', 0xa
len equ $ - msg

And
$ nasm -f elf test1.asm
$ ld -s -o test1 test1.o

But an error:
/usr/bin/ld: i386 architecture of input file `test1.o' is incompatible with i386:x86-64 output

A: When linking 32-bit apps on x86_64, setting emulation to elf_i386 provides the correct elf format. So, for example, if you compile an assembler app with nasm -f elf file.asm -o file.o, the link command is ld -m elf_i386 -o exename file.o.
So use this instead
nasm -f elf test1.asm
ld -m elf_i386 -o test1 test1.o


text:
Q: Proper way to (get from /insert into) table using Erlang Mysql Driver I am trying to get erlang-mysql-driver working, I managed to set it up and make queries but there are two things I cannot do.(https://code.google.com/archive/p/erlang-mysql-driver/issues)
(BTW, I am new to Erlang)
So Here is my code to connect MySQL.
<erl>
out(Arg) ->
            mysql:start_link(p1, "127.0.0.1", "root", "azzkikr", "MyDB"),
            {data, Result} = mysql:fetch(p1, "SELECT * FROM messages").
</erl>

1. I cannot get data from table.
mysql.erl doesn't contain any specific information on how to get table datas but this is the farthest I could go.
        {A,B} = mysql:get_result_rows(Result),
        B.

And the result was this:
ERROR erlang code threw an uncaught exception:
 File: /Users/{username}/Sites/Yaws/index.yaws:1
Class: error
Exception: {badmatch,[[4,0,<<"This is done baby!">>,19238],
                      [5,0,<<"Success">>,19238],
                      [6,0,<<"Hello">>,19238]]}
Req: {http_request,'GET',{abs_path,"/"},{1,1}}
Stack: [{m181,out,1,
              [{file,"/Users/{username}/.yaws/yaws/default/m181.erl"},
               {line,18}]},
        {yaws_server,deliver_dyn_part,8,
                     [{file,"yaws_server.erl"},{line,2818}]},
        {yaws_server,aloop,4,[{file,"yaws_server.erl"},{line,1232}]},
        {yaws_server,acceptor0,2,[{file,"yaws_server.erl"},{line,1068}]},
        {proc_lib,init_p_do_apply,3,[{file,"proc_lib.erl"},{line,240}]}]

I understand that somehow I need to get second element and use foreach to get each data but strings are returned in different format like queried string is Success but returned string is <<"Success">>.
{badmatch,[[4,0,<<"This is done baby!">>,19238],
                      [5,0,<<"Success">>,19238],
                      [6,0,<<"Hello">>,19238]]}

First Question is: How do I get datas from table?
2. How to insert values into table using variables?
I can insert data into table using this method:
    Msg = "Hello World",
    mysql:prepare(add_message,<<"INSERT INTO messages (`message`)  VALUES (?)">>),
    mysql:execute(p1, add_message, [Msg]).

But there are two things I am having trouble,
1. I am inserting data without << and >> operators, because When I do Msg = << ++ "Hello World" >>, erlang throws out an exception (I think I am doing something wrong), i don't know wether they are required but without them I am able to insert data into table except this error bothers me after execution:
yaws code at /Users/{username}/Yaws/index.yaws:1 crashed or ret bad val:{updated,
                                                                                {mysql_result,
                                                                                [],
                                                                                [],
                                                                                1,
                                                                                []}}
Req: {http_request,'GET',{abs_path,"/"},{1,1}}

returned atom is updated while I commanded to insert data.
Question 2 is:  How do I insert data into table in a proper way?

A: Error:
{badmatch,[[4,0,<<"This is done baby!">>,19238],
                      [5,0,<<"Success">>,19238],
                      [6,0,<<"Hello">>,19238]]}

Tells you that returned values is:
[[4,0,<<"This is done baby!">>,19238],
 [5,0,<<"Success">>,19238],
 [6,0,<<"Hello">>,19238]]

Which obviously can't match with either {data, Data} nor {A, B}. You can obtain your data as:
<erl>
out(Arg) ->
    mysql:start_link(p1, "127.0.0.1", "root", "azzkikr", "MyDB"),
    {ehtml,
     [{table, [{border, "1"}],
       [{tr, [],
         [{td, [],
           case Val of
               _ when is_binary(Val) -> yaws_api:htmlize(Val);
               _ when is_integer(val) -> integer_to_binary(Val)
           end}
          || Val <- Row
         ]}
        || Row <- mysql:fetch(p1, "SELECT * FROM messages")
       ]}
     ]
    }.
</erl>


text:
Q: How to handle differing validation rules in RIA Services? We have an Entity Framework model that is used by two different silverlight applications.  The validation rules are very similar in the two contexts, but differ slightly.
For example, a regular user in one of the applications cannot input time that is in the future, but an administrator in the other application can put time that is in the future.
How would you handle designing this application?  Two ideas we came up with:

*

*Creating two entirely separate models, so that each can be independent

*Share the same model, but put a "Context" property on our base Entity class, so that the validation rules can validate differently where necessary.

A: I have never tried it, but what about extending or creating new validation attributes that uses a different validation depending on the authorisation role of the user?

A: Those sound like business rules which should be seperate from data access. You should be able to use the same EDM but implement the business rules in the business layer, not the data layer.


text:
Q: Determine Orientation of a Sketched Arrow with OpenCV I've got a bunch of arrow sketches and I want to determine their orientation, the starting point coordinates, and the ending point coordinates.
I'm using goodFeaturesToTrack but I'm really clueless as to what to do next.
This is what I've got

There is no restriction on the shape of the arrows, they can be as windy as you want them or they could be composed of straight lines and right angles.
I'd really appreciate any ideas because I really am lost. The project is about transforming a sketch of an Finite State Machine into a VHDL code and I've got the circles and characters covered so this is the last component but I have no idea how to approach the problem.

A: Instead of using goodFeaturesToTrack you can use HoughLines which will give you all lines in an image so I suggest that you do some segmentation first to get each arrow separately. HoughLines gives you all lines in polar coordinates which is perfect for you case as you can know the orientation of the lines. You can read more here: https://docs.opencv.org/3.4.0/d9/db0/tutorial_hough_lines.html
For straight lines your task is easy you need to find 3 line segments that intersect in one point (http://answers.opencv.org/question/92164/how-to-find-coordinates-of-intersection-of-lines-after-using-houghlines/). This will be the end point of your arrow, you can find the start point using the equation of the middle line.
For curved lines, it is a bit more tricky as you may get several hough lines for the curved segment or none at all. So in this case I suggest you get the intersection of the the 2 lines as your end point and then use goodFeaturesToTrack then starting from the closest point to your end point start moving to the next closer until you reach the end and pick that as the starting point.
I do not know if this would be the best solution and I did not try it myself but I hope it helps you or give you some direction.


text:
Q: What is the difference between -0 and 0? In C++, for example fmod(-2,2) returns -0. The expression -0 == 0 is true, but the bits are different. What is the purpose of having something like -0 which should be 0 but is represented differently? Is -0 used exactly the same way as 0 in any computations?

A: IEEE Standard 754 allows both +0 and -0. Same mantissa, different sign. They should be the same in computations.

A: No, +0 and -0 are not used in the same way in every computation. For example:
3·(+0) = +0
+0/-3 = -0

I suggest you to read What Every Computer Scientist Should Know About Floating-point arithmetic by David Goldberg, that sheds a light on why +0 and -0 are needed in floating point arithmetic and in which way they differ.
Examples on how +0 ad -0 differ (and why that can be useful when dealing with complex values) can be found in Kahan, W. 1987. Branch Cuts for Complex Elementary Functions, in "The State of the Art in Numerical Analysis" (I wasn't able to find a pdf of this article, you may find one at your local university library).

A: The Signed Zero Wikipedia page will answer most of those questions:

Signed zero is zero with an associated
  sign. In ordinary arithmetic, −0 = 0.
  However, in computing, some number
  representations allow for the
  existence of two zeros, often denoted
  by −0 (negative zero) and +0 (positive
  zero). This occurs in some signed
  number representations for integers,
  and in most floating point number
  representations. The number 0 is
  usually encoded as +0, however it can
  be represented by either +0 or −0.
The IEEE 754 standard for floating
  point arithmetic (presently used by
  most computers and programming
  languages that support floating point
  numbers) requires both +0 and −0. The
  zeroes can be considered as a variant
  of the extended real number line such
  that 1/−0 = −∞ and 1/+0 = +∞, division
  by zero is only undefined for ±0/±0.
(...)
It is claimed that the inclusion of
  signed zero in IEEE 754 makes it much
  easier to achieve numerical accuracy
  in some critical problems, in
  particular when computing with complex
  elementary functions.

A: i believe the negative sign is caused by fmod (mis?)implementation, where the sign bit is handled explicitly and attached back to the result at the end of processing.


text:
Q: "Only if" and "if" direction in Kolmogorov's Existence Theorem The title of this question sounds somewhat grand, but all I'm asking is whether there's a typo in the book I'm reading.
The book is "A First Look at Rigorous Probability Theory," by Jeffrey Rosenthal -- second edition, fifth printing (2011), to be precise.
Page 178:
Theorem 15.1.3.  (Kolmogorov Existence Theorem)  A family of Borel probability measures $\{\mu_{t_1 \, \ldots \, t_k}\colon\; k \in \mathbb{N},\; t_i \in T \text{ distinct}\}$, ... satisfies the consistency conditions (C1) and (C2) if and only if there exists a probability triple $\left(R^T, \,\mathcal{F}, \,P\right)$, and random variables $\left\{X_t\right\}_{t \in T}$ defined on this triple, such that for all $k\in \mathbb{N}$, distinct $t_1, \ldots, t_k \in T$, and Borel $H \in R^T$, we have
$$
P\left(\left( X_{t_1}, \ldots, X_{t_k}\right) \in H \right) = \mu_{t_1 \, \ldots \, t_k}\left(H\right)
$$
The consistency conditions on $\mu$ state that we can permute the $t_i$ and H correspondingly (C1), and remove one of the $t_i$ if the corresponding $H_i=R$ (C2), without changing the probabilities.
The author then states that the "only if" direction of 15.1.3 is immediate, and gives a quick outline of (what he refers to as) the "if" direction.
My question:  isn't that backwards?  Isn't it the "if" direction that's immediate, and the "only if" direction that requires an involved proof?
When we say [A if and only if B], the "if" direction is [B implies A], correct?
If so, the "if" direction in 15.1.3 is going from the existence of the probability triple to the consistency conditions, which is straightforward -- do I have this backwards, or is it the book?
Edit: I've checked http://probability.ca/jeff/ftpdir/errata2.pdf, no mention of p 178.

A: I contacted the author:  it was a typo, and he's added it to http://probability.ca/jeff/ftpdir/errata2.pdf.


text:
Q: How to reduce gas cost in polygon function I have a Smart contract made in polygon.
In this contract, i have a function for voting:
function voteForCandidate(string[] calldata names, string[][] calldata vote ) public returns (bool){//bytes32[] memory  whatsapps
  require(owner == msg.sender, "Only owner can call this function");
  string memory artistas;
  for(uint i = 0; i < vote.length; i++) {
    artistas = "[";
    for(uint y = 0; y < vote[i].length; y++)
    {
       artistas = append(artistas, " , ", vote[i][y]);
       votesReceived[vote[i][y]] += 1;
    }
     artistas = append(artistas, " ] ", "");
    emit Vote(names[i], artistas);
}
return true;

}
I group transaction in lots of 100, so this foor lopp wil run 100 times and emit 100 events.
This is great for what i need to show for the users. But i had paid a lot of gas: (see image)
I am using 500 GWEi of gasprice becuse matic gast track is change everytime and if use a low gas price, sometimes i got transaction underpriced
Any idea to reduce gas cost?


text:
Q: Lighting and material color problems I can't change any object color when lighting is enabled.
This is my init function (the part of the light and material):
glEnable (GL_LIGHTING);
glEnable (GL_LIGHT0);
GLfloat light_ambient[] = {0.5, 0.5, 0.5, 1.0};
GLfloat light_diffuse[] = {0.0, 0.5, 0.5, 1.0};
GLfloat light_specular[] = {0.0, 0.0, 0.5, 1.0};
GLfloat light_position[]={0, -1.0, 0, 0.0};
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);

Each object has a vector of colors. This is how I draw my objects:
float mat_a[] = {0.0, 0.0, 0.0, 1.0};
float mat_d[] = {0.0, 0.0, 0.0, 1.0};
float mat_s[] = {0.0, 0.0, 0.0, 1.0};
...
colors_vect = some_object->getColor();
glDisable(GL_COLOR_MATERIAL);
mat_a[0] = colors_vect.at(0);
mat_a[1] = colors_vect.at(1);
mat_a[2] = colors_vect.at(2);
mat_d[0] = colors_vect.at(3);     //The values are correct.
mat_d[1] = colors_vect.at(4);
mat_d[2] = colors_vect.at(5);
mat_s[0] = colors_vect.at(6);
mat_s[1] = colors_vect.at(7);
mat_s[2] = colors_vect.at(8);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, mat_a);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_d);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_s);
glEnable(GL_COLOR_MATERIAL);

glBegin(GL_POLYGON);
...

This code doesn't work. I tried to give the mat some random values and still nothing changes.
What am I doing wrong? Any help would be appreciated!

A: Your problem is caused by this line:
glEnable(GL_COLOR_MATERIAL);

This enables functionality that allows material properties to track the current color, which is the color set with regular glColor() calls. If this is enabled, glColorMaterial() controls which parts of the material parameters track the current color. The default is GL_AMBIENT_AND_DIFFUSE, which means that the current color is used for the ambient and diffuse material parameters.
You need to make a choice about how you want to update your material properties:

*

*If you need to change colors very frequently, it can be most efficient to enable GL_COLOR_MATERIAL, and use glColor() to update the material properties.

*You can use glColorMaterialfv(), which gives you more control, and e.g. allows you to set different colors for ambient and diffuse. For this approach, you need to keep GL_COLOR_MATERIAL disabled.

You used a mix of these two, where you set the material properties with glColorMaterialfv(), but then also enabled GL_COLOR_MATERIAL. This means that the ambient and diffuse material properties you set are not used. Instead the current color is used for those two properties. These properties would then change any time you call glColor(). If you never call glColor(), they would use the default value for the current color, which is white (1.0, 1.0, 1.0, 1.0).


text:
Q: Clutter - run method at marker? Markers seem to be designed to run a timeline at a point in another timeline. Is there any way to run an ordinary method at a marker, rather than a timeline?

A: no, markers on ClutterTimeline can run any function. just use the ClutterTimeline::marker-reached signal. if you are interested in a specific marker, you can detail the signal using the marker name, e.g.:
g_signal_connect (timeline, "marker-reached::my-marker",
                  G_CALLBACK (on_my_marker_reached),
                  NULL);

and the timeline will call the *on_my_marker_reached* callback when the marker my-marker has been reached.


text:
Q: trouble creating makefiles I always have a problem creating makefiles for some reason. In this case, I'm using clang++ with -std=c++11.
I have an executable Carbuyer.cpp that depends on a CarFactory (.cpp and .h) which in turn relies on Car(.cpp and .h)
my Current attempt looks like this:
CarBuyer: CarBuyer.cpp CarFactory Car
    clang++ -std=c++11 -v -o CarBuyer CarBuyer.cpp CarFactory Car
Car: Car.cpp Car.h
    clang++ -std=c++11 Car.cpp Car.h
CarFactory: CarFactory.cpp CarFactory.h
    clang++ -std=c++11 CarFactory CarFactory.cpp CarFactory.h
clean:
    rm -f core CarBuyer

But i'm getting an undefined function error originating from CarFactory when compiling:
clang++ -std=c++11 CarFactory.cpp CarFactory.h
clang: warning: treating 'c-header' input as 'c++-header' when in C++ mode,
     this behavior is deprecated
/usr/bin/../lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crt1.o: In
    function `_start':
(.text+0x20): undefined reference to `main'
/tmp/CarFactory-13dbb4.o: In function `FordFactory::makeCar()':
CarFactory.cpp:(.text+0x5a): undefined reference to `Ford::Ford()'
/tmp/CarFactory-13dbb4.o: In function `ToyotaFactory::makeCar()':
CarFactory.cpp:(.text+0xba): undefined reference to `Toyota::Toyota()'
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [CarFactory] Error 1

The code compiles fine in VS2015 but not when compiling with clang++, leading me to believe my error is in the Makefile.
Any help is appreciated!

A: First, you need to tell compiler to compile with -c option.
Second, output files must be defined: with -o file or better -o $@
CarBuyer: CarBuyer.o CarFactory.o Car.o
    clang++ -std=c++11 -o $@ CarBuyer.o CarFactory.o Car.o

CarBuyer.o: CarBuyer.cpp
    clang++ -std=c++11 -c -o $@ CarBuyer.cpp

Car.o: Car.cpp Car.h
    clang++ -std=c++11 -c -o $@ Car.cpp Car.h

CarFactory.o: CarFactory.cpp CarFactory.h
    clang++ -std=c++11 -c -o $@ CarFactory.cpp CarFactory.h

clean:
    rm -f core CarBuyer *.o

Having header file into compile rules is quite unusual, give it a check and suppress them from clang++ command lines if you can.


text:
Q: Should `$srandom` apply to seed for `$urandom_range`? Using ModelSim it looks like the seed random call with $srandom does not apply to subsequent random value generation with $urandom_range.
Running the process:
initial
  begin
  $srandom(42);
  $display("1: %0d, %0d, %0d", $urandom_range(1, 10), $urandom_range(1, 10), $urandom_range(1, 10));
  $srandom(42);
  $display("2: %0d, %0d, %0d", $urandom_range(1, 10), $urandom_range(1, 10), $urandom_range(1, 10));
  $srandom(42);
  $display("3: %0d, %0d, %0d", $urandom_range(1, 10), $urandom_range(1, 10), $urandom_range(1, 10));
  end

the output is:
# 1: 3, 1, 7
# 2: 9, 7, 2
# 3: 6, 4, 8

However, I had expected that line 1, 2 and 3 where identical, since $srandom was called be fore with same seed value.
Why are the generated values not the same?

A: You need to use process::self().srandom() instead of $srandom. Then you get the desired results.


text:
Q: Finding a path integral Consider a path
$$ L_1 \ : \quad
\frac{1}{2}+\epsilon \quad \rightarrow \quad
\frac{1}{2}+\epsilon+i(p+\epsilon) \quad \rightarrow \quad
\frac{1}{2}+i(p+\epsilon). $$
where $\epsilon>0$ is arbitrarily small and $p>0$ is fixed.

Question: Find the limit of the path integral
$$ \lim_{\epsilon\to 0^+} \Im\left(\int_{L_1} \frac{d}{ds} \log(s(s-1)) \, ds\right)$$

I tried the following:
First thought: Using fundamental theorem of calculus the path integral becomes
\begin{align*}
\int_{L_1} \frac{d}{ds} \log(s(s-1)) \, ds
&= \log\left[\left(\frac{1}{2}+i(p+\epsilon)\right)\left(-\frac{1}{2}+i(p+\epsilon)\right) \right] \\
&\quad -\log\left[\left(\frac{1}{2}+\epsilon\right)  \left(-\frac{1}{2}+\epsilon\right) \right].
\end{align*}
Hence we have
$$ \int_{L_1} \frac{d}{ds} \log(s(s-1)) \, ds
= \log\left(-(p+\epsilon)^2-\frac{1}{4}\right)-\log\left(\epsilon^2-\frac{1}{4}\right)$$
So we get
$$\lim_{\epsilon\to 0^+} \Im\left(\int_{L_1} \frac{d}{ds} \log(s(s-1)) \, ds\right) = i\pi-i\pi = 0$$
But my Professor says that the answer should be $\pi$. Please help me.

A: Note that
\begin{align*}
\operatorname{Im} \left( \int_{L_1} \frac{\mathrm{d}}{\mathrm{d}s} \log(s(s-1)) \, \mathrm{d}s \right)
&= \operatorname{Im} \left( \int_{L_1} \left( \frac{1}{s} + \frac{1}{s-1} \right) \, \mathrm{d}s \right) \\
&= \operatorname{Im} \left( \int_{L_1} \frac{1}{s} \, \mathrm{d}s \right) + \operatorname{Im} \left( \int_{L_1} \frac{1}{s-1} \, \mathrm{d}s \right).
\end{align*}
Now we invoke the following well-known fact that
$$ \operatorname{Im}\left( \int_{\gamma} \frac{\mathrm{d}z}{z - a} \right) = \text{[change of argument about $a$ along $\gamma$]} $$
for any piecewise $C^1$ path $\gamma$ not passing through $a$. This gives
\begin{align*}
\operatorname{Im} \left( \int_{L_1} \frac{1}{s} \, \mathrm{d}s \right)
&= \color{blue}{\arctan\left(2(p+\varepsilon)\right)}, \\
\operatorname{Im} \left( \int_{L_1} \frac{1}{s-1} \, \mathrm{d}s \right)
&= \color{red}{-\arctan\left(2(p+\varepsilon)\right)}, \\
\end{align*}
see the picture below as well.

Therefore, we have
$$ \operatorname{Im} \left( \int_{L_1} \frac{\mathrm{d}}{\mathrm{d}s} \log(s(s-1)) \, \mathrm{d}s \right) = 0 $$
and letting $\varepsilon \to 0^+$ still gives $0$.


text:
Q: Are JSONB indexes slower than native indexes? I have a large table (30M rows) which has ~10 jsonb B-tree indexes.
When I create a query using few conditions, the query is relatively fast.
When I add more conditions, especially one with a sparse jsonb index (e.g. an integer between 0 and 1,000,000), the query speed drops off dramatically.
I am wondering whether jsonb indexes are slower than native indexes? Would I expect a performance boost by switching to native columns rather than JSON?
Table definition:
id  integer
type    text
data    jsonb
company_index   ARRAY
exchange_index  ARRAY
eligible boolean

Example query:
SELECT id, data, type
FROM collection.bundles
WHERE ( (ARRAY['.X'] && bundles.exchange_index)  AND
type IN ('discussion') AND
( ((data->>'sentiment_score')::bigint > 0 AND
(data->'display_tweet'->'stocktwit'->'id') IS NOT NULL) )  AND
(  eligible = true  )  AND
((data->'display_tweet'->'stocktwit')->>'id')::bigint IS NULL )
ORDER BY id DESC
LIMIT 50

Output:
Limit  (cost=0.56..16197.56 rows=50 width=212) (actual time=31900.874..31900.874 rows=0 loops=1)
  Buffers: shared hit=13713180 read=1267819 dirtied=34 written=713
  I/O Timings: read=7644.206 write=7.294
  ->  Index Scan using bundles2_id_desc_idx on bundles  (cost=0.56..2401044.17 rows=7412 width=212) (actual time=31900.871..31900.871 rows=0 loops=1)
        Filter: (eligible AND ('{.X}'::text[] && exchange_index) AND (type = 'discussion'::text) AND ((((data -> 'display_tweet'::text) -> 'stocktwit'::text) -> 'id'::text) IS NOT NULL) AND (((data ->> 'sentiment_score'::text))::bigint > 0) AND (((((data -> 'display_tweet'::text) -> 'stocktwit'::text) ->> 'id'::text))::bigint IS NULL))
        Rows Removed by Filter: 16093269
        Buffers: shared hit=13713180 read=1267819 dirtied=34 written=713
        I/O Timings: read=7644.206 write=7.294
Planning time: 0.366 ms
Execution time: 31900.909 ms

Note:
There are jsonb B-tree indexes on every jsonb condition used in this query. exchange_index and company_index have GIN indexes.
UPDATE
After Laurenz's changed query:
Limit  (cost=150634.15..150634.27 rows=50 width=211) (actual time=15925.828..15925.828 rows=0 loops=1)
  Buffers: shared hit=1137490 read=680349 written=2
  I/O Timings: read=2896.702 write=0.038
  ->  Sort  (cost=150634.15..150652.53 rows=7352 width=211) (actual time=15925.827..15925.827 rows=0 loops=1)
        Sort Key: bundles.id DESC
        Sort Method: quicksort  Memory: 25kB
        Buffers: shared hit=1137490 read=680349 written=2
        I/O Timings: read=2896.702 write=0.038
        ->  Bitmap Heap Scan on bundles  (cost=56666.15..150316.40 rows=7352 width=211) (actual time=15925.816..15925.816 rows=0 loops=1)
              Recheck Cond: (('{.X}'::text[] && exchange_index) AND (type = 'discussion'::text))
              Filter: (eligible AND ((((data -> 'display_tweet'::text) -> 'stocktwit'::text) -> 'id'::text) IS NOT NULL) AND (((data ->> 'sentiment_score'::text))::bigint > 0) AND (((((data -> 'display_tweet'::text) -> 'stocktwit'::text) ->> 'id'::text))::bigint IS NULL))
              Rows Removed by Filter: 273230
              Heap Blocks: exact=175975
              Buffers: shared hit=1137490 read=680349 written=2
              I/O Timings: read=2896.702 write=0.038
              ->  BitmapAnd  (cost=56666.15..56666.15 rows=23817 width=0) (actual time=1895.890..1895.890 rows=0 loops=1)
                    Buffers: shared hit=37488 read=85559
                    I/O Timings: read=325.535
                    ->  Bitmap Index Scan on bundles2_exchange_index_ops_idx  (cost=0.00..6515.57 rows=863703 width=0) (actual time=218.690..218.690 rows=892669 loops=1)
                          Index Cond: ('{.X}'::text[] && exchange_index)
                          Buffers: shared hit=7 read=313
                          I/O Timings: read=1.458
                    ->  Bitmap Index Scan on bundles_eligible_idx  (cost=0.00..23561.74 rows=2476877 width=0) (actual time=436.719..436.719 rows=2569331 loops=1)
                          Index Cond: (eligible = true)
                          Buffers: shared hit=37473
                    ->  Bitmap Index Scan on bundles2_type_idx  (cost=0.00..26582.83 rows=2706276 width=0) (actual time=1052.267..1052.267 rows=2794517 loops=1)
                          Index Cond: (type = 'discussion'::text)
                          Buffers: shared hit=8 read=85246
                          I/O Timings: read=324.077
Planning time: 0.433 ms
Execution time: 15928.959 ms

A: All your fancy indexes are not used at all, so the problem is not if they are fast or not.
There are several things at play here:

*

*Seeing the dirtied and the written pages during the index scan, I suspect that there are quite a lot of "dead tuples" in your table. When the index scan visits them and notices they are dead, it "kills" those index entries so that subsequent index scans don't have to repeat that work.
If you repeat the query, you will probably notice that the number of blocks and the execution time becomes less.
You can reduce that problem by running VACUUM on the table or making sure autovacuum processes the table often enough.

*Your major problem, however, is that the LIMIT clause tempts PostgreSQL to use the following strategy:
Since you only want 50 result rows in an order for which you have an index, just examine the table rows in index order and discard all rows that do not match the complicated condition until you have 50 results.
Unfortunately it has to scan 16093319 rows until it has found its 50 hits. The rows at the "high id" end of the table don't match the condition. PostgreSQL does not know about that correlation.
The solution is to discourage PostgreSQL from going down that route. The easiest way would be to drop all indexes on id, but given its name that is probably unfeasible.
The other way is to keep PostgreSQL from "seeing" the LIMIT clause when it plans the scan:
SELECT id, data, type
FROM (SELECT id, data, type
      FROM collection.bundles
      WHERE /* all your complicated conditions */
      OFFSET 0) subquery
ORDER BY id DESC
LIMIT 50;

Remark: You didn't show your index definitions, but it sounds to be like you have quite a lot of them, possibly too many. Indexes are expensive, so make sure you define only those that give you a clear benefit.


text:
Q: How should I call splitted functions? centralize them? or call it one next to one? According to Is it OK to split long functions and methods into smaller ones even though they won't be called by anything else?, I should split long functions into smaller functions even if they are used once only, but my question is , how should I call the extracted functions?
Style 1: centralize them
callFunctions(){
    function1();
    function2();
    function3();
}

Style 2: call it one by one:
function1(){
  .
  .
  .
  function2();
}

function2(){
  .
  .
  .
  function3();
}

Which style should I use?

A: I prefer the centralized approach myself, rather than the chained approach.
With the chained approach, you're not gaining anything except a little bit of readability in that you now have a few small functions instead of one large one (and you're not really gaining any readability into the steps taken to complete the larger action, because you then have to read through each of the chained functions to see what's happening across the board).
With the centralized approach, you gain two distinct advantages:

*

*You can now very easily see, from the main function, what steps are required to complete the whole task

*Each of the smaller functions can now be more easily isolated in that they are less likely to have external factors governing how they run (e.g., you can more easily re-use some of these steps later, if need be)

A: In addition to jleach's answer, the reason the "centralized" approach is preferable is that code in functions should usually be at the same level of abstraction (see: Single Level of Abstraction).
In your example, callFunctions() is on a more abstract level, composing the necessary computations into finer steps functionN(). Then these "split" functions go into more detail and are less abstract.
Since functionN() is on this finer level of detail, calling other functionN()s, which is a function call on the higher level of abstraction, within functionN() would break the rule of "same level of abstraction within a function".


text:
Q: How is the syntax of Ruby's alias allowed? This one's been keeping me up at night for a while.
class Foo
  def bar
    'bar'
  end

  # What the hell is going on here?!?
  alias :baz :bar
end

Foo.new.baz #=> 'bar'

Why does alias take 2 symbol as arguments, but without a comma separating them? That doesn't seem to be any form of valid syntax in any other context.  And in fact, if you do use a comma, it actually throws a syntax error.
alias :bar, :baz
# syntax error, unexpected ','

However, if I try to pass 2 symbol in the same way to my own method, it also explodes:
def somemethod(*args)
  :whatever
end
somemethod :a :b
# syntax error, unexpected ':', expecting $end

*

*So why is the alias method get to use a syntax nothing else gets to use?

*Is it possible to use this syntax in any other context?

*What is the benefit of using this odd syntax quirk, when nothing else in the language works this way? I see no discernable benefit to this language inconsistency.

A: It's not a method, and those aren't arguments. alias is one of the few keywords in Ruby (see them all here!). It bothers me as well, so I switched to alias_method (and there are other arguments for this).

A: The reason alias works is because it's a Ruby keyword, similar to class, def, etc. It's not a method.
The alias keyword doesn't need a comma because the Ruby designers decided it didn't. Keywords are essentially hardcoded in the interpreter.
There is a good reason for alias when you need to be certain the alias happens at parse time, not runtime.
The alias keyword may be confusing or surprising. For typical development, I believe it's better to use the Ruby method Module#alias_method, which does use a comma and works at runtime.
Here's a good blog post about alias and alias_method:

This is because alias is a keyword and it is lexically scoped. It
  means it treats self as the value of self at the time the source code
  was read. In contrast alias_method treats self as the value
  determined at the run time.
Overall my recommendation would be to use alias_method. Since
  alias_method is a method defined in class Module it can be overridden
  later and it offers more flexibility.


text:
Q: Find string can be array I got a result like this :
const result = [ 'arg', 'arg2', '[opt1, opt2]' ]

How can I check in this array if a string can be a array ('[opt1, opt2]') and formate it in real array ?
Thank you
EDIT :
I explain all problem :
I want create a script :
yarn start arg1 arg2 "[option1, option2]"

I need a array of options but I can have a lot args without restrictions, when I recover the result :
const res = process.argv.slice(2)

How can I find my array of options ?

A: You can try the following solution with string manipulation

const result = ['arg', 'arg2', "[option1, option2]"]

const output = result.map(item => {
  if (/^\[.+\]$/.test(item)) {
    const prepared = item
      .replace('[', '["')
      .replace(']', '"]')
      .replace(/([a-zA-Z0-9]+),+\s+/g, '$1", "')
    return JSON.parse(prepared)
  }
  return item
})

console.log(output)

Explanation:

*

*/^\[.+\]$/ regex - checks whether the element is an array (based on the presence of matching square brackets)

*all other replace statements change the string into valid string encoded JSON array.

Since the overall result is a valid string encoded JSON array, just use JSON.parse after that and return it.


text:
Q: flutter contructor parameter optional not constant I would like to build a constructor which has a optional parameter. The problem is that this parameter does not receive a const value. How could I have a optional parameter which does not assign a constant value?.
In my code the optional parameter is called _id which uses the UniqueKey() function.
My code is the following:
import 'package:depresion/models/actividad.dart';
import 'package:flutter/widgets.dart';

class RegistroAnsiedad{

  late final UniqueKey _id;
  late final int _estado_animo;
  late final int _fecha;
  late final int _nivel_ansiedad;
  late final Actividad _actividad;

  RegistroAnsiedad(
      this._estado_animo,
      this._fecha,
      this._nivel_ansiedad,
      this._actividad,
      [this._id]
      )
  {
    this._estado_animo = _estado_animo;
    this._fecha = _fecha;
    this._nivel_ansiedad = _nivel_ansiedad;
    this._actividad = _actividad;
    this._id = UniqueKey();
  }

  UniqueKey get id => _id;
  int get estado_animo => _estado_animo;
  int get fecha => _fecha;
  int get nivel_ansiedad => _nivel_ansiedad;
  Actividad get actividad => _actividad;

  @override
  String toString() {
    return "Registro ansiedad [id=${this._estado_animo},"
        "fecha=${this._fecha},"
        "nivel_ansiedad=${this._nivel_ansiedad},"
        "actividad = ${this._actividad}]";
  }
}

Thanks in advance

A: Change your class as follows
 class RegistroAnsiedad{

  final UniqueKey _id;
  final int _estado_animo;
  final int _fecha;
  final int _nivel_ansiedad;
  final Actividad _actividad;

  RegistroAnsiedad(
      this._estado_animo,
      this._fecha,
      this._nivel_ansiedad,
      this._actividad,
      [UniqueKey id]
      ): this._id = id ?? UniqueKey();

  UniqueKey get id => _id;
  int get estado_animo => _estado_animo;
  int get fecha => _fecha;
  int get nivel_ansiedad => _nivel_ansiedad;
  Actividad get actividad => _actividad;

  @override
  String toString() {
    return "Registro ansiedad [id=${this._estado_animo},"
        "fecha=${this._fecha},"
        "nivel_ansiedad=${this._nivel_ansiedad},"
        "actividad = ${this._actividad}]";
  }
}


text:
Q: Using synchronous JAX in registration form for checking username availability I have a registration form. When I hit the Submit button it should check if the Username is not taken and that the passwords match. So I wrote a few functions: one that checks the passwords, one that checks if the username is available and the main function, that calls for the 2 checking functions. The password checking function works nice, but my problem is with the username checking function. This is the function:
function checkIsUsernameExist(){
    if($("#txtNewUsername").val() == "") {
        $("#divIsUsernameExist").html("");
        return false;
    } else {
    $.getJSON("inc/API.php",
        {
            command : 'isUsernameExist',
            username : $("#txtNewUsername").val(),
        },
        function(result)
        {
            if (result != true){
                $("#divIsUsernameExist").html("This username is available!");
                return true;
            } else {
                $("#divIsUsernameExist").html("This username is not available!");
                return false;
            }
        });
    }
}

When the username is empty, it does return False. But when some value is entered it returns Undefined.
Somebody told I should use Synchronous JAX (but didn't tell me how), so I tried to write this code:
function checkIsUsernameExistAsync(){
    if($("#txtNewUsername").val() == "") {
        $("#divIsUsernameExist").html("");
        return false;
    } else {
        $.ajax({
            type: 'POST',
            url: 'inc/API.php',
            data: ({
            command : 'isUsernameExist',
            username : $("#txtNewUsername").val(),
            cache: false,
            async: false
            }),
    success: function(result){
        if (result != true){
                $("#divIsUsernameExist").html("This username is available!");
                return true;
            } else {
                $("#divIsUsernameExist").html("This username is not available!");
                return false;
            }
        }
    });
    }
}

But I get the same result - False when it's empty, Undefined when some value is entered. I tried to change $.ajaxto $.getJSON in the second function, but still had the same result.
This is the code from API.php:
case "isUsernameExist":
        echo (isUsernameExist($_REQUEST["username"]));
        break;

it calls for a function in included page BusinessLogic.php, here's this function:
function isUsernameExist($username)
{
    $arr = select("select * from users where username='$username'");
    if(count($arr) == 1)
    return json_encode(true);
    else
    return json_encode(false);
}

How can I make it work??
Thank you!

A: To summarise the comment chain:

*

*Avoid synchronous AJAX requests: Remove async: false

*Add `dataType: 'json',

*return inside a success handler of jQuery.ajax does not set the return value of the outer function. To correctly pass the results, define a callback handler. Replace:

*Before: http://jsfiddle.net/wGfzc/

*After: http://jsfiddle.net/wGfzc/2/


text:
Q: How do you disable the CPU window in Delphi 7 When stepping a program in Delphi 7, the CPU window sometimes pops up and then steps through that instructions. I find this an annoyance as I wish to only step Pascal Code.
Does anyone know how to disable this CPU pop-up?
I would not be sorry if this window never ever shows.
It did not happen on Delphi 5 which was my previous IDE that I used for Delphi. I do use the Step-Over button mostly and only step-into when wanting to get into detail of a used (pascal) unit.

A: Delphi does not, by default, step into the CPU window. So the answer to your question is not that it can not be done. Maybe the question should be: What did I do that causes this.
EDIT:
From the comments I understand that it happens when you press pause to break in the debugger.
It is not strange that it stops on the exact place where it was executing when you hit pause.
This could very well be in some Windows code for which you do not have the source.
By choosing Run -> Run to Next Source Line or Shift-F7 your program will execute a bit further until it hits some code for which it does have source code.
This is the answer to your problem, but remember that you could have breaked in a spot where you never reach a next source line.

A: it seems that i resolved it: added to the registry:
HKCU\Software\Borland|Delphi\7.0\Debugging: EnableCPU (stringvalue):0

A: Modify the following registry key:
HKEY_CURRENT_USER/software/Borland/Delphi/6.0/Debugging/Integrated Debugging = 0

A: In RAD studio 2009, you can got to Tools->Options->Debugger Options->Codegear Debuggers. In General, select Ignore non-user breakpoints.

A: You fall into the CPU-Window when there are no Debug-Informations for the current Unit.
Try to enable the Debug-DCU's (in Project/Options.../Compiler). If you haven't checked the other debug options, activate them also.


text:
Q: How to add text to end of link to single product page in Woocommerce I am working on a project in Woocommerce. The link structure (slug) on the single product page is the direct product name. For example, if the product name is "x brand computer" link: www.example.com/x-brand-computer-link
What I want to do is to always add a new text "at the end of the link" on the single product page.
For example, like abc
www.example.com/x-brand-computer-link-abc
I found many example solutions for Prefix. However, I couldn't find an example of "for end of link". What's more, I couldn't find any examples of a single product page. I would be very grateful if someone could guide me.

A: Yes, it is possible.
Sample code, has to be tested and refined:
// get all posts
$posts = get_posts( array (  'numberposts' => -1 ) );

foreach ( $posts as $post )
{
    // check the slug and run an update if necessary
    $new_slug = sanitize_title( $post->post_title );
    if ( $post->post_name != $new_slug )
    {
        wp_update_post(
            array (
                'ID'        => $post->ID,
                'post_name' => $new_slug
            )
        );
    }
}


text:
Q: junit, get the failed method name I am using Junit and I want to log the test method name and maybe some stack trace when the test fails, is there a way to do that?
I have my example code below:
public class TestGoogleHomePage extends Browser {

@Test
public void testLoadGoogle() {
       ...............
       //assume this case will fail
}

@Test
public void testSearchGoogle() {
       .......
}

  @Rule
public TestWatcher watchman = new TestWatcher() {

    @Override
    protected void failed(Throwable e, Description description) {
        System.out.println("test fail");
        System.out.println(Thread.currentThread().getStackTrace()[1]
                .getMethodName());
    }

    @Override
    protected void succeeded(Description description) {
    ......

    }
};

}
The statement System.out.println(Thread.currentThread().getStackTrace()[1] .getMethodName()); will print method failed, instead of testLoadGoogle. Is there a way I can capture the name of the failed method instead?
Can I also print the stack trace as well?
Also if I can avoid adding extra codes in the actual test for this purpose, it will be great. Because I don't want to repeat that codes for every of my test case.
Thanks advance for your help.

A: The Description class has a getMethodName() method that states

Returns
If this describes a method invocation, the name of the method (or null
  if not)

So just call it
System.out.println(description.getMethodName());


text:
Q: Random "spawn" of divs I'm trying to create a "spawn point" for a div.  I have made it work and I have a working collision detector for it.  There are two things I wanted to ask regarding my code.

*

*How do I get my code to work with more than one player (window.i).  - At the moment, after an hour of fiddling, I've only broken my code.  This whole area screws up the collision detector, I have more than one player showing at times, but I'm unable to move.

*How do I make it so that it detects the contact before it happens - I've tried working with the "tank's" margin and subtracting it's width, so that before it makes contact it calls an event, but it has been unsuccessful and completely stopped the collision function working.
I'm sorry that it's asking a lot, I really do understand that, but the issues come into eachother and rebound off so I thought it was best I put it all into one question rather than 2 separate ones an hour apart.
function animate() {
    var tank = document.createElement("div");
    tank.id= "tank";
    tank.style.marginLeft="0px";
    tank.style.marginTop="0px";
    tank.style.height="10px";
    tank.style.width="10px";
    document.body.appendChild(tank);

    x = parseInt(tank.style.marginLeft);
    y = parseInt(tank.style.marginTop);

    document.onkeydown = function () {

        e = window.event;
        if (e.keyCode == '37') {
            if (x > 0) {
                if (collisionDetector() == false) {
                    x = x - 10;
                    tank.style.marginLeft = x + "px";
                } else {
                    alert();
                }
            }
        } else if (e.keyCode == '39') {
            if (x < 790) {
                if (collisionDetector() == false) {
                    x = x + 10;
                    tank.style.marginLeft = x + "px";
                } else {
                    alert();
                }
            }
        } else if (e.keyCode == '38') {
            if (y > 0) {
                if (collisionDetector() == false) {
                    y = y - 10;
                    tank.style.marginTop = y + "px";
                } else {
                    alert();
                }
            }
        } else if (e.keyCode == '40') {
            if (y < 490) {
                if (collisionDetector() == false) {
                    y = y + 10;
                    tank.style.marginTop = y + "px";
                } else {
                    alert();
                }
            }
        }
    }
}
window.lives = 3;

function playerSpawn() {
window.i = 1;
while (i > 0) {
        var player = document.createElement("div");
        randMarL = Math.ceil(Math.random()*80)*10;
        randMarT = Math.ceil(Math.random()*50)*10;
        player.id = "player";
        player.style.marginLeft= randMarL + "px";
        player.style.marginTop= randMarT + "px";
        player.style.height="10px";
        player.style.width="10px";
        document.body.appendChild(player);
        i--;
    }
}
function collisionDetector() {
    x1 = tank.style.marginLeft;
    x2 = player.style.marginLeft;
    y1 = tank.style.marginTop;
    y2 = player.style.marginTop;
    if ((x1 == x2 && y1 == y2)) {
        return true;
    } else {
        return false;
    }
}


text:
Q: How to make all buttons function from a template literal I am trying to change the buttons display type to block, but only the first button works. Here is my code:
const descriptions = ['Hi', 'Bonjour', 'Guten Tag', 'Hola', 'Zdravstvuyte', 'Nǐn hǎo', 'Salve', 'Konnichiwa', 'Olá', 'Goddag', 'Shikamoo', 'Goedendag']

//Loop created to do its magic for the array
for (let i = 0; i <= 11; i++) {
    images.push(`<div><img src="${links[i]}"> <button id="myBtn">More info</button><div id='descriptions' style="display: none;">${descriptions[i]}</div></div>`)
}

//Images have been dynamically added!
$images.innerHTML += images.join(' ')

//Event listener so the buttons can function
$images.addEventListener('click', function (event){
    if (event.target.id == 'myBtn') {
       document.getElementById('descriptions').style.display = 'block'
       console.log('button clicked')

    }

A: AS mentioned don't use multiple IDs. IDs must be unique, that is what makes them IDs
Use a sane data structure instead of multiple arrays.
The data is iterated once, do the work there, using a documentFragment, so the DOM is not continually updated.
Finally, use CSS not inline styles adding an active class on button click.

//Use a sane data structure instead of multiple arrays
images = [
  {"link": "Hi.jpg",
   "description": "Hi"
   },
   {"link": "Bonjour.jpg",
   "description": "Bonjour"
   },
   {"link": "Guten-Tag.jpg",
   "description": "Guten Tag"
   },
   {"link": "Hola.jpg",
   "description": "Hola"
   },
   {"link": "Zdravstvuyte.jpg",
   "description": "Zdravstvuyte"
   },
   {"link": "Nǐn-hǎo.jpg",
   "description": "Nǐn hǎo"
   },
   {"link": "Salve.jpg",
   "description": "Salve"
   },
   {"link": "Konnichiwa.jpg",
   "description": "Konnichiwa"
   },
   {"link": "Olá.jpg",
   "description": "Olá"
   },
   {"link": "Goddag.jpg",
   "description": "Goddag"
   },
   {"link": "Shikamoo.jpg",
   "description": "Shikamoo"
   },
   {"link": "Goedendag.jpg",
   "description": "Goedendag"
   }
];

//Get the image
$images = document.getElementById("images");
//Create  frament to do the work in
var fragment = new DocumentFragment();
fragment.innerHTML = "";
//Iterate the data, never hard code a number here, use the length of your data array
for (let i = 0; i < images.length; i++) {
  //update the fragment
  fragment.innerHTML += `<div><img src="${images[i].link}"> <button class="myBtn">More info</button><div class='descriptions'>${images[i].description}</div></div>`;
}

//UPdate the host elemen
$images.innerHTML =fragment.innerHTML;
//Event listener
$images.addEventListener('click', function(event) {
      //If myBtn clicked
      if (event.target.matches('.myBtn')) {
        //Find parent div
        let parent = event.target.closest("div");
        //Find descriptions element and add active class
        parent.querySelector(".descriptions").classList.add("active");

      }
})
.descriptions:not(.active) {
  display:none;
}

A: don't use multiple id read comment above, use class instead. you need is .nextElementSibling to select element after the button.

const links = ["Hi.jpg", "Bonjour.jpg", "Guten-Tag.jpg", "Hola.jpg", "Zdravstvuyte.jpg", "Nǐn-hǎo.jpg", "Salve.jpg", "Konnichiwa.jpg", "Olá.jpg", "Goddag.jpg", "Shikamoo.jpg", "Goedendag.jpg"];
const descriptions = ['Hi', 'Bonjour', 'Guten Tag', 'Hola', 'Zdravstvuyte', 'Nǐn hǎo', 'Salve', 'Konnichiwa', 'Olá', 'Goddag', 'Shikamoo', 'Goedendag']
images = [];

$images = document.body;

//Loop created to do its magic for the array
for (let i = 0; i <= 11; i++) {
  images.push(`<div><img src="${links[i]}"> <button class="myBtn">More info</button><div id='descriptions' style="display: none;">${descriptions[i]}</div></div>`)
}

//Images have been dynamically added!
$images.innerHTML += images.join(' ')

//Event listener so the buttons can function
$images.addEventListener('click', function(event) {
      if (event.target.classList.contains('myBtn')) {
        event.target.nextElementSibling.style.display = 'block'
        console.log('button clicked')

      }
})


text:
Q: How to don't display some values in my search box? I need to know how to make some values with display: none, based of a column from database?
So, I need to disable the items with value="1" from column active, from table news, but I don't know how to do that in my scripts.
Here is the script for search:
    else if(searchcategory == 'news')
            {
                get_values['search'] = search;
                get_values['news_category_url'] = $('#header_news_category_select').val();

                $.ajax(
                {
                    url: "{{ url('search-news-ajax') }}",
                    // data: {get_values:get_values},
                    type: 'GET',
                    data: {
                      '_token': $('input[name=_token]').val(),
                      'get_values': get_values,
                    },
                    success: function( response )
                    {

                        href = '{{ url("view-all-news") }}?category='+ get_values['news_category_url'] + '&search=' + search;

                        response +=
                            '
'+
                                ''+
                                    '

Find more with '+
                                         search +
                                    '

'+
                                ''+
                            '
';
                            // console.log(html);

                             $('.search-item-list').html(response);
                             $(".search-item-list").show();
                             $(".removelist").show();
                    }

                });

            }

NewsController:
     public function searchNewsAjax(requ $request)
    {
        // return $request->all();
        $categoryID =  \App\Category::pluck('id');

        $news = News::with('category')->whereHas('user', function($query) {
                    $query->where('deleted_at', '=', null);
                })->whereIn('category_id',$categoryID);

        if ($user = Sentinel::check())
        {
            if(!$user->inRole('admins'))
            {
                $id = $user->id;
                $news = $news->Where(function($query1) use($id){
                        $query1->where('public','=', 1)->orWhereHas('user.contact', function ($query) use ($id) {
                            $query->where('user_id', '=', $id);
                            })->orWhere('user_id','=',$id);
                });
            }
        }
        else{
            $news = $news->where('public','=', 1);
        }

        $news = $news->where('subject', 'LIKE', '%'.$request['get_values']['search'].'%');

        if(!empty($request['get_values']['news_category_url']))
        {
            $category_id = \App\Category::where('category_url', '=' ,$request['get_values']['news_category_url'])->pluck('id');
            $news = $news->where('category_id', '=',$category_id);
        }

        $news = $news->orderBy('date', 'desc')->take(5)->get();

             $news_data = [];
            foreach ($news as $key => $value) {
                $news_data[$key] = $value;
                $news_data[$key]['subject_url'] = Slugify::slugify($value->subject);
            }
            // echo json_encode($news);
            $data['news'] = $news;
            return view('preview.news',$data);

    }

Here is the view:

                            <input style="height: 33px !important;" class="form-control" placeholder="Search for Jobs, Courses, Career planning and more…" type="text" id="global_search_text" name="search">

                                <button class="btn-u submit" type="button">Go</button>

                            Jobs
jobs

                            Courses
jobs

                            Events
jobs

                            News
jobs

                            Opinions

So, here is my example, first record has in database value 1 at column active, which is disabled.I need to not displaying this records at search, with value 1 in database at column active, table news

I know that is too easy to make that from controller, but I didn't find it anymore, this isn't my code, and I don't know if that's exists because this in on my header layout.I want to know if this is possible, only by scripts.

A: Try this
$news = News::with('category')->whereHas('user', function($query) {
$query->where('deleted_at', '=', null);
})->whereIn('category_id',$categoryID)->where("value","!=",1);

A: change your code with this code below:
public function searchNewsAjax(requ $request)
        {
            // return $request->all();
            $categoryID =  \App\Category::pluck('id');

            $news = News::with('category')->whereHas('user', function($query) {
                        $query->where('deleted_at', '=', null);
                    })->whereIn('category_id',$categoryID)
                    ->where('active','<>',1) // notice this line.. this is what you need.
                    ;

            if ($user = Sentinel::check())
            {
                if(!$user->inRole('admins'))
                {
                    $id = $user->id;
                    $news = $news->Where(function($query1) use($id){
                            $query1->where('public','=', 1)->orWhereHas('user.contact', function ($query) use ($id) {
                                $query->where('user_id', '=', $id);
                                })->orWhere('user_id','=',$id);
                    });
                }
            }
            else{
                $news = $news->where('public','=', 1);
            }

            $news = $news->where('subject', 'LIKE', '%'.$request['get_values']['search'].'%');

            if(!empty($request['get_values']['news_category_url']))
            {
                $category_id = \App\Category::where('category_url', '=' ,$request['get_values']['news_category_url'])->pluck('id');
                $news = $news->where('category_id', '=',$category_id);
            }

            $news = $news->orderBy('date', 'desc')->take(5)->get();

                 $news_data = [];
                foreach ($news as $key => $value) {
                    $news_data[$key] = $value;
                    $news_data[$key]['subject_url'] = Slugify::slugify($value->subject);
                }
                // echo json_encode($news);
                $data['news'] = $news;
                return view('preview.news',$data);

        }


text:
Q: How to include interactive java-based web pages inside LaTeX generated PDF documents Is it possible to open an interactive web page, such as this, inside a latex generated pdf page?

A: Not unless you program a PDF viewer that includes a JRE. AFAIK Adobe Reader does not.


text:
Q: Where are enterprise keywords stored, if MMS connection isn't configured? In Exam Ref 70-331: Core Solutions of Microsoft SharePoint Server 2013 one can read the following quote:

"When you are adding new keywords, you might see this message: The Site Does Not Contain A Default Keywords Term Store. This occurs when you have not yet selected the default storage location for keywords within your SharePoint environment."

If default keywords term store isn't configured, where are enterprise keywords stored (if they are stored at all)?

A: If there is no default storage of keywords, than none can be saved. You'll always end up with an error which guides you to check the checkbox of default keyword term store in one of your Managed Metadata Services.

The first one (where you check to see if Default Keyword Term Store is null or not) ties back to a Managed Metadata Service (MMS) Application configuration option. There's a checkbox on the service application's property page (the property page for the indented one) that controls whether or not this is the default keyword term store. If that's not checked and this is the only MMS application available to your farm, site.DefaultKeywordsTermStore will always be null.

Reference: Correctly Provisioning Managed Metadata (Taxonomy) Fields


text:
Q: perl parse html tree buidler or element or parser I'm trying to extract some information html using perl. I found out about TreeBuilder and Element and Parser, which one should i use?
How would I extract the name and the value of the row below?
Also this is embedded in an html structure, the only way to really target which field I want is given the value of the column "Number of directories".
Or should I just do a regex on the entire html?

Number of directories	:	 80

Number of monitored source files	:	 425

Number of functions	:	 6245

Number of source lines	:	 3245

Number of measurement points	:	 2457

TER	:	 12% (decision)

A: If you need to extract data from an HTML table, then
use HTML::TableExtract;

would be a good choice.

A: Of course everyone is going to have their own favorite. I prefer HTML::TokeParser, I find it easy to understand and use (once you get over the hump of how the return arrays work). Of course I have to point you to the SO classic post, reminding you to please not parse HTML with regular expressions.

A: There are a few steps.

*

*Use one of HTML::TreeBuilder's constructors to parse the HTML.

*Convert the HTML::TreeBuilder object at the root into an HTML::Element by calling elementify.

*Understand the structure of your HTML well enough that you can tell HTML::Element::look_down() how to find the bits you are interested in.  You can specify criteria in almost any form imaginable.

*Use HTML::Element::look_down(), content_list(), left(), right() and related methods to traverse the area of interest and extract data.  DO NOT USE traverse()--it was a bad idea.

*Pass the data you collected to whatever system asked for it in the first place.

Here's some code:
my $blarg = <<'END_HTML';

Number of directories	:	 80

Number of monitored source files	:	 425

Number of functions	:	 6245

Number of source lines	:	 3245

Number of measurement points	:	 2457

TER	:	 12% (decision)

END_HTML

# Use any of the constructors to get your base object.  See the pod.
my $tree = HTML::TreeBuilder->new_from_content($blarg);

$tree->elementify;  # Make it just a plain HTML::Element object.

# Iterate over a list of rows:  look_down and related functions provide powerful ways to find matching elements.  Read the pod for more details.
my %crud_from_table;
for my $row ( $tree->look_down( _tag => 'tr' ) ) {
    my ($key, $value) = map $_->as_text, $row->content_list;  # assumes two td per row.
    $crud_from_table{$key} = $value;
}

The most important part lies in understanding and being able to describe to look_down() how to find your desired information.  Sometimes you can zoom right to it by matching an id.  Other times you have to look for the third div of class 'foo' with a table in it.  This is also the hardest and the part that I can help you with the least.  You are just going to have to experiment.
Good luck.


text:
Q: How do I handle C++ dependencies that conflict on a type name? I'm running CI on a project on linux and macOS. This project depends on Google's V8 and the Cairo graphics library. Recently, the macOS builds have started failing because apparently on macOS, Cairo includes some mac header that defines Boolean. However, V8 also defines a Boolean type. How would I solve this kind of issue?
https://travis-ci.org/github/romgrk/node-gtk/jobs/736552109

A: If the Boolean is a MACRO in one of these two libraries then you can strategically undefine/refefine the MACRO upon inclusion of headers. If it is a type/alias/class/struct in both cases then it is more complex.
If the definitions match then this shouldn't be a problem otherwise this is an ODR (one definition rule) issue and according to C++ standart violating it is strictly forbidden. So you need a work around.
Simplest and most reliable method is to rename all Boolean of one kind to something else. If you work with external library you cannot modify then submit bug report. Other option is to link to the libraries as shared libraries so the Boolean is never defined twice in your code (hopefully Boolean isn't an exported type and used internally only).