text:
Q: Load MovieClip inline in TextField I want to load a MovieClip inside a TextField inline with the text.
The TextField documentation says "HTML text that you assign to a text field can contain embedded media (movie clips, SWF files, GIF files, PNG files, and JPEG files)."
How can this be done with MovieClips? There must be a listener we can override.
source: http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/text/TextField.html

A: You can use the <img> tag to link to an swf.
Or, if you need to have more control, place an <img>to load a placeholder, and use getImageReference to access and/or modify the image's Loader object.  This will also allow you to set the loader content to visible = false, and add a MovieClip to it using addChild.

A: From the documentation :

src: Specifies the URL to an image or
  SWF file, or the linkage identifier
  for a movie clip symbol in the
  library. This attribute is required;
  all other attributes are optional.
  External files (JPEG, GIF, PNG, and
  SWF files) do not show until they are
  downloaded completely.

You can add MovieClip by setting his linkage identifier in the src attribute of the <img> node.

A: For sure MoveiClip can be imported into the TextField inline of your texts...
But there's an easier way also possible from now on, not only the easier way but also more efficient and powerful.
Check out www.doitflash.com
The site produced a class named "TextArea" which is an extension to the original "TextField" class that ends to the shortcomings of TextField.
TextArea not only allows to have MovieClips and SWF files in line of your texts but also allows and created the most efficient ways to communicate with your SWF file live at any time, it allows to have different HTML tags rather than just having the  tag to import images, you can have video player, talking avatar, flash buttons and anything else with their own tags to even set their settings dynamically right from your dynamic content.
It has lots of more features and doesn't specifically limited to this issue. Check out doitflash for more information. the site provides the platform and downloading it is also free of charge :)

A: no you cannot do this in flash. you can only load images in a textfield.


text:
Q: Storing a C array of C structs in NSData I've got a really simple C struct like so:
typedef struct {
    int tag;
    CGPoint position;
} Place;

That is, all scalar types and no pointers in the struct.
Then I've got an array of those points like so:
 Place *dynamicPlaces = calloc(numberOfPlaces, sizeof(Place));

So each element of dynamicPlaces ought to be (unless I've mixed something up… it's certainly possible with me and pointers…) a struct of type Place, initialized with all its members to 0, yeah? So far so good.
Then I'm trying to put that array in an NSData object to be sent over the network (along with the count of elements, not shown):
NSData *placesData = [NSData dataWithBytes:dynamicPlaces length:(sizeof(Place) * numberOfPlaces)];

I'm passing it the array directly, because if memory serves, the pointer dynamicPlaces is really pointing to the first struct element of the array, and then I tell it how many elements there are via length. I think this is good.
Finally, on the other side I do this when decoding my object.
[receivedData getBytes:receivedDynamicPlacesArrayPointer length:[receivedData length]];

But I get an EXC_BAD_ACCESS on that line and I can't quite figure out why. As far as I can tell by the documentation, this ought to be storing the bytes from the NSData into a copied location in memory, and point to that blob with receivedDynamicPlacesArrayPointer.
It's entirely possible I've made a mistake doing this, pointers trip me up, even though I think I understand them. Any help would be greatly appreciated.

A: getBytes:length: docs say: "Copies a number of bytes from the start of the receiver's data into a given buffer."
So you will need to first allocate memory for receivedDynamicPlacesArrayPointer yourself. Did you do that?
In other words, you'd do like:
 Place* receivedDynamicPlacesArrayPointer = (Place*)malloc([receivedData length]);

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# - visit url in background having a brain freeze today.
I'm looking to visit a URL to add tracking information just before my shopping cart gets redirected back to the main page (i.e. just after purchase).
I can't think how I could visit that URL without actually redirecting to my tracking page, and then redirecting again from there back to the homepage.  Does anyone know?
This seems like it should be really easy, but I can't seem to get it working.
Thanks

A: Use the HttpWebClient to programattically visit a web page on the server side?
http://msdn.microsoft.com/en-us/library/system.net.webclient(v=vs.80).aspx

A: There are multiple ways:

*

*Put an Iframe or image tag on your homepage after being redirected from your purchase page that requests that url.

*Programmatically request the tracking page after purchase on your server.

*Make an ajax request from your homepage after being redirected (or before being redirected from your puchase page)

A: Are you familiar w/ JSON requests?  You could hit a URL in the background (and feed it a few parameters) without actually loading a new page.

A: How about using javascript:
function async_url_call(url) {

    xmlHttp = GetXmlHttpObject();

    if (xmlHttp == null) {
        alert("Your browser does not support AJAX!");
        return;
    }

    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
}


text:
Q: factory method is not flexible enough regarding constructors with different parameters or am I missing something? Please consider these 2 classes:
public class Audi implements Car {
private String color;
private int turnAssistLevel;

public Audi() {
}

public Audi(String color) {
    this.color = color;
}

public Audi(String color, int turnAssistLevel) {
    this.color = color;
    this.turnAssistLevel = turnAssistLevel;
}

public String getColor() {
    return color;
}

public void setColor(String color) {
    this.color = color;
}

public int getTurnAssistLevel() {
    return turnAssistLevel;
}

public void setTurnAssistLevel(int turnAssistLevel) {
    this.turnAssistLevel = turnAssistLevel;
}
}

public class Bmw implements Car {
private String color;
private boolean hasXDrive;

public Bmw() {
}

public Bmw(String color) {
    this.color = color;
}

public Bmw(String color, boolean hasXDrive) {
    this.color = color;
    this.hasXDrive = hasXDrive;
}

public String getColor() {
    return color;
}

public void setColor(String color) {
    this.color = color;
}

public boolean isHasXDrive() {
    return hasXDrive;
}

public void setHasXDrive(boolean hasXDrive) {
    this.hasXDrive = hasXDrive;
}
}

I would like to write some factory using factory methods:
Let's say I want to have some factory methods to return empty cars. Easy to do:
public interface CarFactory {
public Car makeCar();
}

As an implementation:
public class BmwCarFactory implements CarFactory {

public Car makeCar() {
    return new Bmw();
}
}

The same I could do for Audi.
Now, say I need a car with color. As I see it I need to define a factory that knows how to do cars with colors:
public interface CarWithColorFactory {
Car makeCar(String color);
}

Now to make a Bmw with color:
public class BmwWithColorCarFactory implements CarWithColorFactory {
public Car makeCar(String color) {
    return new Bmw(color);
}
}

The same for Audi.
But now, say I need to do a Bmw with both color and xDrive. Or an Audi with both color and turnAssistLevel. How would I do this using factory method???
Using simple factory I'd probably do:
public class SimpleCarFactory {

public Car makeBmw(String color, boolean hasXDrive) {
    return new Bmw(color, hasXDrive);
}

public Car makeAudi(String color, int turnAssistLevel) {
    return new Audi(color, turnAssistLevel);
}
}

So how to do it using factory method?
Kind regards,

A: How about using a builder instead ?
That way you can have methods allowing you to set each attribute independently, and provide suitable defaults such that you don't need to specify them explicitly if not required.
e.g.
BuilderFor.type("Audi").withColor("Red").withTurnAssist().build();

so the above effectively uses a factory to give you the appropriate builder

A: A Factory Method provides configuration through subclassing. I find it simpler, therefore, to make all configuration decisions in subclasses. In practice, this means Factory Methods will be nullary (taking no arguments).***
The Factory Method returns an abstract product, with no consideration given to that product's concrete properties. This behavior is consistent with the design principle of programming to an interface. For example, a program needing to drive a Car should depend on the Car interface. It should not depend on a black BMW with XDrive. It is strictly the responsibility of the BMW subclass (and possibly the BMW_XDrive subclass) to configure such a concrete product.
To reiterate: the consumer of the Factory Method (aka the Creator) does not configure the product. Here is an example where the consumer (FactoryMethod) needs to drive a Car and specifies the method rentCar() in order for subclasses to provide that dependency. The two subclasses each configure a specific concrete product, but the consumer simply gets a Car.
public abstract class FactoryMethod {
    abstract Car rentCar();

    public void driveCar() {
        Car car = rentCar();
        car.drive();
    }

    public static class AudiFactoryMethod extends FactoryMethod {
        @Override
        Car rentCar() {
            return new Audi("red", 5);
        }
    }

    public static class BmwFactoryMethod extends FactoryMethod {
        @Override
        Car rentCar() {
            return new BMW("black", true);
        }
    }

    public static void main(String... args) {
        new AudiFactoryMethod().driveCar();
        new BmwFactoryMethod().driveCar();
    }
}

As another example, consider a class that depends on a List. It could obtain that List through a Factory Method by adding an abstract method getList(). This class might then have a LinkedList subclass and an ArrayList subclass.

*** Yes, I know that the GoF describes the use of parameterized factory methods; but these are inevitably implemented in violation of the Open-Closed Principle. A static factory method, as described by Josh Bloch, is simpler and more straight-forward in that case.


text:
Q: Conda cannot see Cuda version I am trying to install the newest Tensorflow GPU version to an Ubuntu environment. The Cuda drivers are correctly installed and working, which I can confirm with the following commands:
nvcc --version

With output:
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2022 NVIDIA Corporation
Built on Tue_May__3_18:49:52_PDT_2022
Cuda compilation tools, release 11.7, V11.7.64
Build cuda_11.7.r11.7/compiler.31294372_0

Also, nvidia-smi returns a valid result:
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 515.43.04    Driver Version: 515.43.04    CUDA Version: 11.7     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|                               |                      |               MIG M. |
|===============================+======================+======================|
|   0  Tesla V100-SXM2...  On   | 00000000:06:00.0 Off |                    0 |
| N/A   40C    P0    68W / 300W |   9712MiB / 16384MiB |      7%      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+

It seems I have the Cuda Version 11.7. Creating an empty Conda environment for Python 3.9, I want to install cudatoolkit and cudnn as instructed at https://www.tensorflow.org/install/pip?hl=en:
conda install -c conda-forge cudatoolkit=11.2 cudnn=8.1.0

However it complains that I do not have the correct Cuda version and won't install:
 - cudatoolkit=11.2 -> __cuda[version='>=11.2.1|>=11|>=11.2|>=11.2.2']

 Your installed CUDA driver is: 11.7

Obviously, my Cuda version meets the requirements, but somehow Conda would not see it. This seems to be a rare error, I didn't saw many similar issues on my search and turned to here. What can be wrong here?


text:
Q: error when erasing object in vector. how do i add move assignment operators to my classes? I am getting an error when I am trying to erase an object from my vector
googled but I can't understand what's wrong. from what I gathered I am calling the erase function correctly but I have to provide a move assignment operator to my classes?
my function where i call the erase
void removegroup(const short &group){
switch (tracker[group].group){
    case 0: {
        guardvec.erase(guardvec.begin()+tracker[group].position); //this is the problem it compiles just fine if i comment out this line
        //guardvec.erase(remove(guardvec.begin(), guardvec.end(), tracker[group].position),guardvec.end()); //tried this and it doesnt work
    }

        break;
}
for (short counter=0;counter<tracker.size();counter++)
    if ((tracker[counter].group==tracker[group].group)&&(tracker[counter].position>tracker[group].position))
        tracker[counter].position=tracker[counter].position--;
}

my class
class guardhitdice {
    friend class guard;
    short const times = 2, dice = 8, plus = 2;
};

class guard : private guardhitdice {
private:
    short units, XP, morale, totalHP=0, dead=0, wounded=0;
    short* HP = new short[units];
public:
    void showstats(){
        std::cout << "STR=1, DEX=1, CON=1, INT=0, WIS=0, CHA=0, Perception=2, Passive Perception=12"<<std::endl
        <<"current xp: "<<XP<<"total HP across units: "<<totalHP<<"casualties: "<<dead<<"wounded: "<<wounded;
    }
    void initializeHP(){
        for (short counter=0; counter<units-1; counter++){
            HP[counter]=plus + D(times, dice);
            totalHP+=HP[counter];
        }
    }
   guard(const short &xp, short &Units, short &Morale){
       XP=xp;
       units=Units;
       morale=Morale;
      // short* HP = new short[units];
       initializeHP();
   }
    ~guard(){
        delete HP;
    }

};

here is my compiler error https://pastebin.com/KSniFkVD
it should be able to remove the object at tracker[group].position. btw position is a short
i also tried adding this to my classes but they don't work
guardhitdice& guardhitdice ::operator=(guardhitdice&&);

  guard& guard ::operator=(guard&&);

it works if I do it for normal vectors but not for vectors of objects

A: Your problem can be reduced down to
#include <vector>

class test{
    short const times = 2;
};

int main()
{
    std::vector<test> t;
    t.push_back(test{});
    t.erase(t.begin()); //<-- BAM!
}

Example: https://ideone.com/MlwUyI
vector does a lot of copy-and-assigning. Copying is cool, but test contains a const member. You can't change a const variable, so you can't assign it.
But since it's initialized with a literal and there's no constructor that'll allow the value to be initialized to something else, all instances of test will have the same value. That's a pretty good fit for static. static variables don't take part in assignment, so the default assignment operator is usable.
class test{
    static short const times = 2;
};

Example: https://ideone.com/npUi4B


text:
Q: R Error in env_has(env, var, inherit = TRUE) : attempt to use zero-length variable name Sample data
ACCOUNT <- c("M191212", "M205668", "M197954", "M208966", "M193465", "M207622", "M191869")
PRODUCT <- c(1, 2, 3, 1, 2, 3, 2)
This is made into a dataset by lazy_dt() and as_tibble()

Code
library(tidyverse)
library(data.table)
library(dtplyr)

data2 <- data %>%
  lazy_dt() %>%
  mutate(YR = substring(ACCOUNT,2,3))%>% #This bit works fine
  mutate(PRODUCT_NAME = dplyr::recode(PRODUCT,
                         `1` = "PROD_A",
                         `2` = "PROD_B",
                         `3` = "PROD_C")) %>%
collect()

When I try to run this I get an error 'Error in env_has(env, var, inherit = TRUE) :
attempt to use zero-length variable name'.
I have tracked it down to the recode section. The answers on here relating to the sero-length error suggest it's the back ticks that are the problem, but I have tried changing them to ' i.e. single quote marks, and I still get the same error. PRODUCT is stored as an integer. This code used to run fine a few months ago, but it's now not working. I am using dtplyr 1.2.1.


text:
Q: How to Copy values from a Datagridview selected row to textboxes I am trying to select a datagridview row and copy values to 3 textbox.
I tried this code (it works in another my project), but I got an error. This is the code:
private void DataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.RowIndex >= 0)
        {
            DataGridViewRow row = this.DataGridView2.Rows[e.RowIndex];

            textBox1.Text = row.Cells["HomeNM"].Value.ToString();
            textBox3.Text = row.Cells["HostNM"].Value.ToString();
            fromTxt.Text = row.Cells["odd1NM"].Value.ToString();

        }
    }

This is my error:
Error 1 ' bexscraping.Form1 ' does not contain a definition of ' DataGridView2 ' and has not been found no extension method ' DataGridView2 ' accepting a first argument of type ' bexscraping.Form1 ' . Probably missing a using directive or a reference to an assembly.

I don't know where is the error- Any idea?
EDIT: I forgot to initialize my datagridview;M now my code is working! Anyway thanks!

A: Make sure that the gridView is initialzed. Then try this
private void dataGridView1_Click(object sender, EventArgs e)
    {
        if(dataGridView1.SelectedRows.Count>0){
           textBox1.Text = dataGridView1.SelectedRows[0].Cells["HomeNM"].Value.ToString();
           textBox2.Text = dataGridView1.SelectedRows[0].Cells["HostNM"].Value.ToString();
            textBox3.Text = dataGridView1.SelectedRows[0].Cells["odd1NM"].Value.ToString();
    }
   } // haha

A: First of all make sure that the name DataGridView2 is correct.
Then open the designer, click on DataGridView2 and in the properties make sure that Design -> GenerateMember is set to true.
Did this help ?

A: try this sir.
if (e.RowIndex >= 0)
{
 txtbox1.text = datagridview1.currentrow.cells["cellname"].value
 . . . 'and so on.
}

hope this will solve your error


text:
Q: JUnit Eclipse View I am running Junit tests using Eclipse Luna. I have implemented @Test method. I loop within the @Test method for multiple records and use Assert.assertEquals for Non-XML messages and XMLAssert.assertXMLEqual for XML messages.
The problem is, when I run the Junit with single or multiple test cases, I do not get the proper result in the Junit View. It always shows "Runs: 1/1" and does not show the correct count of runs. Even the failures and success are not shown correctly. Am I missing something here?

A: If you only have a single @Test method, there is only one thing running, so the Runs: 1/1 is correct. If you want to have more show up, make each assertion in its own test.


text:
Q: sqoop import error from teradata to hive I am using below given sqoop command:
sqoop import
    --libjars /usr/hdp/2.4.0.0-169/sqoop/lib,/usr/hdp/2.4.0.0-169/hive/lib
    --connect jdbc:teradata://x/DATABASE=x
    --connection-manager org.apache.sqoop.teradata.TeradataConnManager
    --username ec
    --password dc
    --query "select *  from hb where yr_nbr=2017"
    --hive-table schema.table
    --num-mappers 1
    --hive-import
    --target-dir /user/hive/warehouse/GG

I'm getting this error:
org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1657) at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:162)
    17/04/06 11:15:41 INFO mapreduce.Job:  map 100% reduce 0%
    17/04/06 11:15:41 INFO mapreduce.Job: Task Id : attempt_1491466460468_0029_m_000000_1, Status : FAILED
    Error: org.apache.hadoop.fs.FileAlreadyExistsException: /user/root/temp_111508/part-m-00000 for client 192.168.211.133 already exists

A: From the error, I can guess that the output file is already in your target directory, may be from your previous sqoop import. There is an option in sqoop import named --delete-target-dir which will delete your target output directory and re-create them in your next sqoop import. Hope that helps.


text:
Q: "Uncaught SyntaxError: Unexpected token :" trying to fetch JSON from url Using the DotA 2 Web API, I'm trying to get the JSON from a certain URL: https://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/V001/?match_id=27110133&key=3C2DCF9BA05F56704FDF3F45BE2C6AD3. I would then like to use the JSON object like this json.players[0].kills.
I open the below html in a file using Chrome, and it gives me the error Uncaught SyntaxError: Unexpected token :.
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script>
      $.ajax({
        type: 'GET',
        url: 'https://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/V001/?match_id=27110133&key=3C2DCF9BA05F56704FDF3F45BE2C6AD3',
        async: false,
        dataType: 'jsonp',
        success: function(data)
        {
          console.log(data);
        },
        error: function(e)
        {
           alert(e.message);
        }
      });
    </script>
  </head>
</html>

I have used JSON before on iOS, but I am a total noob to web development, so apologies for what is a probably really simple question.


text: Q: When I deselect the swatch once after selected, the product image is not displaying in magento 2 When I deselect the swatch once after selected the product image went blank when I inspected and the image src went undefined in Magento 2.2??


text:
Q: jcarousel out of position when not at 100% in chrome I use Sorgilla jcarousel, just wondering can anyone spot something obvious as to why only in Google Chrome, when I zoom in or out, not at 100% the positioning of the carousels are completely off.
Im not sure what specific code to post but here are the 2 carousels being called. both have the same problem.
Im assuming its something to do with the pixels not adjusting for resize or something, but it isnt an issue in other browsers.
Any help would be great thanks.
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('#mycarousel').jcarousel({
    start: 2, // Configuration goes here
    wrap: "circular",
    scroll: 1,
    auto:7
});
});

jQuery(document).ready(function() {
jQuery('#top-carousel').jcarousel({
    start: 2, // Configuration goes here
    wrap: "circular",
    auto: 12,
    scroll: 1

});
});
</script>

A: You can use the workaround that works fine for me.
This is not the best solution, you can definitely try to improve it.
Here is how you can change your code
jQuery(document).ready(function() {
var animation = $.browser.safari ? null : "normal";
jQuery('#mycarousel').jcarousel({
    start: 2, // Configuration goes here
    wrap: "circular",
    scroll: 1,
    auto:7,
    animation: animation,
        itemLoadCallback: {
            onBeforeAnimation: function (instance) {
                if ($.browser.safari) {
                    var itemPos = instance.first;
                    var pageWidth = instance.container.width();
                    var expectedItemPos = pageWidth * (1 - itemPos);
                    instance.container.prevObject.animate({ "left": expectedItemPos + "px" });
                }
            }
        }
});
});

The code above is used for left to right carousel.
Additinal info about jcarousel configuration you can find here


text:
Q: Optimal choosing : MATLAB Consider 2 sets
A = randi(1000,100,7);
B = randi(700,300,7);

I would like to find a function : B# = optimf(A,B) and gives me B# = {100x7} which is a collection of rows from B such that some attribute( eg. mean ) is minimum.
For eg: B# = optimf(A,B) such that mean(B#) - mean(A) is minimum.
Any ideas?

A: According to me Optimization is finding the best suitable value of a function. For example, if you have an equation and you need to find minimum value at which the equation satisfies criteria, then this is an optimization problem.
There is no such optimization function AFAIK for your function. But, you can take help of optimization algorithms like Least Square Errors
Or simply use some filter of MATLAB.
I hope it helps.
UPDATE
(Not a sophisticated solution but just works in some cases.)
Step 1-
Make a for-loop and select randomly some values from input vector. So you get a random subset.
Step 2
Define a cost function. A function that can measure how good is the subset. The function will take input as vector and gives output a numerical quantity such as % of quality.
Step 3
Go on taking these readings. Take the max value of output function and its corresponding vector. That should be a solution.
OR
use algorithms like ACO


text:
Q: ZFS on RAID6 over iSCSI We are planning to deploy a ~100TB storage onto our Debian systems.
The storage consists of an external enclosure (EonStore D1000: ESDS1024) with 24 6TB-disks, that connects to a single host via iSCSI over a 10GBit fibre.
Because the storage is already quite large and we might want to expand it in the future, we'd like to use ZFS as the filesystem.
Now the EonStore D1000, comes pre-configured as a RAID6 system and also supports hardware-encryption (SED). It could also be configured as JBOD.
I read that ZFS should never be used on hardware RAIDs and instead prefers to  get direct access to the harddisks.
However, I'm not sure whether this holds true for iSCSI devices as well (e.g. does iSCSI report enough info to ZFS to make its fault correction shine in relation to the built-in RAID6?)
Also, we are tempted to use SED, which I guess will not play together with ZFS's fault correction at all.
So my question: should I (still) avoid RAID6 at all costs in RAIDZ instead? how about encryption?

A:
I read that ZFS should never be used on hardware RAIDs and instead
  prefers to get direct access to the harddisks.

In this case: Bollocks.
Here is the gist. If you run this as ZFS vs JBOD you multiply your already bad UI bandwidth (10G is NOT a lot). If you run it as Raid 6 then spawn something non redundant on it, you do not deal with redundant network traffic. Case closed.
Use enclosure management to handle enclosure failures. Use the enclosure EACH as "a disc" (with a Raid 6 below) and use ZFS non-redundant storage (or go mirroring if you want to go really crazy, which sometimes makes sense).
It really runs down on performance and seriously, for 24 discs 10G is not exactly ample. You want to avoid redundant network traffic, which happens when you do software based Raid with remote discs.


text:
Q: Работа с БД из двух приложений Есть два приложения:
Приложение А - записывает данные полученные с АЦП в БД,
Приложение Б - считывает данные,полученные с АЦП из БД для анализа.
Как сделать так,чтобы приложение Б считывало данные после того, как приложение А закончит записывать данные? Приложение записывает 2003 значения.
БД - postgresql
Язык - С#


text:
Q: Can I achieve full width of table on mobile screen using Vuetify Can I achieve having table 'zoomed-out' on small screen using Vue2 and Vuetify?
I have a task where table needs to remain being full width on mobile screen where it can be zoomed in. To basically achieve img-like behavior.
I basically need to achieve this second screen from this image, but using v-data-table .

Even though "they both equally suck", I need the second solution.
Is there any Vuetify specific solution for this?

A: In vuetify you can use v-data-table and use prop mobile-breakpoint="0"
 <v-data-table
     ...
      mobile-breakpoint="0"
    ...
    ></v-data-table>


text:
Q: wordpress: sticky menu not sticking upon scroll until later I am using a flat theme (Cordillera) on my new blog set up and had help adjusting the homepage full screen banner to a smaller size (you can see that post and solution in this thread).
The solution worked great but I am now noticing that the sticky menu is not sticking as soon as it hits the top of the page but will jump on board upon scrolling further down (hit jumps on about the blog section for me on chrome). I am assuming that this issue has something to do with the banner resize but to be honest, I'm not 100% sure on that.
I'm not sure what code to pull out for examination, this is my first usage of a flat theme but can if someone tells me what to look for.
Thanks again for any and all help!

A: The code to control your sticky header is in the script file cordillera.js.
The code applies the sticky header at exactly the height of the viewport, which is the variable winHeight:
var winHeight=$(window).height();

If you set winHeight to be a custom number, it will kick in at that point. Here is the code from that script:
   //fixed header
   $(window).scroll(function(){
  if( $(".top-banner").length ){
   var winHeight=$(window).height();
    }
    else{
        var winHeight = 0;
        }
   if( $("body.admin-bar").length){
       if( $(window).width() < 765) {
               stickyTop = 46;

           } else {
               stickyTop = 32;
           }
     }
     else{
         stickyTop = 0;
         }
         $('.sticky-header').css('top',stickyTop);
                   var scrollTop = $(window).scrollTop();
               if ( scrollTop > winHeight + stickyTop ) {
               if( !$(".top-banner").length ){
                   $('header#header').hide();
               }
                   $('.sticky-header').show();
                   } else {
                       if( !$(".top-banner").length ){
                       $('header#header').show();
                       }
                       $('.sticky-header').hide();
                   }
    });


text:
Q: Solve different equation with eigenvalues (multiplicity > 1) and eigenvectors Solve
$$
\frac{du}{dt} = \begin{bmatrix}
1 & 0 \\
1 & 1
\end{bmatrix} u
$$
For $A = \begin{bmatrix}
1 & 0 \\
1 & 1
\end{bmatrix}$, there is only one eigenvalue $\lambda = 1$, and the corresponding eigenvector is $x=\begin{bmatrix}
0 \\
1
\end{bmatrix}$
so, shouldn't the solution be
$$u = c e^t\begin{bmatrix}
0 \\
1
\end{bmatrix}$$.
But from the ref solution, I see
$$u = c_1 e^t\begin{bmatrix}
1 \\
t
\end{bmatrix} + c_2 e^t\begin{bmatrix}
0 \\
1
\end{bmatrix}$$
I wonder how is the $\begin{bmatrix}
1 \\
t
\end{bmatrix}$ part derived?

A: This may be formulated as $\frac{du}{dt}=Au$, where
$$
              A =\left[\begin{matrix}1 & 0 \\ 1 & 1\end{matrix}\right].
$$
And $A=I+N$ where $N^2=0$. The solution is
$$
             u(t)=e^{tA}u(0)=e^{tI}e^{tN}u(0)=e^{tI}(I+tN)u(0)=e^{t}u(0)+te^{t}Nu(0).
$$


text:
Q: Information about resources in a subscription Good morning,
I've been trying to get information about all the resources in a given Azure subscription. Is there a way to see all the resources hosted in a subscription?

A: Have you tried running Az-GetResource via PowerShell
First Install Az Modules
Then would run
Connect-AzAccount

Then after the Pop Up asking to login
Get-AzResource | ft


text:
Q: MaterializeCSS Sidebar Display Issue I have this weird issue with Materialize CSS where the sidebar overlaps the content in the "main" panel as well as the footer (see image here: most content is censored on the page, the "m" in the title is part of the title text "Problem Submission"), even though I believe I have the gridding set properly. It happens both with Chrome and Safari (I bet no hope for IE either). Here's the basic structure of my document, where all of the below markup is within the  tag (it's a Jinja template, script includes and everything are located in a "base" template):

      menu

{{ self.title() }}

Brand Name

    {% block navlinks %}

Back to Home

    {% endblock %}

        {% block jumbo_content %}{% endblock %}

        {% block main_content %}
        {% endblock %}

        {% block toc_content %}
        {% endblock %}

Brand Name

Description

Important Links

Login

Contact Us

About

    Copyright notice

Has anyone had any similar issues or can anyone point out something wrong with my HTML layout?

A: If you check the side nav documentation and scroll all the way to the bottom, it shows how you can offset your content when using a fixed side nav.
Basically, you just add a padding left to your entire content.
 header, main, footer {
   padding-left: 240px;
 }

 @media only screen and (max-width : 992px) {
   header, main, footer {
     padding-left: 0;
   }
 }

The media query will make sure the padding disappears when your side nav disappears on smaller screens. You can also tweak the size of the padding left according to how big your side nav is.


text:
Q: SQL Round query Trying to round sales tax and subtotal to two decimal places for my query in SQL.
Here's my query.
    select OrderID
    , ItemID
    , '$' + cast(price as varchar (7)) as [Price]
    , (price) * 0.06 as [Sales Tax]
    , (price) * 0.06 + (price) as [Subtotal]

    from ORDER_ITEM
    where price >= (20)

Thanks

A: select OrderID
    , ItemID
    , '$' + cast(price as varchar (7)) as [Price]
    ,convert(decimal(18,2), (price) * 0.06) as [Sales Tax]
    , convert(decimal(18,2),(price) * 0.06 + (price)) as [Subtotal]

    from ORDER_ITEM
    where price >= (20)

A:    -- You Can Use ROUND Function to Round Up The Column you want.
       select OrderID
            , ItemID
            , '$' + cast(price as varchar (7)) as [Price]
            , ROUND((price) * 0.06,2) as [Sales Tax]
            , ROUND((price) * 0.06 + (price),2) as [Subtotal]

            from ORDER_ITEM
            where price >= (20)


text:
Q: setting html button to post back with confirm Hi I have a html button like so
<button type="button" runat="server" id="btnDelete" type="button" data-confirm-message="Deleting this page will permanently delete it from the system and it will not be recoverable. Are you sure you wish to continue?">delete</button>

Which generates this html
<button onclick="if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate(''); __doPostBack('ctl00$body$btnDelete','')" id="btnDelete" type="button"   data-confirm-message="Deleting this page will permanently delete it from the system and it will not be recoverable. Are you sure you wish to continue?">delete</button>

and some jQuery
$(document).ready(function () {

    $("#btnDelete").click(function () {
        return confirm($(this).data("confirm-message"));
    });

});

The issue is the page is posted back regardless of the confirm being true or false, any help woudl eb great

A: If you analyze your inline handler, you'll see that postback is performed every time the button is clicked trough __doPostBack('ctl00$body$btnDelete','')
if (typeof(Page_ClientValidate) == 'function')
    Page_ClientValidate('');

__doPostBack('ctl00$body$btnDelete','') // this line is always reached on click

It doesn't matter if you return false from your jQuery click handler as inline code is executed anyway.

A: As others have mentioned, you have an inline click handler with the onclick attribute which submits the form and will beat your jQuery click handler to it every time.
Try this:
$(document).ready(function () {

    $("#btnDelete").removeAttr("onclick").click(function () {
        return confirm($(this).data("confirm-message"));
    });

});

It removes the onclick attribute so it can handle the click itself.

A: In the end i removed the click event and re-attached after confirm is true
 $(".document-confirm-delete").each(function (index, item) {
        var clickEvents = this.onclick;
        this.onclick = null;
        $(this).on("click", function () {
            if (Document.ConfirmDelete(this)) {
                clickEvents();
            }
        });
    });

Thanks for all the help

A: I see you're using .NET. One way you can prevent the postback is by wiring up OnClientClick for an ASP Button/LinkButton/etc.
OnClientClick="return confirm('Your Message');"

A response of false will prevent a postback, and then you can include your postback code in the OnClick handler for true responses. Would something like that work?


text:
Q: why the image can't find in iphone simulator? I want to test a BarCode demo, But I haven't got an Iphone. so I must test the image of BarCode in the simulator.
I drag the image of BarCode on the simulator. And pressed the picture for a while and save it.
but I test the below code. I can't find any picture above.
ZBarReaderController *reader = [ZBarReaderController new];

reader.readerDelegate = self;

if([ZBarReaderController isSourceTypeAvailable:
    UIImagePickerControllerSourceTypeSavedPhotosAlbum])
    reader.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
[reader.scanner setSymbology: ZBAR_I25
                      config: ZBAR_CFG_ENABLE
                          to: 0];
[self presentModalViewController: reader
                        animated: YES];

I have dealt with the problem for a day, but I haven't been able to find why...
Hope I can solve it in the weekend.

A: This is a know issue with the simulator. I once made it work by saving images twice.

A: I had this numerous times. I believe the trick is to open the images app prior to saving the image. Then close it, switch to Safari and save the image.


text:
Q: Ftp camera pics to raspberry pi with usb stick I try to put the camera pictures (external ip camera) to a raspberry pi that I added to my network. The OS is Raspbian and I mounted a usb stick 16G for the pictures.
The problem is that I provided the camera the correct settings (check screenshot), but instead of putting the pictures on the usb stick, it just creates the path in my home folder. What do I forget? Thanks.
Some additional info:
Partial output of fdisk command:
Device     Boot Start      End  Sectors  Size Id Type
/dev/sda1  *     8064 31240703 31232640 14.9G  c W95 FAT32 (LBA)

Folder user, group and permissions:
drwxr-xr-x 3 pi pi 4096 Feb 21 14:28 FTP

A: Problem solved. A friend told me to create a new user/group for the ftp service and map the home dir of this new user to the usb stick. That's what I did and it works. I also 'chown' and 'chgrp' recursively the mounted map of the usb stick to the new user and group that I created. But this last action was only possible after formatting the usb stick in ext4 because it seems you can't change the owner and group of a stick formatted in FAT32.
Now,... the path is created in the correct place... but my snapshots are still not there though. I think that is another issue. Not related to this one. I'll look further why my pics are not coming through. If needed I'll open a new threath with more info.


text:
Q: My Custom Module API Data not saving in magento 2 I have created a custom module (Blog) which contains a save() method, it is executed but values are not saved and it returns an empty object.
<?php
namespace Learning\Blog\Model\Resource;
use Learning\Blog\Api\Data\BlogInterface;

class BlogRepository implements BlogRepositoryInterface
{

  protected $blogFactory;

public function __construct
    (
    \Learning\Blog\Model\BlogFactory $blogFactory
    ){
     $this->blogFactory = $blogFactory;
    }

public function save(BlogInterface $blog){

        $blog_Data = $this->blogFactory->create();
        $blog_Data->save();
        return $blog_Data;
    }
}

Did I miss anything?

A: Finally I have achieved to update.

class BlogRepository implements BlogRepositoryInterface
{

  protected $blogFactory;

   protected $blogBuilder;

  protected $extensibleDataObjectConverter;

public function __construct
    (
    \Magento\Framework\Api\ExtensibleDataObjectConverter $extensibleDataObjectConverter,
    \Learning\Blog\Model\BlogFactory $blogFactory
    ){
     $this->extensibleDataObjectConverter = $extensibleDataObjectConverter;
     $this->blogBuilder = $blogDataBuilder;
     $this->blogFactory = $blogFactory;
    }

public function save(BlogInterface $blog){

       $customerData = $this->extensibleDataObjectConverter->toNestedArray(
            $blog,
            [],
            '\Learning\Blog\Api\Data\BlogInterface'
        );

        $blog_Data = $this->blogFactory->create();
        $blog_Data->setData($customerData);
        $item = $blog_Data->save();
        return $item;
    }
}


text:
Q: How can I make this queryset more tolerable? I have the following class:
class Instance(models.Model):
    products = models.ManyToManyField(Product, blank=True)

class Product(models.Model):
    description = HTMLField(blank=True, null=True)
    short_description = HTMLField(blank=True, null=True)

And this form that I use to update Instances
class InstanceModelForm(InstanceValidatorMixin, UpdateInstanceLastUpdatedMixin, forms.ModelForm):
    class Meta:
        model = Instance
    products = forms.ModelMultipleChoiceField(required=False, queryset=Product.objects.annotate(i_count=Count('instance')).order_by('i_count'))

My instance-product table is sizable (~ 1000 rows) and ever since I've added the queryset for products I am seeing web requests that are timing out due heroku's 30 second request limit.
My goal is to do something to this queryset such that my users are no longer timing out.
I have the following insights:

*

*Accuracy doesn't matter as much to me - It doesn't have to be very accurate. Yes I would like to sort products by the count of instances this product has linked to but if it's off by 5 or 10 it doesn't really matter
that much.

*Limited number of products - When my users are selecting products to be linked to an instance, they are primarily interested in products with less than 10 total linkages to instances. I don't know if a partial query will be accurate, but if this is possible I am open to trying.

*Effort - I know there are frameworks out there that I can install to cache many things. I am looking for something that is light weight and requires less than 1 hr to get up and running.

A: First I would want to ensure that the performance issue actually comes from the query. I've tried to reproduce your problem:
>>> Instance.objects.count()
102499
>>> Product.objects.count()
1000
>>> sum(p.instance_set.count() for p in Product.objects.all())/Product.objects.count()
273.084
>>> list(Product.objects.annotate(i_count=Count('instance')).order_by('i_count'))
[...]
>>> from django.db import connection
>>> connection.queries[-1]
{'sql': 'SELECT "products_product"."id", "products_product"."description", "products_product"."short_description", COUNT("products_instance_products"."instance_id") AS "i_count" FROM "products_product" LEFT OUTER JOIN "products_instance_products" ON ("products_product"."id" = "products_instance_products"."product_id") GROUP BY "products_product"."id", "products_product"."description", "products_product"."short_description" ORDER BY "i_count" ASC', 'time': '0.189'}

By accident, I created a dataset that is probably quite a bit bigger than yours. As you can see, I have 1000 Products with an average of ~273 related Instances, but the query still takes less than a second (both on SQLite and PostgreSQL).
Use a one-off dyno with heroku run bash and check if you get the same numbers.
My guess is that your performance issues are either caused by

*

*an n+1 query, where an extra query is made for each Product, e.g. in your Product.__str__ method.

*the actual rendering of the MultipleChoiceField field. By default, it will render as a <select> with an <option> for each Product. This can be quite slow, and even it wasn't, it would pretty inconvenient to use. You might want to use a different widget, like django-select2.


text:
Q: Makefile: run binaries differently depending on their name I have this in my Makefile:
BINS = $(shell echo *.bin)

.PHONY: $(BINS)
run: $(BINS)

*.bin:
    ./$@

I run it as make -j 8
This way it looks for all files ending with .bin, and runs them in parallel using make's -j option (Makefile run processes in background)
I need to modify the makefile so that it runs all files of the type mpi*.bin as mpirun -np 2 ./mpi*.bin, and the remaining executable files as ./<filename>.bin
Thanks for your help.

A: Here is a simple example I used to test my answer:
touch {a,b,c,d}.bin mpi{a,b,c,d}.bin

to create some empty test files, and my Makefile based on yours:
BINS = $(shell echo *.bin)

.PHONY: $(BINS)
run: $(BINS)

*.bin:
    echo "bin file: " ./$@

mpi*.bin:
    echo "mpi file: " ./$@

It is key here that the rule for the prefixed files follows the non-prefixed rule.  If not, the prefixed rule will be overridden.
This seems to work for distinguishing between the prefixed and non-prefixed files, but gives the following output:
~/tmp$ make
Makefile:10: warning: overriding commands for target `mpia.bin'
Makefile:7: warning: ignoring old commands for target `mpia.bin'
Makefile:10: warning: overriding commands for target `mpib.bin'
Makefile:7: warning: ignoring old commands for target `mpib.bin'
Makefile:10: warning: overriding commands for target `mpic.bin'
Makefile:7: warning: ignoring old commands for target `mpic.bin'
Makefile:10: warning: overriding commands for target `mpid.bin'
Makefile:7: warning: ignoring old commands for target `mpid.bin'
echo "bin file: " ./a.bin
bin file:  ./a.bin
echo "bin file: " ./b.bin
bin file:  ./b.bin
echo "bin file: " ./c.bin
bin file:  ./c.bin
echo "bin file: " ./d.bin
bin file:  ./d.bin
echo "mpi file: " ./mpia.bin
mpi file:  ./mpia.bin
echo "mpi file: " ./mpib.bin
mpi file:  ./mpib.bin
echo "mpi file: " ./mpic.bin
mpi file:  ./mpic.bin
echo "mpi file: " ./mpid.bin
mpi file:  ./mpid.bin

I'm sure that there's a way to suppress those warnings or do it better, but this approach seems to work.


text:
Q: Make if statement neater, unsure how to create a neat loop JAVA programming   @Override
    int getDiscountRate(float priceThisYear, float priceLastYear) {
         float totalPrice;
        totalPrice = priceThisYear + priceLastYear;
        if (totalPrice >= 250 && totalPrice < 350) {
            return 5;
        } else if (totalPrice >= 350 && totalPrice < 450) {
            return 6;
        } else if (totalPrice >= 450 && totalPrice < 550) {
            return 7;
        } else if (totalPrice >= 550 && totalPrice < 650) {
            return 8;
        } else if (totalPrice >= 650 && totalPrice < 750) {
            return 9;
        } else if (totalPrice >= 750 && totalPrice < 850) {
            return 10;
        } else if (totalPrice >= 850 && totalPrice < 950) {
            return 11;
        } else if (totalPrice >= 950 && totalPrice < 1050) {
            return 12;
        } else if (totalPrice >= 1050 && totalPrice < 1150) {
            return 13;
        } else if (totalPrice >= 1150 && totalPrice < 1250) {
            return 14;
        } else if (totalPrice >= 1250 && totalPrice < 1350) {
            return 15;
        } else if (totalPrice >= 1350 && totalPrice < 1450) {
            return 16;
        } else if (totalPrice >= 1450 && totalPrice < 1550) {
            return 17;
        } else if (totalPrice >= 1550 && totalPrice < 1650) {
            return 18;
        } else if (totalPrice >= 1650 && totalPrice < 1750) {
            return 19;
        } else if (totalPrice >= 1750 && totalPrice < 1850) {
            return 20;
        }
        else if (totalPrice > 1850){
        return 20;
        }
          return 0;
    }

Trying to make the code look neater, preferably by decreasing the number of else ifs and maybe implementing some form of loop.
The idea is to have a discount rate which starts at 5 percent when the user has spent over $350 and then a further 1 percent with every $100 spent giving a maximum discount of 20 percent
I understand to experienced programmers this is most likely trivial. The program itself works but I know that can't be the best way to code it.

A: I'd suggest something like this:
if(totalPrice >= 350) {
  int baseDiscount = 5;
  int additionalDiscount = (totalPrice - 350) / 100;
  if(additionalDiscount > 15) additionalDiscount = 15;

  return baseDiscount + additionalDiscount;
}
return 0;

Then we simply follow what you said in words. 5 percent if above 350, then 1 percent additional for each 100$ above that. And I added the "max 20%" rule that you had in your code. :)
(haven't tested it)

A: Disclaimer I wrote this against the code (which gives a 5% discount for purchases 250 <= totalPrice < 350) and not the spec, which says the 5% should start at 350.
First, you are rechecking bounds; for example:
if (totalPrice >= 250 && totalPrice < 350) {
        return 5;
} else if (totalPrice >= 350 && totalPrice < 450) {

We know that, if we have not entered the first if, the amount must be >= 350 unless it is < 250. So if you checked that 250 condition first then you could certainly cut down on code:
if (totalPrice < 250) {
   return 0;
} else if (totalPrice < 350) {
   return 5;
} else if (totalPrice < 450) {
    return 6;

So, what are we actually doing here? We're looking for bounds, how about a Map<Integer, Integer> where we map minSpend -> discount. We would need to use a TreeMap to maintain order:
final Map<Integer, Integer> discounts = new TreeMap<>();
discounts.put(250, 5);
discounts.put(350, 6);
//and so on

In order to find the discount, we loop backwards over the Map and find the first key which is less than totalPrice:
for(final Entry<Integer, Integer> e : discounts.descendingMap().entrySet()) {
    if(e.geyKey() <= totalPrice) {
        return e.getValue();
    }
}
return 0;

This allows for a completely flexible bound to discount mapping. If you have some fixed rule, which you seem to, then you can simply describe it mathematically.
You have "5 at 250 then another 1 for each 100" which comes down to:
return totalPrice < 250 ? 0 : 5 + (totalPrice - 250)/100

A: Req: 5% at 350 spent, +1% per 100 after that
Step 1: Store the amt spent.
Step 2: Check the amt spent, and apply necessary discounts. I would use a subtraction/mod approach.
Step 3: return the discount percentage.
Implementation:
public static int discountPrice(int moneySpent) {
    int percentage = 0;

    // get out early if it's less than the needed amt
    if (moneySpent < 350) {
        return percentage;
    }
    // if at least 350 was spent
    if (moneySpent >= 350) {
        percentage += 5; // add 5 to the percentage
        moneySpent -= 350; // subtract 350 since we've already accounted for it
    }
    // while loop to calculate bonus percentage
    while (moneySpent >= 100) {
        percentage += 1; // add one to the percentage.
        moneySpent -= 100;
    }

    // return a max of 20
    if (percentage > 20) { percentage = 20; }
    return percentage;
}

Putting it in a function like this one makes it easy to change price - discount values. Base percentage can be modified easily in the second if block, as can the minimum money needed to be spent (first and second). Percentage increases per x price can also be easily modified in the last block.

A:
The idea is to have a discount rate which starts at 5 percent when the user has spent over $350 and then a further 1 percent with every $100 spent

You can just do something like this:
int spent = 500;
if(spent > 350){
   int discount = 5 + (spent-350)/100;
}

Might require some tweaking, but you get the basic idea. Also note that the code you posted does not agree with your above requirement.

A: If I saw correctly, it's the floor of (value - 250) / 75
Maybe try:
int minDiscount = 5;

if (totalPrice < 250) {
   return 0;
}

return Math.Floor((totalPrice - 250) / 75) + minDiscount;


text:
Q: Grau de complexidade def fRecursivo(n):
    if(n == 0 ):
        return 1
    if (n%2 ==1):
        return (n+3*fRecursivo(n-1))
    if(n%2 == 0 and n> 0):
        return (n+n+3*n*fRecursivo(n-1))

Qual o grau de complexidade do código para os números pares ? No caso quando for chamado a linha:
return (n+n+3*n*fRecursivo(n-1))

A: Se n é par e maior que zero, é feita a chamada recursiva para n - 1, que é ímpar e portanto cai no segundo if.
Ali é feita outra chamada recursiva para n - 1, que é par (podendo ou não ser maior que zero).
Ou seja, para qualquer n maior que zero são feitas n chamadas recursivas, até que se chegue a zero.
Portanto a complexidade é O(n).


text:
Q: Using docker pull & run to build dockerfile I'm learning how to use docker.
I want to deploy a microservice for swagger. I can do
docker pull schickling/swagger-ui
docker run -p 80:8080 -e API_URL=http://myapiurl/api.json swaggerapi/swagger-ui

To deploy it, I need a dockerfile i can run.
How do i generate the dockerfile in a way I can run it with docker build ?

A: Usually the docker pull pulls the Dockerfile. The Dockerfile for swagger is on the docker repo for it if you wanted to edit it or customize it.
 (https://hub.docker.com/r/schickling/swagger-ui/~/dockerfile/)
That one should work with the build command. The build command builds the image, the run command turns the image into a container. The docker pull command should pull the image in. You don't need to run docker build for it as you should already have the image from the pull. You only need to do docker run.

A: The original question asks for a Dockerfile, perhaps for some CI/CD workflow, so this answer addresses that requirement:
Create a very simple Dockerfile beginning with
FROM schickling/swagger-ui

Then from that directory run
$ docker build -t mycontainername .

Which can then be run:
$ docker run -p 80:8080 -e API_URL=http://myapiurl/api.json mycontainername


text:
Q: I have stored a regex in a variable that I initialized in a service .ts file, how can I use this variable on a formControl?  validationAR: any = "/^([0-9\s@,.=%$#&_\u0600-\u06FF])+$/";

Above is the variable I used to store the regex.

A: Say you have this common variable which you use it across the application, you create an appService in app.service.ts file and store this variable in it.
In the component where you want this variable, inject with appService using Dependency Injection there by having a single instance of appService.
In component.ts
    //.. some imports ..

    constructor(private appService: AppService) {}

    someFormControl: new FormControl(
        { value: null, disabled: false },
        {
            validators: [
            Validators.pattern(this.appService.myPattern)
         ]
        }
    )

This way you can use that variable in service file.

A: Suppose , you stored your regex in a service variable
*//.. some imports ..
@Injectable({
  providedIn: 'root'
})
export class DataService{
  validationRegEx = "/^([0-9\s@,.=%$#&_\u0600-\u06FF])+$/";
    constructor() {}
}*

Now, the component in which you want to use this regex just import the service in the component & you can access all the required service variables.
*
//.. some imports ..
@Component({
  selector: 'app-user-data',
  templateUrl: './user-data.component.html',
  styleUrls: ['./user-data.component.scss']
})
export class UserDataComponent implements OnInit {
constructor(private fb:FormBuilder,private dataService:DataService)
ngOnInit(): void {
this.userDetailsForm = this.fB.group({
      userMobile: ['',[Validators.pattern(this.dataService.validationRegEx )]]
})
}
}

*

*


text:
Q: Why is my nginx "rewrite" directive causing a redirection loop? Given the following http block, nginx performs as expected.  That is, it will rewrite a URL such as http://localhost/3ba48599-8be8-4326-8bd0-1ac6591c2041/ to http://localhost/modif/3ba48599-8be8-4326-8bd0-1ac6591c2041/ and pass it to the uwsgi server.
http {
    upstream frontend {
        server frontend:8000;
    }

    server {
        listen 8000;
        server_name localhost;

        root /www/;

        location ~* "^/([0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})/?$" {
            include uwsgi_params;
            set $uuid $1;
            if ($cookie_admin) {
              # if cookie exists, rewrite /<uuid> to /modif/<uuid> and pass to uwsgi
              rewrite / /modif/$uuid break;
              uwsgi_pass frontend;
            }
            content_by_lua_block {
                ngx.say("Ping!  You got here because you have no cookies!")
            }
        }
    }
}

However, when I add another location block in the manner displayed blow, things fall appart and I get ERR_TOO_MANY_REDIRECTS.
http {
    # access_log /dev/stdout;  # so we can `docker log` it.

    upstream frontend {
        server frontend:8000;
    }

    server {
        listen 8000;
        server_name localhost;

        root /www/;

        location / {  # THIS MAKES EVERYTHING FALL APART :(
            uwsgi_pass frontend;
            include uwsgi_params;
        }

        location ~* "^/([0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})/?$" {
            include uwsgi_params;
            set $uuid $1;
            if ($cookie_admin) {
              # if cookie exists, rewrite /<uuid> to /modif/<uuid> and pass to uwsgi
              rewrite / /modif/$uuid break;
              uwsgi_pass frontend;
            }
            content_by_lua_block {
                ngx.say("Ping!  You got here because you have no cookies!")
            }
        }
    }
}

What's going on here, exactly?  How can I fix this?

A: I see your Nginx is listening on port 8000, but your upstream server is at 'frontend', also on port 8000. If frontend resolves to the same server that Nginx is running on, then you've got a loop of proxy requests happening.


text:
Q: Что такое суррогатные пары? Что такое суррогатные пары?
Прочитал вот это, но все равно не понял.
И почему длина элемента равна 2, а цикл for of выводит только один элемент?

const str = "";

console.log(str.length); // 2

for(let key of str){
  console.log(key) //
}

A: Такие символы записываются двумя 16-битными словами, поэтому длина - 2.
Но символ-то один.
Можно здесь посмотреть информацию https://learn.javascript.ru/string


text:
Q: Wealthy man learns to astrally project from old book, travels to another planet and takes over a dying boy I'm searching for the title of a novel on 'astral projection' I read some years back.
It's about a wealthy man who learned astral projection from a long lost book. He then traveled to another planet where he was able to take over the body of a dying boy.
It's not the Palos trilogy.


text:
Q: Google Cloud Messaging (GCM) with local device groups on Android gives HTTP Error code 401 I am trying to get Google Cloud Messaging (GCM) to work on Android with local device groups as described on https://developers.google.com/cloud-messaging/android/client-device-group .
I have enabled the following services in the web console ( https://console.developers.google.com ):

*

*Google Cloud Messaging for Android

*Google Cloud Pub/Sub

*Google+ API

I have also created the following credentials:

*

*API key (with specified package name and SHA-1 certificate keyprint)

*OAuth 2.0 client IDs (Web application)

My Android code looks as follows (error handling etc. has been stripped):
String account = ACCOUNT_NAME; // E.g. "johndoe@google.com"
String scope = "audience:server:client_id:" + WEB_APPLICATION_CLIENT_ID;
String token = GoogleAuthUtil.getToken(context, account, scope);

// Token is successfully found here :-)

URL url = new URL("https://android.googleapis.com/gcm/notification");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("project_id", NUMERICAL_PROJECT_ID);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.connect();

JSONObject requestBody = new JSONObject();
requestBody.put("operation", "add");
requestBody.put("notification_key_name", "foobar");
requestBody.put("registration_ids",
  new JSONArray(Arrays.asList(new String[]{"42", "44"})));
requestBody.put("id_token", token);

OutputStream os = connection.getOutputStream();
os.write(requestBody.toString().getBytes("UTF-8"));
os.close();

// connection.getResponseCode() is now 401

The submitted JSON to https://android.googleapis.com/gcm/notification looks something like this:
{
  "operation": "add",
  "notification_key_name": "foobar",
  "registration_ids": ["42","44"],
  "id_token": "[veeeeeery long string]"
}

The response contents is:

<TITLE>Unauthorized</TITLE>

Unauthorized

Error 401

What am I doing wrong?

A: Found the trick: you are using a google account to take the id_token, you need to use EXACTLY the email as notification_key_name. So if you are using foo@gmail.com, you need to use this address as notification_key_name.

A: Here's the recap, based on the correct answer by greywolf82. The correct code should follow these principles (error handling etc. has been stripped):
///////////////////////////////////////////////////////////////////////////
// Working example on how to create a locally (client-side) managed      //
// device group for Google Cloud Messaging.                              //
//                                                                       //
// Thanks to greywolf82 for adding the final piece.                      //
// Please vote on his answer. Thank you!                                 //
///////////////////////////////////////////////////////////////////////////

// Get token:
String account = ACCOUNT_NAME; // E.g. "johndoe@gmail.com"
String scope = "audience:server:client_id:" + WEB_APPLICATION_CLIENT_ID;
String idToken = GoogleAuthUtil.getToken(context, account, scope);

// Get registration id:
InstanceID instanceID = InstanceID.getInstance(this);
String registration_id = instanceID.getToken(
        getString(R.string.gcm_defaultSenderId),
        GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);

// Set up HTTP connection:
URL url = new URL("https://android.googleapis.com/gcm/googlenotification");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("project_id", NUMERICAL_PROJECT_ID);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.connect();

JSONObject requestBody = new JSONObject();
requestBody.put("operation", "add");
requestBody.put("notification_key_name", ACCOUNT_NAME); // You *must* use the email!
requestBody.put("registration_ids",
    new JSONArray(Arrays.asList(new String[]{registration_id})));
requestBody.put("id_token", idToken);

// Submit request body
OutputStream os = connection.getOutputStream();
os.write(requestBody.toString().getBytes("UTF-8"));
os.close();

// connection.getResponseCode() is now 200  :-)
// Now read the server response contents from connection.getInputStream()

The submitted JSON to https://android.googleapis.com/gcm/notification looks something like this:
{
  "operation": "add",
  "notification_key_name": "johndoe@gmail.com",
  "registration_ids": ["very long string here"],
  "id_token": "another very long string"
}

The response contents is:
{
  "notification_key": "your notification key is here --- voilá!"
}

A: This is how it is done using the SERVER_API_KEY (not best practice, but the best I have arrived at yet):
First, get an application instance id:
InstanceID instanceID = InstanceID.getInstance(this);
String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
    GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);

// Variable "token" now has the instance id. :-)

Next, get the messaging id token:
String account = ACCOUNT_NAME; // E.g. "johndoe@google.com"
String scope = "audience:server:client_id:" + WEB_APPLICATION_CLIENT_ID;
String idToken = GoogleAuthUtil.getToken(context, account, scope);

// Variable "idToken" now hods the messaging id token. :-)

Now to the magic part. Create a new device group with the instance Id as a member:
URL url = new URL("https://gcm-http.googleapis.com/gcm/notification"); // <-- Use this URL!
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Authorization", "key=" + SERVER_API_KEY); // <--- Auth!
connection.setRequestProperty("project_id", NUMERICAL_PROJECT_ID);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.connect();

JSONObject requestBody = new JSONObject();
requestBody.put("operation", "create");               // <--- Not "add"
requestBody.put("notification_key_name", "foobar");
requestBody.put("registration_ids",
    new JSONArray(Arrays.asList(new String[]{token}))); // <--- Instance Id token here!
requestBody.put("id_token", idToken);

OutputStream os = connection.getOutputStream();
os.write(requestBody.toString().getBytes("UTF-8"));
os.close();

InputStream is = connection.getInputStream();
String responseString = new Scanner(is, "UTF-8").useDelimiter("\\A").next();
is.close();

JSONObject response = new JSONObject(responseString);
Log.d(TAG, "Server response:\n" + response.toString(4));
String notificationKey = response.getString("notification_key");

At this point, the variable "notificationKey" holds the notification key which is the recipient that must be used when sending messages to this device group.
Send a message like this (use the "notificationKey" value as parameter as receipient from above):
private void sendMessage(String recipient) throws IOException, JSONException {

    Log.i(TAG, "Sending message to: " + recipient);
    URL url = new URL("https://gcm-http.googleapis.com/gcm/send");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setDoInput(true);

    Log.d(TAG, "Opening connection to " + url.toString());

    connection.setRequestProperty("Authorization", "key=" + SERVER_API_KEY);
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setRequestProperty("Accept", "application/json");
    connection.connect();

    JSONObject requestBody = new JSONObject();
    requestBody.put("to", recipient);
    JSONObject requestData = new JSONObject();
    requestData.put("hello", "Hello World!");
    requestData.put("hellodata", "42");
    requestBody.put("data", requestData);

    Log.d(TAG, "Request body:\n" + requestBody.toString(4));

    OutputStream os = connection.getOutputStream();
    os.write(requestBody.toString().getBytes("UTF-8"));
    os.close();

    Log.d(TAG, "Response code: " + connection.getResponseCode());

    InputStream is = connection.getInputStream();
    String responseString = new Scanner(is, "UTF-8").useDelimiter("\\A").next();
    is.close();
}

I have not succeeded in doing this without using the server API key. It might be worthwhile to investigate with different Authorization header values on the https://http.googleapis.com/gcm/googlenotification endpoint.
Hopefully this makes sense. Have fun. :-)


text:
Q: Creating depandant Select Input in Shiny R I am new in R trying to accomplish following functionality in r
I created a data frame book3
Region<- c("Americas", "Asia Pacific","Asia Pacific", "EMEA", "EMEA")

Country<- c("Mexico", "China","India", "Germany", "Spain" )

Rating<- c(5,3,3,2,4)

book3<- data.frame(Region, Country, Rating)

I want to pull Region and country which will be defendant. I am trying using this code
ui.R
library(shiny)
shinyUI(fluidPage(
titlePanel("Test Dashboard "),
sidebarLayout(
sidebarPanel(
selectInput("data1", "Select Region", choices = c(book3$Region)),

  selectInput("data2", "select country", choices = c(book3$Country))
   ),
mainPanel()

 )))

A: If you're creating an input based on data, you need to create the input in the server.R so you can access the data. You do this by usng renderUI and uiOutput. See here for reference
Here's a working example. Notice the renderUI( ) functions in the server that generate the selectInput based on the data
library(shiny)

ui <- fluidPage(
titlePanel("Test Dashboard "),
    sidebarLayout(
        sidebarPanel(
            uiOutput("data1"),   ## uiOutput - gets the UI from the server
            uiOutput("data2")
        ),
mainPanel()
))

server <- function(input, output){

    Region<- c("Americas", "Asia Pacific","Asia Pacific", "EMEA", "EMEA")
    Country<- c("Mexico", "China","India", "Germany", "Spain" )
    Rating<- c(5,3,3,2,4)
    book3<- data.frame(Region, Country, Rating, stringsAsFactors = F)

    ## renderUI - renders a UI element on the server
    ## used when the UI element is dynamic/dependant on data
    output$data1 <- renderUI({
        selectInput("data1", "Select Region", choices = c(book3$Region))
    })

    ## input dependant on the choices in `data1`
    output$data2 <- renderUI({
        selectInput("data2", "select country", choices = c(book3$Country[book3$Region == input$data1]))
    })

}

shinyApp(ui, server)

A: You can use the updateSelectInput function in the server code, in order to update the choices (and the selected option) of your selectInput fields:
server <- function(input, output, session) {
    updateSelectInput(session, "data1", "Select Region", choices = c(book3$Region))
}


text:
Q: SQL query to select people interviewed more than once in a year first of all this query will be done in access, I'm trying to find details of people who have been interviewed more than once in a specific year.
It needs to be multi tabled, to both sort out people who have been interviewed more than once in 2013, and the details of those people.
Example
Tables are as follows:

Interview
| ID | InterviewDate |
| 123|  13-12-04 |
  | 789|  14-01-10|
  | 123|  13-12-21 |
Person
| ID | NAME | NUMBER | LOCATION |
| 123|  John| 128231 | USA
  | 789|  Max | 123556 | Europe

So the list is a bit larger, but ideally I want to be able to make a query that will count whose had an interview more than once in 2013 and their details from another table.
I have this query which apparently works but I'm sure there's a better way to show it as this may have some flaws.
SELECT P.ID, Name, Number, Location, COUNT(year(InterviewDate) AS InterviewNo, Year(InterviewDate) AS Year
FROM Person AS P INNERJOIN Interview as I ON P.ID = I.ID
GROUP BY P.ID, Name, Number, Location, Year(InteviewDate)
HAVING COUNT(Year(InterviewDate)) > 1 AND Year(InterviewDate)='2013'

I feel like the year(InterviewDate) is all wrong, would I be able to get the same result without using that exact phrase? Maybe using a sub-query.
Thank you.

A: My access syntax is probably a little off, but I think you are asking fro something like:
SELECT P.ID
      ,Name
      ,Number
      ,Location
      ,InterviewNo
  FROM Person P
       INNER JOIN
       (SELECT ID
              ,COUNT(1) AS InterviewNo
          FROM Interview
         WHERE Year(InterviewDate) = 2013
         GROUP BY ID
        HAVING COUNT(1)> 1) I ON P.ID=I.ID


text:
Q: Zipkin tracing not working for docker-compose and Dapr Traces that should have been sent by dapr runtime to zipkin server somehow fails to reach it.
The situation is the following:
I'm using Docker Desktop on my Windows PC. I have downloaded the sample from dapr repository (https://github.com/dapr/samples/tree/master/hello-docker-compose) which runs perfectly out of the box with docker-compose up.
Then I've added Zipkin support as per dapr documentation:

*

*added this service in the bottom of docker-compose.yml

  zipkin:
    image: "openzipkin/zipkin"
    ports:
      - "9411:9411"
    networks:
      - hello-dapr

*added config.yaml in components folder

apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
  name: daprsystem
spec:
  mtls:
    enabled: false
  tracing:
    enabled: true
    exporterType: zipkin
    samplingRate: "1"
    expandParams: true
    includeBody: true
    zipkin:
      endpointAddress: "http://zipkin:9411/api/v2/spans"

When application runs, it should send traces to the server, but nothing is found in zipkin UI and logs.
Strange thing start to appear in the logs from nodeapp-dapr_1 service: error while reading spiffe id from client cert
pythonapp-dapr_1  | time="2021-03-15T19:14:17.9654602Z" level=debug msg="found mDNS IPv4 address in cache: 172.19.0.7:34549" app_id=pythonapp instance=ce32220407e2 scope=dapr.contrib type=log ver=edge
nodeapp-dapr_1    | time="2021-03-15T19:14:17.9661792Z" level=debug msg="error while reading spiffe id from client cert: unable to retrieve peer auth info. applying default global policy action" app_id=nodeapp instance=773c486b5aac scope=dapr.runtime.grpc.api type=log ver=edge
nodeapp_1         | Got a new order! Order ID: 947
nodeapp_1         | Successfully persisted state.

Additional info - current dapr version used is 1.0.1. I made sure that security (mtls) is disabled in config file.

A: Configuration file is supposed to be in different folder then components.

*

*Create new folder e.g. dapr next to the components folder.

*Move components folder into newly created dapr folder.

*Then create config.yaml in dapr folder.

*Update docker-compose accordingly.

docker-compose
services:
  nodeapp-dapr:
    image: "daprio/daprd:edge"
    command: ["./daprd",
     "-app-id", "nodeapp",
     "-app-port", "3000",
     "-placement-host-address", "placement:50006",
     "-dapr-grpc-port", "50002",
     "-components-path", "/dapr/components",
     "-config", "/dapr/config.yaml"]
    volumes:
      - "./dapr/components/:/dapr"
    depends_on:
      - nodeapp
    network_mode: "service:nodeapp"

config.yaml
apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
  name: daprConfig
spec:
  mtls:
    enabled: false
  tracing:
    enabled: true
    samplingRate: "1"
    expandParams: true
    includeBody: true
    zipkin:
      endpointAddress: http://host.docker.internal:9411/api/v2/spans

I had issue with localhost and 127.0.0.1 in URL which I resolved using  host.docker.internal as hostname.

PS: Don't forget to kill all *-dapr_1 containers so it can load new configuration.


text:
Q: How to get index numbers of array in PHP using foreach? I'm trying to parse data from an TV Shows API, but I'm having trouble figuring out how to get the index numbers.
Example:
{
"data": {
    "0": {
        "1": {
            "param1": "value1",
            "param2": "warning",
        }
    },
    "1": {
        "1": {
            "param1": "value1",
            "param2": "value2",
        },
        "2": {
            "param1": "value1",
            "param2": "warning",
        },
        "3": {
            "param1": "value1",
            "param2": "warning",
        },
    }
}
}

The "params" and "values" I'm able to get just fine, but I can't 'echo' the index numbers.
This is how I'm trying to do it:
$string = file_get_contents(api);
$json_a = json_decode($string, true);
foreach ($json_a['data'] as $seasons) {
    foreach ($seasons as $episodes) {
            if ($episodes['param2']=="warning") {
            // echo index number of season
            // echo index number of episode

            }
    }
}

I believe I've read that using foreach I'm not able to get the index numbers? If so, what would be the solution?
I tried 'manually' incrementing variables for season number and episodes, but index numbers may vary. They may not be sequential and some start with index "1" instead of "0".

A: Use foreach (array_expression as $key => $value) instead of just foreach (array_expression as $value). The $key is what you're missing.
PHP: foreach

A: You don't need a counter, just add the key in your definition of the foreach
eg.
$test = array('foo' => 'bar');

foreach($test as $key => $value) {
    echo $key . "\n";
    echo $value;
}

Outputs
foo
bar

http://php.net/manual/en/control-structures.foreach.php

A: Try this:
foreach ($json_a['data'] as $index1 => $seasons) {}

and similarly:
foreach ($seasons as $index2 => $episodes) {}

A: i couldnt encode your json but,
used an array like:
array
  0 =>
    array
      1 =>
        array
          'param1' => string 'value1' (length=6)
          'param2' => string 'warning' (length=7)
  1 =>
    array
      1 =>
        array
          'param1' => string 'value1' (length=6)
          'param2' => string 'warning' (length=7)
      2 =>
        array
          'param1' => string 'value1' (length=6)
          'param2' => string 'value2' (length=6)

and here is the code:
$a[0][1] = array("param1"=>"value1","param2"=>"warning");
$a[1][1] = array("param1"=>"value1","param2"=>"warning");
$a[1][2] = array("param1"=>"value1","param2"=>"value2");

foreach($a as $key=>$val)
{
    foreach($val as $skey => $sval)
    {
        if($sval['param2']=="warning")
            echo $key."-".$skey."<br>";
    }
}


text:
Q: How to go to an activty at a specific time using Broadcast receiver? When I set a time,how to start an activity or do some actions like button click actions(not toast) at that specific time using broadcast receiver??

A: You might need Handler;
Intent intent;
Handler handler;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    intent = new Intent(this, ChildActivity.class);
    handler = new Handler();

    setContentView(R.layout.activity_streaming_client_example);

}

and to make it run at specific time use handler.postAtTime
handler.postAtTime(new Runnable() {
@Override
public void run() {
        MotherActivity.this.startActivityForResult(intent, 0);
    }
}, millisecond_toStartfromUpTime);

if you want to post after some seconds, use handler.postDelayed
handler.postDelayed(new Runnable() {
@Override
public void run() {
        MotherActivity.this.startActivityForResult(intent, 0);
    }
}, millisecond_delayhere);

A: You might need AlarmManager + Service to do that.
you can look it here
http://android-er.blogspot.com/2010/10/simple-example-of-alarm-service-using.html
and in Service class (in the link) that display Toast,
just make some new intent and startActivity(intent) there
PS. before start. It's important that you must add this line also
youintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

like this
public class AlarmService extends Service {

private Intent alarmIntent;

@Override
public void onCreate() {
    alarmIntent = new Intent(this, AlarmActivity.class);
    alarmIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}

@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);

    //Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG)
    //      .show();

    startActivity(alarmIntent);
}

// another implement method......
}


text:
Q: How to make Telescope ignore files inside node_modules? I'm new in the VIM / NEOVIM world so I probably am doing something else wrong, but from the docs it says that Telescope will ignore all the files registered in the .gitignore file, which is definitively there but it still searches in node_modules
So this is what I do:

*

*I cd into my project folder

*Hit nvim

*hit <leader>ff

*Telescope opens and I start typing, but searches are really slow because they are including node_modules
These are the plugins that I have for setting up telescope
" Telescope
Plug 'nvim:solua/popup.nvim'
Plug 'nvim-lua/plenary.nvim'
Plug 'nvim-telescope/telescope.nvim'

And then my remaps right from the docs:
" Find files using Telescope command-line sugar.
nnoremap <leader>ff <cmd>Telescope find_files<cr>
nnoremap <leader>fg <cmd>Telescope live_grep<cr>
nnoremap <leader>fb <cmd>Telescope buffers<cr>
nnoremap <leader>fh <cmd>Telescope help_tags<cr>

All this is running in a WSL terminal with Ubuntu. What am I missing?

A: Install BurntSushi/ripgrep
See telescope readme under Suggested dependencies
Then put node_modules in your .gitignore and your good to go.

A: Just add
require('telescope').setup{  defaults = { file_ignore_patterns = { "node_modules" }} }
to your init.lua

A: You need some customization for rg:
--ignore-file <PATH>...
    Specifies a path to one or more .gitignore format rules files. These patterns
    are applied after the patterns found in .gitignore and .ignore are applied
    and are matched relative to the current working directory. Multiple additional
    ignore files can be specified by using the --ignore-file flag several times.
    When specifying multiple ignore files, earlier files have lower precedence
    than later files.

Add to config for nvim:
require('telescope').setup{
  defaults = {
    vimgrep_arguments = {
      'rg',
      '--color=never',
      '--no-heading',
      '--with-filename',
      '--line-number',
      '--column',
      '--smart-case',
      '--ignore-file',
      '.gitignore'
    },


text:
Q: Decrease the number of calls I have arraylist of filenames (java) and I want to delete these files using rm
  for(String check: checks){
here I am removing each file using rm
 }

but it is time consuming can I do batching using xargs or something else which can help to delete files faster.

A: Don't use rm.  Use Java.
As others have pointed out, spawning a process is much slower than doing it in your program.  Also, it's just bad design to use a system command for something that can be done in code.
And finally, by using Files.delete, you gain platform independence.  Your code is now write once, run anywhere!
Here's what your loop would look like:
for (String check : checks) {
    Files.delete(Path.of(check));
}

This is essentially the same as what rm would do anyway.


text:
Q: Latex .tex file input highlighted, listed, code I have the latex document:
\begin{document}

Document introduction.

\onecolumn
\section*{That's how the code looks like}

\begin{algorithm}

\input{z.tex}

\begin{algorithm}

\end{document}

And I wanted to make that z.tex (tex file is exported from program Mathematica) will looks like this:
I think that "listing" won't work and I have to use "algorithm" but I don't know how. The tex in file after appropriate formatting looks like this:

Thank you for your help.

A: I have tried to solve Your problem using \usepackage{listings}, soI have created file named z.tex and as a result everything working fine:

\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}

\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codepurple}{rgb}{0.58,0,0.82}
\definecolor{backcolour}{rgb}{0.95,0.95,0.92}

\lstdefinestyle{mystyle}{
    backgroundcolor=\color{backcolour},
    commentstyle=\color{codegreen},
    keywordstyle=\color{magenta},
    numberstyle=\tiny\color{codegray},
    stringstyle=\color{codepurple},
    basicstyle=\ttfamily\footnotesize,
    breakatwhitespace=false,
    breaklines=true,
    captionpos=b,
    keepspaces=true,
    numbers=left,
    numbersep=5pt,
    showspaces=false,
    showstringspaces=false,
    showtabs=false,
    tabsize=2
}

\lstset{style=mystyle}

\begin{document}
The next code will be directly imported from a file

\lstinputlisting[language=tex]{z.tex}

\end{document}


text:
Q: CSS - how to style a footer is there a way to style a footer, so when there is a content (more than the height of the browser) it will be at bottom of the page(hidden), but if there is not enough content it will stick at bottom edge of the browser?

A: One solution I use requires a known height of your footer.
Fiddles:
A lot of content
A little content
Here's the HTML:
<main>
  hello
</main>
<footer>
  i am the footer
</footer>

And here's the CSS:
html, body {
    height: 100%;
}
main {
    min-height: 100%;
    margin-bottom: -100px;
    background: #ddd;
}
main:after {
    content: "";
    display: block;
    height: 100px;
}
footer {
    height: 100px;
    background: #eee;
}

The trick is to set the main part of your document to have a min-height of 100%. This element must contain everything else on your page. In my example, I used the main element for this.
Next, give this element a negative margin equal to the height of the footer. This moves it up just enough to leave room for the footer there at the bottom.
The last piece of the puzzle is the after element. This is required to fill the space of that negative margin. Otherwise, the content of the main will overflow into the footer.

A: I can only recommend to read this.
Show footer if at bottom of page or page is short else hide
or this
http://css-tricks.com/snippets/css/fixed-footer/

A: You can always use the calc function in CSS to make out the difference in between the footer and the body height.
footer {
 height: calc(100vh - 100px);

}
for example...


text: Q: Callback functions in client dll of Citrix virtual channel are not called I have the following problem: I've created client DLL with all needed callback functions (DriverOpen, DriverClose etc.). But they are not called, and I, actually, don't know why. Test dll vdping is working fine. May be the thing is I use VS2010 to build that DLL? Or should I use any specific compiler or link flags?


text:
Q: How to switch from CLI to GUI Ubuntu I am currently running Ubuntu 16.04 operating system. In order to experiment, I had asked for the way to login to Ubuntu CLI mode only (i.e. the GUI version must not start at all). In response to my question, I was suggested something like
sudo systemctl start lightdm.services

when I entered this command and restarted the system, it indeed worked and I was given a command line interface to login (No GUI element whatsoever; even the browser was not opening when I typed firefox www.google.co.in).
Now, I want to go back to the GUI version again.
I typed the following command
sudo systemctl stop lightdm.services

and then restarted the system. The OS still opens in the CLI mode only. Is there anything wrong with my commands?
Kindly guide me.

A: The commands you mentioned have effect only on the current boot. The stop one can temporarly disable your GUI, but at the next reboot you'll be back to the graphical interface. I assume you meant sudo systemctl disable lightdm and systemctl enable lightdm, that would respectively disable and enable your GUI (thus were a solution to your previous problem)
As you probably were trying different solutions for your previous problem, i suggest executing the following commands in sequence:

*

*sudo systemctl unmask lightdm (if you mask lightdm, it won't start even if you enable it)

*sudo systemctl enable lightdm (if you enable it, you'll still have to boot in "graphical.target" mode to have GUI)

*sudo systemctl set-default graphical.target
Then sudo reboot to restart your machine, and you should be back to your GUI.

A: sudo systemctl set-default graphical.target Then sudo reboot to restart your machine. Works fine on my system, I am redirected to my GUI immediately after rebooting.

A: sudo systemctl start lightdm.service should start the display manager lightdm. A display manager is the screen that prompts you to enter the username and password of a user, so you can log in to the system. On Ubuntu, it is enabled by default, i.e. it starts on boot.
That command shouldn't make you enter tty (i.e. CLI mode). If you want to go into tty, you can just run sudo systemctl stop lightdm.service but the easiest way is to press Ctrl + Alt + one of the function keys (e.g. F3 for tty3).
Since lightdm.service is probably enabled, you should boot into it whenever you boot up he OS. If it's disabled for some reason, try enabling it with sudo systemctl enable lightdm.service and then either start it with sudo systemctl start lightdm.service or just reboot.


text:
Q: CSS/HTML using a radio button to activate hyperlink Building a site that uses multiple radio buttons that control multiple content divs sliding on and off the screen. Would like the buttons to also activate a new html loaded into the iframe that i use as a background screen.
Reason for this is i have video playing in the iframe to start and would like to replace it with a simple background html doc when some content comes onto the screen. I can make the label for the radio buttons a hyperlink but this requires 2 clicks 1 on the label and 1 on the button.
CSS Section
#iframe_Back   {
position:fixed;
top: 0;
left: 0;
height:100%;
width:100%;
z-index:-1;
}

html,body {
height:100%;
width:100%;
overflow:hidden;
}

input {
position:absolute;
left:-9999px;
top:-9999px;
}

label {
cursor:pointer;
display:block;
-webkit-appearance:none;
-moz-appearance:none;
appearance:none;
width:100px;
margin-bottom:10px;
height:20px;
background-color:#ccc;
Border:2px solid black;
border-radius:20px;
}

.slider {
position:absolute;
width:400px;
height:100%;
top:0;
right:-400px;
background-color:#ccc;
-webkit-transition: all 0.5s;
-moz-transition: all 0.5s;
-ms-transition: all 0.5s;
-o-transition: all 0.5s;
transition: all 0.5s;
}

.slider_two {
top:100%;
left:0;
right:0;
width:100%;
}

.slider_three {
top:-100%;
left:20%;
right:0;
width:50%;
}

#one:not(:checked) ~ .slider_two ~ .slider_three, #two:not(:checked) ~ .slider_one ~ .slider_three, #three:not(:checked) ~ .slider_one ~ .slider_two {
-webkit-transition-delay:0.2s;
-moz-transition-delay:0.2s;
transition-delay:0.2s;
}

#one:checked ~ .slider_one {
right:0;
}

#two:checked ~ .slider_two {
top:20%;
}

#three:checked ~ .slider_three {
top:0%;
}

HTML Section

<input type="radio" name="slider" id="one">
<input type="radio" name="slider" id="two">
<input type="radio" name="slider" id="three">

slider one
slider two
slider three

one

two

three

Looking for a CSS/HTML solution not Jscript
Thanks


text:
Q: errors not shown in Firebug console with dojo/when promise Newbie to Dojo. I don't understand why js errors are not written to the firebug console when happening in the resolved promise handler of the dojo/when function. With synchronous code, errors are written. However when the error happens, the erroneous line is shown in the Firebug script view. I'm using Dojo 1.8 FF 19.0 and Firebug 1.11.2.

A: there has to be a try catch block somewhere along the code, that prevents dojo/when to throw errors.
You can add that functionality by adding a try catch block by yourself, check out this jsfiddle:
http://jsfiddle.net/kYMKF/1/
    try{
        should.bombAndLogAnErrorInFirebug(); //this does not log an error in Firebug! Why?
    } catch(e) {
            alert("error");
        }


text:
Q: ghc/flymake hangs on preprocessor directives I'm using flymake(-ghc) on emacs (prelude setup, before anybody wonders, no extra configuration) for a yesod project which has some #if's here and there by default. All good apart from the fact that flymake shows this error:
/path/to/Import.hs:18:2:
    lexical error at character 'i'

and the line is precisely
#if __GLASGOW_HASKELL__ >= 704

so, exactly the same behaviour as ghci:
Prelude> #if something

<interactive>:2:2: lexical error at character 'i'

is there anything I'm missing here?
bonus: auto-complete doesn't work either (emacs, prelude, default setup etc.): it works for other things (e.g. R).

A: I presume this flymake-ghc thing does not enable the C preprocessor while checking.  To fix it, add the following to the top of affected Haskell files::
{-# LANGUAGE CPP #-}

This pragma enables the preprocessor for the containing file.
Generally, that's actually the preferred way to enable Haskell language options and extensions, because this way they are confined to files that actually require them.


text:
Q: How to calculate parasitic capacitance in a trace? I am given the equation for parasitic-capacitance as:
\$ C = \dfrac{\epsilon_r \cdot \epsilon_0 \cdot L \cdot W }{ d }\$
I am also told my trace is to be 1000 micrometers long (1mm) and 45nm wide. The spacing between traces is 45nm as well (and the thickness of the metal layer is 45nm). A second coplanar trace is 100 micrometers long (.1mm).
I am not sure what I am plugging into the equation. I understand that the adjacent trace will distort the signal on my original trace with noise, especially at high power or high frequency, which I assume is the point, but I need to calculate the actual capacitance. I don't mind doing the math, but I need to know what goes where in the equation.

A: Your equation:
\$ C = \frac{e_oe_rLW}{d}  \$
Is the parallel plate capacitance equation and assumes that the plate size L*W is large enough and the gap size d is small enough that most of the e-field is captured between the plates.  With your system, most of the capacitance will be in the field lines around the wires so the result will not be accurate.
Usually this would be simulated with software but as a first approximation you should use the capacitance of a two wire line.  This will be some what inaccurate because teh conductors are a significant size wrt to the spacing.  But it will be better.
\$ C = \frac{2 \pi e_r e_o L}{2 ln(2h/b)} \$
where h = 1/2 the distance between wires and b = the "radius" of the wires.
In your case the wires will not be circular (but they are not square either).  but this is a good first approx..
Some open source software, that is kind of hard to use if you don't have the right tools is found by a search of "fast field solvers"

A: An estimate of what the value could be:
parasitic capacitance, I found this at TI site: "http://www.ti.com/lit/an/sloa013a/sloa013a.pdf"
"Circuit traces on a PCB with a ground and power plane will have about 1−3 pF/in and interconnecting wires have about 20−30 pF/ft conductor to shield or ground".

A: As others have noted, it can be quite hard to approximate capacitance from physical layouts due to fringing effects.
This answer: adjacent trace capacitance (horizontal) provides a formula for strips of equal length, but since one of your strips is a factor 10 longer than the other strip, it will be a poor approximation in your case.
I have developed a tool to simplify calculation of capacitance for multilayer PCBs: http://www.capext.com
The software, CapExt, is commercial, but I am more than happy to provide free evaluation licenses.

A: Some better approximation of two wires:
http://www.pulsedpower.eu/toolbox/toolbox_capacitances.html#capacitances


text:
Q: How can I pass data back from my XAML to my binding source? I've XAML that looks a bit like this:
<UserControl x:Class="MyNamespace.MyClass"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:MyNamespace"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="500">

<UserControl.Resources>
    <local:MyViewModel x:Key="ViewModel"/>
</UserControl.Resources>

<UserControl.DataContext>
    <Binding Source="{StaticResource ViewModel}"/>
</UserControl.DataContext>

    <DataGrid Name="_myGrid" AutoGenerateColumns="False"
   ItemsSource="{Binding Path=MyDataTable}">
   <DataGrid.Columns>
            <DataGridTemplateColumn Header="Name">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <StackPanel>
                            <TextBlock Text="{Binding Path=name}" />
                            <TextBlock Text="{Binding
                                Source={StaticResource ViewModel}, Path=IsValidName}"/>
                        </StackPanel>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
                <DataGridTemplateColumn.CellEditingTemplate>
                    <DataTemplate>
                        <Grid FocusManager.FocusedElement="{Binding ElementName=NameTextBox}">
                            <TextBox Name="NameTextBox" Text="{Binding Path=name}" />
                        </Grid>
                    </DataTemplate>
                </DataGridTemplateColumn.CellEditingTemplate>
            </DataGridTemplateColumn>

        </DataGrid.Columns>
    </DataGrid>

As you can probably see above, my DataGrid binds to a data table as its ItemsSource.  I typically bind to columns in the data table view, such as 'name'.  In some cases, I bind to my view model, rather than a DataRowView.  That can be seen in the 2nd TextBlock above, where I bind to the view model's IsValidName property.  My question is, how can I pass information from my XAML back to my binding source, in this case my view model?  I'd like to pass the rowIndex, DataRowView object, name, or something similar so that the IsValidName property on the view model would have context as to which row is being validated.
Thanks,
Notre

A: Looks like you want to call your IsValidName Property like a Method passing Parameters as to which row is being validated.
if you have control over each row's Type, implement the IsValidName Property there, completely avoiding the StaticResource Binding!


text:
Q: Java Rotate Image Lost Quality I have this function for rotating images.Although i am loosing quality.Any there any change which can improve it ?
 public BufferedImage RotateImage(String imagePath,int degrees) throws IOException{
         File file = new File(imagePath);
         Image image = ImageIO.read(file);
         BufferedImage img=bufferImage(image, BufferedImage.TYPE_INT_RGB);

         AffineTransform tx = new AffineTransform();
         double radians = (Math.PI / 180) * degrees;

         double width = img.getWidth()/2;
         double height = img.getHeight()/2;

         if(degrees != 180){
             tx.translate(height,width);
             tx.rotate(radians);
             tx.translate(-width,-height);
         }else{
         tx.rotate(radians,width, height);
         }

         AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
         img = op.filter(img, null);
         return img;
         }

A: Try using bicubic or bilinear.  Link shows an example of each.
AffineTransformOp op =
    new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);

A: The AffineTransform filtering parameter several others mentioned is important, but it also depends on the encoding your images come in. If it's JPEG, lossless rotation isn't universally possible.

A: AffineTransformOp.TYPE_NEAREST_NEIGHBOR will always make everything look like blergh. Try using AffineTransformOp.TYPE_BILINEAR or AffineTransformOp.TYPE_BICUBIC.

A: Try using either
TYPE_BICUBIC
or
TYPE_BILINEAR