Q: Find out max divisor of a positive integer I need to find the biggest divisor of a positive integer and output it. Divisor should not be 1 or be equal to the integer itself. If it's a prime number the output should be "0". I have this code so far. However it doesn't work. It only works when I use "break" instead of "return 0" statement, but according to the task I should not use break :( How can I fix it? Thnx
#include <stdio.h>

int main() {
    int input, maxDiv;
    int div = 2;

    scanf("%d", &input);

    for ( ; div <= input/2; div += 1 ) {
        if ( input % div == 0 ) {
            maxDiv = input / div;
            return 0;
        } else {
            maxDiv = 0;
        }
    }

    printf("%d\n", maxDiv);

    return 0;
}

A: You can rewrite it this way
int main(){
    int input, maxDiv = 0;
    int div = 2;

    scanf("%d", &input);

    for(; !maxDiv; div++)
        if(!(input%div))
            maxDiv = input/div;

    printf("%d\n", ( maxDiv == 1 || input < 0 ? 0 : maxDiv ) );
    return 0;
}

It is an infinite loop that will exit as soon as maxDiv != 0. The complexity is O(sqrt (n)) as there is always a divisor of n less than or equal to sqrt(n), so the code is bound to exit (even if input is negative).
I forgot, you have to handle the case where input is zero.

A: Maybe you can declare a flag?
#include <stdio.h>

int main() {
    int input, maxDiv;
    int div = 2;
    char found = 0;

    scanf("%d", &input);

    for ( ; div <= input/2 && !found ; div += 1 ) {
        if ( input % div == 0 ) {
            maxDiv = input / div;
            found = 1;
        } else {
            maxDiv = 0;
        }
    }

    printf("%d\n", maxDiv);

    return 0;
}

A: You can stop the loop when you reach sqrt(input)... it's not that difficult to find a perfectly good integer sqrt function.
There's not a lot of point dividing by all the even numbers after 2.  In fact there's not a lot of point dividing by anything except the primes.  It's not hard to find the primes up to sqrt(INT_MAX) (46340, for 32-bit integer)... there are tables of primes freely available if you don't want to run a quick sieve to generate same.
And the loop...
  maxdiv = 0 ;
  i = 0 ;
  sq = isqrt(input) ;
  while ((maxdiv == 0) && (prime[i] < sq))
    {
       if ((input % prime[i]) == 0)
         maxdiv = input / prime[i] ;
       i += 1 ;
     } ;

assuming a suitable integer sqrt function and a table of primes... as discussed.

A: Since you are looking for the largest divisor, is there a reason you're not looping backward to 2? If there isn't, then there should be no need for a break statement or any special logic to exit the loop as you should keep looping until div is greater than input / 2, testing every value until you find the largest divisor.
maxDiv = -1;
for (div = input / 2;
     div >= 2 && maxDiv == -1;
     --div)
  {
    if (input % div == 0)
      maxDiv = div;
  }

maxDiv += (maxDiv == -1);

printf ("%d\n", maxDiv);

I added the extra condition of maxDiv being -1, which is like adding a conditional break statement. If it is still -1 by the end of the loop, then it becomes 0 because maxDiv += 1 is like writing maxDiv = -1 + 1, which is 0.
Without any jump statement such as break, this sort of test is what you must do.
Also, regarding your code, if I input 40, the if statement will be triggered when div is 2, and the program will end. If the return 0 is changed to a break, maxDiv will be 2, not 20. Looping backward will find 20 since 40/2=20, and 40%20==0.

A: Let us denote D to the max divisor of a given composite number N > 1.
Then, obviously, the number d = N / D is the min non-trivial divisor of N.
If d would not a primer number, then d would have a non-trivial divisor p < d.
By transitivity, this implies that p is a divisor of N, but this fact would contradict the fact that d is the min divisor of N, since p < d.

*

*So, d must be a prime number.

In particular, it is enouth to search over those numbers which are less than sqrt(N), since, if p is a prime number greater than sqrt(N) which divies N, then N / p <= sqrt(N) (if not, *p * (N / p) > sqrt(N)sqrt(N) == N, wich is absurd).
This shows that it's enough to do the search the least divisor d of N just within the range of primer numbers from 2 to sqrt(N).
For efficiency, the value sqrt(N) must be computed just once before the loop.
Moreover, it is enough a rough approximation of sqrt(N), so we can write:
   #include <math.h>
   #include <stdio.h>

   int main(void)
   {
      int N;
      scanf("%d",&N);

      // First, we discard the case in that N is trivial
      // 1 is not prime, but indivisible.
      // Change this return if your want.
      if (N == 1)
         return 0;
      // Secondly, we discard the case in that N is even.
      if (N % 2 == 0)
         return N / 2;

      // Now, the least prime divisor of N is odd.
      // So, we increment the counter by 2 in the loop, by starting in 3.

      float sqrtN = fsqrt(N); // square root of N in float precision.
      for(d = 3; d <= sqrtN; d += 2)
         if (N % d == 0)
            return N/d;

      // If the loop has reached its end normally,
      // it means that N is prime.

      return 0;
   }

I think that the problem is not well stated, since I consider that a better flag to signalize that N is prime would be a returned value of 1.
There are more efficient algorithms to determine primality, but they are beyond the scope of the present question.


Q: extract individual words from string c++ I am trying to make a C++ program that receives user input, and extracts the individual words in the string, e.g. "Hello to Bob" would get "Hello", "to", "Bob". Eventually, I will be pushing these into a string vector. This is the format I tried to use when designing the code:
//string libraries and all other appropriate libraries have been included above here
string UserInput;
getline(cin,UserInput)
vector<string> words;
string temp=UserInput;
string pushBackVar;//this will eventually be used to pushback words into a vector
for (int i=0;i<UserInput.length();i++)
{
  if(UserInput[i]==32)
  {
    pushBackVar=temp.erase(i,UserInput.length()-i);
    //something like words.pushback(pushBackVar) will go here;
  }
}

However, this only works for the first space encountered in the string.It does not work if there are any spaces before the word (e.g. if we have "Hello my World", pushBackVar will be "Hello" after the first loop, and then "Hello my" after the second loop, when I want "Hello" and "my".) How do I fix this? Is there any other better way to extract individual words from a string? I hope I haven't confused anyone.

A: See Split a string in C++?
#include <string>
#include <sstream>
#include <vector>

using namespace std;

void split(const string &s, char delim, vector<string> &elems) {
    stringstream ss(s);
    string item;
    while (getline(ss, item, delim)) {
        elems.push_back(item);
    }
}

vector<string> split(const string &s, char delim) {
    vector<string> elems;
    split(s, delim, elems);
    return elems;
}

So in your case just do:
words = split(temp,' ');

A: You can use the operator >> direct to a microbuffer (string) to extract the word. (getline is not needed). Take a look at the function below:
vector<string> Extract(const string& Text) {
    vector<string> Words;
    stringstream ss(Text);
    string Buf;

    while (ss >> Buf)
        Words.push_back(Buf);

    return Words;
}

A: #include <algorithm>        // std::(copy)
#include <iostream>         // std::(cin, cout)
#include <iterator>         // std::(istream_iterator, back_inserter)
#include <sstream>          // std::(istringstream)
#include <string>           // std::(string)
#include <vector>           // std::(vector)
using namespace std;

auto main()
    -> int
{
    string user_input;
    getline( cin, user_input );
    vector<string> words;
    {
        istringstream input_as_stream( user_input );
        copy(
            istream_iterator<string>( input_as_stream ),
            istream_iterator<string>(),
            back_inserter( words )
            );
    }

    for( string const& word : words )
    {
        cout << word << '\n';
    }
}

A: Here I have created a vector of words from the sentence.
#include<bits/stdc++.h>
using namespace std;
int main(){
string s = "the devil in the s";
string word;
vector<string> v;
for(int i=0; i<s.length(); i++){
    if(s[i]!=' '){
        word+=s[i];
    }
    else{
        v.push_back(word);
        if(i<s.length()+1)
            word.clear();
    }
}
v.push_back(word);
for(auto i:v){
    cout<<i<<endl;
  }
}


Q: Designing a database connection class in VS 2005 I am working on designing a SQL Server database connection class in VB.net 2005. The idea behind doing this will be so a developer can can call the class, pass it a stored procedure name along with the parameters, and get return values back (if any).
My question is, how would I design the class so the stored proc parameters are dynamic?
My second question is, how would I account for the data type being passed to the stored procedure?

A: This assumes SQL Server, but the SqlParameter type could be changed to match the connection type. As items are added to this list the data type would have to be identified.
    Imports System.Data.SqlClient
    Dim Params As List(Of SqlParameter)

    Public Property ParameterList() As List(Of SqlParameter)
        Get
            Return Params
        End Get
        Set(ByVal value As List(Of SqlParameter))
            Params = value
        End Set
    End Property

You'll have to loop through the list and add each parameter to a command object.


Q: clicking href on capybara I'm trying to tell Capybara/Cucumber to click on href  but failed trying different options. Here's the code:

      Option 1
      More

      Option 2
      More

   ...

1st attempt was to have find_link('More').click the "link".
within(all(.animation-visible.tile-animation.link-group.color-white.border-round.bg-primary.animated>a).[0]) do
    find_link('More').click
end

That didn't work. I've tried having it clicked straight away.
find(all('.animation-visible.tile-animation.link-group.color-white.border-round.bg-primary.animated>a')[0]).click

That didn't work either.
Just wondering if there's any other way to click Option 1? Or Option 2? These options need to be tested individually.

A: Assuming the elements are visible on the page (not sure what the animation classes on the h6 elements are actually doing) then your first attempt wont work because of the extra > a on the selector in the within - which means you're finding the a already and then saying inside that find another a.  Your second attempt won't work because find takes a selector type and selector (selector type defaults to css) to match against elements, but all returns an array of elements (you call either find to return one element or all to return multiple elements) - the following should work instead
within(all('.animation-visible.tile-animation.link-group.color-white.border-round.bg-primary.animated')[0]) do
  find_link('More').click
end

which is saying inside the first .animation-visible... matching element find a link with 'More' for its text and click it.  This could also be written
within(first('.animation-visible.tile-animation.link-group.color-white.border-round.bg-primary.animated', minimum: 1)) do
  click_link('More')
end

That is basically the same thing except the minimum: 1 option will make it wait until at least one matching element is on the page (good for if your previous call is #visit or the elements are loading via ajax
Note: you could use the minimum: 1 (or whatever number of elements you're expecting to appear on the page) on the first example too
The find_link calls suggested in the other answer won't work because find_link doesn't take a css selector, it takes a string to match against the text, id, or title of the link.  So the following would work
find_link('More', href: 'http://some.com/page1/').click

or
click_link('More', href: 'http://some.com/page1/')

A: Wouldn't these work?
First link
find_link("a[href$='page1/']").click

Second link:
find_link("a[href$='page2/']").click

Translation of the css selector:
  Find the link that ends with XXX


Q: PHP while() wrapping items I have this html code:

and I am looking for a way to implement it in my php while (wordpress).
The while is as
while ( have_posts() ) : the_post();
   echo '

';
endwhile;

I've tried a lot of stuff, but none have worked. I need to divide every 2 items and put them in a wrap
 after that the next 4 items in
 and after that the next 3 items in

I did a lot of searching, but I am not even sure what to search for.

A: A little crude but here's one solution
$i = 0; // Number of items made so far in the row
$mode = 0; // Current row type enumerated by $elem
$elem = array(2,4,3); // Enumeration of the desired row sizes
while ( have_posts() ) : the_post();
    // Make a new row when there's no items yet
    if ($i == 0) echo '
';
    echo '

';
    $i++;
    // Once the items in the current row has reached the row's maximum size
    if ($i % $elem[$mode] == 0):
        echo '
';
        $i = 0; // Reset items made for the row back to 0
        $mode = ($mode + 1) % 3; // Increment mode and wrap if necessary
    endif;
endwhile;
if ($i > 0) echo '
'; // Finish the last row if it wasn't finished

This is what the modulos was built for!


Q: How to display all projects in the Project View in PHPStorm? In eclipse / Zend Studio the project manager displays per default all projects of the workspace (or of one of its Working Sets, if selected):

Now I'm looking for the according configuration in PHPStorm, that shows only one project per window:

How can I see all my projects in the project view of the same window?

A: PhpStorm does not support multiple independent projects in one window / frame:
https://youtrack.jetbrains.com/issue/WI-15187 -- star/vote/comment to get notified on progress.

But ... you can list files from another project there (in Project View panel). If that is good enough, then just go to Settings | Directories and add desired folder as an Additional Content Root. P.S. This also means that the setting from current project will be applied to all content roots.


Q: How can I prevent RMySQL errors and show to user in Shiny? I have a Shiny App that executes a query to a MySQL database like this example:
UI
textAreaInput("query")

SERVER
data <- reactive({
  df<-dbGetQuery(conection, input$query)
  return(df)
})

The problem is that when the user types a wrong syntax in the textAreaInput the Shiny App closes and the error is shown in the R Console.
What I want is to print that error in the app so the user can try again and write another query.
Can someone help me please?

A: We can use tryCatch. Here is a complete example based on  @Fan Li's answer here
library(RSQLite)
con <- dbConnect(SQLite(), dbname="sample.sqlite")
dbWriteTable(con, "test", data.frame(value1 = letters[1:4], value2 = letters[5:8]))
dbDisconnect(con)

library(shiny)
library(RSQLite)
runApp(list(
  ui = bootstrapPage(
    #select * from te fail
    #select * from test work
    textAreaInput("query",'Query'),
    actionButton("action", label = "Run Query"),
    hr(),
    tableOutput("table")
  ),
  server = function(input, output){
    #Reactive is eager by definition and it will signal unreal/annoying errors, hence I used eventReactive
    data <- eventReactive(input$action,{
      tryCatch({
        con <- dbConnect(SQLite(), dbname="sample.sqlite")
        data<-dbGetQuery(con, input$query)
        dbDisconnect(con)
        return(data)
        },
               error = function(e){
                 showModal(
                   modalDialog(
                     title = "Error Occurred",
                     tags$i("Please enter valid query and try again"),br(),br(),
                     tags$b("Error:"),br(),
                     tags$code(e$message)
                   )
                 )
               })
    })
    output$table <- renderTable(data())
  }))


Q: How do I update my HTML Selects with ajax based on other Selects? I've got this search page with 7 different Selects and 2 textfields.
The data wich is stored in the selects is fetched from a MYSQL database.
Now when I make a choice, I want the other selects to update based on the choise I made.
This needs to be accomplished with Ajax. Can someone point me in the right direction?

A: collect the values of already filled selects, and send them to the server to obtain the filtered values list.
let's say you have an car manufacturer / model selector.
<select name="manufacturer">
 <option value="1">Acura</option>
 <option value="2">Audi</option>
 ...
</select>

<select name="model"></select>

the function to fill "model" select with values should look like this:
$.get('/get_models_by_manufacturer', {manuf: $('select[name=manufacturer']).val()}, function(data){
  // data returned by the server is expected to be html code of options NOT surrounded with <select>
  $('select[name=model]').html(data);
});

A: IF your're using jquery there is an discussion: http://forum.jquery.com/topic/how-to-reload-a-select-in-a-form-using-ajax-via-jquery


Q: EF Code first - many to many relation mapping table with extra columns I am having a User Model and and a Group Model.  User and Group share a many to many relationship. In when I translate this to table, I want to have a mapping table. I am using the following to achieve this.
modelBuilder.Entity<UserGroup>()
        .HasMany(a => a.Users)
         .WithMany(b => b.UserGroup)

         .Map(mc =>
         {

             mc.ToTable("UserUserGroupMapping");
             mc.MapLeftKey("UserId");
             mc.MapRightKey("UserGroupId");

         });

This creates a table with UserId and UserGroupId as columns. However I have few challenges,
I would like to be able to add an Identity column to this table and some audit columns (ex: Created by, created date) to the table. I am not sure how to do this.
Can any one help me here?
Thanks

A: I think it'll work if you do the following:

*

*Remove the configuration you showed in the code snippet above

*Add a mapping table and configure its table name to match the original table name.
// name this whatever you want
class UserUserGroupMapping
{
    public UserUserGroupMappingId { get; set; }
    public int UserId { get; set; }
    public virtual User User { get; set; }
    public int UserGroupId { get; set; }
    public virtual UserGroup UserGroup { get; set; }
    // other properties
}

modelBuilder.Entity<UserUserGroupMapping>()
    .HasKey(um => um.UserUserGroupMappingId)
    .ToTable("UserUserGroupMapping");

*Replace the many-to-many collection properties from User and UserGroup and replace it with one-to-many associations
class User
{
    // other properties
    // remove this:
    // public virtual ICollection<UserGroup> UserGroup { get; set; }
    public virtual ICollection<UserUserGroupMapping> UserGroupMappings { get; set; }
}

class UserGroup
{
    // other properties
    // remove this:
    // public virtual ICollection<User> Users { get; set; }
    public virtual ICollection<UserUserGroupMapping> UserMappings { get; set; }
}

modelBuilder.Entity<UserUserGroupMapping>()
    .HasRequired(um => um.UserGroup).WithMany(g => g.UserMappings)
    .HasForeignKey(um => um.UserGroupId);

modelBuilder.Entity<UserUserGroupMapping>()
    .HasRequired(um => um.User).WithMany(g => g.UserGroupMappings)
    .HasForeignKey(um => um.UserId);

*Use the package manager to Add-Migration and remove anything from the scaffolded migration that might attempt to drop the old table and create a new table. The migration will need to at least (I might be missing some here):

*

*DropPrimaryKey for the original key columns

*AddColumn for the new columns (with Int(identity:true, nullable: false) for the new primary key column)

*AddPrimaryKey for the new key column

Then you can use the methods outlined in this answer to retrieve entities.


Q: Does delete[] need to be called on the original pointer position According to answers in this question : "How does delete[] "know" the size of the operand array?"

your allocator will keep track of how much memory you have allocated

and

How free knows how much memory to deallocate"

Yes, the memory block size is stored "somewhere" by malloc (normally in the block itself), so that's how free knows. However, new[]/delete[] is a different story. The latter basically work on top of malloc/free. new[] also stores the number of elements it created in the memory block (independently of malloc), so that later delete[] can retrieve and use that number to call the proper number of destructors

Does this mean that delete[] is independent on where the pointer points to? Is the following code valid or will it result in memory leaks?
void createArray(){
    char* someArray = new char[20];
    readData(someArray);
    //Is this delete still valid after moving the pointer one position?
    delete[] someArray;
}

char readData(char* &arr){
    char value = *arr;
    //Let it point to the next element
    arr += 1;
    return value;
}

A: Yes it does. If you change a new[]-ed pointer value and then call delete[] operator on it you are invoking undefined behavior:
char* someArray = new char[20];
someArray++;
delete[] someArray; // undefined behavior

Instead store the original value in a different pointer and call delete[] on it:
char* someArray = new char[20];
char* originalPointer = someArray;
someArray++; // changes the value but the originalPointer value remains the same
delete[] originalPointer; // OK

A: You might be interested to know what new and delete really do under the covers (some licence taken, ignores exceptions and alignment):
template<class Thing>
Thing* new_array_of_things(std::size_t N)
{
  std::size_t size = (sizeof(Thing) * N) + sizeof(std::size_t);
  void* p = std::malloc(size);
  auto store_p = reinterpret_cast<std::size_t*>(p);
  *store_p = N;
  auto first = reinterpret_cast<Thing*>(store_p + 1);
  auto last = first + N;
  for (auto i = first ; i != last; ++i)
  {
    new (i) Thing ();
  }
  return first;
}

template<class T>
void delete_array_of_things(Thing* first)
{
    if (first)
    {
        auto store_p = reinterpret_cast<std::size_t*>(first) - 1;
        auto N = *store_p;
        while (N--)
        {
            (first + N)->~Thing();
        }
        std::free(store_p);
    }
}

Summary:
The pointer you are given is not a pointer to the beginning of the allocated memory. The size of the array is stored just before the memory that provides storage for the array of objects (glossing over some details).
delete[] understands this and expects you to offer the pointer that was returned by new[], or a copy of it.

A: General rule is that you can delete only pointers you got from new. In an non-array version you are allowed to pass a pointer to base class subobject created with new (granted the base class has virtual destructor). In case of array version, it must be the same pointer.
From cppreference

For the second (array) form, expression must be a null pointer value or a pointer value previously obtained by an array form of new-expression. If expression is anything else, including if it's a pointer obtained by the non-array form of new-expression, the behavior is undefined.


Q: Android calendarview font size I am using Xamarin for building android application this is my first app. I have a CalendarView I need to change the font size and style of the day.
I tried the below code the font color changed but the size is too small. The minimum API level is 11 and target API level is 16. I am using galaxy note 2 for testing.
<style name="Widget.CalendarView.Custom" parent="@android:style/Widget.CalendarView">
    <item name="android:focusedMonthDateColor">@color/gray</item>
    <item name="android:weekDayTextAppearance">@android:style/TextAppearance.Medium</item>
    <item name="android:dateTextAppearance">?android:attr/textAppearanceLarge</item>
    <item name="android:selectedWeekBackgroundColor">@android:color/transparent</item>
</style>

A: All you need to do is reference a different style that includes a slightly bigger font for the size of the date. I'm not exactly sure why yours isn't working using the styles.xml as it seems correct. However I would just simply add it to the XML attributes for the calendar. This will be fine as presumably you're only using one Calendar and therefore it isn't really inefficient. Add this line to the calendar XML:
android:dateTextAppearance="@android:style/TextAppearance.Large"

Hope this helps you!

A: You should change "android:dateTextAppearance", you can check this reference too ;)
CalendarView
also you can try this
Style will save the world!


Q: How to know most used procedure in my database? I completed my project, there are many procedures used and now I got the job to find the mostly used procedure and there average execution time.
In this way I know what are the procedures I need to tune first?
It there any way to get procedure execution history for a particular database?

A: I believe you can use the sys.dm_exec_query_stats dynamic management view.  There are two columns in this view called execution_count, and total_worker_time that will help you.
execution_count gives the total number of times the stored procedure in question was executed since the last time it was recompiled.
total_worker_time gives the total CPU time in milliseconds that was spent executing this stored procedure since the last time it was recompiled.
Here is an MSDN link:
http://msdn.microsoft.com/en-us/library/ms189741.aspx

A: You can use dm_exec_cached_plans to look for the stored procedures that have been compiled into query plans.  The function dm_exec_query_plan can be used to retrieve the object id for a plan, which in turn can be translated into the procedure's name:
select  object_name(qp.objectid)
,       cp.usecounts
from    sys.dm_exec_cached_plans cp
cross apply
        sys.dm_exec_query_plan(cp.plan_handle) qp
where   cp.objtype = 'Proc'
order by
        cp.usecounts desc

A: I think you want to check SQL Server Profiler for this.
You can check the details in MSDN and other places as well.
But, before using it in production server, you need to keep in mind that:
 Profiler adds too much overhead to production server. So, first check when your site has less no of hits, and go ahead.

A: This is what the SQL Server Profiler is for. With it you can keep track of query run count, execution time, etc.


Q: Email sending from ASP.net fails on IIS server I have implemented email service in my ASP.net application, and am using SmtpClient class to send email. The mail sending works perfectly fine from my local code, however it throws exception when published on the server.
The code is pretty basic, as below:
var message = new MailMessage();
message.To.Add(new MailAddress(recipientEmail));
message.Subject = subject;
message.Body = emailBody;

using (var smtp = new SmtpClient())
{
    smtp.Credentials = new NetworkCredential(EmailSettings.Username, EmailSettings.Password);
    smtp.Host = EmailSettings.Host;
    smtp.Port = EmailSettings.Port;
    smtp.EnableSsl = true;
    await smtp.SendMailAsync(message);
}

The exception which is being thrown is as follows:
"Syntax error, command unrecognized. The server response was: "


Q: Using struct in a switch statement I'm trying to create a struct that can be used in a switch statement. I'm using a bunch of wierd compilers like keil armcc and old-fashioned gcc 4.7.1.
That also means c++11 is not an option.
For some time this idea actually worked:
struct Test
{
    const int a;

    Test() : a(1) {}

    template<typename T>
    operator T() const;

    operator int() const {return a;}

};

...

Test t;

switch(t)
{
case 1:
    break;
}

That compiled just fine. Now I'm trying to move to more recent version of gcc without breaking compatibility with armcc.
But now gcc gives me this:
error: ambiguous default type conversion from 'Test'
 switch(t)
         ^
error:   candidate conversions include 'template<class T> Test::operator T() const'

And I can't really understand where is the ambiguity since template operator has no body.
Is there any way to fix this?

A: You could assign to a temporary int:
int n = t;
switch (n) {
   ...
}

In the context of switch (t), the compiler considers coercion to integer types including int, unsigned int, long.  By assigning to a variable of type int, we collapse the wave function force it to pick the conversion we want, and there's no ambiguity when we get to the switch.
You should also seriously consider making your template conversion operator explicit if you can, as a catch-all conversion can lead to unpleasant surprises.

A: switch(t)
{
case 1:
    break;
}

Here the compiler doesn't know what conversion operator to call; it's ambiguous. It could instantiate your templated conversion operator for a few different integral types or call your int conversion operator. The fact that the templated conversion operator function is undefined doesn't matter to overload resolution.
The simplest solution is to use switch (static_cast<int>(t)).


Q: How to fail a cucumber scenario In my scenario, i need to validate if there exists 10 objects in a page.
If any of the object doesn't exists, then the step should be failed and eventually the scenario should also be reported as failed, but the script execution should continue to validate the remaining object exists.
I know scenario.getStatus()give if the scenario is failed, but how can i set the status of the scenario to failed? Importantly the script execution should continue afterwards.

A: Depending on the testing framework you are using junit or testng you can use the concept of soft assertion. Basically it will collect all the errors and throw an assertion error if something is amiss.
To fail a scenario you just need an assertion to fail, no need to set the status of the scenario. Cucumber will take care of that if an assertion fails.
For testng you can use the SoftAssert class - http://testng.org/javadocs/org/testng/asserts/SoftAssert.html You will get plenty tutorials for this. Call to doAssert will trigger of the verification of all stored assertions.
For junit you can use the ErrorCollector Rule class -
http://junit.org/junit4/javadoc/4.12/org/junit/rules/ErrorCollector.htmlenter link description here As cucumber does not support @Rule annotation, you need to inherit from this class and override the verify property to change its modifier to public in place of protected. Create an instance of the new class and add the assertions. Call to verify method will start the verification.

A: QAF provides assertion and verification concepts, where on assertion failure scenario exited with failed status and in case of verification scenario continue for next step and final status of step/scenario is failed if one or more verification failure.
You also can set step status failure using step listener which result in test failure. With use of step listener, you also can continue even step failure by converting exception to verification failure.

A: It is not a good idea to continue executing steps after a step failure because a step failure can leave the World with an invariant violation. A better strategy is to increase the granularity of your scenarios. Instead of writing a single scenario with several "Then" statements, use a list of examples to separately test each postconditions. Sometimes a scenario outline and list of examples can consolidate similar stories. https://cucumber.io/docs/reference#scenario-outline
There is some discussion about adding a feature to tag certain steps to continue after failure. https://github.com/cucumber/cucumber/issues/79
There are some other approaches to continuing through scenario steps after a failure here: continue running cucumber steps after a failure


Q: WordPress add_action style arguments works but changes admin panel I've made a code so you can easily add a style sheet to the site, this is for our framework.
It works but if I use this the CSS changes the dashboard layout either? Same with customizer, if I don't use this method, but just a normal wp enqueue it works but that's not what I want.
    class theme_setup{
        function main_css_setup($css) {
            wp_enqueue_style( 'style', get_template_directory_uri().'/css/'.$css.'.css' );
        }
        function add_css_main($css){
            add_action( 'wp_enqueue_scripts', array($this, 'main_css_setup'),10,1 );
            do_action( 'wp_enqueue_scripts', $css );
        }
    }
$theme_setup = new theme_setup();
$theme_setup->add_css_main('main');

Dashboard change:
First example
Second example
I think it has something to do with the do_action, I searched on my best behave, but without any luck.
I'm using the 'do_action' to pass the argument that the user gives with the add_css_main, I know I can use global variables, but these are "static", and that will make the idea be gone of a flexible function.

Update:

function themename_custom_logo_setup($height,$width) {
    $defaults = array(
        'height'      => $height,
        'width'       => $width,
        'flex-height' => true,
        'flex-width'  => true,
        'header-text' => array( 'site-title', 'site-description' ),
    );
    add_theme_support( 'custom-logo', $defaults );
}

    function add_custom_logo($width,$height){
    add_action( 'after_setup_theme', array($this, 'themename_custom_logo_setup' ),10,2);
    do_action( 'after_setup_theme', $height,$width);
}

$theme_setup->add_custom_logo(88,250);

Does work, but the variables are not even passed at al.

A: This should avoid loading the CSS with this conditional (maybe apply it somewhere else in your code):
function add_css_main($css){
    if( !is_admin() ) {
        add_action( 'wp_enqueue_scripts', array($this, 'main_css_setup'),10,1 );
        do_action( 'wp_enqueue_scripts', $css );
    }
}


Q: E/AndroidRuntime: FATAL EXCEPTION: main PID: 5112 Hy
I am new to Android / Java is I am facing a BMO problem
I code it but it does not work
an idea ??
thank you
<string name="onCreate_Go">onCreate Go</string>

            <TextView
            android:id="@+id/scrollTxt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="18sp" />

import android.widget.TextView;

private  final TextView txt = (TextView) this.findViewById(R.id.scrollTxt);
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    txt.setText(R.string.onCreate_Go);
}

5112-5112/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: com.gmail.test1, PID: 5112
                                                 java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.gmail.test1/com.gmail.test1.MainActivity}: java.lang.NullPointerException
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
                                                     at android.app.ActivityThread.access$800(ActivityThread.java:135)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:136)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5017)
                                                     at java.lang.reflect.Method.invokeNative(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:515)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
                                                     at dalvik.system.NativeStart.main(Native Method)
                                                  Caused by: java.lang.NullPointerException
                                                     at android.support.v7.app.AppCompatDelegateImplBase.(AppCompatDelegateImplBase.java:117)
                                                     at android.support.v7.app.AppCompatDelegateImplV9.(AppCompatDelegateImplV9.java:149)
                                                     at android.support.v7.app.AppCompatDelegateImplV11.(AppCompatDelegateImplV11.java:29)
                                                     at android.support.v7.app.AppCompatDelegateImplV14.(AppCompatDelegateImplV14.java:54)
                                                     at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:202)
                                                     at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:183)
                                                     at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:519)
                                                     at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
                                                     at com.gmail.test1.MainActivity.(MainActivity.java:13)
                                                     at java.lang.Class.newInstanceImpl(Native Method)
                                                     at java.lang.Class.newInstance(Class.java:1208)
                                                     at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
                                                     at android.app.ActivityThread.access$800(ActivityThread.java:135)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:136)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5017)
                                                     at java.lang.reflect.Method.invokeNative(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:515)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
                                                     at dalvik.system.NativeStart.main(Native Method)
02-16 16:41:21.634 5112-5112/? I/Process: Sending signal. PID: 5112 SIG: 9

A: Please add your Activity in your  AndroidManifest.xml. like below code:
<activity android:name=".activities.MainActivity"/>

Also put the findViewById() after setContentView() so it can actually return something other than null.

A: You can't initialize the textView before call "setContentView" method. I recommend you create a "init" method where initialize all layout's elements and call it after "setContentView"


Q: How can I upload a file to a GitHub Codespaces environment? I use GitHub Codespaces, but I don't know how to upload a single file to GitHub Codespaces without the assistance of, for example, github.

A: Simple Drag and Drop has worked for me.
To update the answer, there is now also an update option if you right click in the explorer view:

A: I was able to transfer a ton of training data from firebase to a codespace using firebase-admin.
in the codespace terminal:
pip install firebase-admin
pip install --ignore-installed <other firebase-admin dependencies>
run whatever script you use to download things from firebase

note that there are storage limits


Q: How not to remove first number in the sentence and remove later occurances of numbers in Python? I have a sentence that consists of numbers and words. I am looking for a solution to remove numbers except at the beginning. I have tried the following code, but it's removing all the numbers.
x = '45 is fourth five 45 when 9 and 5 are multiplied'

re.sub('\d', '', x)

Its output was
'is Fourth five when and are multiplied'

But need the output in the following manner.
'45 is Fourth five when and are multiplied'

Note:

*

*The number may or may not present at the beginning.

*Inside the sentence, there can be alphanumeric (460KG), then it should be changed (KG). That means, except at the beginning, the number should be removed elsewhere.
example :
6-apples price is 56Rs

I need an output as
6-apples price is Rs

A: You can use this:
x = '45 is fourth five 45 when 9 and 5 are multiplied'

string = re.sub(r'(?<!^)\b\d+\s', '', x)

Result:
>>> print(string)

45 is fourth five when and are multiplied

A: Using Pypi regex library, you can do:
import regex

x = '45 is fourth five 45 when 9 and 5 are multiplied'
print regex.sub(r'(?<=\D*\d+\D+)\d+ ?', '', x)

Output:
45 is fourth five when and are multiplied

Explanation:
(?<=        # positive lookbehind, make sure we have before:
    \D*         # 0 or more non digits
    \d+         # 1 or more digits
    \D+         # 1 or more non digits
)           # end lookbehind
\d+         # 1 or more digits
 ?          # optional space


Q: Eclipse Marketplace hangs (Luna, Java8) My newly installed Eclipse Luna hangs when I launch Marketplace. I tried to move my workspace out of the way, clean everything, re-install and start fresh.
It would still hang and has to be killed -9.  I saved the stack trace (as well as versions of the OS, Java, and Eclipse) at https://gist.github.com/c51821cbd4e676cd7c9f
The funny part is, things go just fine if I switch back Java1.7.0_25.  I'd like to use Java8 though.
Is that a known problem and are there ways around it?

A: I would try to un-install and install again the Java8 JDK. Have you tried that?
Have you got multiple JDK installed? If yes try with just Java8 (un-install the others).
Or try also to run eclipse with
eclipse -vm c:\java8path\jre\bin\javaw.exe

or
eclipse -vm c:\java8path\jre\bin\client\jvm.dll


Q: Resampling of MultiIndex I would like a daily breakdown of a dataset by type.  There are not records for every day for every type, where they don't exist I would like NaN.
I'm able to get a 'resampled to daily' result, but the type is ommitted.
The code below should be a fully working example (well, working apart from the known error at the end!):
import pandas as pd
import datetime as dt

df = pd.DataFrame({
    'Date': [dt.datetime(2021,1,1), dt.datetime(2021, 1, 3), dt.datetime(2020,1,2)],
    'Type': ['A', 'A', 'B'],
    'Value': [1,2,3]
})

df.set_index('Date', inplace=True)
#   this loses the 'type'
print(df.resample('1D').mean())

df = df.reset_index().set_index(['Date', 'Type'])

#   this raises an exception "TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'MultiIndex'"
print(df.resample('1D').mean())

Output I'm looking for is a row for every day / type combo:

date
type
value

20210101
A
1

20210102
A
NaN

20210103
A
2

20210101
B
NaN

20210102
B
3

20210103
B
NaN

Any advice or pointers gratefully received.

A: If need resample per groups is possible use Grouper for resample per days and then for add missing values is used Series.unstack with DataFrame.stack:
df = (df.groupby(['Type', pd.Grouper(freq='1D', key='Date')])['Value']
        .mean()
        .unstack()
        .stack(dropna=False)
        .reset_index(name='Value')

      )
print (df)
  Type       Date  Value
0    A 2021-01-01    1.0
1    A 2021-01-02    NaN
2    A 2021-01-03    2.0
3    B 2021-01-01    NaN
4    B 2021-01-02    3.0
5    B 2021-01-03    NaN

If need only append missing datetimes per groups is used DataFrame.reindex:
mux = pd.MultiIndex.from_product([df['Type'].unique(),
                                  pd.date_range(df['Date'].min(), df['Date'].max())],
                                  names=['Date','Type'])
df = df.set_index(['Type','Date']).reindex(mux).reset_index()
print (df)
  Date       Type  Value
0    A 2021-01-01    1.0
1    A 2021-01-02    NaN
2    A 2021-01-03    2.0
3    B 2021-01-01    NaN
4    B 2021-01-02    3.0
5    B 2021-01-03    NaN


Q: Bootstrap carousel image height change according to sm md sx lg The issue is quality of  image at smaller screens i.e 320px 375px 425px gets blur as i mention height in the class.. I am mentioning the height as i want the image to fit screen initially without user needing to scroll down to look for further information
My question here is should i resize the image so that it has quality in it..
Am sharing my code
 CSS
'
.carousel{
    background-color: #2f4357;

}
.carousel .item img{
    margin: 0 auto;
    height:570px;/* Align slide image horizontally center */
}
.bs-example{
    margin: 20px;
}

'
html
    '

'

A: You do not need to set any height or width to images in Bootstrap carousel if you are using them as img source. You need to add height only if you are using them as a background image. For this, you need to add height to .item class and set the background properties for the same.


Q: handling page orientation change in Xamarin When using Xamarin, what is the best or most accepted method of handling changes in orientation?
I have a carousel page which rotates through 5 content pages (the same page, just different text/images), in the content pages I have a 6 row grid, each row containing either an image, text or a button.
When changing from portrait to landscape I reset the size and padding of these within OnSizeAllocated. This seems to work randomly for 3 out of 5 content pages, the text in the other 2 will be out of position, and it's not always the same 3 that work either.
I'm guessing there's a better way to do this than manually resize things?
protected override void OnSizeAllocated(double width, double height)
        {
            base.OnSizeAllocated(width, height); //must be called
            if (this.width != width || this.height != height)
            {
                this.width = width;
                this.height = height;
                //reconfigure layout
                if (width > height)
                {
                    img.HeightRequest = 62.5;
                    img.WidthRequest = 62.5;
                    logo.HeightRequest = 52.5;
                    logo.WidthRequest = 142.27;
                    headerStack.Padding = new Thickness(0, -60, 0, 0);
                    txtStack.Padding = new Thickness(20, -60, 20, 0);
                    sIndicator.Padding = new Thickness(20, 0, 20, 100);
                    sButton.Padding = new Thickness(0, -40, 0, 0);
                }
                else
                {
                    img.WidthRequest = 250;
                    img.HeightRequest = 250;
                    logo.HeightRequest = 70;
                    logo.WidthRequest = 189.7;
                    headerStack.Padding = new Thickness(20, 40, 20, 0);
                    txtStack.Padding = new Thickness(20, 0, 20, 0);
                    sIndicator.Padding = new Thickness(20, 25, 20, 0);
                }
            }
        }

A: With a few tweaks to what I was setting I got this working just fine, would still be interested in other peoples' views on how they do it.


Q: Function to show result in multiple divs I need to make this script to print the result (true, or false) for the transparency of the image in the divs according to the area if its transparent or not.
Here is the example where I can see the result if its transparent but only on mouse move and for pixel by pixel according to the pointer.
https://jsfiddle.net/kdichev/0jhazjoa/
Here i have put a overlay over the image with 1/10 of the size square divs which I would like to change colors depending if they have transparent pixels in their area or not
https://jsfiddle.net/kdichev/ae9pjstm/1/
Ideally if there is one pixel below the box it should have a red background color or print in it false.
(function () {
var img = new Image(),
    output = document.getElementById('transparent'),
    bImg = document.getElementById('img');
img.src = bImg.src;

function isTransparent(e) {
    var x = e.pageX - this.offsetLeft,
        y = e.pageY - this.offsetTop;

    var canvas = document.getElementById('imgcheck-canvas') || (function (_this) {
        var e = document.createElement('canvas');
        e.setAttribute('width', _this.width);
        e.setAttribute('height', _this.height);
        e.setAttribute('id', _this.id + '-canvas');
        e.setAttribute('style', 'display:none;');
        document.body.appendChild(e);
        var cx = e.getContext('2d');
        cx.drawImage(_this, 0, 0, _this.width, _this.height);
        return e;
    })(this);
    if (canvas.getContext === undefined) {
        return false;
    }
    var ctx = canvas.getContext('2d');

    output.innerHTML = ((ctx.getImageData(x, y, 1, 1).data[3] === 0) ? true : false);
}

function init() {
    console.log('init');
    bImg.addEventListener('mousemove', isTransparent, false);
}

img.addEventListener('load', init, true);

})();


Q: Object.entries and addEventListener I have this object and I want to display the key in the options that gets created and the value in the .info
 tag. I then want to change the info text, when I change the city by using an addEventListener.
My question is, is it possible to use the info in for(const [city, info] of entries) in a addEventListener function? I tried to have the eventListener in the for loop but that didn't work out right. But can I somehow pass the info to another function? Or is it better too just loop the keys and then do another loop for the values in an addEventListener function?

let citiesWithInfo = {"New York": 'The biggest city in the world.',
    "Los Angeles": 'Home of the Hollywood sign.',
    "Maui": 'A city on the beautiful island of Hawaii.',
    "Vancover": 'It\'s a city where it rains alot. And I mean alot.',
    "Miami": 'The samba city of the world.'
};

const cityWithInfoPrompt = document.querySelector('#cities-with-info');
const entries = Object.entries(citiesWithInfo);

for(const [city, info] of entries) {
    let optionCity = document.createElement("option");
    optionCity.textContent = city;
    optionCity.value = city;
    cityWithInfoPrompt.appendChild(optionCity);

    let currentCity = cityWithInfoPrompt.options[cityWithInfoPrompt.selectedIndex];
    if(currentCity.textContent == city) {
        document.querySelector(".info").textContent = info;
    }
}

    <select name="cities-with-info" id="cities-with-info"></select>

Info:

A: You can attach the event outside the loop where you can match the value between the selected value and the object property name:

let citiesWithInfo = {"New York": 'The biggest city in the world.',
    "Los Angeles": 'Home of the Hollywood sign.',
    "Maui": 'A city on the beautiful island of Hawaii.',
    "Vancover": 'It\'s a city where it rains alot. And I mean alot.',
    "Miami": 'The samba city of the world.'
};

const cityWithInfoPrompt = document.querySelector('#cities-with-info');
const entries = Object.entries(citiesWithInfo);

for(const [city, info] of entries) {
    let optionCity = document.createElement("option");
    optionCity.textContent = city;
    optionCity.value = city;
    cityWithInfoPrompt.appendChild(optionCity);
}

cityWithInfoPrompt.addEventListener('change', function(){
  let currentCity = this.options[this.selectedIndex].value;
  document.querySelector(".info").textContent = citiesWithInfo[currentCity];
});
// On page load
// Create event
var event = new Event('change');
// Dispatch the event
cityWithInfoPrompt.dispatchEvent(event);

    <select name="cities-with-info" id="cities-with-info"></select>

Info:

Solution using  Arrow Function (() => {}) and Event.target

let citiesWithInfo = {"New York": 'The biggest city in the world.',
    "Los Angeles": 'Home of the Hollywood sign.',
    "Maui": 'A city on the beautiful island of Hawaii.',
    "Vancover": 'It\'s a city where it rains alot. And I mean alot.',
    "Miami": 'The samba city of the world.'
};

const cityWithInfoPrompt = document.querySelector('#cities-with-info');
const entries = Object.entries(citiesWithInfo);

for(const [city, info] of entries) {
    let optionCity = document.createElement("option");
    optionCity.textContent = city;
    optionCity.value = city;
    cityWithInfoPrompt.appendChild(optionCity);
}

cityWithInfoPrompt.addEventListener('change', () => {
  let currentCity = event.target.value;
  document.querySelector(".info").textContent = citiesWithInfo[currentCity];
});
// On page load
// Create event
var event = new Event('change');
// Dispatch the event
cityWithInfoPrompt.dispatchEvent(event);

    <select name="cities-with-info" id="cities-with-info"></select>

Info:

A: I used this code for the addEventListener to get the info from the object to the info HTML tag.
cityWithInfoPrompt.addEventListener("change", (e) => {
    let selectedCity = e.target.value
    for(const [city, info] of entries) {
        if(selectedCity == city) {
            document.querySelector(".info").textContent = info;
        }
    }
});


Q: How to integrate git hooks with eclipse I am trying to setup pre-commit hook which we have customized to our requirement .
It is working fine in git bash but it is unable to pick up the hook from eclipse .
How can I integrate or configure so the pre-commit hook gets invoked.


Q: Is there a way to include both WICTextureLoader and DDSTextureLoader without 'redefinition' errors? I'm trying to load a DDS texture. For that, I'm using DDSTextureLoader11 provided by DirectXTex. I already am using another texture loader from the same library - WICTextureLoader11.
The problem is, I don't get errors with WICTextureLoader11, however I do get errors either when including only DDSTextureLoader11, or when I use both of them.
This is some of the errors I get when I include both or only DDSTextureLoader11:
/WICTextureLoader11.cpp:51:17: error: redefinition of 'SetDebugObjectName'
/WICTextureLoader11.cpp:273:17: error: redefinition of 'MakeSRGB'
/WICTextureLoader11.cpp:747:17: error: no matching function for call to 'SetDebugObjectName'
/DDSTextureLoader.h:156:35: error: redefinition of default argument
I first thought that it was because both WICTextureLoader and DDSTextureLoader contain same functions, so when including both they "overlap" (i.e. compiler detects redefinition).
I'm using a batchfile to compile my project, where I link against both DirectXTex and DirectXTK. I also tried to include DDSTextureLoader, but without success: I've read the GitHub page of the DirectXTK's DDSTextureLoader, where I include <DDSTextureLoader.h> that gives me a link error, which I guess is related to the incorrect call of the function CreateDDSTextureFromFile, so right now I'm trying to find a way to make the right call to the function.
Edit: no, it seems like I'm making the right function call. The wrong thing is that I'm trying to include DDSTextureLoader.h, but it also wants DDSTextureLoader.cpp. However, the errors occur when I include DDSTextureLoader.cpp, such as:
'DDSTextureLoader.cpp': call to 'BitsPerPixel' is ambiguous -> 'DirectXTex.h' or 'DDSTextureLoader' error: redefinition of 'SetDebugTextureInfo', previous definition in 'WICTextureLoader'.
I think, what I need is to include the .cpp file, but somehow get rid of the errors.
Edit2: So far, I tried to get rid of DirectXTex (I don't remember why I even needed it), and I've included WICTextureLoader.cpp and DDSTextureLoader.cpp. I downloaded and built the DirectXTK library, then included #pragma comment(lib, "directxtk.lib"). Now, the weird thing is: when I compile with Clang++, it doesn't throw any errors (but the program crashes after a second-long gray screen), however when I compile with cl (through vcvars64), I get fatal error LNK1104: cannot open file 'directxtk.lib'.
Edit3: Wait, I don't even know why I even need the directxtk.lib. So I removed it, and it compiles, but nothing works. I thought I needed that static library to resolve external symbol errors when trying to include the header (XXXTextureLoader.h), instead of the source (XXXTextureLoader.cpp).
Edit4: Wait,wait,wait. I think, I'm going crazy. Now, if I include only WICTextureLoader.cpp (and remove DDSTextureLoader.cpp), it gives me this error: (directxtk.lib) mismatch detected for 'RuntimeLibrary': value 'MD_DynamicRelease' doesn't match value 'MT_StaticRelease'. I don't know why I did that, but I'm crazy now, I blindly brute-force my way through resolving this cursed issue. Why can't I just throw both headers in my directory and just simply include them? Is there a way to do so? What should I do? Why doesn't DirectXTK/Tex pages on GitHub give a step-by-step guide to how to use these things? The examples drive me crazy!
Please, help me resolve this what seems to be a simple issue.
Edit5: The last thing that I tried is to include DDSTextureLoader.h and WICTextureLoader.h, and use directxtk.lib, but it gives me these errors:
directxtk.lib(DDSTextureLoader.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MD_DynamicRelease' doesn't match value 'MT_StaticRelease' in main-3dacd8.o
directxtk.lib(pch.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MD_DynamicRelease' doesn't match value 'MT_StaticRelease' in main-3dacd8.o
LINK : warning LNK4098: defaultlib 'MSVCRT' conflicts with use of other libs; use /NODEFAULTLIB:library
I don't use VS, so I don't know how to use /NODEFAULTLIB.

A: You have three choices for loading DDS and other image files with WIC:

*

*Use DirectXTex (the library)

*Use DDSTextureLoader/WICTextureLoader (the standalone versions)

*or use DirectX Tool Kit (the library).
There's no reason to use more than one of them in the same program, and it's going to conflict if you try. See this post.
Unless you are writing a texture processing tool, or need support for the plethora of legacy DDS pixel formats, using DirectX Tool Kit is usually the simplest. The tutorials for DirectX Tool Kit covers this pretty well.
The error you are getting indicates something much more basic to using Visual C++. The DirectXTex, DirectXTK libraries build using the recommended "Multithreaded DLL" version of the C/C++ Runtime (i.e. /MDd and /MD).
The error indicates your program is building with "Statically linked" version of the C/C++ Runtime.
See Microsoft Docs
You didn't mention what compiler toolset you are using other than "not VS".
See directx-vs-templates for a bunch of 'basic device and present loop' samples. If you don't use VS, there are 'CMakeLists.txt' available on that site.

A: I was confused once again with DirectXTex and DirectXTK.
I resolved the issue by:

*

*Removing DirectXTex

*Downloading DirectXTK

*Running the DirectXTK_Desktop_2019_Win10 solution

*Changing the Build to Release and x64

*Opening the properties

*Finding the option Runtime Library

*Choosing Multi-threaded /MT

*Building the solution

In my source file, I include:
#include <WICTextureLoader.h> and #include <DDSTextureLoader.h>
I can now link to the generated static library directxtk.lib, without getting errors.
Plus. If there are people who want to use things like /NODEFAULTLIB:library, but you don't use cl or Visual Studio, you can use the #pragma directive in your source file like this:
#pragma comment(linker, "/NODEFAULTLIB:MSVCRT")


Q: WSO2IS - Disable Embedded LDAP - deployment.toml How can I disable Embedded Ldap on Identity Server 5.10.0 version? I'm checking conf/identity/embedded-ldap.xml and enable property is true.
  <EmbeddedLDAP>
    <Property name="enable">true</Property>
    <Property name="port">${Ports.EmbeddedLDAP.LDAPServerPort}</Property>
    <Property name="instanceId">default</Property>
     .....

I couldn't find how I can disable. If I overwrite this file when docker starts it came back to true.

A: *

*If you have <wso2is-5.10.0-home>/repository/resources/conf/templates/repository/conf/identity/embedded-ldap.xml.j2 file and it's enable property value under <EmbeddedLDAP> is templated as {{embedded_ldap.enable}} (shown below),

<EmbeddedLDAP>
    <Property name="enable">{{embedded_ldap.enable}}</Property>
    <Property name="port">${Ports.EmbeddedLDAP.LDAPServerPort}</Property>
    <Property name="instanceId">default</Property>
.....
</EmbeddedLDAP>

you can use the following deployment.toml config
[embedded_ldap]
enable = false

*If the <wso2is-5.10.0-home>/repository/resources/conf/templates/repository/conf/identity/embedded-ldap.xml.j2 file contains the EmbeddedLDAP config's enable property value as hardcoded to "true", you can change it to false and restat the server to change the config in embedded-ldap.xml.

<EmbeddedLDAP>
    <Property name="enable">true</Property>
    <Property name="port">${Ports.EmbeddedLDAP.LDAPServerPort}</Property>
    <Property name="instanceId">default</Property>
.....
</EmbeddedLDAP>

*If you don't have <wso2is-5.10.0-home>/repository/resources/conf/templates/repository/conf/identity/embedded-ldap.xml.j2 file, the property value changes in embedded-ldap.xml won't be replaced once the server is restarted.

A: In WSO2 Identity Server 5.10.0 the configurations are managed by a centralized toml file which is called as deployment.toml. We can add the following configuration to the deployment.toml file which is located in <IS_HOME>/repository/conf directory.
[embedded_ldap]
enable = false

A: In WSO2 Identity Server 5.10.0 version the file embedded-ldap.xml.j2 doesn't come inside
wso2is-5.10.0/repository/resources/conf/templates/repository/conf/identity so I needed to copy the file from this link: embedded-ldap.xml.j2 and put inside my configuration for docker container conf/is-as-km/repository/resources/conf/templates/repository/conf/identity
docker-compose.yml
...
volumes:
 - ./conf/is-as-km:/home/wso2carbon/wso2-config-volume
 ports:
  - "9444:9443"
...

After that I put the property in deployment.toml:
[embedded_ldap]
enable = false

And everything worked as shown in docker log:
cup-is-as-km ... NFO {org.wso2.carbon.identity.oauth.uma...} - UMA Grant component activated successfully.
cup-is-as-km ... INFO {org.wso2.carbon.ldap.server.DirectoryActivator} - Embedded LDAP is disabled.
cup-is-as-km ... INFO {org.wso2.carbon.mex.internal.Of...} - Office365Support MexServiceComponent bundle activated successfully..

Based on the last answers and comments I reached the solution ;).


Q: Why my picture resolution are very bad with UIImage in swift I use the following function to make picture photoOutput?.capturePhoto(with: AVCapturePhotoSettings(), delegate: self).
When I save the picture his weight is only about 200Ko however the size with the AVCaptureSession.presset is .hight so it's make 1920x1080.
there is m'y prepare function to change view where all "image" var are UIImage :
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showPhoto_Segue"{
        let previewVC = segue.destination as! PreviewViewController
        previewVC.image = self.image

    }
}

in my photoOutput function I have :
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {

    if let imageData = photo.fileDataRepresentation(){
        image = UIImage(data: imageData)
        Arrayimages.append(image!)
        Arraytimes.append(Float64(CMTimeGetSeconds(currentCamera!.exposureDuration)))
    }
    if pictureNumber < 11 {
        pictureNumber += 1
        DispatchQueue.main.asyncAfter(deadline: .now() + newDurationSeconds + 0.3, execute: {
            self.photoOutput?.capturePhoto(with: AVCapturePhotoSettings(), delegate: self)
        })
    }
    else{
        image = OpenCVWrapper.hdrImaging(Arrayimages, Arraytimes)
        performSegue(withIdentifier: "showPhoto_Segue", sender: nil)
    }
}

In my OpenCVWrapper.mm I have :
+(UIImage *) hdrImaging:(NSArray *)images :(NSArray *)times{
    std::vector<cv::Mat> imagesVector;
    std::vector<float> timesVector;
    for (int i = 0; i < images.count; i++) {
        UIImage * imageToUse = images[i];

        UIImageWriteToSavedPhotosAlbum(imageToUse, nil, nil, nil);
    }

    //some traitment
    return response;
}

when I use UIImageWriteToSavedPhotosAlbum function my pictures are already compressed but I don't know why and the weight of the file is to small to get good quality !
what can I do to get full resolution of my piture in 1920x1080 ?
maybe with AVCapturePhotoSettings ??
thanks!


Q: Am I correct in my understanding of selectors?

.top-menu {
  margin: 50px auto;
  padding: 0;
  list-style: none;
  width: 610px;
  height: 35px;
  box-shadow: 0 3px 4px #8b8b8b;
  background-color: #dadada;
}

.top-menu li {
  float: left;
  border-right: 1px solid #929292;
}

.top-menu li a:link {
  color: black;
  text-decoration: none;
  text-align: center;
  display: block;
  width: 100px;
  height: 35px;
  line-height: 35px;
}

.top-menu li a:visited {
  color: black;
}

ul li a:hover {
  background-color: #555;
  color: #fff;
}

  <meta charset="UTF-8">
  <title>pseudo selecotor</title>

menu1

menu2

menu3

menu4

menu5

menu6

i run this page,
if hover on menu, text color is black.
but in css, hover's text color is white.
if i change hover's selector
from ul -> to .top-menu
text color is white.
Is this because I gave black as class selector and white as tag selector?
Is it because the class is applied after applying the tag?

A: It's because classes have higher specificity value than Elements and Pseudo Elements. In your case .top-menu have higher specificity than the element ul, therefore its style is followed/used. Refer to this table for specificity:

More on specificity here.


Q: How to rearrange data frame so that values in one column are row names? I have a data frame containing 450K methylation beta-values for approx. 450 probes for two samples. This data is displayed in three columns, and looks like this:
>head(ICGC)
 submitted_sample_id    probe_id    methylation_value
1  X932-01-4D          cg00000029         0.6
2  X932-01-6D          cg00000029         0.4
3  X932-01-4D          cg00000108         0.3
4  X932-01-6D          cg00000108         0.7
5  X932-01-4D          cg00000109         0.9
6  X932-01-6D          cg00000109         0.1

I would like to rearrange this data.frame so that the probe IDs are the rownames and the sample IDs are the column names, so that it looks like this:
>head(ICGC_2)
           X932-01-4D    X932-01-6D
cg00000029    0.6           0.4
cg00000108    0.3           0.7
cg00000109    0.9           0.1

I have tried:
>library(tidyverse)
ICGC_2 <- ICGC %>% remove_rownames %>% column_to_rownames(var = "probe_id")

But this didn't work as each probe ID in ICGC appears twice in the column (as there are two samples). I also tried:
hello <- data.frame(ICGC[,-2], row.names = ICGC[,2])

But this had the same problem. The reason I want to rearrange this data in this way is because I would like to convert the beta values to M-values and use this data as the object in cpg.annotate (available through Bioconductor package DMRcate) - cpg.annotate requires the object to have unique Illumina probe IDs as rownames and unique sample IDs as column names.
Thank you!

A: You are very close. spread funciton from the tidyr package is what you need.
library(tidyverse)

ICGC_2 <- ICGC %>%
  spread(submitted_sample_id, methylation_value) %>%
  remove_rownames() %>%
  column_to_rownames(var = "probe_id")
ICGC_2
           X932-01-4D X932-01-6D
cg00000029        0.6        0.4
cg00000108        0.3        0.7
cg00000109        0.9        0.1

Data:
ICGC <- read.table(text = "submitted_sample_id    probe_id    methylation_value
1  'X932-01-4D'          cg00000029         0.6
2  'X932-01-6D'          cg00000029         0.4
3  'X932-01-4D'          cg00000108         0.3
4  'X932-01-6D'          cg00000108         0.7
5  'X932-01-4D'          cg00000109         0.9
6  'X932-01-6D'          cg00000109         0.1",
                   header = TRUE, stringsAsFactors = FALSE)

A: In base R you can do this:
wICGC <- reshape(ICGC, idvar = "probe_id",
                       timevar = "submitted_sample_id", direction = "wide")
wICGC <- data.frame(wICGC[,-1], row.names=wICGC[,1])

wICGC

#            methylation_value.X932.01.4D methylation_value.X932.01.6D
# cg00000029                          0.6                          0.4
# cg00000108                          0.3                          0.7
# cg00000109                          0.9                          0.1

A: For a different perspective, you can also use melt in reshape.
library(reshape)
m <- melt(IGC, id=c("submitted_sample_id", "probe_id"))
cast(m, probe_id~submitted_sample_id)

> cast(m, probe_id~submitted_sample_id)
    probe_id X932-01-4D X932-01-6D
1 cg00000029        0.6        0.4
2 cg00000108        0.3        0.7
3 cg00000109        0.9        0.1


Q: Is it possible to subclass the immutable date class and override the __str__ method? I am trying to subclass the immutable date class in Python, but I also need to override the __str__ method. So far, I have the following:
from datetime import date

class Year(date):
    def __new__(cls, year):
        return super(Year, cls).__new__(cls, year, 1, 1)
    def __str__(self):
        return self.strftime('%Y')

Constructor works fine, but the __str__ method is completely ignored when I try to print the object. I have seen a few samples subclassing other immutable classes such as int and float. All of them were using the same convention. Am I missing something? Is there anything special for the date object?
UPDATE:
It seems that there is nothing wrong with the code. I was trying to print a Year object inside a Django template and since Django formats date objects using a localizable format __str__ method was being ignored.

A: Add a return to the __str__ method.

UPDATE:
I ran your updated code on my machine, and it works fine:
aj@localhost:~/so/python# cat date2.py
from datetime import date

class Year(date):
    def __new__(cls, year):
        return super(Year, cls).__new__(cls, year, 1, 1)
    def __str__(self):
        return self.strftime('%Y')

y=Year(2011)
print str(y)
aj@localhost:~/so/python# python date2.py
2011

A: If this is your complete code you are missing the return statement:
def __str__(self):
    return self.strftime('%Y')


Q: OpenAPI definition not generating Scala properties I'm using the springdoc-openapi-ui plugin with spring-boot to generate an OpenAPI definition. It doens't seem to detect properties from Scala based objects. Java defined objects are working fine. Is there a way to fix this?
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>1.6.9</version>
</dependency>

Controller:
case class OpenApiTest(a: String, b: String)

@RestController
class TestController {
  @GetMapping(path=Array("/open-api-test"))
  def openApiTest = OpenApiTest("a", "b")
}

Result of /v3/api-docs. Source is a Java class, OpenApiTest Scala:
"components": {
    "schemas": {
        "Source": {
            "type": "object",
            "properties": {
                "path": {
                    "type": "string"
                }
            }
        },
        "OpenApiTest": {
            "type": "object"
        }
    }
}


Q: Change AppBar back icon size in Flutter Here's the current AppBar code:
AppBar(
  iconTheme: IconThemeData(
    color: Colors.black,
    size: 100 // This isn't performing any changes
  ),
  centerTitle: false,
  backgroundColor: Colors.white,
  title: Text(
    title,
    style: TextStyle(color: Colors.black87,

  ),
  elevation: 1.0,
);

Current size attribute from IconThemeData not making any change.

A: Try this you need to use leading

*

*A widget to display before the title.

SAMPLE CODE
 AppBar(
      title: new Text("Your Title"),
      leading: new IconButton(
        icon: new Icon(Icons.arrow_back,size: 50.0,),
        onPressed: () => {
          // Perform Your action here
        },
      ),
    );

OUTPUT

A: You can use Transform.scale widget and wrap IconButton with it. This widget has scale property which you can set based on your need. Working sample code below:
appBar: AppBar(
        leading: Transform.scale(
          scale: 2,
          child: IconButton(
          icon: Icon(Icons.arrow_back, color: Colors.black),
          onPressed: () {}
          )
        ),

  centerTitle: false,
  backgroundColor: Colors.white,
  title: Text(
    'test',
    style: TextStyle(color: Colors.black87,

  ),
//  elevation: 1.0,
)),

Hope this answers your question.


Q: How to fetch both IPv4 and IPv6 on dual stack OS I have dual stack machine .
My problem is i am getting only IPv4 using
InetAddress address = InetAddress.getLocalHost();

and If i use Network Interface API then i get all the IP address in which includes my MAC addrres as well in the form of IP address.
why-do-i-get-multiple-global-ipv6-addresses-listed-in-ifconfig
Now is there any way i can get both IPv4 and IPv6 of my machine.

A: In Linux,
InetAddress.getLocalHost() will look for the hostname and then return the first IP address assigned to that hostname by DNS. If you have that hostname in the file /etc/hosts, it will get the first IP address in that file for that hostname.
If you pay attention this method returns only one InetAddress.
If you haven't assigned a hostname, most probably it will be localhost.localdomain. You can set the hostname with command line:
hostname [name]

or by setting it in file /etc/sysconfig/network
If you want to get all ip addresses, including IPv6, assigned to a hostname you can use:
InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());

If you want to get all ip addresses, including IPv6, assigned to a host's network interfaces, you must use class NetworkInterface.
Here I'm pasting some example code:
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.SocketException;
import java.net.NetworkInterface;
import java.util.*;

public class Test
{
    public static void main(String[] args)
    {
        try
        {
            System.out.println("getLocalHost: " + InetAddress.getLocalHost().toString());

            System.out.println("All addresses for local host:");
            InetAddress[] addr = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
            for(InetAddress a : addr)
            {
              System.out.println(a.toString());
            }
        }
        catch(UnknownHostException _e)
        {
            _e.printStackTrace();
        }

        try
        {
            Enumeration nicEnum = NetworkInterface.getNetworkInterfaces();
            while(nicEnum.hasMoreElements())
            {
                NetworkInterface ni=(NetworkInterface) nicEnum.nextElement();
                System.out.println("Name: " + ni.getDisplayName());
                System.out.println("Name: " + ni.getName());
                Enumeration addrEnum = ni.getInetAddresses();
                while(addrEnum.hasMoreElements())
                {
                    InetAddress ia= (InetAddress) addrEnum.nextElement();
                    System.out.println(ia.getHostAddress());
                }
            }
        }
        catch(SocketException _e)
        {
            _e.printStackTrace();
        }
    }
}

For this example, I got code from one of the responses in InetAddress.getLocalHost().getHostAddress() is returning 127.0.1.1


Q: Why swift compiler doesn't find Alamofire? I try to install Alamofire. I really haven't possibility to use cocoaPods, so I try to install it manually.
The steps I took:

*

*I download Alamofire from GitHub.

*In folder drag Alamofire.xcodeproj and drop into my projects

*In my projects in "generals" in "Embedded Binaries" add framework for iOs

*import Alamofire in code

When I want to make a request I enter "Alamofire" and swift offers me "AlamofireExtended", "AlamofireNotifications", "AlamofireExtension" and "AlamofireVersionNumber".
I try to enter request manually, but nothing happen

A: Did you follow their guidelines for manual installation?
You should run
$ git init

(if your project is not initialized as a git repository)
and then
$ git submodule add https://github.com/Alamofire/Alamofire.git

(so that you can add it as a submodule)
I would also suggest you to delete the derived data, clean the project and then build it again.


Q: On orientation change button touchlistener not working I have two layouts table.xml(port) and table.xml(land) which from there names one of the landscape and other for the protrait.

I have included this layout in another layout called fragment_test.xml like this:
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
         >

   <include layout="@layout/table"/>

    </RelativeLayout>

And this is my fragment code of the above layout fragment_test:
public class Fragment_test extends Fragment  implements View.OnTouchListener{
     @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);

         mytable= (LinearLayout) getActivity().findViewById(R.id.mytableid);
        typeface = Typeface.createFromAsset(getActivity().getAssets(),   "fonts/font.ttf");

                  for (int i = 0; i < table1.getChildCount(); i++) {
                    LinearLayout mychild = (LinearLayout) mytable.getChildAt(i);
                    for (int j = 0; j < mychild.getChildCount(); j++) {
                        Button b = (Button) child.getChildAt(j);
                        b.setTypeface(typeface);
                         b.setOnTouchListener(this);
                   }

                }
            }

         }

        //this is called when a button is touched
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
    return true;
    }

}

So basically I have several buttons in the table layout I am looping through to setontouchlistener for each one of them.
So my problem is when I switch from protrait to landscape or the opposite the touchlistener of the button does not work anymore and even the typeface doesn't work anymore when changing the layout.
> Edit: this is the activity code
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("Home");

       FragmentManager manager = getFragmentManager();
       manager.beginTransaction().add(R.id.container, new Fragment_test(), "mytag").commit();

    }

A: Try calling setRetainInstance(true) after super.onActivityCreated(savedInstanceState);
here is the documentation of setRetainInstance(boolean)
Activity :
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);

    FragmentManager manager = getSupportFragmentManager();
    Fragment myFragment = manager.findFragmentByTag("myFragment");
    if (myFragment == null) {
        myFragment = new ParentFragment();
    }

    manager.beginTransaction().add(R.id.fragmentHolder, myFragment, "myFragment").commit();
}
}

Fragment:
public class ParentFragment extends Fragment{

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setRetainInstance(true);
}
}

A: I am just give you the information.
you can check the Orientataion of device this way and set it layout.
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    if (newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE){
        setContentView(R.layout.table_horizontal);
        button1 = (Button)findViewById(R.id.button1);
        button1.setOnClickListener(this);
    }else if (newConfig.orientation==Configuration.ORIENTATION_PORTRAIT){
        setContentView(R.layout.table_vertical);
        button1 = (Button)findViewById(R.id.button1);
        button1.setOnClickListener(this);
    }
}


Q: HTML Code to display UIAlertView on iOS I've gone to different websites on my iPhone that will pop up a UIAlertView when it loads.  How is this accomplished?  I want to put some code on my page to pop up a UIAlertView when viewed on an iPhone.

A: You can make use of bridecall from the js to native code to trigger the UIAlertView..


Q: SQL Server compare two tables rows with identical columns and return changed columns I want to compare two tables with the same columns:

*

*product - Id, Name, Description

*Temp_Product - Id, Name, Description
Now update done by user will be saved into Temp_Product. When admin will see the details of that product I need to show the changes done by user. I want to compare both tables with a query and return columns that have changed from Product to Temp_Product.
Please suggest me better way to do this?

A: Select p.id,p.name as orgn,t.name as altn,p.descripion as orgd,t.description as altd
from product p
join tmp_product t
on t.id=p.id and (t.name<>p.name or t.description <> p.description)

A:
I want to compare both tables with a query and return columns that
  have changed from Product to Temp_Product

Since the two tables have the same structure, you can use the EXCEPT  set oeprator for this:
SELECT * FROM Temp_Product
EXCEPT
SELECT * FROM Product;

SQL Fiddle Demo


Q: Applescript Copy All File from USB to Folder Could you help me to make this script working ?
property ignoredVolumes : {"DD APPLE", "MobileBackups"}
tell application "System Events"

set Destination_Folder to folder "/Users/Joseph/Downloads/Test" of startup disk
set rootVolume to disk item (POSIX file "/Volumes" as text)
set allVolumes to name of every disk item of rootVolume

repeat with aVolume in allVolumes
    if aVolume is not in ignoredVolumes then
        copy every item of folder (aVolume) to Destination_Folder
    end if
end repeat
end tell

The problem is in the line copy every item of folder (aVolume) to Destination_Folder - the error message I get is Can’t get every file of "NO NAME". (No Name is my USB key.)
Thank you very much for your help.

A: System Events doesn't have a "copy" command. Where did you get that? You might try "move" instead. Plus "aVolume" is not a folder, it's a disk. You probably want to change "folder aVolume" to "disk aVolume". And you might even need to use "disk (contents of aVolume)"
EDIT: Try the following script. I didn't test it but it should work. Good luck.
property ignoredVolumes : {"DD APPLE", "MobileBackups", "home", "net"} -- leave home and net in this list
set Destination_Folder to ((path to downloads folder as text) & "Test:") as alias

set mountedVolumes to list disks

repeat with i from 1 to count of mountedVolumes
    set thisVolume to item i of mountedVolumes
    if thisVolume is not in ignoredVolumes then
        tell application "Finder"
            set theItems to items of disk thisVolume
            move theItems to Destination_Folder
        end tell
    end if
end repeat


Q: Discordbot javascript react to mentions I'm completely new to Javascript and i would like to make a discord bot.
I have a bot already running with a few commands, now i would like to add something that posts a reaction whenever someone specific is tagged.
client.on('message', message => {
  var user = "123456479879541";
  if(message.mentions.users.id === user) {
    message.channel.send('ok');
  }
});

What do i have to do to make it work?

A: Message.mentions.users is a collection.  You need to determine if your ID is in the collection.  You are comparing equality, which since user is not a collection will always be false.  Replace this with a .has  You can then add a react to the message.  For that, there is a guide here describing how to get a unicode reaction as shown below.
  var user = "123456479879541";
  if(message.mentions.users.has(user)) {
    message.channel.reply('ok');
    message.react('');
  }

A: You should use Message#react()
So basically for example you could do:
client.on('message', message => {
var user = "123456479879541";
const reaction = message.guild.emojis.find(emoji => emoji.name === 'EMOJI NAME')
    if(message.mentions.users.has(user)) {
        message.channel.reply('ok');
        message.react(reaction)
}});


Q: How to get index position in textBox using javascript How do i get the index position when user click in textBox using JavaScript?
for example in my textBox have this string :
`this is best| of the world`.

it should be return 13.


Q: Link Resources in c# Project I have 2 files, 1 is form1.cs and the second is form1.resx. they should be linked but are not. how can I link the 2? if i just make sure the namespaces are the same will they automatically link to each other? do i need to clean the project?

A: Install VSCommand 2010.
Select two files then group two item from the context menu.

A: Right-click both files and click Exclude from project.
Then, click Show all Files on top of the Solution Explorer, then right-click the .cs file and click Include in project.

A: You mean one as a subtree of the other?  If what SLaks says doesn't work you can edit the proj file.
I think it is like this, using the dependentupon xml
<Compile Include="FPtoICVService.cs">
      <SubType>Component</SubType>
    </Compile>
    <Compile Include="FPtoICVService.Designer.cs">
      <DependentUpon>FPtoICVService.cs</DependentUpon>
    </Compile>


Q: Personal Autoformat (Visual Studio C# / git) I have 2 different settings in visual studio, my personal and our company guidelines and a git repository where code should be commited with our company guidelines. Is it possible to automatically autoformat the code on opening the file with my personal settings? Then, when I finished working (either on save or preferably on git pre-commit) I would like to autoformat the files I worked on with our company guidelines.
Is there a way to achieve this?
EDIT: Language is C#.


Q: Cannot find element in Vue Js Applications I created vue js applications with visual studio 2017 . but the problem is when i run the applications , i got following errors in google chrome console windows .
[Vue warn]: Cannot find element: #intro
[Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.
Here is the code for App.vue...
<template>

        <Home msg="Hello world!" />

</template>

Here is the code for component1.vue..
<template>

{{ message }}

</template>

Here is the screen shot of the google console windows ..

A: You have set the class on the element instead of the id.
But that is irrelevant anyway because you do not need to any of this for a single file component; just do this instead (as you did for App.vue):
<template>

{{ message }}

</template>

Constructing a Vue component manually with new Vue() is only necessary for the root component instance.


Q: UWP: BackgroundTask open App Mainpage Is it possible to open my app by my own backgroundtask?
when i have a backgroudtask in windows universal platform, can i start or open my app.mainpage from there?
my backgroundtask checks periodicaly the clipboard and if it gets an hit, then it should open my app.
does this work with uwp or is uwp again a no-go software ?
any soltutions or ideas therefore?

A: You can do that by a toast. Here is an example.
   var content =
        $@"
            <toast activationType='foreground' launch='args'>
                <visual>
                    <binding template='ToastGeneric'>
                        <text>Open app</text>
                        <text>Your clipboard is ready.Open app</text>
                    </binding>
                </visual>
                <actions>

                    <action content='ok' activationType='foreground' arguments='check'/>

                  <action activationType='system' arguments='dismiss' content='cancel' />

                </actions>
            </toast>";

        Windows.Data.Xml.Dom.XmlDocument toastDOM = new Windows.Data.Xml.Dom.XmlDocument();
        toastDOM.LoadXml(content);
        ToastNotification toast = new ToastNotification(toastDOM);
        var notifier = ToastNotificationManager.CreateToastNotifier();
        notifier.Show(toast);

And then if user press the ok button you must go in App.xaml.cs and handle that
 protected override void OnActivated(IActivatedEventArgs args)
    {
        if (args.Kind == ActivationKind.ToastNotification)
        {
            var toastArgs = args as ToastNotificationActivatedEventArgs;
            var arguments = toastArgs.Argument;

            if (arguments == "check")
            {
                Frame rootFrame = Window.Current.Content as Frame;
                if (rootFrame == null)
                {
                    rootFrame = new Frame();
                    Window.Current.Content = rootFrame;
                }
                rootFrame.Navigate(typeof(YOURPAGEHERE));
                Window.Current.Activate();
            }
        }
    }


Q: laravel 5 .. ubuntu .. command line I am working using laravel5 php framework on ubuntu and I have 2 problems
1- when I try to use the composer to require anything .. it doesnt work
2- when i tried to make some changes to illuminate/Html .. it doesn't work too
so after that when i tried to use the artisan to serve my project I got that error
PHP Fatal error:  Class 'Illuminate\Html\HtmlServiceProvider' not found in /home/shaimaa/Sites/Laravel5/eoswdt/storage/framework/compiled.php on line 5617
exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class 'Illuminate\Html\HtmlServiceProvider' not found' in /home/shaimaa/Sites/Laravel5/eoswdt/storage/framework/compiled.php:5617
Stack trace:
#0 /home/shaimaa/Sites/Laravel5/eoswdt/storage/framework/compiled.php(1500): Illuminate\Foundation\Bootstrap\HandleExceptions->fatalExceptionFromError(Array)
#1 [internal function]: Illuminate\Foundation\Bootstrap\HandleExceptions->handleShutdown()
#2 {main}

A: Just run the following in your composer
composer require "illuminate/html":"5.0.*"

Inside your config/app.php add the following codes inside it
In the 'providers' => [ ..]
'Illuminate\Html\HtmlServiceProvider',

And in the
'aliases' => [ ..]
'Form'=> 'Illuminate\Html\FormFacade',
'HTML'=> 'Illuminate\Html\HtmlFacade',

And then refresh the page you should find that it should be working.


Q: error when try to install flask in the virtual enviroment I just configure the environment to develop the flask based web app. All the things goes smoothly, but when I run my hello world app, the python interpret tell me no module named flask:
Traceback (most recent call last):
  File "hello.py", line 1, in <module>
    from flask import Flask
ImportError: No module named flask

but I seriously install flask.
When I get the error, i just run the command in the virtual environment, sudo pip install flask. Then, the console show the message:
(venv)ubuntu@localhost:/var/www/demoapp$ sudo pip install flask
Requirement already satisfied (use --upgrade to upgrade): flask in /usr/local/lib/python2.7/dist-packages
Requirement already satisfied (use --upgrade to upgrade): Werkzeug>=0.7 in /usr/local/lib/python2.7/dist-packages (from flask)
Requirement already satisfied (use --upgrade to upgrade): Jinja2>=2.4 in /usr/local/lib/python2.7/dist-packages (from flask)
Requirement already satisfied (use --upgrade to upgrade): itsdangerous>=0.21 in /usr/local/lib/python2.7/dist-packages (from flask)
Requirement already satisfied (use --upgrade to upgrade): markupsafe in /usr/local/lib/python2.7/dist-packages (from Jinja2>=2.4->flask)
Cleaning up...

Who can tell me how can I run my hello world flask app?

A: When you run

$ sudo pip install...

system pip will be used. So to install flask in current environment just run

$ pip install ...
  or as:
  $ /path/to/venv/bin/pip install ...

Or make your venv able to load global system packages by parameter --system-site-packages, while configure virtual environment.

A: If you are having the same trouble even if you have your virtualenv running, just make sure you didn't accidentally delete the files and attempt to execute pip in that folder you created for your venv...  Like I did.  :D


Q: How to use the default value attribute of a select tag Now im working on a small task with a select tag like this
       <select
            name="selectmedgroup"
            id="selectmedgroup"
            value={selectedGroupValue}
            onChange={filterOnSelectChange}
          >
            <option value="" defaultValue hidden>
              -Select Group-
            </option>
            <option value="a">A</option>
            <option value="b">B</option>
            <option value="c">C</option>
            <option value="d">D</option>

          </select>

I want to get the value on change. Here is my on change function and state
const [selectedGroupValue, setSelectedGroupValue] = useState();

  const filterOnSelectChange = (e) => {
    setSelectedGroupValue(e.target.value);
    console.log(selectedGroupValue);
  };

Everything seems to work fine but when I log out the selected option first if I choose A for the first time I get undefined on the logs. If I choose B I get A logged out. If  I choose C I get B logged out.
I don't think it's my ordering that's wrong. Remember I don't want to have an initial value on the state because this will be just a selection that I will use to filter what the user sees on the page. So for the first time on the component mount, nothing should be filtered.
I have a feeling that the problem is the first Option tag with the -Select Group- . Is there any way I can avoid using that first options tag because it is just like a placeholder whose value I don't need to be selected?
How can I get the correct values? Please help

A: Try to console your selectedGroupValue on useEffect hook , solve it like this
import React, { useState } from 'react';

const App = () => {
    const [selectedGroupValue, setSelectedGroupValue] = useState();

    const filterOnSelectChange = (e) => {
        setSelectedGroupValue(e.target.value);
    };
    React.useEffect(() => {
        console.log(selectedGroupValue);
    }, [selectedGroupValue]);

    return (
        <>
            <select
                name="selectmedgroup"
                id="selectmedgroup"
                value={selectedGroupValue}
                onChange={filterOnSelectChange}
            >
                <option value="" defaultValue hidden>
                    -Select Group-
                </option>
                <option value="a">A</option>
                <option value="b">B</option>
                <option value="c">C</option>
                <option value="d">D</option>
            </select>
        </>
    );
};

export default App;


Q: two digit year as primary key in sql server I have a table with these columns:
ID int,
d date

Now what I need is to define the primary key in such a way that ID would be unique for each year; meaning that there can not be two same IDs in 2004, but it is possible to have two same IDs in two different years.
Like:
insert into myTable values(1, '1-1-2004'), (1, '1-1-2005')

but not like:
insert into myTable values(1, '3-1-2005'), (1, '1-1-2005')

I tried this:
primary key(ID, datepart(YY, d))

but I get syntax error.

A: One way of doing this, if you can alter the table structure, is to add a persisted computed column for the year part, and then add a primary key for (id, computer_col), like this:
CREATE TABLE myTable (
    id INT NOT NULL,
    d DATE NOT NULL,
    y AS DATEPART(YEAR,d) PERSISTED NOT NULL,
    PRIMARY KEY(id,y)
    )

I'm not saying this is a good solution in any way, but it should work. Using a trigger on insert or a check constraint might be better.
Using your test data this will allow the first insert statement, but disallow the second as it violates the primary key constraint.


Q: Tap UIImageView with no alpha response? I have an image which has a relatively large area of transparency, alpha space. So is there a way I can detect a tap on this UIImageView but not have any response if the user taps the alpha area?

A: This is theoretical and I don't have code to add, but you could create an identical button and add it for UIControlStateTouched so there's no change when the button/image is touched.