text:
Q: Maven WAR plugin and how to manage dependencies Okay, this may well be a familiar question, however I still remain confused and I'm struggling to find an answer that really clarifies the details.
The scenario
I have several Maven projects, the majority create JAR artefacts and one is responsible for creating the WAR artefact. The WAR artefact has dependencies on the JAR artefacts with a scope of compile, in order that these JARs are included within the WEB-INF/lib folder.
The confusion
I'm still unclear how this plugin responds to scopes as to which dependencies and transitive dependencies get included within the WARs lib folder. My understand is that compile will result in a JAR being included along with its dependencies that are also declared with a compile scope (and so on recursively), but the buck stops with provided. A dependency with the provided scope will not get included.
The issue
To take a specific example, the WAR project war-a has a dependency on an internal JAR project jar-a with a scope of compile. jar-a will be included with the WARs lib folder because of the scope. Now jar-a has a dependency on the 3rd party library log4j with a scope of compile. The log4j JAR also gets included in the lib folder because of its scope. But... so does log4j's dependencies, such as mail, etc. I want log4j but I dont want its dependencies. If I configure log4j with provided, its dependencies wont be included, but neither will itself.
I've considered the options, such as using exclusions, but when there are 40+ internal JAR projects, that's a lot of exclusions in POM files. Also, to use exclusions requires me to know specific knowledge of a 3rd parties dependencies, which feels unnecessary.
Can anyone clarify, expand, answer any of the above? Any input will be most appreciated.
Update Further to the above, I'm stuck with a decision. Should I allow the list of required 3rd party JARs to be bundled within the WAR, be resolved via the compile scope dependencies of the various internal Maven JAR projects we have. Or should I declare all 3rd party dependencies as provided within the internal Maven JAR projects, then specify a clear set with the compile scope on the Maven WAR project.
I prefer the former approach as additional 3rd party dependencies will be automatically added to the WAR artefact via the transitive dependency paths. Yet the second approach provides the certainty of knowing exactly what 3rd party libraries will be included.

A: In the pom.xml of the jar-a project exclude the mail dependency with the exclusions tag:
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.x</version>
    <exclusions>
        <exclusion>
            <groupId>log4j</groupId>
            <artifactId>mail</artifactId>
        </exclusion>
    </exclusions>
</dependency>

If your 3rd party lib depends on an unnecessary library that is the best thing you can do. If they are open source projects you can submit a patch which removes the unnecessary libs.
About the 'future proofing': If you would like a repeatable build you should declare exact version numbers for your dependencies like [1.0] which doesn't let maven to update them whenever a new version come out. In this way a 3rd party library never changes its dependencies because you don't update to a new version which depends on other libs. Of course you should check the dependencies too when you update a 3rd party lib to a new version.
On the other hand your functional tests should report when a new library version broke your application.
I see that it's not too easy with 40+ POMs but it still easier than the old times when you had to download every dependency by hand.
http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Transitive_Dependencies

A: The subject discussed in this documentation is somewhat an answer to my question. It discusses the use of the <dependencyManagement> tag.
This tag can be declared within a parent POM file and allows you to specify the details of dependencies, as well as exclusions. Then any POM that inherits from the parent POM can declare a dependency as usual, but it will inherit any configuration from the parent, unless overridden.
For instance, take the parent POM dependency configuration:
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.15</version>
        <exclusions>
          <exclusion>
            <groupId>log4j</groupId>
            <artifactId>mail</artifactId>
          </exclusion>
        </exclusions>
        <scope>compile</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

The dependency within the child POM is now made far simpler:
  <dependencies>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
    </dependency>
  </dependencies>

Here the child POM inherits the version, exclusions and scope configuration. This doesn't resolve all the concerns I've mentioned, such as the need to know about the 3rd party library's dependencies, but it does provide a single place for configuring and managing these finer details.


text:
Q: Setting a navigation property in addition to select all in linq I have a linq query similar to the following that joins with the entity ProductCategories:
var list = from p in db.Products
           join pc in db.ProductCategories on p.ProductCategoryId equals pc.Id
           select new Product()
           {
              Id = p.Id, Name = p.Name, CategoryName = pc.Name
           };

Lets say I want to select p.* and in addition set the CategoryName navigation property from ProductCategories. Is this possibe? Or will I always have to specify everything when using navigation properties?

A: Create an anonymous object and select your product object under one property and the category name under another property
select new
       {
          Product = p, Name = p.Name, CategoryName = pc.Name
       };

A: The following should work as well if you want the entire thing, and your navigation properties are set up correctly (Make sure you have using System.Data.Entity; at the top of your file:
var list = db.Products.Include(p=>p.ProductCategories);

or a more simple anonymous class:
var list = db.Products.Select(p=>new {
    p.Id,
    p.Description,
    ProductCategoryName=p.ProductCategories.Name});

redpajama_set_name: RedPajamaStackExchange


text:
Q: iOS How to detect only the front face? I have been working on apple CoreImage library to detect faces, so far i have been successful, i am able to detect faces.
What i really want is later to send that image to server for face recognition. But for recognition face, must be front facing camera. The problem is CoreImage will detect face even in side position, and that is not good.
I get the metadata object
if([metadataObject.type isEqualToString:AVMetadataObjectTypeFace])

But am unable to find if the person is looking sideways. Is there easy way to this, like some property, or some class, because I can't seem to find it.

A: It looks like you could just check for the detection of left and right eyes:
for (CIFaceFeature *f in features)
{
    NSLog(NSStringFromRect(f.bounds));

    if (f.hasLeftEyePosition)
        NSLog("Left eye %g %g", f.leftEyePosition.x. f.leftEyePosition.y);

    if (f.hasRightEyePosition)
        NSLog("Right eye %g %g", f.rightEyePosition.x. f.rightEyePosition.y);

    if (f.hasmouthPosition)
        NSLog("Mouth %g %g", f.mouthPosition.x. f.mouthPosition.y);
}

code snippet from here
Previously I've used OpenCV (which you can embed in iOS apps), which has frontal face haar cascades pre-trained.


text:
Q: how to pass values from Visualforce Email Template to custom component I have created a simple visualforce email template:
<messaging:emailTemplate subject="** Inventory Wishlist Match Found **" recipientType="User" relatedToType="Inventory_Wishlist__c">
<messaging:htmlEmailBody >

Year: {!relatedTo.Year__c}

Make: {!relatedTo.Make__c}

Model: {!relatedTo.Model__c}

Below is a link to your request and the matching inventory.

Request: {!relatedTo.Name}

Inventory: <c:ProductLinkComponent yearValue="{!relatedTo.Year__c}" makeValue="{!relatedTo.Make__c}" modelValue="{!relatedTo.Model__c}" />

</messaging:htmlEmailBody>
</messaging:emailTemplate>

Here is my component:
<apex:component access="global" controller="ProductLinkController">

<apex:attribute name="yearValue" description="Attribute for product year" type="String" required="required" assignTo="{!year}" />
<apex:attribute name="makeValue" description="Attribute for product make" type="String" required="required" assignTo="{!make}" />
<apex:attribute name="modelValue" description="Attribute for product model" type="String" required="required" assignTo="{!model}" />

{!productName}

</apex:component>

Here is my component controller:
public class ProductLinkController {

public Product2 product {
    get {
        List<Product2> productList = [select Id, Name from Product2 where year__c =: year AND Make__c =: make and Model__c =: model limit 1];
        if(!productList.isEmpty() && product == null) {
            product = productList[0];
        }
        else {
            product = new Product2();
        }
        return product;
    }
    set;
}
public String year { get;set; }
public String make { get;set; }
public String model { get;set; }

public ProductLinkController() {

}

public String getProductId() {
    return product.Id;
}

public String getProductName() {
    return product.Name;
}
}

I'm trying to output a link to a product in my email based on the values (year, make, model) that are passed thru the email template to the controller.
The query is not returning the correct product and I'm having problems debugging the component controller to see the values that are getting passed in.
Any help is appreciated.
Thanks.

A: The reason it's not working as intended has to do with the order of execution for page loads
The controller constructor is executed before the class properties are set (year, make, model). So the bind variables in the SOQL query in the constructor are all null when the constructor executes. THEN, year make and model are set from the values on the page.
One way to remedy this is in the component controller, move the SOQL query to a getter on the product variable.
private final Product2 product {
   get {
      product = [select Id, Name from Product2 where year__c =: year AND Make__c =: make and Model__c =: model limit 1];
      return product; }
   set;
}


text:
Q: GeoEXT using WFS-T draw on point Layer Hello this is my first post. I'm new with openlayers and geoext and i'm facing a problem while trying to add a new record in a point layer via wfs-t
the code is below (it is from http://workshops.opengeo.org/geoext/wfs/editing.html):
function reconfigure(store, url) {
            var fields = [], columns = [], geometryName, geometryType;
            // regular expression to detect the geometry column
            var geomRegex = /gml:(Point|Line|Polygon|Surface|Geometry).*/;
                var types = {
                // mapping of xml schema data types to Ext JS data types
                "xsd:int": "int",
                "xsd:short": "int",
                "xsd:long": "int",
                "xsd:string": "string",
                "xsd:dateTime": "string",
                "xsd:double": "float",
                "xsd:decimal": "float",
                // mapping of geometry types

                **//Here i want to put something for drawing in point layer**
                "Line": "Path",
                "Surface": "Polygon"
            };

I've tried to put "Poin": "Point", but it didn't work!
Has anybody an idea about what i have to put there so as to work with point layer too(it already works with line and polygon layers)??
Another point of the code which may cause the problem is the save function:
{
    text: "Save",
    handler: function() {
        app.featureGrid.store.proxy.protocol.commit(
            vectorLayer.features, {
                callback: function() {
                    var layers = app.mapPanel.map.layers;
                    for (var i=layers.length-1; i>=0; --i) {
                        layers[i].redraw(true);
                    }
                    app.featureGrid.store.reload();
                }
        });

Which of the two may cause the problem?
Thank's a lot!


text:
Q: How to count number of vowels from file word by word and attach the results to the words? I am trying to write a code in C that reads n words from a file and modifies the content word by word.
The program will count the number of vowels in each word. If the number of vowels in the current word is even, the program will swap the vowels in pair of two (no swapping in case of odd number), then it will attach the number of vowels to the word.
For example if the word is apple , the modified word will look like eppla_2vow .
My problem is that I don't quite know how am I supposed to make the modifications word by word.
     FILE *f = fopen("input.dat","r");
     int i;
     int bufflen=256;
     char buff[bufflen];

     while(n)
     {
      fscanf(f,"%s",buff);
      n--;
     }

     int vowels=0;

     for(i=0; buff[i]!='\0'; i++)
     {
          if (buff[i] == 'a' || buff[i] == 'e' || buff[i] == 'i' ||
          buff[i] == 'o' || buff[i] == 'u' || buff[i] == 'A' ||
          buff[i] == 'E' || buff[i] == 'I' || buff[i] == 'O' ||
          buff[i] == 'U')
          { vowel++;}

          if (buff[i] == ' ')
          {
           vowels=0;
          }
     }

I'm not even sure if I iterate over the string the right way in order to be able to make those modifications.
I will give another example, let's say the content of the file is:
apple juice strawberry can make pineapple

And the modified words will look like:
eppla_2vow juice_3vow strewbarry_2vow can_1vow meka_2vow penieppla_4vow

A: I'd restructure the program to make things easier. Here's an outline:

*

*get the input file size, eg stat()

*allocate size+1 bytes and place a null byte at the end

*read the file into the allocated buffer

*define a small buffer with sufficient space for a word + _XXvow bytes

*scan the allocated buffer in a loop with strtok()

*copy from strtok() return address into small local buffer

*modify bytes in the small buffer (during or after copying) and output the revised word

Extra: instead of the set of many tests for vowel chars, you could create an array of bytes for all chars, init everything to zero, then fill the vowel locations with a replacement letter; when any indexed byte is non-zero, replace the vowel with the new one and increment a vowel count.  This method gains efficiency from indexing an array instead of many (test + branch).

A: This can be broken into a few sub-tasks:
First, we need a function to count the number of vowels in a string. That's pretty straightforward. We could generalize it to count the number of occurrences of any chars in a string in another string without any trouble.
Second, we need a function that swaps the vowels in a string. The two-pointer technique seems like the way to go for this. While the front and back pointers haven't met, iterate the front pointer forward until it lands on a vowel. At this point, decrement the back pointer until it hits a vowel and swap them. Keep swapping like that until the pointers cross. As above, it's easy to pass the character list to swap into the string.
Other than that, everything else is boilerplate--chunking the string on spaces and IO. Writing results back to a file instead of a string makes it easier to deal with reallocation for the _Nvow requirement; you can use fprintf to glue the word and count together.
Putting it all together:
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int str_count_in_chars(char *start, char *end, char *chars) {
    int count = 0;

    for (; start != end; count += !!strchr(chars, *(start++)));

    return count;
}

void str_swap_in_chars(size_t str_len, char **str, char *chars) {
    for (int front = 0, back = str_len - 1; front < back; front++) {
        if (strchr(chars, (*str)[front])) {
            for (; !strchr(chars, (*str)[back]); back--);

            char tmp = (*str)[front];
            (*str)[front] = (*str)[back];
            (*str)[back--] = tmp;
        }
    }
}

char *file_to_str(FILE *fin) {
    int buf_len = 64;
    char buf[buf_len];
    char *str = malloc(buf_len);
    str[0] = '\0';

    for (int i = 1; fgets(buf, buf_len, fin); i++) {
        if (!(str = realloc(str, i * buf_len))) {
            fprintf(stderr, "%s:%d realloc failed\n", __FILE__, __LINE__);
            exit(1);
        }

        strcat(str, buf);
    }

    return str;
}

int main() {
    char *vowels = "aeiou";
    FILE *fin = fopen("input.dat", "r");
    FILE *fout = fopen("output.dat", "w");

    if (!fin || !fout) {
        fprintf(stderr, "%s:%d fopen failed\n", __FILE__, __LINE__);
        exit(1);
    }

    char *words = file_to_str(fin);
    fclose(fin);
    int words_len = strlen(words);

    for (int i = 0; i < words_len;) {
        if (isspace(words[i])) {
            fputc(words[i++], fout);
            continue;
        }

        int start = i;

        for (; i < words_len && !isspace(words[i]); i++);

        char *word = words + start;
        int word_len = i - start;
        int vowel_count = str_count_in_chars(word, words + i, vowels);

        if (vowel_count % 2 == 0) {
            str_swap_in_chars(word_len, &word, vowels);
        }

        fprintf(fout, "%.*s_%dvow", word_len, word, vowel_count);
    }

    fclose(fout);
    free(words);
    return 0;
}

After executing this, output.dat contains:
eppla_2vow juice_3vow strewbarry_2vow can_1vow meka_2vow penieppla_4vow


text:
Q: WeakEventManager not handling interfaces correctly? I try to use the WeakEventManager to - well - use weak events. As source type I am using an interface and that is causing a problem. See code sample below.
When I start the program as is, it errors when calling WeakEventManager (last statement, see comment "here's the error"). It says, there is no PropertyChanged event on IMyEventSource. I then thought to add event PropertyChangedEventHandler PropertyChanged to IMyEventSource. That indeed fixes the issue but leaves me with the warning that my event declaration in the interface would hide the inherited member. Which makes sense as IMyEventSource says it would implement INotifyPropertyChanged. It's feels like catch-22.
Obviously I can accept the warning and add new to the event declaration. But I hope someone can tell me how to do better.
class Program
{
    public static void Main(string[] args)
    {
        MyEventSource source = new MyEventSource();
        WeakEventListener listener = new WeakEventListener(source);
        source.Name = "John Dow";
        Console.ReadLine();
    }
}

public interface IMyEventSource : INotifyPropertyChanged
{
    // event PropertyChangedEventHandler PropertyChanged;   // fixes the issue
    string Name { get; set; }
}

public class MyEventSource : IMyEventSource
{
    private string name;
    public string Name
    {
        get => name;
        set { name = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Name")); ; }
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

public class WeakEventListener
{
    private void OnEvent(object source, PropertyChangedEventArgs args) => Console.WriteLine("WeakEventListener received event.");

    public WeakEventListener(MyEventSource source)
    {
        WeakEventManager<IMyEventSource, PropertyChangedEventArgs>.AddHandler(source, "PropertyChanged", OnEvent); // here's the error
    }
}


text:
Q: How to know where query is executed in EF I get this query in sql profiler
SELECT [r].[OfficialFactorId], [r].[AllowCalcTax], [r].[AndicatorNumber], [r].[BasketId], [r].[BookDateTime], [r].[CalculatedWithUserCurrency], [r].[CashPayementPercent], [r].[Comment], [r].[CorporationId], [r].[CreateUserId], [r].[CustomerId], [r].[Date], [r].[EnvoyAddress], [r].[EnvoyEmail], [r].[EnvoyFirstName], [r].[EnvoyFullname], [r].[EnvoyLastName], [r].[EnvoyMobile], [r].[EnvoyNationalCode], [r].[EnvoyPhone], [r].[EnvoyTel], [r].[FactorStatusId], [r].[FactorTypeId], [r].[FirstPaymentPercent], [r].[HasRemaine], [r].[Info], [r].[IsDeleted], [r].[IsLock], [r].[IsManually], [r].[Number], [r].[ParentFactorId], [r].[PassengerFillTypeId], [r].[PaymentTypeId], [r].[PreFactor], [r].[PrePaymentPrice], [r].[PrePaymentType], [r].[Recipted], [r].[ReferenceNumber], [r].[RefundCardNumber], [r].[RegisterDateTime], [r].[RequestUserId], [r].[Revoked], [r].[RowVersion], [r].[SaleCorporationFinancialPeriodId], [r].[SaleMethod], [r].[SettlementTypeId], [r].[SiteAddress], [r].[TourDateId], [r].[TrackingResponsibleUserId], [r].[UserAgentHeader], [r].[UserNote], [r].[order_id]
FROM [ORD].[OfficialFactor] AS [r]
WHERE EXISTS (
    SELECT 1
    FROM [ORD].[OfficialFactorDetail] AS [x]
    WHERE ([x].[IsDeleted] = 0) AND ([r].[OfficialFactorId] = [x].[OfficialFactorId]))
ORDER BY [r].[OfficialFactorId]

This query genrated with EF Core and this is very slow and return 3,000,000 records.
I want to know where query is executing in project. project is very big and i can't find the query.
In SQL profiler only show UserName and Query.
Is there any way to know where query is  executed?

A: A really helpful feature with EF core is the .TagWith method.
An example being:
var peopleList = dbContext.people
    .Where(b => b.Name != null)
    .TagWith("Getting peoplelist query.")
    .ToList();

which would translate to :
-- Getting peoplelist query.

SELECT [b].[PersonId], [b].[Email], [b].[Name], [b].[Title]
      FROM [Person] AS [b]
      WHERE [b].[Name] IS NOT NULL

It would help you Track down the query that is causing the issue


text:
Q: Missing VT-x option in Surface Laptop 3 BIOS VT-x option is missing Surface Laptop 3 BIOS menu(Intel i7-1065G7 procesor), without this VT-x enabled, I cannot run any virtualization on Windows. Anyone encountered the same problem and know how to fix?

A: Bit late on the response so I dont know if you have worked this out already, but it might help someone else. I also have a Surface Laptop 3 but with an AMD CPU etc. Virtualisation was also missing on my BIOS. My issue was that when using Oracle VirtualBox, the 'Start' opting to begin installing Ubuntu was 'grayed out' or unable to be selected. After searching around, all I needed to proceed with installing Ubuntu was to do what this guide says.
Essentially I just searched in the Windows taskbar 'Turn Windows features on our off'. Here I was able to enable 'Virtual Machines Platform'. I also enabled Windows Hypervisor Platform although I am not sure if this is necessary. Restarted the system and I was able to proceed and install Ubuntu through VirtualBox! Hope this helps!

A: I found a little option using the Oracle Virtual Box for the Intel version of your Surface!
In the Task Manager, under Performance, you can check that virtualization is disabled. Just follow my easy steps:

*

*Run VirtualBox as an administrator

*Create new virtual machine (it doesn't matter what you choose)

*Run it for the first time

*Go to Machine Settings > System > Processor—as you can see, it is set to a default of 1

*Change the number from one core to more than one and somewhere on the bottom side of the GUI you could see an attention icon that says something like

virtualization off. If you save these setting it will be automatically turned on

*Just press OK and voila! It will be turned on!
Now when I type this response I checked too if it is enabled in Task Manager and it was, so yeah!


text:
Q: Замена битов в байтах (двойная плотность пикселей) Имеется массив байт (Конвертированый BMP) в котором нужно проверять биты
если бит=1 то следующий тоже=1 если бит=0 то следующий=0
как реализовать такой цикл ?

A: Надо понимать что бит 1 мы заменяем на 11 т.е. число 3. Если нет, то 0. 10=> 1100 = 12, но 12/2 = 6. Таким образом можно распаковать биты. abcdefg => aabbccddeeffgg
Реализация в с++ где-то так...
 unsigned short* doubledensity(char* a, int size){
      unsigned short* q = (unsigned short*)malloc(size*2); // или другим способом получить массив назначения
      for (int i=0;i<size;i++)
         q[i]=(a[i]&1)*3+(a[i]&2)*6+(a[i]&4)*12 +(a[i]&8)*24 +(a[i]&16)*48+(a[i]&32)*96+(a[i]&64)*192+(a[i]&128)*384;
      return q;
      }

Не забудте q освободить. Если бит был один - стало два - то массив q должен быть в два раза больше размеров. Если q будет массив char или int - прийдётся кастить в short (при таком способе) иначе не правильно посчитает (или прийдётся менять механизм записи в q). Желательно не ошибится с кастом.
a - это имеется ввиду массив с чистым изображением, без шапок, без выравниваний.

A: Судя по вашим предыдущим вопросам, вы работаете с массивом байтов, полученным из изображений типа System.Drawing.Image, System.Drawing.Bitmap.
Как вариант, можно обойтись возможностями самой GDI+.
Допустим, имеется картинка с исходным изображением:
Bitmap source = new Bitmap("source.bmp");

Следующая строка кода создаст новую картинку, увеличенную вдвое (растянутую) по горизонтали. Вроде, именно это вам и нужно.
Bitmap target = new Bitmap(source, source.Width * 2, source.Height);

Всё! Можно её использовать. Например, сохранить:
target.Save("target.bmp", ImageFormat.Bmp); // выберите желаемый формат

Код на C#. Думаю, перевести на C++/CLI не составит труда.

Другой вариант, отрисовка через Graphics. У этого класса есть множество свойств, можно поиграться с их настройкой для получения нужного качества.
Bitmap target = new Bitmap(source.Width * 2, source.Height); // создаем пустое изображение

var graphics = Graphics.FromImage(target);
//graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
//graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.DrawImage(source, new Rectangle(0, 0, target.Width, target.Height));

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


text:
Q: how do i let 2 radio buttons each in a a different groupbox act as they are in the same group? well i have 2 radio buttons and each one exist in a different groupbox.
they they act as they are not related to each other.
but i want them to be as they exist in a same form.
is there a method to 2 that ?
i can do that by handling the the click and unchek the other checkbox but i was wondering if there is a better way?
thanks
Update:
currently i have
private void c_RadioButton1_CheckedChanged(object sender, EventArgs e)
{
    if (RadioButton1.Checked)
         RadioButton2.Checked = false;
}
private void c_RadioButton2_CheckedChanged(object sender, EventArgs e)
{
    if (RadioButton2.Checked)
         RadioButton1.Checked = false;
}

Update2:

A: If you only have one set of radio buttons, you can fake the UI out by placing them at the form level instead of inside of separate group boxes.
To do this in visual studio you will have to manually edit the designer generated code. Or place the radio buttons outside of the form and use your arrow keys to place it in the correct location.
You have to do this because once you drag the radio button with your mouse the designer will place it inside of the group box.


text:
Q: How to import all Vue components from a folder? I am trying to load all my vue's components automatically from a folder,
which is working fine if I don't use vue "Async Components".
Once I try to use Async Components with import .. I get this error:
10:11-36 Critical dependency: the request of a dependency is an expression

My code that load all components, which generate this error:
const ComponentContext = require.context('./', true, /\.vue$/i);

ComponentContext.keys().forEach((componentFilePath) => {

    const componentName = componentFilePath.split('/').pop().split('.')[0];
    Vue.component(componentName, () => import(componentFilePath));

});

How to fix this ? or is there is any other way to accomplish this?

A: Ok, I needed to add 'lazy' in:
const ComponentContext = require.context('./', true, /\.vue$/i, 'lazy');

and then:
Vue.component(componentName, () => ComponentContext(componentFilePath));

A: I had to merge the question with an answer here to get this final solution:
const ComponentContext = require.context('./', true, /\.vue$/i, 'lazy');

ComponentContext.keys().forEach((componentFilePath) => {

    const componentName = componentFilePath.split('/').pop().split('.')[0];
    Vue.component(componentName, () => ComponentContext(componentFilePath));

});

The 'lazy' third param was added to require.context(), and () => import() was changed to () => ComponentContext().
I can see the bundles in the Network tab of the dev tools pane, and I don't see the bundles when I navigate to a page that doesn't render any of the auto-loaded components.
Therefore, I am reasonably-certain the above code is autoloading and dynamic importing. I will also confirm that in my project, I am using:
require.context('~/components/common', true, /\.vue$/i, 'lazy')

Note where mine is different at ~/components/common compared to ./. Your project needs will likely be different. In mine, the ~ is a Webpack alias for /resources/js, so my full path would be ./resources/js/components/common. The rest of the code above is an algorithm, and can remain untouched.

A: Instead of
Vue.component(componentName, () => import(componentFilePath));

Try
Vue.component(componentName, ComponentContext(componentFilePath));

Or
Vue.component(componentName, ComponentContext(componentFilePath).default);

not sure about the default part.


text:
Q: Finding a potential function for $\vec F=\frac{-y}{x^2+y^2}\vec i+\frac{x}{x^2+y^2}\vec j$ on $\Omega=\mathbb{R}^2- \{(x,y)\,|\,y=0,\,x\geq0 \}$ In one of my Calculus III classes the professor presented the following vector field, defined on the set $S$ of all points $(x,y) \neq(0,0)$ :
$$
\bbox[6px,border:1px solid black] {
\vec{F}=\frac{-y}{x^2+y^2}\vec{i} + \frac{x}{x^2+y^2}\vec{j}
}
$$
Although $\vec{F}$ is not a gradient on $S$, it is a gradient on the set $\Omega=\mathbb{R}^2-\left\{(x,y)\,|\,y=0, \, x\geq0\right\}$, i.e, all points in the xy-plane except those on the positive x-axis. In the class, my professor wrote a potential function for $\vec{F}$ on $\Omega$ using the following functions:
$$
\bbox[6px,border:1px solid black] {
\begin{alignat}{0}
\Psi_1(x,y)=-\arctan\left(\frac x y \right), \,y\neq0 &\text{and} &\Psi_2(x,y)=\arctan\left(\frac y x \right), \,x\neq0
\end{alignat}
}
$$
The first is a potential of $\vec F$ on $\Omega^+=\{(x,y)\in\mathbb{R}^2\,|\,y>0\}$ and on $\Omega^-=\{(x,y)\in\mathbb{R}^2\,|\,y<0\}$.
The last one is a potential of $\vec F$ too, but on $\Omega_+=\{(x,y)\in\mathbb{R}^2\,|\,x>0\}$ and on $\Omega_-=\{(x,y)\in\mathbb{R}^2\,|\,x<0\}$
The potential function wrote by my professor:

$$
\bbox[8px,border:1px solid black] {
\phi (x,y) =
\begin{cases}
\Psi_1(x,y) & \text{if $(x,y) \in R_1$} \\[2ex]
\Psi_2(x,y)+\frac\pi 2 & \text{if $(x,y) \in R_2$} \\[2ex]
\Psi_1(x,y)+2\pi & \text{if $(x,y) \in R_3$} \\
\end{cases}
}
$$
(Note: I remember that my professor started with the argument that since $\nabla\Psi_1=\vec F = \nabla\Psi_2$, then $\Psi_1-\Psi_2=k, \,k \in \mathbb{R}$)

My doubts:

*

*I've tried a lot, but still have not figured out how to build $\phi (x,y)$ using $\Psi_1$ and $\Psi_2$. So, how to find this specific potential function of $\vec F$ ?

*Why can't I simply write potential functions of $\vec{F}$ in the following ways
$$
\phi_A (x,y) =
\begin{alignat}{0}
\begin{cases}
\Psi_1(x,y) & \text{if $(x,y) \in R_1$} \\[2ex]
\Psi_2(x,y) & \text{if $(x,y) \in R_2$} \\[2ex]
\Psi_1(x,y) & \text{if $(x,y) \in R_3$} \\
\end{cases}
&\text{or}
&\phi_B(x,y)=
\begin{cases}
\Psi_1(x,y) & \text{if $y>0$} \\[2ex]
0 & \text{if $y=0$ and $x<0$} \\[2ex]
\Psi_1(x,y) & \text{if $y<0$} \\
\end{cases}
\end{alignat}
$$
since $\nabla\phi_A=\nabla\phi_B=\vec F$ on $\Omega$ ?


text:
Q: Application Request Routing redirected calls fail when machine names are used I am having two servers in my application. One is web server and another is app server. I have a static file in my application server inside my IIS Web Application. App Server web application is enabled with Windows Authentication. I have created URL rewrite using ARR for calls with specific URL to get redirected to the static file.
When I use IP address in my URL and call web server from client machine, things works fine. When I use machine name, I am getting 401 error.
1) I checked on the IIS Logs -> When call fails, repeated attempt was made by client to connect with web server and all calls failed with 401 error. From web server to app server, call was made only one and it returned 401 error.
2) When call success scenario, two 401 failure in web server and one 401 failure in app server. after that one success call in both web server and app server.
I also checked on Failure Request Tracing and didn't get additional information.
Below is the configuration I have in web server for ARR.
<validation validateIntegratedModeConfiguration="false" />
<rewrite>
  <rules>
    <rule name="Reverse Proxy to Test Model" stopProcessing="true">
      <match url="^Sample/(.*)" />
      <action type="Rewrite" url="http://appserver/{R:0}" />
    </rule>
  </rules>
</rewrite>

Let me know if more information is required.
Regards,
Madhan

A: The above issue was due to a Kerberos issue. We registered the SPN for the runtime account of the accessed URL (basically the Application Pool account in which Virtual Application is running) in the application server against the web server. After this, calls were accepted in the application server and required response was returned back.


text:
Q: How do I add a color overlay to an image using CSS? im using react, html, css and material ui
I am trying to toggle between color overlay being present and not present with onclick on an image.
below is the javascript:
const About = ({imgState, setImgState}) => {

const imgTracker = () => {
    if(imgState === true){
      setImgState(false);
    }
    else if(imgState===false){
      setImgState(true);
    }
  }

...

<Box
                  className={imgState ? 'AboutImg active' : 'AboutImg notactive'}
                  component="img"
                  alt="face"
                  src={img2}
                  onClick={imgTracker}
                />

and below is the css:
.MidSectionTop{
    .MidSectionTopText{

    }

    .MidSectionImage{
        .AboutImg{
            height: calc(100vh * 4/12);
            width: calc(100vw * 2/12);

            &.active{
                background: rgba(0, 197, 165, 0.5);

            }
            &.notactive{
                background: none;
            }
        }
    }
}

my problem so far is that the image is overlayed ontop of the background color. I have tried giving z-index to the '&.active' class but it did not work out. any help grealy appreciated! Let me know what else I could provide

A: You can use what's called pseudo-elements (::before or ::after) for this.
.AboutImg{
    position: relative;
    &::after{
        position:absolute;
        left:0;
        top:0;
        right:0;
        bottom:0;
        display:block;
        content: '';
    }
    &.active::after{
        background: rgba(0, 197, 165, 0.5);
    }
    &.notactive::after{
        background: none;
    }
}


text:
Q: Does a differential manifold implies existence of unique tangent space at every point? I like differential geometry and I want to know if a differentiable manifold implies unique tangent space at every point. I have searched but the definition I have found of differential manifold is that differentiable manifold is a topological manifold in which we construct an atlas that covers the entire manifold and the transition functions in the intersection of the coordinate systems of the atlas are differentiable. But this doesn't say anything about tangent spaces. Whatever I have read about differential geometry, tangent spaces are defined always after the definition of differentiable manifold, so it seems tangent spaces are not need to define what a differentiable manifold is and for a topological manifold to be a differentiable manifold is only need that we construct an atlas with the characteristics I said before. But then if you have for example, a 1 dimensional topological manifold that is a real line with one point that is not smooth, because it has the form of a peak, there is no unique tangent space at this point, although there is in the other points. Then we construct an atlas in which the transition functions are differentiable at this point just  because we can define the coordinate systems in a way that the transition functions from one coordinate to another  is differentiable. Although the manifold has no unique tangent space in this point. I always believed that differentiability at manifold level implies unique tangent space and that the manifold doesn't care about coordinate system differentiability. But the definition of differentiable manifold is based on differentiability in coordinate systems. So if we can define an atlas that is smooth but the real manifold is not, Therefore, differentiable manifold doesn't implies unique tangent space. Am I missing something?
Sorry for my bad expression but english is not my mother tongue and I tried to express the better I can.

A: $\newcommand{\Reals}{\mathbf{R}}$In the context of your question, a smooth $n$-manifold $M$ is a topological space equipped with additional intrinsic structure (locally homeomorphic to the Cartesian space $\Reals^{n}$, smooth overlap maps).
Each tangent space of $M$ is defined in terms of (and uniquely characterized by) this intrinsic structure. In that sense, $M$ has a unique tangent space at each point.
A smooth manifold does not come equipped with an embedding into a Cartesian space. In fancier words, the underlying set of points of a smooth manifold need not be a subset of $\Reals^{N}$ for some positive integer $N$.
If $M$ is a $n$-smooth manifold, and if $\phi:M \to \Reals^{N}$ is a smooth embedding, then the image $\phi(M) \subset \Reals^{N}$ is locally homeomorphic to $\Reals^{n}$, and these homeomorphisms may be chosen so that the overlap maps are smooth. In this setting, the intrinsic tangent space of $M$ at a point $p$ corresponds naturally with a certain affine subspace in $\Reals^{N}$ passing through $\phi(p)$. This is the intuitive picture underlying your question. Note carefully, though, that you are no longer considering a smooth manifold alone, but a smooth manifold together with a smooth embedding in $\Reals^{N}$.
Consider a subset $M \subset \Reals^{N}$ that is locally homeomorphic to $\Reals^{n}$, such as the graph $y = |x|$ in $\Reals^{2}$. It may be true that $M$ can be given the structure of a smooth manifold (by fixing, at each point $p \in M$, one homeomorphism from some neighborhood of $p$ to $\Reals^{n}$, then taking all "smoothly compatible" homeomorphisms), but even if you do so, it does not follow that the inclusion map $i:M \to \Reals^{N}$ is smooth. (!) That is, the intrinsic tangent spaces of $M$ need not correspond with affine subspaces of $\Reals^{N}$. This resolves the apparent paradox implicit in your question.

A: Fix two different parameterizations $p: U \longrightarrow M,q:V \longrightarrow M$ around a point $x$ on a smooth manifold $M$. The corresponding points $u_1 \in U, v_1 \in V$ lie in Euclidean spaces where tangents exist naturally. Pick a tangent vector to $u_1$, that is a vector $\vec{u_1}$ with its base at $u_1$. The transition map $U \longrightarrow V $ takes $u_1$ to $v_1$ and the vector $\vec{u_1}$ to a new vector $\vec{v_1}$ tangent to $V$ at $v_1$. Since transition map is a local diffeomorphism, its derivative is 1-to-1 and this gives a pairing of tangent vectors on $U$ and $V$.
The tangent to $M$ at $x$ can be thought of as tangent to $U$ at $u_1$ for some parameterization of $M$ around $x$. To have  well-defined notion we identify such $\vec{u_1}$ and $\vec{v_1}$ pairs under transition of parameterizations. In other words, one tangent vector to $M$ at $x$ is the classof all tangent vectors  to localizations of $M$ where we identify two vectors in two parameterizations iff they map to one another under transition of maps.

A: The differentiable structure on the manifold does determine (uniquely) its tangent space.
As for familiar broken shapes, it depends how you look at them. If you only see them as topological subsets of Euclidean spaces, that is all you borrow from $R^n$ is the topology, then you can (yourself) ENDOW them with a differentiable atlas and structure
For instance, a rectangle, when we see it as a topological space is no different than a circle. Then we can transfer the differentiable structure of $S^1$ onto the rectangle via their homeomorphism. However, the circle is by default a differentiable submanifold of $R^2$, that is, with $R^2$'s atlas restricted to the circle, we do get an atlas on $S^1$. The problem with the rectangle is we may equip it with a differentiable structure, but it won't be the restriction of the plane's atlas to the rectangle. This is a relief! Since our intuition of rectangle being non-smooth is respected by our math definitions.
Addition: You may be surprised to hear that there exists topological manifolds that do not admit any smooth structures! That is among so many spaces that a fixed space is homeomorphic to, non is a smooth manifold!


text:
Q: Weblogic package deployment plan inside ear I'm trying to install the solace weblogic resource adapter as described here https://dev.solace.com/wp-content/uploads/2016/06/Solace-JMS-Integration-with-WebLogic.pdf
The problem is that we are not allowed to manually deploy anything inside weblogic with our infrastructure. This means that in order to get the rar inside weblogic I have to package it inside the ear that also contains the war for our application.
The problem is that once the resource adapter is deployed on the server it still needs to be configured which requires manual intervention and that is again not allowed.
When manually configuring the resource adapter locally it creates a deployment plan that it then uses to configure the resource adapter when the server starts.
My question is, is there a way to somehow pre-package the deployment plan for the rar inside the ear so that I can configure it at build time?

A: Weblogic handles the deployment plans separately from applications. It is not possible to deploy a deployment plan by pre-packaging it inside of the RAR file.
If you are not permitted to use the Weblogic console, another option would be to
use the weblogic.Deployer Java command which handles the application and the plan separately, but it still gets the deployment done in one command without using the console.


text:
Q: MS Azure DB: cannot find data type XML & Incorrect syntax near ' Identity' I was trying to change the data type into XML in order to split one column into multiple columns. However, when I ran the syntax below, an error: cannot find data type XML was showed. I searched some of the answers online. It seems Azure is supported for XML. Is there a way to solve it?
cast('<m>'+replace(Employee_Name,@delimiter,'</m><m>')+'</m>' as XML)

Besides, I found that IDENTITY(1,1) is not supported either.

A: With SQL-Server 2016 there is native support for this: STRING_SPLIT()-function. But - according to the linked doumentation - this seems not to be offered for Azure Data Warehouse...
The string splitting via XML needs the XML-DataType, since you will need .nodes() and .value() to retrieve the values. According to this documentation this is supported with Azure Database, don't know of restriction with the Data Warehouse version...
There are many examples for string splitting functions using loops or recursive CTEs. This article compares some of them...

A: This error occurs when you try to run the query casting to XML while logged into a Microsoft Azure SQL Data Warehouse. Azure SQL Data Warehouse does not support the XML datatype. You can confirm your version with the following sql:
select @@version
https://learn.microsoft.com/en-us/azure/sql-data-warehouse/sql-data-warehouse-tables-data-types


text:
Q: Autocovariance of a Stochastic Process Let us define a stochastic process $X_t$ as follows:
$$X_t = \sum_{i=0}^p \alpha_i \epsilon_{t-i} + \sum_{i=0}^q \beta_i \delta_{t-i}$$
where {$ε_t$} and {$δ_t$} are mutually independent normally distributed white noise processes
with finite variances $σ^2_ε$ and $σ^2_δ$ respectively. We can also assume that $p, q > 0$ and that $α_p$, $β_q$ are non-zero.
Can any braniacs help me find an expression for the autocovariance function of {$X_t$} for general values of $p, q, α_i$ and $β_i$ ? I have been trying to crack this for a while and just can't get my head around it. Any statistical wizardry would be vastly appreciated, I cannot find much about it online and I need to try and grasp this solution as soon as possible! Many, many thanks in advance.


text:
Q: Why is scan.setCacheBlocks(false) is recommended for mapReduce job? I understand why scan.setCaching is good for mapreduce jobs, but I don't understand why setCacheBlocks(false) is bad.  Does it overburden the server?

A: In short - yes, it burdens the RegionServer if you set blockcaching to true in mapreduce jobs .When you are using mapreduce jobs mostly on input scans , its high probability that the recently  scanned input is going to be discarded in next map phase. Blockcache is LRU.. It puts data into Blockcache during first request , then finds that its of no usage in second request and swaps it and the process continues. So the RegionServer is continuosly swapping data in and out of BlockCache for no gain. Its just a  lot of unnecessary IO usage. But in case of  normal reading , it's advisable to keep it true to gain from data locality.


text:
Q: jQuery replace element with textbox I want to replace a p tag with a textbox using jQuery. What I have tried isn't working.

A: <p> Some text.. </p>

$('p').dblclick(function(){
    var textArea = $('<textarea />')
    var oldText = $(this).text();

    $(this).replaceWith(textArea);
    textArea.val(oldText);
});

See example here.
On focusout, you can read the new value (or old) and set it back within a p tag.
See that example here

A: Please try this:
API: http://api.jquery.com/replaceWith/ DEMO: http://jsfiddle.net/Yuuhr/

Replace each element in the set of matched elements with the provided
  new content.

Please let me know if I missed anything or provide full html
Hope this helps
code
$('p').replaceWith('<textarea id="foohulk"/>')


text:
Q: Estimation of Electrolytic Capacitor ESR at SMPS Frequencies While working on compensation networks or ripple calculations, it helps to know the ESR for my output capacitors. In high voltage SMPS systems, this seems to be difficult for the following reasons:

*

*ESR if quoted is at 120Hz. - Commonly people will explain to use Tan(\$ \delta\$) to calculate ESR for a given frequency beyond 120Hz... See issue #2.

*Tan(\$ \delta\$) seems to not be consistent across frequency (source p. 7) So unless you are close to the often quoted 120Hz, this is not useful.

*Does Voltage bias affect ESR? I assume not, but I have not found any info supporting either yes or no.

I have made crude setups to test ESR of capacitors I am planning on using, but I would like to perform it more analytically if possible... Also depending on if ESR is affected by voltage bias, that has a huge affect on the complexity of testing ESR, since this is typically for ~400V output supplies.
Any advice or experts on the 3 points above? I'm guessing the consensus will be to just estimate and test...

Below are a datasheet for reference and an image of the plots from page 7 of the Nichicon capacitor manual I reference above.


text:
Q: Rust string lifetimes and iterator adapters (lifetime compile error) I'm working with CSV so I need to trim newlines and split on commas for each line, and filter out any lines that have a '?' in them.
let instances: Vec<Vec<&str>> = file.lines()
    .map(|x| x.unwrap())
    .filter(|x| !(x.contains("?")))
    .map(|x| x.as_slice().trim_chars('\n').split_str(",").collect()).collect();

This is the compiler error message I'm getting:
.../src/main.rs:13:18: 13:19 error: `x` does not live long enough
.../src/main.rs:13         .map(|x| x.as_slice().trim_chars('\n').split_str(",").collect()).collect();
                                                             ^
.../src/main.rs:7:11: 21:2 note: reference must be valid for the block at 7:10...
.../src/main.rs:7 fn main() {
.../src/main.rs:8     let path = Path::new("./...");
.../src/main.rs:9     let mut file = BufferedReader::new(File::open(&path));
.../src/main.rs:10     let instances: Vec<Vec<&str>> = file.lines()
.../src/main.rs:11         .map(|x| x.unwrap())
.../src/main.rs:12         .filter(|x| !(x.contains("?")))
                                            ...
.../src/main.rs:13:18: 13:72 note: ...but borrowed value is only valid for the block at 13:17
.../src/main.rs:13         .map(|x| x.as_slice().trim_chars('\n').split_str(",").collect()).collect();

I don't understand how the lifetimes of the string types in Rust are supposed to be used in this context. Changing instances to Vec<Vec<String>> doesn't fix the problem either.
What's extra confusing to me is that following works with a single String:
let x: Vec<&str> = some_string.as_slice().trim_chars('\n').split_str(",").collect();

What am I doing wrong with the lifetime of these values to cause this compiler error?
If iterator adapters are not an idiomatic approach to this problem please explain why and how I should approach this differently.

A: The x &str is a reference to the contents of a String, the ones yielded by lines(). A &str can only live as long as the String it is a reference into, and you're not storing the String anywhere. You would need to either store the lines in another variable:
let lines = file.lines().map(|x| x.unwrap()).collect::<Vec<_>>();
let instances: Vec<Vec<&str>> = lines.iter()
    .filter(|x| !(x.contains("?")))
    .map(|x| x.trim_chars('\n').split_str(",").collect()).collect();

Or else you would convert all of the &strs into Strings:
let instances: Vec<Vec<String>> = file.lines()
    .map(|x| x.unwrap())
    .filter(|x| !(x.contains("?")))
    .map(|x| x.trim_chars('\n').split_str(",")
        .map(|x| x.into_string()).collect()).collect();

As an incidental note, the collect() calls can be written collect::<Vec<_>>(), allowing you to remove the type annotation from the instances variable. Which is better? Up to you to decide.


text:
Q: Why do I keep getting an Unresolved External Symbol error when using the CredUIPromptForCredentials function from wincred.h I keep getting these two errors in Visual Studio C++:
"Error  LNK2019 unresolved external symbol __imp__CredUIPromptForCredentialsW@40 referenced in function _main   ConsoleApplication1"
"Error  LNK1120 1 unresolved externals  ConsoleApplication1"
I am trying to get the part that opens up the enter credentials dialog of this example code to run: https://learn.microsoft.com/en-us/windows/desktop/taskschd/weekly-trigger-example--c---
I am new to C++ but I am pretty sure that all of the datatypes that I am passing in to the CredUIPromptForCredentials function are correct. I have already tried reading the links from the error but they are not helping me.
int main() {
    CREDUI_INFO cui;
    TCHAR credLoc[CREDUI_MAX_USERNAME_LENGTH] = _T("");
    TCHAR pszName[CREDUI_MAX_USERNAME_LENGTH] = _T("");
    TCHAR pszPwd[CREDUI_MAX_PASSWORD_LENGTH] = _T("");
    BOOL fSave;
    //DWORD dwErr;

    cui.cbSize = sizeof(CREDUI_INFO);
    cui.hwndParent = NULL;
    //  Ensure that MessageText and CaptionText identify
    //  what credentials to use and which application requires them.
    cui.pszMessageText = TEXT("Account information for task registration:");
    cui.pszCaptionText = TEXT("Enter Account Information for Task Registration");
    cui.hbmBanner = NULL;
    fSave = FALSE;

    //  Create the UI asking for the credentials.
    CredUIPromptForCredentialsW(
        &cui,                             //  CREDUI_INFO structure
        credLoc,                         //  Target for credentials
        NULL,                             //  Reserved
        0,                                //  Reason
        pszName,                          //  User name
        CREDUI_MAX_USERNAME_LENGTH,       //  Max number for user name
        pszPwd,                           //  Password
        CREDUI_MAX_PASSWORD_LENGTH,       //  Max number for password
        &fSave,                           //  State of save check box
        CREDUI_FLAGS_DO_NOT_PERSIST);

    return 0;
}

I am expecting to see a dialog box that prompts for a username and password but I only get the errors listed above and the program fails to build.

A: Your project needs to link to Credui.lib, as stated in the CredUIPromptForCredentialsW() documentation. Either add the .lib file to your project, or else use a #pragma comment(lib, "Credui.lib") statement in your code.


text:
Q: Eclipse RCP 3.x draggable Toolbar In addition to my previous question, since there are some issues with Drag and Drop on E4:

The DND addon is found in the org.eclipse.e4.ui.workbench.addons.swt plugin. However it requires the compatibility layer and is not available for native E4AP applications.

Question
Is it possible to create an old-style Eclipse 3.x application, that runs on the current Eclipse 4.5.1 platform and uses the nice toolbar from the Eclipse IDE with Drag and Drop functionality?

Starting with a fresh installation of Eclipse for RCP 4.5.1, I created an eclipse 3.x application with sample content using the wizrad.

It contains two toolbars, but D&D functionality is missing. So what to do next?


text:
Q: How to add key/value pair in to array dynamically I want to add an array dynamically using jquery. How can i do that.(or)
I want to push the elements in to array like this.
 var array = [{"question":"1","answer":"2"}];

i want to do that dynamically using for loop i mean
    initially i will add
array.push({"question":"1"});
then array.push({"answer":"2"});

but I want the elements to in the same array[0] element
but it is taking as array[0],array[1]
How can I do that. I am using for loop to add the elements in to an array.

A: If you are pushing an answer immediately after, can you not do something like
  array[index] = { "question" : array[index].question, "answer": 2 };

If not you will have to find some other way of finding the index where the question was pushed and then
Just note that array.push always adds a new object to the array, and does not update it.


text:
Q: Multiple level host alias in ssh config My system admin manages a set of SSH configs for our remote servers, these configs are updated and pushed to my /etc/ssh/ folder regularly. However, host names in the managed ssh configs are too long to type (I'm lazy). Can I create host name aliases in my ~/.ssh/config? Note that this is not alias for HostName.
For example, my admin pushes configs to my /etc/ssh/ssh_config.d/ which look like this:
Host a.long.host.name
    HostName real-host-name.example.com
    ProxyCommand some proxy command
    ...

I want to give a.long.host.name a different, shorter name so I can type ssh foo instead of ssh a.long.host.name, I don't want to use shell alias because other commands like scp will need separate shell aliases.
I think ProxyCommand ssh -J localhost a.long.host.name would work, but localhost must be have sshd enabled, which I can't do.

A: "Host a.long.host.name" is an arbitrary name, it can be anything you like so long as it's not a duplicate or a reserved word etc. It is effectively an ssh config specific alias. User specific ssh configs will take precedence over system level configs in /etc/ssh/


text:
Q: Number of columns related to results MySQL I have three tables:
Table 1 - documents:
ID    Title
====================
1     doc 1
2     doc 2
3     doc 3
4     doc 4

Each document can be assigned to multiple subcategories - this relation resides in table 2.
Table 2 - doc_subcategory which matches document_id and subcategory_id:
document_id    subcategory_id
============================
1              1
1              2
1              5
2              1
2              2
3              1
3              7
4              2
4              3
4              5

Table 3 - subcategories - there's also a subcategory table that contains its id, name and higer_level_category_id of another (higher) level of category.
id    name           higer_level_category_id
============================================
1     To buy         1
2     To give back   1
3     To send        1
4     To buy         2
5     To send        2
6     To throw       2
7     To destroy     2

What want to get is this:
doc_id    doc_title    subcat_id        subcat_id       upper_1  upper_2
                       for_upper_cat1   for_upper_cat2

==========================================================================================
1         doc 1        1,2              5               1        2
2         doc 2        1,2              NULL            1        NULL
3         doc 3        1,7              7               1        2
4         doc 4        2,3              5               1        2

I created a query that kind, but I've no idea how to separate subcategories and upper categories into separate columns:
SELECT
  documents.id as doc_id,
  documents.title as doc_title,
  group_concat(DISTINCT doc_subcategory.subcategory_id) as subcat_id,
  group_concat(DISTINCT subcategories.higer_level_category_id) as upper
FROM
  documents
LEFT JOIN
  doc_subcategory
  ON
  (
    documents.id = doc_subcategory.id
  )
LEFT JOIN
  subcategories
  ON
  (
    doc_subcategory.subcategory_id = subcategories.id
  )
GROUP BY documents.id;

I've noticed that when I give another parameter to order by clause which is subcategories.higer_level_category_id this gives me a bit better results, but still this is far from what I want. The problem is with dynamic columns which should be created on the fly that relates to number of subcategories.higer_level_category_id.

A: There seem to be a few errors in your query (e. g. there is no column doc_subcategory.id). I put together a little rextester-demo with your query. You can find it here: http://rextester.com/XOP97169
I updated your query to
SELECT
  documents.id as doc_id,
  documents.title as doc_title,
  group_concat(DISTINCT doc_subcategory.subcategory_id) as subcat_id,
  group_concat(DISTINCT subcategories.higher_level_category_id) as upper
FROM documents
LEFT JOIN doc_subcategory ON documents.id       = doc_subcategory.document_id
LEFT JOIN subcategories   ON doc_subcategory.subcategory_id = subcategories.id
GROUP BY documents.id;

This results in
doc_id  doc_title   subcat_id   upper
--------------------------------------
1       doc 1       1,2,5       1,2
2       doc 2       1,2         1,2
3       doc 3       1,7         1,2
4       doc 4       2,3,5       2,3

Maybe you can illustrate a few finer points on the basis of this fiddle. But, as @Strawberry already said, the "presentation" of the data should usually be left to your embedding application, be it in JavaScript (node.js), python, c# or php....


text:
Q: what sorting algorithm could be this one? I am trying to use this sort algorithm, just I am asking if it is using the quick sort algorithm or another type of sort
void qsufsort(uint64_t *I,uint64_t *V,u_char *old,uint64_t oldsize)
{
  uint64_t buff[256];
  uint64_t i,h,len;

  for(i=0;i<256;i++) buff[i]=0;
  for(i=0;i<oldsize;i++) buff[old[i]]++;
  for(i=1;i<256;i++) buff[i]+=buff[i-1];
  for(i=255;i>0;i--) buff[i]=buff[i-1];
  buff[0]=0;

  for(i=0;i<oldsize;i++) I[++buff[old[i]]]=i;
  I[0]=oldsize;
  for(i=0;i<oldsize;i++) V[i]=buff[old[i]];
  V[oldsize]=0;
  for(i=1;i<256;i++) if(buff[i]==buff[i-1]+1) I[buff[i]]=-1;
  I[0]=-1;

  for(h=1;I[0]!=-(oldsize+1);h+=h) {
    len=0;
    for(i=0;i<oldsize+1;) {
      if(I[i]<0) {
        len-=I[i];
        i-=I[i];
      } else {
        if(len) I[i-len]=-len;
        len=V[I[i]]+1-i;
        split(I,V,i,len,h);
        i+=len;
        len=0;
      };
    };
    if(len) I[i-len]=-len;
  };

  for(i=0;i<oldsize+1;i++) I[V[i]]=i;
}

what I understood that it will count the occurrence of each character in an array of 256 elements


text:
Q: Convert loop logic to LINQ Does anyone know if there's a cleaner way of doing this (maybe LINQ)? I want to group the value into bucket, and give it a score, so for example in the code below, if the value is:

*

*less or equal to 5, increase the score by 1

*10 and below, increase score by 2

*15 and below, increase score by 3

*else increase by 4.

There are about 10 properties that I have to do this for, and each property have different range for scoring.
public static PScore GetScore(IEnumerable<PStat> rs)
    {
        var data = new PScore();

        foreach(var item in rs)
        {
            if(item.Kill <= 5)
            {
                data.Kills++;
            }
            else if (item.Kill <= 10)
            {
                data.Kills += 2;
            }
            else if (item.Kill <= 15)
            {
                data.Kills += 3;
            }
            else
            {
                data.Kills += 4;
            }
        }

        return data;
    }

edit#1
Thanks everyone, the ranges varied as well, and I have 10 properties to loop through, so I use this and just passed in the value and ranges
public static int GetScoreASC(int value, int[] range)
    {

        if (value <= range[0])
        {
            return 1;
        }
        else if (value <= range[1])
        {
            return 2;
        }
        else if (value <= range[2])
        {
            return 3;
        }
        else if (value <= range[3])
        {
            return 4;
        }
        else if (value <= range[4])
        {
            return 5;
        }
        else if (value <= range[5])
        {
            return 6;
        }
        else if (value <= range[6])
        {
            return 7;
        }
        else if (value <= range[7])
        {
            return 8;
        }
        else if (value <= range[8])
        {
            return 9;
        }
        else
        {
            return 10;
        }
    }

This way I can reused the same method for all properties.

A: I would do some math per each property using LINQ:
public static PScore GetScore(IEnumerable<PStat> rs)
{
   var data = new PScore();
   data.Kills = rs.Sum(item => Math.Min(item.Kill / 5 + (item.Kill % 5 == 0 ? 0 : 1), 4));
   return data;
}

A: You can repeat yourself less by using Select to grab the Kill values from rs and then Sum to aggregate across them.
public static PScore GetScore(IEnumerable<PStat> rs)
{
    return new PScore
    {
        Kills = rs.Select(item => item.Kill).Sum(kill =>
        {
            if (kill <= 5) return 1;
            if (kill <= 10) return 2;
            if (kill <= 15) return 3;
            return 4;
        })
    };
}

If you like Konrad's style of converting the conditionals to a closed form computation, you need to correct his formula slightly. I personally would stick with the conditionals for this, though.
public static PScore GetScore(IEnumerable<PStat> rs)
{
    return new PScore
    {
        Kills = rs.Select(item => item.Kill)
            .Sum(kill => Math.Max(1, Math.Min((kill + 4) / 5, 4)));
    };
}


text:
Q: Fill an array (or arraylist) from SqlDataReader Is there a way to fill an array via a SqlDataReader (or any other C# ADO.NET object) without looping through all the items?  I have a query that is returning a single column, and I want to put that into a string array (or ArrayList, or List, etc).

A: Apparently, ever since .NET 1.1 SqlDataReader had the following method:
int size;
object[] data = new object[]{};
size = reader.GetValues(data);

This populates data with the values of the current reader row, assigning into size the number of objects that were put into the array.

A: It is possible. In .NET 2.0+, SqlDataReader inherits from DbDataReader, which implements IEnumerable (non-generic one). This means that you can use LINQ:
List<string> list = (from IDataRecord r in dataReader
                     select (string)r["FieldName"]
                    ).ToList();

That said, the loop is still there, it's just hidden in Enumerable.Select, rather than being explicit in your code.

A: Since any IDataReader implementation (SqlDataReader included) will be a forward-only reader by definition, no there is no way to do this without looping.  Even if there were a framework library method to do this it would have to loop through the reader, just like you would.

A: No, since SqlDataReader is a forward-only read-only stream of rows from a SQL Server database, the stream of rows will be looped through whether explicitly in your code or hidden in a framework implementation (such as DataTable's Load method).
It sounds like using a generic list and then returning the list as an array would be a good option. For example,
List<int> list = new List<int>();

using (SqlDataReader reader = cmd.ExecuteReader())
{
    while (reader.Read())
    {
         list.Add(reader.GetInt32(0));
    }
}
return list.ToArray();

In response to your comment, calling ToArray() may be overhead, it depends. Do you need an array of objects to work with or would a generic collection (such as List<T> or ReadOnlyCollection<T>) be more useful?

A: The orignial OP asked for Array, ArrayList or List. You can return Array as well. Just call the .ToArray() method and assign it to a previously declared array.  Arrays are very fast when it comes to enumerating each element.  Much faster than a List if the list has more than 1000 elements.
You can return to Array, List, or Dictionary.
ids_array = (from IDataRecord r in idReader
select (string)r["ID"]).ToArray<string>();

Additionally, if you are using a lookup of keys for example, you might consider creating a HashSet object with has excellent lookup performance if you are simply checking one list against another to determine if an elements key exists in the HashSet object.
example:
 HashSet<string> hs = new HashSet<string>(
(from IDataRecord r in idReader select (string)r["ID"]).AsEnumerable<string>() );

A: You have to loop, but there are projects that can make it simpler.  Also, try not to use ArrayList, use List instead.
You can checkout FluentAdo for one:  http://fluentado.codeplex.com
    public IList<UserAccount> List()
    {
        var list = new FluentCommand<UserAccount>("SELECT ID, UserName, Password FROM UserAccount")
            .SetMap(reader => new UserAccount
            {
                ID = reader.GetInt("ID"),
                Password = reader.GetString("Password"),
                UserName = reader.GetString("UserName"),
            })
            .AsList();

        return list;
    }

A: If you read your SqlDataAdapter into a DataTable:
DataTable dt as DataTable;
dt.fill(data);

Then you can use some of the toys in System.Data.DataSetExtensions as referenced in Joel Muller's answer to this question.
In uses a bit of Linq, so you will net .Net 3.5 or higher.

A: var array = reader.GetValue("field_name") as long[];


text:
Q: Why is npm deleting my npm folder when trying to install gulp? I installed node into a "custom" directory:
 c:\Apache24\htdocs\node\

Everything is there.  When I run:
 $ npm install --global gulp-cli

like the docs suggest it appears to install.  Then, if I attempt:
 $ npm init

it gives me the errors:
                Error: Cannot find module 'C:\Apache24\htdocs\node\node_modules\npm\bin\npm-cli.
                js'
                    at Function.Module._resolveFilename (module.js:547:15)
                    at Function.Module._load (module.js:474:25)
                    at Function.Module.runMain (module.js:693:10)
                    at startup (bootstrap_node.js:191:16)
                    at bootstrap_node.js:612:3
                module.js:549
                    throw err;
                    ^

                Error: Cannot find module 'C:\Apache24\htdocs\node\node_modules\npm\bin\npm-cli.
                js'
                    at Function.Module._resolveFilename (module.js:547:15)
                    at Function.Module._load (module.js:474:25)
                    at Function.Module.runMain (module.js:693:10)
                    at startup (bootstrap_node.js:191:16)
                    at bootstrap_node.js:612:3

When I investigate I find that the npm folder ("c:\apache24\htdocs\node\node_modules\npm") is completely gone - erased, no longer there!  This also happens to me when just attempting to install plain gulp and not the gulp-cli.  Does anyone know why this could be happening?
I'm running windows 8.1.
Here is the package.json:
{
  "name": "my-project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "npm": "^5.6.0"
  },
  "devDependencies": {
    "gulp": "^3.9.1"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

A: have had issue with copy node module directory from one place to another to another before
What i did was
first of all
run npm init
and then npm install --global gulp-cli
that worked for me before


text:
Q: Remove duplicates but leave null fields I allready found part of the solution in the following thread:
Removing duplicate email address based on the lowest id in mysql
I have this MYSQL table that contains also email addresses from which i want the duplicates to be removed witch leaving the duplicate with the highest ID intact.
There are also many empty email-fields that should be ignored and thus preserved.
After that no duplicate entries should ever be allowed for the emailfield in the future.
How can i achieve this? My head is absolutely spinning over this and i can'figure it out.
I want to do this from within phpmyadmin since it should be a onetime operation only.
Coming from the following link: MySQL remove duplicates from big database quick
I tried:
create table tmp like yourtable;

alter table tmp add unique (text1, text2);

insert into tmp select * from yourtable
on duplicate key update text3=ifnull(text3, values(text3));

rename table yourtable to deleteme, tmp to yourtable;

drop table deleteme;

But that gave me a syntax error concerning the select * statement (3rd line).

A: Try :
insert into tmp (email) select X.email from ((SELECT email FROM yourtable WHERE LENGTH(email) = 0) UNION (SELECT email FROM yourtable WHERE LENGTH(email) > 0 GROUP BY email ORDER BY id DESC)) AS X;


text:
Q: How to create an object requires multiple bounded contexts? I will describe my problem with a very typical example, an e-commerce application.
Says we have to manage Products, and we have 2 bounded contexts Sales, and Warehouse that store the product information.
The Sales bounded context cares about price, product name, description.
The Warehouse bounded context cares about sizes, position, quantity, quality.
When we create a new product, we have to input all of the above information. Following the CQRS pattern, we have to send 2 commands Create Product to Sales and Warehouse bounded context, which could be 2 microservices.
The problem is, if the Product is created in Sales, but not valid to be created in Warehouse, or the command to Warehouse is not sent, then the Product in Sales does not make sense. The same goes with the reverse.
So how do you create an object, in this case, a product, that appears in multiple bounded contexts?

A: Product objects in two different bounded contexts should be usually seen as two different objects which share the same name "just by coincidence". Of course, this is not completely coincidentally, since both objects will be a representation of the same physical item, but those two Product classes can (and will) represent very different aspects of a real-world "product". This may go as far as storing  products in the warehouse by their quantity (one Product object represents multiple real-world items, counted by quantity), and storing products in Sales in a 1:1 manner to their real-world pendant.
So in each bounded context, there is a creation process for its own Product objects, implemented in some kind of Product factory. These processes should be completely independent from the other bounded context.
Now let's assume, for example, there is a use case "Advertise Product" from Sales, which checks if the product is available in the warehouse, and only creates the sales-related Product object when there is still a corresponding product in the warehouse. Then in the context of this use case, the related Product factory from Sales has to query Warehouse whether there are products of the give type in stock (this query may utilize a tempory warehouse Product object, which should be created by the Sales independent creation process). If the query to Warehouse fails, "Advertise Product" won't deliver any saled Products.
Same could work the other way round: say there is a use case "reorder products" from Warehouse, and for determining the reorder quantity, Warehouse needs to ask Sales how many advance bookings for a certain product are already there. Then the creation process of "reorder products" will issue a query for the related products from Sales. In case there will be nothing returned, "reorder products" won't create any warehouse Products for reordering, or maybe just fewer ones.
So in short:

*

*see Warehouse.Product and Sales.Product as different products, which can be created independently - hence the create commands should stay independent

*there may be certain use cases which forbid independend creation of a product object on one context if it is not available in the other - if so,  model and implement those use cases, for example, as a service, but don't try to stuff a whole use case implementation into a single creation command.


text:
Q: Need PHP code to store a JSONArray from android into a remote database My aim is to add the contents of the local database onto a remote database.
I am adding the contents of the database as a custom object into a JSONArray.
I am converting this JSONArray as string and Passing this string as POST parameter to the php page,but i am unable to write the php code to store this content in the database on the serverside.
Pls help me to write the PHP Code
Getting the data from the data base and storing into JSONArray
DataEntry d=new DataEntry(context);
JSONArray call_records=d.get();
String update_content=call_records.toString();
success= new GetUpdateStatus().execute(update_content).get();

get() method of DataEntry class
public JSONArray get() throws JSONException
    {
        JSONArray CallList = new JSONArray();

        String selectQuery = "SELECT  * FROM " + DATABASE_TABLE +";";
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst()) {
        do {
                CallRecord record = new CallRecord();
                record.setId(cursor.getInt(0));
                record.setCaller(cursor.getString(1));
                record.setReciever(cursor.getString(2));
                record.setMapUrl(cursor.getString(3));
                record.setTimeStamp(String.valueOf((cursor.getType(4))));

                CallList.put(record.getJSONObject());

            } while (cursor.moveToNext());
        }
        return CallList;
    }

CallRecord class:
public class CallRecord {
    //private variables
    int _id;
    String _caller;
    String _reciever;
    String _map;
    String _ts;
//This class has set and get methods for each variable.
}

The JSON Parser Code:
protected Integer doInBackground(String... a) {
        int success=0;
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("add",a[0]));
                JSONObject json = jsonParser.makeHttpRequest(
                               url_update, "POST", params);

and this:
if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

A: Did you try to get the raw POST data.
$post = file_get_contents('php://input');

A: using this you will get all post data as array in $data variable.
$data = json_decode(file_get_contents('php://input'), true);


text:
Q: Calculation coefficients of compositions I am working on practice problems for my combinatorics & optimization class and I'm having some issues figuring out how to approach a type of question. The textbook doesn't have any related examples and there aren't any answers, so I'm not sure what to do/if my thinking is correct.
The question asks to "Calculate the following coefficients:"
a) $[x^{8}](1-x)^{-7}$
b) $[x^{10}]x^{6}(1-2x)^{-5}$
c) $[x^{8}](x^3+5x^4)(1+3x)^{6}$
and so on. I listed 3 since they all have very different functions beside the exponent on the left. So my thinking was as follows:
The functions beside the $x$ in the bracket, call them $a(x), b(x), c(x)$ respectively, each form a generating series for some composition. So $a(x)$ is a composition with items from the set $A = \{1, 7, 49, 343, ...\}$ and $[x^8]$ represents the coefficient of $x^8$, ie I need to find the number of compositions that can be formed so that their sum adds up to 8 and so that each entry $c_i$ is in $A$. So the only possible compositions are $(1, 7)$ and $(7, 1)$, so the coefficient is 2.
Alternatively, still for a), I could take the approach wherein I try to find a recurrence relation, ie try to find some way to relate each term in the series $a(x)$. This I would do by seeing that $(1-x)^{-7} = \frac{1}{(1-x)^7}$ and $(1-7)^7 = 1 - 7x + 21x^2 - 35x^3 + 35x^4-21x^5+7x^6-x^7$ so for the coefficients $a_n$ in $a(x)$ one can find the recurrent relation $a_n = 7a_{n-1}-21a_{n-2}+35a_{n-3}-35a_{n-4}+21a_{n-5}-7a_{n-6}+a_{n-7}$ where $a_0 = 1$. Is this at all a correct way of going about it? If not, how should I approach this question?
That being said, I have no idea how to start b) and c). Using my approach above, with the recurrence relation, wouldn't seem to work since $b(x)$ has a numerator with a greater exponent than the denominator. Also, $c(x)$ isn't a fraction at all.
If anyone could please explain how to solve these questions/where my thinking goes wrong, I'd really appreciate it. Thanks!

A: You can use the binomial theorem for all of these.  The first is
$$
[x^8](1-x)^{-7}=(-1)^8\binom{-7}{8}=(-1)^8\frac{(-7)(-8)\ldots(-14)}{8!}=\binom{14}{8}.
$$
This can be interpreted as the number of ways of writing $8$ as the sum of seven non-negative integers, but the combinatorial interpretation is not needed to solve the problem.  For the others, I would go directly to the binomial theorem, without trying to interpret.


text:
Q: solr 4.4 integration with magento - plausible? Sorry to bring up a question that has already been answered on these forums. I have noticed there is a post on these forums clearly stating that magento 1.13 only supports solr 3.6.
I've informed my architect on this and even though the official line is clear he still wants me to investigate whether or not it is feasible to hack the solr config files to get 4.4 working with magento 1.13.
I understand where he is coming from as he is concerned about supportability of an old version of solr.
In people's opinions is hacking the solr config files to try and get 4.4 working with magento 1.13 a plausible theory? Or are there other factors at play that make this not possible at all?
thanks

A: Correct, 3.6 but you have more problems than that, 'hacking' core code is a techies way of trying to fix problems where the business side has not seen the necessity to fix the 'problem'. In a higher end environment, and as you are using Enterprise will have revenue in the $millions, you need to be taking a more business/technical centric approach.
Companies such as SAP have 7year cycles (Large Enterprise), Medium Enterprise will have 3.5year cycles, and Small Enterprise (which you will be in) will have 1.5-2year cycles, (Micro Enteprise have 9-12mth cycles - companies under $2million revenue per year). Basically you can run a version for 2years without needing to think about upgrading, meaning that Solr 3.6 is perfectly fine and as it will not be visitor accessed directly you can double the time.
Given the economy people are having a habit of 'finding' work. So, yes you can do it in theory from a technical perspective if you have plenty of time and patience, but from a business point of view it is pointless. It sounds like your architect is taking a Micro Enterprise approach.

A: The SOLR library being used for the Enterprise module is not that great IMO. There is another library called Solarium ( http://www.solarium-project.org/ ) that (in my experience) is a bit more robust and polished (and is also still actively maintained).
If you're capable, I would suggest writing your own module using this library instead (I am not aware of any pre-built modules using this library, other than what I have built). It will also require the installation of another module, https://github.com/magento-hackathon/Magento-PSR-0-Autoloader .
Benefits should be obvious. You learn how it works better. You can use SOLR 4 and newer (I'm currently running with 4.5.1). The library is actively maintained and has a community and support available.


text:
Q: See all autofill data In Google chrome when I start typing in a text box I get auto completion for things I have use din the past, this however is only for the current letter. Is there a way I can see all of the auto complete data Google Chrome has for this text box?

A: Google Chrome stores a lot of stuff in SQLite databases. To look at this data, download and run SQLite Browser.
The instructions are for Windows systems. On other platforms, use the location of user data directories specific to that OS.

*

*Open %LOCALAPPDATA%\Google\Chrome\User Data\Default\Web Data

*If Chrome is currently running, you won't be able to access the file, so first make a copy of it by running:
copy "%LOCALAPPDATA%\Google\Chrome\User Data\Default\Web Data" "%LOCALAPPDATA%\Google\Chrome\User Data\Default\WebData-working"

*Open WebData-working in SQLite Browser, switch to the Browse Data tab and select autofill from the Table dropdown list.


text:
Q: What is the radius of the circle in cm? The rectangle at the corner measures 10 cm  * 20 cm.
The  right bottom corner of the rectangle is also a point on the circumference of the circle.
What is the radius of the circle in cm?
Is the data sufficent to get the radius of circle?

A: Hint: with a coordinate system at the center of the circle, the point of intersection of the circle with the rectangle is $(10-r,r-20)$, so
$$
(10-r)^2+(r-20)^2=r^2.
$$
Note also, that to be in the situation imposed by the diagram, you must have $r>20$.

A: Let $R$ denote the radius, and let $w$ and $h$ be the width and the height of the rectangle.
Consider right triangle, formed by the center of the circle $O$, point where the rectangle touches the circle $A$ and the point $B$ - projection of $A$ on the horizontal diameter.
Then, by Pythagorean theorem:
$$ \begin{eqnarray}
     R^2 &=& (R-w)^2 + (R-h)^2 \\
     R^2 &=& 2 R^2 - 2 R(w+h) + w^2 + h^2
 \end{eqnarray}
$$
It remains to solve this quadratic equation, and choose the appropriate root (considering the special case of a square, when $w=h$, helps):
$$
    R = w + h + \sqrt{2 w h}
$$

A: $$r^2=x^2+y^2 \tag{1}$$
$r=y+20$ and $r=x+10$ therefore
$$y+20=x+10 \quad \mbox{then } \quad y=x-10 \tag{2}$$
Substitute $(2)$ into $(1)$
$$(r+10)^2=x^2+(x-10)^2$$
$$x^2+20x+100=x^2+x^2-20x+100$$
$$X^2=40x$$
$$x=40$$
Then substitute $x=40$ into $(2)$
$$y=40-10$$
$$y=30$$
substitute $x=40$ and $Y=30$ into $(1)$
$$r^2=(40)^2+(30)^2$$
$$r=50\rm{cm}.$$

A:
In the circle shown above the triangles $\triangle AGT$ and $\triangle TKX$ are similar.
We know $BC=10$ and $AG=20$
Let $CK=y$ and radius of the circle $BX=R$
In the similar triangles $\triangle AGT$ and $\triangle TKX$ we have,
$\frac{AG}{GT}=\frac{TK}{KX}$
$\frac{20}{10+y}=\frac{R-20}{R-(10+y)}$
i.e. $CK=y=10$
$GT=BK=BC+CK=10+10$
$AT=\sqrt{{AG}^2+{GT}^2}=20\sqrt{2}$
${TK}^2+{KX}^2={TX}^2$
$(R-20)^2+(R-20)^2={TX}^2$
TO BE CONTINUED


text:
Q: align my content according to div I have four columns with diff divs, the fourth column is hover. You have to mouseover the fourth column before the input bar shows up. My problem is, since the fourth column is hidden, the data on the first column goes to the fourth column. Help me with this. Here's my code: http://jsfiddle.net/kerokeroppi/DYvCz/
.branch_class {
    float:left;
    width:150px;
    padding:0 5px;
    margin-top:10px;
    font-size:12px;
    font-family:"Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, Verdana, sans-serif;
    color:#666;
       }

.branchid_class {
    float:left;
    width:150px;
    padding:0 5px;
    margin-top:10px;
    font-size:12px;
    font-family:"Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, Verdana, sans-serif;
    color:#666;
    }

.balance_class {
    float:left;
    width:100px;
    padding:0 5px;
    margin-top:10px;
    font-size:12px;
    font-family:"Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, Verdana, sans-serif;
    color:#666;
              }

.amount_class {
    float:left;
    width:150px;
    padding:0 5px;
    margin-top:10px;
    font-size:12px;
    font-family:"Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, Verdana, sans-serif;
    color:#666;
              }

and

Branch Name

Branch ID

Balance

Amount

     <form id="topupform-b1" action="" onSubmit="return false">

Mail and More-Hermosa

234

234.289

         <input type="string" name="amount" id="amount" style="margin-top:7px; margin-left:15px; background:#FFF;" />

image:

A: It looks like you're using the jQuery .hide() method. The hide() and show() methods modify the css display property.
.hide or display:none;, hides an element does not take up any space when it is hidden. What you want is visibility:hidden; which hides an element, but that element will still take up the same space it did before it was hidden.
If you want to do this with jQuery, try this:
$(selector).css('visibility', 'hidden');
$(selector).css('visibility', 'visible');


text:
Q: Adding class on hover I am having some issues adding a class on hover. I have the basics of it down, but my end result isn't what I am looking for.
On hover over profile-pic-container I am looking for the profile-pic-hover to only come up 30% of the height, from the bottom of profile-pic-container. Also I cannot figure out how to set the #profile-pic-change to display on this hover as well.
What am I doing wrong?

$('#profile-pic-container').hover(
       function(){ $(this).addClass('profile-pic-hover') },
       function(){ $(this).removeClass('profile-pic-hover') }
)
#profile-pic-container {
 position: relative;
 width: 200px;
  height: 200px;
  border: 1px solid black;
 cursor: pointer;
}
.profile-pic-hover {
 background: rgba(0, 0, 0, 0.5);
 height: 30%;
 width: 100%;
 bottom: 0;
}
#profile-pic-change {
  display: none;
  color: #fff;
}

Change picture

A: You need to add another rule to set it to be visible.
.profile-pic-hover #profile-pic-change {
  display: none;
  color: #fff;
}

but there is no reason to use JavaScript here simple :hover in the CSS and you can style the elements.

#profile-pic-container {
  position: relative;
  width: 200px;
  height: 200px;
  border: 1px solid black;
  cursor: pointer;
}
#profile-pic-container:hover {
  background: rgba(0, 0, 0, 0.5);
}
#profile-pic-change {
  display: none;
  color: #fff;
}
#profile-pic-container:hover #profile-pic-change {
  display: block;
}

Change picture

A: id selector is more specific than class selector, for overwrite the properties you can add the id selector to the class or add !important keyword:
#profile-pic-container {
    position: relative;
    width: 200px;
    height: 200px;
    border: 1px solid black;
    cursor: pointer;
}
#profile-pic-container.profile-pic-hover {
    background: rgba(0, 0, 0, 0.5);
    height: 30%;
    width: 100%;
    bottom: 0;
}
#profile-pic-change {
  display: none;
  color: #fff;
}

With !important:
#profile-pic-container {
    position: relative;
    width: 200px;
    height: 200px;
    border: 1px solid black;
    cursor: pointer;
}
.profile-pic-hover {
    background: rgba(0, 0, 0, 0.5);
    height: 30% !important;
    width: 100% !important;
    bottom: 0;
}
#profile-pic-change {
  display: none;
  color: #fff;
}

A: You can achieve this by using only CSS, with transition property. change profile pic link can be displayed using hover property

#profile-pic-container {
 position: relative;
 width: 200px;
  height: 200px;
  border: 1px solid black;
 cursor: pointer;
  transition: height 1s;
}
.profile-pic-hover {
 background: rgba(0, 0, 0, 0.5);
 height: 30%;
 width: 100%;
 bottom: 0;
}

#profile-pic-change {
  display: none;
  color: #fff;
}
#profile-pic-container:hover {
  height: calc(200px*(30/100));
  background: rgba(0, 0, 0, 0.5);
}
#profile-pic-container:hover #profile-pic-change {
  display: block;
}

Change picture


text:
Q: Address of minimum value in an array in C/C++ Just a week into C/C++. I have a function that takes a pointer to an array as an argument. Manipulating this input array inside the function results in a change in another (globally defined) array.
I need to find and return the address of the minimum value in this (globally defined) array of floats. In C++ I can do this relatively easily with std::min_element(), since this returns an iterator. Any way to do this in C? I can write a loop to find the minimum value in an array, but not sure how to access its address? Here'e the (pseduo)code.
globalArray[100] = {0}
float *DoSomething(float *array)
{
    if (conditionMet == 1)
        { Do something to array that modifies globalArray;}
    float min;
    min = globalArray[0];
    for (int i = 0; i <100; i++)
    {
         if (globalArray[i] < min)
            min = globalArray[i];
    }
    return &min;
}

A: You need to keep an extra variable around to track the index.
min = globalArray[0];
int minIndex = 0;
for (int i = 0; i <100; i++)
{
     if (globalArray[i] < min) {
        min = globalArray[i];
        minIndex = i;
     }
}
return &globalArray[minIndex];

Alternatively, you can use the extra variable to track the pointer.
min = globalArray[0];
float* minPointer = globalArray;
for (int i = 0; i <100; i++)
{
     if (globalArray[i] < min) {
        min = globalArray[i];
        minPointer = globalArray + i;
     }
}
return minPointer;


text:
Q: Java Casting Abstract Between Two Concrete Classes I am implementing a factory pattern to create two concrete classes in an abstract which has the factory methods overloaded (see below):
public abstract class User {
    ...
    public static User make(int id, String name) {
        return new Admin(id, name);
    }

    public static User make(int id, int student_id, String name) {
        return new Student(id, student_id, name);
    }
}

Here is the factory calls:
ArrayList<User> users = new ArrayList<>(
    Arrays.asList(
        User.make(1000, "Andy"),    // makes new Admin
        User.make(1001, 101001, "Bob")    // makes new Student
    )
);

Here is the Admin class:
public class Admin extends User {
    ...
    // constructor
    protected Admin(int id, String name) {
        super(id, name);
    }
    ...
}

Here is the Student class:
public class Student extends User {
    ...
    // constructor
    protected Student(int id, int student_id, String name) {
        super(id, name);
        this.student_id = student_id;
    }
    ...
}

Each of these concretes are placed into a User ArrayList. I have a function (below) which loops through the list and does runtime inference to call particular methods unique to each concrete; however I am getting a ClassCastException error in my IDE stating Admin cannot be cast to Student.
Full exception message is:
Exception in thread "main" java.lang.ClassCastException: presentation_layer.Admin cannot be cast to presentation_layer.Student
public class App {
    ...
    public static void main(String[] args) {
        ArrayList<User> users = new ArrayList<>(
            Arrays.asList(
                User.make(1000, "Andy"),        // makes new Admin
                User.make(1001, 101001, "Bob")  // makes new Student
            )
        );

        users.forEach((u) -> {
            if (u instanceof Admin)) {
                System.out.println("hello admin");
                ((Admin)u).anAdminFunc();
            } else if (u instanceof Student)) {
                System.out.println("hello student");
                ((Student)u).aStudentFunc();
            }
        });
    }
    ...
}

When I comment out the concrete method calls, the respective print statements output as expected with no errors; however, when trying to use these unique method calls between each loop iteration I get the casting error. Can you please advise how this can be addressed and what I am doing wrong, with either my approach at inference or my approach at a factory pattern?

A: use instanceof instead.
also, you might want to rethink your use of inheritance if you find yourself doing lots of casting

A: Try this:
    public static User make(int id, String name) {
      User user = new Admin(id,name);
      return user;
}

public static User make(int id, int student_id, String name) {
     User user = new Student(id, student_id, name);
     return user;
}

reference: parent-child type conversion


text:
Q: Would "fabricate" indicates "on bad purpose" or "on bad manners" in terms of meaning of "make up"? To give some background for a post (Should I use simple present or simple past in a tiny story to illustrate a scenario of the usage of some words?) I said

I made up a tiny story to illustrate a scenario of the usage of "just" in a post (In terms of meaning "recently", what is the difference between just & only?).

I was trying to use the word "fabricate" instead of "make up" though, I was worried "fabricate" indicates meaning like "on bad purpose" or "on bad manners", so I didn't choose it there.
So, would "fabricate" indicates meaning like "on bad purpose" or "on bad manners"?

A: "Fabricate" doesn't always have a negative meaning. Let's substitute it in your example sentence to see:

I fabricated a tiny story to illustrate a scenario of the usage of "just" in a post.

Here, the reader won't automatically assume some negative meaning in the word, mostly because it's hard to imagine how you making up a sentence to illustrate usage of "just" could be some nefarious thing.

However, in practice, the word usually is reserved for scenarios where you want to specifically imply that the person doing the fabricating did so for nefarious purposes. This is definition 1b in Merriam-Webster:

to make up for the purpose of deception

"Make up" sounds much more natural and is more colloquial for the example sentence you gave.