text:
Q: How to get count for different columns on same table Table #01 Status:
StatusID    Status
-----------------------
 1          Opened
 2          Closed
 3          ReOpened
 4          Pending

Table #02 Claims:
ClaimID     CompanyName StatusID
--------------------------------------
1               ABC     1
2               ABC     1
3               ABC     2
4               ABC     4
5               XYZ     1
6               XYZ     1

Expected Result:
CompanyName TotalOpenClaims TotalClosedClaims TotalReOpenedClaims TotalPendingClaims
--------------------------------------------------------------------------------
ABC                 2           1                      0               1
XYZ                 2           0                      0               0

How do I need to write the query so that I could get the result as expected?

A: It's easiest with SUM() and a CASE statement:
select CompanyName,
sum(case when StatusID=1 then 1 else 0 end) as TotalOpenClaims,
sum(case when StatusID=2 then 1 else 0 end) as TotalClosedClaims,
sum(case when StatusID=3 then 1 else 0 end) as TotalReOpenedClaims,
sum(case when StatusID=4 then 1 else 0 end) as TotalPendingClaims
from Claims
group by CompanyName;

A: This is a typical pivot transformation, and conditional aggregation, as suggested by Phil, is the good old way of implementing it.
There is also a more modern syntax of achieving the same result, which uses the PIVOT clause:
SELECT
  CompanyName,
  TotalOpenClaims     = [1],
  TotalClosedClaims   = [2],
  TotalReOpenedClaims = [3],
  TotalPendingClaims  = [4]
FROM
  dbo.Claims
  PIVOT
  (
    COUNT(ClaimID)
    FOR StatusID IN ([1], [2], [3], [4])
  ) AS p
;

Internally this arguably simpler looking syntax is equivalent to Phil's GROUP BY query. More exactly, it is equivalent to this variation:
SELECT
  CompanyName,
  TotalOpenClaims     = COUNT(CASE WHEN StatusID = 1 THEN ClaimID END),
  TotalClosedClaims   = COUNT(CASE WHEN StatusID = 2 THEN ClaimID END),
  TotalReOpenedClaims = COUNT(CASE WHEN StatusID = 3 THEN ClaimID END),
  TotalPendingClaims  = COUNT(CASE WHEN StatusID = 4 THEN ClaimID END)
FROM
  dbo.Claims
GROUP BY
  CompanyName
;

So, a PIVOT query is an implicit GROUP BY query, essentially.
PIVOT queries, however, are notoriously trickier in handling than explicit GROUP BY queries with conditional aggregation. When you are using PIVOT, you need to always keep in mind this one thing:

*

*All columns of the dataset being pivoted (Claims in this case) that are not explicitly mentioned in the PIVOT clause are GROUP BY columns.

If Claims consists of only the three columns shown in your example, the PIVOT query above will work as expected, because apparently CompanyName is the only column not explicitly mentioned in PIVOT and thus ends up as the only criterion of the implicit GROUP BY.
However, if Claims has other columns (say, ClaimDate), they will implicitly be used as additional GROUP BY columns – that is, your query will essentially be doing
GROUP BY CompanyName, ClaimDate, ... /* whatever other columns there are*/`

The result will most likely be not what you want.
That is easy to fix, though. In order to exclude irrelevant columns from participating in the implicit grouping, you can just use a derived table, where you will select only the columns needed for the result, although that makes the query less elegant-looking:
SELECT
  CompanyName,
  TotalOpenClaims     = [1],
  TotalClosedClaims   = [2],
  TotalReOpenedClaims = [3],
  TotalPendingClaims  = [4]
FROM
  (SELECT ClaimID, CompanyName, StatusID FROM dbo.Claims) AS derived
  PIVOT
  (
    COUNT(ClaimID)
    FOR StatusID IN ([1], [2], [3], [4])
  ) AS p
;
Still, if Claims is already a derived table, there is no need to add another level of nesting, just make sure that in the current derived table you are selecting only the columns required to produce the output.
You can read more about PIVOT in the manual:

*

*Using PIVOT and UNPIVOT

A: Admittedly my experience is with MySQL mostly and I haven't spent much time on SQL Server. I would be very surprised if the following query didn't work:
SELECT
  CompanyName,
  status,
  COUNT(status) AS 'Total Claims'
FROM Claim AS c
  JOIN Status AS s ON c.statusId = s.statusId
GROUP BY
  CompanyName,
  status;

This doesn't give you the output in the format that you want but it does give you all of the information you want, albeit leaving out the zero cases. This feels much simpler to me than dealing with CASE statements inside of a query which feel like an especially bad idea if it is just being used for formatting.


text:
Q: How to append icon before svg using jquery? I have a menu in which I want to append font-awesome fonts before or after the SVG icons, here my live demo jsfiddle
Here is my HTML

        <svg aria-labelledby="menu" class="ast-mobile-svg ast-menu-svg" fill="currentColor" version="1.1" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M3 13h18c0.552 0 1-0.448 1-1s-0.448-1-1-1h-18c-0.552 0-1 0.448-1 1s0.448 1 1 1zM3 7h18c0.552 0 1-0.448 1-1s-0.448-1-1-1h-18c-0.552 0-1 0.448-1 1s0.448 1 1 1zM3 19h18c0.552 0 1-0.448 1-1s-0.448-1-1-1h-18c-0.552 0-1 0.448-1 1s0.448 1 1 1z"></path>
        </svg>

        <svg aria-labelledby="menu-toggle-close" class="ast-mobile-svg ast-close-svg" fill="currentColor" version="1.1" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M5.293 6.707l5.293 5.293-5.293 5.293c-0.391 0.391-0.391 1.024 0 1.414s1.024 0.391 1.414 0l5.293-5.293 5.293 5.293c0.391 0.391 1.024 0.391 1.414 0s0.391-1.024 0-1.414l-5.293-5.293 5.293-5.293c0.391-0.391 0.391-1.024 0-1.414s-1.024-0.391-1.414 0l-5.293 5.293-5.293-5.293c-0.391-0.391-1.024-0.391-1.414 0s-0.391 1.024 0 1.414z"></path>
        </svg>

Here is the jquery code
var getOpenIcon = $('.ast-menu-svg');
var openHamburger =$(" ");

var getCloseIcon = $('.ast-close-svg');
var closeHamburger =$(" ");

getOpenIcon.insertBefore(openHamburger);
getCloseIcon.insertBefore(closeHamburger);

Instead of inserting new element before the svg icons it delete the icons, whats wrong here?

A: You need to use the before function instead of insertBefore.
getOpenIcon.before(openHamburger);
getCloseIcon.before(closeHamburger);

The insertBefore function inserts the left hand value before the argument passed.
The before function inserts the argument passed before the left hand value.

redpajama_set_name: RedPajamaStackExchange


text:
Q: IIS default datetime format We have a WCF web service returns back some xml containing a datetime value as a string.  The value is first read out from a database and then appended to an xml string using .ToString().
We have a number of web servers running but this particular one is converting the datetime value to a 24 hour value, we need it has a 12 hour value but I can't figure out how to change IIS default date format.  I have tried changing the regional settings and have look at the culture and ui culture values of the web service which are both set to "Invariant Language (Invariant Country)".
I think it might require a registry change.  Does anyone know how to change the datetime format of a web service?
We cannot change the code at this stage so my only choice is to update the server itself.
Its running on windows server 2008.
thank you

A: Nevermind people I've figured it out.  To change the datetime regional settings of an IIS website/webs ervice here is what you do:
First go into IIS and click on the website/web service you want to configure.  On the right hand side open up .Net Globalization and change the culture and ui culture to anything other than the one you want.
Now in the control panel go into the region and language screen and change the datetime format to what you want it to be.  Then on the administration tab of the region and language screen click the "Copy settings" button and tick the box "Welcome screen and system accounts".  Click ok on both screens to exit region and language.
Now go back to IIS and change the culture and ui culture back to what it was before you change it.  Your website/webservice should now be serving up the correct datetime format.
I think the key point here is copying the region and language settings to all system users.  then changing the IIS culture settings makes IIS pickup the new settings.  You might get away with not changing the culture and simply restarting the webserver or the machine after making the changes in the region and language screen but i haven't tried this.


text:
Q: quick Edit module not working in drupal 7.5 I tried inline-editing using quick edit module.I ahve included ctool,library,entities and two js files.(ie) backbone.js and underscore.js in (site/all/libraries) and granted permission for 'Access in-place editing' and 'Use contextual links' as administrator.
After enabled the modules I can see the inline edit icon but I cant edit.
Does I want to do any other steps to enable editing.

A: I was facing same problem in drupal 7, i resolve it by

*

*Downloading backbone and underscore js from  url

*Extract them into libraries folder of drupal 7 separately

*Clear the cache [Drupal cache]


text:
Q: Testing method injected class against existing injector I have a set of classes that are injected at runtime, because of a legacy code base. I want to write a unit test that checks the injector can satisfy all injected dependencies of those classes. I already have the list of classes to be injected available, and I can instantiate the injector, in Stage.TOOL, because otherwise it will do stuff like connect to a database.
My question is, how do I check those classes against the injector? I've tried injector.getMembersInjector(classToBeInjected), but this fails because injectors in Stage.TOOL do not support it. Basically, I don't need the injector instance, but I need it to check if it could be created.
For reference, here is my current implementation:
@AllArgsConstructor
@RunWith(Parameterized.class)
public class HtmlActionInjectTest {
    @Parameters(name="{1}")
    public static List<Object[]> parameters() {
        return ImmutableList.of(classesUnderTest);
    }

    @BeforeClass
    public static void setUp() {
        injector = Guice.createInjector(Stage.TOOL, myLongListOfModules);
    }

    private static Injector injector;
    private final Class<?> actionClass;

    @Test
    public void test() {
        injector.getMembersInjector(actionClass);
    }
}

I've also tried using the SPI api, using Elements.getElements(myModules), but I couldn't get it to tell me if the dependencies of the classToBeInjected can be satisfied.
Example of a class under test:
public class MyAction implements SomeInterface {
  public MyAction(UnInjectableDependency dep) {
    // can't be injected here for legacy reasons
  }

  @Inject void doInject(SomeDep dep) {
     this.dep = dep;
  }

  @Override void someInterfaceMethod() { /* you get the idea */ }
}

A: I've found the solution with the help of a colleague.
Guice offers a class called InjectionPoint, which can be used to find all dependencies of the class to be injected. So, the solution looks like this:
@AllArgsConstructor
@RunWith(Parameterized.class)
public class HtmlActionInjectTest {
    @Parameters(name="{1}")
    public static List<Object[]> parameters() {
        return ImmutableList.of(classesUnderTest);
    }

    @BeforeClass
    public static void setUp() {
        bindings = Guice.createInjector(Stage.TOOL, myLongListOfModules).getAllBindings().keySet();
    }

    private static Set<Key<?>> bindings;
    private final Class<?> actionClass;

    @Test
    public void test() {
        for (InjectionPoint point : InjectionPoint.forInstanceMethodsAndFields(actionClass)) {
            for (Dependency<?> dependency : point.getDependencies()) {
                assertTrue("injector cannot satisfy dependency " + dependency.getKey() + " in " + actionClass.getName(), bindings.contains(dependency.getKey()));
            }
        }
    }
}


text:
Q: merge two fields in document using mongodb Below is my JSON, is there any way where I can merge multiple fields of a same document.
 "_id" : 1,
 "sem" : 1,
 "achieve" : [ 70, 87, 90 ]

I am expecting the output as
 "_id" : 1,
 "sem" : [1,70, 87, 90],
 "achieve" : [ 70, 87, 90 ]

A: One of the simple methods just to achieve what you are asking. You can create a loop for all the documents of the collection though. The code below has 'stack' collection having just one document, the one you mentioned.
doc = db.stack.findOne();
var tmp = doc.sem;
doc.sem = new Array();
doc.sem.push(tmp);
i = 0;
for(i = 0;i<doc.achieve.length;i++){
    doc.sem.push(doc.achieve[i]);
}
db.stack.update({sem:1},doc);


text:
Q: charCodeAt() working with some validations, but not some other validations I could have sworn I validated everything properly until my teacher decided to look for every single possible combination of characters and somehow doc me for 10 points. So I went in my code and try to fix the validation but, even though this is just like the example in his lecture outline, it decides to let a1 unwantingly pass the form. I double checked the ascii char code chart using this link
and the 1 still keeps getting through.  this is my code section:
else if(f1.state.value.length != 2 ||
    !( (f1.state.value.charCodeAt(0)>=65 && f1.state.value.charCodeAt(0)<=90) ||
    (f1.state.value.charCodeAt(1)>=97 && f1.state.value.charCodeAt(1)<=122) ))
    {
        alert('Please enter a state in abreviated form');
        f1.state.focus();
        return false;
    }

why does the 1 keep getting through?
edit: also, i notice 1a works (or doesnt work), but not a1..

A: interesting, i took the ! out and put it around each individual parenthesese to ! and it worked.. so it was returning true if one or the other was true... then !ing it.
so it should have been :
else if(f1.state.value.length != 2 ||
        ( !(f1.state.value.charCodeAt(0)>=65 && f1.state.value.charCodeAt(0)<=90) ||
        !(f1.state.value.charCodeAt(1)>=97 && f1.state.value.charCodeAt(1)<=122) ))
        {
            alert('Please enter a state in abreviated form');
            f1.state.focus();
            return false;
        }


text:
Q: simple modal not scroll background  I'm using simple modal. Is there any way to keep the background (behind the overlay) from scrolling when you roll the mouse wheel while outside the boundaries of the modal?
Thanks!

A: While creating the modal, set overflow:hidden for body. Then you will not be able to scroll the background and when hiding the modal, set overflow:auto for body.

A: I think you can do this:
$(document).on('mousewheel', '.simplemodal-overlay, .simplemodal-data', function(event) {
    event.preventDefault();
});

I'm not sure if mousewheel has full cross-browser support, though.
Edit: I verified this works, but you need the mousewheel plugin:  https://github.com/brandonaaron/jquery-mousewheel/downloads
Example: http://jsfiddle.net/jtbowden/AhpLc/
(I pasted jquery.mousewheel.min.js into the script area... Don't do that)


text:
Q: Do something while in VBA I have a lot of files in one folder. What I want to do is add a column with the name of the file. I found a solution to this, but I want to optimize. Currently I am just adding the values from J2 to J1000 to make sure I cover all rows. This is not ideal as the amount of rows in each file differ. What I want to do is find a way to add the value matching the amount of rows that exists in the sheet.
I want to find a way to check if there is data in column A for each row and then add the value as long as there is some data in column A for each row.
My thoughts would be to do a while statement to check if each row in column A is different from an empty string and add the value as long as it is different from an empty string. However I am not sure how to implement this.
Here is my code:
Sub AllWorkbooks()
   Dim MyFolder As String 'Path collected from the folder picker dialog
   Dim MyFile As String 'Filename obtained by DIR function
   Dim wbk As Workbook 'Used to loop through each workbook

   On Error Resume Next
   Application.ScreenUpdating = False
   'Opens the folder picker dialog to allow user selection
   With Application.FileDialog(msoFileDialogFolderPicker)
       .Title = "Please select a folder"
       .Show
       .AllowMultiSelect = False
       If .SelectedItems.Count = 0 Then 'If no folder is selected, abort
           MsgBox "You did not select a folder"
           Exit Sub
       End If
       MyFolder = .SelectedItems(1) & "\" 'Assign selected folder to MyFolder
    End With

    MyFile = Dir(MyFolder) 'DIR gets the first file of the folder
    'Loop through all files in a folder until DIR cannot find anymore
    Do While MyFile <> ""
        'Opens the file and assigns to the wbk variable for future use
        Set wbk = Workbooks.Open(FileName:=MyFolder & MyFile)
        'Replace the line below with the statements you would want your macro to perform
        Sheets(1).Range("j1").Value = "Date"
        Sheets(1).Range("j2:j1000").Value = Mid(ActiveWorkbook.Name, 10, 10)
        wbk.Close savechanges:=True
        MyFile = Dir 'DIR gets the next file in the folder
    Loop

    Application.ScreenUpdating = True
End Sub


text:
Q: How to set a limit of clicking a button when user already click it for 10 times-android I have a button called "Save".
When I click it, it will call below coding :
public void SaveText(View view){

            try {
              OutputStreamWriter out = new OutputStreamWriter(openFileOutput ("myfilename.txt",MODE_APPEND));

                double latitude = gps.getLatitude();
                double longitude = gps.getLongitude();

                String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
                String latt = Double.toString(latitude);
                String lonn = Double.toString(longitude);

              String text =(latt+" "+lonn+" "+mydate);
              out.write(text);
              out.write('\n');

              out.close();

              Toast.makeText(this,"Text Saved !",Toast.LENGTH_LONG).show();

              }

                 catch (java.io.IOException e) {
                //do something if an IOException occurs.
                    Toast.makeText(this,"Sorry Text could't be added",Toast.LENGTH_LONG).show
    ();
                                           }

I want to set the "Save" button unclickable when user already click it for 10 times so that
it will not save more than 10 texts to text file.
EDIT
What I have tried so far :
do{
        try {
          OutputStreamWriter out = new OutputStreamWriter(openFileOutput ("myfilename.txt",MODE_APPEND));

            double latitude = gps.getLatitude();
            double longitude = gps.getLongitude();

            String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
            String latt = Double.toString(latitude);
            String lonn = Double.toString(longitude);

          String text =(latt+" "+lonn+" "+mydate);
          out.write(text);
          out.write('\n');

          out.close();

          Toast.makeText(this,"Text Saved !",Toast.LENGTH_LONG).show();
          count++;
          }

             catch (java.io.IOException e) {
                Toast.makeText(this,"Sorry Text could't be added",Toast.LENGTH_LONG).show
();
                                       }}

    while(count<9);
    if (count>9){Button btn=(Button)findViewById(R.id.Save); btn.setEnabled(false);}

 }

The result is when click "Save" button once, it disable my "Save" button without waiting it to be clicked until 10 times.
NEW CODE
 public void SaveText(View view){
     if (this.counter <= 10) {

        try {
          OutputStreamWriter out = new OutputStreamWriter(openFileOutput ("xy.txt",MODE_APPEND));

            double latitude = gps.getLatitude();
            double longitude = gps.getLongitude();

            String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
            String latt = Double.toString(latitude);
            String lonn = Double.toString(longitude);

          String text =(latt+" "+lonn+" "+mydate);
          out.write(text);
          out.write('\n');

          out.close();

          Toast.makeText(this,"Text Saved !",Toast.LENGTH_LONG).show();

          }

             catch (java.io.IOException e) {

                Toast.makeText(this,"Sorry Text could't be added",Toast.LENGTH_LONG).show
();
                                    }
    this.counter++;     }

 }}

All method I have tried but when I click "Save" button for the second time, it will do nothing.
SOLUTION :
Thank you very much.
Everyone really help me to solve this.
 public void SaveText(View view){

          if (this.counter <= 10) {
            //to-do coding
                                            }
              this.counter++;

    }

          else{Button btn=(Button)findViewById(R.id.Save); btn.setEnabled(false);}

     }}

A: You need to keep the counter of button clicks in your class. Since you didn't specify what your class name, I'll just call it YourClass.
public class YourClass ... {

     private int buttCounter = 0;
     ...
}

Then you need to update and check this counter whenever the button is clicked.
public void SaveText(View view){

    if (this.buttCounter <= 10) {
        // Your old method body goes here
        this.buttCounter++;
    }
}

This will not deactivate the button, but it will do nothing on button press. If you want to disable the button, you can use Button.setClickable(false), Button.setEnabled(false) or even hide it using Button.setVisibility(View.INVISIBLE).

A: Well set a instance variable to hold the clicks and have an onclick listener that increments that variable. Then once it reached that amount change the button properties.
If you'd like further help we'll need to see the whole class to show you where.

A: Add this to the top of your click listener.
    private int numClicks = 0;
    public void SaveText(View view){
            numClicks++;
            if(numClicks == 10) {
                    view.setEnabled(false);
            }

A: Create a variable that you'll increment at the end of the onclick. In the onclick, before the incrementation, make a condition to check if your variable is equal to 9. If it is equal to 9, make the button disabled.
Edit:
int counter = 0;
public void SaveText()
{
   doSomething();

   if(counter == 9)
   {
      myButton.setEnabled(false);
   }
   counter++;
}


text:
Q: Automapper - Creating Maps in C# Was just getting started with AutoMapper and wanted to get clarity on something.
Let's say I want to seamlessly map between a User and a UserDto.
The examples all seem to suggest that I must first go to a startup area (for example WebApiConfig.cs or startup.cs or global.axax etc) and do something like this:
Mapper.CreateMap<User, UserDto>();

Presumably if I had 50 or 100 entities/DTOs that I wanted to map, I would need to literally add 50 or 100 lines of code with mappings between one class to another? Surely there's a smarter way, right?
If I don't ever need to do any specific mapping / overriding, do I really need to do this? I must have misunderstood the fundamentals of the framework because that just seems wrong to me.
Thanks!

A: As long as everything matches up on the source and the target, you could use DynamicMap:
var target = Mapper.DynamicMap<TSource, TTarget>(source);

However it would be more efficient to create a mapping as required:
if (Mapper.FindTypeMapFor<TSource, TTarget>() == null)
{
    Mapper.CreateMap<TSource, TTarget>();
}

var target =  Mapper.Map<TSource, TTarget>(source);


text:
Q: ksh - check if String has a pattern I have a String of command as below:
CMD_LAUNCH="launch.sh \
    -v $ABC_VERSION \
    -p something \
    -X $MAX_HEAP_SPACE_PARAM \
    -Dpersist false \
    -DanotherPasram Abc"

I will launch this command in ksh as below:
$CMD_LAUNCH

How can I make sure the command has -Dpersist false ?
I want to cover the cases where there can be any no of spaces between -Dpersist and false. but my attempt fails to accomplish this.
Try 1)
if [[ "$CMD_LAUNCH" = *"Dpersist\s+false"* ]]
then
        echo "It's there!"
else
        echo "It's not there!"
fi

I want to test if Dpersist false is present in command.

A: Solution 1:
if [[ "$CMD_LAUNCH" == *+(Dpersist+(\s)false)* ]]
then
        echo "It's there!"
else
        echo "It's not there!"
fi

Ksh's pattern matching is different to regex as it will always match the whole string - like regex starting with ^ and ending with $.
Therefore you have to enclose the pattern, which itself is enclosed in parentheses, with asterisks. The * matches any sequence of characters.
The + in front of each pattern means match 1 or more occurrences of the pattern.
Solution 2:
Another option is to use the =~ operator:
if [[ "$CMD_LAUNCH" =~ Dpersist\s+false ]]
then
    echo "Its there!"
else
     echo "Its not there!"
fi

=~ uses regex syntax.
Resources
For more examples see

*

*http://blog.fpmurphy.com/2009/01/ksh93-regular-expressions.html

*http://honglus.blogspot.de/2010/03/regular-expression-in-condition.html

*https://docstore.mik.ua/orelly/unix3/korn/ch04_05.htm
Sidenote
Also check out ShellCheck, it helps greatly finding errors in your shell scripts.


text:
Q: How to get conditional input in java? I want to enter two numbers CSV and CR.
The condition is that:
If CSV is Positive, CR can be Positive or Negative.
If CSV is Negative, CR cannot be Positive
So how can i do this?

A: Scanner scanner = new Scanner(System.in);

System.out.print("CSV: ");
double csv = scanner.nextDouble();

System.out.print("CR: ");
double cr =  scanner.nextDouble();

if (csv < 0.0) {
    while (cr > 0.0) {
        System.out.println("CR cannot be positive since CSV is negative.");
        System.out.print("CR: ");
        cr = scanner.nextDouble();
    }
}


text:
Q: How do I call a function from my DLL during run-time linking? I do not understand DLLs very well, so I've constructed a simple example that I woudl like some help with. I have a simple dll here.
// HelloDLL.cpp

#include "stdafx.h"

int     __declspec(dllexport)   Hello(int x, int y);

int Hello(int x, int y)
{
    return (x + y);
}

How would I call the Hello(int x, int y) function in a separate program once I've run LoadLibrary()? Here's a rough layout of what I have so far but I'm not sure if what I have is correct, and if it is, how to proceed.
// UsingHelloDLL.cpp

#include "stdafx.h"
#include <windows.h>

int main(void)
{
    HINSTANCE hinstLib;

    // Get the dll
    hinstLib = LoadLibrary(TEXT("HelloDLL.dll"));

    // If we got the dll, then get the function
    if (hinstLib != NULL)
    {
        //
        // code to handle function call goes here.
        //

        // Free the dll when we're done
        FreeLibrary(hinstLib);
    }
    // else print a message saying we weren't able to get the dll
    printf("Could not load HelloDLL.dll\n");

    return 0;
}

Could anyone help me out on how to handle the function call? Any special cases I should be aware of for future usage of dlls?

A: After loading the library, what you need is to find the function pointer. The function Microsoft provides is GetProcAdderess. Unfortuantely, you have to know function prototype. If you don't knwo, we are going all the way to COM/DCOM, etc. Probably out of your scope.
FARPROC WINAPI GetProcAddress( _In_  HMODULE hModule, _In_  LPCSTR lpProcName );

So in your example, what you do nromally is like this:
typedef int (*THelloFunc)(int,int);  //This define the function prototype

if (hinstLib != NULL)
{
    //
    // code to handle function call goes here.
    //

    THelloFunc f = (THelloFunc)GetProcAddress(hinstLib ,"Hello");

    if (f != NULL )
        f(1, 2);

    // Free the dll when we're done
    FreeLibrary(hinstLib);
}


text:
Q: Teradata column not sorting correctly I'm trying to join two tables by a column, and sort a table by the same column.
Here is some example data from the two tables:
table.x
state
00039
01156

table.y
state
39
1156

How do I join and sort the tables in SQL assistant?

A: Simplest solution would be to cast both sides to integer as @Andrew mentioned, so you could use simple casting, or trycast(...) which will try to cast the value and if that fails won't return an error, but NULL value instead:
select *
from x
inner join y on
  trycast(y.state as integer) = trycast(y.state as integer)
order by y.state

Old answer (leaving this here for sake of future readers and what you can / can't do):
If you have a recent version of Teradata (you didn't specify it) you would also have LPAD function. Assuming that y.state is not text, but a number we'd also need to cast it, as lpad takes string as argument. If it is, omit cast(...):
select *
from x
inner join y on
  x.state = lpad(cast(y.state as varchar(5)), 5, '0')
order by y.state

If you don't have an LPAD function, then some dirty code with substring might come in handy:
select *
from x
inner join y on
  x.state = substring('00000' from char_length(cast(y.state as varchar(5))+1) || cast(y.state as varchar(5)
order by y.state

Above assumes that you store numbers within maximum 5 digits. If it's beyond that number (your sample data says 5) then you need to adjust the code.


text:
Q: How to find linear equation from text A company produces covers for cell phones. The costs of a production of $x$ units can be described by a linear function $C(x)=ax+b$.
At a production of $150$ units the costs are DKK $6000$.
At a production of $200$ units the costs are DKK $7500$.
Find an equation for $C$

A: The first statement tells you $C(150) = 6000$, or $150 a + b = 6000$. The second statement tells you $C(200) = 7500$ or $200 a + b = 7500$.
Now, use linear combinations or substitution to solve the two equations together to get $a,b$.


text:
Q: Procedure error with '&' error screenshot I am trying to execute the below program in Toad.
create or replace procedure tst_excp as
    var_sal number;
    var_empid number;
    var_excp exception;
begin
    select sal into var_sal from emp
    where  empno = &var_empid;

    if var_sal < 4500 then
        raise var_excp;
    end if;
exception
    when var_excp then
        dbms_output.put_line ('The salary is low');
end;

and I am getting an error at the line: where empno = &var_empid;
error message is:
PL/SQL: ORA-00936: missing expression

I am planning to pass the value to the variable while executing it.

A: the & is part of the sqlplus (and TOAD, SQL Developer and PL/SQL Developer) runtime variables. it will prompt you on execution (in your case while compiling the procedure) for an input to replace in the code.
if you want the get an input for the procedure, so it will be added to the where clause on every run, you need to receive it as an input variable:
create or replace procedure tst_excp (var_empid in number) as -- << changed here
var_sal number;
var_empid number;
var_excp exception;
begin
    select sal into var_sal from emp
    where empno = var_empid; -- << changed here too

        if var_sal < 4500 then
        raise var_excp;
    end if;
    exception
    when var_excp then
    dbms_output.put_line ('The salary is low');
end;


text:
Q: Javascript MVC Controller and Click Events I'm having a problem with the click events not working using a Javascript MVC Controller.
TEST.Assignments.AssignmentsController = function (element) {

var elements = {
    activeAssignmentsPanel: $('#lpn-activeAssignments_Cont'),
    assignmentViewLink: $("#lpn-activeAssignments_Cont table tr th a")
};

var _this = this;
var model = new TEST.Assignments.AssignmentModel();

this.buildAssignmentsList = function () {
    var assignments = model.getActiveAssignmentsList({
        assignmentMode: "active",
        mock: true,
        success: function (data) {
                dust.render("ActiveAssignmentsPanel", data, function(err, out) {
                elements.activeAssignmentsPanel.append(out);
            });
        }
    });
};

this.getAssignmentDetails = function(assignmentId) {
    console.log(assignmentId);
};

//bind all events
elements.assignmentViewLink.click(function (e) {
    console.log("blah");
    console.log($(this).data("assignmentKey"));
});

};//end assignments controller

$(function () {
    var assignmentsController = new TEST.Assignments.AssignmentsController();
    assignmentsController.buildAssignmentsList();
});

If you look at the //bind events, I have a click function there that should be working. But it is not. The constructor is being called and the elements are traced out correctly. Any idea why the click event won't work?

A: I assume the assignmentViewLink elements are created and appended in the success callback. If so, it looks like a sequence problem. When you bind the click event, the assignmentViewLink elements have not been created yet, and hence, the click eventhandler isn't attached.
//bind all events
// assignmentViewLink is empty []
elements.assignmentViewLink.click(function (e) {
  console.log("blah");
  console.log($(this).data("assignmentKey"));
});

To verify this, move the elements.assignmentViewLink(...) into the success callback.


text:
Q: Laravel 5.5 middleware does not work I have middleware called IsAdmin, here is the code for it:
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class IsAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $user = Auth::user();

        if ($user->role === 10)
        {
            Session::flash('error', 'Трябва да сте администратор за да видите тази страница.');
            return redirect('/home');
        }

        return $next($request);
    }
}

here is registering it in the kernel:
<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\TrustProxies::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'isadmin' => \App\Http\Middleware\IsAdmin::class,
    ];
}

and here is how I am protecting the routes in the controllers:
public function __construct()
{
    $this->middleware(['auth', 'isadmin']);
}

the auth middleware works just fine.
The isadmin middleware stopped working when I changed the permission field I use in the database, on the user model. It used to be "$user->is_admin" and I've changed it to "$user->role" now even reverting back to the old way doesn't fix the problem.
Here is also the migration for the User model:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->tinyInteger('role')->default(0);
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Here are also my routes or web.php file:
<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('auth.login');
});

Auth::routes();

Route::get('/home', 'ReportController@home')->name('home');
Route::get('/dashboard', 'HomeController@dashboard')->name('dashboard');

Route::resource('/obekti', 'ObektiController');
Route::resource('/entrances', 'EntrancesController');
Route::resource('/apartments', 'ApartmentsController');
Route::resource('/people', 'PeopleController');
Route::resource('/boardmembers', 'BoardMembersController');
Route::resource('/companies', 'CompaniesController');

Route::get('/apartments/{id}/people', 'ApartmentsController@people');
Route::get('/entrances/{id}/apartments', 'EntrancesController@apartments');
Route::get('/obekti/{id}/entrances', 'ObektiController@entrances');
Route::get('/obekti/{id}/boardmembers', 'ObektiController@boardMembers');

Route::post('/search', 'HomeController@search');

A: If you are including your middleware inside $routeMiddleware property then you can use the middleware method to assign middleware to a route:
try this
Route::get('/dashboard', 'HomeController@dashboard')->name('dashboard')->middleware(['isadmin','auth']);

or you can use the group method
Route::group(['middleware' => ['isadmin', 'auth']], function () {
    //
});

A: The problem was this line:
if ($user->role === 10)

it should've been this:
if ($user->role === 0)


text:
Q: What is the best way to float elements of the same class side by side? HTML/CSS beginner here, trying to figure out the best way to do things. Ideally it would be nice to have an explanation as well as a solution.
So what I'm trying to do is placing several buttons (maybe 5-6) side by side, followed by a label
The buttons are formatted using the same CSS class. To place them side by side, I am setting float: left;
Unfortunately, this places the next element after the buttons (the label) on the same line as well, even if I set clear: both; for the label.
The problem is that float: left; governs how other elements format around the given element. This is great for the first n-1 buttons since it places the next button to the side of it. But it also places the label next to the last button.
Is there a way to fix this behavior without having to add specific CSS formatting to the last button, or provide a specific width which forces the label to be on the next line? (like maybe a different method of doing this altogether?)
This is a sample of what I'm doing now:

  <button class="myButton">Button 1</button>
  <button class="myButton">Button 2</button>
  <button class="myButton">Button 3</button>
  <button class="myButton">Button 4</button>
  Output Text

Thanks

A: label is, by default, an inline element. clear however only works on block-level elements, which makes sense.
You would have to wrap the buttons in a separate element, and/or apply display:block to the label.

A: You don't need to float your buttons; they will naturally flow next to each other the same as text (kinda). If you want to put the label on its own line, you have a couple options:

*

*Put a line break (
) in the html between the last button and the label

*Make your label display: block; in the CSS, which will ensure that it's the only thing on its line (after the floats are gone)

A: Please check this: jsFiddle. I basically wrapped the buttons in a
 and assigned the following styles to that
.
#buttons {
    width: 100%;
    overflow: hidden;
}


text:
Q: How to get currently displayed fragment in viewpager I'm new with viewPagers. Here is my problem. I've got a viewPager containing  3 fragments, inside an activity. I've a Next button which triggers different actions according to different fragments. Currently I'm applying following method:
btnNext.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        if(viewPager.getCurrentItem() == 0){
            mViewPager.setCurrentItem(getItem(+1), true);
        }else if(viewPager.getCurrentItem() == 1){
            // trigger something
        }
    }
});

When I am in position 0, if I click next button, viewPager swipes to second fragment and both conditions are triggered! Isn't it supposed to be the first one only ? How to trigger one action at a time for corresponding fragment position? Any help will be greatly appreciated.

A: You can try something like this:
btnNext.setOnClickListener(new OnClickListener() {

 @Override
       public void onClick(View view) {
         if(viewPager.getCurrentItem() == 0){
           viewPager.setCurrentItem(viewPager.getCurrentItem() + 1,true);
         }
         else if(viewPager.getCurrentItem() == 1){
            // trigger something
         }
       }
    });

A: Perform operation in listener call back methods
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        //Do it here
    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
});

Please let me know if it helps.


text: Q: Turn off audio in web app when iOS device is locked I am building a web application with sound - when I run it on iOS (in a browser, mobile Safari or Chrome - I'm not using a native wrapper like PhoneGap) and lock the screen, the sound keeps playing.  Is there any way to detect from a webapp whether the user has locked the screen and to turn the sound off when the screen is locked?


text:
Q: How to loop over local storage removing elements with the same value Assume that there are some data stored in local storage like:

*

*key  :  value

*item1:   1

*item2:   4

*item3:   2

*item4:   1

*item5:   4
and I want the result to be like:

*

*"item1: value 1 repeated 2 times"

*"item2: value 4 repeated 2 times"

*"item3: value 2 repeated 1 time"

and delete the similar value items
I am using js, html, css


text:
Q: TweetSharp 'GetRequestToken' return no token on Windows Phone 7.1 I'm trying to share picture to twitter in my app with TweetSharp, the code is as follow:
TwitterService TwitterApi = new TwitterService("My_consumerKey", "My_consumerKey_Secret");
TwitterApi.GetRequestToken(twitterProcessRequestToken);

private void twitterProcessRequestToken(OAuthRequestToken token, TwitterResponse response)
{
    //...
}

but when twitterProcessRequestToken was invoked, the token is null and response.StatusCode is 'Not Found'.
Because I'm in China now and the government has forbidden accessing to Twitter.com with GFW, I have to set up a proxy to access the Twitter.com. I don't know if the proxy lead to this problem. But I could access Twitter with IE integrated in WP7.
So how can I fix this problem?

A: I solved this problem. It is because I use a proxy server to across the GFW and the proxy server will resist the Authentication Request


text:
Q: Delegate and AddClass not working I am having a problem with getting this piece of code to work. Its built to allow for a user to click on one row to "select" it by highlighting via a different class. If another row is clicked, that one is highlighted and the current one is cleared. If one that is already highlighted is clicked again, it will be cleared back to normal.
This is within an ajax call to refresh the page, so everytime the call finishes and inserts the html for the table, this function below is then called. For some reason, every other reload of the table, this works. Ive tracked down the the line that is not functioning to be $(this).addClass(selectedUserClass) at the end of the function. The debug console log I put in there works, with the right class, but the next section does not add the class for some reason.
In firebug, the line changes from .. to , but it doesn't change? I've been looking at this for hours and I can't figure it out. Thanks for any help!
function loadUserListener(style) {
    if (style == "normal") {
        selectedUserClass = 'selectedUser';
        selectedJQueryClass = '.selectedUser';
    } else {
        selectedUserClass = 'selectedUserInverted';
        selectedJQueryClass = '.selectedUserInverted';
    }
    console.log('setting');
    $("#selectuser").delegate("tr", "click", function () {
        if ($(this).hasClass(selectedUserClass)) {
            $(selectedJQueryClass).removeClass(selectedUserClass);
        } else if ($(selectedJQueryClass)[0]) {
            console.log('another');
            $(selectedJQueryClass).removeClass(selectedUserClass);
            $(this).addClass(selectedUserClass);
        } else {
            console.log(selectedUserClass);
            $(this).addClass(selectedUserClass);
        }
    });
}

A: adeneo pointed out some things for me, mainly that the listener is still there even though the table is refreshed, so after every ajax call, a listener is being put on another which results in the functionality that only works on 'even' calls.
I used the 'off' function from jquery to clear the event handler every time this listener loading function is called. I also switched delegate to on to be more correct.
I essentially did this:
$('.selectuser').off("click");


text:
Q: text/plain and text/html with c++ mail I am using System::Net::Mail to send emails.
I was questioned about is it able to send two versions of email:
1) the html version of email for clients that can read html emails
2) text/plain for people who can't read html emails, and also the html version will be attached
is this possible using System::Net::Mail? I know how to enable HTML body version, but, how to send to types of message?
Thanks!

A: To let the recipient decide which version she wants to read, the mail needs to be composed using the multipart/alternative MIME type. System.Net.Mail supports this by means of the System.Net.Mail.MailMessage.AlternateViews collection.


text:
Q: cmd.ExecuteNonQuery(); SqlException Unhandled Every time I click the button without a value (null, or blank), I get an error.
This is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;

namespace Fifth_Attempt
{
    class Prof
    {
        public SqlException AddProfessorInformation(ProfModel oPM)

        {
            string connStr = @"Data Source=USER-PC;Integrated Security=True;";
            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connStr);
            SqlCommand cmd = new SqlCommand("INSERT INTO ProfInfo(ID,FirstName,MiddleName,LastName,Department,Username,Password)  VALUES(@LRN,@FirstName,@MiddleName,@LastName,@Department,@Username,@Password)", conn);
            cmd.Parameters.AddWithValue("@ID", oPM.ID);
            cmd.Parameters.AddWithValue("@Firstname", oPM.FirstName);
            cmd.Parameters.AddWithValue("@MiddleName", oPM.MiddleName);
            cmd.Parameters.AddWithValue("@LastName", oPM.LastName);
            cmd.Parameters.AddWithValue("@Department", oPM.Department);
            cmd.Parameters.AddWithValue("@Username", oPM.Username);
            cmd.Parameters.AddWithValue("@Password", oPM.Password);
            conn.Open();
            cmd.ExecuteNonQuery();
            return null;

        }
    }
}

>link to full code
why do I get the error?

A: why add parameter for @LRN missing ?
cmd.Parameters.AddWithValue("@LRN", ??);


text:
Q: xsd traversing in java How to traverse XSD using java and put into some data structure? I want to traverse XSD and collect all attributes and their constraints(like min./max values)  The options i see are XSOM(Parsing XSD Schema with XSOM in Java. How to access element and complex types) which is not maintained. Other option is to use JAXB, to create Java classes and then use reflection to get all the attributes which looks time consuming.
Is there any other way ?


text:
Q: InfoPath 2010 form not getting into form library I have an InfoPath 2010 form published in SharePoint. When I select "Add Document" I get the form in the browser, I fill it in and Submit it. It gives no errors but it doesn't get added to the Form Library.
Any idea on what I may be missing here?
Thx in advance

A: Open the form in InfoPath Designer and check that the Submit options are correct, i.e. pointing to the right library.


text:
Q: Updating a table which contains an Image datatype column I have a table which contains a few columns, one of which is an image datatype, this is used to store BLOB data, which could be anything from a jpg to a large PDF.
I have a requirement to update one of the other columns in the table, however the query is taking a ludicrously long time to complete - that's if it does complete at all.
The table is the following format:
ID (int), HexData (image), FileName(nvar), Filetype(nvar), folder(nvar), user(int)
The query used is simply -
update [database].[dbo].[myTable]
set user = 5
where id = 2

This is a test table on a test database, not the live system. There are only 5 rows, no indexes (including clustered), and no other tables in the database.

A: The table in question is a heap. This storage structure does not release pages made empty by delete operations, unless the delete occurs while an exclusive table lock is taken (and not always then).
From DELETE (Transact-SQL) in the documentation:

To delete rows in a heap and deallocate pages, use one of the following methods.
  Specify the TABLOCK hint in the DELETE statement. Using the TABLOCK hint causes the delete operation to take an exclusive lock on the table instead of a row or page lock. This allows the pages to be deallocated.

The upshot is that your table likely contains a large number of empty pages allocated for rows the heap held in the past. You can check this using:
SELECT
    DDIPS.index_id,
    DDIPS.partition_number,
    DDIPS.index_type_desc,
    DDIPS.alloc_unit_type_desc,
    DDIPS.index_depth,
    DDIPS.index_level,
    DDIPS.page_count,
    DDIPS.record_count,
    DDIPS.ghost_record_count,
    DDIPS.version_ghost_record_count,
    DDIPS.forwarded_record_count
FROM sys.dm_db_index_physical_stats
    (
        DB_ID(),
        OBJECT_ID(N'dbo.Heap', 'U'), -- Your table name here
        0,
        NULL,
        'DETAILED'
    ) AS DDIPS;

Without any indexes, the only way for the SQL Server to process the update query is to employ a full table scan. This will touch every data page allocated to the table, including the empty ones. If there are many pages that must be brought into memory from permanent storage, this can take a long time.
The solution is to rebuild the heap table using ALTER TABLE <table_name> REBUILD, or create a clustered index.
The image data type has been deprecated in favour of varbinary(max) for a very long time now. If you have any freedom to change this, you probably should. Even so, it is also possible that the existence of this LOB column is causing the slowness through a quite separate mechanism I describe in detail here on SQLblog.com:

*

*Deletes that Split Pages and Forwarded Ghosts
From that article:

Summary
If you ever wonder why your deletes are so slow, it is worth checking to see if you are suffering from page splitting due to an enabled trigger and a table definition that allows for LOB allocations or ROW_OVERFLOW.
Any table with a LOB column (including the max data types) qualifies, as does one with even a surprisingly small number of variable-length columns, as shown in the examples in this post.
This is a great reason to avoid using 'max' or old-style LOB data types unnecessarily, and to be careful about the maximum length of 'normal' variable-length data types too.
Remember, it is the potential maximum row size that is important, not the actual row size.


text:
Q: Use offset of Windowstart in azure data factory I wish to incrementally copy data from azure table to azure blob. I have created linked services, datasets and pipelines. I wish to copy data from table to blob after every hour. The table has a timestamp column.I want to transfer data from table to blob in such a way that the data which gets added to the table from 7am to 8am should be pushed to blob in activity window starting at 8 am. In other words, I don't want to miss any data flowing into the table.

A: I have changed the query used to extract data from the azure table.
"azureTableSourceQuery": "$$Text.Format('PartitionKey gt \\'{0:yyyyMMddHH} \\' and PartitionKey le \\'{1:yyyyMMddHH}\\'', Time.AddHours(WindowStart, -2), Time.AddHours(WindowEnd, -2))"

This query will get data which was added to the table 2 hours back and hence I wont miss any data.


text:
Q: Why do I keep getting "error: expected unqualified-id before 'case'"? I'm making a code where the users decide which shape they want to see using a switch statement.  I was doing fine with the first four cases but I ran into trouble when I got to the fifth one.  I Keep getting an error saying "error: expected unqualified-id before 'case' " whenever I try to make a fifth case and I can't figure out the issue.
What is happening with my code?
    #include <iostream>
using namespace std;
int main() {
int choice;
cout << "Please enter the shape you would like to see" << endl;
cout << "1. Rectangle" << endl;
cout << "2. Square" << endl;
cout << "3. Right Triangle" << endl;
cout << "4. Isosceles Triangle" << endl;
cout << "5. Kite" << endl;
cout << "6. Quit" << endl;
cin >> choice;

switch(choice){
    case 1 : double length,width; //rectangle
             cout << "Enter the length and width of the rectangle" << endl;
             cin >> length >> width;
             for(int i = 0; i < length; i++){
             for(int j = 0; j < width; j++){
             cout << "*";
             }
             cout << "\n";
             }
    break;
    case 2 : cout << "Enter the length and width of the square" << endl;
             //square
             cin >> length >> width;
             for(int i = 0; i < length; i++){
             for(int j = 0; j < width; j++){
             cout << " * ";
             }
             cout << "\n";
             }
    break;
    case 3 : cout << "Enter the length of the triangle" << endl;
             //right triangle
             cin >> length;
             for(int i = 0; i < length; i++){
             for(int j = 0; j < i; j++){
             cout << "*";
             }
             cout << "\n";
             }
    break;
    case 4 : int star=1;
             for(int i=1;i<=5;i++){
             for(int j=4;j>=i;j--){
             cout<<" ";
             }
             for(int z=0;z<star;z++){
             cout<<"*";
             }
             cout<<endl;
             star=star+2;
             }
             }
             }
    case 5 : cout << "???";

A: Your curly braces are mismatched. You have two extra } before case 5.
These braces should go after case 5. One for the switch statement, one for the main function.
In addition, your #include on the first line should not have any indentation.


text:
Q: Testing command line parameters What is the best way to test a command line parameter from within the Visual Studio C# Express 2010 IDE?  All i see is the "Play" button to start debugging (and running) my program.

A: Setting the arguement value in the project properties is good if the values don't change.
If you are wanting to test many different command line arguement combinations, going to the Properties window between each run can get very tedious.  One way to get around this is to place a breakpoint on the { at the start of the Main method and set a debug watch on the command arguments.
Then all that is needed is to run the program, wait for it to break and then edit the value of the arguement in the watch window.  When you continue execution it will be as if you had given those command line arguements.

A: Right click the project in Solution Explorer, select Properties, then the Debug tab. Here you will see a textbox labeled "Command line arguments". If you enter any arguments here, they will be passed as command line arguments when you debug, ie. "hit Play".

A: You could set command line arguments in the properties of the project:


text:
Q: UNity3D, return value from one class/method to another class/method in Unity3D In Unity3D,
I have a weapon script and a stamina script. What I want to do now is to drain stamina when my weapon swings.
I tried my code and i have been playing around with it for a couple of hours.
I am using unity so it also gives me a comment about using new and that I should use Add.component etc so I would appreciate an answer to that question as well!
Hopefully this post is a bit better in terms of the title and information/layout as I am very tired and low on energy. Im going to take a short food break before I get back to it!
Here is the Stamina system:
`
public class HandS : MonoBehaviour {

public int startingHealth = 100;
public int currentHealth;
public int healthReg;
Sword mySword;

bool isRegenHealth;

public float startingStam = 100;
public float currentStam;
public float stamReg;

bool isRegenStam;

void Awake()
{
    currentStam = startingStam;
}

void Update()
{
    if (currentStam != startingStam && !isRegenStam)
    {
        StartCoroutine(RegainStamOverTime());
    }
}

private IEnumerator RegainStamOverTime()
{
    isRegenStam = true;
    while (currentStam < startingStam)
    {
        Stamregen();
        ReduceStamina(mySword.stamDrain);
        yield return new WaitForSeconds(1);
    }
    isRegenStam = false;
}

public void Stamregen()
{
    currentStam += stamReg;
}

public void ReduceStamina(float _stamDrain)
{
    currentStam -= _stamDrain;
}

}
`
Here is the Sword script:
using UnityEngine;
using System.Collections;

public class Sword : MonoBehaviour {
static Animator anim;
public GameObject hitbox;
HandS hp = new HandS();
public int Sworddamage = 20;
public float sec = 0.5f;
public float maxStamina = 20;

public float  AttackCD;
public float delayBetweenAttacks = 1.5f;
public float stamDrain = 50;

public AudioSource WeaponSource;
public AudioClip WeaponSound;

void Start () {
    anim = GetComponentInParent<Animator>();
    WeaponSource = GetComponent<AudioSource>();
}

// Update is called once per frame
void Update () {
    attack();
    block();

}
public void attack()
{
        if (Input.GetButtonDown("Fire1") && Time.time > AttackCD)
    {
        AttackCD = Time.time + delayBetweenAttacks;
        anim.SetBool("IsAttacking", true);
        hitbox.SetActive(true);
        StartCoroutine(LateCall());
        WeaponSource.PlayOneShot(WeaponSound);
        Debug.Log("hit");
        hp.ReduceStamina(stamDrain);
    }
    else
    {
        anim.SetBool("IsAttacking", false);
    }

}
public void block()
{
    if (Input.GetButtonDown("Fire2"))
    {
        anim.SetBool("IsBlocking", true);
    }
    else
    {
        anim.SetBool("IsBlocking", false);
    }
}

IEnumerator LateCall()
{
    yield return new WaitForSeconds(sec);
    hitbox.SetActive(false);
}

}

A: You can create getter/setter methods to set/get attributes from the Class A.
In your class B, you can create an instance o class A and access to that attibutes.
Example Class A:
public class Genre
{
    public string Name { get; set; }
}

Example instance in Class B:
Genre genre = new Genre();
string name = genre.getName();

Hope it helps.


text:
Q: Integration Facebook SSO is not working I am integrating Facebook SSO and it was working fine with my two of the apps and now when i am configuring it with my third app its just not working. Below is my errors i am getting in the logcat. please anyone help me out.
     09-22 18:01:38.885: E/ActivityThread(10499): Failed to find provider info for  com.facebook.katana.provider.AttributionIdProvider
     09-22 18:02:19.805: E/ActivityThread(10499): Failed to find provider info for com.facebook.katana.provider.PlatformProvider
     09-22 18:02:19.815: E/ActivityThread(10499): Failed to find provider info for com.facebook.wakizashi.provider.PlatformProvider
     09-22 18:02:29.674: D/dalvikvm(10499): GC_EXPLICIT freed 561K, 45% free 3422K/6151K, external 5536K/6743K, paused 76ms
     09-22 18:02:38.753: D/Request(10499): Warning: Sessionless Request needs token but missing either application ID or client token.

A: Follow the tutorial and exmaple might be you missed out some steps its worked for me:
https://developers.facebook.com/docs/android/getting-started
https://github.com/facebook/facebook-android-sdk


text:
Q: Looking for 80s sci-fi movie, Aliens who fuse, Robotic Band Members So im looking for a movie I think is from the 80s (maybe 90s) involving two aliens and a robot band (I think).
I remember seeing this movie as a kid during the 90s. The only thing I can remember where to alien creatures riding in a shopping cart in a mall. Outside of the mall the two alien creatures "collided" and fused with each other. And also there was a robot band (I think). I am sorry if this sounds kind of "druggy" or whatever but I have a very clear memory of this particular scene/scenes. I also remember the alien creatures looking somewhat like E.T (short, brownish).
Please tell me that this is not some kind of fever dream I had as a kid.

A: This sounds like Bill and Ted's Bogus Journey.
The plot involved four robot copies of the title characters (who themselves were time travelling musicians and star of the previous movie, Bill And Ted's Excellent Adventure).  Towards the end, two of them (the ones that looked more robotic) joined the band.

The aliens were called "Station", an alien genius they met in Heaven (after they were killed by their evil robot duplicates), who built the Good-Robot-Bill-and-Ted and they fused together into one larger alien who also could only say "Station".

The Grim Reaper, Death himself, also joined the band.


text:
Q: Mutually inverse functions based on the two real branches of the Lambert W function $\require{begingroup} \begingroup$
$\def\e{\mathrm{e}}\def\W{\operatorname{W}}\def\Wp{\operatorname{W_0}}\def\Wm{\operatorname{W_{-1}}}$
Let
\begin{align}
f_0(x)&=-\Wp(-\tfrac1x\,\exp(-\tfrac1x))
\tag{1}\label{1}
,\\
f_1(x)&=-\frac{1}{\Wm(-x\,\exp(-x))}
\tag{2}\label{2}
,\quad x\in(0,1)
.
\end{align}
Then
\begin{align}
f_1(f_0(x))&=x
\tag{3}\label{3}
,\\
f_0(f_1(x))&=x
\tag{4}\label{4}
.
\end{align}
Note that
for $x\in(0,1)$
\begin{align}
\Wp(-\tfrac1x\,\exp(-\tfrac1x))
\ne -\tfrac1x
\tag{5}\label{5}
,\\
\Wm(-x\,\exp(-x))
\ne -x
\tag{6}\label{6}
.
\end{align}
Here is a graph:

The area under the curve $f_1(x)$ is
\begin{align}
\int_0^1 f_1(x)\,dx &=\gamma
\approx 0.5772156649
,
\end{align}
hence the area bounded by
$f_0(x)$ and $f_1(x)$ is $2\gamma-1$.
Question: is there known references where these
mutually inverse functions were used?
$\endgroup$


text:
Q: Flurry API crashing iPhone simulator My app is crashing using iOS5 and iOS4.3 iPhone simulators in Xcode 4.2, the stack trace shows BAD_ACCESS signal in [FlurryAPI stopBackgroundTask] method.
While in the iOS4.3 simulator the app is only crashing when sending the app to background, in iOS5 is crashing always.I am attaching a picture of the debug navigator showing the thread where the BAD_ACCESS is happening.
On the other hand the app is working fine using a real device.
Any ideas of how can I get more information of what is going on and why this is happening?

A: I've worked around this issue by adding the following to didFinishLaunchingWithOptions
#if TARGET_IPHONE_SIMULATOR
        [FlurryAnalytics setSessionReportsOnPauseEnabled:NO];
#endif

A: Flurry analytics does not run other than main Thread. It might crash on background thread.

A: It looks like you have a zombie - you have a situation where you're using code after you've released it.  The retain count reaches zero, so the system dealloctes and re-uses the memory, then you make a change through the original reference.  Now you have two different references to the same memory, each of which expects a different object to be there.  In your case, one of the references is within flurry.
The reason for your device/simulator differences is the different memory allocation schemes the two architectures use - the simulator seems to re-use memory very aggressively.
Enable NSZombie and run in the debugger.  If you're lucky, it will give you the object and the point it's used after deallocation.
Enable NSZombie: Menu 'Product', 'Edit Scheme...'  'Run' page, 'Diagnostics' tab, tick 'Enable Zombie Objects'.


text:
Q: pm.sendRequest is working after the for loop iteration is completed even though the request is inside the loop I'm trying to trigger a "pm.sendRequest" inside a for loop and the request is getting sent only after the iteration is completed, though I have kept the request inside the loop.
This is how my code looks like in the test section,
for (i = 0; i < 5; i++) {
    const requestObject = {
        url: "https://reqres.in/api/users?page=2",
        method: "GET",
        header: "Content-Type:application/json",
    };

    console.log(i);

    pm.sendRequest(requestObject, (err, res) => {
        console.log(i);
    });
}

The "i" which is getting printed inside the pm.sendRequest is alwas printed as 5.
Could you please help me in resolving this issue.

A: pm.sendRequest() is an asynchronous function it calls the callback which get resolved as when it requires
THere is no order for this
so inside forloop the function call is initiated but you get the output after the forloop gets completed


text:
Q: Algorithm design manual solutions error? I've read about Big O notation from many sources, including Skiena and the Wikipedia entry, the Example section of which states:

In typical usage, the formal definition of O notation is not used
  directly; rather, the O notation for a function f(x) is derived by the
  following simplification rules:

*

*If f(x) is a sum of several terms, the one with the largest growth rate is kept, and all others omitted.

*If f(x) is a product of several factors, any constants (terms in the product that do not depend on x) are omitted.

The solution to problem 2.2 is O((n^3)/3).  Shouldn't the "/3" be omitted, or am I missing something?

A: The constants do not need to be omitted, they just don't carry any information - O(n^3) is the same as O(n^3 / 3). You'll note that the quoted passage discusses typical usage, not rigorous requirements.
Looking at the specific answer, the solution is asymptotically equivalent to n^3 / 3. While not formally any different than O(n^3), I'd guess the idea is to provide more specific information by giving O(n^3 / 3).

A: Not must, positive constant factors are allowed in O-notation. They are just pointless and therefore should be omitted.

A: You are correct. 1/3 is a constant, and therefore should omitted.

A: You're correct, to be proper, O(n^3 /3) (i.e., O(1/3 * n^3)) should have the 1/3 coefficient omitted from the final answer. This is because the 1/3 component of the expression is trivial with extremely large n. This would be a good opportunity to edit Wikipedia and make the correction.

A: Let me give an example.
suppose we have function,
                f(n)=1/3 * (4n^3) + 4n^2+ 1

 lets gather all the facts...

 we know that ,
          for all sufficient large value of n>=1
              1/3 * (4n^3) <= 1/3 *  4n^3

          for all sufficient large value of n>=1
               4n^2 <= 1/3 * 12n^3

      and similarly, for all sufficent large value of n>=1
                  1 <= 1/3 * 5n^3

  thus we can conclude that,
   1/3 * (4n^3) + 4n^2+ 1  <= 1/3 * 4n^3 + 1/3 * 12n^3+1/3 * 5n^3   , where n >=1

  lets simplify it,
           1/3 * (4n^3) + 4n^2+ 1  <= (1/3) * 21n^3
                            f(n)   <= (1/3) * 21n^3
                            f(n)   <= ((1/3)*21)*n^3
                            f(n)   <= (7)*n^3
                            f(n)   = O(n^3) , where c=7 and n0=1

 if we don't include 1/3 in c than,
                            f(n)   <= (1/3) * 21n^3
                            f(n)   <=  (21)*(n^3 /3)
                            f(n)   = O(n^3 /3), where c=21 and n0=1

 so the constant value 'c' will be changed.


text:
Q: (Single Layer) Perceptron in PyTorch, bad convergence I'm trying to develop a simple single layer perceptron with PyTorch (v0.4.0) to classify AND boolean operation.
I want to develop it by using autograd to calculate gradient of weights and bias and then update them in a SGD manner.
The code is very simple and is the following:
# AND points and labels
data = torch.tensor([
    [0, 0],
    [0, 1],
    [1, 0],
    [1, 1]
    ], dtype=torch.float32)
labels = torch.tensor([0,0,0,1], dtype=torch.float32)

weights = torch.zeros(2, dtype=torch.float32, requires_grad=True)
bias = torch.zeros(1, requires_grad=True)
losses = []
epochs = 100
eta = 0.01
for epoch in range(epochs):
    total_loss = 0
    for idx in range(4):
        # take current input
        X = data[idx,:]
        y = labels[idx]

        # compute output and loss
        out = torch.add(torch.dot(weights, X), bias)
        loss = (out-y).pow(2)
        total_loss += loss.item()
        # backpropagation
        loss.backward()

        # compute accuracy and update parameters
        with torch.no_grad():
            weights -= eta * weights.grad
            bias -= eta * bias.grad
            # reset gradient to zero
            weights.grad.zero_()
            bias.grad.zero_()
    losses.append(total_loss)

The model converges, as you can see from the learning curve

but the resulting plane is:

with 50% of accuracy.
I tried with different inital parameters and also by using the SGD optimizer from PyTorch but nothing changed.
I know that MSE is a regression loss but I don't think the problem is there.
Any ideas?
Update
The plane is computed with these 2 lines of code
xr = np.linspace(0, 1, 10)
yr = (-1 / weights[1].item()) * (weights[0].item() * xr  + bias.item())
plt.plot(xr,yr,'-')

A: The equation you use to compute the plane
yr = (-1 / weights[1].item()) * (weights[0].item() * xr  + bias.item())

is derived in the case where y_i = [+1, -1] and there is a sign function: it's computed by looking for the plane that separates positive and negative examples. This assumption is not valid anymore if you change targets.
If you draw this:
x1 = np.linspace(0, 1, 10)
x2 = np.linspace(0, 1, 10)
X, Y = np.meshgrid(x1, x2)
w1, w2 = weights.detach().numpy()[0, 0], weights.detach().numpy()[1, 0]
b = bias.detach().numpy()[0]
Z = w1*X + w2*Y + b

which is the correct plane in 3D, you get the correct separation
You can get a correct separation with your formula if you offset by a factor that depends on the average of the labels, like:
yr = (-1 / weights[1].item()) * (weights[0].item() * xr  + bias.item() - 0.5)

but I can't come around at justifying it formally.

A: I managed to solve the problem in 2 different ways:
Method 1 - Change labels in -1 and 1
By simply changing labels from (0, 1) to (-1, 1) the plane is computed correctly.
Hence, the new labels (same data) are:
labels = torch.tensor([-1,-1,-1,1], dtype=torch.float32)

Method 2 - Add a sigmoid function after out
With (0, 1) labels, add a sigmoid function just after computing out, in this way:
out = torch.add(torch.dot(weights, X), bias)
out = torch.sigmoid(out)

I think that method 1 accounts for the sign function of the perceptron, as the plan must discriminate points based on the sign of the output.
The method 2 adapts this reasoning for (0,1) labels by using a squashing function.
These are just tentative, partial explanations. Try to comment below with more accurate ones.


text:
Q: How to cache all directories of my repository using Gitlab CI I have a problem, how could I cache multiple directories in gitlab ci? When Gitlab-runner download the repository, inside I have like 10 folders (diferent projects), some project depeneds of another, so I would like do it available for the next jobs.
I thought do it something like that, without specifying all folders manually
cache:
  paths:
    - "./"

Could be work this or I need something else?
Thanks in advance

A: If what you want is to cache all the untracked files and directories of the repository, yo can use untracked:true
job_name:
  script: test
  cache:
    untracked: true

You can also combine this with the path keyword like this:
rspec:
  script: test
  cache:
    untracked: true
    paths:
      - your_path/

You may use wildcards for the paths too like your_path/*.jar to take every .jar file in the directory.
I point you to the official GitLab documentation for more info: GitLab-CI documentation


text:
Q: Combine return and switch How can I combine return and switch case statements?
I want something like
return switch(a)
       {
          case 1:"lalala"
          case 2:"blalbla"
          case 3:"lolollo"
          default:"default"
       };

I know about this solution
switch(a)
{
    case 1: return "lalala";
    case 2: return "blalbla";
    case 3: return "lolollo";
    default: return "default";
}

But I want to only use the return operator.

A: switch(a)
{
    case 1: return "lalala";
    case 2: return "blalbla";
    case 3: return "lolollo";
    default: return "default";
}

A: This is the closest I can think of:
return    a==1 ? "lalala"
        : a==2 ? "blalbla"
        : a==3 ? "lolollo"
        : "default";

A: My mapping solution looks like Jordão's solution but it is more flexible and shorter.
return a
  .Map(1,"lalala")
  .Map(2,"blabla")
  .Map(3,"lololo")
  .Else(string.Empty);

Both arguments can also be a function:
return a
    .Map(x => x <= 0, "lalala")
    .Map(2, "blabla")
    .Map(x => x >= 3, x => "lololo" + x.ToString()); // lololo3 etc.

A: I've created a Nuget package (FluentSwitch) that should do what you want. So you can do the following:
var result = myValue.Switch()
    .When(1, "lalala")
    .When(2, "blalbla")
    .When(3, "lolollo")
    .Else("default")
    .Value();

A: Note: As of C#8 (ten years later!) this is now possible, please see the answer below.

switch and return can't combine that way, because switch is a statement, not an expression (i.e., it doesn't return a value).
If you really want to use just a single return, you could make a Dictionary to map the switch variable to return values:
var map = new Dictionary<int, string>()
{
    {1, "lala"},
    {2, "lolo"},
    {3, "haha"},
};
string output;
return map.TryGetValue(a, out output) ? output : "default";

A: I believe that this solution is the most straighforward one, and you should definitely use it:
switch(a) {
  case 1: return "lalala";
  case 2: return "blabla";
  case 3: return "lololo";
  default: return "default";
}

But, since you asked for one return, you could use this little fluent class:
public class Switch<TElement, TResult> {
  TElement _element;
  TElement _currentCase;
  IDictionary<TElement, TResult> _map = new Dictionary<TElement, TResult>();

  public Switch(TElement element) { _element = element; }
  public Switch<TElement, TResult> Case(TElement element) {
    _currentCase = element;
    return this;
  }
  public Switch<TElement, TResult> Then(TResult result) {
    _map.Add(_currentCase, result);
    return this;
  }
  public TResult Default(TResult defaultResult) {
    TResult result;
    if (_map.TryGetValue(_element, out result)) {
      return result;
    }
    return defaultResult;
  }
}

To create code like this:
  return new Switch<int, string>(a)
    .Case(1).Then("lalala")
    .Case(2).Then("blabla")
    .Case(3).Then("lololo")
    .Default("default");

Unfortunately, the type parameters could not be inferred by the compiler, and it feels a bit clumsy. The Default will trigger the evaluation of the "switch", and must be the last method call in the chain. Note that you always need a default value, since you've turned switch into an expression.
UPDATE: You can solve the type inference problem and drive the user to do the right thing with this code:
public static class Switch {

  public static SwitchBuilder<TElement>.CaseBuilder On<TElement>(TElement element) {
    return new SwitchBuilder<TElement>(element).Start();
  }

  public class SwitchBuilder<TElement> {
    TElement _element;
    TElement _firstCase;
    internal SwitchBuilder(TElement element) { _element = element; }
    internal CaseBuilder Start() {
      return new CaseBuilder() { Switch = this };
    }
    private ThenBuilder Case(TElement element) {
      _firstCase = element;
      return new ThenBuilder() { Switch = this };
    }
    private SwitchBuilder<TElement, TResult>.CaseBuilder Then<TResult>(TResult result) {
      return new SwitchBuilder<TElement, TResult>(
        _element,
        _firstCase,
        result).Start();
    }
    public class CaseBuilder {
      internal SwitchBuilder<TElement> Switch { get; set; }
      public ThenBuilder Case(TElement element) {
        return Switch.Case(element);
      }
    }
    public class ThenBuilder {
      internal SwitchBuilder<TElement> Switch { get; set; }
      public SwitchBuilder<TElement, TResult>.CaseBuilder Then<TResult>(TResult result) {
        return Switch.Then(result);
      }
    }
  }

  public class SwitchBuilder<TElement, TResult> {
    TElement _element;
    TElement _currentCase;
    IDictionary<TElement, TResult> _map = new Dictionary<TElement, TResult>();
    internal SwitchBuilder(TElement element, TElement firstCase, TResult firstResult) {
      _element = element;
      _map.Add(firstCase, firstResult);
    }
    internal CaseBuilder Start() {
      return new CaseBuilder() { Switch = this };
    }
    private ThenBuilder Case(TElement element) {
      _currentCase = element;
      return new ThenBuilder() { Switch = this };
    }
    private CaseBuilder Then(TResult result) {
      _map.Add(_currentCase, result);
      return new CaseBuilder() { Switch = this };
    }
    private TResult Default(TResult defaultResult) {
      TResult result;
      if (_map.TryGetValue(_element, out result)) {
        return result;
      }
      return defaultResult;
    }
    public class CaseBuilder {
      internal SwitchBuilder<TElement, TResult> Switch { get; set; }
      public ThenBuilder Case(TElement element) {
        return Switch.Case(element);
      }
      public TResult Default(TResult defaultResult) {
        return Switch.Default(defaultResult);
      }
    }
    public class ThenBuilder {
      internal SwitchBuilder<TElement, TResult> Switch { get; set; }
      public CaseBuilder Then(TResult result) {
        return Switch.Then(result);
      }
    }
  }

}

The result is this nice, type-safe, fluent interface; where at each step you'll only have the right choice of methods to call (e.g. Then after Case):
return Switch.On(a)
  .Case(1).Then("lalala")
  .Case(2).Then("blabla")
  .Case(3).Then("lololo")
  .Default("default");

A: Actually this is possible using switch expressions starting with C# 8.
return a switch
    {
        1 => "lalala",
        2 => "blalbla",
        3 => "lolollo",
        _ => "default"
    };

Switch Expressions

There are several syntax improvements here:

*

*The variable comes before the switch keyword. The different order
makes it visually easy to distinguish the switch expression from the
switch statement.

*The case and : elements are replaced with =>. It's
more concise and intuitive.

*The default case is replaced with a _
discard.

*The bodies are expressions, not statements.

For more information and examples check the Microsoft's C# 8 Whats New.

A: I normally do it this way:
var result = null;

switch(a)
{
    case 1:
        result = "lalala";
        break;
    case 2:
        result = "blalbla";
        break;
    case 3:
        result = "lolollo";
        break;
    default:
        result = "default";
        break;
};

return result;

A: With the new C# 8, you can combine both return and switch. The new switch is so cute.
public static RGBColor FromRainbow(Rainbow colorBand) =>
    colorBand switch
    {
        Rainbow.Red    => new RGBColor(0xFF, 0x00, 0x00),
        Rainbow.Orange => new RGBColor(0xFF, 0x7F, 0x00),
        Rainbow.Yellow => new RGBColor(0xFF, 0xFF, 0x00),
        Rainbow.Green  => new RGBColor(0x00, 0xFF, 0x00),
        Rainbow.Blue   => new RGBColor(0x00, 0x00, 0xFF),
        Rainbow.Indigo => new RGBColor(0x4B, 0x00, 0x82),
        Rainbow.Violet => new RGBColor(0x94, 0x00, 0xD3),
        _              => throw new ArgumentException(message: "invalid enum value", paramName: nameof(colorBand))
    };

The equivalent old switch is as below.
public static RGBColor FromRainbowClassic(Rainbow colorBand)
{
    switch (colorBand)
    {
        case Rainbow.Red:
            return new RGBColor(0xFF, 0x00, 0x00);
        case Rainbow.Orange:
            return new RGBColor(0xFF, 0x7F, 0x00);
        case Rainbow.Yellow:
            return new RGBColor(0xFF, 0xFF, 0x00);
        case Rainbow.Green:
            return new RGBColor(0x00, 0xFF, 0x00);
        case Rainbow.Blue:
            return new RGBColor(0x00, 0x00, 0xFF);
        case Rainbow.Indigo:
            return new RGBColor(0x4B, 0x00, 0x82);
        case Rainbow.Violet:
            return new RGBColor(0x94, 0x00, 0xD3);
        default:
            throw new ArgumentException(message: "invalid enum value", paramName: nameof(colorBand));
    };
}

You can read about this feature here.

A: If you want switch to return value, you can use delegate:
int a = 2;
string result = new Func<string>(delegate ()
{
    switch (a)
    {
        case 1: return "lalala";
        case 2: return "blalbla";
        case 3: return "lolollo";
        default: return "default";
    }
})();

Or:
int a = 2;
string result = new Func<int,string>(delegate (int i)
{
    switch (i)
    {
        case 1: return "lalala";
        case 2: return "blalbla";
        case 3: return "lolollo";
        default: return "default";
    }
})(a);

Or just use lambda:
int a = 2;
string result = new Func<int,string>((int i) =>
{
    switch (i)
    {
        case 1: return "lalala";
        case 2: return "blalbla";
        case 3: return "lolollo";
        default: return "default";
    }
})(a);

A: As an extension to others' responses, i recommend using tuples together with return switch when a few parameters are involved in decision making. This combination with discard is pretty strong:
return (param1, param2, param3) switch
{
    (value1, value2, value3) => returnValue1,
    (value2, _, value3) => returnValue2
    (value3, _, _) => returnValue3

}

Another sample by Microsoft:
https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#tuple-patterns

A: Using latest version of C# I have done with following way :
public string GetValue(string name)
        {
            return name switch
            {
                var x when name is "test1" || name is "test2" => "finch",
                "test2" => somevalue,
                _ => name
            };
        }

A: public String doStaff(int a) {

   switch(a)
       {
          case 1: return "lalala"
          case 2: return "blalbla"
          case 3: return "lolollo"
          default: return "default"
       };
}

A: We can have one use case where we may need to return the value from condition written inside the switch; let's say:
public void SomeMethod(SomeType enumType)
{
    switch (enumType)
    {
        case a:
            if (condition)
            {
                if (condition1  && condition2)
                {
                    return true;
                }
            }
            return false;
            //break; break is actually not be required here if return used before break
        case b:
            if (condition)
            {
                if (condition3  && condition4)
                {
                    return true;
                }
            }
            return false;
            // break;
        default:
            return false;
            //break;
    }

    Public enum SomeType
    {
        a,
        b,
        c,
        d
    }

A: You can use (switch case) instead of (if statement).
    public InvoiceDeliveryStatus InvoiceDeliveryStatus { get; set; }

public string GetInvoiceDeliveryStatusTxt { get { return InvoiceDeliveryStatusSwitch(); } }

        private string InvoiceDeliveryStatusSwitch()
        {

            if (InvoiceDeliveryStatus == InvoiceDeliveryStatus.Canceled) return "Is Rejected";
            if (InvoiceDeliveryStatus == InvoiceDeliveryStatus.Completed) return "Is Completed";

                return InvoiceDeliveryStatus.ToString();
        }


text:
Q: Hadoop Cluster setup in a server or hadoop cluster setup using pcs for performance testing Which of the following hadoop cluster setup would be best suitable for performance testing?
Setup 1 : Server based cluster
Setup 2 : Common PCs are used as data nodes.
Cluster size is upto 100 Nodes
Also what would be the pros and cons of both cluster setups mentioned above?


text:
Q: When do user-defined rust types implement drop? Do user-defined rust types get an automatic drop implementation for them, if they have a field or variant that might contain an item that needs to be dropped?
Consider a struct as follows:
struct Guard<T> {
  pointer: Box<T>,
  locked: bool
}

Is this struct going to automatically have drop implemented for it? How about if the type was an enum, where only one variant had the box?
enum MaybeDroppable<T> {
    A(Box<T>),
    B
}

A: I think your question stems from some confusion between implementing the Drop trait, and variables being dropped when they go out of scope.
When a variable goes out of scope it is dropped (unless it is uninitialized) meaning its destructor is called and its memory can be reused after the destructor has finished. If this variable is of a type that implements the Drop trait then its drop implementation is run first as part of its destructor.
So, the Drop trait (merely) provides a way to run user-defined code when a variable gets dropped. It has no bearing on whether (or when) a variable is dropped.
For a compound variable this process happens recursively (and in a special order) for each field, such that you don't have to do anything in almost all circumstances.

A: I want to thank the Rust Discord Members for helping me to answer the question. Essentially the relevant information is in https://doc.rust-lang.org/reference/destructors.html.
Normally in Rust, when a user-defined type is dropped, all of its fields are dropped in order, whether or not there is an implementation of drop for that particular user-defined type. This is called "drop glue" code. If there is an implementation of drop, the drop code runs first, and then every field (in the case of a struct) is dropped, in order.
struct Guard<T> {
  pointer: Box<T>,
  locked: bool
}

would drop the fields in declaration order. Since pointer needs to be dropped, the code for dropping it is run. As for locked, no code needs to be run in order to drop it.
If the user-defined type is an enum, I believe there is a match statement that runs in order to determine which variants to drop.


text:
Q: How can I drop all triggers in a single database? I have a database with 104 triggers, is there a way to delete all the triggers with a single command from a single database called 'system_db_audits?

A: Use Sys.Triggers Meta Data Table which contains a row for each object that is a trigger

*

*Change output mode to text by clicking the toolbar button shown here:

*Execute this script:
USE YourDBName
GO
SELECT ' GO ' + Char(10) + Char(13) + 'DROP TRIGGER '
    + QUOTENAME(OBJECT_SCHEMA_NAME(O.[object_id])) + '.'
    + QUOTENAME(name)
FROM sys.sql_modules as M
    INNER JOIN sys.triggers as O
        ON M.object_id = O.object_id;

*Copy Output into a new SQL Server Management Studio window, verify the code performs the actions you are expecting, and Execute.

A: You can use Dynamic SQL and the sys.triggers DMV to build query that you can execute.
is_ms_shipped excludes any triggers that were shipped with SQL Server.
parent_class_desc filters for object level triggers, rather than database level.
Change the PRINT to an EXEC once you are happy with the output.
USE system_db_audits;
GO

DECLARE @sql NVARCHAR(MAX) = N'';

SELECT @sql +=
    N'DROP TRIGGER ' +
    QUOTENAME(OBJECT_SCHEMA_NAME(t.object_id)) + N'.' +
    QUOTENAME(t.name) + N'; ' + NCHAR(13)
FROM sys.triggers AS t
WHERE t.is_ms_shipped = 0
  AND t.parent_class_desc = N'OBJECT_OR_COLUMN';

PRINT @sql;

A: In case you want to run a sql job on a central server [ServerA] to do the trigger deletion work,
I'll provide a PowerShell version assuming you have a SQL Server 2012 (or above) instance with SQLPS module installed on [ServerA]
Say you want to delete all triggers in [AdventureWorks] database on [ServerB] SQL Server instance (SQL Server 2005+).
You can run the following PS on [ServerA]:
import-module sqlps -DisableNameChecking;
$db=get-item -Path "sqlserver:\sql\ServerB\default\databases\AdventureWorks";

#before deletion, you can check that triggers do exist
$db.tables.triggers | select name

#now delete
$db.tables.triggers |Where-Object {-not $_.IsSystemObject } | foreach-object {$_.drop()};

#check after deletion
$db.tables.triggers | select name;

Please remember to replace ServerB and AdventureWorks with your own values.
This is pretty flexible solution which you can easily customize to adapt to other different requirements, such as only delete triggers belong to a specific set of tables, or disable (instead of delete) some specific triggers etc.
Strictly speaking, the solutions provided by @Mark Sinkinson is not correct because the requirement is not to delete triggers on 'system_db_audits' db, but to delete triggers in another db from 'system_db_audits'. This means you need to create a dynamic sql in 'system_db_audits' to wrap the "dynamic sql" provided by @Mark Sinkinson to delete those target triggers assuming that both 'system_db_audits' and the target db are on the same sql server instance. Otherwise if the two dbs are not on the same instance, it will be even much "ugly" to handle the deletion (such as via linked server etc). In such scenario, PS is an elegant solution no matter where the target db is or is not on the same sql instance.

A: To take into account the limit of the string holding the sql string:
SET NUMERIC_ROUNDABORT OFF;
SET ANSI_PADDING, ANSI_WARNINGS, CONCAT_NULL_YIELDS_NULL, ARITHABORT, QUOTED_IDENTIFIER, ANSI_NULLS, NOCOUNT ON;
SET DATEFORMAT YMD;
SET XACT_ABORT ON;
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION

DECLARE @items AS CURSOR
DECLARE @item AS nvarchar(250)

SET @items = CURSOR FOR SELECT N'DROP TRIGGER ' + QUOTENAME(OBJECT_SCHEMA_NAME(t.object_id)) + N'.' + QUOTENAME(t.name) + N'; '
    FROM sys.triggers AS t WHERE t.is_ms_shipped = 0 AND t.parent_class_desc = N'OBJECT_OR_COLUMN';

OPEN @items
FETCH NEXT FROM @items INTO @item
WHILE @@FETCH_STATUS = 0
BEGIN
    EXEC (@item)
    FETCH NEXT FROM @items INTO @item
END
CLOSE @items
DEALLOCATE @items

COMMIT TRANSACTION;

For Views the SET command would be:
SET @items = CURSOR FOR SELECT N'DROP VIEW ' + QUOTENAME(OBJECT_SCHEMA_NAME(r.object_id)) + N'.' + QUOTENAME(r.name) + N'; '
FROM sys.views AS r WHERE r.is_ms_shipped = 0;

For Stored Procedures the SET command would be :
SET @items = CURSOR FOR SELECT N'DROP PROCEDURE ' + QUOTENAME(OBJECT_SCHEMA_NAME(t.object_id)) + N'.' + QUOTENAME(t.name) + N'; '
    FROM sys.procedures AS t WHERE t.is_ms_shipped = 0


text:
Q: Calculating python variable only once I want to extract an excel file in my script extractor.py and import it my script calculation.py but without recalculating it!
Here is my code :
in extractor.py
current_directory=os.getcwd()
workbook_clients=pandas.ExcelFile(current_directory+"/Documents/clients.xlsx")
clients=pandas.io.excel.ExcelFile.parse(workbook_clients)

in calculation.py
from extractor import *
print clients

Right now when I run calculation.py it takes 30 seconds to run and I don't understand why, I just want to call a variable in memory...

A: Ok I finally found another way to do what I want :
in extractor.py
current_directory=os.getcwd()
workbook_clients=pandas.ExcelFile(current_directory+"/Documents/clients.xlsx")
global clients
clients=pandas.io.excel.ExcelFile.parse(workbook_clients)

in calculation.py
print clients

A: In case your dataset is very large, read_csv should be a lot faster than read_excel. (Source)
Edit after your comments: write a method if you want to make sure that you are getting the values with the extractor just once in your routine
import os
import pandas as pd

def get_data():
    current_directory=os.getcwd()
    workbook_clients=pd.ExcelFile(current_directory+"/Documents/clients.xlsx")
    data=pd.io.excel.ExcelFile.parse(workbook_clients)
    return data

clients = get_data()
print(clients)

Now you can do with clients whatever you want and it's being called from memory. In case you want to re-read the data, just call the method again.
Obviously, you can also write the method inside the extractor.py and call it from somewhere else.
BTW: from module import * is on the you should not do-list. Further reading. :)


text:
Q: Counting with PHP from a dynamictable I'm not an expert in PHP even though I've been working with some stuff, copying and pasting from here and there, well I want to ask something that I can not find and that I don't have the slightest idea on how to implement it.
For instance, at a table like this:
    +------+-----+
    |NAME  |BIRTH|
    +------+-----+
    |John  |1980 |
    |Carl  |1982 |
    |Alice |1990 |
    |June  |1994 |
    |Rob   |1998 |
    |Alice |1998 |
    |John  |2000 |
    |Alice |2001 |
    |Etc.  |     |
    +------+-----+

I do different queries, like these below (and I could keep doing queries with any combination of years):

*

*Select * from table where BIRTH between 1980 and 1990

*Select * from table where BIRTH between 1980 and 2001

*Select * from table where BIRTH between 1990 and 2001
So I will get 3 different tables, and from those tables I need to count the different contents,
for instance, from the table obtained with the query1 I need to obtain:
   John = 1
   Carl = 1
   Alice = 1

from table of query2:
   John = 2
   Carl = 1
   Alice = 3
   June = 1
   Rob =1

from table of query3:
   Alice = 3
   John = 1
   Carl = 1
   June = 1
   Rob =1

And remember the big table has 700 records, so it could appear any new name, and I need to print out the result in the same way:
   Alice = 3
   John = 1
   NewName = 1
   June = 1
   Rob =1

My final goal is do percentages in relation to the obtained table, and not to the total of registers.

A: You should do it in SQL, not in PHP :
select NAME, count(1)
from TABLE
where condition
group by NAME

This will produce the exact view you want. Names as first column, the count on the second.


text:
Q: How to change a sine function? I use sine functions to control cyclic animations I create with code. For example, I can use something like a * sin(millis() * f * 2 * pi), and assign that value to some property of a geometry, making it cycle from -a to a.
I'd like to have some kind of "dumping" applied to it, so that the curve goes "faster"/"slower" to 1.  I played a bit with combining sine with other functions but nothing worked.