text:
Q: How to correctly create a date condition using moment js There is a table with data and dates. Please help me to make a correct condition so that when it is triggered, the date will be coloured in different colours.
The table has a Deadline column. I need the date to be colored red 5 days before the deadline, and gray after the date has passed. In other cases it is black. All in all I'm not really getting it right. The date in the column is written in this order 2023-02-01
moment(currentRow["Deadline"]).fromNow() >= "in 5 days"?'#f50202' : moment(currentRow["Deadline"]).fromNow() > "in 0 days"?
'#0d0d0d' : '#999999'

Tried working with a simple condition if the deadline date is less than the current text is greyed out.
I can't find a solution to the more complex condition yet.

A: moment's fromNow method returns a string, so you are comparing strings, not relative times.
The >= operator will compare the strings character by character until it reaches different characters, then returns the result of that comparison. So "2 hours ago" >= "1 year ago" will return true when you might expect it to return false. Similarly "in 5 minutes" >= "in 4 years" will also return true.
What you need is something like:
moment(currentRow["Deadline"]) >= moment().add(5, 'days')

or, if you want to just compare the date and ignore time:
moment(currentRow["Deadline"]) >= moment().add(5, 'days').startOf('day')

Note that if currentRow["Deadline"] does not resolve to a format understood by moment.js, you should also include the format so that it is parsed correctly, otherwise it will fall back to implementation dependent heuristics for parsing.


text:
Q: How to restart host nginx from inside docker after certbot renew If you have a docker container running certbot, but a nginx instance usign those certificates running on the host, how do you restart the host nginx from inside the docker container?
This is the running container
certbot:
    image: certbot/dns-ovh
    container_name: certbot
    volumes:
      - /etc/letsencrypt/:/etc/letsencrypt
      - /var/lib/letsencrypt:/var/lib/letsencrypt
      - /root/.secrets/certbot-ovh.ini:/root/.secrets/ovh-creds.ini
    entrypoint: /bin/sh -c 'trap exit  TERM; while :; do certbot renew sleep 12h & wait $${!}; done;'

A: You have to add a --post-hook to the renew command, which uses ssh to send the nginx reload command to the host.
For this to work, the container needs to be run with network_mode: "host"
then you need to isntall sshpass and openssh when starting/recreating the container. this is done with
apk add openssh sshpass
then in the post-hook you need to ssh into the host and reload nginx
sshpass -p 'your password' ssh -o 'StrictHostKeyChecking no' root@localhost 'systemctl reload nginx'
assuming you have root access. This uses sshpass to enter the password in ssh which skips the "do you want to add the fingerprint" message and sends the relaod command to localhost
putting this all into the docker-compose file looks like this:
  certbot:
    image: certbot/dns-ovh
    container_name: certbot
    network_mode: "host"
    volumes:
      - /etc/letsencrypt/:/etc/letsencrypt
      - /var/lib/letsencrypt:/var/lib/letsencrypt
      - /root/.secrets/certbot-ovh.ini:/root/.secrets/ovh-creds.ini
    entrypoint: >
      /bin/sh -c
      'apk add openssh sshpass &&
      trap exit  TERM; while :;
      do certbot renew --post-hook
      "sshpass -p '"'"'your password'"'"' ssh -o '"'"'StrictHostKeyChecking no'"'"' root@localhost '"'"'systemctl reload nginx'"'"'";
      sleep 12h & wait $${!}; done;'

the > here allows for writing as many indented lines as i want, without needing to add anotehr layer of escaping. it also combines the lines into one line later.
the '"'"' used here is used to escape the singe ' inside the --post-hook quotes, it closes the first single quote, opens a new double quote which contains a single quote, and then opens the single quote again.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tensorflow Cloud ML Object Detection - Errors with Distributed Training I'm trying to follow Tensorflow's Object Detection tutorial for distributed training my own model but am using the code exactly as is from the repository.
I've made a couple changes from the tutorial, notably to use runtime 1.5 instead of 1.2 as said in the tutorial. There aren't any explicit errors (that I can see) when I try running on Google Cloud ML, but the task quickly exits without training.
Here's the command I use to start the training job:
gcloud ml-engine jobs submit training object_detection_`date +%s`
    --job-dir=gs://test-bucket/training/
    --packages dist/object_detection-0.1.tar.gz,slim/dist/slim-0.1.tar.gz
    --module-name object_detection.train
    --region us-central1
    --config ./config.yaml
    --
    --train_dir=gs://test-bucket/data/
    --pipeline_config_path=gs://test-bucket/configs/ssd_inception_v2_coco.config

And this is my config.yaml:
trainingInput:
  runtimeVersion: "1.5"
  scaleTier: CUSTOM
  masterType: complex_model_l
  workerCount: 9
  workerType: standard_gpu
  parameterServerCount: 3
  parameterServerType: large_model

And finally the logs from my job finishing up:
I  worker-replica-6 Clean up finished.  worker-replica-6
I  worker-replica-7 Signal 15 (SIGTERM) was caught. Terminated by service. This is normal behavior.  worker-replica-7
I  worker-replica-7 Module completed; cleaning up.  worker-replica-7
I  worker-replica-7 Clean up finished.  worker-replica-7
I  worker-replica-8 Signal 15 (SIGTERM) was caught. Terminated by service. This is normal behavior.  worker-replica-8
I  worker-replica-8 Module completed; cleaning up.  worker-replica-8
I  worker-replica-8 Clean up finished.  worker-replica-8
I  worker-replica-1 CreateSession still waiting for response from worker: /job:master/replica:0/task:0  worker-replica-1
I  worker-replica-1 Signal 15 (SIGTERM) was caught. Terminated by service. This is normal behavior.  worker-replica-1
I  worker-replica-1 Module completed; cleaning up.  worker-replica-1
I  worker-replica-1 Clean up finished.  worker-replica-1
I  worker-replica-7 CreateSession still waiting for response from worker: /job:master/replica:0/task:0  worker-replica-7
I  worker-replica-8 CreateSession still waiting for response from worker: /job:master/replica:0/task:0  worker-replica-8
I  worker-replica-6 CreateSession still waiting for response from worker: /job:master/replica:0/task:0  worker-replica-6
I  worker-replica-3 CreateSession still waiting for response from worker: /job:master/replica:0/task:0  worker-replica-3
I  worker-replica-0 CreateSession still waiting for response from worker: /job:master/replica:0/task:0  worker-replica-0
I  worker-replica-2 CreateSession still waiting for response from worker: /job:master/replica:0/task:0  worker-replica-2
I  worker-replica-5 CreateSession still waiting for response from worker: /job:master/replica:0/task:0  worker-replica-5
I  worker-replica-1 CreateSession still waiting for response from worker: /job:master/replica:0/task:0  worker-replica-1
I  worker-replica-7 CreateSession still waiting for response from worker: /job:master/replica:0/task:0  worker-replica-7
I  worker-replica-8 CreateSession still waiting for response from worker: /job:master/replica:0/task:0  worker-replica-8
I  worker-replica-6 CreateSession still waiting for response from worker: /job:master/replica:0/task:0  worker-replica-6
I  worker-replica-3 CreateSession still waiting for response from worker: /job:master/replica:0/task:0  worker-replica-3
I  worker-replica-0 CreateSession still waiting for response from worker: /job:master/replica:0/task:0  worker-replica-0
I  worker-replica-2 CreateSession still waiting for response from worker: /job:master/replica:0/task:0  worker-replica-2
I  worker-replica-5 CreateSession still waiting for response from worker: /job:master/replica:0/task:0  worker-replica-5
I  worker-replica-1 CreateSession still waiting for response from worker: /job:master/replica:0/task:0  worker-replica-1
I  worker-replica-7 CreateSession still waiting for response from worker: /job:master/replica:0/task:0  worker-replica-7
I  worker-replica-8 CreateSession still waiting for response from worker: /job:master/replica:0/task:0  worker-replica-8
I  worker-replica-6 CreateSession still waiting for response from worker: /job:master/replica:0/task:0  worker-replica-6
I  Finished tearing down TensorFlow.
I  Job failed.

As I mentioned, I haven't been able to get something useful from the logs. A bit further up I get this error Master init: Unavailable: Stream removed but am unsure how to handle this. Thanks for any push in the right direction!

A: I reproduced your issue. I fixed it following this:

roysheffi commented on this issue 3 months ago. Hi @pkulzc, I think I
  may have a lead:
On line 357, object_detection/trainer.py calls
  tf.contrib.slim.learning.train() which uses the deprecated
  tf.train.Supervisor and should be migrated to
  tf.train.MonitoredTrainingSession instead, as documented in
  tf.train.Supervisor
This is already requested in tensorflow/tensorflow#15793 and is
  reported as a solution to tensorflow/tensorflow#17852 on the last
  comment of yahoo/TensorFlowOnSpark#245. [1]

So, in the end, I did this inside trainer.py:

*

*Put tf.train.MonitoredTrainingSession( instead of slim.learning.train(


text:
Q: How can I mock a method globally for all tests in python My Django project has hundreds of test in various modules across a number of apps. Recently we added a feature where an email gets sent (via sendgrid) on creation of a User object (using Django Signals).
The problem we ran into is that when running tests, many users are created either explicitly or as fixtures. This results in many hundreds of emails being sent on each test cycle, and because most of them are invalid we get hundreds of bounces. In addition to the costs involved, Sendgrid actually suspended our account briefly due to the odd behaviour.
Obviously I can mock the call on each test individually, however this would have to take place in hundreds of places, and we would have to remember to do it on all future tests we create.
Is there an easier way to globally mock a particular chunk of code for all tests (leaving it intact for when actually running of course)

A: I don't use Django and maybe there is some idiomatic way to do it well in Django.
My approach to this kind of problem is to create my own TestCase class that extend from unittest.TestCase and override setUpClass()/tearDownClass/setUp()/tearDown() to set up the mock/patch that I need globally in my tests (or at least in a part of them).
Now every time I need it instead of importing unittest.TestCase module I'm importing myunittest.TestCase
Example: myunittest.py
import unittest

class TestCase(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        super(TestCase, cls).setUpClass()
        # Init your class Mock/Patch

    @classmethod
    def tearDownClass(cls):
        # Remove Mocks or clean your singletons
        super(TestCase, cls).tearDownClass()

    def setUp(self):
        super(TestCase, self).setUp()
        # Init your obj Mock/Patch

    @classmethod
    def tearDown(self):
        # ... if you need it
        super(TestCase, self).tearDown()

And in your tests:
from myunittest import TestCase

    class Test(TestCase):
        ... Your test

A: Two ways that I have used in a big django project
Assuming a: my_mock = patch("myapp.mymodule.MyClass.my_method")
1) You can add a mock inside a custom test runner class:
from mock import patch
from django.test.runner import DiscoverRunner

class MyTestRunner(DiscoverRunner):
    @my_mock
    def run_tests(self, test_labels, **kwargs):
         return super(MyTestRunner, self).run_tests(test_labels, **kwargs)

2) You can add a mock on a custom base test class:
from mock import patch
from django.test import TestCase

class MyTestCase(TestCase):

   def setUp(self):
      super(MyTestCase, self).setUp()
      my_mock.start()

   def tearDown(self):
      super(MyTestCase, self).tearDown()
      my_mock.stop()

A: Below are two methods to implement mocking.
Method 1: With modifications to production code:
You can create a pseudo-package and import it for testing instead of importing the original package. This check-based-import could be done at the beginning of every file.
For example:
import os
    if 'TEST' in os.environ:
        import pseudoTime as time
    else:
        import time

print time.time

Method 2: No modifications to production code:
In your test program, you could import the utility package ( the package containing the email function described in the question) and overwrite the utility function.
For example:
Consider the following code:
import time
def function():
    return time.time()

The test code could do the following:
import code
import time

def helloWorld():
    return "Hello World"

print "Before changing ...", code.function()
oldTime = time.time # save
time.time = helloWorld
print "After changing ...", code.function()
time.time = oldTime # revert back

The output for above test was:
Before changing ... 1456487043.76
After changing ... Hello World

Thus the test code can import the utility file, overwrite the function it provides and then run the tests on production code.
This method is superior as it does not change production code.


text:
Q: How do I display content if local Storage is null or empty I have a PhoneGap application which displays an RSS feed. I am using local Storage to save a favorite category for the user, and call it from local storage when the application loads. However, when the application is first installed it should display the general RSS feed.
For some reason the RSS feed comes up blank until a category is selected. Then when the application is reloaded, it works fine. Can someone help with this? Thanks!
Here is what I have to check the local storage:
//get local storage item
var rssURL = localStorage.getItem('url');

//set the URL for the ajax call in case there is no stored item
var URL = 'http://www.RssUrlHere.com';

//if the localstorage is undefined or null, use the general RSS url , if not get assign stored URL Note: also tried != to see if that made a difference, it did not.
if (rssURL !== "undefined" || rssURL !== "null") { URL = rssURL }

//comparing the URL with category URLs, works fine but clunky!
                if(URL == 'http://www.RssUrlHere.comA') { $('#header-title').html("Bioengineering"); $('#event-title').html("Bioengineering");}
                else if (URL == 'http://www.RssUrlHere.comB') { $('#header-title').html("Communications"); $('#event-title').html("Communications");}
                else if (URL == 'http://www.RssUrlHere.comC') { $('#header-title').html("Electrical/Power"); $('#event-title').html("Electrical/Power");}
                else if (URL == 'http://www.RssUrlHere.comD') { $('#header-title').html("Electronics Design"); $('#event-title').html("Electronics Design");}
                else if (URL == 'http://www.RssUrlHere.comE') { $('#header-title').html("Nanoengineering"); $('#event-title').html("Nanoengineering");}
                else if (URL == 'http://www.RssUrlHere.comF') { $('#header-title').html("Optics/Display"); $('#event-title').html("Optics/Display");}
                else if (URL == 'http://www.RssUrlHere.comG') { $('#header-title').html("Semiconductors"); $('#event-title').html("Semiconductors");}
                else if (URL == 'http://www.RssUrlHere.comH') { $('#header-title').html("Computers/Software"); $('#event-title').html("Computers/Software");}
                else if (URL == 'http://www.RssUrlHere.comI') { $('#header-title').html("Technology Management"); $('#event-title').html("Technology Management");}
                else { $('#event-title').html("All Events"); $('#header-title').html("Mobile");}

//My ajax call with for the URL
    $.ajax({
                type: 'GET',
                url: URL,
                dataType: 'xml',
                success: function (xml) {

                         //functions here

A: var URL = localStorage.getItem('url') || 'http://www.RssUrlHere.com';

|| is OR operator. It starts evaluating from left, if left most one is falsy value the result will be the one in right side.
also when working with undefined, the format is different
if(typeof x === "undefined"){
}

var title = "General";

switch(URL){
case 'http://www.RssUrlHere.comB' :title="Bioengineering"; break;
case 'http://www.RssUrlHere.comC' :title="dfsfsdf"; break;
case 'http://www.RssUrlHere.comD' :title="sdfsdf"; break;
case 'http://www.RssUrlHere.comE' :title="sdfsdf"; break;
case 'http://www.RssUrlHere.comF' :title="sdfsdfsdfsdf"; break;
case 'http://www.RssUrlHere.comG' :title=""; break;
case 'http://www.RssUrlHere.comH' :title="sdfsdf"; break;
case 'http://www.RssUrlHere.comI' :title="sdfsdfsdf"; break;
default : title = "Unknown Title";
}

$('#header-title').html(title);
$('#event-title').html(title);

A: try using
if (!typeof rssURL == "undefined" || rssURL !== "null") { URL = rssURL }

instead of
if (rssURL !== "undefined" || rssURL !== "null") { URL = rssURL }


text:
Q: Java - My super.toString is returning null I'm having an issue where my toString method in Department is returning null values, it seems the super.toString isn't getting the values that are inputed. I'm not sure where the code went wrong, I know it's a lot to sort through, I tried to get rid of any code that isn't important. Thanks for taking a look. Sorry if I structured this wrong.
public class Person {
String name;
private int age;
private String ssn;
private boolean alive;

public Person(String name, int age, String ssn, boolean alive) {
    this.name = name;
    this.age = age;
    this.ssn = ssn;
    this.alive = alive;
}

public String toString() {
    return "Name: " + this.getName() + "\n" +
            "Age: " + this.getAge() + "\n" +
            "SSN: " + this.getSsn() + '\n' +
            "Alive: " + this.isAlive();
}
}

Teacher extends Person
public class Teacher extends Person {
private String id;
private int salary;
private int num_yr_prof;

public Teacher(String name, int age, String ssn, boolean alive,           String id, int salary, int num_yr_prof) {
    super(name, age, ssn, alive);
    this.id = id;
    this.salary = salary;
    this.num_yr_prof = num_yr_prof;
}
public Teacher(Teacher t) {
    this.id = t.id;
    this.salary = t.salary;
    this.num_yr_prof = t.num_yr_prof;
}

@Override
public String toString() {
    return super.toString() +
            "\nID: " + getId() +
            "\nSalary: $" + getSalary() +
            "\nYears as a prof: " + getNum_yr_prof();
}
}

This class uses an array of teachers
public class Department {
private String deptName;
private int numMajors;
private Teacher[] listTeachers;

public Department(String dN, int nM, Teacher[] lT) {
    this.deptName = dN;
    this.numMajors = nM;
    this.listTeachers = new Teacher[lT.length];
    for (int i = 0; i <lT.length ; i++) {
        listTeachers[i] = new Teacher(lT[i]);
    }
}

public String toString() {
    String output = "Department: ";
    output += "\n   Name: " + getDeptName();
    output += "\n   Majors: " + getNumMajors();
    output += "\n   Teachers: \n";
    for (int i = 0; i < listTeachers.length; i++) {
        output += listTeachers[i].toString(); //This is returning null values
    }
    return output;
}
}

The main method
public class lab4prt2 {
public static void main(String[] args) {
    Teacher[] teachers = new Teacher[]{
            new Teacher(
                    "Tracy",
                    36,
                    "39890280",
                    true,
                    "4859279",
                    100000,
                    5)
    };

    Department d1 = new Department("Math", 4, teachers);

    System.out.println(d1.toString());

}
}

A: At a first look, it seems to me that the Department constructor invokes the Teacher constructor with argument Teacher.
In this constructor, the super() is not invoked, and it doesn't compile, so I guess you probably missed something during your copy paste.
Anyway, I'm afraid that this is a very inefficient code because you re-create the Teacher objects starting from your array, and above all, you're losing part of the information.


text:
Q: Get dataModel back from [NSArray valueForKeyPath:@"@max.value"] other than just value Here is my data model:
@interface DataModel : NSObject
@property (strong, nonatomic) NSString *label;
@property (nonatomic) float value;
@property (nonatomic) NSInteger index;
@property (nonatomic, strong) NSString *unit;
@end

And i have a NSArray with this data model
NSArray *myDataModels;

Now i need to get a data model back from this array with the highest @property (nonatomic) float value;
I can get the highest value back by using
[[myDataModels valueForKeyPath:@"@max.value"] intValue]

But what i need is the whole DataModel with highest value, not just the value.
Anyone can help me?

A: You need to iterate your array and find the max value.
DataModel *maxModel = nil;
float maxValue = FLT_MIN;
for (DataModel *model in myDataModels) {
    if (model.value > maxValue) {
        maxModel = model;
        maxValue = model.value;
    }
}

NSLog(@"The max model is %@", maxModel);

A: Smallest version using Predicate can be
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.value ==%@.@max.value", myDataModels];
NSArray *filteredArray = [myDataModels filteredArrayUsingPredicate:predicate];
if(filteredArray.count>0)
    DataModel *smallestValue = [filteredArray objectAtIndex:0];

Or you can do it like this as well (As @Puneet suggested in comment),
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.value == %@",[myDataModels valueForKeyPath:@"@max.value"]];
NSArray *filteredArray = [myDataModels filteredArrayUsingPredicate:predicate];
if(filteredArray.count>0)
    DataModel *smallestValue = [filteredArray objectAtIndex:0];


text:
Q: Qt missing library? I am trying to run my qt application on another (debian) machine. I get an error about missing libraries (for example, libQt5WebKitWidgets). Is it possible to bundle these libraries within my application ?

A: You need to either install the Qt libraries on the machine running your application, or statically link them into your application.
See here.
You could also try taking a look at the Qt Installer Framework as another alternative.


text:
Q: My custom theme does not load the translations I made a custom theme named testTheme having these files:

And I wanted to put some translation on it therefore I created the required .po and .mo files for greek language via poedit as seen in the following image:

But I cannot make it load the custom translations I created via poedit. Do you have any idea how I will load them?
Edit 1
The functions.php as asked:
<?php

if(!function_exists('loadThemerequirements')):

function loadThemerequirements()
{
    load_theme_textdomain( 'testTheme', get_template_directory() . '/languages' );
}

endif;

add_action( 'after_setup_theme', 'loadThemerequirements' );

Update1
The translations files were moved and renamed like that:

Still Same result.
Edit 2:
This is not a child theme but a from-scratch made one.
Edit 3:
I tried renaming the .po and .mo files as el_GR.po and el_GR.mo still same result. I also tried to rename them in to testTheme/el_GR.po and testTheme/el_GR.mo without any success.
Update 2
The theme is in this git repository: https://github.com/pc-magas/testTheme
Edit 1
I changed my 404 page (that has some text to be translated into greek) like that:
<?php
get_header();
?>

404

<?php _e('The requested page does not exist.','testTheme');?>

<?php
    wp_reset_query(); //resetting the page query
    get_footer();
?>

A sample of my page and the translated text is:

As you can see still no result.

A: If you have a child theme, in your function.php you have to change get_template_directory() by get_stylesheet_directory()

A: *

*Change your translate file name to el_GR.po and el_GR.mo:
el_GR.po in: testTheme\languages\el.po
el_GR.mo in: testTheme\languages\el.mo

*In 404.php file for print text you should write code like this (add textdomain):
<?php _e('The requested page does not exist.', 'testTheme'); ?>

Second parameter is textdomain.


text:
Q: I am confused about repositories I am running Ubuntu 20.04 and, when I open the "applications" application (the checkerboard looking thing in the sidebar) some of the applications have duplicate icons, and, in the case of the Audacity sound editor, clicking on each one brings up an Audacity that behaves differently.
I also have a "software updater" along with a "software and updates" plus a "Ubuntu Software" and; wait, there's more...a "snap store"
Are these different "repositories?" and, when a box pops open saying "Updated software is available for this computer" with install now (or later) is that the way I should be updating; because I can also go to the "software and updates" and it will tell me the sources are out of date, I need an internet connection, and then will go to "refreshing cache" before hanging up, so I have to pull the battery out of the laptop then reboot (because I can't even bring up a terminal to run pgrep and kill)
I prefer to use command lines in a terminal because I'm trying to learn unix and eventually the kernel etc.
Can I run apt-get update; then upgrade and skip all the graphical package managers, which is what I believe the snap store and Ubuntu software is?
I think I have 3 copies of Audacity and they overwrite each other; or they have their config files in different places and I have lost music that I've spent hours on by forgetting which icon opened the program if I have to restart...
I just want a simple way to update, even if I have to do it manually every other day...
livepatch is on, too, confusing me more...thanks for reading this far and for any help; trying to attach a screenshot...


text:
Q: A cast to int has gone wrong. android im having an issue while video mixing with audio. everytime when I try to make it.
That always give me an error which is

Java.lang.RuntimeException: A cast to int has gone wrong. Please contact the mp4parser discussion group.

Im using googlecode mp4 parser : implementation  com.googlecode.mp4parser:isoparser:1.1.22 and also tried that but no success  implementation 'org.mp4parser:isoparser:1.9.41'
Also on forum there's no proper answer on that question.
here's my code
 public Track CropAudio(String videopath, Track fullAudio) {
    try {

        IsoFile isoFile = new IsoFile(videopath);

        double lengthInSeconds = (double)
                isoFile.getMovieBox().getMovieHeaderBox().getDuration() /
                isoFile.getMovieBox().getMovieHeaderBox().getTimescale();

        Track audioTrack = (Track) fullAudio;

        double startTime1 = 0;
        double endTime1 = lengthInSeconds;

        long currentSample = 0;
        double currentTime = 0;
        double lastTime = -1;
        long startSample1 = -1;
        long endSample1 = -1;

        for (int i = 0; i < audioTrack.getSampleDurations().length; i++) {
            long delta = audioTrack.getSampleDurations()[i];

            if (currentTime > lastTime && currentTime <= startTime1) {
                // current sample is still before the new starttime
                startSample1 = currentSample;
            }
            if (currentTime > lastTime && currentTime <= endTime1) {
                // current sample is after the new start time and still before the new endtime
                endSample1 = currentSample;
            }

            lastTime = currentTime;
            currentTime += (double) delta / (double) audioTrack.getTrackMetaData().getTimescale();
            currentSample++;
        }

        CroppedTrack cropperAacTrack = new CroppedTrack(fullAudio, startSample1, endSample1);

        return cropperAacTrack;

    } catch (IOException e) {
        e.printStackTrace();
    }

    return fullAudio;
}

public Runnable runnable = new Runnable() {
    @Override
    public void run() {

        try {

            Movie m = MovieCreator.build(video);

            List nuTracks = new ArrayList<>();

            for (Track t : m.getTracks()) {
                if (!"soun".equals(t.getHandler())) {
                    nuTracks.add(t);
                }
            }

            Track nuAudio = new AACTrackImpl(new FileDataSourceImpl(audio));
            Track crop_track = CropAudio(video, nuAudio);
            nuTracks.add(crop_track);
            m.setTracks(nuTracks);

            Container mp4file = new DefaultMp4Builder().build(m);
            FileChannel fc = new FileOutputStream(new File(output)).getChannel();
            mp4file.writeContainer(fc);
            fc.close();

            try {
                Variables.closeProgressDialog();
            } catch (Exception e) {
                Log.d(Variables.tag, e.toString());
            } finally {
                Go_To_preview_Activity();
            }

        } catch (Exception e) {
            Variables.closeProgressDialog();
           // Toast.makeText(context, "Something went wrong"+ e.toString(), Toast.LENGTH_SHORT).show();
            //Go_To_preview_Activity();
            e.printStackTrace();
            Log.d(Variables.tag, e.toString());

        }

    }

};


text:
Q: $\mu $ ergodic $\iff \mathcal{O}^{+}_{\phi}(x)\cap A\neq\emptyset$ Let $\mathcal{A}$ be a $\sigma$-Algebra on $X$ and $\phi: X\rightarrow X$ measurable (i.e. $\phi^{-1}(A)\in\mathcal{A}$) .
Let $\mu:\mathcal{A}\rightarrow[0,1]$ be probability measure which is $\phi$-invariant (i.e. $\mu(\phi^{-1}(A))=\mu(A)\thinspace \forall A\in\mathcal{A}$).

To prove:
$\mu$ is ergodic $\iff$$\forall A\in \mathcal{A}$ with $\mu(A)>0 \colon\qquad\mathcal{O}^{+}_{\phi}(x)\cap A\neq\emptyset$ for almost all $x\in X $
Has anyone an idea how to start both ways ? Maybe the fact that $\mathcal{O}^{+}_\phi(x)\subseteq X $ for an invariant $\phi$ could help. I've tried the facts that $\mu(\mathcal{O}^{+}_\phi(x)\cup A) = \mu(\mathcal{O}^{+}_\phi(x))+\mu(A)-\mu(\mathcal{O}^{+}_\phi(x)\cap A)$. and $\mathcal{O}^{+}_\phi(x)$ is countable  $\mu(\mathcal{O}^{+}_\phi(x))=0$
I'm thankful for any tips

A: For all $A \in \mathcal{A}$, let $x \in \phi^{-n}(A)$ iff $\phi^n(x) \in F$. Then, $O_\phi(x) \cap A \neq \emptyset$ a.s. iff $\mu(\cup_{n=1}^\infty\phi^{-n}(A))=1$.
($\Rightarrow$) Suppose that $\mu$ is ergodic and let $\mu(A)>0$.
Let $F_n = \bigcup_{k=n}^\infty \phi^{-k}(A)$ and note that $F_{n+1} \subset F_n$ and $\phi^{-1}(F_n) = F_{n+1}$. By $\phi$-invariance, $\mu(F_n) = \mu(F_{n+1})$. Let $F = \bigcap_{n=1}^\infty F_n$ and note that $\phi^{-1}(F)=F$.
By ergodicity, $\mu(F) = 0$ or $1$. But $F_n \downarrow F$ and $\mu(F_n) = \mu(F_1)$ imply that $\mu(F_1)=0$ or $1$.
To finish, then, it suffices to show that $\mu(F_1)>0$. Simply observe that $\phi^{-1}(A) \subset F_1$ and use $\phi$-invariance once more to get $\mu(F_1) \geq \mu(\phi^{-1}(A)) = \mu(A)>0$.
($\Leftarrow$) For the converse assume that $\mu$ is not ergodic and let $A$ be a witness to this fact. Then, $\phi^{-1}(A)=A$, and $0 < \mu(A)<1$. By induction $\phi^{-n}(A)=A$ for all $n$, hence $$\mu(\cup_{n=1}^\infty\phi^{-n}(A)) = \mu(A) < 1.$$


text:
Q: Is there a way to set the minimum width of a slimbox popup? We have several images in our app, some of which are less than 100 pixels wide.  When this happens, the slimbox caption text and "Close [X]" link get cutoff.  Is there a way to force the slimbox popup to a minimum width?  There is an initialWidth option, but once the image loads it chooses the width of the image.

A: Use min-width css property. It doesn't allow real width to be less than min-width, even if it is set less eexplicitly in style.
It doesn't work in ie6.


text:
Q: How to attach a Thumb to a TextBlock? I have the following XAML:
<Window x:Class="thumb_test.MainWindow" Title="MainWindow" ... >
    <Grid>
        <Canvas>
            <Thumb Canvas.Top="25" Canvas.Left="25" Width="50" Height="50"
                Name="_thumb1" DragStarted="ThumbStart" DragDelta="ThumbMoved" >
            </Thumb>
        </Canvas>
    </Grid>
</Window>

And the following is the corresponding code-behind:
void ThumbStart(object sender, DragStartedEventArgs e)
{
    _originalLeft = Canvas.GetLeft(_thumb1);
    _originalTop = Canvas.GetTop(_thumb1);
}
void ThumbMoved(object sender, DragDeltaEventArgs e)
{
    double left = _originalLeft + e.HorizontalChange;
    double top = _originalTop + e.VerticalChange;
    Canvas.SetLeft(_thumb1, left);
    Canvas.SetTop(_thumb1, top);
    _originalLeft = left;
    _originalTop = top;
}

The above displays a rectangle, which can be dragged around on the canvas.
My question: How can I associate this Thumb with a TextBlock, such that the Thumb overlays the TextBlock (with the Thumb being transparent) and I can drag the TextBlock around?  (PS: Believe me, what I have tried so far is not worth showing here.)
My ultimate goal is to be able to drag TextBlocks around, so I am open to other approaches.  I would like to operate on a Canvas, though.
I am using VS2010 on Win 7, with .NET 4.0.

A: have you read Dragging Elements in a Canvas ?
or this easy way(that i never saw until now -google) How to make any UI element drag-able using Behaviors in WPF


text:
Q: quote.shippingAddress() is getting null/with no values , just after adding new billing address quote.shippingAddress() gets blank/with no values in object , while adding to new billing address
in Magento_Checkout/js/view/shipping-address/address-renderer  in initObservable() method in default.js file.
Any help appreciated

A: Commented this portion of code solves issue
initialize: function () {
        this._super();
        quote.paymentMethod.subscribe(function () {
            checkoutDataResolver.resolveBillingAddress();
        }, this);

      /*  shippingRatesValidator.initFields(this.get('name') + '.form-fields'); */
    },


text:
Q: How to rotate top-border around the circle? I'm trying to achieve this CSS animation but don't know how to do it. I want to rotate the top-border around the circle but the whole thing is rotating including text. I just want to rotate the top-border on 360 degree. Here is my code snippet below:

div#skill {
    /*background: url(../img/white.jpg) center no-repeat;
    background-size: cover;*/
    background-color: rgba(144, 0, 64,0.8);
    color: #fff;
    padding: 10px 0;
}

div#skill h3 {
    color: #fff;
    text-transform: none;
}

div#skill .row {
    margin-right: -15px;
    margin-left: -15px;
    padding: 15px 150px;
}

div#skill .circle {
    height: 120px;
    width: 120px;
    border: 5px solid #ccc;
    border-top-color: orange;
    border-radius: 60px;
    background-color: #74002f;
    /*Making the top border to spin*/
    animation: spin 2s linear infinite;
}

div#skill .circle:after {
    content: url(../img/icons/arrow-point-to-right.png);
    position: absolute;
    top: 25px;
    right: 0;
}

div#skill .circle.last:after{
    display: none;
}

.circle .caption {
    font-weight: bold;
    padding: 20px 24px;
}

.caption h6 {
    font-size: 15px;
}

/*Animation on circle*/
@keyframes spin {
    from {transform: rotate(0deg);}
    to {transform: rotate(360deg);}
}

My development process

1

Concept

2

Design

3

Code

4

Launch

about my skills

Please help me out! Will really appreciate your help in this.Thank you in advance!

A:

div#skill {
  /*background: url(../img/white.jpg) center no-repeat;
    background-size: cover;*/
  background-color: rgba(144, 0, 64, 0.8);
  color: #fff;
  padding: 10px 0;
}
div#skill h3 {
  color: #fff;
  text-transform: none;
}
div#skill .row {
  margin-right: -15px;
  margin-left: -15px;
  padding: 15px 150px;
}
div#skill .circle {
  height: 120px;
  width: 120px;
  border: 5px solid #ccc;
  border-top-color: orange;
  border-radius: 50%;
  background-color: #74002f;
  /*Making the top border to spin*/
  animation: spin 2s linear infinite;
}
div#skill .circle:after {
  content: url(../img/icons/arrow-point-to-right.png);
  position: absolute;
  top: 25px;
  right: 0;
}
div#skill .circle.last:after {
  display: none;
}
.circle .caption {
  font-weight: bold;
  padding: 20px 24px;
}
.caption h6 {
  font-size: 15px;
}
/*Animation on circle*/

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
.col-md-3 {
  position: relative;
}
.caption {
  position: absolute;
  z-index: 10;
  text-align: center;
  left: 65px; /* (120px width + 5+5px border )/2  */
  transform: translate(-50%, 0);
}

My development process

1

Concept

2

Design

3

Code

4

Launch

about my skills

A: The solution is to make another div that will be behind the .circle with position:absolute; that how, it will "take" the .circle size but not contains the .circle content.

div#skill {
  /*background: url(../img/white.jpg) center no-repeat;
  background-size: cover;*/
  background-color: rgba(144, 0, 64,0.8);
  color: #fff;
  padding: 10px 0;
}

div#skill h3 {
  color: #fff;
  text-transform: none;
}

div#skill .row {
  margin-right: -15px;
  margin-left: -15px;
  padding: 15px 150px;
}

div#skill .circle {
  position:relative;
  height: 120px;
  width: 120px;
  border: 5px solid #ccc;
  /*border-top-color: orange;*/
  border-radius: 50%;
  background-color: #74002f;
}

div#skill .circle:after {
  content: url(../img/icons/arrow-point-to-right.png);
  position: absolute;
  top: 25px;
  right: 0;
}

div#skill .circle.last:after{
  display: none;
}

.circle .caption {
  font-weight: bold;
  padding: 20px 24px;
  position:relative;
  z-index:1;
}

.caption h6 {
  font-size: 15px;
}

.circle-rotate {
  height: 100%;
  width: 100%;
  border-top: 5px solid orange;
  border-radius: 60px;
  background-color: #74002f;
  /*Making the top border to spin*/
  animation: spin 2s linear infinite;
  position:absolute;
  top:0;
  left:0;
}

/*Animation on circle*/
@keyframes spin {
  from {transform: rotate(0deg);}
  to {transform: rotate(360deg);}
}

My development process

1

Concept

2

Design

3

Code

4

Launch

about my skills


text:
Q: How to design an approximate solution algorithm I want to write an algorithm that can take parts of a picture and match them to another picture of the same object.
For example, If I gave the computer a picture of a vase and a picture of a scene with the vase in it, I'd expect it to determine where in the image the vase is.
How would I begin to develop an algorithm like this?
The final usage for this algorithm will be an application that for example with a picture of somebody's face could tell if they were in a crowd of people. This algorithm would eventually be applied to video streams.
edit: I'm not expecting an actual solution to this problem as I don't hope to solve it anytime soon. The real question was how do you define something like this to a computer so that you could make an algorithm to do it.
Thanks

A: A former teacher of mine wrote his doctorate thesis on a similar sort of problem, except his input was a detailed 3D model of something, which he would use to find that object in 2D images. This is a VERY non-trivial problem, there is no single 'answer', certainly nothing that would fit the Stack Overflow format.
My best answer: gather a ton of money and hire a very experienced programmer.
Best of luck to you.

A: The simple answer is, find a mathematical way to describe faces, that can account for angles and partial missing data, then refine and teach it.
Apparently apple has done something like this, however, it still makes mistakes and has to be taught as it moves forward.
I expect it will be more about the math, than about the programming.

A: The first problem you describe and the second are both quite different.
A major part of each is solved by the numerous machine vision libraries available.  You may need a combination of techniques to achieve any success at either task.
In the first one, you would need something that generically recognizes objects.  Probably i'd use a number of algorithms in concert to identify the foreground object in the model image and then do some kind of weighted comparison of the partitioned target image.
In the second case, examining faces, is a much more difficult problem relative to the general recognizer above.  Faces all look the same, or nearly so.  The things that a general recognizer would notice aren't likely to be good for differentiating faces.  You need an algorithm already tuned to facial recognition.  Fortunately this is a rapidly maturing field and you can probably do this as well as the first case, but with a different set of functions.

A: I think you will find this to be quite a challenge. This is an extremely difficult problem and is one of the many areas of computing that fall under the domain of artificial intelligence (AI). Facial recognition would certainly be the most popular variant of this problem and in spite of what you may read in the media, any claimed success are not what they are made out to be. I think the closest solutions involve neural nets and they require very clear and carefully selected images usually.
You could try reading here though. Good luck!


text:
Q: How can I make multiple API calls with the same key I'm working on my Project and currently I have one API call to spoonacular's search by recipe GET request. I want to add the search by video GET Request but I seem to having problems getting both to render at once into the DOM. How can I fix this issue?
const apikey = '';
const urls = { search:'https://api.spoonacular.com/recipes/complexSearch',
videos: 'https://api.spoonacular.com/food/videos/search'
};

function queryParams(params) {
    const queryItems = Object.keys(params).map(key=>`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
    return queryItems.join('&');
}

///render results
function getRecipe(tacos,maxResults){
  const params ={
    query: tacos,
    number: maxResults,
  };

  const queryString = queryParams(params)
  const url = urls+'?'+queryString +'&apiKey='+ apikey;

  console.log(url);

  fetch(url)
  fetch(urls.search)
  .then(response =>{
    if(response.ok){
      return response.json();
    }
    throw new Error(response.statusText);
  })
  .then(responseJson => displayResults(responseJson))
  .catch(err =>{
    $('#js-error-message').text(`Something went wrong: ${err.message}`);
  });
}

A: Your urls is an object containing two strings. You need to treat it as such and make two separate calls.
You should have a fetch(urls.search) and fetch(urls.videos) call, each with their own response chain.
I'm not sure this code is doing what you think it is:
const url = urls+'?'+queryString +'&apiKey='+ apikey;
You'll need to append the queryString and apiKey to each string within urls separately. Something like
const searchUrl = urls.search+'?'+queryString +'&apiKey='+ apikey;
const videosUrl = urls.videos+'?'+queryString +'&apiKey='+ apikey;


text:
Q: How to map a file handle to the file it is accessing I am trying to map a file handle like file6
(the result of a previous set fh [open somefile.txt w]) to the file it was accessing.
So I'd like a mapping between file6 --> somefile.txt
I tried file channels, but this only lists the channel names - not the actual file name.

A: As you've noticed, Tcl doesn't keep this information for you, but you can easily keep track of it for yourself by doing something like this:
set fh [open somefile.txt w]
set filenames($fh) somefile.txt

Then when you want to know the associated file name, you can
puts $filenames($fh)

You can automate this by e.g.:
proc myOpen {name args} {
    global filenames
    set fh [open $name {*}$args]
    set filenames($fh) $name
    return $fh
}

This is of course a quick-and-dirty semi-solution that leaves some important things open, like for instance how the association needs to be similarly removed if the channel is closed. It is possible, but a bit complicated, to create a more comprehensive solution.
Documentation:
global,
open,
proc,
puts,
return,
set,
{*} (syntax)


text:
Q: how can I prove that if I have a regular language L, that L' is a regular language how can I prove that if  I have a regular language L
and I create a new language L'
where L' = (L but with last letter repeated)
(i.e. if ab is in language L then abb is in language L')
that L' is a regular language
I tried solving the question but I have no way of being sure of
my solutions so I'll post it here:

L is a regular language therefor there is a regular expression for it,
we create a new language x where x =L*($\Sigma$),
$\Sigma$ is all the letters in language L
,x is a regular language because it is regular language chained with a letter
,and letters are a regular expression
the language L' is a subset of x,
there for x can be written as x=L' $\cup$ t (t=x/L'),
and therefor L' has to be a regular expression
because if it wasn't then x would not be a a regular language

A: Since $L$ (over some alphabet $\Sigma$) is regular, there is a finite automaton $\mathcal{M}$ that recognises $L$. We now need to try and build a finite automaton $\mathcal{M}'$ that recognises $L'$. Let $Q_F$ be the collection of all state-symbol pairs of $\mathcal{M}$ that cause a transition into any of its accept states. More formally, $$Q_F := \{(q,s)\in Q\times \Sigma : \delta(q,s) \in F\},
$$ where $\delta\colon Q\times \Sigma \to Q$ is the transition function of $\mathcal{M}$, and $F$ is the set of accept states. We add a new state $A$ to $Q$ and make this the only accept state. Next, for every pair $(q,s)\in Q_F$, we add a new state $n_{(q,s)}$, and set $\delta^+(q,s) = \{n_{(q,s)}, \delta(q,s)\}$ and $\delta^+(n_{(q,s)},s) = A$. For $(q,s)\in (Q\times \Sigma) \setminus Q_F$ we leave $\delta^+(q,s) = \delta(q,s)$.
Note that the resulting automaton is non-deterministic, but this is fine since an equivalent DFA always exists. I now leave it up to you to show that this new NDFA $\mathcal{M}' := \{Q\cup A, \Sigma, \delta^+, q_o, A \}$ recognises $L'$.

A: Let $A$ be the alphabet. For each letter $a \in A$, let
$$
  La^{-1} = \{u \in A^* \mid ua \in L\}
$$
It is a well known fact that if $L$ is regular, then so is $La^{-1}$. Now your language $L'$ can be written as
$$
  L' = \bigcup_{a \in A}\ (La^{-1})aa
$$
For each $a \in A$, $(La^{-1})aa$ is the product of the two regular languages $La^{-1}$ and $aa$ and this is regular. It follows that $L'$ is a finite union of regular languages and this is regular.


text:
Q: Group, then create a 'break' if the datetime exceeds a certain time, creating a new value within original grouped column (R, dplyr) I have dataset, df,
  Subject      Folder     Message    Date
  A            Out                   9/9/2019 5:46:38 PM
  A            Out                   9/9/2019 5:46:40 PM
  A            Out                   9/9/2019 5:46:42 PM
  A            Out                   9/9/2019 5:46:43 PM
  A            Out                   9/9/2019 9:30:00 PM
  A            Out                   9/9/2019 9:30:01 PM
  B            Out                   9/9/2019 9:35:00 PM
  B            Out                   9/9/2019 9:35:01 PM

I am trying to group this by Subject, find the duration, and create a new Duration column. I also wish to create a threshold if the Date time exceeds a certain amount of time. My dilemma is that within Group A, the time goes from 5:46 in the 4th row to 9:30 in the 5th row. This gives an inaccurate duration in Group A. I wish to 'break' that time and find the new time duration while creating a new value (A1) in the Subject when the time exceeds 10 minutes. I am not sure if I should use a loop for this?
 Subject   Duration   Group
 A         5 sec      outdata1
 A1        1 sec      outdata2
 B         1 sec      outdata3

Here is my dput:
structure(list(Subject = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
2L, 2L), .Label = c("A", "B"), class = "factor"), Folder = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "Out", class = "factor"),
Message = c("", "", "", "", "", "", "", ""), Date = structure(1:8, .Label = c("9/9/2019 5:46:38 PM",
"9/9/2019 5:46:40 PM", "9/9/2019 5:46:42 PM", "9/9/2019 5:46:43 PM",
"9/9/2019 9:30:00 PM", "9/9/2019 9:30:01 PM", "9/9/2019 9:35:00 PM",
"9/9/2019 9:35:01 PM"), class = "factor")), row.names = c(NA,
-8L), class = "data.frame")

This is what I tried:
thresh <- duration(10, units = "minutes")

df %>%
mutate(Date = mdy_hms(Date)) %>%
transmute(Subject, Duration = diff = difftime(as.POSIXct(Date, format =
"%m/%d/%Y %I:%M:%S %p"),as.POSIXct(Date,
format = "%m/%d/%Y %I:%M:%S %p" ), units = "secs")) %>%
ungroup %>%
distinct %>%
mutate(grp = str_c("Outdata", row_number()))

 mutate(delta = if_else(grp < thresh1, grp, NA_real_))

A: We can calculate the duration between consecutive Date values to create new group and then calculate the difference in time between min and max in each group.
library(dplyr)
thresh <- 10

df %>%
  mutate(Date = as.POSIXct(Date, format = "%m/%d/%Y %I:%M:%S %p")) %>%
  group_by(Subject, Group = cumsum(difftime(Date,
            lag(Date, default = first(Date)), units = "mins") > thresh)) %>%
  summarise(Duration = difftime(max(Date), min(Date), units = "secs")) %>%
  ungroup %>%
  mutate(Group = paste0('outdata', row_number()))

# A tibble: 3 x 3
#  Subject Group    Duration
#  <fct>   <chr>    <drtn>
#1 A       outdata1 5 secs
#2 A       outdata2 1 secs
#3 B       outdata3 1 secs


text:
Q: Git poll setup for Jenkins groovy (scripted) pipeline I'm trying to setup GIT poll for groovy pipeline. Scripted, not declarative
git branch: '${Branch}',
    credentialsId: 'some.key.ssh',
    poll: true,
    url: "ssh://git@bitbucket-ssh.company.com/project-${env.Project}.git"

Git Branch is set from parameters:
Poll SCM is set to: * * * * *

I see that polling works - but it can't get anything - it doesn't trigger build

So the question is - is there a way to fix that?
Please don't suggest webhooks - I can't use that. Only Poll SCM

A: Made it work with GitSCM
checkout([$class: 'GitSCM',
     ranches: [[name: '*/master']],
     doGenerateSubmoduleConfigurations: false,
     extensions: [],
     submoduleCfg: [],
     userRemoteConfigs: [[url: 'https://github.com/unickq/allure-nunit.git']]])

Snipplet Generator:

A: In a Jenkinsfile you can use cron like so:
pipeline {
    agent { label "master" }

    triggers {
        cron('* * * * *')
    }
    .
    .
    .
}


text:
Q: Looking for advice: Short-term forecasting using actual forecasts and real time data First of all apologies, I have very little experience in statistics and my biggest problem is using the correct terminology. I'm here mainly looking for guidance and direction.
Background: I have a few rain gauges around the same area reporting real time rainfall in millimetres. How often the rainfall is reported is not consistent due to network problems.
I would like to use this real time rainfall data along with actual predictions made by my Met office, which has hourly predictions of rainfall also in millimetres. The goal is to combine these two in order to make an prediction if rainfall will pass a defined threshold, a few hours before it will happen. Intense rainfall causes minor road flooding in my area and causes heavy traffic jams and would like to have an 'alert' system so one can take appropriate action.
I have been looking into time series and ARIMA models for rainfall, but I'm wondering how do I incorporate actual predictions into a statistical model?
Any advice will be greatly appreciated, thank you.

A: The first step is to organise all of your historical data and clean it - you say you have inconsistent reporting due to network problems, this will lead to gaps in your historical dataset which will need to be imputed. The method by which you choose to do this will wildly vary depending on the size of the gaps.
From there you would need to decide on what features might influence rainfall at time $t+1$ - maybe you could use temperature, cloud cover, humidity, lagged features (rainfall at $t_{t-1}$ may influence rainfall at time $t$) etc...
From there it becomes a machine learning problem where you will aim to build a model(s) to forecast raincover - this can be done in Python or R.
Finally you move onto deployment - you may only want to forecast the days raincover in the morning and so this is fairly easy to do with a simple script that you manually enter your features into and the model spits a forecast back out or you could go the more complex route of hosting your model and feeding it a constant stream of data to get continuous predictions - This is a major can of worms however.
Those are the broad-strokes, you could just open source your data on somewhere like Kaggle and have the open-source community build out your model for you and you merely have to use it to predict!


text:
Q: ListViewAdaper, item not redrawing depending on handling getView(XXX) I'm building a couple of custom ListViews which contains listViewItems whom expands on click. I made my first one without major trouble, and the listViewItems expands correctly on click.
Now i'm building an other ListView, with the difference that it contains more than one kind of item, becuse of this i found it convenient to let the adaper contain a list of views instead of a list of data and creating the views when prompted for them by getView(XX).
Everything works fine except that the items in the new list does not expand until i swap activity back and forth to redraw. I have tested to mimic the implementation in the first listview (with several drawbacks) and with this gets them to redraw correctly.
The main diffrence is these 2 lines, the first one works the second one does not redraw.
return new TransactionChild(context, attrs, transactions.get(position));

.
return (View) children.get(position);

What is the best way to fix this? Try to force a redraw on the entire list(on expanding view shifts the rest down...)? or is there something neater i can do with either the ListView or the adapter?
Help would be great :D

A: You can use an ExpandableListView where the groups don't have any children and have different layouts on group open and closed.
If using a normal ListView, i suggest you make use of the getItemViewType() method of the Adapter, so in this way you keed a list of items normal and clicked and on getView you check the type and change the layout. And on the click listener you change the type of the item clicked and notify for data changed.


text:
Q: How to make a DIV centered and has almost a 100% width and a 100% height

How to center the div main and make its height and width almost 100% with 20px gap from each side of the screen.

A: The width of a block element is already 100% by default.
All you need do is add padding or margin to create your "gap".

edit
I missed your absolute positioning.
With absolute positioning, I'd use this:
#main {
background: #a00;
position: absolute;
top: 0;
left: 50px;
right: 50px;
height: 100%;
}

DEMO FIDDLE

A: Hey now define this css

A: This would center align the div with 50px space on left and right side.
.main {
    margin: 0 50px;  /* [top,bottom] [left,rigth] shorthand syntax */
    width : 100%;
}

A: You can do :

A: You can use the new calc() attribute in CSS3:
.main
{
    margin: 0 auto;
    background-color:black;
    color: #fff;
    position:absolute;
    width: -webkit-calc(100% - 20px);
    height: -webkit-calc(100% - 20px);  /*repeat with other browsers codes*/
}

This tells the div to be 100% wide/high but remove 20px while keeping it in the center.
IT can be used in IE9 (not below)m Firefox 4.0, Chrome 19 and Safari 6. So it might not be the best solution..
http://jsfiddle.net/Kyle_Sevenoaks/wVUat/

A: Since you are using absolute positioning you could try this:

A: How about solution below:
<!DOCTYPE html>

    <title>Test</title>
    <meta charset="utf-8">

Please find it at http://jsfiddle.net/balkon_smoke/yPF8Y/2/


text:
Q: How to correctly modelize FAQ Questions and Answers? I'm actually working on an FAQ system where questions can be answers to other questions.
The principle that i must respect is that a well-defined set of questions is shown to the user at start (the most general questions). Then, further we go into the "tree", more specific will the questions / answers be. And at the end of the tree (leaf) there will be the most suitable answer for the user.
I've thinking of using a tree. The fact is I've only studied it last year in my Computer Science Degree so I'm like a beginner in the field (in practice mostly).
The questions and answers will be stored in a database and show progressively to the user regarding chosen "path" through the FAQ system.

A: It seems to me that if a question can be an answer to another question, then you might want to take a very general approach and say that any one piece of text can be a child (branch) of any other piece of text.  For example:

*

*Statement answers a question

*Question answers a question

*Statement comments on a question

*Statement comments on another statement

This being the case a simple table with a self-referencing relationship (parent item foreign key) will probably be both simple and effective for you.


text:
Q: Excel VBA : Showing value in cell from msgbox I have a MsgBox and the message includes a count of a range. How do I enter the value used in the Msgboxinto a cell in the worksheet?
A code sample is below:
MsgBox "Todays count is" & " " & Count(Range("g2:g484"))

A: The number is calculated via a function Count. To use the value in a cell, you could assign the count to a variable and then set the value of the cell you want to have the value like so:
Dim i As Long

i = Count(Range("G2:G484"))
MsgBox "Todays count is " & i
Worksheets("WS Name").Range("A1").Value = i

Amend WS Name to the name of your worksheet and A1 to the cell you want to have the value.


text:
Q: Complete setup for XeLaTeX or LuaLaTeX in VSCode with Julia Code using Minted I've asked the Julia community here my question, and have gotten some nice help.
I thought I might cast a wider net for clarification.
TL; DR: What is the complete setup for VSCode to run XeLaTeX or LuaLaTeX, with working examples using unicode characters with minted? I've looked everywhere, finding the latex-workshop.latex.tools in one spot, the latex-workshop.latex.recipes in another spot, then example .tex files elsewhere, and they don't play nicely together. I am so confused.
So, I am new to the world of programming and spend more than half my time lost trying to understand what on earth everyone is talking about.
In this answer to a Stack Exchange question, Brad gives an example without the need to "define" new unicode characters (as with another answer to that question) because it has a huge variety of them.
In this post, the creator of LaTeX-Workshop discourages the use of the magic comment which is used in the Stack Exchange answer aforementioned, so I've deleted it. I also have no idea where the latex-workshop.latex.toolchain is meant to be copied-and-pasted (or edited).
I've learned from here that minted is better than listings because the former takes in the syntax highlighting and formatting rules from pygmentize, which I have installed through the python installer.
I've obtained an example of defining the xelatex tool from here. But it has no example of a recipe.
This guy's example isn't specific enough for me, i.e. VSCode settings are unclear to me.
The guy who replied to me in the Julia discourse community showed that the compilation works in Overleaf. I took his suggestion and tried compiling via the command line, but it doesn't work either.
The JuliaProgramming.tex file I have is as follows,
\documentclass[12pt]{article}

\usepackage[letterpaper]{geometry}
\usepackage{fontspec,unicode-math}
\usepackage{xunicode}
\usepackage{minted}

\setmonofont{FreeMono}

\begin{document}

\section{Example Code}
Hello, here is some code.

\begin{minted}{julia}
f(x) = x.^2 + π
const ⊗ = kron
const Σ = sum # Although `sum` may be just as good in the code.
# Calculate Σ_{j=1}^5 j^2
Σ([j^2 for j ∈ 1:5])
\end{minted}

\end{document}

With the following as my settings.json file for VSCode.
{
    "latex-workshop.latex.recipes": [
        {
            "name": "latexmk",
            "tools": "latexmk"
        }
    ],
    "latex-workshop.latex.tools": [
        {
            "name": "latexmk",
            "command": "latexmk",
            "args": [
                "--shell-escape",
                "-xelatex",
                "-synctex=1",
                "-interaction=nonstopmode",
                "-file-line-error",
                "%DOC%"
            ]
        }
    ]
}

Are these sufficient for a successful run? It doesn't run successfully for me.
Edit: The output I get from running my .tex file is very lengthy. Some of the lines are/include (and repeat many times):
Sorry, but miktex-makemf did not succeed.

! Package fontspec Error: The font "FreeMono" cannot be found.

`BI' can't be a subfont created by hbf2gf

The log file hopefully contains the information to get MiKTeX going again:

C:\<Path>\Local\MiKTeX\2.9\miktex\log\miktex-maketfm.log

I could check the log file. I could try to install the font FreeMono. But I've been exploring rabbit holes for too long and I'm tired of it now.

A: *

*Be sure you have FreeMono installed on you machine. On GNU/Linux, you can check it by typing fc-list

*Include \usepackage{polyglossia} on your preamble, click here for more info.

*Be sure you are using LuaLaTeX or XeLaTeX

\documentclass{article}
\usepackage{minted}
\usepackage{fontspec}
\usepackage{polyglossia}
\usepackage{unicode-math}

\usepackage{xunicode}
\setmonofont{FreeMono} %switched to FreeMono

\begin{document}

\section{Example Code}
Hello, here is some code.

\begin{minted}{julia}
f(x) = x.^2 + π
const ⊗ = kron
const Σ = sum # Although `sum` may be just as good in the code.
# Calculate Σ_{j=1}^5 j^2
Σ([j^2 for j ∈ 1:5])
\end{minted}

\end{document}


text:
Q: SQL server - high buffer IO and network IO I have a a performance tuning question on SQL server.
I have a program that needs to run every month and it takes more than 24hrs to finish. I need to tune this program in the hope that I can decrease the running time to 12 hrs or less.
As this program isn't developed by us, i can't check the program content and modify it. All i can do is just open the SQL server profiler and activity monitor to trace and analyze the sql content. I have disabled unused triggers and did some housekeeping, but the running time only decreased 1 hr.
I found that the network I/O and buffer I/O are high, but i don't know the cause and meaning of this ?

Can anyone tell me the cause of these two issues (network I/O and butter I/O)? Are there any suggestions for optimizing this program?
Thank you!

A: *

*. According to your descriptions, I think your I/O is normal, your
   question is only one:one procedure is too slowly. the solution:
   1.open the SSMS
   2.find the procedure
   3.click the buttton named "Display estimated execution plan"
   4.fix the procedure.

A: To me it seems like your application reads a lot of data into the application, which would explain the figures. Still, I would check out the following:

*

*Is there blocking? That can easily be a huge waste of time if the process is just waiting for something else to complete. It doesn't look like that based on your statistics, but it's still important to check.

*Are the tables indexed properly? Good indexes to match search criteria / joins. If there's huge key lookups, covering indexes might make a big difference. Too many indexes / unnecessary indexes can slow down updates.
You should look into plan cache to see statements responsible for the most I/O or CPU usage

*Are the query plans correct for the most costly operations? You might have statistics that are outdated or other optimization issues.

*If the application transfers a lot of data to and/or from the database, is the network latency & bandwidth good enough or could it be causing slowness? Is the server where the application is running a bottleneck?
If these don't help, you should probably post a new question with detailed information: The SQL statements that are causing the issues, table & indexing structure of the involved tables with row counts and query plans.


text:
Q: Enumeration of proofs Is it possible to enumerate short proofs of short statements, so as to make sure that, say, Goldbach's conjecture doesn't have one of those? How hard would it be? Is it being done?
It's seems likely to me that something interesting might have been missed among short proofs. Though I wouldn't know how short they'd have to be to make it a computationally feasible endeavor, or how hard it would be to tell which statements are interesting.

A: Yes, it is possible to enumerate short proofs -- in fact, to enumerate all proofs in order from shortest to longer.
However, we should not really expect to learn something interesting that way. There are very many short proofs of completely trivial or inane truths, such as $2+2=4$ or $\forall x.(2+x=1+x+1)$, and simply getting past them in order to find a proof of something interesting would -- for any practical purpose -- take "forever".
The classical way to enumerate all proofs is to enumerate all possible strings of symbols and check for each of them whether it happens to be a valid proof or not. This is nice and simple to explain that an enumeration is possible in principle, but as a practical procedure for anything it fails horribly. Even with the fastest computers, a proof of something like $2+2=4$ wouldn't emerge within a lifetime.
It's easy to think up some local improvements to this procedure and find a search strategy that would happen across a proof of $2+2=4$ (say, in Peano Arithmetic) in a more or less reasonable time. However, if we up the ante to for example $10+10=20$, that probably still wouldn't happen within any human lifetime -- unless we envisage some kind of guided search that aims to prove $10+10=20$ specifically rather than just searching through all proofs until one for $10+10=20$ pops up.
And by these measures, Goldbach's conjecture is not a "short" sentence -- stating it formally would need about 100 symbols, drawn from an alphabet of more than a handful of different symbols. So even if we just enumerate all sentences, without even requiring proof of them, we should expect to wait for not less than $5^{100}$ tries before it comes up. That's much, much longer than the number of nanoseconds in the lifetime of the universe.


text:
Q: copy a column in a .csv file to another using batch I have a file that has
Class,section,name
Math,02,Scott

What I need is a .csv that copies a column so it looks like below
Class,section,name,class
Math,02,Scott,Math

I am looking to do this using batch file commands.  Any suggestions?  I know how to do basic copy commands, and tried downloading python but was having trouble getting it to work

A: @ECHO OFF
SETLOCAL
(
FOR /f "tokens=1-3delims=," %%a IN (q22334682.txt) DO (
 ECHO(%%a,%%b,%%c,%%a
)
)>new.csv

GOTO :EOF

-Assuming that the case of the class header on the generated column in the file should match that in column 1.
I used a file named q22334682.txt for my testing, putting the result in new.csv.


text:
Q: How do I do client side authentication check with React front end and Spring Boot security backend? I've got the spring boot security dependency set up
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

I've also restricted some pages in my WebSecurityConfigAdapter e.g.
  http
        .authorizeRequests()
        .antMatchers("/").permitAll()
        .antMatchers("/admin/**").hasRole("ADMIN")

(I've also done the various other boilerplate setup of UsersDetailsService etc.)
In a traditional front end where I'm using html/thymeleaf I can simply do something like this to display a logout link, if the user is logged in.
 <form sec:authorize="isAuthenticated()" id="frmlogout" th:action="@{/logout}" method="post" class="form-inline">
        Logout
 </form>

Question is, how can I do a similar "isAuthenticated()" check  (as well as a role check) from my react .js classes? Is it even possible?
The desired outcome is so that I can then add the logout button to my navbar, which is defined in my .js classes.

A: This post on React.js + Spring Security shows an approach of using a session cookie which is the traditional way of securing communication in spring mvc.
Or you could use Basic Auth for your API and implement the login logic in React. If a call to the API results in a HTTP 401 Unauthenticated then ask the user to provide credentials and use the in react to call the API.


text:
Q: "TypeError: Failed to fetch dynamically imported module" on Vue/Vite vanilla setup We have a vanilla Vue/Vite setup and I'm receiving TypeError: Failed to fetch dynamically imported module on sentry logs.
It seems like the errors are correlated in time with new deployment to prod, although I don't have enough data to confirm. It doesn't happen on local and appears only on deployed code.
I've seen some similar questions for react's setups, but none with a satisfactory response.
I've also found a similar question regarding dynamically imported svgs, but our errors happen for full components.
The only place where we use dynamic imported components is on routing:
export const router = createRouter({
  history: routerHistory,
  strict: true,
  routes: [
    {
      path: '/',
      name: routes.homepage.name,
      component: () => import('@/views/Home.vue'),
      children: [
        {
          path: '/overview',
          name: routes.overview.name,
          component: () => import('@/views/Overview.vue'),
        },
        // other similar routes
      ],
    },
  ],
});

Our deps versions:
    "vue": "^3.0.9",
    "vue-router": "^4.0.5",
    "vite": "^2.0.5",

Any additional information on this issue and how to debug it would be much appreciated!

A: The accepted answer correctly explains when this error is triggered but does not really provide a good solution.
The way I fixed this is by using an error handler on the router. This error handler makes sure that when this error occurs (so thus when a new version of the app is deployed), the next route change triggers a hard reload of the page instead of dynamically loading the modules. The code looks like this:
router.onError((error, to) => {
  if (error.message.includes('Failed to fetch dynamically imported module')) {
    window.location = to.fullPath
  }
})

Where router is your vue-router instance.

A: When you dynamically import a route/component, during build it creates a separate chunk. By default, chunk filenames are hashed according to their content – Overview.abc123.js. If you don't change the component code, the hash remains the same. If the component code changes, the hash changes too - Overview.32ab1c.js. This is great for caching.
Now this is what happens when you get this error:

*

*You deploy the application

*Your Home chunk has a link to /overview route, which would load Overview.abc123.js

*Client visits your site

*You make changes in your code, not necessarily to the Overview component itself, but maybe to some children components that Overview imports.

*You deploy changes, and Overview is built with a different hash now - Overview.32ab1c.js

*Client clicks on /overview link - gets the Failed to fetch dynamically imported module error, because Overview.abc123.js no longer exists

That is why the errors correlate with deployments. One way to fix it is to not use lazy loaded routes, but that's not a great solution when you have many heavy routes - it will make your main bundle large

A: In my case the error was caused by not adding .vue extension to module name.
import MyComponent from 'components/MyComponent'

It worked in webpack setup, but with Vite file extension is required:
import MyComponent from 'components/MyComponent.vue'

A: I had the exact same issue. In my case some routes worked and some didn't. The solution was relatively easy. I just restarted the dev server.

A: My situation was similar.
I found that my Quasar setup works fine on the initial page but not page that are loaded dynamically through an import('../pages/page.vue');.
Short response:
I replaced import('../pages/TestPage.vue') in the middle of the route file by import TestPage from '../pages/TestPage.vue' at the top.
More detailed response:
In my situation I don't expect to have much pages, a single bundle with no dynamic loading is fine with me.
The solution is to import statically every page I need.
In my routes.ts I import all the pages I need.
import IndexPage from '../pages/IndexPage.vue';
import TestPage from '../pages/TestPage.vue';

Then I serve them statically in my routes :
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    component: () => import('layouts/MainLayout.vue'),
    children: [
      { path: 'test', component: () => TestPage },
      { path: '', component: () => IndexPage }
  ],
  },
  // Always leave this as last one,
  // but you can also remove it
  {
    path: '/:catchAll(.*)*',
    component: () => import('pages/ErrorNotFound.vue'),
  },
];

A: I recently expriencied this.  The error was caused by an empty href inside an a tag:  <a href="" @click="goToRoute">.  You can either remove the href or change the a tag to something else, ie. button.  Let me know if this helps.

A: I had the same problem. I found that I had not started my project.


text:
Q: Перегрузка операции инкремента Перегрузил операцию инкремента специально для своего класса, но возникла проблема: если написать my_class++ то код не работает, зато при ++my_class все выполняется правильно.
my_class &operator++(my_class &in)
{
}

A: Вы перегрузили оператор преинкремента, он обычно выглядит так:
my_class& operator++(my_class &in)
{
    // какие-то инкрементирующие действия
    return in;
}

Этот оператор вызвается кодом:
my_class A;
++A;

Оператор постинкремента имеет вид:
my_class operator++(my_class &in, int dummy)
{
    my_class tmp = in;
    // Какие-то инкрементирующие действия
    return tmp;
}

Этот оператор вызвается кодом:
my_class A;
A++;

Обратите внимание на следующее:
1) Сигнатура оператора постинкремента имеет фиктивный аргумент int
2) Преинкремент возвращает ссылку на класс, который получился после инкрементирования
3) Постинкремент перед изменением in сохраняет его в временную переменную, чтобы потом вернуть его "до изменения" (и возвращает не ссылку, а копию).


text:
Q: Disabling mouse in Vim disables indentation I have Vim version 8.0.122 on FreeBSD 9.3 (installed with pkg). I have default global vimrc. I want to disable mouse support completely on my account, so I put
    set mouse=

in my local .vimrc. It works, mouse is disabled, but also autoindent is gone, i.e. I press enter in a .php or .c file and I'm back at the begining of the line instead of current indent position.
I want to have both, mouse disabled, autoindent working as it used to. What should I do?

A: I faced a similar problem. This is what helped me solve it.
On my computer the vim settings which made many things pretty are stored in /usr/shar/vim/vim*/defaults.vim, but this file was read only if there is no ~/.vimrc. So if you can either copy this entire file to you ~/.vimrc, or if you are an admin and want to make a change for all users, modify the file itself. Just comment out the line which says set mouse=a.


text:
Q: How To Upload CSV To Algolia Using A Script I would like to upload my CSV file using a PowerShell script. How is one able to accomplish this?
I was unable to find anything in the documentation. If there is something it should be searchable in the documentation.
https://www.algolia.com/doc/

A: As of November 2018, you can use the Algolia CLI to easily import your JSON or CSV file(s) from your terminal:

*

*$ npm i -g @algolia/cli

*$ algolia import -s path/to/your/file.csv -a your_app_id -k your_api_key -n your_index_name

A: I figured I'd post my solution. Just make sure that node.js and algolia-csv package is installed and then you can run the algolia-upload command from within PowerShell
https://github.com/algolia/algolia-csv-js
NPM Manager (Which is packaged with Node)
https://www.npmjs.com/package/npm
Windows Installer - https://nodejs.org/en/download/

*

*After installing "node-v6.11.1-x64" open the "node.js command
prompt" application via the start menu

*Run the following commands:
npm install -g algolia-csv

*Now you can prepare your command. (The CSV file must have headers in the first row only).

Options: algolia-upload $APP_ID $API_KEY $indexName $file|$url [-d $delimiter] [-b $batchSizer] [--clear-index] [--parse-arrays=$column]
Mandatory parameters are the aplication id, a key with write rights, the target index name and the input CSV (locally or accessible with http/https).
Other parameters:
-d let you set the delimiter used in your file. This should be set in quotes. Default is ','.
-b let you set the batch size. Default is 10000.
--clear-index forces the index to be cleared before uploading the new data.
--parse-arrays= let you specify if a column value should be splitted with ',' before uploading the data. More than one column can be set.
--geo-colums=latCol,longCol let you specify two columns that are to be used for creating the special algolia attribute _geoloc
This is the command that I ended up using just as a example.
algolia-upload APPID APIKEY INDEX PATH.csv

A: we don't currently have an example written for PowerShell, but the steps it would come to are:

*

*read the csv in PowerShell

*convert the csv to JSON

*push to the API using curl

However, by going this route, you can't take advantage of the retry and DSN logic that's built into the Algolia API clients. You can use any of the API clients to upload the data instead.
There's also a node CSV toolbox, which is a CLI to split and upload a csv file.
You can also upload it on the dashboard as described here


text:
Q: i need to know what different between screen size and screen density in my android app i need to support multiple  screens (all sizes and all screens )
so i have read about density and screen size but i don't know what i should to choose when i creat another xml file for every single activity .. a four xml files depend on screen size like this :
res/layout/your_layout.xml             (layout for normal screen)
res/layout-small/your_layout.xml       (layout for small screen)
res/layout-large/your_layout.xml       (layout for large screen)
res/layout-xlarge/your_layout.xml      (layout for extra large screen)

or five files to support all density like what i do with drawable png files
plz help me to find the answer i need to what better and what the deference between them .

A: This is so simple like if you are using hard values like setText="22sp.Now it might good your test mobile but good for every mobile screen so you have to create four folder
**hdpi,xhdpi,xxhdpi,xxxhdpi**

Copy the same file in these 4 folders and adjust it. when the app runs on any mobile Android framework automatically detects the screen and gets one of them.
Note: if you are using not hard values like matchparent etc then no need to create 4 duplicate files of that.


text:
Q: How to define a method like int.from_bytes() in Python? In python there is a method on the type int, namely int.from_bytes. It's not a method on a particular int, instead it's a method on the type. E.g.
>>> int.from_bytes(b'\xee\xff',"big")
61183

>>> int.from_bytes
<built-in method from_bytes of type object at 0x107fdb388>

How do I define something like this? Let's say a class called "point" is defined, how do I define something like
>>> point.from_coordinates(3,5)
<__main__.point object at 0x10c0c9310>

>>> point.from_keys(b'\x12\x3e')
<__main__.point object at 0x10bed5890>

? (Assuming points are initialized by some different method.)

A: You want classmethod, which is normally used as a decorator:
class point(object):
    @classmethod
    def from_coordinates(cls, x, y):
        pt = cls()
        pt.x, pt.y = x, y
        return pt

This is sometimes called the "alternate constructor" idiom. If there are multiple different ways to construct your type, instead of putting them all into one __init__ method with a mess of optional parameters or varags, put them all into separate classmethods.

A: You can use a classmethod, such as the mocked up example whose init expects ints, but also provides a convenient from_hex that tries to take strings and convert them to integers...
class MyClass(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b
    @classmethod
    def from_hex(cls, a, b):
        return cls(int(a, 16), int(b, 16))

The from_hex knows which class it is associated with, so by calling cls(...) you're able to construct a type of MyClass as though you'd written MyClass(a, b) with valid integers yourself.


text:
Q: Programmatically Scroll at specific item or offset, with UIKit Compositional Layout collectionView? I have an iOS 14 collectionView, configured with compositional layout.
You can scroll vertically through the collectionView, and you can scroll horizontally within the sections.
I would like to know if there is a way to scroll programmatically, within a section?
Something like collectionView.setContent(offset: 100, inSection: 2)
And is there a way to get the contentOffset of a particular section?
I can't find any function to do that.
Sincerely,
Jery

A: Its a hack but for such sections the parent is a UIScrollView which you can get a reference to by referencing a cell in the section and then referencing its superview.
Like this:
let cell = collectionView.cellForItem(at: indexPath)!
let scrollView = cell.superview as! UIScrollView
scrollView.setContentOffset(<#CGPoint#>, animated: true)


text:
Q: How to add quotes to first row and first 2 columns (csv - command line) I am struggling a bit because I need to add double quotes to the first row and first two columns of a csv file as illustrated here:
Input
var1,var2,var3,var4
x1,x2,x3,x4
y1,y2,y3,y4

Output:
"var1","var2","var3","var4"
"x1","x2",x3,x4
"y1","y2",y3,y4

I have tried for a while now, and the closest thing I have come to is:
# add single quotes around columns of csv files
sed "s/[[:alnum:]]*/'&'/g" input.csv >output1.csv
# transform the single quotes into double quotes
tr "'" '"' < output1.csv > output2.csv

But this is putting quotes around all columns like this:
"var1","var2","var3","var4"
"x1","x2","x3","x4"
"y1","y2","y3","y4"

Are you, more experienced command line users, able to help me?

A: You can qualify substitution for particular line numbers
$ sed '1s/[^,]*/"&"/g; 2,$s/\([^,]*\),\([^,]*\)/"\1","\2"/' ip.txt
"var1","var2","var3","var4"
"x1","x2",x3,x4
"y1","y2",y3,y4

*

*1s/[^,]*/"&"/g add quotes to all fields of first line

*2,$s/\([^,]*\),\([^,]*\)/"\1","\2"/ add quotes only for first two fields from 2nd line to end of file


text:
Q: Php curl и браузер тор Подключаюсь к сайтам через curl использую прокси тор.
Но прокси работают только при условии что браузер тор запущен, при его закрытии прокси перестают работать.
Как сделать чтоб работали прокси если я закрою браузер тор

A: Установить tor отдельно, а не в составе tor-браузера. Запустить его в режиме демона (в настройках проверить/указать адрес и порт).
Затем пропустить curl через tor (адрес и порт приведены условно, в кач-ве примера):
curl --socks5-hostname localhost:5555 http://ya.ru/ (curl старше версии 7.18.0)
или
curl -x socks5h://localhost:5555 http://www.google.com/ (на версиях старше 7.21.7)
Параметры вызова curl непосредственно из php надо поискать аналогичные.
Ещё можно прописать в ${HOME}/.curlrc настройку вида socks5 = localhost:5555
или добавить переменные окружения среды:
http_proxy=socks5h://localhost:5555 и https_proxy=socks5ya.ruh://localhost:5555
Если нужен HTTP прокси в кач-е прослойки перед tor - обычно используется связка tor+privoxy.
Цепочки в tor, запущенном в режиме демона, можно менять, посылая команду signal NEWNYM через telnet (вручную или скриптом).


text:
Q: Get all the jira information by hitting api using ruby I need to get all the information from a particular Jira using rest api in ruby,
I have tried using my credentials and my companies Jira URL, it's working fine but I want to do this without my credentials, I don't have much idea about it, using some access token some said it can be done, but I don't know how!
require 'rubygems'
require 'pp'
require 'jira-ruby'

options = {
 username: '',
 password: '',
 site: '',
 context_path: '',
 auth_type: :basic,
 use_ssl: true
}

client = JIRA::Client.new(options)
projects = client.Project.all

# Show all projects
# issues = client.Project.find('ion_authn_engine').issues

projects.each do |project|
 puts "name: #{project.name}"
end

I'm getting all the jira's but I have to use my credentials here, can it be done in other ways.

A: You didn't specify is you were using Jira Cloud or Jira on-prem.
If you are using the Cloud version, you can use API tokens
If you are using the on-prem solution, you can use OAuth, or cookies besides basic auth.

A: There are two ways to connect to a Jira instance (3 if you count your personal login/password).

*

*Using an account-based API key

*Using a server-generic oauth application key
Think of the long-term use case before deciding which one.
Account based API
The account based API key is connected with your account (whichever is used to make it).  This means it will have your account's permissions, including however ever they will change.  That could lead to unexpected behavior from the integrated apps, if your perms change without planning / coordination.
Also, this can be ideal, as the accounts API key is then a 'flexible permissions window' into the Jira server.  It's a good solution if you may want later to change what can go out over the query.  Maybe you want to make a few such accounts with different perms, so that the app can dynamically query data without seeing too much, ever.
Also, you can create these account-based API keys without involving your server's admin. They're just another thing a user can do.
Where to find it

A Revokable Password

Server generic Oauth
This kind of connection will always have unfettered access to the Jira instance's data.  This is a master key, and it's permissions can never be reduced.
Oauth keys need to be setup by a Jira site admin, since they bypass all other permissions levels.  They are suitable for do BI data links, which it sounds like that's what you're doing here.  They're more effort to setup, but more predictable long-term.  There's no mistake that the can be delete or changed by any of the admin actions that can impact user accounts.


text:
Q: Simple PHP Login URL not connecting with code I have been trying to make working php code which will return "1".
As well the database information is all removed, but is accurate since I get no "3" error.
Example being: www.mysite.com/login.php/?test=itemindatabase
and if "itemindatabase" is found in the database, then it will return "1"
A few notes:
login is the name of the table.
test is the name of the only column (other than id)
<?php
 $host = "localhost";
 $username = "";
 $password = "";
 $database = "";

      $connect = new PDO("mysql:host=$host; dbname=$database", $username, $password);
      $connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
           if(empty($_POST["test"]))
           {
                die("3");
           }
           else
           {
                $query = "SELECT * FROM login WHERE test = :test";
                $statement = $connect->prepare($query);
                $statement->execute(
                     array(
                          'test'     =>     $_POST["test"]
                     )
                );
                $count = $statement->rowCount();
                if($count > 0)
                {
                     die("1"); //success!
                }
                else
                {
                     die("0"); //fail not found
                }
        }

?>

I have only been getting "0" every try which means failure.

A: Things:-
1.Your all db credentials are empty? if you removed them because of security issue then Ok. Otherwise please provide valid and correct values there.Otherwise connection itself will not create.
2.$_POST["test"] need to be  $_GET["test"]
3.array('test'=>$_POST["test"]) need to be array(':test'=>$_POST["test"])
Check this code and try:-
<?php

 //comment these two lines when code started working fine
 error_reporting(E_ALL);
 ini_set('display_errors',1);

 $host = "localhost";
 $username = "";  //check and provide valid value
 $password = "";  //check and provide valid value
 $database = "";  //this can't be empty in any case

    try {
        $connect = new PDO("mysql:host=$host;dbname=$database", $username, $password);
        $connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

           if(!empty($_GET['test'])){
                $statement = $connect->prepare("SELECT * FROM login WHERE test = :test");
                $statement->execute(array(':test'=>$_GET["test"]));
                $count = $statement->rowCount();
                if($count > 0)
                {
                     echo "record found successfully";
                }
                else
                {
                     echo "no record found";
                }

           }else{
             echo "Please provide input value";
           }
    }
    catch(PDOException $e){
        echo "Error: " . $e->getMessage();
    }
    $conn = null;
?>

Note:- How to fetch records


text:
Q: Как задать адаптивную верстку блоку на html и .scss? Есть блок из шести подблоков, которые расположены по  два в ряду.

Как и где, с помощью свойства max-width, задать нужное значение, чтобы при просмотре на экране шириной 700px отображение блоков стало в один столбец (из шести блоков, один под другим)?
Т.е. я изменю масштаб окна браузера и при этом увижу один целый столбец из картинок.

.solutions {
  padding: 0px;
  position: relative;
  padding-bottom: 100px;
}
.solutions .hover-block {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  padding: 18px;
  background: transparent url("../images/prod-bg-hover.png");
  font-size: 15px;
  color: #ffffff;
  line-height: 21px;
  opacity: 0;
  -webkit-transition: all .3s ease;
  -o-transition: all .3s ease;
  transition: all .3s ease;
}
.solutions .hover-block h3 {
  text-align: center;
  font-family: 'DINPro-Black', sans-serif;
  color: #fff;
  font-size: 58px;
  font-weight: 500;
  line-height: 124px;
  text-transform: uppercase;
}
.solutions .hover-block h3.small {
  font-size: 32px;
}
.solutions .hover-block p {
  font-weight: 400;
  text-align: center;
  font-size: 18px;
}
.solutions .container-solutions a {
  position: relative;
  display: block;
  -ms-flex-negative: 0;
  flex-shrink: 0;
  -webkit-box-flex: 1;
  -ms-flex-positive: 1;
  flex-grow: 1;
}
.solutions .container-solutions a:hover img, .solutions .container-solutions a:focus img {
  transform: scale(1.2);
  transition: 1s cubic-bezier(0, 0, 1, 1) 500ms;
}
.solutions .container-solutions a:hover .hover-block, .solutions .container-solutions a:focus .hover-block {
  opacity: 1;
}
.solutions .flex-column {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
}
.solutions .flex-center-column {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  width: 100%;
}
.solutions .flex-center-column a {
  overflow: hidden;
  width: 50%;
}

Наши решения

Promo Face

                                    Вспомогательная программа, позволяющая отслеживать

                                    эффективность и осуществлять контроль

                                    работы над промо-персоналом.

Корпоративный университет

                                    Виртуальный портал для дистанционного обучения и
                                    развития сотрудников, а также для ознакомления
                                    со структурой и внутренним взаимодействием
                                    в Компании.

CRM-Promo

                                    Cистема с возможностью интеграции с сайтом, социальными
                                    медиа, инструментами распознавания QR кодов и т.д.
                                    позволяющая собирать показатели об эффективности
                                    проводимой промоакции.

DIGITAL SAMPLING

                                    Возможность интеграции в Интернет-магазины для
                                    предложения пользователям семплингов
                                    (вложений) к совершенным покупкам.

Программа Лояльности

                                    Мотивационная программа для стимулирования сотрудников
                                    к повышению показателей с возможным
                                    дальнейшим награждением.

Library

                                    Программа для информирования мерчендайзеров и
                                    сотрудников торговых точек/учреждений о
                                    новых продуктах и изменениях.

A: Добавьте этот код в конец css файла
@media only screen and (max-width: 700px) {
  .flex-row {
   width: 100%;
  }
  .solutions .flex-row a {
    width: 100%;
  }
}

.solutions {
  padding: 0px;
  position: relative;
  padding-bottom: 100px;
}

.solutions .hover-block {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  padding: 18px;
  background: transparent url("../images/prod-bg-hover.png");
  font-size: 15px;
  color: #ffffff;
  line-height: 21px;
  opacity: 0;
  -webkit-transition: all .3s ease;
  -o-transition: all .3s ease;
  transition: all .3s ease;
}

.solutions .hover-block h3 {
  text-align: center;
  font-family: 'DINPro-Black', sans-serif;
  color: #fff;
  font-size: 58px;
  font-weight: 500;
  line-height: 124px;
  text-transform: uppercase;
}

.solutions .hover-block h3.small {
  font-size: 32px;
}

.solutions .hover-block p {
  font-weight: 400;
  text-align: center;
  font-size: 18px;
}

.solutions .container-solutions a {
  position: relative;
  display: block;
  -ms-flex-negative: 0;
  flex-shrink: 0;
  -webkit-box-flex: 1;
  -ms-flex-positive: 1;
  flex-grow: 1;
}

.solutions .container-solutions a:hover img,
.solutions .container-solutions a:focus img {
  transform: scale(1.2);
  transition: 1s cubic-bezier(0, 0, 1, 1) 500ms;
}

.solutions .container-solutions a:hover .hover-block,
.solutions .container-solutions a:focus .hover-block {
  opacity: 1;
}

.solutions .flex-column {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
}

.solutions .flex-center-column {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  width: 100%;
}

.solutions .flex-center-column a {
  overflow: hidden;
  width: 50%;
}

@media only screen and (max-width: 700px) {
  .flex-row {
    width: 100%;
  }
  .solutions .flex-row a {
    width: 100%;
  }
}

Наши решения

Promo Face

                Вспомогательная программа, позволяющая отслеживать
 эффективность и осуществлять контроль
 работы над промо-персоналом.

Корпоративный университет

                Виртуальный портал для дистанционного обучения и развития сотрудников, а также для ознакомления со структурой и внутренним взаимодействием в Компании.

CRM-Promo

                Cистема с возможностью интеграции с сайтом, социальными медиа, инструментами распознавания QR кодов и т.д. позволяющая собирать показатели об эффективности проводимой промоакции.

DIGITAL SAMPLING

                Возможность интеграции в Интернет-магазины для предложения пользователям семплингов (вложений) к совершенным покупкам.

Программа Лояльности

                Мотивационная программа для стимулирования сотрудников к повышению показателей с возможным дальнейшим награждением.

Library

                Программа для информирования мерчендайзеров и сотрудников торговых точек/учреждений о новых продуктах и изменениях.


text:
Q: Excel Index Match with adjustable rows I am using Excel 2019 and I want to write a formula that will do the following:
search for a student name in Sheet1 (named classes) and for every class he/she took, update from Sheet2 (named Archive) the Code number.
Here is what the data looks like:
Sample of Student Records
If the number of classes was fixed for everyone, e.g. if every student had 1 class the answer would be to write something like:
=INDEX(Sheet2!C$3:C$21,MATCH(Sheet1!A3,Sheet2!A$2:A$21,0),1)
In our case however the number of classes may vary per student (e.g. John has 2 classes, Physics and Biology, while Helen has 4).

A: Add a column to the archive sheet that puts the name of each student against each row.
In cell D2, I have this:
=IF(B2="",A2,D1)

Then for the formula to get the code, I have this in cell K2:
=INDEX($C$2:$C$9,MATCH($I2&$J2,$D$2:$D$9&$A$2:$A$9,0))

A: replace Sheet2!C$3:C$21 with INDIRECT("Sheet2!C$"&match(Sheet1!A3,Sheet2!A:A)&":C$21")
and MATCH(Sheet1!A3,Sheet2!A$2:A$21,0) with MATCH(Sheet1!B3,INDIRECT("Sheet2!A$"&match(Sheet1!A3,Sheet2!A:A)&":A$21"),0)
pls share if it works/not/understandable..


text:
Q: PyQt QTreeView, once the folder expanded, I can not delete the folder I am implementing a workspace area that showing the files in the workspace folder by using QTreeView. The workspace itself is a object which constructed by QTreeView and QFileSystemModel and QMenu(once user right clicks, a menu will show up to do copy paste and so on)
I have several QWidgets which sits in tabs, each tab also contains a workspace obj(they are not one single object, workspace obj gets created multiple times, each tab contains one).
I implemented copy paste, delete and so on. Everything works fine except one case:
once a folder expanded and shows its content, it can not be deleted even I collapsed it. I have to relaunch the program and delete the folder without browsing it.
If the folder is ever browsed, when I tried to delete it. it keeps showing access denied info. I tried to use os.chmod to change the permission. However, it does not allow me to do so and also shows access denied.Also, not only delete it, I can not copy it and so on.
I thought the reason may be that I created multiple workspace objects and they conflict with each other and when I delete the folder, the obj does not get the access because the others are displaying the folder. However, even I constructed only one workspace obj and added to the layouts with tabs. it still shows the same behavior: once the folder is expanded, I lost the permission. However, if the folder is not expanded ever. I can delete it successfully.
Can anyone help me on this please? Thank you!