text:
Q: How to find a word in a text file and delete the line containing the word and the next two lines? I want to find a word in a text file using a batch file and then I want to remove that line containing the word and also delete some other lines below for example:
_italic_ or **bold**
put returns between paragraphs
indent code by 4 spaces
indent code by 4 spaces
_italic_ or **bold**2

so the result should be:
_italic_ or **bold**
_italic_ or **bold**2

A: You can try this batch code:
@echo off
set skipline=2
set search=returns
set File=Input.txt
setlocal EnableDelayedExpansion
for %%a in ("%File%") do (
    set linecount=1
    set skip=0
    For /f "usebackq tokens=* delims=" %%b IN (`type "%%a" ^| find /V /N ""`) do (
        set a=%%b
        set a=!a:*]=!
        if "!a!" NEQ "" (
            set search=!a:%search%=!
            if "!search!" NEQ "!a!" set /a skip=%skipline%+!linecount!
        )
        if !linecount! GTR !skip! echo(!a!
        set /a linecount+=1

    )>>tmp
    move /Y "tmp" "%%a">Nul
)
EndLocal
exit

This is working with a file containing blank lines and multiple line.
Change set skipline=2 for how many line to skip after find a word you search.
And for multiple files just change set File=Input.txt.
Example for file with extension .txt in current directory:
set File=*.txt

A: @echo off
setlocal EnableDelayedExpansion

rem Get the number of lines before the one that contain "returns"
for /F "delims=:" %%a in ('findstr /N "returns" input.txt') do set /A "lines=%%a-1"

rem Open a code block to read from input.txt and write to output.txt
< input.txt (

   rem Read and write the first "lines" lines
   for /L %%i in (1,1,%lines%) do (
      set "line="
      set /P "line="
      echo(!line!
   )

   rem Omit the number of desired lines (3 in this example)
   for /L %%i in (1,1,3) do set /P "line="

   rem Copy the rest of lines
   findstr "^"

) > output.txt

rem Replace the original file by the new one
move /Y output.txt input.txt

A: Here is a batch code for this task working only for an input text file not containing empty lines as those lines are skipped by command FOR.
It removes all blocks with 3 lines whereby first line contains returns.
@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "SkipLineCount=0"
set "OutputFile=OutputTextFile.txt"
del "%OutputFile%" 2>nul
for /F "usebackq eol=^ delims=" %%I in ("InputTextFile.txt") do (
    if !SkipLineCount! EQU 0 (
        set "Line=%%I"
        set "Line=!Line:returns=!"
        if "!Line!" NEQ "%%I" ( set "SkipLineCount=1" ) else echo(%%I>>"%OutputFile%"
    ) else (
        set /A SkipLineCount+=1
        if !SkipLineCount! EQU 3 set "SkipLineCount=0"
    )
)
move /Y "%OutputFile%" "InputTextFile.txt"
endlocal

This batch file processes each non empty line. Command FOR skips automatically all lines not containing any character.
Note 1: eol=^ in line with command FOR is necessary to read in and output also lines just containing commas or semicolons which otherwise would be also ignored by command FOR.
The current line is assigned to variable Line if currently no lines should be skipped. Next all occurrences of the word returns are removed case-insensitive from the line if the line contains at least one returns.
The line is ignored if the string of variable Line is not equal after the string replace with unmodified line read from file because this means the line contains at least one returns.
Otherwise the line read from input file is appended to output file.
Note 2: ( between echo and %%I is used here to output also input lines containing only 1 or more spaces or tabs as otherwise with a space instead of ( the command echo would write for such a case its current state OFF into the output file instead of the spaces/tabs read from input file.
The next 2 lines after a line with at least one returns are also ignored for being copied to output file.
As last command the created output file with the 3 lines removed is moved over the input text file.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

*

*del /?

*echo /?

*for /?

*if /?

*move /?

*set /?

*setlocal /?
Read also the Microsoft article about Using Command Redirection Operators.


text:
Q: Refactoring: How to replace a type (and update imports)? i.e. currently we use a type OldType from an npm package @old-package in our code base.
We want to replace it with our own type NewType, which can be imported via @new-package.
Example
Old imports
import {
  AnyImport,
  OldType,
  AnotherImport
} from '@old-package';

should be updated to:
New imports
import {
  AnyImport,
  AnotherImport
} from '@old-package';
import { NewType } from '@new-package';

How can we do this refactoring in IntelliJ, so that the import statements are correctly updated?
Notes:

*

*I think a simple replace RegEx will not work, because the old import may be one of many on multiple lines

*I checked the IntelliJ Migrate feature, but it seems this only works for Java code

*I checked the Structural search and replace feature, but cannot make it work for my case

Since this is a on-off operation it's also okay, if this can be done in another IDE or via a command-line tool, etc.

A: Structural searching for imports is not supported/implemented at this time (related feature request: IDEA-285199).
You can try some solutions available on the web, see https://www.npmjs.com/package/refactor-imports?activeTab=readme, for example

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flow provides null as data from room database When I use Flow ( kotlinx.coroutines.flow.Flow) I get null as response. Dao  code below :
   @Query("SELECT * FROM connect")
   fun getProfiles(): Flow<List<ConnectModel>>

But when I use List<ConnectModel> and remove flow I get expected result.
My connectImpl code:
 override fun getProfilesFromDB(): LiveData<List<ConnectModel>>
{
    val result = connectDAO.getProfiles()
    return result.asLiveData()
}

In viewmodel
     private val _users = MutableLiveData<List<ConnectModel>>()
     val users: LiveData<List<ConnectModel>>
    get() = _users

 fun getConnectUsers() {

    viewModelScope.launch {
        val response = getConnectUsersFromDbUseCase.invoke()
        _users.postValue(response.value)

    }
}

If I make the _users lateinit then it works fine but not when it is MutableLiveData.
In Fragment
  viewModel.users.observe(viewLifecycleOwner,{list ->
        if (list != null) {
            for(profile in list)
                Timber.i("Observer Active ${profile.name}")
        }
    })

Database
Any kind of help is appreciated. Thanks in advance.

A: Use collect or first like the code below
connectViewModel.getProfilesFromDB().collect {
      //do stuff
}

A: There is nothing wrong in your code, I've tried it and it's working perfectly fine as it should. It may be how you are observing this live data after getting it. I've this method in my view model and this is how I'm observing it inside fragment.
    connectViewModel.getProfilesFromDB().observe(viewLifecycleOwner){
          //do stuff
    }


text:
Q: Number of vectors $(x_1,...,x_n)$ such that $\sum_{i=1}^nx_i \leq k$ where $x_i$ is a positive integer The problem goes like this:

Determine the number of vectors $(x_1,...,x_n)$ such that $\sum_{i=1}^nx_i \leq k$ where $x_i$ is a positive integer and $k \geq n$

Notice the operator $\leq$. Its not $=$, in which case it turns out to be star and bar problem theorem 1.
How do I approach this one?
Update
Ok I found solution at the end of the exercise. But the explanation is fuzzy. It goes like this:

Since there are $\binom{j-1}{n-1}$ positive vectors whose sum is $j$, there must be $\sum_{j=n}^k\binom{j-1}{n-1}$ such vectors. But $\binom{j-1}{n-1}$ is the number of subsets of size $n$ from the set of numbers $\{1,...,k\}$ in which $j$ is largest element in the subset. Consequently, $\sum_{j=n}^k\binom{j-1}{n-1}$ is just the total number of subsets of size $n$ from a set of size $k$, showing that the preceding answer is equal to $\binom{k}{n}.$

I didn't get from the second sentence "But...".

A: You could introduce an extra variable $x_{n+1}$ defined to
be $k+1-\sum_{i=1}^nx_i$.

A: Although I prefer the other answer, another possibility is for each $l=n,n+1,\dots,k$ finding the number of solutions to
$$\sum_{i=1}^nx_i=n$$
(via stars and bars, like you linked) and then adding those values. Notice that $l=n$ is the smallest value $\sum x_i$ may assume if the $x_i\geq 1$, ie, they are positive.


text:
Q: Struts2: Get id from request prior to getModel() call I encountered the problem after upgrading Struts2 to 2.3.15 from 2.3.1
In my action I use ModelDriven Interface to populate a bean. In request I also pass parameter id that identifies object in the session. Id parameter is not part of the bean. To populate id field in action prior to getModel() I used "params" interceptor in front of other interceptors.
In Struts 2.3.15 I get lots of errors from ParametersInterceptor - no setter could be found. It throws errors for all fields that supposed to set my bean fields.
What is the right way to handle such situation?


text:
Q: Cannot see why convergence to zero follows from two hypothesis I read a proof which at some point reaches a sequence of this kind:
$b_m \leq m^{-1+1/p} g(m) /p$, where $p \in (1,2)$ and $0 < g(m) \rightarrow 0$
Now it is interested in showing that $\frac{1}{n^{1/p}}\sum_{m=1}^n b_m \rightarrow 0$.
It claims that it follows from the fact that $\sum_{m=1}^n m^{-1+1/p} \leq K n^{1/p}$ and that $g$ goes to zero. But from those two facts I can only see that the desired limit is finite, not necessarily zero.
If someone could point me to a convergence criterion that can be used to prove that the limit is zero I would be thankful.

A: Let $\epsilon >0$. Choose $N$ such that $g(m) <\epsilon$ for $m \geq N$. For $n >N$ we have $n^{-1/p} \sum\limits_{m=1}^{n}b_m=n^{-1/p} \sum\limits_{m=1}^{N}b_m+n^{-1/p} \sum\limits_{m=N+1}^{n}b_m$. The second term is less than $\epsilon K/p$. The first term tends to $0$ as $n \to \infty$.

A: Hint: Observe that $$\frac{1}{n^c}\sum_{j=1}^n a_j\sim\frac{1}{n^c}\sum_{j=N}^n a_j$$ for any $c>0$ and $N\in\mathbb N$ fixed.
To the original question, note that the constant $p$ in the expression of $b_m$ doesn't affect the convergence, so let $\varepsilon>0$. Then using the fact that $\sum_{j=1}^n j^{-1+1/p}\leq K\cdot n^{1/p}$, take $N$ large enough so that $g(n)<\varepsilon/K$ for all $n\geq N$. Now $$\frac{1}{n^{1/p}}\sum_{j=1}^n b_j\sim\frac{1}{n^{1/p}}\sum_{j=N}^n b_j< \frac{\varepsilon}{K}\cdot K=\varepsilon.$$ Note that this approach only requires $p>0$, so it is slightly more general than the original problem.


text:
Q: Context Menu ShortcutKeys do not work C# I would like to add shortcuts to the MenuItems in my ContextMenu.
I am using this code:
mnuContextMenu = new ContextMenu();
saveMenuItem = new MenuItem("Speichern", SaveFile, Shortcut.CtrlS);
mnuContextMenu.MenuItems.Add(saveMenuItem);

The Shortcut is even shown inside the ContextMenu, but it does not respond when i am pressing the keys.
Anybody has an idea why?


text:
Q: how to submit with a form data? I use a FormData() and I need to keep the behaviour of a regular form:
<form id="myForm" method="post", action="/pageToGo">
    stuff...
</form>

<script>
    var regularForm = document.getElementById('myForm')

    var myFormData = new FormData(regularForm)
    myFormData.append(stuff...)

    var request = new XMLHttpRequest()
    request.open('post', '/pageToGo')

    request.send(myFormData) // Do not change document.location.href
    regularForm.submit() // Do not include the happened stuff
</script>

I want to be redirected like if I submited in a regular form.
What can I do ? Thank you for your help

A: Don't use FormData.
Append hidden input elements to the form instead. Then call its submit() method.

A: create hidden input fields with name id and value you want to send
eg.<input name="say" id="say" value="Hi">

then see in your networks form data in devtool


text:
Q: Maven default local repository There is problem with local maven repository. I want to change maven and local repository path. I use Intellij and did it in setting->build,execution,deployment->maven, just changed here user settings file and local_repository then choose override and apply.
If I put mvn install there is still default path (/.m2/repository/). How is it possible do solve this problem?

A: Why don't you try to update the local repo path in the settings.xml inside 'conf' directory with a text editor?
<localRepository>{your-new-path}</localRepository> <!-- goes inside the settings tag -->

Once done, make sure that the maven location pointed to by MAVEN_HOME and the settings file you have configured are one and the same.

A: Overrriding Local Repository preference in Intellij doesn't change the system-level settings. They only resonate well inside Intellij. You will have to use Maven Projects view inside intellij and run the maven goals from there for this setting to take effect. If you run from inside a terminal, whether from inside Intellij or outside it, you will have to explicitly specify the loca repo as an argument to the command. Check this: Can I add maven repositories in the command line?

A: It looks like you have only changed the maven path and not the repository path.
Your repository location is specified in the .m2/conf/settings.xml file. Once you change your MAVEN_HOME in your classpath to point to the right maven location, you should also change the repository location in the settings xml.
Hope this helps.


text:
Q: How to make a record from a sequence of values I have a simple record definition, for example
(defrecord User [name email place])

What is the best way to make a record having it's values in a sequence
(def my-values ["John" "john@example.com" "Dreamland"])

I hoped for something like
(apply User. my-values)

but that won't work. I ended up doing:
(defn make-user [v]
  (User. (nth v 0) (nth v 1) (nth v 2)))

But I'm sensing there is some better way for achieving this...

A: the defrecord function creates a compiled class with some immutable fields in it. it's not a proper clojure functions (ie: not a class that implements iFn). If you want to call it's constructor with apply (which expects an iFun) you need to wrap it in an anonymous function so apply will be able to digest it.
 (apply #(User. %1 %2 %3 %4) my-values)
it's closer to what you started with though your approach of defining a constructor with a good descriptive name has its own charm :)
from the API:
Note that method bodies are
not closures, the local environment includes only the named fields,
and those fields can be accessed directy.

A: Warning: works only for literal sequables! (see Mihał's comment)
Try this macro:
(defmacro instantiate [klass values]
        `(new ~klass ~@values))

If you expand it with:
(macroexpand '(instantiate User ["John" "john@example.com" "Dreamland"]))
you'll get this:
(new User "John" "john@example.com" "Dreamland")
which is basically what you need.
And you can use it for instantiating other record types, or Java classes. Basically, this is just a class constructor that takes a one sequence of parameters instead of many parameters.

A: Writing your own constructor function is probably the way to go.  As Arthur Ulfeldt said, you then have a function you can use as a function (e.g. with apply) rather than a Java-interop constructor call.
With your own constructor function you can also do argument validation or supply default arguments.  You gain another level of abstraction to work with; you can define make-user to return a hash-map for quick development, and if you later decide to change to records, you can do so without breaking everything.  You can write constructors with multiple arities, or that take keyword arguments, or do any number of other things.
(defn- default-user [name]
  (str (.toLowerCase name) "@example.com"))

(defn make-user
  ([name] (make-user name nil nil))
  ([name place] (make-user name nil place))
  ([name user place]
     (when-not name
       (throw (Exception. "Required argument `name` missing/empty.")))
     (let [user (or user (default-user name))]
       (User. name user place))))

(defn make-user-keyword-args [& {:keys [name user place]}]
  (make-user name user place))

(defn make-user-from-hashmap [args]
  (apply make-user (map args [:name :user :place])))

user> (apply make-user ["John" "john@example.com" "Somewhere"])
#:user.User{:name "John", :email "john@example.com", :place "Somewhere"}

user> (make-user "John")
#:user.User{:name "John", :email "john@example.com", :place nil}

user> (make-user-keyword-args :place "Somewhere" :name "John")
#:user.User{:name "John", :email "john@example.com", :place "Somewhere"}

user> (make-user-from-hashmap {:user "foo"})
; Evaluation aborted.
; java.lang.Exception: Required argument `name` missing/empty.

A: One simple thing you can do is to make use of destructuring.
(defn make-user [[name email place]]
  (User. name email place))

Then you can just call it like this
(make-user ["John" "John@example.com" "Dreamland"])

A: Update for Clojure 1.4
defrecord now defines ->User and map->User thus following in Goran's footstaps, one can now
(defmacro instantiate [rec args] `(apply ~(symbol (str "->" rec)) ~args))

which also works with non-literal sequences as in (instantiate User my-values).
Alternatively, along the lines of map->User one can define a function seq->User
(defmacro def-seq-> [rec] `(defn ~(symbol (str "seq->" rec)) [arg#] (apply ~(symbol (str "->" rec)) arg#)))

(def-seq-> User)

which will allow (seq->User my-values).

A: The idiomatic way to call a Record constructor is with the Clojure symbol ->MyRecord and that works just fine with apply.
(def my-values ["John" "john@example.com" "Dreamland"])
(defrecord User [name email place])
(apply ->User my-values)

; => #my-ns.User{:name "John",
                 :email "john@example.com",
                 :place "Dreamland"}


text:
Q: How to add Data in Array Dynamically, from form In PHP I have a task to take input from user and push it in array.
How can I take input from input field submit it, push it in to array and then do this again?
    <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
        Input Stuff in this Table :
        <input type="text" name="insert">
        <input type="submit" name="submit">
    </form>

    <?php
        $insert = ($_POST["insert"]);
        array_push($data, $insert);
        print_r($data);
    ?>

A: you will miss the content of your variable and will re-initialize it on every page load, the solution is to keep your $data variable in the session and use it on every form submission:
<?php
   session_start();
   $data = isset($_SESSION['data']) ? $_SESSION['data'] : [];
   array_push($data, $_POST["insert"]);
   $_SESSION['data'] = $data;
?>


text:
Q: Testing wrapper.props shallow render is undefined I want to test the following code:
<React.Fragment>
    <Connect />
    <FlatList
        data={[
            {key: "pp", title: "Privacy Policy"},
            {key: "tos", title: "Terms of Service"},
        ]}
        renderItem={({item}) => {
            return (
                <View
                    onPress={() => this.handleOnPress(item.key)}
                >
                    <Text>{item.title}</Text>
                </View>
            );
        }}
    />
</React.Fragment>

These are my tests:
it("should render a FlatList with 2 items", () => {
        const wrapper = shallow(
            <Menu
            />
        );
        expect(wrapper).toMatchSnapshot();
        expect(wrapper.props().data).toHaveLength(2);
    });

For some reason, it is failing and showing .data is undefined. I basically want to test that my flat list has 2 items.

A: If I understand the problem, then it looks like you're trying to get the .props() of the <Menu/> (wrapper) , rather than the <FlatList/> which is a child of the wrapper.
By using the .childAt method, you should be able to resolve the problem with the following:
it("should render a FlatList with 2 items", () => {
    const wrapper = shallow(
        <Menu
        />
    );
    expect(wrapper).toMatchSnapshot();

    // expect(wrapper.props().data).toHaveLength(2);

    expect(
      wrapper // the wrapper of 'Menu'
      .childAt(1) // the second child of the 'Menu' which is the 'FlatList'
      .props() // the props of 'FlatList'
      .data // the data field of 'FlatList' props
    ).toHaveLength(2);
});

Here is more information on the .childAt() method - hope this helps


text:
Q: i want to open new activity in Array Adapter tell me how its possible This is my code which is i'm working but the startActivity function is not working here and the click Listener is working. Please help me how is this  possible.
This is my main Thread code:
restaurant_Array_list = new ArrayList<home_listview_model>();
        new get_restaurant_data().execute("http://unstoppable.io/food/androidApi");

        ListView listview = (ListView)findViewById(R.id.home_list);
        home_listadapter = new home_listadapter(getApplicationContext(), R.layout.home_list_view, restaurant_Array_list);

        listview.setAdapter(home_listadapter);

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,long id) {
                Toast.makeText(getApplicationContext(), restaurant_Array_list.get(position).getRestaurant_name(), Toast.LENGTH_LONG).show();
            }
        });

This is AsyncTask code:
public class get_restaurant_data extends AsyncTask<String, Void, Boolean> {

    ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = new ProgressDialog(home.this);
        dialog.setMessage("Loading... please wait");
        dialog.show();
        dialog.setCancelable(false);
    }

    @Override
    protected Boolean doInBackground(String... urls) {
        try {

            //------------------>>
            HttpGet httppost = new HttpGet(urls[0]);
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = httpclient.execute(httppost);

            // StatusLine stat = response.getStatusLine();
            int status = response.getStatusLine().getStatusCode();

            if (status == 200) {
                HttpEntity entity = response.getEntity();
                String data = EntityUtils.toString(entity);

                JSONObject jsono = new JSONObject(data);
                JSONArray jarray = jsono.getJSONArray("restaurant_list_data");

                for (int i = 0; i < jarray.length(); i++) {
                    JSONObject jsonrealobject = jarray.getJSONObject(i);
                    home_listview_model lisviewarray = new home_listview_model();

                    lisviewarray.setRestaurant_id(jsonrealobject.getString("restaurant_id"));
                    lisviewarray.setRestaurant_name(jsonrealobject.getString("restaurant_name"));
                    lisviewarray.setRestaurant_address(jsonrealobject.getString("address"));
                    lisviewarray.setRestaurant_opping_time(jsonrealobject.getString("restaurant_opping_time"));

                    restaurant_Array_list.add(lisviewarray);
                }
                return true;
            }

            //------------------>>

        } catch (ParseException | IOException | JSONException e1) {
            e1.printStackTrace();
        }
        return false;
    }
    protected void onPostExecute(Boolean result) {
        dialog.cancel();
        home_listadapter.notifyDataSetChanged();
        if(result == false){
            Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
        }
    }
}

This is Array Adapter where i want to open new Activity:
    package com.example.nhp04.gqfood;

    import android.content.Context;
    import android.content.Intent;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.TextView;

    import java.util.ArrayList;

    public class home_listadapter extends ArrayAdapter<home_listview_model> {

    ArrayList<home_listview_model> restaurant_Array_list;
    LayoutInflater vi;
    int Resource;
    ViewHolder holder;

    public home_listadapter(Context context, int resource, ArrayList<home_listview_model> objects) {
        super(context, resource, objects);
        vi = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        Resource = resource;
        restaurant_Array_list = objects;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // convert view = design
        View v = convertView;
        if (v == null) {
            holder = new ViewHolder();
            v = vi.inflate(Resource, null);
            holder.restaurant_id = (TextView)v.findViewById(R.id.restaurant_id);
            holder.restaurant_name = (TextView)v.findViewById(R.id.restaurant_name);
            holder.restaurant_address = (TextView)v.findViewById(R.id.address);
            holder.restaurant_opping_time = (TextView)v.findViewById(R.id.opningtime);
            v.setTag(holder);
        } else {
            holder = (ViewHolder) v.getTag();
        }
        holder.restaurant_id.setText(restaurant_Array_list.get(position).getRestaurant_id());
        holder.restaurant_name.setText(restaurant_Array_list.get(position).getRestaurant_name());
        holder.restaurant_address.setText(restaurant_Array_list.get(position).getRestaurant_address());
        holder.restaurant_opping_time.setText("Opens at "+restaurant_Array_list.get(position).getRestaurant_opping_time());

        holder.restaurant_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(home_listadapter.this, restaurent.class));
            }
        });
        return v;

    }

    static class ViewHolder {
        public TextView  restaurant_id;
        public TextView  restaurant_name;
        public TextView  restaurant_address;
        public TextView  restaurant_opping_time;

    }
}

A: Do like this...
holder.restaurant_name.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(AdapterView<?> arg0, View arg1,int position, long arg3)
        {
        Intent i = new Intent(context, restaurent.class);
        context.startActivity(i);
        }
    });

A: Save your context on your home_listadapter constructor
Context mContext;

public home_listadapter(Context context, int resource, ArrayList<home_listview_model> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
restaurant_Array_list = objects;
mContext = context;
}

Then on your holder.restaurant_name.setOnClickListener
holder.restaurant_name.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(mContext, restaurent.class)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
    }
});

A: try this,
Do this in Your Adapter Constructor:
Context mContext;
public home_listadapter(Context context, int resource, ArrayList<home_listview_model> objects) {
    super(context, resource, objects);
   mContext=context;
    vi = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    Resource = resource;
    restaurant_Array_list = objects;
}

And on Click start the activity:
mContext.startActivity(new Intent(mContext, restaurent.class));

A: Try this:
 Intent intent = new Intent(context, restaurent.class);
 ((Activity) context).startActivity(intent);

A: Do like this
 holder.restaurant_name.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
              Intent in=new Intent(v.getContext(),SingleItemView.class);
                    v.getContext().startActivity(in);

        }
    });


text:
Q: Cannot connect to internet-facing NLB forwarding traffic to a private instance I have configured a cloud with following configuration

*

*VPC with a public and private subnet in two availability zones. Public subnet has an internet gateway and private subnet has a NAT gateway configured

*An internet-facing Network Load Balancer allowing TCP traffic configured in both availability zones

*A target group to forward traffic from the load balancer

*An EC2 instance in private subnet configured with haproxy listening at port 80. It's security group is configured to accept TCP traffic at port 80 from both the subnets in which NLB is configured

*Added this instance to the target group, the status is healthy
When I try to hit the NLB DNS it is giving me 'Connection timed-out' error. I am expecting that when I hit NLB DNS it should forward me to the private instance. I have checked many AWS documents such as this link but still cannot find the resolution to this issue. Please feel free to ask for more information if this is not sufficient.

A:
It's security group is configured to accept TCP traffic at port 80 from both the subnets in which NLB is configured

When targets are registered by instance-id, the security group for instances behind an Internet-facing NLB need to allow traffic from 0.0.0.0/0 -- or whatever range of public IP addresses need to access them through the balancer -- not just the subnets of the balancer (which are needed for health-checks).

If your target type is an instance, add a rule to your security group to allow traffic from your load balancer and clients to the target IP.
https://aws.amazon.com/premiumsupport/knowledge-center/security-group-load-balancer/

Unlike ALB and Classic balancers, NLB traffic has the source address of the external client when the targets are configured by instance-id, and this is the address the security group is matching against.


text:
Q: How to change product image size in Magento 2 In the gird view of a category I want to reduce the number of products per ROW from 4 to 3, and I want to increase the image size there ... how can I do that?

A: For increasing the image size, we can change the default values in view.xml of our custom theme.
app/design/frontend/{Vendor_Theme}/{Theme_Name}/etc/view.xml
<image id="category_page_grid" type="small_image">
    <width>240</width>
    <height>300</height>
</image>
<image id="category_page_list" type="small_image">
    <width>240</width>
    <height>300</height>
</image>

We can read more here.
From my experience, in Magento 1, we can easily set items per row in products/category pages by adding <action method="setColumnCount"><count>5</count></action>. Currently, Magento 2 doesn't support the set and get column count. However, we can do this by using CSS. For example, we can find the css in file: vendor/magento/theme-frontend-luma/Magento_Catalog/web/css/source/module/_listings.less.
If we want to be more advance, we can add the set and get column count method by overriding the class \Magento\Catalog\Block\Product\ListProduct.

A: Magento product uses the file view.xml for image size dimensions at path vendor/magento/theme-frontend-luma/etc/view.xml
Here you will find node inside the node.
Copy the file view.xml and put it in your theme path and make the changes, say app/design/frontend/MyThemePackage/MyTheme/etc/view.xml
<view xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Config/etc/view.xsd">
<media>
 <images module="Magento_Catalog">
    ........
    <image id="category_page_list" type="small_image">
         <width>270</width>
         <height>450</height>
    </image>
    ........
  </images>
</media>
......
</view>

Write Below css to change display from 4 to 3 products per row
.page-products .products-grid .product-item {
  margin-left: calc(0.00333333%) !important;
  width: 33.33%!important;
}

Clear the cache and load the category list page. Your changes will be reflected.


text:
Q: Produce a bundle layout with a csv file I'm trying to produce a bundle layout and I managed to do it. However, I'd like to be able to use a simple CSV field instead of json. I've tried to replace the d3.json by the d3.csv function but I can't make it work.
Any idea?
My code: http://plnkr.co/edit/0hwlJmEhNyjqhuCPdW5w
<!DOCTYPE html>
<meta charset="utf-8">
<style>

.node {
  font: 300 11px "Helvetica Neue", Helvetica, Arial, sans-serif;
  fill: #bbb;
}

.node:hover {
  fill: #000;
}

.link {
  stroke: steelblue;
  stroke-opacity: .4;
  fill: none;
  pointer-events: none;
}

.node:hover,
.node--source,
.node--target {
  font-weight: 700;
}

.node--source {
  fill: #2ca02c;
}

.node--target {
  fill: #d62728;
}

.link--source,
.link--target {
  stroke-opacity: 1;
  stroke-width: 2px;
}

.link--source {
  stroke: #d62728;
}

.link--target {
  stroke: #2ca02c;
}

</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<div>
<script>

var diameter = 480, // diameter = 960 ou 480
    radius = diameter / 2,
    innerRadius = radius - 120;

var cluster = d3.layout.cluster()
    .size([360, innerRadius])
    .sort(null)
    .value(function(d) { return d.size; });

var bundle = d3.layout.bundle();

var line = d3.svg.line.radial()
    .interpolate("bundle")
    .tension(.85)
    .radius(function(d) { return -d.y; })
    .angle(function(d) { return d.x / 180 * Math.PI; });

var svg = d3.select("body").append("svg")
    .attr("width", diameter)
    .attr("height", diameter)
  .append("g")
    .attr("transform", "translate(" + radius + "," + radius + ")");

var link = svg.append("g").selectAll(".link"),
    node = svg.append("g").selectAll(".node");

d3.json("test.json", function(error, classes) {
  var nodes = cluster.nodes(packageHierarchy(classes)),
      links = packageLinks(nodes); // links = packageImports(nodes);

  link = link
      .data(bundle(links))
    .enter().append("path")
      .each(function(d) { d.source = d[0], d.target = d[d.length - 1]; })
      .attr("class", "link")
      .attr("d", line);

  node = node
      .data(nodes.filter(function(n) { return !n.children; }))
  // add an URL on each link
    .enter().append('a')
    .attr("xlink:href", function(d){return d.url;})
    .append("text")
      .attr("class", "node")
      .attr("dy", ".31em")
      // put the parents on the left rather than on the right
      .attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + ((-d.y) - 8) + ",0)" + (d.x < 180 ? "" : "rotate(180)"); })
      //.attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + (d.y + 8) + ",0)" + (d.x < 180 ? "" : "rotate(180)"); })
      .style("text-anchor", function(d) { return d.x < 180 ? "end" : "start"; })
      .text(function(d) { return d.key })
      .on("mouseover", mouseovered)
      .on("mouseout", mouseouted);
});

function mouseovered(d) {
  node
      .each(function(n) { n.target = n.source = false; });

  link
      .classed("link--target", function(l) { if (l.target === d) return l.source.source = true; })
      .classed("link--source", function(l) { if (l.source === d) return l.target.target = true; })
    .filter(function(l) { return l.target === d || l.source === d; })
      .each(function() { this.parentNode.appendChild(this); });

  node
      .classed("node--target", function(n) { return n.target; })
      .classed("node--source", function(n) { return n.source; });
}

function mouseouted(d) {
  link
      .classed("link--target", false)
      .classed("link--source", false);

  node
      .classed("node--target", false)
      .classed("node--source", false);
}

d3.select(self.frameElement).style("height", diameter + "px");

// Lazily construct the package hierarchy from class names.
function packageHierarchy(classes) {
  var map = {};

  function find(name, data) {
    var node = map[name], i;
    if (!node) {
      node = map[name] = data || {name: name, children: []};
      if (name.length) {
        node.parent = find(name.substring(0, i = name.lastIndexOf(".")));
        node.parent.children.push(node);
        node.key = name.substring(i + 1);
      }
    }
    return node;
  }

  classes.forEach(function(d) {
    find(d.name, d);
  });

  return map[""];
}

// Return a list of imports/links for the given array of nodes.
function packageLinks(nodes) { //function packageImports(nodes) {
  var map = {},
      links = []; // imports = [];

  // Compute a map from name to node.
  nodes.forEach(function(d) {
    map[d.name] = d;
  });

  // For each import/link, construct a link from the source to target node.
  nodes.forEach(function(d) {
    if (d.links) d.links.forEach(function(i) { //if (d.imports) d.imports.forEach(function(i) {
      links.push({source: map[d.name], target: map[i]}); //imports.push({source: map[d.name], target: map[i]});
    });
  });

  return links; //return imports;
}

</script>
</div>

test.json file:
[
{"name":"brut.smith.Grandpa","url":"http://www.google.com","tooltip":"Lorem","links":["brut.smith.Grandpa"]},
{"name":"brut.smith.Daddy","url":"http://www.gmail.com","tooltip":"Ipsum","links":["brut.smith.Grandpa"]},
{"name":"brut.smith.Mummy","url":"http://www.yahoo.com","tooltip":"Dolor","links":["brut.smith.Mummy"]},
{"name":"pmu.smithKid.Peter","url":"http://www.microsoft.com","tooltip":"Sit","links":["brut.smith.Daddy", "brut.smith.Mummy"]},
{"name":"pmu.smithKid.Simon","url":"http://www.google.fr","tooltip":"Amet","links":["brut.smith.Daddy", "brut.smith.Mummy"]},
{"name":"brut.martin.Uncle","url":"https://github.com/mbostock/d3/wiki/CSV","tooltip":"Consectetur","links":["brut.martin.Uncle"]},
{"name":"brut.martin.Aunt","url":"http://bl.ocks.org/mbostock/7607999","tooltip":"Elit","links":["brut.martin.Aunt"]},
{"name":"pmu.martinKid.Mathis","url":"http://stackoverflow.com/","tooltip":"Lorem","links":["brut.martin.Uncle", "brut.martin.Aunt"]},
{"name":"pmu.martinKid.Adrien","url":"htpp://www.microsoft.com","tooltip":"Ipsum","links":["brut.martin.Uncle", "brut.martin.Aunt"]},
{"name":"pmu.martinKid.Chloé","url":"http://www.d3js.org","tooltip":"Dolor","links":["brut.martin.Uncle", "brut.martin.Aunt"]}
]

test.csv file:
name;url;tooltip;links
parent.smith.Grandpa;http://www.google.com;Lorem;[parent.smith.Grandpa]
parent.smith.Daddy;http://www.gmail.com;Ipsum;[parent.smith.Grandpa]
parent.smith.Mummy;http://www.yahoo.com;Dolor;[parent.smith.Mummy]
child.smithKid.Peter;http://www.microsoft.com;Sit;[parent.smith.Daddy, parent.smith.Mummy]
child.smithKid.Simon;http://www.google.fr;Amet;[parent.smith.Daddy, parent.smith.Mummy]
parent.martin.Uncle;https://github.com/mbostock/d3/wiki/CSV;Consectetur;[parent.martin.Uncle]
parent.martin.Aunt;http://bl.ocks.org/mbostock/7607999;Adipiscing;[parent.martin.Aunt]
child.martinKid.Mathis;http://stackoverflow.com/;Elit;[parent.martin.Uncle, parent.martin.Aunt]
child.martinKid.Adrian;htpp://www.microsoft.com;Lorem;[parent.martin.Uncle, parent.martin.Aunt]
child.martinKid.Chloé;http://www.d3js.org;Ipsum;[parent.martin.Uncle, parent.martin.Aunt]


text:
Q: How to get rounded Corner button image in QML after tiling I have Button image with Rounded Button image. I am tiling image to get bigger button in QML . I am using parent as rectangle and image as BorderImage. After tiling I am getting rectangle on top image is visible. I need to remove the part of the rectangle so that only rounded button image (Has transparency) is Visible. Even i need to change the color of the behind rectangle so that Color animation is possible.
Please suggest efficient method to remove the behind rectangle and provide the color animation also.
I am attaching the Rounded button border image as attachment and source code for tiling the button image.
Rectangle{
id:outerBorderRect
smooth:true
anchors.fill:parent
//opacity:.25
//border.width:0
BorderImage{

id:innerBorderRect
smooth:true
anchors.fill:parent
border{left:20;top:16;right:17;bottom:20}
horizontalTileMode:BorderImage.Round
verticalTileMode:BorderImage.Round

source:"button_3.png"

}
}

A: A simple and semi-hack way to do this is to use the radius property in Rectangle to hide the corners of your button.
Or you could use a proper mask by using Qt's OpacityMask.
I'm not sure what kind of animation you're looking for. You'll have to provide more details for me to answer that part.


text:
Q: Unable to run the app on hosted server I have just installed Ci framework and tried on my local some basics according to the tutorial.
http://ellislab.com/codeigniter/user-guide/tutorial/static_pages.html
On local machine, everything was OK and page was displayed.
Than I upload project to the server (I am using wedos web hosting where I already have som web which is working correctly) but this is not working for the application which I copied it here. When I type the URL I got 404 error.
On my webhosting service I have www folder where i put my index.html file. Than when i type www.mydomain.eu I get this index.html file. Than I have subfolder www/folder/index.html Than when i type www.mydomain.eu/folder i get this page so it is ok.
Than i have www/folder2/here i unzip CodeIgniter framework and when i type www.mydomain.eu/folder2, 404 Page Not Found appears. The error is not general error from browser but generated from the CI framework.
I have created my own controler in application/controllers/mycontroller.php
<?php

class Mycontroller extends CI_Controller {

public function view($page = 'enter_form')
{

  $data['title'] = ucfirst($page); // Capitalize the first letter

  $this->load->view('templates/header', $data);
  $this->load->view('pages/'.$page, $data);
  $this->load->view('templates/footer', $data);
}
}

And I have following structure of views:
views/pages/enter_form.php
views/templates/header.php and footer.php
And the following settings:
1)  $config['base_url'] = ''; but I have tried 'http://mydomain.eu/' and 'http://mydomain.eu/www/' or 'http://mydomain.eu/www/folder2/'
2)  $route['default_controller'] = 'mycontroller/view';
$route['(:any)'] = 'mycontroller/view/$1';
Thank you for any help

A: Sounds to me like there is either a configuration issue or a rewrite issue going on. Do you have a .htaccess file in your CI root folder where your index.php file lives? Seeing that you are depending on the CI to pick up any uri and reroute it to a specific route, this might be the issue. I've ran into issues with this before on different hosts. Make sure mod rewrite is enabled and make sure your .htaccess is something similar to this:
RewriteEngine on
RewriteBase /
RewriteCond $1 !^(index\.php|assets|uploads)
RewriteRule ^(.*)$ /index.php/$1 [L]

A: Ok, so it seems like the typo somewhere, because when I used the default CI welcome pages, it works. So I will try to find the typo myself and i will see...


text:
Q: Check values in file is greater or equal in bash script I have file.txt include:
2
10
60
90
now how can i check if numbers in that file is equal on greater than 50 end then do something. Something in my case is sending an email this part i have.
I have tried do this with awk but it does not work in script.

A: The following command will output the greatest value of your file:
sort -nr file.txt | head -1

Then just compare it to the value of your choice and voilà. Something like:
if [ `sort -nr file.txt | head -1` -ge 50 ]
then
  <do something>
fi

Explanation:
sort -n sorts the file as numbers (otherwise 12 would be considered greater than 100).
sort -r reverse the sort (by default it displays lower numbers first, with -r it displays higher first).
head -1 displays only the first output.

A: This will serve your job.
$ awk 'FNR > 0 { if($1 > 50) print $1 }' <file>


text:
Q: .htaccess not working on Ubuntu Server x64 I developed an application on XAMPP (Windows 8). Now i moved it to a VM with Ubuntu Server x64 and the rewriting is not working anymore.
I want always call index.php in the root folder (/var/www/html) except if the file (http://10.0.0.XX/any_path/filename) exist in the folder /var/www/html/app/web/ (like /var/www/html/app/web/any_path/filename).
This is my .htaccess:
<IfModule mod_rewrite.c>
RewriteEngine on

RewriteRule ^[A-z/]*$ index.php [L]

RewriteCond %{DOCUMENT_ROOT}/app/web/%{REQUEST_URI} -f
RewriteRule ^(.+)$ app/web/$1 [L]
</IfModule>

On Xampp on windows it worked fine, but on Ubuntu server it doesn't seem to work anymore. phpinfo() says that the model mod_rewrite is loaded.
Thanks for your help!
Edit:
The AccessLog and ErrorLog of apache doesn't say anything useful.

A: AllowOverride was set to none in apache2.conf. Thanks to @MarcB for the hint!


text:
Q: Mongoid: How to have distinct fields in User & Message n to m relation I have got two models like following:
class User
include Mongoid::Document

   has_many_and_belongs_to :messages

end
class Message
  include Mongoid::Document

  has_many_and_belongs_to :users

  field :text
  field :visited, type: Boolean, default: false
end

As far as i know when this template implements message fields are common among users. What i want to have here is visited field be distinct for every user to work with. Any idea how would that applicable? I have an alternative such as a middle model to save user & message id with desire field but that seems messy.

A: You need to build the has_and_belongs_to_many relation yourself. This way you can customize the class used to link a User and a Message:
class User
  include Mongoid::Document

  has_many :user_messages
end

class Message
  include Mongoid::Document

  has_many :user_messages
end

class UserMessage
  include Mongoid::Document

  belongs_to :user
  belongs_to :message

  field :visited, type: Boolean, default: false

  scope :visited,   -> { where(visited: true) }
  scope :unvisited, -> { where(visited: false) }
end

Then you can do:
u = User.new
m = Message.new

u.user_messages.build(message: m, visited: true)
u.user_messages.build(message: m, visited: false)
u.user_messages.count
=> 2
u.user_messages.visited.count
=> 1
u.user_messages.unvisited.count
=> 1

More information about this kind of association from Rails Guide here.
Note that the UserMessage class name is quite annoying. You could instead use a different naming such as Conversation:
class User
  has_many :messages
end

class Conversation
  has_many :messages
end

class Message
  belongs_to :user
  belongs_to :conversation

  field :visited, type: Boolean, default: false
end

Which is used nicely:
u = User.new
c = Conversation.new
u.messages.build(conversation: c)


text:
Q: Let (X, d) be a metric space and let A be a subset of X. Prove that A is closed if and only if Fr(A) $\subseteq$ A. The direction from closedness to Fr(A) being contained in A is quite easy.
But I don't see how I can do the if direction.

A: Suppose that $Fr(A) \subseteq A$ and let $(a_n)$ be a convergent sequence in $A$ with limit $a$. We have to show that $a \in A$.
Case 1: $a \in A$. Then we are done.
Case 2: $a \notin A$. Then $a \in Fr(A)$. Hence $a \in A$.

A: If $Fr(A)\subset A.$ Let $x \in X-A$.
If $x\in cl(A)$. So $x\in cl(A)-A\subset Fr(A)$. It's a contradiction.
So $x\notin cl(A).$ Then, $x \in cl(A) \Rightarrow x\in A$. Hence $A$ is closed.


text:
Q: unable to call external api in node js I am trying to call an external API from my Node platform, but I am not getting expected result.
I have tried with npm request module and to convert my postfield data query string. I tried to set JSON: true, but I am not getting the result.
var request = require('request');
var querystring = require('querystring');

// api_call function
api_call_with_data = function(url, form_data) {
  return new Promise((resolve, reject) => {

    request.post({
              uri: url,
              headers: {
                "content-type": "application/json"
              },
              body: form_data,
              method: 'POST',
              json: true
            }, (err, res, final_res) => {
              if (err) reject(err)
              resolve(final_res)
            });
        })
    };

app.get('/call_api', (req, res) => {

    var api_url = "http://www.example.com/api/test";

    var api_form = {
        "first_name": "Stack",
        "last_name": "Overflow",
        "email_id": "test@example.com"
    };

    var formData = querystring.stringify(api_form);

    api_call_with_data(api_url, formData)
    .then(response => {

        res.send(response);

    })
    .catch(error => {
        res.send(error)
    })

});

I am getting the error:
{"library":"digital envelope routines","function":"EVP_DecryptFinal_ex","reason":"wrong final block length","code":"ERR_OSSL_EVP_WRONG_FINAL_BLOCK_LENGTH"}

Expected result:
{'status' : 'success', "api_response" : "Thank you to call API"}


text:
Q: Is $*:U(R)\times R^+\longrightarrow R^+,\ (g,a)\mapsto g*a:=g\cdot a$ surjective? Let $R=(R,+,\cdot)$ be a ring with $1_R$. We will write $U(R)=(U(R),\cdot)$ the multiplicative group of units of this ring and $R^+=(R,+)$ the additive group of this ring. The group $U(R)$ acts in the group $R^+$, if we define a group action
$$*:U(R)\times R^+\longrightarrow R^+,\ (g,a)\mapsto g*a:=g\cdot a.$$
Then, we know that the function
$$\phi: U(R)\longrightarrow \mathrm{Aut}(R^+),\ g\mapsto \phi(g):=\phi_g $$
is a group homomorphism. We can show that $\ker {\phi}=\{1_G\}$, so $\phi$ is injective and we have monomorphism.
My question: Is $\phi $ surjective?
Lets take an element $\psi \in \mathrm{Aut}(R^+)$. We want to find an element $g\in U(R)$ such that $\phi(g)=\psi$. Then $\phi _g=\psi \iff \phi_g(r)=\psi(r),\ \forall r\in R^+ \iff g\cdot r=\psi (r), \forall r\in R^+$.
But how can we solve the last equation, to find $g$? Any ideas please?
Thank you.


text:
Q: pivotting in pandas index and column has same column i have data frame
data=pd.DataFrame({'year':[2010,2010,2010,2011,2011,2011],
'position':[1,2,3,1,2,3],
'name':['a','a','b','c','c','d'],
'points':[34,36,32,14,15,16],
'team':['A','B','C','C','B','A'],
'venue':['ny','ny','ny','cali','cali','cali']})

my code:
data.pivot(index=['position','name'],columns='year',values='points')

It works but for the actual dataset I have to put the year as index otherwise it says duplicate index can we solve I need year in the index and also columns

A: You can use pivot_table() which supports duplicates:
data.pivot_table(index=['position', 'name'], columns='year', values='points')

By default, it will average the duplicates. If you prefer a different aggregation, you can specify aggfunc, e.g. to take the max:
data.pivot_table(index=['position', 'name'], columns='year', values='points',
                 aggfunc='max')


text:
Q: OctoberCMS - How to retrieve data from database into backend chart I'm creating a chart for my booking data but based on the sample code here I declare the value and label myself. So what I'm trying to do is creating a chart based on my database but I'm not sure how to retrieve the label and value from my own database? Is there any example? Or anyone can help me?
<?php

    // our data
    $chartData = [
        ['label' => '1st Month', 'value' => 10],
        ['label' => '2nd Month', 'value' => 6],
        ['label' => '3rd Month', 'value' => 3],
        ['label' => '4th Month', 'value' => 20],
        ['label' => '6th Month', 'value' => 20],
        ['label' => 'nth Month', 'value' => 15],
    ];

    // preparing data for chart
    $values = $labels = [];
    foreach ($chartData as $key => $data) {
        $values[] = [$key, $data['value']];
        $labels[] = [$key, $data['label']];
    }

    $labelDataInJson = json_encode($labels);
    // removing first and last [, ] so it can be valid data for chart
    $chartDataInJson = strtr(json_encode($values), ['[[' => '[', ']]' => ']']);

?>

Booking Report

    <div
        data-control="chart-line"
        data-time-mode="weeks"
        style="height: 200px;width: 100%;"
        data-chart-options='xaxis: {mode: "none", ticks: <?= $labelDataInJson ?>}'
    >
        <span
            data-chart="dataset"
            data-set-color="#008dc9"
            data-set-name="Visits"
            data-set-data='<?= $chartDataInJson ?>'

A: You need to arrange your data correctly, just follow below code to arrange your data.

Here I used User's modal in your code you can replace it with Booking table. and achieve same result.

// we will show last 7 (6 day + 1 current day) day's stats
$sixDayAgo = \Carbon\Carbon::now()->subDay(6);
$users = RainLab\User\Models\User::whereDate('created_at', '>=',
                                      $sixDayAgo->toDateString())->get();

$period = \Carbon\CarbonPeriod::create($sixDayAgo, \Carbon\Carbon::now());

$chartData = [];
foreach ($period as $date) {
    $val = ['label' => $date->format('Y-m-d'), 'value' => 0];
    foreach ($users as $user) {
      if($date->format('Y-m-d') == $user->created_at->format('Y-m-d')) {
        $val['value']++;
      }
    }
    $chartData[] = $val;
}
// dd($chartData);

once you get your $chartData then you can show chart

follow https://tutorialmeta.com/october-cms/how-to-use-charts-in-octobercms this tutorial to show $chartData as chart.
Result

if any doubts please comment.


text:
Q: XSLT - how to test value I have the following xml:
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <soap:Body>
  <QueryResponse xmlns="http://tempuri.org/QueryAuthRequests/Service1">
     <RespMessage xmlns="http://altsq/XMLSchema/epayments/standard">
        <PaymentList>
           <OriginatorsReference>0000000784</OriginatorsReference>
           <RecReference>0000000784</RecReference>
           <LineNumber>1</LineNumber>
           <RequestDate>2022-11-16T11:40:39</RequestDate>
           <RequestMessage>Masked</RequestMessage>
           <ResponseMessage>No details available</ResponseMessage>
           <RequestStatus>A</RequestStatus>
        </PaymentList>
       </RespMessage>
  </QueryResponse>
 </soap:Body>
</soap:Envelope>

I want to test the value of request status but it doesn't seem to like the syntax. Whats the correct syntax to test the value
<form:field>
    <form:name>request_status</form:name>
    <xsl:when test="//.[local-name()='RequestStatus']/text() = 'A'">
            <form:value>Accepted</form:value>
    </xsl:when>
    <xsl:otherwise>
            <form:value>Refused</form:value>
    </xsl:otherwise>
</form:field>

A: Try this as your starting point:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
xmlns:svc="http://tempuri.org/QueryAuthRequests/Service1"
xmlns:std="http://altsq/XMLSchema/epayments/standard"
exclude-result-prefixes="soap svc std">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/soap:Envelope">
    <output>
        <xsl:choose>
            <xsl:when test="soap:Body/svc:QueryResponse/std:RespMessage/std:PaymentList/std:RequestStatus='A'">Accepted</xsl:when>
            <xsl:otherwise>Refused</xsl:otherwise>
        </xsl:choose>
    </output>
</xsl:template>

</xsl:stylesheet>

Applied to your input example, this will return:
Result
<?xml version="1.0" encoding="UTF-8"?>
<output>Accepted</output>


text:
Q: How to work with javascript functions in an anonymous function in the browser console? I've found an interesting method of defining functions:
! function() {
  function myFunction() {
    return returnValue;
  }
}();

However, this function can not be called directly from the browser console, how could I achieve it?

A: That is an IIFE (immediately invoked function expression) wrapped around your function.
I would suggest using this approach for the code that you've written:
!function() {
  function myFunction() {
    return 'hello';
  }

  window['myFunction'] = myFunction;
}();

Now call myFunction in the console.
Previously myFunction was hidden inside your IIFE and was not exposed as a global.


text:
Q: How to know the exit code of a process run in the background I'm writing a script that runs a process in the background while shows a progress bar until the mentioned process ends. my question is, how can I check the exit code of that process??
thanks in advance

A: The wait builtin will return the exit code of the waited process if you specify a PID or job spec. (Note that it returns zero if you don't specify either of those.)
Here's how you could use it:
#! /bin/bash

(exit 10)&
pid=$!
wait $pid
echo $?

This will print 10.

A: You can use the $? variable:
command & #run command in background
pid=$!    #get pid
wait $!   #wait for the sucker to finish
status=$? #exitcode for pid


text:
Q: How to get probability of prediction per entity from Spacy NER model? I used this official example code to train a NER model from scratch using my own training samples.
When I predict using this model on new text, I want to get the probability of prediction of each entity.

    # test the saved model
    print("Loading from", output_dir)
    nlp2 = spacy.load(output_dir)
    for text, _ in TRAIN_DATA:
        doc = nlp2(text)
        print("Entities", [(ent.text, ent.label_) for ent in doc.ents])
        print("Tokens", [(t.text, t.ent_type_, t.ent_iob) for t in doc])

I am unable to find a method in Spacy to get the probability of prediction of each entity.
How do I get this probability from Spacy? I need it to apply a cutoff on it.

A: Getting the probabilities of prediction per entity from a Spacy NER model is not trivial.
Here is the solution adapted from here :

import spacy
from collections import defaultdict

texts = ['John works at Microsoft.']

# Number of alternate analyses to consider. More is slower, and not necessarily better -- you need to experiment on your problem.
beam_width = 16
# This clips solutions at each step. We multiply the score of the top-ranked action by this value, and use the result as a threshold. This prevents the parser from exploring options that look very unlikely, saving a bit of efficiency. Accuracy may also improve, because we've trained on greedy objective.
beam_density = 0.0001
nlp = spacy.load('en_core_web_md')

docs = list(nlp.pipe(texts, disable=['ner']))
beams = nlp.entity.beam_parse(docs, beam_width=beam_width, beam_density=beam_density)

for doc, beam in zip(docs, beams):
    entity_scores = defaultdict(float)
    for score, ents in nlp.entity.moves.get_beam_parses(beam):
        for start, end, label in ents:
            entity_scores[(start, end, label)] += score

l= []
for k, v in entity_scores.items():
    l.append({'start': k[0], 'end': k[1], 'label': k[2], 'prob' : v} )

for a in sorted(l, key= lambda x: x['start']):
    print(a)

### Output: ####

{'start': 0, 'end': 1, 'label': 'PERSON', 'prob': 0.4054479906820232}
{'start': 0, 'end': 1, 'label': 'ORG', 'prob': 0.01002015005487447}
{'start': 0, 'end': 1, 'label': 'PRODUCT', 'prob': 0.0008592912552754791}
{'start': 0, 'end': 1, 'label': 'WORK_OF_ART', 'prob': 0.0007666755792166002}
{'start': 0, 'end': 1, 'label': 'NORP', 'prob': 0.00034931990870877333}
{'start': 0, 'end': 1, 'label': 'TIME', 'prob': 0.0002786051849320804}
{'start': 3, 'end': 4, 'label': 'ORG', 'prob': 0.9990115861687987}
{'start': 3, 'end': 4, 'label': 'PRODUCT', 'prob': 0.0003378157477046507}
{'start': 3, 'end': 4, 'label': 'FAC', 'prob': 8.249734411749544e-05}

A: Sorry I do not have any better answer - I can only confirm that the 'beam' solution does provide some 'probabilities' - though in my case I am getting way too many entities with prob=1.0, even in cases where I can only shake  my head and blame it on too little training data.
I find it quite strange that Spacy reports an 'entity' without having any confidence attached to it. I would assume there is some threshold to decide WHEN Spacy reports an entity and when it does NOT (perhaps I missed it). In my case, I see confidences 0.6 reported as 'this is an entity' while entity with confidence 0.001 is NOT reported.
In my use-case, the confidence is essential. For a given text, Spacy (and for example Google ML) report multiple instances of 'MY_ENTITY'. My code has to decide which ones are to be 'trusted' and which ones are false positive. I have yet to see IF the 'probability' returned  by the above code has any practical value.


text:
Q: Google Chrome throttling with Selenium There was a similar question to this a year ago (Network throttling with chrome and selenium), but it looks like the answers to that question are no longer valid as a bug and fix have come out in the last couple months. https://bugs.chromium.org/p/chromedriver/issues/detail?id=984
I am trying to implement network throttling in google chrome using selenium implemented with Java with little to no success. I'm using the latest chrome driver and standalone server 3.0.1.
Any and all help is greatly appreciated!!

A: You can use proxyServer instead of chrome network throttling.
ProxyServer proxy = new ProxyServer(4444);
proxy.setReadBandwidthLimit(125000); // 125 000 (1Mbps)
proxy.setWriteBandwidthLimit(125000);

A: See my answer in the linked question. Unfortunately Java bindings are not available at the moment, but there is an issue asking to add them, which you can upvote.
Also contributing an implementation should be pretty straight-forward judging from existing bindings for JavaScript and Python.


text:
Q: RestTemplate.exchange() - Illegal character(s) in message header value I'm getting an java.lang.IllegalArgumentException: Illegal character(s) in message header value error when executing the restTemplate.exchange() method.
I guess the problem is a huge HTTP header, which internally will be base64 encoded:

It seems the SDK is using the old "sun.misc.BASE64Encoder" which will breaking a new line "\n" if the encoded string is too long (>76 characters).

Source
My code snippet which produces the error:
HttpHeaders headers = new HttpHeaders();
headers.set("jwt", jwt); // JSON Web Token with length of over 900 characters
HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
ResponseEntity<String> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);

But how can I change the used base64-encoder which is used by the RestTemplate?
The stack trace:
java.lang.IllegalArgumentException: Illegal character(s) in message header value: eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJJc3N1ZXIiLCJhdWQiOi...

at sun.net.www.protocol.http.HttpURLConnection.checkMessageHeader(Unknown Source) ~[na:1.8.0_91]
at sun.net.www.protocol.http.HttpURLConnection.isExternalMessageHeaderAllowed(Unknown Source) ~[na:1.8.0_91]
at sun.net.www.protocol.http.HttpURLConnection.addRequestProperty(Unknown Source) ~[na:1.8.0_91]
at sun.net.www.protocol.https.HttpsURLConnectionImpl.addRequestProperty(Unknown Source) ~[na:1.8.0_91]
at org.springframework.http.client.SimpleBufferingClientHttpRequest.addHeaders(SimpleBufferingClientHttpRequest.java:104) ~[spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.http.client.SimpleBufferingClientHttpRequest.executeInternal(SimpleBufferingClientHttpRequest.java:70) ~[spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48) ~[spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53) ~[spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:596) ~[spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:557) ~[spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:475) ~[spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE]

EDIT:
And while adding the stack trace to my question I found the error: The newline wasn't added by the base64 encoding but by the service that gave me the jwt String...
I guess I could delete my question but maybe somewhen someone will stumble upon the same mistake, so: Check your header values!

A: You can do it like this
 headers.setAcceptCharset(Arrays.asList(Charset.forName("UTF-8")))

or even better would be
restTemplate.getMessageConverters()
        .add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));

Considering you want to change your charset to UTF-8


text:
Q: How to design a class of background task for swing application I can load data from query result in JTable nicely.
SELECT * FROM 'customer info';

Make a result set and place to JTable is easy to handle.
But problem is, as my database table is so big and it takes so much time to load. My application totally freeze until current task complete. I know swing worker can perform a background task. I study this, but i find no any appropriate solution in my case. Because i already write a lot of function in basic way.
So finally what i need?
I need a Class, design with swing worker by which i can easily use it's object anywhere in my application. suppose i send my query string and JTable in this class constructor. Then it automatically starts a background thread to make result set and place it in JTable.

A: ok now its work in my case :) here is my own solution ....
public class UsableSwingWorkerThread extends SwingWorker<ResultSet, Object> {

JTable table;
String query;

public UsableSwingWorkerThread(JTable table, String query) {
    this.table = table;

    this.query = query;

}

@Override
protected ResultSet doInBackground() throws Exception {

    return DatabaseFunctionClass.con.prepareStatement(query).executeQuery();
}

void loadTable(TableModel tb) {
    new UsableDefaultLoadTable(tb, table);
}

@Override
protected void done() {
    try {
        loadTable(DbUtils.resultSetToTableModel(get()));
    } catch (Exception ignore) {
        StaticAccess.showMassageDialog(StaticAccess.mainFrame, "Fail to load. try again later..", ignore);
    }
}

}


text:
Q: Two definitions for non-singular in codimension 1 I am trying to understand how the following definitions are the same.
Shafarevich definition (pg 128) -
A variety is non-singular in codimension one if the singular locus has codimension $> 1$.
Hartshorne definition (pg 130) -
A scheme is non-singular in codimension one if every local ring $\mathcal{O}_x$ of dimension one is regular.
My question is how to prove Hartshorne $\implies$ Shafarevich.
I guess that if $X$ is an affine variety and $Sing(X)$ has an irreducible component $Y$ of codimension one, then the local ring $\mathcal{O}_{\mathfrak{p}}$ of the corresponding prime $\mathfrak{p}$ should be non-regular. Is this true? If so where can I find the proof?


text:
Q: tests.php issue - sipp webfrontend I'm trying to install a PHP based application called sipp webfrontend on a centos 6.5 server.
I think I have met all of the following requirements:

*

*LAMP Environement (Linux, Apache, Mysql, PHP)

*At least 0.5MB free disk space

*A valid MYSQL user with privileges to create a database and tables

*Write access in or beneath apache's www subfolder, or at least one of its subfolders (directly or via FTP, SSH ...)

*At least one version of SIPp installed

But when I point my browser at the URL I get the following:
. * * * * END LICENCE * * * * */ header("location: tests.php"); ?>
I see nothing in the httpd.log file.
Does anyone know what maybe going wrong here?
The code
    ?
/*
 * SIPp Webfrontend - Web tool to create, manage and run SIPp test cases
 * Copyright (c) 2008 Mario Smeritschnig
 * Idea, support, planning, guidance Michael Hirschbichler
 *
 * * * BEGIN LICENCE * * *
 *
 * This file is part of SIPp Webfrontend.
 *
 * SIPp Webfrontend is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * SIPp Webfrontend is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with SIPp Webfrontend.  If not, see <http://www.gnu.org/licenses/>.
 *
 * * * END LICENCE * * *
 *
 */

// Here the user gets an overview of existing tests and can sort or remove them.

session_start();
require_once "authentication.php";
require_once "db.php";
require_once "dbHelper.php";
require_once "helper.php";

$action = $_GET["action"];
$id = $_GET["id"];

// manage ascending and descending sortable colums
if($_GET["sort"] != "") {
    if($_SESSION["s_sort"] != $_GET["sort"]) $order = "ASC";
    else {
        $order = $_SESSION["s_order"];
        if($order == "ASC") $order = "DESC";
        else $order = "ASC";
    }
    $_SESSION["s_order"] = $order;
    $_SESSION["s_sort"] = $_GET["sort"];
}

// define default sort parameters
if($_SESSION["s_sort"] == "") $_SESSION["s_sort"] = "name";
if($_SESSION["s_order"] == "") $_SESSION["s_order"] = "ASC";
$order = $_SESSION["s_order"];
$sort = $_SESSION["s_sort"];

if($admin && $action == "del" && id != "") {
    $tObj = new Test($id);
    $tObj->remove();
}

$tObj = new Test();
$res = $tObj->getOverview($sort." ".$order);
?>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="css/styles.css" rel="stylesheet" type="text/css">
<link href="css/bg.css" rel="stylesheet" type="text/css">

<? require_once "navigation/pagehead.php"; ?>

    Tests overview

    <? if($admin) { ?>» create new test <? } ?>

        name<? if($sort=="name") { ?> <img src="<? if($order == "ASC") echo "pix/ascending.gif"; else echo "pix/descending.gif"; ?>" width="9" height="7" border="0" alt="view"><? } ?>
        description<? if($sort=="description") { ?> <img src="<? if($order == "ASC") echo "pix/ascending.gif"; else echo "pix/descending.gif"; ?>" width="9" height="7" border="0" alt="view"><? } ?>
        created<? if($sort=="created") { ?> <img src="<? if($order == "ASC") echo "pix/ascending.gif"; else echo "pix/descending.gif"; ?>" width="9" height="7" border="0" alt="view"><? } ?>
        last modified<? if($sort=="last_modified") { ?> <img src="<? if($order == "ASC") echo "pix/ascending.gif"; else echo "pix/descending.gif"; ?>" border="0" width="9" height="7" alt="view"><? } ?>
        runs<? if($sort=="run_count") { ?> <img src="<? if($order == "ASC") echo "pix/ascending.gif"; else echo "pix/descending.gif"; ?>" border="0" width="9" height="7" alt="view"><? } ?>
        <? if($admin) { ?>

        <? } ?>

    <?
    $even = true;
    while($row = mysql_fetch_object($res)) {
    if($even) $bgcol = "#EEEEEE";
    else $bgcol = "#DDDDDD";
    ?>
    <tr style="background-color:<? echo $bgcol; ?>;" onMouseOver="this.style.background='#B9FAFD'" onMouseOut="this.style.background='<? echo $bgcol; ?>'">
        <td onClick="location.href='test_detail.php?version=-1&id=<? echo $row->id; ?>'"><? echo $row->name; ?>
        <td onClick="location.href='test_detail.php?version=-1&id=<? echo $row->id; ?>'"><? echo shorten($row->description, 40); ?>
        <td align="center" onClick="location.href='test_detail.php?version=-1&id=<? echo $row->id; ?>'"><? echo $row->created; ?>
        <td align="center" onClick="location.href='test_detail.php?version=-1&id=<? echo $row->id; ?>'"><? echo $row->last_modified; ?>
        <td align="center" onClick="location.href='test_detail.php?version=-1&id=<? echo $row->id; ?>'"><? echo $row->run_count; ?>
        <? if($admin) { ?>
        <a href="javascript: delTest(<? echo $row->id; ?>, '<? echo $row->name; ?>')">
        <? } ?>

    <?
    $even = !$even;
    }
    ?>

A: Modify php.ini with the change: short_open_tag = On


text:
Q: Increase the number of maximum redis arguments in an entry without changing source code and recompiling it for Freeradius Redis module Me and my team are trying to implement Freeradius to our authentication mechanism with a Redis database utilizing the Redis streams data type.
However i came across with the limitation of maximum Redis arguments of 16 in a single Redis streams entry -128 would be enough for our use case-.
After searching around i found the limitation to reside in the files of the Redis module for Freeradius:
#define MAX_REDIS_ARGS                  16

The above mentioned argument can be found both in redis.h (line38) and rlm_redis.c (line 40).
Although changing the said value and compiling Freeradius from source code would solve the issue does anyone know an easier/ less error prone method to achieve this. Like somehow overwriting this value from a configuration file when using a prepackaged version.
Thank you for any advice or opinion.

A: The Redis argument limit is hardcoded in the source, but from v3.2.1 it will be raised from 16 to 256. See https://github.com/FreeRADIUS/freeradius-server/pull/4535.


text:
Q: Database Programming Data Validation I tried using the symbol || which represents or. However, when I tried it in my program it still shows me the error message where I would actually put it in a message box and display it to the user to let them know that they type it wrong, however, even if I type it right it still shows me that message. Below is my code. Hope there will be someone that cold help me.
private void SaveChanges()

{

//declare variable for store code integer
int storeCode = 0;

//check if first and last name are empty

if (txtName.Text == "")

        {

            MessageBox.Show("Fill in First Name", "Missing Data");
            txtName.Focus();
        }
        else if(txtLastname.Text == "")
        {
            MessageBox.Show("Fill in Last Name", "Missing Data");
            txtLastname.Focus();
        }
        else if(txtJobCode.Text == "" || txtJobCode.Text != "SEC" || txtJobCode.Text != "MGR" &&
            txtJobCode.Text != "GEN")
        {
            MessageBox.Show("Fill in Job Code with SEC, MGR or GEN", "Missing Data");
            txtJobCode.Focus();
        }
        else if(int.TryParse(txtStoreCode.Text, out storeCode) || txtStoreCode.Text == "")
        {
            if (storeCode <= 1 && storeCode >= 5)
            {
                MessageBox.Show("Fill in Store Code 1-5", "Missing Data");
                txtStoreCode.Focus();
            }

            MessageBox.Show("Fill in Store Code", "Missing Data");
            txtStoreCode.Focus();
        }
        else
        {
            this.eMPLOYEEBindingSource.EndEdit();
            this.tableAdapterManager.UpdateAll(this.empDataSet);
        }
    }//end SaveChanges

A: I'm assuming you're getting the error message at the line
else if(txtJobCode.Text == "" || txtJobCode.Text != "SEC" || txtJobCode.Text != "MGR" &&
            txtJobCode.Text != "GEN")
        {
            MessageBox.Show("Fill in Job Code with SEC, MGR or GEN", "Missing Data");
            txtJobCode.Focus();
        }

The reason is this will never evaluate to 'false' and skip the statement, plus you have an && for GEN.  As soon as you successfully meet any of the first || statements you're going to fail the &&.  It can't be one of those and GEN.  Let's say you put GEN in.
== "" (false) != "SEC" (true) boom! (short circuited to error message)
Let's say you put SEC
== "" (false) != "SEC" (false) != "MGR" (true) boom! (short circuited to error message)
With or operators || the code will continue to check UNTIL it finds a true value.  When it does it returns true from that point and doesn't look further. Therefore it reads if(true).. so it performs the if statement.
With and operators && the will continue to check UNTIL it finds a false.  When it does it returns false and doesn't look any further.  Therefore it read if(false)... and DOES NOT perform the if statement.
Now of course if no || statements are true it will return false and if no && values are false it will return true.
You need to write this I believe:
IF jobCode == "" OR (jobCode != SEC AND jobCode != MGR AND jobCode != GEN) then ShowMessage()
Now type SEC
== "" (false) || ( != SEC (false) ) - result false... Good! No message.
Now type GEN
== "" (false) || ( != SEC (true) && != MGR (true) && != GEN (false) ) - result false...  Good! No message.
Now type ""
== "" (true) ... Good! We get a message.
Now try HELLO
== "" (false) || ( != SEC (true) && != MGR (true) && != GEN (true) )... Good! We get a message.
I would also like to add that nesting if statements and multiple and / or operators, although sometimes it can't be completely avoided, isn't the cleanest way because even looking at it myself it took me a moment to sort through it.  I would re-write that logic to make better use if possible, even put the different tests in their own method if needed and test the method itself for success.  Anything to make it easier to read and debug.
Looking to simplify it, with that line of code, since you have the three constants, just check to see if it DOES equal any of them.
You also have the range check backwards which will never be true.  It can't be <= 1 and >= 5.
Here's the cleanup that should work; the way I would do it.  (not tested, just scratched up on the spot.)  Even if you prefer not to use it maybe you can read it easier and see the mistakes.  Being easier to read makes it easier to debug and manage so hopefully I'm helping in more than one way with this.
    public void SaveChanges()
    {
        var isValid = validateFirstName()
                   && validateLastName()
                   && validateJobCode()
                   && validateStoreCode();

        if (isValid)
        {
            this.eMPLOYEEBindingSource.EndEdit();
            this.tableAdapterManager.UpdateAll(this.empDataSet);
        }
    }

    private bool validateFirstName()
    {
        var isValidFirstName = !string.IsNullOrEmpty(txtName.Text);

        if (!isValidFirstName)
        {
            MessageBox.Show("Fill in First Name", "Missing Data");
            txtName.Focus();
        }

        return isValidFirstName;
    }

    private bool validateLastName()
    {
        var isValidLastName = !string.IsNullOrEmpty(txtLastname.Text);

        if (!isValidLastName)
        {
            MessageBox.Show("Fill in Last Name", "Missing Data");
            txtLastname.Focus();
        }

        return isValidLastName;
    }

    private bool validateJobCode()
    {
        var isValidJobeCode = txtJobCode.Text == "SEC"
                           || txtJobCode.Text == "MGR"
                           || txtJobCode.Text == "GEN";

        if (!isValidJobeCode)
        {
            MessageBox.Show("Fill in Job Code with SEC, MGR or GEN", "Missing Data");
            txtJobCode.Focus();
        }

        return isValidJobeCode;
    }

    private bool validateStoreCode()
    {
        var storeCode = 0;
        var isValidStoreCode = int.TryParse(txtStoreCode.Text, out storeCode)
                               && storeCode >= 1
                               && storeCode <= 5;

        if (!isValidStoreCode)
        {
            MessageBox.Show("Fill in Store Code 1-5", "Missing Data");
            txtStoreCode.Focus();
        }

        return isValidStoreCode;
    }
}


text:
Q: How can I get the name of the sourced script in tcsh? I'm looking for a way to get the name of a script that's being sourced from another script that's being executed in tcsh.
If I needed to the the name of a script being executed (not sourced), it's $0. If I need to get the name of a script that's being sourced from the command line, I can get it from $_. But when an executed script sources a script, I get an empty value for $_ in the sourced script, so I can't get the script name or pathname from that.
I'm looking for a non-manual method for getting that information.

A: There isn't really anything for this; source is mostly just a way to read the file and run it in the current scope.
However, it does accept arguments; from the tcsh manpage:
   source [-h] name [args ...]
           The shell reads and executes commands from name.  The commands
           are not placed on the history list.  If any args are given,
           they are placed in argv.  (+) source commands may be nested; if
           they are nested too deeply the shell may run out of file
           descriptors.  An error in a source at any level terminates all
           nested source commands.  With -h, commands are placed on the
           history list instead of being executed, much like `history -L'.

So for example source file.csh file.csh will have argv[1] set to file.csh.
Another option is to simple set a variable before the source command:
set src = "file.csh"  # Will be available in file.csh
source file.csh

If you can't or don't want to modify the source call then you're out of luck as far as I know. (t)csh is an old crusty shell with many awkward things, large and small, and I would generally discourage using it for scripting unless you really don't have any option available.
$_ simply gets the last commandline from history; maybe, very maybe it's possible to come up with a super-hacky solution to (ab)use the history for this in some way, but it seems to me that just typing the filename twice is a lot easier.


text:
Q: Edit Text and CheckBox checking I currently have 2 checkboxes with an edit text field beside them.  There are 4 checkboxes total and I have the logic to check each one and uncheck others if they are checked (almost radio button style).  These 2 however could both be checked if they have values in the edit text fields.
However, if the EditText field (which is set to numeric) has a value of 0 or is blank I want it to uncheck the check box and set the value to 0.
Here is the code I have to do this
    if (etBase.getText().toString() == "0" || etBase.getText().toString() == ""){
        etBase.setText("0");
        cbBase.setChecked(false);
    } else {
        cbBase.setChecked(true);
    }
    if (etField.getText().toString() == "" || etField.getText().toString() == "0"){
        etField.setText("0");
        cbField.setChecked(false);
    } else {
        cbField.setChecked(true);
    }

As it sits right now I default the two fields to be "0" when it starts.  When this logic runs, it is setting both checkboxes to checked.
I must be missing something here.

A: To compare string, you must use .equals() function. ( Or .compareTo() but that's no the today's deal)
Ex :
if (etBase.getText().equals("0") || etBase.getText().equals("")){
  ...
}

var1 == var2 is used to get if these both variable have the same object


text:
Q: C# XPath Soap, how to navigate to embedded node In C#, Asp.Net, I am trying to return the Error node inside of BISearchResponse:
I am able to get the GetWireResult node returned in an XMLNode.
How do I get to the Error node?
<?xml version="1.0" encoding="utf-8" ?>
- <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
-     <soap:Body>
-          <GetWireResponse xmlns="http://OpenSolutions.com/">
                <GetWireResult><?xml version="1.0"?>
                      <BISearchResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
                            <Error xmlns="https://bixg.choicepoint.com/webservices/3.0">
                                   <Message>BI System: Failed to Login</Message>
                                   536870917
                             </Error>
                      </BISearchResponse>
                </GetWireResult>
            </GetWireResponse>
       </soap:Body>
  </soap:Envelope>

My code:
XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(result);

            XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
            nsmgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
            nsmgr.AddNamespace("ab", "http://OpenSolutions.com/");
            nsmgr.AddNamespace("bg", " https://bixg.choicepoint.com/webservices/3.0");
            nsmgr.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
            nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");

            XmlNode xmlnode = xmlDoc.DocumentElement.SelectSingleNode("/soap:Envelope/soap:Body/ab:GetWireResponse", nsmgr);

This works to here.
.
I am adding the xml here, but it is only visible in edit mode.
<?xml version="1.0" encoding="utf-8" ?>
- <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
- <soap:Body>
- <GetWireResponse xmlns="http://OpenSolutions.com/">
  <GetWireResult><?xml version="1.0"?> <BISearchResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Error xmlns="https://bixg.choicepoint.com/webservices/3.0"> <Message>BI System: Failed to Login</Message> 536870917 </Error> </BISearchResponse></GetWireResult>
  </GetWireResponse>
  </soap:Body>
  </soap:Envelope>

A: In debug mode, when you copy this XML, try choose another debug visualizer, e.g. "Text visualizer". You can select it clicking the magnifying glass icon in datatip.
I think your XML looks like:
<?xml version="1.0" encoding="utf-8" ?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <GetWireResponse xmlns="http://OpenSolutions.com/">
      <GetWireResult>
        <?xml version="1.0"?>
        <BISearchResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <Error xmlns="https://bixg.choicepoint.com/webservices/3.0">
        <Message>BI System: Failed to Login</Message>
        <Code>536870917</Code>
        </Error>
        </BISearchResponse>
      </GetWireResult>
    </GetWireResponse>
  </soap:Body>
</soap:Envelope>

or
<?xml version="1.0" encoding="utf-8" ?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <GetWireResponse xmlns="http://OpenSolutions.com/">
      <GetWireResult>
        <![CDATA[
        <?xml version="1.0"?>
        <BISearchResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
          <Error xmlns="https://bixg.choicepoint.com/webservices/3.0">
            <Message>BI System: Failed to Login</Message>
            536870917
          </Error>
        </BISearchResponse>
        ]]>
      </GetWireResult>
    </GetWireResponse>
  </soap:Body>
</soap:Envelope>

No matter. So you can select GetWireResult using following XPath:
/soap:Envelope/soap:Body/ab:GetWireResponse/ab:GetWireResult

and then load it content in new XML document and get desired response.

A: You're almost there. Extend your XPath
"/soap:Envelope/soap:Body/ab:GetWireResponse"

to
"/soap:Envelope/soap:Body/ab:GetWireResponse/ab:GetWireResult/ab:BISearchResponse/bg:Error"

However that extra XML prologue stuck in there in the middle, <?xml version="1.0"?>, makes the XML not well-formed. I'm surprised it can be processed at all. I would think the C# API should throw an exception on xmlDoc.LoadXml(result).
Another approach, seeing as the above does not return anything for you, would be to use your C# code to explore the structure of the XML document and print out the children of each node. E.g. if you are getting a node for "/soap:Envelope/soap:Body/ab:GetWireResponse" but not for "/soap:Envelope/soap:Body/ab:GetWireResponse/ab:GetWireResult", does ab:GetWireResponse have what text node children, and if so, what are their values (contents)? That should give insight into why the XPath is not working.
If there's a block of unparsed (i.e. escaped) XML in there, you could either copy it out and parse it as XML like you said, or just search for the pattern you need using a regexp... depending on the complexity.


text:
Q: Enable UTF8 characters in IEx (Interactive Elixir Console) on Windows how can enable UTF8 characters in IEx (Interactive Elixir Console) on windows?
Can't get the following to work:
# Strings are all encoded in UTF-8:
"héllò" #=> "héllò"

A: As Suggested in the comments, this works very well:
iex --werl
It does NOT require you to set any code page at all and you have UTF8 readily available.
I would suggest that the Elixir core docs be updated to point this really helpful switch --werl  out to other first time users.


text:
Q: Listing scheduled tasks that exist on a server I am trying to build some simple monitoring of scheduledtasks to see if they maybe fail, or get disabled.  This in itself should be fairly simple, and in the most part is.  However I have found an issue that I am struggling to understand let alone resolve.
get-scheduledTask
schtasks.exe /query /V /FO CSV
These list scheduled tasks nicely, but in my case when run interactively the results are as expected (although in schtasks some of the tasks get duplicated), however when I run the code through a scheduled task then some of the scheduled tasks fail to appear in the list.
I happen to be on a windows cluster which may be doing something clever as the missing tasks are missing on the other node in the cluster.
Is anyone able to assist me understand what the command is doing?  I do not believe get-scheduled task can go to a remote server, so not sure how this is possibly getting the wrong information
Thanks in advance for any help or suggestions


text:
Q: Moving laravel db models into folder Models (App\Models) as per Laravel 8 gives error I though I was clever to organise all the DB models into the folder as per Laravel 8 which I am running on my project...
What I did is :

*

*create the folder and move all the models into so now i.e. Articles.php is inside the app/Models folder

*add "namespace App\models;" in each model file

*replace all the instance of "use App\Article;" by "use App\Models\Article;" in all controllers

Now I get an error "Class '\App\User' not found (View: ...list.blade.php) which is displayed through the controller where all the models are properly defined as above.
If I run artisan dumpautoload I get "Class App\models\Article located in ./app/Models/Article.php does not comply with psr-4 autoloading standard. Skipping."
So what do I have to do to fix that issue?

A: Make sure the namespace you use is capitalized correctly - namespace App/Models rather than the App/models you noted above.
You may also need to update the file config/auth.php. Find the 'User Providers' section and look for the 'model' entry which points to the User model.


text:
Q: how to replace an entire column on Pandas.DataFrame I would like to replace an entire column on a Pandas DataFrame with another column taken from another DataFrame, an example will clarify what I am looking for
import pandas as pd
dic = {'A': [1, 4, 1, 4], 'B': [9, 2, 5, 3], 'C': [0, 0, 5, 3]}
df = pd.DataFrame(dic)

df is
'A' 'B' 'C'
 1   9   0
 4   2   0
 1   5   5
 4   3   3

Now I have another dataframe called df1 with a column "E" that is
df1['E'] = [ 4, 4, 4, 0]

and I would like to replace column "B" of df with column "E" of df1
'A' 'E' 'C'
 1   4   0
 4   4   0
 1   4   5
 4   0   3

I tried to use the .replace() method in many ways but I didn't get anything good. Can you help me?

A: If you don't mind getting a new data frame object returned as opposed to updating the original Pandas .assign() will avoid SettingWithCopyWarning. Your example:
df = df.assign(B=df1['E'])

A: Simply do:
df.B = df1.E

That's all!

A: If the indices match then:
df['B'] = df1['E']

should work otherwise:
df['B'] = df1['E'].values

will work so long as the length of the elements matches

A: For those that struggle with the "SettingWithCopy" warning, here's a workaround which may not be so efficient, but still gets the job done.
Suppose you with to overwrite column_1 and column_3, but retain column_2 and column_4
columns_to_overwrite = ["column_1", "column_3"]

First delete the columns that you intend to replace...
original_df.drop(labels=columns_to_overwrite, axis="columns", inplace=True)

... then re-insert the columns, but using the values that you intended to overwrite
original_df[columns_to_overwrite] = other_data_frame[columns_to_overwrite]

A: Another way is to use eval:
In [7]: df.eval('B = @df1.E', inplace=True)

In [8]: df
Out[8]:
   A  B  C
0  1  4  0
1  4  4  0
2  1  4  5
3  4  0  3

Since inplace=True you don't need to assign it back to df.


text:
Q: Cutting a CSV file up into different columns using R This is a follow up question to Pivoting a CSV file using R.
In that question, I wanted to cut up a single column (type) into several columns based on the values in column (repository_name). The following input data was used.
                 type          created_at repository_name
1         IssuesEvent 2012-03-11 06:48:31       bootstrap
2         IssuesEvent 2012-03-11 06:48:31       bootstrap
3   IssueCommentEvent 2012-03-11 07:03:57       bootstrap
4   IssueCommentEvent 2012-03-11 07:03:57       bootstrap
5   IssueCommentEvent 2012-03-11 07:03:57       bootstrap
6        IssuesEvent 2012-03-11 07:03:58        bootstrap
7         WatchEvent 2012-03-11 07:18:45        hogan.js
8         WatchEvent 2012-03-11 07:18:45        hogan.js
9         WatchEvent 2012-03-11 07:18:45        hogan.js
10   IssueCommentEvent 2012-03-11 07:03:57      bootstrap

The full CSV file is available on https://github.com/aronlindberg/VOSS-Sequencing-Toolkit/blob/master/twitter_exploratory_analysis/all_events.csv.
Here is a dput() of the first 30 rows of the CSV:
structure(list(type = structure(c(3L, 3L, 3L, 3L, 3L, 3L, 2L,
2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 1L, 1L,
1L, 4L, 4L, 4L, 2L, 2L, 2L), .Label = c("ForkEvent", "IssueCommentEvent",
"IssuesEvent", "WatchEvent"), class = "factor"), created_at = structure(c(1L,
1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L, 5L, 5L, 5L, 6L, 6L,
6L, 7L, 7L, 7L, 8L, 8L, 8L, 9L, 9L, 9L, 10L, 10L, 10L), .Label = c("2012-03-11 06:48:31",
"2012-03-11 06:52:50", "2012-03-11 07:03:57", "2012-03-11 07:03:58",
"2012-03-11 07:15:44", "2012-03-11 07:18:45", "2012-03-11 07:19:01",
"2012-03-11 07:23:56", "2012-03-11 07:32:43", "2012-03-11 07:38:52"
), class = "factor"), repository_name = structure(c(1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L,
1L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 1L, 1L, 1L), .Label = c("bootstrap",
"hogan.js", "twemproxy"), class = "factor")), .Names = c("type",
"created_at", "repository_name"), class = "data.frame", row.names = c(NA,
-30L))

That question was well answered by @flodel who proposed this code.
data.split <- split(events.raw$type, events.raw$repository_name)
data.split

list.to.df <- function(arg.list) {
  max.len  <- max(sapply(arg.list, length))
  arg.list <- lapply(arg.list, `length<-`, max.len)
  as.data.frame(arg.list)
}

df.out <- list.to.df(data.split)
df.out

However, now I would like to sort the list so that events (type) for each repo (repository_name) are ordered in a column each per month (as extracted from the "created_at" column) as such:
    bootstrap_2012_03   bootstrap_2012_04    hogan.js_2012_03
1    IssuesEvent          PushEvent          PushEvent
2    IssuesEvent          IssuesEvent        IssuesEvent
3    OssueCommentEvent    WatchEvent         IssuesEvent

Some other assumptions are:

*

*Time stamps is just for ordering and do not need to by synchronized across the row

*Even if "IssuesEvent" is repeated 10x I need to retain all of these, since I will be doing sequence analysis using the R package TraMineR

*Columns can be of unequal length

*There is no relationship between the columns for different repos ("repository_name")

*Data for different months of the same repository are completely independent

How can I accomplish this in R?

A: Instead of splitting by the repository_name column, first create a new column that combines repository_name and the month:
events.raw$month      <- format(as.Date(events.raw$created_at), "%Y_%m")
events.raw$repo.month <- paste(events.raw$repository_name,
                               events.raw$month, sep = "_")

head(events)
#          type          created_at repository_name   month        repo.month
# 1 IssuesEvent 2012-03-11 06:48:31       bootstrap 2012_03 bootstrap_2012_03
# 2 IssuesEvent 2012-03-11 06:48:31       bootstrap 2012_03 bootstrap_2012_03
# 3 IssuesEvent 2012-03-11 06:48:31       bootstrap 2012_03 bootstrap_2012_03
# 4 IssuesEvent 2012-03-11 06:52:50       bootstrap 2012_03 bootstrap_2012_03
# 5 IssuesEvent 2012-03-11 06:52:50       bootstrap 2012_03 bootstrap_2012_03
# 6 IssuesEvent 2012-03-11 06:52:50       bootstrap 2012_03 bootstrap_2012_03

Then use the same method I suggested last time:
data.split <- split(events.raw$type, events.raw$repo.month)

list.to.df <- function(arg.list) {
  max.len  <- max(sapply(arg.list, length))
  arg.list <- lapply(arg.list, `length<-`, max.len)
  as.data.frame(arg.list)
}

df.out <- list.to.df(data.split)
head(df.out)
#    bootstrap_2012_03 hogan.js_2012_03 twemproxy_2012_03
# 1        IssuesEvent       WatchEvent        WatchEvent
# 2        IssuesEvent       WatchEvent        WatchEvent
# 3        IssuesEvent       WatchEvent        WatchEvent
# 4        IssuesEvent             <NA>              <NA>
# 5        IssuesEvent             <NA>              <NA>
# 6        IssuesEvent             <NA>              <NA>