text:
Q: Gigabit NIC with TCP offload and open driver I'm looking for a gigabit Ethernet adapter with a TCP offload engine that will work nicely with a modern Linux kernel. Due to the way patches and updates are handled, I really need one that has an open (blob-less) driver.
I'm beginning to think such a thing might not exist. I'm hoping that I'm just missing a lesser known manufacturer that I could try. I'd rather put up with a relatively quirky card than have to deal with the issues surrounding closed source TOE drivers in Linux.
I'm aware of the venerable Broadcom and Intel team cards, but I don't want to buy yet another piece of hardware that requires dealing with non-free firmware or driver blobs. I'm so close to getting rid of anything that won't work without them, I'd hate to introduce something else.
I'd also appreciate any 'home brew' experiences, if they relate to this question.

A: Based on the linux networking maintainers dislike of TOE, I'd be surprised if such a thing exists.


text:
Q: Keep everything inbetween quotations in an Excel file I have an Excel file (xlsx) with one column and a thousand rows.
Example:
row A| oulzdwdwjdwojd=."A180202"wodwdojwdowj
row B| dwodjwodjwdowj-."N310302"wdwdwdwdwdw
row C| wdowduwoduwoduwdowudowudwoduwoduwdouw
row D| woduwoduwdowu-"N330201"

There is a lot of junk mixed in with asset numbers between quotations. I am needing to remove everything except for what's inside of the quotations. Leaving me with something like
row A| A180202
row B| N310302
row C| N330201

I am a complete beginner to VBS. I believe that I could write a program to do this in C++ or Java but do not know how to complete such a task with VBScript that is part of Excel. I have obtained similar results using the Excel tools in the GUI but nothing that leaves me with exactly what I need.
How would I go about doing something like this in VBScript? I would guess I have to use a delimiter with left, right or replace.

A: This will do you:
VBA
Sub SO()

Dim RE As Object, i As Long
Set RE = CreateObject("VBScript.RegExp")

With RE
    .Pattern = """.*"""
    .Global = True
    .IgnoreCase = True
End With

For i = 1 To Range("A" & Rows.Count).End(xlUp).Row
    If RE.Test(Cells(i, 1).Value) Then
        With Cells(i, 1)
            .Value = Replace(RE.Execute(.Value)(0), """", "")
        End With
    Else
        Cells(i, 1).ClearContents
    End If
Next

Range("A1:A" & Cells(Rows.Count, 1).End(xlUp).Row).SpecialCells(xlCellTypeBlanks).EntireRow.Delete shift:=xlUp

End Sub

VBScript.RegExp is just a Regular Expression engine that allows you to match patterns in a string (I'd be surprised if you haven't come across this before in C++ or Java...). You can set a reference to this but for ease I've gone with the late-binding option.
To try and explain, the code is looping through each cell in column A and performing a RegEx test against it. If the pattern matches, it replaces the value of the cell with the match - if the pattern doesn't match then it clears the contents of the cell.
Finally, we use Excel's SpecialCells method to identify any blank cells in column A and at the same time delete the row that they belong to.
If it makes it easier, the loop in Java would probably look something like this I imagine:
for(var i = 0; i <= 1000; i++){
    if(RE.Test(Excel.Workbooks.ActiveWorkbook.Cells(i, 1).Value2)){
        // Blah blah....
    }
}

(I don't write Java in case you haven't noticed...)

A: The following is written in VBA. For VBS you'll just need to change the Range references, and put it in a loop:
Sub Test()
    Dim startQuote
    Dim endQuote
    startQuote = InStr(Range("A1").Value, """")
    endQuote = InStr(startQuote + 1, Range("A1").Value, """")
    Range("B1").Value = Mid(Range("A1").Value, startQuote + 1, endQuote - startQuote - 1)
End Sub

InStr is used to find the position of the first and second quote, Mid is used to extract the text between the quotes.
The double quote needs to be quoted, which is why there are four quotes.

A: (Assuming you mean VBA...)
Add a reference to the Microsoft VBScript Regular Expressions 5.5 library and you can use a regex to extract the asset ID. This assumes you have a single asset ID in column A, per row, and it will will put the extracted ID into column B.
Public Sub DoIt()

    Dim re As New RegExp
    re.Pattern = """([^""]+)"""

    Dim intRow As Long
    For intRow = 1 To 1000
        If re.Test(Cells(intRow, 1)) Then
            Cells(intRow, 2) = re.Execute(Cells(intRow, 1))(0).SubMatches(0)
        End If
    Next

End Sub

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find all function $f:\mathbb Q^+ \rightarrow \mathbb Q^+$ that satisfy $f(x)+f\bigg(\dfrac{1}{x}\bigg)=1$ and $f(2x+1)=\dfrac{f(x)}{2}$

Find all function $f:\mathbb Q^+ \rightarrow \mathbb Q^+$ that satisfy $$f(x)+f\bigg(\dfrac{1}{x}\bigg)=1$$ and $$f(2x+1)=\dfrac{f(x)}{2}$$ for all $x$ in domain of $f$

My Approach:
Put $x=1$ in $f(x)+f\bigg(\dfrac{1}{x}\bigg)=1$
$\implies$
$f(1)+f(1)=1$
$\implies$
$f(1)=\dfrac{1}{2}$
Now put $x=2$ in $f(x)+f\bigg(\dfrac{1}{x}\bigg)$
we obtain $f(2)+f(\dfrac{1}{2})=1 \cdots \cdots (1)$
Now using $f(2x+1)=\dfrac{f(x)}{2}\cdots \cdots (2)$
Put$x=\dfrac{1}{2}$ in eqation $(2)$
$\implies$
$f\bigg(\dfrac{1}{2}\bigg)=2f(2)$
Using above result in Equation $(1)$ we obtain $f(2)=\dfrac{1}{3}$
In similar fashion we finally obtain $f(x)=\dfrac{1}{1+x}$ For Integers
I want to know Some other method to solve this
I also tried using $g(x)=f(x-1)$ like this Help in solving a simple functional equation: $3f(2x+1)=f(x) + 5x$. But couldn't get desired result
Also this question is similar to Showing that $f(x)=\frac x{x+1}$ is the unique function satisfying $f(x)+f\left(\frac1x\right)=1$ and $f(2x)=2f\big(f(x)\big)$


text:
Q: How to show days in a week without specific date in Vuetify v-calendar in weekly mode? In Vuetify v-calendar weekly mode example the header shows day name (eg. Mon or Monday) and day of the month (eg. 7th of the month). Is it possible to show only day names without month days? I'd like to use this control just as a weekly schedule and without coupling it to the specific date or week in a year.

A: According to the source of vuetify (line 98 - line 121) you can't override this behavior, but you can't hide the date itself with css:
.v-calendar-daily_head-day-label {
    display: none;
}

If you use the scoped styling don't forgot to use the deep selector

A: The above answer in now outdated.
With the latest version of Vuetify (2.3.10) you can come close to hiding the date via slots as follows;
<v-sheet height="600">
  <v-calendar
  ref="calendar"
  type="week">
    <template v-slot:day-label-header="{}">-</template>
  </v-calendar>
</v-sheet>

Although it will show a "-" in place of the date if you use the above code.


text:
Q: Update context variables using .js. Its possible? i'm trying to send a user name to my WCS but i not sure how can i do that using a request. My consersation ask for the user email and use a js script to return a json from my sql server...
I'm doing something like that:
What's your email? // WCS
caique.rodrigues@test.com //USER
Just a minute. // WCS
nodeTrue //USER (I sent this after confirmated if the user exist and got the user name.)
Hi ! //WCS
I know this is not the best way to do that but it is working. I'm trying to call my js functions using something like "output:{'action':}" (And handle it in my node.js like the 'car dashboard sample'), but, it's possible send a varible from my .js to a conversation context?

A: I had the same problem a few months ago. In this case, I used functions for access the context variables on the client side (Using this example from Ashley and accessing the context), but, for security issues of some company data, I did need to use custom code in the server-side... And, for this case, you can use the method call for Watson Conversation, and access the context variables and creates values with custom code in your favor.
Something like this:
conversation.message(payload, function (err, data) {
    data.context.yourValue = returnFromYourDatabase;
    if (err) {
      return res.status(err.code || 500).json(err);
    }
    updateMessage(payload, data, req, res);

  });
});

You can see the function updateMessage, this call is one example from IBM Developers, and this function is used to update the message in every request. You can use this function to set too, because this function get the parameters from the call.
For example:
function updateMessage(input, response) {
  response.context.yourValue = returnFromYourDatabase;
  var responseText = null;
  if (!response.output) {
    response.output = {};
  }
}

See API Reference for Watson Conversation Service using Node.js.
See the Project with Node.js by IBM Developers.


text:
Q: Adding CakePHP folder to existing domain Right now some of our domains which are drupal sites, have a cakephp app associated with them, like it is a directory within that domains directory, but the cakephp app is outside of that domains directory. www.domain.com/thecakephpapp is how it looks and what I would type to get to the cakephp part. But in /var/www the two are seperate like:
drwxr-xr-x 14 user www-data   4096 2011-06-03 15:25 domain.com
drwxr-xr-x 10 user www-data   4096 2012-04-11 16:08 cakephpapp
I have no idea where to associate them together though. So that when I type in www.domain.com/cakephpapp it points to the location of cakephpapp. I've looked at the ones setup before me but haven't been able to make heads or tales of it.

A: If i get this right "var/wwwdomain.com" is the folder that is used as webroot by your domain.com website. If the cakeapp is in /var/www/cakeapp the most easy solution would be to symlink it.
ln -s /var/www/cakeapp/webroot /var/www/wwwdomain.com/cakeapp

A: I found out you can do something similar with an Alias in apache. And it would look something like this in your apache configuration file.
Alias /cakeapp /web/cakeapp/webroot


text:
Q: How to use an execute command to test for an item/s in a chest? I want to detect if a player is standing on a chest using an execute command then if so detect what is in that chest and give an output. E.G Player is standing on a chest there is 64 stone in the chest if so give a redstone or score board output?
I have tried
execute @p ~ ~ ~ setblock ~ ~-2 ~ command_block 0 replace {command:"testforblock ~ ~1 ~ chest -1 {Items:[{id:minecraft:stone,Slot:0b,Count:64b}]}"

and
execute @p ~ ~ ~ testforblock ~ ~-1 ~ chest -1 {Items:[{id:minecraft:stone,Slot:0b,Count:64b}]}

A: In order to target that player afterwards, you must use CommandStats to track the success of a command.
Prerequisites:
Objective to hold the return value.
/scoreboard objectives add AboveChest dummy

Applying the "AffectedBlocks" trigger to all players, who will then set their own "AboveChest" score depending on the success of block-related commands. This may need to run on a clock if new players can join at any time.
/stats entity @a set AffectedBlocks @a[c=1] AboveChest

In order for CommandStats to modify a target's score, that target must be tracked prior. This may also need to run on a clock.
/scoreboard players add @a AboveChest 0

Clock commands:
The following must be run on a clock in numerical order.

*

*Cause players to run a /testforblock to find the chest. If the command is successful, that player will have their "AboveChest" score set to 1. If unsuccessful, that player will have their score set to 0.
/execute @a ~ ~ ~ testforblock ~ ~-1 ~ minecraft:chest -1 {Items:[{id:"minecraft:stone",Count:64b,Slot:0b}]}

*Target players based on their "AboveChest" score.
/say @a[score_AboveChest_min=1] is above a chest containing a stack of 64 stone.

A: 1.13+ Update to Skylinerw's answer
1.13 has completely changed commands. Are you playing 1.13 and have the same question? This is the answer for you.
Prerequisites

*

*Objective:
/scoreboard objectives add AboveChest dummy

*Set the player's initial score.
/scoreboard players set @a AboveChest 0

/stats is deprecated, use /execute store instead.
Clock commands

*

*Find chest and store success/failure in scoreboard variable.
/execute as @a at @s if block ~ ~ ~ chest{Items:[{id:"minecraft:stone",Count:64b,Slot:0b}]}

*Target players who have a score of 1. Use whatever command you want and this target selector to get them
@e[scores={AboveChest=1}]


text:
Q: Android-Output of an ArrayList not displayed I have written a code to get the contents of an arrayList but instead of that i am getting random numbers as output.
Student.java
    package com.example.com.arraylist;

    public class Student {

        int Enrno;
        String Name;

       public Student(int Enrno, String Name){

           this.Enrno=Enrno;
           this.Name=Name;
        }
    }

MainActivity.java
    package com.example.com.arraylist;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.Toast;

    import java.util.ArrayList;

    public class MainActivity extends AppCompatActivity {

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

    Student s1=new Student(1,"Rahul");
    Student s2=new Student(2,"Rajiv");
    Student s3=new Student(3,"Rohan");

    ArrayList<Student> studentArrayList=new ArrayList<Student>();

    studentArrayList.add(s1);
    studentArrayList.add(s2);
    studentArrayList.add(s3);

    for(Student a:studentArrayList)
        System.out.println(a);

       }
   }

Output:
   I/System.out: com.example.com.arraylist.Student@d6765f3
                 com.example.com.arraylist.Student@308a2b0
                 com.example.com.arraylist.Student@5f1529

i want to display content using this for-loop itself.
Thanks.

A: Override toString() in your Student class as follows:
@Override
public String toString() {
    return "Data: Name= "+this.Name+" Enrno= "+this.Enrno;
}

A: You can use getter and setter method to retrieve data from your Student class
create getter and setter method in your Student class like below code
Try this
public class Student {

    int Enrno;
    String Name;

    public Student(int Enrno, String Name){

        this.Enrno=Enrno;
        this.Name=Name;
    }

    public int getEnrno() {
        return Enrno;
    }

    public void setEnrno(int enrno) {
        Enrno = enrno;
    }

    public String getName() {
        return Name;
    }

    public void setName(String name) {
        Name = name;
    }
}

activity code
public class MainActivity extends AppCompatActivity {

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

        Student s1 = new Student(1, "Rahul");
        Student s2 = new Student(2, "Rajiv");
        Student s3 = new Student(3, "Rohan");

        ArrayList<Student> studentArrayList = new ArrayList<Student>();

        studentArrayList.add(s1);
        studentArrayList.add(s2);
        studentArrayList.add(s3);

        for (Student a : studentArrayList) {

            System.out.println(a.getEnrno());
            System.out.println(a.getName());

        }

    }

}


text:
Q: Adding a number to a sorted descending array without disturbing the order (C) So here I fill the array and produce sorting. I need to insert the number entered from the keyboard into the array without knocking down its order. Tell me please how i can do it.
#include <stdio.h>

int main(void)
{
    //Creating array
    int a[5];
    int i, j, temp;

    printf("Enter number to create array\n");
    for (i = 0; i < 5; i++)
        scanf("%d", &a[i]);

    //Sorting the array ascending descending
    for (i = 1; i < 5; i++) {
        temp = a[i];
        for (j = i - 1; j >= 0; j--)
            if (temp > a[j]) {
                a[j + 1] = a[j];
              a[j] = temp;
            }
    }
    //Output of sorted array
    for (i = 0; i < 5; i++)
        printf("%d\n", a[i]);
    return 0;
}

A: An array's size is fixed once it's defined. You need to define another array with the increased size if you want to add elements to it. If you want to maintain sort order, you have to compare your existing elements with the new one.
#include <stdio.h>

int main(void)
{
  //Creating array
  int a[5];
  int i, j, temp;
  int extra;

  printf("Enter number to create array\n");
  for (i = 0; i < 5; i++)
    scanf("%d", &a[i]);

  //Sorting the array ascending descending
  for (i = 1; i < 5; i++) {
    temp = a[i];
    for (j = i - 1; j >= 0; j--)
      if (temp > a[j]) {
        a[j + 1] = a[j];
        a[j] = temp;
      }
  }

  //Output of sorted array
  for (i = 0; i < 5; i++)
    printf("%d\n", a[i]);

  puts("Enter another number to add");
  scanf("%d", &extra);

  /* Define a larger array to hold the extra element. Naturally, you can
     extend this to use a variable value from user input. */
  int b[6];
  j = 0;
  for (i = 0; i < 5; i++) {
    if (extra > a[i]) {

      /* insert the extra number in the proper order */
      b[j++] = extra;
      b[j++] = a[i];

      /* You have to have a way to stop further comparisons once an
         insertion point is reached. In this case, it's a simple
         expedient of setting the value to zero. Many times a boolean
         flag is used for this purpose. Using zero for this assumes
         that you're only sorting positive integers. */
      extra = 0;
    }
    else {

      /* otherwise, just copy over the sorted elements */
      b[j++] = a[i];
    }
  }
  for (i = 0; i < 6; i++)
    printf("%d\n", b[i]);

  return 0;
}

If you were using a heap-allocated array of integers, you could use realloc() to resize it, and then find your insertion point, use your temp variable like you did with the sort, and shuffle the rest of the array elements down by 1.


text:
Q: C# WPF - Global variable that updates its value on different Windows I am creating a project for a grocery store, where it manages Stock and Money (sales and actual money on the register)... I am using SQLite, as this would be used only on one PC. I actually have this project finished, but it does not work correctly, so I started from scratch.
Before, I used to have the database in memory at all times, which made the app VERY slow after a few months of sales/purchases, so now I am using Services and interfaces to manage the database, and only request the rows I need at each time.
My issue here is that I need to have always on display the money that is supposed to be in the register, for that I request this values from the database (there are only two rows in the "Caja" table, which corresponds to "Cash" and "Credit")
And I cast them into a property in my ViewModel, so it allows me to bind it to the View.
But this Properties are somehow not linked to the database, so whenever I sell something, this values do not update automatically, the property is not aware that the values have changed...
public class MyViewModel
{
    private CajaModel _cajaCash;
    public CajaModel cajaCash { get { return _cajaCash; } set { _cajaCash = value; OnPropertyChanged(); }

    private CajaModel _cajaCredit;
    public CajaModel cajaCredit { get { return _cajaCash; } set { _cajaCash = value; OnPropertyChanged(); }

    void LoadCajaValues()
    {

         KioscoDbContextFactory kioscoDbContextFactory = new KioscoDbContextFactory();
         GenericDataService<CajaModel> cajaService = new GenericDataService<CajaModel>(kioscoDbContextFactory);

         cajaService.Get(1).ContinueWith(task =>
         {
             if (task.Exception == null && task.Result != null) { cajaCash = task.Result; }
         });

         cajaService.Get(2).ContinueWith(task =>
         {
             if (task.Exception == null && task.Result != null) { cajaCredit = task.Result; }
         });
    }
}

public class AnotherViewModelAndWindow()
{
    Void SellSomething(Decimal cashPayedByClient, Decimal creditPayedByClient)
    {
         KioscoDbContextFactory kioscoDbContextFactory = new KioscoDbContextFactory();
         GenericDataService<CajaModel> cajaService = new GenericDataService<CajaModel>(kioscoDbContextFactory);

         cajaService.Get(1).ContinueWith(task =>
         {
             if (task.Exception == null && task.Result != null) { CajaModel _tempCaja = task.Result; _tempCaja.Dinero += moneyPayedByClient; cajaService.Update(_tempCaja) }
         });

         cajaService.Get(2).ContinueWith(task =>
         {
             if (task.Exception == null && task.Result != null) { CajaModel _tempCaja = task.Result; _tempCaja.Dinero += creditPayedByClient; cajaService.Update(_tempCaja); }
         });
    }

}

So in the example, it loads correctly the first time I load the application, when I call LoadCajaValues() in MyViewModel, and it displays the values without issue, then, I make a sell from the sell window, and it updates the values ON THE DATABASE correctly, but it does not updates on the variables cajaCash and cajaCredit from MyViewModel... nor in the UI... but if I close and open the app again, then I have the updated values... I just don't know how to tell those properties that the value actually changed.
I tried making a separated static class, which holds the variables, and then make the updates directly there... which works, as I only call the Get() from the database once, then I use those same properties to update the database when I make a sell. But this way, the Static properties change, but I have no idea how to Bind those to the Window which is attached to the MyViewModel, and not to the Static class...


text:
Q: How to open an input accessory view through a UIAlertAction using swift? I have a UIAlertController with some UIAlertActions in it as shown below.
let alertController = UIAlertController(title: nil, message : nil, preferredStyle: .ActionSheet)
let addMoreAction = UIAlertAction(title: "Add more", style: .Default) { (action) in
    // Want to be able to call an input accessory view from here
    }
alertController.addAction(addMoreAction)
self.presentViewController(alertController, animated: true, completion: nil)

When user clicks on the "Add more" action, it should dismiss the UIAlertController and open up the keyboard with a UITextView attached on top of the keyboard. (Like you see in chat apps like Facebook Messenger).
How do I achieve this using swift?

A: Perhaps you are looking for inputAccessoryView property. You can check this tutorial. Using this you can make your own view that can be shown to the top of the keyboard.


text:
Q: How to model heat movement and loss of a house? I was recently looking at the recommended insulation values for houses, and was surprised to find wall insulation recommendation was not just moderately less than the attic, but a tiny fraction of it. I am thinking that this probably has more to do with the amount of room available in the typical wall than the physics of thermal conductivity.
Has anyone done any work at modeling how heat moves in a house, any theory, or real world measurements or exactly what percentage of heat escapes from the roof vs walls?


text:
Q: My Android Program Fragment can't link to other activities, I don't know where is the problem I have a Home fragment for MainActivity. There are 21 buttons, each of them link to one activity. I used OnClickListener from the buttons. When I clicked them, I should have go to the activity. However when I pressed the buttons, they didn't link me to other activities. This is my code and I don't know why. Please help me.
public class HomeFragment extends Fragment implements View.OnClickListener {

    private HomeViewModel homeViewModel;
    private View view;
    private Button button_greetings, button_general_conversation, button_accommodation, button_celebration,
            button_city_and_prefecture, button_colors, button_country_and_region, button_dating,
            button_directions_and_places, button_drink, button_eating, button_emergency, button_family,
            button_feeling, button_numbers, button_shopping, button_sick, button_time_and_date,
            button_tongue_twisters, button_tourist_attractions, button_transportation;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home, container, false);
        button_greetings = (Button) view.findViewById(R.id.button_greetings);
        button_greetings.setOnClickListener(this);
        button_general_conversation = view.findViewById(R.id.button_general_conversation);
        button_general_conversation.setOnClickListener(this);
        button_accommodation = view.findViewById(R.id.button_accommodation);
        button_accommodation.setOnClickListener(this);
        button_celebration = view.findViewById(R.id.button_celebration);
        button_celebration.setOnClickListener(this);
        button_city_and_prefecture = view.findViewById(R.id.button_city_and_prefecture);
        button_city_and_prefecture.setOnClickListener(this);
        button_colors = view.findViewById(R.id.button_colors);
        button_colors.setOnClickListener(this);
        button_country_and_region = view.findViewById(R.id.button_country_and_region);
        button_country_and_region.setOnClickListener(this);
        button_dating = view.findViewById(R.id.button_dating);
        button_dating.setOnClickListener(this);
        button_directions_and_places = view.findViewById(R.id.button_directions_and_places);
        button_directions_and_places.setOnClickListener(this);
        button_drink = view.findViewById(R.id.button_drink);
        button_drink.setOnClickListener(this);
        button_eating = view.findViewById(R.id.button_eating);
        button_eating.setOnClickListener(this);
        button_emergency = view.findViewById(R.id.button_emergency);
        button_emergency.setOnClickListener(this);
        button_family = view.findViewById(R.id.button_family);
        button_family.setOnClickListener(this);
        button_feeling = view.findViewById(R.id.button_feeling);
        button_feeling.setOnClickListener(this);
        button_numbers = view.findViewById(R.id.button_numbers);
        button_numbers.setOnClickListener(this);
        button_shopping = view.findViewById(R.id.button_shopping);
        button_shopping.setOnClickListener(this);
        button_sick = view.findViewById(R.id.button_sick);
        button_sick.setOnClickListener(this);
        button_time_and_date = view.findViewById(R.id.button_time_and_date);
        button_time_and_date.setOnClickListener(this);
        button_tongue_twisters = view.findViewById(R.id.button_tongue_twisters);
        button_tongue_twisters.setOnClickListener(this);
        button_tourist_attractions = view.findViewById(R.id.button_tourist_attractions);
        button_tourist_attractions.setOnClickListener(this);
        button_transportation = view.findViewById(R.id.button_transportation);
        button_transportation.setOnClickListener(this);

        homeViewModel =
                new ViewModelProvider(this).get(HomeViewModel.class);
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        final TextView textView = root.findViewById(R.id.text_home);
        homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);

            }
        });
        return root;
    }
     @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_greetings:{
                Intent i = new Intent(getActivity(), Greetings.class) ;
                startActivity(i);
                break; }
            case R.id.button_general_conversation:{
                Intent i = new Intent(getActivity(), General_Conversation.class);
                startActivity(i);
                break; }
            case R.id.button_accommodation:{
                Intent i = new Intent(getActivity(), Accommodation.class);
                startActivity(i);
                break; }
            case R.id.button_celebration:{
                Intent i = new Intent(getActivity(),  Celebration.class);
                startActivity(i);
                break; }
            case R.id.button_city_and_prefecture:{
                Intent i = new Intent(getActivity(), City_and_Prefecture.class);
                startActivity(i);
                break; }
            case R.id.button_colors:{
                Intent i = new Intent(getActivity(), Colors.class);
                startActivity(i);
                break; }
            case R.id.button_country_and_region:{
                Intent i = new Intent(getActivity(), Country_and_Region.class);
                startActivity(i);
                break; }
            case R.id.button_dating:{
                Intent i = new Intent(getActivity(), Dating.class);
                startActivity(i);
                break; }
            case R.id.button_directions_and_places:{
                Intent i = new Intent(getActivity(), Directions_and_Places.class);
                startActivity(i);
                break; }
            case R.id.button_drink:{
                Intent i = new Intent(getActivity(), Drink.class);
                startActivity(i);
                break; }
            case R.id.button_eating:{
                Intent i = new Intent(getActivity(), Eating.class);
                startActivity(i);
                break; }
            case R.id.button_emergency:{
                Intent i = new Intent(getActivity(), Emergency.class);
                startActivity(i);
                break; }
            case R.id.button_family:{
                Intent i = new Intent(getActivity(), Family.class);
                startActivity(i);
                break; }
            case R.id.button_feeling:{
                Intent i = new Intent(getActivity(), Feeling.class);
                startActivity(i);
                break; }
            case R.id.button_numbers:{
                Intent i = new Intent(getActivity(), Numbers.class);
                startActivity(i);
                break; }
            case R.id.button_shopping:{
                Intent i = new Intent(getActivity(), Shopping.class);
                startActivity(i);
                break; }
            case R.id.button_sick:{
                Intent i = new Intent(getActivity(), Sick.class);
                startActivity(i);
                break; }
            case R.id.button_time_and_date:{
                Intent i = new Intent(getActivity(), Time_and_Date.class);
                startActivity(i);
                break; }
            case R.id.button_tongue_twisters:{
                Intent i = new Intent(getActivity(), Tongue_Twisters.class);
                startActivity(i);
                break; }
            case R.id.button_tourist_attractions:{
                Intent i = new Intent(getActivity(), Tourist_Attractions.class);
                startActivity(i);
                break; }
            case R.id.button_transportation:{
                Intent i = new Intent(getActivity(), Transportation.class);
                startActivity(i);
                break; }
        }
    }

}

enter image description here

A: You should not define the same variable in the same scope more than once.. Here the intent i is defined in every switch case
@Override
public void onClick(View v) {
    switch (v.getId()) {

        Intent i; // Define once

        case R.id.button_greetings:{
            i = new Intent(getActivity(), Greetings.class) ;
            startActivity(i);
            break; }

        case R.id.button_general_conversation:{
            i = new Intent(getActivity(), General_Conversation.class);
            startActivity(i);
            break; }

        case R.id.button_accommodation:{
            i = new Intent(getActivity(), Accommodation.class);
            startActivity(i);
            break; }

       // repeat the same for the rest of cases

A: Why did you inflate two different views from one layout? First time you set inflated view to a global field, and second time you inflate new object and return it as a result of onCreateView(). It seems like your buttons getted from view which never be shown on the screen and never will been clicked. Try to remove second inflating and use just result of first one.
And, of course, bring out your intent declaration out of switch block (before).


text:
Q: firefox addon repack I create a firefox addon using the addon builder
https://builder.addons.mozilla.org/
From there I downloaded the distributable file, but they didnt include an option for setting the addon icon.
I heard that by default it uses icon.png, so I unzipped the xpi file, put the icon in the folder. But when I re-zip it, it always denies the addon.
How can I re-zip without this issue.
Also how can I develop firefox addons in general.
I am interested in a book that explains everything top to bottom, instead of some very poorly written snippet examples that are scattered across the web.

A: Jetpack add-ons are signed automatically, simply changing something won't work because the signature becomes invalid. If you need features that the builder doesn't provide you need to download the SDK and create a package yourself. SDK documentation: https://addons.mozilla.org/en-US/developers/docs/sdk/1.0/
Update: The "signing" part is outdated, the Add-on SDK no longer signs the add-ons. Still, creating a new package is the way to go here - one might run into all kinds of obscure issues otherwise.

A: You need to repack it as a zip file with the zip extension. The install.rdf should be at the root directory of the zip file, i,e. it shouldn't contain a root directory that holds these files.
After repacking as a zip, rename it to xpi. Keep in mind that if you are in Windows, you need to configure it to show the file extensions.
Mozilla MDN contains some useful documentation, but not sure whether it's advanced enough to fit your needs.

A: Open the addon with an unzip program (dont extract it), and throw inside the icon.png or that ever you want to add, overwrite.
Edit: you can add icon into the package.json... it is editable just after the input for the name of the add on.


text:
Q: Spring AOP not working with @Configuration and @EnableAspectJAutoProxy in my application i am using AOP on the Controller and DAO Layer - it works properly.
However, on my service layer, which is created inside a @Configuration class (as a bean), it does not work.
So my problem is that the pointcuts and advices for Controller and DAO layer work - but not for the Service Layer.
Reading on the internet - i found out that i should add @EnableAspectJAutoProxy annotation - but it still does not work with this.
Side NOTE:
@Bean("nameOfResolver")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.TARGET_CLASS)

The class that does not work is like this
public class ResolveImpl implements Resolve {

private static final Logger LOGGER = LoggerFactory.getLogger(ResolveImpl.class);

@CustomAnnotation(user = "user")
public TestClass createTestClass(String user) {
    ......
    }
}

I have this in my bean which resolves which bean should be returned.
Thanks a lot for your help

A: Ok i finally found the solution to my problem.
Since Spring AOP uses proxying mechanisms, i have a method that calls the @CustomAnnotation(user = "user") method which is in the same class. This causes the proxying mechanism not to be triggered.
Check
Spring AOP not working for method call inside another method
for explanation


text:
Q: Admin Table Filtering not Working for Custom Post Type When I attempt to filter a custom post type's admin table(CPT's posts) using the select dropdown, the filtered table that loads shows 0 items.
This is the url structure that is being created by submitting the filter table form (I've added linebreaks for readability):
{HOST}/wp-admin/edit.php
?s
&post_status=all
&post_type=dog
&action=-1
&dog=labrador
&filter_action=Filter
&paged=1
&mode=list
&action2=-1
There are no errors, I've tried numerous tutorials and countless tweaks and can't seem to get anything to take.  Anyone have any idea what might be going on?
I can add any filters, actions, functions, declarations I've used to this question if they would be of use -- just let me know what would be helpful to see.

A: Well, the short answer is that your taxonomies and custom post types share slugs, which is what is causing the list table to display nothing. If you were to change the taxonomy slugs from $newType to $newType . '_tax' it should work. I actually used that same slug formula in the rewrites example below.
If you're really just trying to save time by using the same slugs, simply make the slugs unique for post_type vs taxonomy and ignore the rest of this answer.
However, if you're using the same slugs in an attempt to share the front-end rewrite slugs, e.g. example.com/dog/labrador (term) vs example.com/dog/this-is-a-dog-item (post), the following should work for that in some measure:
/**
 * Match taxonomy term rewrite slugs with custom post type slugs.
 *
 * @param WP_Rewrite $wp_rewrite WP_Rewrite global.
 */
function match_tax_rewrites_to_cpt( $wp_rewrite ) {
    $pairs = array();

    // Set up post type and taxonomy pairs.
    foreach ( array( 'dog', 'cat', 'fish', 'bird' ) as $slug ) {
        $post_type = get_post_type_object( $slug );
        $taxonomy  = get_taxonomy( $slug . '_tax' );
        if ( is_object( $post_type ) && is_object( $taxonomy ) ) {
            $pairs[ $slug ] = array(
                'post_type' => $post_type,
                'taxonomy'  => $taxonomy
            );
        }
    }

    if ( ! empty( $pairs ) ) {
        $rules = array();

        // Loop through the pairs.
        foreach ( $pairs as $slug => $objects ) {

            // Check if taxonomy is registered for this custom type.
            if ( ! empty( $tax_obj_type = $objects['taxonomy']->object_type[0] ) ) {
                if ( $tax_obj_type == $slug ) {

                    // Term objects.
                    $terms = get_categories( array(
                        'type'       => $tax_obj_type,
                        'taxonomy'   => $objects['taxonomy']->name,
                        'hide_empty' => false
                    ) );

                    // Build your rewrites.
                    foreach ( $terms as $term ) {
                        $rules[ "{$tax_obj_type}/{$term->slug}/?$" ] = add_query_arg( $term->taxonomy, $term->slug, 'index.php' );
                    }
                }
            }
        }
        // Merge the rewrites.
        $wp_rewrite->rules = $rules + $wp_rewrite->rules;
    }
}
add_action( 'generate_rewrite_rules', 'match_tax_rewrites_to_cpt' );

It's worth noting that if you use this function to generate rewrite rules, it's actually important that you move the register_post_type() calls above the register_taxonomy() calls. This is to ensure that the base rewrite rules generated by WordPress end up in the right order.


text:
Q: How to access appended element through another appended element in jQuery
I have a form, which allows adding up to 6 people (pic1) one by one.
.
"ADD" and "+" both add the user and clear the form. This appends a piece of HTML to #worker-container and hides it through display: none.

Here's the HTML part of the code.

ADD MAX OF 6 USERS

                Name
                <input id="team_name" name="team_name" type="text" class="form-control name" placeholder="" required>

                Surname
                <input id="team_s_name" name="team_s_name" type="text" class="form-control s_name" placeholder="" required>

                Phone
                <input id="team_tel" name="team_tel" type="tel" class="form-control team" placeholder="" required>

                Email
                <input id="team_mail" name="team_mail" type="mail" class="form-control mail" placeholder="" required>

Here's the JS/jQ part:
var addWorker = $('here goes the HTML from above').appendTo($('#worker-container'));
var addWorkerIcn = $('').appendTo($('#team_add_worker_icn'));

So after appending it looks like this:

I want to be able to click the green top-right user icon to show the details of the added user. I know it has to do with dynamically added elements and I need to use bubbling to let jQuery know about the new element. I can do it with the dynamically added addWorkerIcn and it shows the alert.

    $('body').on('click', addWorkerIcn, function() {
        alert('click');
        // set display: block on the addWorker element
    });
My question is, how do I go about showing the appended addWorker element after clicking on another appended element?. I want it to show after clicking on the icon. I could trigger it via click event, but that is not what I am looking for.

A: Instead of appending the event to the newly created element, simply make a custom class for the created element and make this binding on page load:
$("body").on('click', '.your-class', function(e){
    var $el = $(this);
})

This way you won't need to append a click event to body every time, instead you'll have a single event that fires when an element of .your-class is clicked inside the body tag.


text:
Q: SMTP Authentication Error "Failure Sendng Mail" I am trying to send email from my asp.net web page if certain conditions are fulfilled.
Here is my code.
SmtpClient smtpClient = new SmtpClient();
NetworkCredential basicCredential =
    new NetworkCredential("username", "password");
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress("from@yourdomain.com");

smtpClient.Host = "mail.mydomain.com";
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;

message.From = fromAddress;
message.Subject = "your subject";
//Set IsBodyHtml to true means you can send HTML email.
message.IsBodyHtml = true;
message.Body = "
your message body
";
message.To.Add("to@anydomain.com");

try
{
    smtpClient.Send(message);
}
catch(Exception ex)
{
    //Error, could not send the message
    Response.Write(ex.Message);
}

I have not shared the server details. I'm trying to send it from my outlook email address. However, I keep getting an error: Failure sending mail.

A: try this code
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 25);

    smtpClient.Credentials = new System.Net.NetworkCredential("youremailid@gmail.com", "yourPassword");
    smtpClient.UseDefaultCredentials = true;
    smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
    smtpClient.EnableSsl = true;
    MailMessage mail = new MailMessage();

    //Setting From , To and CC
    mail.From = new MailAddress("fromemailid@gmail.com", "MyWeb Site");
    mail.To.Add(new MailAddress("toemailid@gmail.com"));
    mail.CC.Add(new MailAddress("ccemailid@gmail.com"));
    mail.Subject = "your subject";
    mail.IsBodyHtml = true;
    mail.Body = "
your message body
";

    smtpClient.Send(mail);

thanks,

A: For sending mail you can't use your development server port.
You have to use the smtp server port of your mail server.
for smtp.live.com you should use either port 25 or 587
For this code below, specify VALID login details (email/password)
client.Credentials = new System.Net.NetworkCredential(
            @"email_account",
            @"email_password");


text:
Q: Importing SRTM Data into Grass I am having issues importing an SRTM HGT file into Grass. I first made a new location as the instructions from this Grass Newsletter Tutorial states. I then went to the download site and downloaded the file to my desktop. Inside GRASS, I went to
File > Import raster data > SRTM HGT import [r.in.srtm]
I choose the filename of the .hgt.zip file and remove the extension .hgt.zip (as the instructions say).
The statement looks like this:
r.in.srtm input=C:\Users\Joe\Desktop\N47E007

The following is the output that I'm getting:
Extracting 'C:\Users\Joe\Desktop\N47E007'...
Converting input file to BIL...
mv: cannot stat `C:\\Users\\Joe\\Desktop\\N47E007.hgt': No
such file or directory
ERROR 4: `C:\Users\Joe\Desktop\N47E007.bil' does not exist
in the file system,
and is not recognised as a supported dataset name.
rmdir: C:\Users\Joe\Documents\grassdata/demolocation/PERMANE
NT/.tmp/8120.0: Directory not empty
ERROR: Unable to import data

At the beginning of the script, the file is definitely there because the program recognizes it and starts converting it. Once it produces an error, I notice the file has been moved to another directory
C:\Users\Joe\Documents\grassdata\demolocation\PERMANENT\.tmp\8120.0

What can I do to fix this problem? Thanks!

A: You need to unzip the zip file, not rename it. Then it will work.
As per gene's suggestion, see also the GRASS Wiki article: GRASS GIS: HOWTO import SRTM elevation data.


text:
Q: mechanize: cookies getting mixed up? I'm using mechanize to visit the same web-site from different proxies. The website has a log-in page. I have 5 proxies and 5 different log-ins, one to use for each proxy.
If I just run my script with one proxy and one log-in, each one works fine. However, if I run two or more proxies/log-ins at once, then I start getting errors (from the website) like "either your session has timed out or cookies are not enabled." This happens whether I'm running the 5 instances from the same script (same process), or from different scripts (different processes).
What would cause this to work individually but not all at once?

A: That is because mechanize automatically creates a shared "cookie jar" by default. For more advanced cookie handling options, you will have to create your own cookie jar for each of the script sessions.
I had to use a custom cookie jar in a past project, in order to move cookies from one session to another. The end result is the same, each instance of your script would have it's own unique file to store it's cookies, so it's on you to manage the cookie files and know that they don't get confused.
>>>> import mechanize

>>>> cj1 = mechanize.CookieJar()
>>>> cj2 = mechanize.CookieJar()
>>>> mech1 = mechanize.OpenerFactory().build_opener(mechanize.HTTPCookieProcessor(cj1))
>>>> mech2 = mechanize.OpenerFactory().build_opener(mechanize.HTTPCookieProcessor(cj2))

>>>> request = mechanize.Request('http://example.com') # testing shows they can share a request

>>>> response1 = mech1.open(request)
>>>> response2 = mech2.open(request)

>>>> print cj1
<mechanize._clientcookie.CookieJar[<Cookie JSESSIONID=54FBB2BE99E4CFDA8F8386F52FCF59C3>]>
>>>> print cj2
<mechanize._clientcookie.CookieJar[<Cookie JSESSIONID=350C0D544CDAD344A1272DA8D7B016B0>]>

In this example I've tested, you can see the two mechanize objects, each with it's own independent cookie jar.


text:
Q: tinymce - initially hide() I am able to create a tinymce editor, and toggling the editor on and off.  Upon initially creation, is there a preferred way to have it hidden (not actually hidden, but editor off and just show the div)?
tinymce.init({
    'selector': "#divID"
});

tinymce.editors['divID'].hide();
tinymce.editors['divID'].show();

A: This is what I eventually did.  Don't know if there is a better way, but it works.
tinymce.init({
    'selector':'#divID',
    setup: function(ed) {
        ed.on('init', function(e) {
            e.target.hide();
        });
    }
});

A: I really am not sure if I understand you right.
Tinymce is an javascript iframe editor, you cant manipulate with it until its full load in page.
You want to show editor on click inside the div?
You could use this inline parameter:
tinymce.init({
    selector: "divID",
    inline: true
});

Working example
You want to hide the editor after some event?
You could use this:
$('#bottonID').click(function(){
  tinymce.editors['divID'].hide();
});

Working example
Or alternatively, try to use jquery tinymce:
download
Then manipulate tinymce like this:
$(function() {
   $('textarea.tinymce').tinymce({
    //your code
   });
});

If you could be more concrete,what you want to achieve, i could provide more exact answer.


text:
Q: How to use objects from a later version of Sencha ExtJS? So I am working on a project using Sencha ExtJS 4.1.0 but I need to use some methods that are not present on this version, but they are on version 4.2.1.
Specifically, I am looking to use the Ext.form.field.ComboBox class, and methods such as setMargin.
Is it safe and possible to just replace the class I need on my ExtJS folder with the new one?
Thanks!

A: Generally, you cannot just take a class (file) from a newer version and replace with it the corresponding class in the older version. It is very likely that methods were not only added but some may be removed, still required by the older version, signatures (arguments with which to call methods) may have changed, html markup could also be changed, etc.
What you can do is to study the method in new class and add it manually to the existing one in the form of an extension or override.
Also, if you find that you need the new functionality more and more, it is perhaps the time to upgrade the whole app to the new, or newer, Ext version.


text:
Q: how to design a microgrid I am working on designing a theoretical microgrid for a school building, but before I can even select theoretical components, I need to select what the structure of my microgrid will be.
Here's what I know:

*

*That MPPT charge controllers work by finding the maximum power points on your solar panels to ensure you get the most bang from your solar panel (and charge your battery safely and quickly)

*MPPT CC's can work with hybrid inverters to invert however much you need to power your AC loads while the rest gets sent to batteries (refer to the diagram at the bottom)

*DC coupled systems are much more efficient at charging batteries than AC coupled systems

*About 160 [kW] of PV panels would be used

*Unlike hybrid inverters, grid-tie inverters sync with the grid frequency and therefore scale infinitely

*A purely grid-tied system with no batteries is the most economical, but my project involves looking into a system with batteries anyway as a "what-if" scenario

*A DC busbar would be used to connect the batteries, hybrid inverter, and output of the MPPT CC's for the model. The higher the voltage, the less losses in the lines but there are safety considerations and component selection limitations to consider as well.

Here's what I don't know (these are my questions):

*

*How to make a system that uses MPPT CC's, hybrid inverters, and grid-tie inverters (to "sell back" excess generation when the batteries are full). A picture of what I was thinking is shown below. Otherwise, I feel as if I would need to have some of my PV panels only connected to a MPPT and a grid-tie inverter. Then the rest connected to the MPPT CC, battery bank, hybrid inverter, and loads. The problem with that is that there will be times when the batteries are full so the part of the PV panels that is connected to the batteries and hybrid inverter would be wasted.

*How AC combiner boxes work. Are they manufacturer specific where they only work with a specified inverter model (and number of inverters) or are they more of a stand-alone product like an inverter can be?
Current idea:

So what I was thinking was having a switch that just switches the PV panels to the grid-tie inverter when the batteries are full. As you can see, DC-coupled system. The problem with this idea is then the school building will start draining the batteries unnecessarily (batteries cost money and using them when you don't need to lowers their lifespan).
Another possibility I was thinking was just to leave however much the building will ever need at a given time always connected to the hybrid inverter and then just switching the rest of the PV panels either to the hybrid inverter or grid-tie inverter based on need (batteries need charged or batteries are full and I need to sell the excess).
I'm not an EE, so I wanted to see what your thoughts on this was (and info on AC combiner boxes).

A: The typical PV installation is either classified as "off grid" or "on grid".
The off grid version charges batteries from the solar panels via a DC bus and an inverter converts the DC bus to AC to supply the facility loads. There is no interconnect between utility company provided mains and the solar system. These systems are often used when utility company energy is not available or it is prohibitively expensive to install and operate.
The on grid version is the most common form. Here a number of solar panels are wired in series and connected to an inverter. The inverter converts the DC bus from the panels to AC. The inverter monitors the utility company AC line and syncs its frequency and phase to the AC line. If the AC mains fail, the inverter has protection circuits so that it drops off of the AC line to avoid causing harm to power line workers, etc. Many installation codes still require a separate mains disconnect switch, however. This type of system supplies all of its energy back to the power utility and the facility loads remain connected to the utility. This essentially allows the solar produced energy to offset the purchased energy.
An on grid system can include any number of inverters to reach the desired energy capacity. No special connections are required as they are typically paralleled on the utilities side and connected to a unique string of solar panels on the DC side.
Either style of system can employ MPPT (Maximum Power Point Tracking). This is a technique that extracts the maximum power available from the solar panel under the current sunlight conditions. Some newer systems put small MPPT trackers in place for every solar panel or a small collection of panels with the promise of further optimizing the total solar panel array power when some panels are shaded by a tree or cloud for example.
A few on grid system offer an accessory connection to the inverter for a few kW of power to provide a limited form of backup for the facility when the mains fail. This is rarely sufficient to power all facility loads.


text:
Q: Increase regex performance when matching only if not in html attribute TYPO3 blocks rendering of pages with more than 13 content-elements when using the Typoscript:
brandReplacing {
    stdWrap {
        replacement {
            10 {
                search = ®(?=[<]*(?:<[^>]*>[^<]*)*$)
                replace = ®
                useRegExp = 1
            }
        }
    }
}

as the regex even needs 118 Steps for this short example (steps needed increases exponentially / like 83000 steps needed for two more attributes). All in all the regex works fine but is too "huge".
Does anybody have an idea how to reduce the steps (performance) needed to execute the regex and maybe also exclude ®-Symbols already wrapped with -tags? Or is there a better way to solve this problem TYPO3-sided?
The regex like above:
®(?=[<]*(?:<[^>]*>[^<]*)*$)

The html code:

Copyright replacement correct: ®

Also correct replacement here: ®
Maybe NOT here: ®

A: I didn't analyse your regex to find exactly what is going on, but obviously backtracks are eating up resources. There are other ways to put an end to a pattern to prevent it to go further: Following the rules.
There should be some rules for defining attributes and their placeholders. I come with two rules which you may add to them later (see like when ® is inside an attribute value):

*

*There may be another attr = " value " immediately to be followed
by current one. Matching continues till engine sees a > without
jumping over any < or >: [^"<>]*"(\s\s*[\w-]+="[^<>]*>

*Or it may be last attribute that is going to reach a closing brace >: \/?>
Regex:
(®)(?!([^"<>]*"(\s\s*[\w-]+="[^<>]*>|\s*\/?>)))

Live demo
If you compare it to both your Regular Expressions you will notice how fast it is. Captured ®s have the same exact positions as previous ones.  It hardly matches wrong positions.
Failing cases:
It doesn't match a ®:

*

*If it is immediately followed by " string="...> within a literal text. E.g:

® character" some-chars-here="...."  />

*

*If it is immediately followed by a "   /> or  "   > within a literal text. E.g:

®   "        />

I think it rarely happens really.


text:
Q: MySQL: Select value where date between two dates. If date/value does not exist display date and value 0 I have this table:
+------------+---------+--------+----------+
| date       | regular | deduct | overtime |
+------------+---------+--------+----------+
| 2018-01-01 | 8       | 0      | 0        |
+------------+---------+--------+----------+
| 2018-01-03 | 8       | 0      | 0        |
+------------+---------+--------+----------+
| 2018-01-04 | 8       | 0      | 1        |
+------------+---------+--------+----------+
| 2018-01-09 | 8       | 2      | 0        |
+------------+---------+--------+----------+

And i want to select:

*

*Everything between 2018-01-01 and 2018-01-09

*Hours = regular - deduct + overtime

*If date not found, display with hours = 0

to get the following result:
+------------+-------+
| date       | hours |
+------------+-------+
| 2018-01-01 | 8     |
+------------+-------+
| 2018-01-02 | 0     |
+------------+-------+
| 2018-01-03 | 0     |
+------------+-------+
| 2018-01-04 | 9     |
+------------+-------+
| 2018-01-05 | 0     |
+------------+-------+
| 2018-01-06 | 0     |
+------------+-------+
| 2018-01-07 | 0     |
+------------+-------+
| 2018-01-08 | 0     |
+------------+-------+
| 2018-01-09 | 6     |
+------------+-------+

This is the SQL to generate the series of dates between two dates of which works:
SELECT DATE(cal.date) as date
FROM (
      SELECT SUBDATE(NOW(), INTERVAL 60 DAY) + INTERVAL xc DAY AS date
      FROM (
            SELECT @xi:=@xi+1 as xc from
            (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4) xc1,
            (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4) xc2,
            (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4) xc3,
            (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4) xc4,
            (SELECT @xi:=-1) xc0
      ) xxc1
) cal
WHERE cal.date >= '2018-01-01' and cal.date <= '2018-01-09'
GROUP BY DATE(cal.date)
ORDER BY cal.date ASC

And this is how I try to join my table above with the hours with no result:
SELECT DATE(cal.date) as date, IFNULL((x.regular + x.overtime - x.deduct), 0) AS hours
FROM (
      SELECT SUBDATE(NOW(), INTERVAL 60 DAY) + INTERVAL xc DAY AS date
      FROM (
            SELECT @xi:=@xi+1 as xc from
            (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4) xc1,
            (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4) xc2,
            (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4) xc3,
            (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4) xc4,
            (SELECT @xi:=-1) xc0
      ) xxc1
) cal
LEFT JOIN attendance x ON x.date = cal.date
WHERE cal.date >= '2018-01-01' and cal.date <= '2018-01-09'
GROUP BY DATE(cal.date)
ORDER BY cal.date ASC

A: Here is a simple fix:
SELECT DATE(cal.date) as date, IFNULL((x.regular + x.overtime - x.deduct), 0) AS hours
FROM (SELECT (DATE('2018-01-01') + INTERVAL xc DAY) AS date
      FROM (SELECT (@xi := @xi + 1) as xc
            FROM (SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4) xc1 CROSS JOIN
                 (SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4) xc2 CROSS JOIN
                 (SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4) xc3 CROSS JOIN
                 (SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4) xc4 CROSS JOIN
                 (SELECT @xi:=-1) xc0
           ) xxc1
     ) cal LEFT JOIN
     attendance x
     ON x.date = cal.date
WHERE cal.date >= '2018-01-01' and cal.date <= '2018-01-09'
GROUP BY DATE(cal.date)
ORDER BY cal.date ASC;

The problem is the JOIN and NOW().  NOW() as a time component, so the JOIN will always fail (well, unless you run at exactly midnight).
You could fix your version using CURDATE(), but I find the logic hard to follow, with dates relative to the present in one part of the query and fixed dates in another.


text:
Q: Best Compiler Destination I've got a few languages I've been building as interpreters.  When I'm ready to take "that next step", what options are best for non-native compiled formats... what are the pros and cons of each?
I've been looking at compiling to CLR or LLVM, and contemplated C-midcompile a few times, but I'm not completely certain.
A few features I'm hoping to be able to port are as follows:

*

*REPL - One of the languages I'm building supports block-level evaluation during runtime.

*Robust Macros - One of the languages I'm building requires the ability to filter through code seperately before tokenizing, and in the midstep between tokenizing and parsing.

Ok, not really "a few", just two.  I like to think I can port any other features my languages support to "anything".
What are my best options, and their pros/cons?

A: LLVM seems promising. The team claims better runtime performances on gcc with their backend compared to native. The ability to compile from the AST is really interesting (take a look at the tutorial). It can compile and optimize at runtime, which is a must for dynamic. It can also run as a pure interpreter.
I consider using LLVM in a project that involves creating a Tcl-like language. Tcl is heavily dynamic, so I don't know what this implies at this stage, but I'm confident that I'll get better performances than the current bytecode-based core.

A: Code generation is my business :-)
Comments on a few options:

*

*CLR:

*

*Pro: industrial support

*Con: you have to buy into their type system pretty much completely; depending on what you want to do with types, this may not matter

*Con: Only Windows platform is really prime-time quality

*LLVM:

*

*Pro: enthusiastic user community with charismatic leader

*Pro: serious backing from Apple

*Pro: many interesting performance improvements

*Con: somewhat complex interface

*Con: history of holes in the engineering; as LLVM matures expect the holes in the engineering to be plugged by adding to the complexity of the interface

*C--

*

*Pro: target is an actual written language, not an API; you can easily inspect, debug, and edit your C-- code

*Pro: design is reasonably mature and reasonably clean

*Pro: supports accurate garbage collection

*Pro: most users report it is very easy to use

*Con: very small development team

*Con: as of early 2009, supports only three hardware platforms (x86, PPC, ARM)

*Con: does not ship with a garbage collector

*Con: project has no future

*C as target language

*

*Pro: looks easy

*Con: nearly impossible to get decent performance

*Con: will drive you nuts in the long run; ask the long line of people who have tried to compile Haskell, ML, Modula-3, Scheme and more using this technique.  At some point every one of these people gave up and built their own native code generator.

Summary: anything except C is a reasonable choice.  For the best combination of flexibility, quality, and expected longevity, I'd probably recommend LLVM.
Full disclosure: I am affiliated with the C-- project.

A: pro/cons:

*

*CLR:

*

*pro: CLR environment readily available; a lot of stuff to bind to

*con: bound to CLR (;-); targetting some systems will be hard or impossible (embedded, mainframes, etc. CLR impl. might be less mature on non MS systems)

*LLVM:

*

*pro: independent from MS.

*con: targetting some systems might involve porting LLVM (?); interfacing to DOT-net, Java etc. might be troublesome (possibly needs FFI)

*C as target language:

*

*pro: almost all targets possible; easy code generation

*con: you will have to implement some VM stuff as runtime library (GC, dynload, dyn compilation etc.); some things are hard to do in C (continuations, backtracking, stack tracing, exceptions); some things are hard to do efficiently and portable in C (GC, dynamic types, stack layout dependence).

*Java ByteCode as target:

*

*pro: probably the biggest set of possible target platforms (even mobil phones and embedded stuff); a lot of existing tools around; easy interfacing to existing libraries

*con: some things are hard to implement or hard to implement efficiently (dynamic types, continuations, backtracking)

From all the above, I think targeting Java ByteCode would probably be best for you.
EDIT: actually an answer to a comment, but 300chars are not enough.
JByteCode iffy - I agree (being a Smalltalker, JBytecode is too limiting for me).
VM-wise, I think there is a relatively wide range of performance you can get as JVM, starting at pure slow bytecode interpreters up to high end sophisticated JITting VMs (IBM). I guess, CLR VM's will catch up, as MS is stealing and integrating all innovation anyway sooner or later, and the techniques to speedup dynamic translation are published (read the Self papers, for example). LLVM will probably progress a bit slower, but who knows. With C, you will benefit from better compilers for free, but things like dynamic retranslation etc. are hard to implement with C as target. My own system uses a mixture of precompiled and dynamically compiled code (having all: a slow bytecode interpreter, JITter and precompiled static C-code in one memory space).


text:
Q: Webdriver não da erro porém também não abre o navegador Testei um código simples para fazer o webdriver abrir o Chrome, e foi realizado com sucesso, porém o codigo abaixo não da erro, porém não abre o navegador.
from selenium.webdriver.common.keys import Keys
import time

class InstagramBOT:
 def _init_(self, username, password):
     self.username = username
     self.password = password
     self.driver = webdriver.Chrome(executable_path=r'C:\Program Files (x86)\chromedriver.exe')

def login(self):
 driver = self.driver
 driver.get('https://www.instagram.com/')

 Raphaelbot = InstagramBOT('***', '***')
 raphaelbot.login()

A: Já enfrentei esse mesmo erro, experimente instalar o webdriver numa variável
com essa lib from webdriver_manager.chrome import ChromeDriverManager
Seu código ficará assim:
from selenium.webdriver.common.keys import Keys
import time

#CASO NÃO TENHA A LIB, IRÁ BAIXAR A LIB ATRAVÉS DO PIP E IMPORTARÁ
#USE ESSE TRY/EXCEPT NO PRIMEIRO USO, DEPOIS NÃO É MAIS NECESSÁRIO
#OU UTILIZE O TERMINAL PARA INSTALAR A LIB E PODE IMPORTAR NORMALMENTE
import os
try:
    from webdriver_manager.chrome import ChromeDriverManager
except:
    os.system("pip install webdriver-manager")
    from webdriver_manager.chrome import ChromeDriverManager

_webdriver=ChromeDriverManager().install()

class InstagramBOT:
 def _init_(self, username, password):
     self.username = username
     self.password = password
     self.driver = webdriver.Chrome(_webdriver)

def login(self):
 driver = self.driver
 driver.get('https://www.instagram.com/')

 Raphaelbot = InstagramBOT('***', '***')
 raphaelbot.login()

Meu sistema operacional é o Linux, se for Windows o seu, pesquise como usar essa lib webdriver-maneger se der erro na execução. Mas acredito que vai funcionar.


text:
Q: Cannot have typeof(std::endl) as template parameter? So, I was trying to write a function like this:
void append_to_stream(std::ostream &stream)
{ }

template <typename T, typename... Args>
void append_to_stream(std::ostream &stream, T first, Args&&... rest)
{
  stream << first;
  append_to_stream(stream, rest...);
}

and call it like:
append_to_stream(stream,
                 std::endl,
                 std::endl);

But this doesn't work. I get an error that says 'too many arguments' to the function. I've narrowed it down to the point I know that the std::endl is guilty - probably because it's a function. I managed to 'solve' this by declaring a struct called endl and define the <<operator for it so that it simply calls std::endl. This works but doesn't feel particularly good. Is it not possible to accept std::endl as a template argument? The function works for other types.
Edit: here's the error:
src/log/sinks/file_sink.cpp:62:21: error: too many arguments to function 'void log::sinks::append_to_stream(std::string&, Args&& ...) [with Args = {}, std::string = std::basic_string<char>]'

Update
Trying to get the compiler to deduce the correct template arguments @MooingDuck suggested that a function of the following form could be used:
  template<class e, class t, class a>
  basic_ostream<e,t>&(*)(basic_ostream<e,t>&os) get_endl(basic_string<e,t,a>& s)
  {
return std::endl<e,t>;
  }

However, this doesn't compile.
Error:
src/log/sinks/file_sink.cpp:42:28: error: expected unqualified-id before ')' token
src/log/sinks/file_sink.cpp:42:53: error: expected initializer before 'get_endl'

Any ideas why? For the sake of compiling this, I've added using namespace std;

A: Much easier than specifying template arguments or defining a whole new template(!) is resolving the overload by cast.
typedef std::ostream & (&omanip_t)( std::ostream & );

append_to_stream(stream,
                 static_cast< omanip_t >( std::endl ),
                 static_cast< omanip_t >( std::endl ) );

This will work for all manipulators, whereas some manipulators could be templated differently, for example if user-provided.
Also, you should pass T first by either perfect forwarding or const reference. It doesn't make much sense to forward first, and then pass by value. Also, without a call to std::forward, rvalue arguments will be passed by value… just following the idiom, it would be
template <typename T, typename... Args>
void append_to_stream(std::ostream &stream, T &&first, Args&&... rest)
{
  stream << std::forward< T >( first );
  append_to_stream(stream, std::forward< Args >( rest ) ... );
}

http://ideone.com/cw6Mc

A: std::endl is a template, not a function, and the compiler cannot resolve which endl to use.
Try:
append_to_stream(std::cout,
             std::endl<char, std::char_traits<char>>,
             std::endl<char, std::char_traits<char>>);

Or, MooingDuck's solution (corrected):
template<class e, class t, class a> //string version
std::basic_ostream<e, t>& (*get_endl(const std::basic_string<e, t, a>&))
    (std::basic_ostream<e, t>& )
{ return std::endl<e,t>; }

template<class e, class t> //stream version
std::basic_ostream<e, t>& (*get_endl(const std::basic_ostream<e, t>&))
    (std::basic_ostream<e, t>& )
{ return std::endl<e,t>; }

int main () {
  std::ostream& stream = std::cout;
  append_to_stream(stream,
                 get_endl(stream),
                 get_endl(stream));
}

Here is get_endl solution, simplified by C++11 decltype feature:
template<class e, class t, class a> //string version
auto get_endl(const std::basic_string<e, t, a>&)
  -> decltype(&std::endl<e,t>)
{ return std::endl<e,t>; }

template<class e, class t> //stream version
auto get_endl(const std::basic_ostream<e,t>&)
  -> decltype(&std::endl<e,t>)
{ return std::endl<e,t>; }

int main () {
  std::ostream& stream = std::cout;
  append_to_stream(stream,
                 get_endl(stream),
                 get_endl(stream));
}


text:
Q: Phonegap Android Webview Video plays only audio I've started to play around with phonegab today. When I was trying to capture video its working fine. Now I wanna show the captured video in the webview. so I was trying as below.
var captureSuccess = function(mediaFiles) {
    var i, path, len;
    for (i = 0, len = mediaFiles.length; i < len; i += 1) {
        path = mediaFiles[i].fullPath;
        videoString = "<video width='320' height='240' controls='controls'><source src="+path+" type='video/mp4' /> <source src="+path+" type='video/ogg' />   <source src="+path+" type='video/webm' />Your browser does not support the video tag.</video>";
        $('#myVideo').html(videoString);
    }

};

// capture error callback
var captureError = function(error) {
    navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
};

// start video capture
function takeVideo(){
    navigator.device.capture.captureVideo(captureSuccess, captureError, {limit:1});
}

but in the UI I see the player being appended but it plays only the audio not the video.. wot could be the problem.??
Any help appreciated and thanks for your time in advance.

A: you have two source tag for video, that maybe a problem as there specified two different type.
<source src="+path+" type='video/mp4' />
<source src="+path+" type='video/webm' />

so, try to remove one of them.


text: Q: Is a react app which has multiple renderers much slower than a normal react app in react 18? Here is an old project, i want to use some react components in future development, so i need to embed multiple renderers in dom. But I don't know whether to do so will make the performance of the entire application lower.


text:
Q: Basis of sum subspace Let $W$ be a vector space and $U, V$ two subspaces with bases $ {u_1,...,u_n}$ and ${v_1, ..., v_s}$ respectively. How can I show rigorously that the basis of $U+V$ is ${u_1, ..., u_n, v_1,...,v_s}$?

My work:
First I have to show that $U+V \subset <{u_1, ..., u_n, v_1,...,v_s}>$. That is,  $h=u+v \implies h = (au_1+ ... + au_n)+ (bv_1 + ... +bv_s) = au_1+ ... + au_n+ bv_1 + ... +bv_s$. So $h \in U+V \implies h \in <{u_1, ..., u_n, v_1,...,v_s}>$.
Second I have to show that $<{u_1, ..., u_n, v_1,...,v_s}> \subset U+V$. That is, $h \in <{u_1, ..., u_n, v_1,...,v_s}> \implies h = au_1+ ... + au_n+ bv_1 + ... +bv_s = (au_1+ ... + au_n)+ (bv_1 + ... +bv_s) = u + v$, for some $ u \in U$ and $v \in V$.
Is this good enough or should I prove that <{u_1, ..., u_n, v_1,...,v_s}> are linearly independent first? If so, how should I do it?

A: This is true if and only if $V + W = V\oplus W$.  Otherwise the union of the bases is a spanning set; it must be "weeded" to get an actual basis.

A: It is not true that $u_1,\ldots ,u_n,v_1,\ldots ,v_s$ in general will be a basis.  It will span $U+V$, but it won't necessarily be a linearly independent set.  For example, in $\mathbb{R}^2$, take $U$ to be the space spanned by $u_1:=(1,0)$ and $V$ to be the space spanned by $v_1:=(0,1),v_2:=(1,1)$ (so that $V=\mathbb{R}^2$).  Then, $U+V=\mathbb{R}^2$, but $(1,0),(0,1),(1,1)$ is not a basis (the sum of the first and second is the third, and hence they are not linearly independent).
We can, however, show that it spans.  As $\{ u_1,\ldots ,u_n,v_1,\ldots ,v_s\} \subseteq U+V$, we immediately have that $\mathrm{Span}\, \{ u_1,\ldots ,u_n,v_1,\ldots ,v_s\} \subseteq \mathrm{Span}\, (U+V)=U+V$.
For the other direction, let $w=u+v\in U+V$ be arbitrary with $u\in U$ and $v\in V$.  You can write $u$ as a linear combination of $u_1,\ldots ,u_n$ and you can write $v$ as a linear combination of $v_1,\ldots ,v_s$, so that $w$ is a linear combination of $u_1,\ldots ,u_n,v_1,\ldots ,v_s$, i.e. $w\in \mathrm{Span}\, \{ u_1,\ldots ,u_n,v_1,\ldots ,v_s\}$.


text:
Q: What is a schema manager in Spring's Hibernate and how I set it? Some tables were dropped at development environment during a spring-data-jpa project test and the developer responsible for it said it only used spring.jpa.hibernate.ddl-auto=update. Checking here, I suspected he had it set as create-drop, but since he said he didn't use, I went for this piece of information:

Spring Boot chooses a default value for you based on whether it thinks your database is embedded.
It defaults to create-drop if no schema manager has been detected

Since his application actually managed to connect to our development environment PostgreSQL database (since it dropped some tables), I start to think he maybe could have forgotten to set hbm2ddl.auto and automatically it went as create-drop.
Is it possible to connect to PostgreSQL and don't have a valid schema manager defined? Which are the most common schema managers?
PS: at this application @DataSource is set this way:
@Bean
public DataSource dataSource() {
    Class.forName("org.postgresql.Driver");
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setUrl(someUrlConnectionStringFromApplicationDotPropertiesFile);
    return dataSource;
}

like String someUrlConnectionStringFromApplicationDotPropertiesFile = "jdbc:postgresql://ipAddress:port/dbName?user=user&password=pass". I know spring-data-jpa sets everything with spring jpa properties automatically without this method, this is currently an unchangeable legacy code :(

A: Spring Boot said they are Higher-level Database Migration Tool (Flyway or Liquibase).
ref: https://docs.spring.io/spring-boot/docs/2.7.x/reference/html/howto.html#howto.data-access.jpa-properties, https://docs.spring.io/spring-boot/docs/2.7.x/reference/html/howto.html#howto.data-access.jpa-properties
You can also configure them through Spring Boot documentation or their own docs. ref: https://docs.spring.io/spring-boot/docs/2.7.x/reference/html/howto.html#howto.data-initialization.migration-tool
For example, configure Flyway community version through maven (https://flywaydb.org/download/community):
<build>
    ...
    <plugin>
        <groupId>org.flywaydb</groupId>
        <artifactId>flyway-maven-plugin</artifactId>
        <version>9.12.0</version>
    </plugin>
    ...
</build>


text:
Q: an error of running a SQL query from cursor.execute in pyodbc of python 3.2.5 onm win 7 I am working on pyodbc in Eclipse (4.3.2v20140221-1852) with PyDev on Win 7. My python is 3.2.5.
At my code:
 cursor.execute("select top " + str(1) + " a.my_id, a.mycode" +
               "from my_table as a where a.mycode = ?", aGivenCode)

I got an error :
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver]
[SQL Server]Incorrect syntax near the keyword 'as'. (156) (SQLExecDirectW)")

Why I got error at " as a " ?
thanks !

A: A couple suggestions for future development:

*

*Use multi-line string notation """ to allow better identification of syntax errors (like the missing space between column and table in the original query).

*Instead of string concatenation, use a parameter for TOP values. The value must be wrapped in parentheses.
With these guidelines, your original code would be updated to:
top = 1
cursor.execute("""select top (?) a.my_id, a.mycode
                  from my_table as a
                  where a.mycode = ?""",
               (top, aGivenCode))

A: Try this? I think you're missing a space in there:
cursor.execute("select top " + str(1) + " a.my_id, a.mycode from my_table as a where a.mycode = ?", aGivenCode)

See how there is no space in between 'a.mycode' and 'from my_table'? I'm not 100% sure that is right, but give it a try.
These things are also easier to debug like this:
sql = "select top " + str(1) + " a.my_id, a.mycode from my_table as a where a.mycode = ?"
print sql
cursor.execute(sql, aGivenCode)


text:
Q: Making a new line in js string I want to make a new line between Editing and Become.
I tried \n but it didn't work
Any clue?
var i = 0;
var text = "Animation - Web Development- Video Editing Become a member & More.";

function typeWriter(){
    if(i < text.length){
        document.getElementById("text").innerHTML += text.charAt(i);
        i++;
        setTimeout(typeWriter, 50);
    }
}
typeWriter();

A: Add a line break to your string with \n. In your code check to see if a line break is the character, if it is, replace it with

var i = 0;
var text = "Animation - Web Development- Video Editing\nBecome a member & More.";

function typeWriter() {
  var ch = text.charAt(i)
  if (ch === '\n') {
    ch = '
'
  }
  document.getElementById("text").innerHTML += ch
  i++;
  i < text.length && setTimeout(typeWriter, 50);
}
typeWriter();

A: Because HTML doesn't render line feeds, you need to add a condition in your function or adapt your HTML code.
Solution #1
Update your Javascript function, add a special case in your first if statement:
var i = 0;
var text = "Animation - Web Development- Video Editing Become a member & More.";

function typeWriter(){
  if(i < text.length){
    if(text.charAt(i) === "\n")
      document.getElementById("text").innerHTML += "
";
    document.getElementById("text").innerHTML += text.charAt(i);
    i++;
    setTimeout(typeWriter, 50);
  }
}
typeWriter();

In that case, HTML will render
 tag by adding a new line. Don't forget to add the \n in your text variable.
Solution #2:
Use
 HTML tag, not recommended but content will be rendered too, without changing your Javascript function.

A: I believe /n isn't a good practice here, if you're receiving those data from a 3rd-party API for example, you won't be able to get /n in the text. So, your best bet is checking for the exact word you're looking for, and add break line after it.
Solution Explanation
The wordCheck boolean value is set to true by default, so our condition below keep running, until we found the word Editing in the printed text. In that case, we add a line break, set false value to wordCheck to prevent adding line breaks later.
I cached the element txtElement for better code readability.

var i = 0;
var text = "Animation - Web Development- Video Editing Become a member & More.";
var wordCheck = true;

function typeWriter(){
  var txtElement = document.getElementById("text");

  if(i < text.length){
    txtElement.innerHTML += text.charAt(i);
    i++;
    setTimeout(typeWriter, 50);

    // Here's we detect if the value reached the word "Editing", if so, we do break line
    var currentVal = txtElement.innerHTML;
    if(wordCheck && currentVal.indexOf('Editing') >= 1) {
      txtElement.innerHTML += "
";
      wordCheck = false;
    }
  }
}
typeWriter();


text:
Q: Replace switch statement with more concise logic I have a chunk of code like
        switch (newDir)
        {
            case "left":
                {
                    this.dx = -1; this.dy = 0;
                    break;
                }
            case "up":
                {
                    this.dx = 0; this.dy = 1;
                    break;
                }
            case "right":
                {
                    this.dx = 1; this.dy = 0;
                    break;
                }
            case "down":
                {
                    this.dx = 0; this.dy = -1;
                    break;
                }
            default: // never happens
                break;
        }

which is meant to set the direction that an object in my game is moving. I think it's nicely readable, self-explanatory, but it's too bulky for my liking. I'm wondering if you guys know of a fancy way for me to consolidate it to
this.dx = ... ;
this.dy = ... ;

Maybe something that involves bitwise operators or maps or something.

A: Use an object as a map
var directions = {
  'left': {
    dx : -1, dy : 0
  },
  'right': {
    dx : 1, dy : 0
  },
  'up': {
    dx : 0, dy : 1
  },
  'down': {
    dx : 0, dy : -1
  }
};

this.dx = directions[newDir].dx;
this.dy = directions[newDir].dy;

A: Just for the sake of it...
dir_map = {right:0,up:1,left:2,down:3}
dirs = [[1,0],[0,1],[-1,0],[0,-1]]

dir = dir_map[newDir] // and keep it as number from now on. Never get back to string.
this.dx += dirs[dir][0]
this.dy += dirs[dir][1]

Even if neutral direction is required:
if (dir != null) {
    this.dx += dirs[dir][0]
    this.dy += dirs[dir][1]
}


text:
Q: Function which returns dictionary overwriting all dictionaries Brief description of code:
The main code first makes a blank dictionary, which is passed on to my function. The function tallies how many of each number and updates the dictionary which is then returned. However when the function executes, it overwrites the input 'blank_dictionary' to be the same as the dictionary it returns ('new_dictionary'). Why does this happen? I want the 'dictionary' in the main code to remain blank throughout so that it can be reused.
def index_list(lst, blank_dictionary):
    new_dictionary = blank_dictionary
    for i in lst:
        new_dictionary[i] += 1
    return new_dictionary

number = 1
maximum = 3
numbers = range(1,maximum+1)

dictionary = {}
for i in numbers:
    dictionary[i] = 0

print ('original blank dictionary', dictionary)
new_dictionary = index_list([3,3,3],dictionary)
print ('new dictionary which indexed the list', new_dictionary)
print ('should still be blank, but isnt', dictionary)

Outputs:
original blank dictionary {1: 0, 2: 0, 3: 0}
new dictionary which indexed the list {1: 0, 2: 0, 3: 3}
should still be blank, but isnt {1: 0, 2: 0, 3: 3}

Thanks very much

A: You are setting new_dictionary to the reference to blank_dictionary. Change the line to new_dictionary = dict(blank_dictionary) and you will be fine. Using the dict() constructor function will make a new new_dictionary and so blank_dictionary will not be modified.
You might want to investigate the defaultdict in the collections module. If you only need to count the number of times each element appears, consider collections.counter.

A: This behavior is not limited to dicts. In Python, any time you pass a mutable object to a function, the function operates on the original object, not a copy. This is not true for immutable objects like tuples and strings.
However in this case there is no reason to pass a blank dictionary to the function in the first place. The function can create a new dictionary and return it.


text:
Q: How to take console input for C/C++ program in Eclipse CDT I have eclipse June CDT with gcc4 and gdb via cygwin on Windows7. I can't seem to taken input from the console. I searched around and it might be related to EOF for eclipse which might be resolved by unchecking "Connect process input & output to a terminal" in the Run/Debug configuration. But I can't seem to uncheck it.
Can anyone suggest best way to fix this issue.
#include <stdio.h>
#include <stdlib.h>

void menu();
int main(void) {

    menu();
    return 0;
}

void menu()
{
    int i=0;
     printf(" \n1. Push to Queue");
         printf(" \n2. Pop from Queue");
         printf(" \n3. Display Data of Queue");
         printf(" \n4. Exit\n");
         while(1)
         {
              printf(" \nChoose Option: ");
              scanf("%d",&i);
              switch(i)
              {
                    case 1:
                    {
                         int value;
                         printf("\nEnter a valueber to push into Queue: ");
                         scanf("%d",&value);
                        // push(value);
                        // display();
                         break;
                    }
                    case 2:
                    {
                        // delQueue();
                        // display();
                         break;
                    }
                    case 3:
                    {
                        // display();
                         break;
                    }
                    case 4:
                    {
                         exit(0);
                    }
                    default:
                    {
                         printf("\nwrong choice for operation");
                    }
              }
         }

}

A: You need to configure the command line arguments for Eclipse: Under Run configurations>Arguments
Read here
Also consider using Ant as a build script. Works better in the long run.

A: Found a pair of relevant related SO questions:

*

*Eclipse CDT Console output not showing up in debug with path and not showing up in run without path

*C++ program written in Eclipse using Windows and MinGW cannot display output to console view
Long story short, they are saying that cygwin is treated "differently" as a buffer compared with other OS's, and because of this the console is not as "interactive" as it (probably) should be.  Some solutions recommend an explicit flush of the buffer, while others offer configuration options.


text:
Q: Is it possible to use a javascript bookmarklet to invoke a locally stored/locally hosted Java applet? Wondering if this is possible, I have a java applet which I am embedding on my own version of website login pages (using wordpress currently) and using a Java applet to allow for login with a smartcard token which has the login details stored on it.
I was wondering if it was possible to use a javascript bookmarklet or something similar to load this Java Applet and add this functionality to pages which I do not have control of?
Thanks.
Edit: Currently I use the following code on pages which I can edit the html/php on, but I'd like to add it to other sites where I cannot do this with a javascript bookmarklet if possible. Pass happens to be the name of the function run by the page when the submit button is pressed.
  <script language="JavaScript"><!--
  function pass()
  {
    document.tstapp.put();
    document.loginform.user_login.value = document.tstapp.get();
    document.loginform.user_pass.value = document.tstapp.get2();

  }
  //-->
  </script>

  <APPLET name=tstapp code=LoginCard21.class archive="Cardv2.jar"  WIDTH=100 HEIGHT=30>
  </APPLET>

A: javascript:var applet = document.createElement('applet'); applet.name = 'tstapp'; applet.code = 'LoginCard21.class'; applet.archive = 'Cardv2.jar'; applet.width = 100; applet.height = 30; document.body.appendChild(applet); var pass = function () { document.tstapp.put(); document.loginform.user_login.value = document.tstapp.get(); document.loginform.user_pass.value = document.tstapp.get2(); };

The crux of this bookmarklet; that I think you didn't know about, is document.createElement.


text:
Q: Django - Managing page content in Django Admin I'm new to working with Django and am developing for a client who wants to be able to change page content in the Django Admin. They need to be able to change the html of the index page without editing the files on the server.
I know about flatfiles but I'm not sure that's completely what I'm after as I can't display stuff such as Django forms for example.
EDIT: Kind of like how a CMS works but without the users/group stuff and be able to use Django View modules such as forms.
Any advice?
Thanks

A: Honestly, the scope of what you're looking for is too huge to cover in this format. There's a number of ways this could be done, but they're all going to require some work and customization based on the client's needs.
Flatpages could work if you allow HTML content and make sure the content is rendered as "safe" in the template. This really only covers the "content" area of the site, though. It wouldn't be wise to use flatpages for an entire site template, including header, sidebar, footer, etc.
You could create editable areas. So, you actually create models for things like headers, sidebars, footers, and modules within those areas, and then just pull them into the template as needed. Then, the client is only editing pieces of the template instead of responsible for the whole HTML document.
Forms are going to be a challenge, because they require backend-processing that requires a connected view. The client won't be able to just arbitrarily drop in some form code and have a form. But, you could use a third-party service form forms and just embed them in the available content regions. Or, there's a couple of django apps that try to implement a type of "form builder" in the admin. That might somehow let the client add a form via something like the shortcodes used in Wordpress, but you'd likely have to lay down some infrastructure to make that work.
At a certain point, stuff like this reaches a point of diminishing returns, though. The only way to allow total customization of the template is to drop down into the actual physical file and make changes there. You can make certain things easier for the client, but ultimately, they either need to scale back their customization needs or deal with the fact that they'll have to work with the filesystem.

A: I don't believe that is possible at this time. Of course you can edit your models but templates, I think not.

A: I would find out how much they need to change? If they plan a complete redesign every week then you're still looking for an answer. If they just need a dynamic front page then you can split it up into variables and let them edit sections of html. Much safer and less prone to breaking the html.


text:
Q: Why does type& cannot bind const lvalue Why does type& cannot bind to a const L-value? I understand type& can bind to L-value but is const L-value is just an immutable address of some type of variable? My 2nd question is why does type& cannot bind to a "mordifiable R-value" either? your help is highly appreciated.

A:
Why is type& cannot bind to const L-value?

If it were allowed, you will be able to modify a const object.
void foo(int& v)
{
   v = 10;
}

int main()
{
   const int i = 20;
   int& ref = i;
   foo(ref);  // If the previous line were allowed, the value of i will be 10 after
              // the function returns, which violates the const-ness of i
}


text:
Q: DataGrip fails to import CSV file with entries-count exceeding a specific threshold I have a MaridaDB table and importing a CSV file of 36,000 entries using the DataGrip "import" dialog box succeeds with no issues at all; but, when a single entry is added to the CSV file to have 36,001 entries, the import fails with the following not-so-helpful notice:

Can't rollback changes with error records. Check connection and
database settings and try again.

I'm using the latest version of DataGrip (v2022.3.2, build #DB-223.8214.62) with MariaDB (v10.4.24) and the latest stable version of DataGrip MariaDB Driver (v3.0.7). My table doesn't have any restrictions (like having a unique column, or whatever), and the issue is certainly not with the added entry (it's absolutely valid and all).
To me, it seems like some kind of "overflow" issue. So, how may I successfully import larger count of CSV entries using DataGrip?

Interestingly, the same CSV file of 36,001 entries gets imported to the same table using phpMyAdmin with no problems at all. I've gone even further and successfully imported a CSV file of 100K+ entries using phpMyAdmin; but sadly, the small CSV file of 36,001 entries still doesn't get imported using DataGrip!

A: Please open a support ticket:
https://youtrack.jetbrains.com/newIssue?project=DBE
Attach the idea.log and activate the error log option from the Import window.
If you could additionally provide the csv file in question, that'd be great.


text:
Q: Text is disappearing when I try to add an image in PHP + GD library I'm trying to create a PNG with some text and a scaled picture in it. Here is the code for just the text, it works fine:
<?php
session_start();
error_reporting(E_ALL);

$label = imagecreate(500, 500);
imagecolorallocate($label, 0, 0, 0);

// up text
$color = imagecolorallocate($label, 255, 255, 255);
imagettftext($label, 50, 0, 0, 150, $color, "arial.ttf", "UP UP UP");

// down text
$color = imagecolorallocate($label, 255, 255, 255);
imagettftext($label, 50, 0, 0, 350, $color, "assets/fonts/arial.ttf", "DOWN DOWN DOWN");

header('Content-type: image/png');
imagepng($label);
imagedestroy($label);
die();
?>

With the code above you get the following picture, which is correct:

Now I'm trying to have a small picture in it, So I'm loading the picture from a JPEG file (adidas.jpg). Here's the code
<?php
session_start();
error_reporting(E_ALL);

$label = imagecreate(500, 500);
imagecolorallocate($label, 0, 0, 0);

// up text
$color = imagecolorallocate($label, 255, 255, 255);
imagettftext($label, 50, 0, 0, 150, $color, "arial.ttf", "UP UP UP");

// image
$src = imagecreatefromjpeg("adidas.jpg");
$pic = imagecreatetruecolor(500, 500);
imagecopyresampled($label, $src, 0, 0, 0, 0, 150, 150, imagesx($src), imagesy($src));
$white = imagecolorallocate($pic, 255, 255, 255);
imagefill($label,0,0,$white);
imagedestroy($pic);

// down text
$color = imagecolorallocate($label, 255, 255, 255);
imagettftext($label, 50, 0, 0, 350, $color, "arial.ttf", "DOWN DOWN DOWN");

header('Content-type: image/png');
imagepng($label);
imagedestroy($label);
die();
?>

And this is what I get:

To my surprise the "down" text disappeared. Why is that? The text added before the picture is fine, the text added after it turns to black for some reason

A: Your code is bit messy, "DOWN.." text will appear if you remove second:
$color = imagecolorallocate($label, 255, 255, 255);

You dont fill the original image, you try it later but with wrong color ($white is from $pic, not $label).
I cleaned it up:
<?php
session_start();
error_reporting(E_ALL);

$label = imagecreate(500, 500);
$black = imagecolorallocate($label, 0, 0, 0);
$white = imagecolorallocate($label, 255, 255, 255);
imagefill($label, 0, 0, $black);

imagettftext($label, 50, 0, 0, 150, $white, "arial.ttf", "UP UP UP");

$src = imagecreatefromjpeg("adidas.jpg");
$pic = imagecreatetruecolor(500, 500);
imagecopyresampled($label, $src, 0, 0, 0, 0, 150, 150, imagesx($src), imagesy($src));
$white2 = imagecolorallocate($pic, 255, 255, 255);

imagettftext($label, 50, 0, 0, 350, $white, "arial.ttf", "DOWN DOWN DOWN");

ob_end_clean();
header('Content-type: image/png');
imagepng($label);

imagedestroy($src);
imagedestroy($pic);
imagedestroy($label);
die();
?>


text:
Q: How Can I Switch Settings.settings between DEBUG and RELEASE mode? I have a url, to be more specific, a web service url, in Project/Properties/Settings.settings. It is added by Visual Studio when I add a web service reference.
The url should be different between DEBUG and RELEASE mode, how can I set up Visual Studio so that it build with correct url under DEBUG/RELEASE?
PS: I don't want to modify Settings.settings manually because it is not suggested by Visual Studio.

A: You could have both urls in your Settings file. And then you can access the specific settings depending on the current mode:
#if DEBUG
    string myUrl = Properties.Settings.Default.DebugUrl;
#else
    string myUrl = Properties.Settings.Default.ReleaseUrl;
#endif

A: I found a solution:
The auto generated proxy class inherited from SoapHttpClientProtocol has a property "Url", which you can set to point web service to another location. So I can save the web service link in config file, and fetch it to "Url" on the newly created proxy client object:
string serviceUrl = ConfigurationManager.AppSettings["URL"];
QisWebServiceClient qis = new QisWebServiceClient();
qis.Url = serviceUrl;