text:
Q: Cannot build prod version of Angular project for ASP.NET Boilerplate I'm trying to build a prod version of ABP 3.4.1 but when I run yarn run ng build --prod I get the following exception:
11% building modules 11/14 modules 3 active
...\bootstrap\dist\css\bootstrap.min.cssNode#moveTo was deprecated. Use
Container#append.                     Date: 2018-01-08T13:43:30.326Z
Hash: 988f3df7ec204a6033a2
Time: 21028ms
chunk {0} styles.e1f5a87bb585ebbb225d.bundle.css (styles) 414 kB [initial]
[rendered]
chunk {1} polyfills.3bc34265385d52184eab.bundle.js (polyfills) 86 bytes
[initial] [rendered]
chunk {2} main.e402deade8b026b7d50e.bundle.js (main) 84 bytes [initial]
[rendered]
chunk {3} inline.a6814d03da59c81640d4.bundle.js (inline) 1.45 kB [entry]
[rendered]

ERROR in : "let-" is only supported on ng-template elements. ("
  </thead>
  <tbody>
    <template ngFor [ngForOf]="rows" [ERROR ->]let-rowz="$implicit" let-index="index">
    <tr *ngIf="!(datePicker.onlyCurrentMonth && rowz[0].sec")
: "let-" is only supported on ng-template elements. ("
  </thead>
  <tbody>
    <template ngFor [ngForOf]="rows" let-rowz="$implicit" [ERROR ->]let-index="index">
      <tr *ngIf="!(datePicker.onlyCurrentMonth && rowz[0].secondary && rowz[6].sec")

error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

I cannot figure out where this error is occurring but after searching I found this post suggesting I set --aot=false but then I get the following error:
11% building modules 13/19 modules 6 active
...\bootstrap\dist\css\bootstrap.min.cssNode#moveTo was deprecated. Use
Container#append.                      94% asset optimization(node:2080)
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): SyntaxError: Unexpected token: punc ({)
(node:2080) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Done in 60.77s.

What can I do to get the prod version building correctly?

A: Answered in this issue: https://github.com/valor-software/ngx-bootstrap/issues/3024

Use ngx-bootstrap@2.0.0-beta.8

Set this in angular/package.json:
"ngx-bootstrap": "^2.0.0-beta.8",


text:
Q: How do I add item to Pidgin menu I want to add arbitrary item to Pidgin menu. Let it be Buddies → Show → Groups. I want it to be checkbutton (like Buddies → Show → Empty Groups) with custom function associated. How can I do this?

*

*In Pidgin 2.10.9

*In Pidgin 3.0.0 (development branch)

A: The following example is for Pidgin version 2.10.9. I believe there are not many changes in 3.0.0 (current development branch) so it will be applicable there too with minimal modifications.
First of all, download Pidgin sources. In Ubuntu this is done simply by running
apt-get source pidgin

Which will fetch libpurple, pidgin and finch sources. Then go into pidgin-2.10.9/pidgin/gtkblist.c and find the line

static GtkItemFactoryEntry blist_menu[] =

There you will see Gtk menu in text. Add the following line:
{ N_("/Buddies/Show/_Groups"), NULL, pidgin_blist_show_groups_cb, 1, "<CheckItem>", NULL },

after
{ N_("/Buddies/Show/_Empty Groups"), NULL, pidgin_blist_show_empty_groups_cb, 1, "<CheckItem>", NULL },

You can see that the line added is just the analog of after which it was added. The 3rd array member is the function responsible for updating menu item status.
Next, add the function you just specified, pidgin_blist_show_groups_cb. You can do it finding the pidgin_blist_show_empty_groups_cb and copying it's contents.
static void pidgin_blist_show_groups_cb(gpointer data, guint action, GtkWidget *item)
{
    pidgin_set_cursor(gtkblist->window, GDK_WATCH);

    purple_prefs_set_bool(PIDGIN_PREFS_ROOT "/blist/show_groups",
            gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(item)));

    pidgin_clear_cursor(gtkblist->window);
}

Also, you need to set item status on startup. Find the function
static void pidgin_blist_show(PurpleBuddyList *list)

and add
gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(gtk_item_factory_get_item (gtkblist->ift, N_("/Buddies/Show/Groups"))),
                                                      purple_prefs_get_bool(PIDGIN_PREFS_ROOT "/blist/show_groups"));

after
gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(gtk_item_factory_get_item (gtkblist->ift, N_("/Buddies/Show/Empty Groups"))),
                                                   purple_prefs_get_bool(PIDGIN_PREFS_ROOT "/blist/show_empty_groups"));

The adding preference "/blist/show_groups" as well as adding callback to it is explained in How do I add custom preference into Pidgin?. To test your changes, compile and install pidgin:

sudo apt-get build-dep pidgin
cd pidgin-2.10.9/
fakeroot debian/rules binary
sudo dpkg -i ../pidgin_2.10.9-0ubuntu3.deb

A: Pidgin-3.0.0
There are some changes in the way which Pidgin generates menu in 3.0.0 version. First, there is new array GtkToggleActionEntry blist_menu_toggle_entries[]. You need to add there
{ "ShowGroups", NULL, N_("_Groups"), NULL, NULL, G_CALLBACK(pidgin_blist_show_groups_cb), FALSE },

after
{ "ShowEmptyGroups", NULL, N_("_Empty Groups"), NULL, NULL, G_CALLBACK(pidgin_blist_show_empty_groups_cb), FALSE },

And, there is static const char *blist_menu. You need to add
"<menuitem action='ShowGroups'/>"

after
"<menuitem action='ShowEmptyGroups'/>"

Then follow the instructions from this answer skipping the very first.

redpajama_set_name: RedPajamaStackExchange


text:
Q: toggle child of clicked class pure Javascript - no JQuery I have two toggles with a class .submenu-toggle and they contain a ul child with a class .submenu. What I would like to happen is when the user clicks on .submenu-toggle the ul child(.submenu) of that class(submenu-toggle) is shown and then when it is clicked again it is hidden.
I need to achieve this using pure Javascript without any JQuery.
If you're able to also let me know how to hide .submenu if the user clicks outside that element... that would be awesome!
Thanks for your time and help.
Here is my current Javascript:
      // Drop Down Menus
      var subToggle = document.getElementsByClassName("submenu-toggle");
      var menu = subToggle.children;

      for (var i = 0; i < subToggle.length; i++) {
          subToggle.item(i).onclick = function () {

              menu[1].style.display = "block";
          }
      }

Here is my current html:

Menu 1

Menu 2

A: You could easily do this menu with CSS. But here's an example with vanilla JavaScript:
// JS
var submenu = document.getElementsByClassName("submenu-toggle");

for (var i = 0; i < submenu.length; i++) {
    submenu[i].addEventListener('click', menus, false);
}

function menus() {
  var menu = this.querySelector('.submenu');
  menu.classList.toggle("hidden");
};

// CSS

.hidden {
   display: none;
}

DEMO - Codepen


text:
Q: Ajax post table every row first cell Is it somehow possible to get table every row first cell input value and send it over ajax to PHP and it would send this information to mysql?

    12
    empty

    34
    empty

$('.addtodb').click(function(){
  $('#kogused tbody tr td.addr input').each(function() {
      var text = $(this).val();
  $.ajax({
        type: "POST",
        url: "insert/insert_addr.php",
        data: "aadress="+ text,
        success: function(){
            alert('Õnnestus!');
            }
        });
        return false;
    });
});

In this way - it adds two rows to DB but with the same value

A:
Is it somehow possible to get table
  every row first cell input value and
  send it over ajax to php and it would
  send this information to mysql?

To get every first cell, you would use the :first or :nth-child like this:
$('#kogused tbody tr td:first input')

Or
$('#kogused tbody tr td:nth-child(1n) input')


text:
Q: jQuery LayerSlider: LayerSlider not working with single image in IE 10 I am using LayerSlider (http://kreaturamedia.com/layerslider-jquery-full-width-slider/) which is working fine on all browsers except IE 10. Even the demo link is working fine on the browser but when I integrate the slider in the website I am working on, it fails to load the image and the following error is shown in the console:
"It seems like the URL of the image or background image "image name" is pointing to a wrong location and it cannot be loaded. Please check the URLs of all your images used in the slider."

The link of the image is correct and the issue appears if only one image is added. If more than one image is added, then the above error does not show.
I have checked for compatibility issues with other plugins by disabling other jQuery plugins but still no effect. I even tried to use the same version of jQuery the demo is using but still no luck.
If anyone has an idea what the problem is, kindly help me out
Thanks


text:
Q: Unable to call sub with if I am trying to call validation with if but the same not working and other line is continue executing, please help.
Private Sub BtnCreateInvioce_Save_Click(sender As Object, e As EventArgs) Handles BtnCreateInvioce_Save.Click
    If txtvalidation() = True Then

        PrintPreviewModule.Document = PrintModule

        add_items()
        PrintPreviewModule.ShowDialog()
        estimateclear()
        janAutoNumberUpdate("invoiceno")
        frmestimate_Load(sender, e)

    End If

End Sub

A: Try to replace your txtvalidation() function with something like this:
Public Function txtvalidation() as boolean
    return True
End Function

then, click on the BtnCreateInvioce_Save button. If works in this way, the problem is the txtvalidation() function that not produce the expected value.
Post this function code so we can understand what the problem is.
A tip: it is not necessary to write
If txtvalidation() = True Then
...

You can simply write
If txtvalidation() Then
...


text:
Q: Does $\sum_{n=1}^\infty \frac{n^n}{(2n)!}$ converge or diverge? This task made me curios about this theme $\su m_{n=1}^\infty \frac{n^n}{(2n)!}$
Can you help me? What method should I use? Can we use D'Alembert's principle here?

A: For convergence or divergence
of sums involving $n!$,
I always first use
$(n!)^{1/n} \approx \dfrac{n}{e}
$.
In this case,
$\begin{array}\\
\left(\frac{n^n}{(2n)!}\right)^{1/n}
&\approx \dfrac{n}{((2n)!)^{1/n}}\\
&= \dfrac{n}{\left(((2n)!)^{1/(2n)}\right)^2}\\
&\approx \dfrac{n}{\left(2n/e\right)^2}\\
&=\dfrac{e^2}{4n}\\
&\to 0\\
\end{array}
$
so the sum converges
by the n-th root test.

A: Use the lim$\frac{a_{n+1}}{a_{n}}$ criterion and you will easily find that is $\frac{e}{2}$ lim $\frac{1}{2n+1}$= zero! Therefore the series converges!! Proof is the following: $\frac{a_{n+1}}{a_{n}}$=$\frac{\frac{(n+1)^{n+1}}{(2(n+1))!}}{\frac{n^{n}}{(2n)!}}=(\frac{n+1}{n})^{n}(n+1).\frac{(2n)!}{(2n+2)!}$. The last factor of the product is $\frac{(2n)!}{(2n)!(2n+1)(2n+2)}=\frac{1}{2(n+1)(2n+1)}$. So, the fraction is ($\frac{n+1}{n})^{n}\frac{1}{2n+1}$(1/2) and taking limits we get (e/2).0=0


text:
Q: How to visualize data in paraview with fortran I wrote a program in Fortran which calculates molecular movements (basically their centers in 3d space - xyz). I'd like to visualize these data in ParaView, which I'm capable of. My programs output is VTK file which I can load into ParaView and see everything I need clearly. But I'd like to somehow make this process autonomous.
Basically I'd like to do computations and after some steps I'd like to visualize molecules with ParaaView, take a screenshot from certain angle save images as png (or any other img format which ParaView supports). Because of a high number of iterations I can't do this myself, therefore I thought about incorporating some kind of script into my Fortran code or any other way to make this happen, but I don't even know if this is possible or how?
I do really hope you can help me I'm in a pinch here, I'm quite new to Fortran, so I hope what I'm asking for is not impossible.
I'd like to thank you very much for any help you can provide me with. (I'm not asking for a prepared script, but for some hint/guide how to do this if possible, but I'm not against examples either).

A: Paraview has Python built into it for this exact purpose.

A: As Kyle Kanos said, you can script Paraview using Python. Those scripts then can be called from Fortran using call SYSTEM('cmd',status) (pre-Fortran 2008, non-standard, but supported by at least gfortran and ifort) or call EXECUTE_COMMAND_LINE('cmd') (Fortran 2008).
Here is the GCC documentation: SYSTEM and EXECUTE_COMMAND_LINE.


text:
Q: Button's click listener in listiview not working which extends Fragment When the listview in Activity,the button works,as long as my class extends Fragment ,there nothing happen.
public class OnlineNopaymentInsuranceFragment extends Fragment implements OnItemClickListener,OnItemSelectedListener,OnListViewListener,OnClickListener {

    private ScrollListView MainView;
    private BasicAdapter Adapter;
    private Integer Step=3;
    private Integer Start=0;
    private Integer End=Step;
    private Handler handler,handler2;
    //private List<Map<String, Object>> Lists;
    private DataTable Table;

    public static String SelectCode="";

    private static final int OVER = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_online_insurance,container,false);
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
                this.MainView=(ScrollListView)getView().findViewById(R.id.contractlistView1);

                this.MainView.setOnItemClickListener(this);
                this.MainView.setOnItemSelectedListener(this);
                this.MainView.setPullLoadEnable(true);
                this.MainView.setXListViewListener(this);

                handler2 = new Handler();

                Control.StartDialog(getActivity());
                new Thread(new Runnable() {
                    public void run() {
                        Looper.prepare();
                        handler2.post(runSetList);
                        handler1.sendEmptyMessage(1);
                        Looper.loop();
                    }
                }).start();

                this.MainView.setOnItemClickListener(new OnItemClickListener() {
                       @Override
                        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                               long arg3) {

                           Toast.makeText(getActivity(), "nothing", Toast.LENGTH_LONG).show();
                       }
                   });

    }

    private void SetList(){
        Start=0;
        End=3;
        this.Table = new DataTable(getActivity(),"newcontracta");
        this.Table.Load("AgentCode="+OnlineNopaymentInsuranceFragment.SelectCode+"&Start=0&End="+Step);
        if(Table.GetRowCount()>0){
            this.MainView.setVisibility(0);
            this.StartData(this.Table.GetList(),R.layout.userlistitem3);

        }else{
            this.MainView.setVisibility(8);
            TextView NullView=(TextView) getView().findViewById(R.id.listViewNull1);
            NullView.setVisibility(0);
            NullView.setHeight(50);
        }
    }

    private void StartData(ArrayList<Map<String, Object>> List, int Resource) {
        this.Adapter = new BasicAdapter(getActivity(), List, Resource,
                new String[] { "Provider", "ProdName", "NoType", "ContractNo",
                        "AcceptTime", "ContractStatus", "Premium", "Gain",
                        "ReceivedPremium", "Name" },
                new int[] {R.id.contractitem_label_Provider,
                        R.id.contractitem_label_ProdName,
                        R.id.contract_label_cno,
                        R.id.contractitem_label_contractNo,
                        R.id.contractitem_label_acceptTime,
                        R.id.contractitem_label_contractStatus,
                        R.id.contractitem_label_premium,
                        R.id.contractitem_label_feilv,
                        R.id.contractitem_label_receivedPremium,
                        R.id.contractitem_label_Name },
                new int[] {R.id.listitem_button_look, R.id.listitem_button_pay,R.id.listitem_main1 });

        handler = new Handler();
        this.Adapter.Start(this.MainView);
        this.Start += Step;
        this.End += Step;
    }

    private void LoadData(){
        this.Table.Load("AgentCode="+OnlineNopaymentInsuranceFragment.SelectCode+"&Start="+Start+"&End="+End);
        this.Start += Step;
        this.End += Step;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.listitem_button_pay:
                LogUtil.e("OnlineNopaymentInsuranceFragment", "nothing happen in here");
                Toast.makeText(getActivity(),"nothing happen in here", Toast.LENGTH_SHORT).show();

        break;
            case R.id.listitem_main1:
                Toast.makeText(getActivity(),"nothing happen in here,too", Toast.LENGTH_SHORT).show();
                break;

        default:
            break;
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int Index, long id) {}

    @Override
    public void onNothingSelected(AdapterView<?> parent) {}

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int Index, long id) {}

    private void stopRefresh() {
        this.MainView.stopRefresh();
        this.MainView.setRefreshTime("刚刚");
    }

    private void stopLoadMore() {
        this.MainView.stopLoadMore();
    }

    @Override
    public void onRefresh() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                SetList();
                stopRefresh();
            }
        }, 2000);
    }

    @Override
    public void onLoadMore() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                LoadData();
                stopLoadMore();
            }
        }, 2000);
    }

    @SuppressLint("HandlerLeak")
    Handler handler1 = new Handler() {
        public void handleMessage(Message msg) {
                switch (msg.what) {
                case OVER:
                    Control.ExitDialog();
                        break;
                default:
                        break;
                }
                super.handleMessage(msg);
        }
    };

    Runnable runSetList = new Runnable() {

        @Override
        public void run() {
            SetList();

        }
    };
}

Adapter code:
public class BasicAdapter extends SimpleAdapter {

    private Context context;
    private ArrayList<Integer> Indexs;

    public BasicAdapter(Context context,List<? extends Map<String,?>> data,int resource,String[] from,int[] to){
        super(context,data,resource,from,to);
        this.context=context;
        this.Indexs =new ArrayList<Integer>();
    }

    public BasicAdapter(Context context,List<? extends Map<String,?>> data,int resource,String[] from,int[] to,int[] Ids){
        super(context,data,resource,from,to);
        this.context=context;
        this.Indexs =new ArrayList<Integer>();
        if (Ids != null) {
            for (int i = 0; i < Ids.length; i++) {
                this.Indexs.add(Ids[i]);
            }
        }
    }

    public void Add(Integer ViewId){this.Indexs.add(ViewId);}

    @Override
    public View getView(int position,View convertView,ViewGroup parent){
        LogUtil.e("===basicadapter", "getview");
        View view = super.getView(position, convertView, parent);
        for(int i=0;i<this.Indexs.size();i++){
            View TempView=(View) view.findViewById(this.Indexs.get(i));
            TempView.setOnClickListener((OnClickListener) this.context);
            TempView.setTag(position);
        }
        return view;
    }

    public void Start(ListView View){
        View.setAdapter(this);
        this.setViewBinder(new ViewBinder() {
            @Override
            public boolean setViewValue(View view,Object data,String textRepresentation) {
                if(view instanceof TextView && data instanceof HkBoolean){
                    HkBoolean Data = (HkBoolean) data;
                    view.setVisibility(Data.GetVisibility());
                    return true;
                }else if(view instanceof ImageView && data instanceof Bitmap){
                    ImageView iv = (ImageView) view;
                    iv.setImageBitmap((Bitmap) data);
                    return true;
                }else if(view instanceof ImageView && data instanceof Integer){
                    ImageView iv = (ImageView) view;
                    iv.setBackgroundResource((Integer) data);
                    return true;
                }else {
                    return false;
                }
            }
        });
    }

}

If I put button lister in BasicAdapter,it can call ,too.But I want the button'click listener in Fragment.Any suggestion will be appreciated.

A: this.Adapter = new BasicAdapter(getActivity(), List, Resource,
            new String[] { "Provider", "ProdName", "NoType", "ContractNo",
                    "AcceptTime", "ContractStatus", "Premium", "Gain",
                    "ReceivedPremium", "Name" },

Fragment is implementing the listener and not the activity. So you should do
this.Adapter = new BasicAdapter(this, List, Resource,
            new String[] { "Provider", "ProdName", "NoType", "ContractNo",
                    "AcceptTime", "ContractStatus", "Premium", "Gain",
                    "ReceivedPremium", "Name" },


text:
Q: Copy SVN Repository I have an SVN repo at a hosted SVN service which I need to move to our locally hosted SVN service. The host offers an export feature, which I've used. But how do I take that exported file and import it into a new repository?
EDIT
I tried using svnadmin load, but got an error message:
% svnadmin load . < ~/ss2_14066_rev36
svnadmin: Malformed dumpfile header

The service I'm exporting from is http://beanstalkapp.com, and their help page for export says this exported file can be reimported to another svn server. Is this possibly a server version mismatch?

A: If the export was created using svnadmin dump you can import it into a new, empty repository using
# cd /path/to/new/repo
# svnadmin load . < /path/to/dumpfile

A: If your hosting provider uses Subversion 1.4 or later you can also use svnsync to create a copy from the repository.
See The Subversion Book for more details.

A: Is it possible that it's not a dumpfile but rather a tar.gz of the repository itself?

A: This bit:
/path/to/dumpfile

has to be an absolute path to a (.dmp) FILE that can be streamed back to the svnadmin load command, not just a directory location.


text:
Q: Amazon S3 bucket objects access I am uploading user videos on S3 bucket, i want to make restricted access to these videos. My application hosted on three locations.
1) Web application on a server.
2) I Phone app
3) Android app
After uploading the video on S3 bucket i store the URL(Cloud front web URL) in DB. All the above app query the db and pass the URL to players.
Currently the videos are public, how i can restrict these videos to only access by the 3 apps mentioned above.
I have tried IP restriction, HTTP referrer, authenticated access. The last option look like work, but anyone who has the authenticated URL.

A: Since you're serving content via Amazon S3 and Amazon CloudFront, the best way to serve private content would be:

*

*Secure the content in S3 so that it can only be accessed via CloudFront

*Secure the content in CloudFront so that it can only be accessed via Signed URLs

*Have your application generate Signed URLs so that authorized users can access the content from CloudFront

A Signed URL is a way to permit access to private content for a limited time. For details, see: Serving Private Content through CloudFront


text:
Q: Problem with Reducer that contains few different values I'm kind of new to React.js & Redux, so I have encountered a problem with Reducers.
I am creating a site that have a main "Articles" page, "Question & Answers" page, I created for each one a separate Reducer that both work just fine.
The problem is in "Main Page" which contains a lot of small different pieces of information, and I don't want to create each little different piece of information its on Reducer, so I am trying to create one Reducer which will handle a lot of very small different pieces of information, and I can't make that work, inside the main "Content" object, I put 2 Key Value Pairs that each have an array, one for each different information, one is "Features" info, and one for the "Header" info.
This is the error that I'm getting:
Uncaught TypeError: Cannot read property 'headerContent' of undefined
    at push../src/reducers/ContentReducer.js.__webpack_exports__.default (ContentReducer.js:15)

I am not sure what's the problem, maybe my code is wrong or maybe my use of the spread operator, any solution?
I have added the necessary pages from my code:
ACTIONS FILE
export const addFeatureAction = (
    {
        title = 'Default feature title',
        feature = 'Default feature',
    } = {}) => ({
        type: 'ADD_FEATURE',
        features: {
            id: uuid(),
            title,
            feature
        }
})

export const addHeaderAction = (
    {
        title = 'Default header title',
        head = 'Default header',
    } = {}) => ({
        type: 'ADD_HEADER',
        header: {
            id: uuid(),
            title,
            head
        }
})

REDUCER FILE:
const defaultContentReducer = {
    content: {
        featuresContent: [],
        headerContent: [],
    }
}

export default (state = defaultContentReducer, action) => {
    switch(action.type) {
        case 'ADD_FEATURE':
            return [
                ...state.content.featuresContent,
                action.features
            ]
        case 'ADD_HEADER':
            return [
                ...state.content.headerContent,
                action.header
            ]
        default:
            return state
    }
}

STORE FILE:
export default () => {
    const store = createStore(
        combineReducers({
            articles: ArticleReducer,
            qnaList: QnaReducer,
            content: ContentReducer
        })
    );
    return store;
}

A: The reducer function is supposed to return the next state of your application, but you are doing a few things wrong here, you are returning an array, a piece of the state and not the state object, I would suggest you look into immer to prevent this sort of errors.
Simple fix:
export default (state = defaultContentReducer, action) => {
    switch(action.type) {
        case 'ADD_FEATURE':
            return {...state, content: {...state.content. featuresContent: [...action.features, ...state.content.featuresContent]}}
        // More actions are handled here
        default:
            return state
    }
}

If you use immer, you should have something like this
export default (state = defaultContentReducer, action) => {
  const nextState = produce(state, draftState => {
     switch(action.type) {
        case 'ADD_FEATURE':
            draftState.content.featuresContent = [...draftState.content.featuresContent, ...action.features]
  });
            break;
        default:
            break;

  return nextState
}


text:
Q: Add Disclaimer Screen I am trying to add a disclaimerViewController to my application as the initial viewController, which, if accepted will lead the user tot he entryViewController, and if not, will not allow the user to use the application. However, I want to to be that if the user accepts the disclaimer, any time after he opens the application he won't be presented with the  disclaimerViewControleler but with the entryViewController.
I know that it has something do to with editing the AppDelegate.swift file, but am unsure of were to start.

A: You need to save user choice in UserDefaults
The code below is using Swift 3
If you don't want to load entryViewController then In the AppDelegate:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        //retrieve values from UserDefaults
        //for the first time it will be false, because it was not set earlier
        let isAccepted = UserDefaults.standard.bool(forKey: "isAccepted")

        if isAccepted == false {
           //present your disclaimer here
        }else{
           //show entryViewController
        }

        return true
}

Or you can load entryViewController and present disclaimer instantly, then in your entryViewController:
override func viewDidLoad() {
        super.viewDidLoad()

   //retrieve values from UserDefaults
   //for the first time it will be false, because it was not set earlier
   let isAccepted = UserDefaults.standard.bool(forKey: "isAccepted")

   if isAccepted == false {
      //present your disclaimer here
   }
}

In the DisclaimerVC:
@IBAction func accept(_ sender: UIButton){
    //it can be another action in your controller
    //but anyway, you should save user choice after that
    UserDefaults.standard.set(true, forKey: "isAccepted")

    //add code here to dismiss disclaimer
}

A: The way I would go about doing this is by setting your disclaimerViewController to the initial view controller in your storyboard file.
In the swift file check to see if the user has previously accepted the disclaimer in the viewDidLoad method, if they haven't, allow the code to function normally and display the screen, if they have push the user on to your entryViewController
If you want to set your initial view controller in the AppDelgate and not in the storyboard, here is a useful link: set initial viewcontroller in appdelegate - swift
To transition to a new viewcontroller in swift, here is a useful link:  Switching view controllers in swift

A: The smoothest way to implement this is to switch the views programmatically.
Make sure to set the restoration ids for your ViewControllers in the StoryBoard.
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    var mainViewController: ViewController?
    var acceptViewController: AcceptViewController?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        mainViewController = mainStoryboard.instantiateViewController(withIdentifier: "MainView") as? ViewController
        acceptViewController = mainStoryboard.instantiateViewController(withIdentifier: "AcceptView") as? AcceptViewController
        if mainViewController == nil {
            print("mainViewController is nil")
        }
        if acceptViewController == nil {
            print("acceptViewController is nil")
        }

        let isAccepted = UserDefaults.standard.bool(forKey: "isAccepted")

        if isAccepted == false {
            switchToAcceptViewController()
        } else {
            switchToMainViewController()
        }
        return true
    }

    func switchToMainViewController() {
        //mainViewController?.selectedIndex = 0 // only needed if the main view controller is a tab view
        self.window?.rootViewController = mainViewController
        self.window?.makeKeyAndVisible()
    }
    func switchToAcceptViewController() {
        //mainViewController?.selectedIndex = 0 // only needed if the main view controller is a tab view
        self.window?.rootViewController = acceptViewController
        self.window?.makeKeyAndVisible()
    }

}

AcceptViewController
class AcceptViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func acceptAction(_ sender: Any) {
        UserDefaults.standard.set(true, forKey: "isAccepted")
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.switchToMainViewController()
    }

}

You can get the full project here: https://github.com/ryantxr/legendary-fiesta


text:
Q: Replace command with ^word1^word2 in alias Hello I have a long command like this :
adb shell am instrument -w -r -e debug false -e password mypassword -e class 'com.XXX.XXX.XXX.XXXX#testsomething[false]' -e clearPackageData true com.XXX.XXX.XXX.XXXX.test/androidx.test.runner.AndroidJUnitRunner

And I want to have a command that I can invoke quickly to replace the password.
The following command is perfect when I enter it in the shell but it doesn't work when I create an alias for it like this:
alias fastcommandchange="^mypassword^real_password"

Any ideas ? or suggestions ? or questions ? (I use zshrc)


text:
Q: Square roots modulo p For Chebyshev-polynomials on finite fields $F_p$ with a prime $p$, I have found the following expression:
$$
T_n(x)=\frac{(x+\sqrt{x^2-1})^n+(x-\sqrt{x^2-1})^n}{2} mod\space p.
$$
But obviously, $\sqrt{x^2-1}$ is not defined on $F_p$ for some $x$. How can this formula still be a correct representation of Chebyshev-polynomials modulo $p$?
Thanks so much for some help!

A: The simple fact is that the expression
$$(x+\alpha)^n+(x-\alpha)^n$$
contains no odd powers of $\alpha$.


text:
Q: Django with PostgreSQL 10? Does Django support PostgreSQL 10 at the moment? I tried to use pgadmin3 with the psql V10 and found, it breaks pdagmin3.
Somebody has opened a ticket on django project which may be in discussion.
Is there any known breaking changes in v10 compared to v9.6 for Django? (because it breaks in pgadmin3)?
let me know thanks.

A: Django supports PostgreSQL 10 with Psycopg 2.7.3.2


text:
Q: jQuery change script from another script This could be a newbie question, but here it goes. I have the following script in a file where I cannot make any changes.
$('.btn-group label:not(.active)').click(function()
{
    var label = $(this);
    var input = $('#' + label.attr('for'));

    if (!input.prop('checked')) {
        label.closest('.btn-group').find('label').removeClass('active btn-success btn-danger btn-primary');
        if (input.val() == '') {
            label.addClass('active btn-primary');
        } else if (input.val() == 0) {
            label.addClass('active btn-danger');
        } else {
            label.addClass('active btn-success');
        }
        input.prop('checked', true);
    }
});

but I need to make a simple modification on it. Is there a way from another script (in another file) change the above one to look like this
$('.btn-group label:not(.active)').click(function()
{
    var label = $(this);
    var input = $('#' + label.attr('for'));

    if (!input.prop('checked')) {
        label.closest('.btn-group').find('label').removeClass('active btn-success btn-danger btn-primary');
        if (input.val() == '') {
            label.addClass('active btn-primary');
        } else if (input.val() == 0) {
            label.addClass('active btn-danger');
        } else {
            label.addClass('active btn-success');
        }
        input.prop('checked', true);
        input.trigger('change');          // Added line
    }
});

A: You should just bind a new handler:
$('.btn-group label:not(.active)').click(function()
{
    $('#' + label.attr('for') + ':not(:checked)').trigger('change');
});

Beware, if class active can switch, to handle this change, you should delegate event:
$('.btn-group').on('click', 'label:not(.active)', function(){...});


text:
Q: How to enable selection of entire Table item when TableEditor is used I'm using SWT table which consists of one column and i'm using SWT TableEditor to edit the column values.
When i try to edit a particular row, only the text of that particular TableItem gets selected.
Is there any way to enable the entire selection of that Table item.
My selectionListner code for the table looks like this:
final TableEditor editor1 = new TableEditor(table);
    //The editor must have the same size as the cell and must
    //not be any smaller than 50 pixels.
    editor1.horizontalAlignment = SWT.LEFT;
    editor1.grabHorizontal = true;
    editor1.minimumWidth = 130;
    final int keyEditableColumn = 0;
    table.addSelectionListener(new SelectionAdapter()
    {
        public void widgetSelected(SelectionEvent e)
        {
            // Clean up any previous editor control
            Control oldEditor = editor1.getEditor();
            if (oldEditor != null) oldEditor.dispose();

            // Identify the selected row
            final TableItem item = (TableItem)e.item;

            if (item == null)
            {
                return;
            }

            // The control that will be the editor must be a child of the Table
            Text newEditor = new Text(table, SWT.NONE);

            //Adding the list of Text Widgets that have been created for a component.
            textWidgetsList.add(newEditor);

            newEditor.setText(item.getText(keyEditableColumn));
            newEditor.addModifyListener(new ModifyListener()
            {
                public void modifyText(ModifyEvent me)
                {
                .....
                .....
                .....
                .....
                .....
                                    }
            });
            newEditor.selectAll();
            newEditor.setFocus();
            editor1.setEditor(newEditor, item, keyEditableColumn);
        }
    });

Please let me know your suggestions....

A: You have to create your Table with the style SWT.FULL_SELECTION.


text:
Q: How to specify available time for Shiny App usage I made a Shiny App which basically teaches students about simple statistic tests and plots. However, because (an while) I have a free account on shiny, I have a limited amount of time to make it available per month. Therefore, I'm going to set specific windows of time for it to run every week. The thing is I can't manually do it every time, not only because I'd likely forget, but because I'm not available during the closing time (17h) to do it. Also, I'm not sure how I'd do that.
Therefore, I wanted to know if there was a way to automate available times for the Shiny App to be open and possibly running, and to have the link be useless at any other time.
I realise I've only written things here, so if I forgot any important information, please ask and I'll edit this question.

A: You could use a reactiveTimer to check regularly time, use a modalDialog if the time is over to warn the user, and stop the App after a few seconds:
library(shiny)

ui <- shinyUI(fluidPage(actionButton("run", "Do something")))

server <- shinyServer(function(input, output, session) {
  # Check time every minute
  time <- reactiveTimer(60000)
  observe({
    currenthour <- as.numeric(format(time(), '%H'))
    if (currenthour >= 17) {
      showModal(modalDialog(title = "App not available after 17h",
                            paste("it's", format(time(), '%H:%M'), "h, please try again tomorrow")))
      Sys.sleep(5)
      stopApp()
    }
  })
})

shiny::shinyApp(ui, server)


text:
Q: RangeError (index): Invalid value: Not in inclusive range 0..9: 100
*

*I have to face issues like below code when I try to create load more items with GroupedListView.
Here is UI code I make and have issues when I using GroupListView:

  GroupedListView<TrackingOrderItemListResponse, DateTime>(
                      controller: controller.scrollController,
                      key: controller.statePageKey,
                      elements:
                          controller.trackingOrderListResponse!.body.items!,
                      groupBy: (element) => DateTime.parse(
                          DateFormat("yyyy-MM-dd").format(element.orderDate)),
                      groupComparator: (value1, value2) {
                        return value2.compareTo(value1);
                      },
                      useStickyGroupSeparators: true,
                      padding: const EdgeInsets.all(16.0),
                      groupSeparatorBuilder: (DateTime value) {
                        var dateStr;
                        var dNow = DateTime.now();
                        if (value.isAtSameMomentAs(
                            DateTime(dNow.year, dNow.month, dNow.day))) {
                          dateStr = "Today";
                        } else {
                          dateStr = DateFormat("MMM dd, yyyy").format(value);
                        }
                        return Padding(
                          padding: const EdgeInsets.all(16.0),
                          child: Text(
                            dateStr,
                            style: TextStyle(fontSize: 16),
                          ),
                        );
                      },
                      itemBuilder: (c, data) {
                        return Padding(
                          padding: const EdgeInsets.only(bottom: 16.0),
                          child: TrackingCell(
                            trackingController: controller,
                            data: data,
                            onTap: () => controller.gotoDetailPage(data.id),
                            onReorder: () async {
                              Get.toNamed(Routes.EXPRESS_DETAILS, arguments: {
                                "is_reorder": true,
                                "id": data.id,
                              });
                            },
                          ),
                        );
                      },
                    )

I have to face issues like below UI code when I try to create load more items with GroupedListView.
And here is my controller:
  fetchMoreTrackingOrder(
    String startData, String endData, int page, int rpp) async {
  scrollController.addListener(() async {
    if (scrollController.position.maxScrollExtent ==
        scrollController.position.pixels) {
      page += 1;
      print("Information page: $page");
      var resData = await _trackingService.trackingListOrder(
          endData, startData, page, rpp, currentStatus);
      if (page == 1) {
        trackingOrderListResponse = resData;
      } else {
        trackingOrderListResponse!.body.items!.addAll(resData!.body.items!);
      }
      update();
    }
  });
}


text:
Q: Multiple keystrokes as autohotkey shortcut I'm new to AutoHotkey.
I have a specfic need to be achieved in Powerpoint using autohotkey.
Let's say in Powerpoint, I want to change font color.
The normal steps are:

*

*Select the text

*Click "Home" > Click "Font Color" > The Font palette gets expanded and I select the color.

Now, I want to make this process quicker as below

*

*Select the text

*Press FC (as shortcut from keyboard) and autohotkey should press the following keys Alt+H+FC (Very importantly, if I don't press C immediately after F, then it should get typed as replaced text of highlighted text)

So, my code goes as like this
#SingleInstance, Force
#IfWinActive ahk_exe POWERPNT.EXE ; check whether ppt is the active window
f::
#if keypress c
    send, !HFC
#if
return

But, this doesn't work.
I don't where am I making mistake. Could someone help, please

A: I know this is an autohotkey question, but the quick access toolbar (QAT) in PowerPoint may solve your problem out of the box.
The QAT assigns Alt+1 to the first feature, alt+2 to the second, etc. By customizing the order of buttons on the QAT, you can access features you use often with one key combination.
Instructions
First add the font color button to the QAT: right click the 'font color' button, and click 'add to quick access toolbar'

Change the order of features in the QAT: right click on the QAT - customize quick access toolbar). Use the arrow buttons on the right side to change the ordering.
This is the order I use myself:

This allows me to very quickly align objects on a slide, change background color, outline, and text color, all initiated from the keyboard.


text:
Q: No bootable device insert bootable device Can't turn on laptop Acer aspire V5 561G(purchased at 2014),always gives this msg,also can't enter bios,pressing f2 but no reaction,is there any solution,where can i download bios or recovery tools if official site don't give it for old laptops?

A:
Common keys to enter the BIOS are F1, F2, F10, DEL, ESC

Source article. You should be able to get to BIOS (or UEFI config UI) with one of those and see if the system recognizes any disks or USB / DVD drives.


text:
Q: How to interpret GRASS v.kernel results? GRASS manual reads:

v.kernel - Generates a raster density map from vector points data using a moving 2D isotropic Gaussian kernel ...

Ok, but how do I interpret the results? I understand that v.kernel is the more advanced than v.neighbor function but I'm unsure as to which advantages it has.

A: Have you seen the Geospatial Analysis web book? They have a quite detailed section on point density, which covers Gaussian functions. Even in general I feel it's a very useful resource.

A: Here's a grossly oversimplified way to think about it:
Imagine a dartboard with several rings radiating out from the center. At each location in the result, a score is computed by putting the dartboard over the location and seeing where the vector points are on the dartboard. From that the score is tallied and the raster is made.
There are many variables to how this is computed:
-- the size of the dartboard (the kernel)
-- the shape of the dartboard (2D isometric or 'the same in every direction in x/y', i.e. a flat circle)
-- the way the dartboard assigns points (Gaussian implies a 'normal' distribution, i.e. higher scores as the point gets closer to the center, in a bell curve shape)
The advantage is that it will compute a much smoother version without large (discontinuous) jumps that can take in information with a wider and more consistent radius. It also will be less affected by the differences in size/shape of the areas used.
Think about using Nearest Neighbors on counties: On the east coast they are much smaller than the Midwest, but the number of neighbors is similar and largely affected the geometry of the boundary. Which is more dense? If your kernel radius is 50 miles you'd get a much different answer that described their relative density much more accurately.

A: The results estimate points per unit area.  As a check, you should multiply the density values by the area of a cell and add up these values over the grid: the total should equal the sum of the original data.  (These two values often differ for two reasons, boundary effects and numerical imprecision.  The boundary effects occur because the density map can spread data off the edge of the map and those values don't get recovered from the density grid.  But the differences ought to be small.)
One image I have used in classes asks students to imagine the kernel as a bucket of sand: you upend the bucket at a point, allowing the sand to slump.  The slumping barely occurs for short half-widths but is extensive for large band-widths (maybe the sand is wetter ;-).  Regardless, it's always the same amount of sand left, no matter how slumping occurs.  Now go dump one bucket at the location of each point (or, more generally, if there is a positive value x associated with each data point, first put an amount of sand in the bucket proportional to x and then dump it).  The sand slumps.  It piles up in areas where there are lots of buckets.  The density grid gives you the height of the piled sand at the center of each grid cell.  Multiplying this by a cell's area estimates the volume of sand occupying each cell.  Summing this cell volume over any region (such as a Census block) estimates the total volume of sand in that region, which represents the total amount of quantity x you think is in the region.


text:
Q: create registry key using variable in batch file 2008r2 I would like to create a new registry key to add the current computer name to the internet explorer trusted sites in windows 2008r2 x64
My server is called "MyServerName"
in a batch file if I type echo %hostname% it return MyServerName
but in the registry command it doesnt work it create the key using "%hostname%" instead of "MyServerName"
Here is the command I tried :
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\EscDomains\%hostname%" /v http /t REG_DWORD /d 00000002 /f

I would expect the key to be created to look more like this:
HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\EscDomains\MyServerName"
Any help would be appreciated, I tried digging to find info on how to do this but couldn't find anything that would solve my problem.
In case you wonder, we have an application that needs to run locally and use the server hostname to access a website and apparently for IE MyServerName is different from localhost even if localhost is already in the trusted site.

A: There is a system binary C:\windows\system32\hostname.exe, but Windows doesn't have an Environment Variable %HOSTNAME%
C:\> set | FIND /I "HOSTNAME"
<no results>

Perhaps you mean to use %COMPUTERNAME% instead?
C:\> set | FIND /I "COMPUTERNAME"
COMPUTERNAME=SRV1


text:
Q: Adwords and Double-click: possible to have interactive banner ads where you click multiple times within the ad before being redirected to a website? I have a client who is requesting something that I don't think is possible, but wanted to verify before I tell them it can't be done. What they want: to create an interactive animated banner ad, where the user would click on the ad to attempt to shoot a basket though a basketball goal. They will miss the first one, but try again, then make the basket. Then the ad would animate through to the end where they would then click through to the client's website. It seems like it wouldn't be possible to click multiple times on a banner ad. Is this correct or is there a way to do this? Thanks in advance for your help!

A: A part of what you are describing should be doable using the ExitApi, which allows you to make only a specific part of your ad a clickable exit. It's not very well documented but mentioned here.
Note that there might be other Adwords policies which will prevent you from implementing your creative exactly as described, but having only a specific element in your ad triggering a click-through is possible.


text:
Q: Issue in sending email I am working on an example that is for sending an email using Swift. I am using the following code:
@IBAction func sendMailButtonAction(sender: UIButton) {

        if MFMailComposeViewController.canSendMail() {
            let mail = MFMailComposeViewController()
            mail.mailComposeDelegate = self
            mail.setToRecipients(["abc@gmail.com"])
            mail.setMessageBody("
You're so awesome!
", isHTML: true)
           // mail.addAttachmentData(<#T##attachment: NSData##NSData#>, mimeType: <#T##String#>, fileName: <#T##String#>)
            presentViewController(mail, animated: true, completion: nil)
        } else {
            print("Error Received While sending mail")        }

    }

When I click the send button of the MFMailComposeViewController() to send the mail, I receive the error in the device logs as:
>     1. <Error>: 18:32:54.282 [0x16e1bb000] >vibe> Error: Empty atoms array
>     2. ERROR:    [0x16e1bb000] 919: Vibe engine could not play vibe pattern, err = -50, actionID = 1001. Please file a bug.

A: The issue was with the server firewall of the organisation. It is blocking the server port to send the mail. Tried to send the mail using cellular network and it worked.


text:
Q: How to get the distance moved by the splitter? Scenario:
I am using a telerik:RadRotator and splitter.
I have 3 user controls on the page separated by the splitter. I have this telerik:RadRotator and vertical splitter is moved Horizontally on one control.
Question
Now, I want to resize the RadRotator as the splitter is moved.
I have achieve that by this piece of code:
function resizing(sender, Args) {
    var rotator = $jQuery(".rrRelativeWrapper");
    var oldRotatorWidth = rotator[0].style.width;
    var width = parseInt(oldRotatorWidth.substr(0, (oldRotatorWidth.indexOf('px') + 1)));
    var newRotatorwidth = (width + (sender._width - width)) - 50;
    rotator[0].style.width = newRotatorwidth.toString() + "px";
}

But the problem is the "-50" that I have added to adjust the differences. This breaks the jquery if the splitter is resized at higher speed.
As I am not able to get the exact distance moved by the splitter when it is resized.
So, please can any one help me out how to get the exact difference in distance moved by the splitter?
Note: I want to write this Jquery on event OnClientResizing not on OnClientResized.

A: If you use an event that is fired numerous times you may get a race condition and things may break. Use the event that fires when the resizing has finished. Otherwise, take a look here for an approach to fire the handler only once: https://stackoverflow.com/a/668185/812369.
Also, RadRotator does not support dimensions changes on the client, so things will not work as expected, I think. Take a look here for an approach that can work once you have the needed dimensions: http://www.telerik.com/support/kb/aspnet-ajax/rotator/setting-radrotator-s-size-in-percent.aspx.


text:
Q: how to use tqdm progress bar in dask_cudf and cudf I can use tqdm progress bar in pandas for example:
tqdm.pandas()
df = df['var'].progress_apply(lambda x: something(x))

can i do same in thing cudf or dask_cudf if not then how can i use tqdm progress bar in it,

A: Until progress_apply is available, you would have to implement an equivalent yourself (e.g. using apply_chunks). Just a sketch of the code:
full_size = 100
t = tqdm(total=full_size)
def chunks_generator():
    chunk_size = 5
    for s in range(0,full_size,chunk_size):
        yield s
        t.update(s)

df.apply_chunks(..., chunks=chunks_generator())


text:
Q: Python Function Append String to a list with variable name I want to append values to the variable which is s_stat,f_stat and stat (for example for stats_players(pass), variable should be s_pass,f_pass and pass). It gives me error that s_stat is not defined. It is probally do not detect variable as s_pass.
Function
def stats_players(stat,player_id):
a = {}
b = {}
if stat != "Start" and stat != "FormationChange" :
    print(stat)
    for js in data_events[str(stat)]:
        icdType = js["playerId"]
        if icdType in a:
            a[icdType].append(js)
        else:
            a[icdType] = [js]

    data = json.dumps(a)
    data = json.loads(data)
    if str(player_id) in data == True:
        for js in data[str(player_id)]:
            icdType = js["outcomeType"]["displayName"]
            if icdType in b:
                b[icdType].append(js)
            else:
                b[icdType] = [js]
        data = json.dumps(b)
        data = json.loads(data)
        if  "Successful" in data != "False":
            suc = len(data["Successful"])
            s_stat.append(len(data["Successful"]))
        else:
            suc = 0
            s_stat.append("0")
        if  "Unsuccessful" in data != "False":
            fail  = len(data["Unsuccessful"])
            f_stat.append(len(data["Unsuccessful"]))
        else:
            fail = 0
            f_stat.append("0")
        Pass.append(suc+fail)
    else:
        suc = 0
        fail = 0
        Pass.append(suc+fail)
        s_stat.append(suc)
        s_stat.append(fail)

Code
Pass = []
f_Pass = []
s_Pass = []

stats_players("Pass",player_id)

Error
Traceback (most recent call last):
File "test.py", line 446, in <module>
stats_players("Pass",player_id)
File "test.py", line 98, in stats_players
s_stat.append(suc)
NameError: name 's_stat' is not defined

A: You need to first declare that s_stat is a list.
s_stat = []
This will let the compiler know that s_stat is a list


text:
Q: How to send an SMS Message using Email or HTTP Protocols I want to write a piece of PHP code that will send SMS to any number in the world. I read somewhere one can use email to do this as follows.

user-number@carrier-domain.com ⇒ 1234567894@vnet.com

I tried this with my number and my carrier's website domain and it didn't work. I think the domain is something which is not publicly available so my job should be able to find it first. Am I right here? Also they can put some checks as what the source is when they receive the SMS so they reject. Is that true too?
On the other hand, is there any way HTTP can be used to do so?

A: This is possible, but usually you'll need a special agreement with the carrier or a third-party who'll send the sms. And it'll cost you (here in germany starting at 8-10 Cent for a small number of sms).
There may be different ways to deliver sms, e-mail, http or a special api.
But a simple e-mail to number@telco.example.com will most likely not work. I have never heard of such method. Some telcos accept e-mails sent to these addresses, but the recipient has to allow/activate this.
Edit: Another method you could consider: connecting a gsm-module (or even an old mobile phone) to a server and send sms via at-commands over a serial/usb connection.

A: Check the web site of your mobile carrier, or contact their technical support.  Email-to-SMS and HTTP-to-SMS gateways are specific to each carrier.


text:
Q: Simultaneous gRPC clients sync/async server I'm just curious,

*

*Does a sync gRPC server supports connection from multiples clients?

*If not, and the async ones does?

*And combination of async server/sync client? is even possible?

A: Yes, synchronous gRPC supports multiple connected clients out of the box. I have personally tested with up to 2000 simultaneously connected clients to an microservice written in Go exposing a single API.


text:
Q: Import Excel file into a myPhpAdmin MySQL database So I am working on my extended essay that has to do with mysql databases. I want to create an excel spreadsheet with 100 or so books and then import then in to three database tables with different collation types. I have saved the excel file as a csv file and when i go to phpMyAdmin and click on import in my database, i get an error.

1064 - You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '1,In Pharoah's Army,Tobias Wolff,NULL,NULL,FALSE,NULL,NULL
2,MacBeth,William Sha' at line 1

How would i go about importing an excel spreadsheet into myPHPAdmin using the import function given, so that i can do this using GUI instead of codes, which i don't know much about.
I am using XAMPP to create a local server and the myPHPadmin server version is 5.1.44

A: To import a XLS or XLSX file into MySQL using PHPMyAdmin can be done a number or ways. I have used CSV and OpenDocument Spreadsheet.
When importing a CSV file, make sure that the amount of columns in the sheet math your database otherwise this will throw an error. Be aware that CSV will remove all formatting in your sheet so potentially if your using an ISBN or barcode in your sheet it could cause problems when displayed in the database.
As for OpenDocument Spreadsheet, this will allow you to export your sheet into MySQL keeping your formats. Although this is good it does not name your columns and will always create a new table. This can be edited easily by creating your column names at the top of your spread sheet and then editing the table name in PHPMyAdmin. Be aware though that this is a bad method when exporting large spreadsheet it will probably time out.
So from your situation I would us OpenDocument Spreadsheet format which you can save as .ODS.
Hope this helps.


text:
Q: When is it ok to use a JS redirect? I am currently working on a site where an offer on a specific set of knife has just finished. I have therefore been asked to create a JS redirect and canonical link from this page to a page that lists all the knives that we sell for SEO purposes.
I personally don't think think that this is the correct use of a JS redirect or canonical link, what does anyone else think?
P.S. I am unable to create 301 or 302 redirects at the moment.

A: I would say JS is pretty much never the best way to do a redirect – whether or not it's "okay" is really subjective, and depends on the needs and goals of your project.
If I were in your position, my first choice would be to try to explain why JS is a poor choice (no ability to do 301/302, won't work for users without JS, search engines won't know about it, etc.). If management or your client understands the drawbacks and still wants to use JS, then that's fine. I think you've done your job by presenting options and explaining the pros and cons.

A: I'm not expert on SEO and cannot tell you which solution is better for search engine ranking, but with user experience in mind, the user has entered a URL for a specific knife offer, so the best way is to show the user that this offer is expired so they know what happened to the resource they are looking for. You can show some relevant offers (and give user the option to visit list of knife offers) or redirect automatically to knife section root after a few seconds, although I prefer the former. I also do not think a canonical link is correct here as the two URLs are clearly for two different resources (one is for a specific knife set, the other for all knife sets).

A: It's ok to use JS redirects when you want to redirect an url with an #anchor. Because there is no other way you can redirect such a link, a serverside redirect ignores the #anchor.
So I found a JS redirect script which we used to redirect this link to a new page (you can see the redirect in action here) → https://www.nationaleberoepengids.nl/onderwijsassistent#salaris
Since 2019 Google seems to follow these clientside JS redirects, you can find it in this Google video → https://www.youtube.com/watch?v=_SDIN0KiQp4


text:
Q: Get minX, maxX, minY, maxY from multidimensional array I have an array like this
var my_array = [
  [3,9],
  [1,5],
  [7,2],
  [5,4]
 ]

As you can see my_array is a multidimensional array that includes in this case 4 different arrays.
All of the arrays are x/y-coordinates ([3,9] ---> X: 3, Y: 9) and I'd like to move the arrays of the array with ...

*

*the biggest X value,

*the biggest Y value,

*the smallest X value,

*the smallest Y value

... to an object like this:
var my_object = {
  "minX": [1,5],
  "maxX": [7,2],
  "minY": [7,2],
  "maxY": [3,9]
}

The function I've created you can find below, but my function is just returning the listed values from above instead of returning the full array. So my current (wrong) result looks like this:
var wrong_object = {
  "minX": 1, // missing 5
  "maxX": 7, // missing 2
  "minY": 2, // missing 7
  "maxY": 9  // missing 3
}

var my_array = [
  [3, 9],
  [1, 5],
  [7, 2],
  [5, 4]
]

var extreme_result = {}
extreme_result.minX = Math.min.apply(Math, my_array.map(function(i) {
  return i[0]
}));
extreme_result.maxX = Math.max.apply(Math, my_array.map(function(i) {
  return i[0]
}));
extreme_result.minY = Math.min.apply(Math, my_array.map(function(i) {
  return i[1]
}));
extreme_result.maxY = Math.max.apply(Math, my_array.map(function(i) {
  return i[1]
}));

console.log(extreme_result)

I hope somebody can help me with this problem.
Thanks in advance, Greetings Pete

A: This sorts the array and grabs the first and last elements for the smallest and largest objects.

var my_array = [
  [3, 9],
  [1, 5],
  [7, 2],
  [5, 4]
];

my_array.sort(function(a, b){ return a[0] - b[0]; });
var minX = my_array[0];
var maxX = my_array[my_array.length - 1];
my_array.sort(function(a, b){ return a[1] - b[1]; });
var minY = my_array[0];
var maxY = my_array[my_array.length - 1];

console.log(JSON.stringify({
  minX: minX,
  maxX: maxX,
  minY: minY,
  maxY: maxY
}));

A: function findExtremes( array ){
  let maxX = array[0],
       maxY = array[0],
       minX = array[0],
       minY = array[0];

  for(const [x,y] of array){
    if(x < minX[0]) minX = [x,y];
    if(x > maxX[0]) maxX = [x,y];

    if(y > minY[1]) minY = [x,y];
    if(y < maxY[1]) maxY = [x,y];
  }

  return {maxX, maxY, minX, minY};
}

This is O(n) ...

A: If you don't mind using es6, you can do something like this:

const my_array = [
  [3,9],
  [1,5],
  [7,2],
  [5,4],
];

const results = {
  xMax: Math.max(...my_array.map(e => e[0])),
  xMin: Math.min(...my_array.map(e => e[0])),
  yMax: Math.max(...my_array.map(e => e[1])),
  yMin: Math.min(...my_array.map(e => e[1]))
}

const points = {
  xMax: my_array.filter(e => e[0] === results.xMax),
  xMin: my_array.filter(e => e[0] === results.xMin),
  yMax: my_array.filter(e => e[1] === results.yMax),
  yMin: my_array.filter(e => e[1] === results.yMin)
}

console.log(points);

EDIT:
Sorry, I misread the question. Edit the answer above.

A: I would accomplish this by comparing in a forEach rather than mapping, sorting or whatever.

let my_array = [
  [3, 9],
  [1, 5],
  [7, 2],
  [5, 4]
]

let extreme_result = {
  minX: my_array[0],
  minY: my_array[0],
  maxX: my_array[0],
  maxY: my_array[0]
};

my_array.forEach( (el) => {

  if ( extreme_result.minX[0] > el[0] ) {
    extreme_result.minX = el;
  } else if ( extreme_result.maxX[0] < el[0] ) {
    extreme_result.maxX = el;
  }

  if ( extreme_result.minY[1] > el[1] ) {
    extreme_result.minY = el;
  } else if ( extreme_result.maxY[1] < el[1] ) {
    extreme_result.maxY = el;
  }

});

console.info(extreme_result);

A:

var my_array = [
    [3, 9],
    [1, 5],
    [7, 2],
    [5, 4]
];
let extreme_result={};
extreme_result.MinX=my_array.reduce(function(a,b){
    if(a[0]<b[0]){
        return a;
    }
    else{
        return b;
    }
});
extreme_result.MinY=my_array.reduce(function(a,b){
    if(a[1]<b[1]){
        return a;
    }
    else{
        return b;
    }
});
extreme_result.MaxX=my_array.reduce(function(a,b){
    if(a[0]>b[0]){
        return a;
    }
    else{
        return b;
    }
});
extreme_result.MaxY=my_array.reduce(function(a,b){
    if(a[1]>b[1]){
        return a;
    }
    else{
        return b;
    }
});
console.log(extreme_result);


text:
Q: Is it possible to increase the resolution of an image without expensive software? Is it possible to increase the resolution of an image (or increase the quality of an image) using some simple software or process? If yes, how might I go about it?

A: As Mike says, you can only work with the information that already exists in the graphic file, but that doesn't mean you can't increase the resolution, merely that you will have to make some trade-offs to do it. sometimes you are given an image that doesn't have the resolution needed for the purpose at hand, but have no choice in the matter. In those cases you can use the software like the one linked above (which increases the pixel count and averages the original pixels on either side) to reduce the apparent amount of blurriness to some extent. Then use existing techniques that can be found elsewhere on the web to increase sharpness and make the image appear sharper than it actually is. The result will definitely be less effective than using an image of the proper resolution, but might bring the image you are stuck with at least into the realm of usability.
Mike, I was taught the same absolutes as you, but sometimes it pays to step back from the instinctive, knee-jerk reactions, and check a little deeper. This is where learning and growing as a craftsman occurs.

A: There's a nice online one here http://waifu2x.udp.jp/ which uses "Deep Convolutional Neural Networks". It's especially good for enlarging logos and line art.

A: Yes.
Something like this: SmillaEnlarger
Will do it without just making a blurry mess too. There are other fractal enlargers out there which try to mimic missing detail - but this one is free.

A: This little free ware utility http://sourceforge.net/projects/imageenlarger/ does a good job of enlarging without the usual jaggies you get.  The interface isn't the most intuitive but if you can work it out it does the job.

A: Yes.  Almost any photo editing software will do this for you.  Some free ones:
MSPaint - built into Windows
Paint.net
Gimp

A: Sorry everyone - but you CAN NOT increase resolution on something.
Why do people think you can? If the information is not there in the image - how is photoshop or something going to find it and add it in???? IT CAN'T.
It's a  give and take relationship that resolution and physical size have.
You got something at 8.5x11 (physical) and 300dpi - you blow it up to 14x16 - guess what, it's going to be way less than 300dpi not matter what you try to increase. Vice versa it will work great. Basically You can take away but you can't add to. That's the real truth. Do your tests and prove it to yourself.
Don't answer questions you don't understand. All these "experts" out there. Just cause you own a toothbrush, doesn't make you a dentist.
Again - something that is 72dpi at 7inches will most likely be around 37dpi at 14inches. Give and take. Start your original as high as you can (be it a scan or photo) and keep it b/c that's as large and as good looking as it will ever be.

A: YES YOU CAN!  I used GIMP and its free.

*

*Open up a NEW project and set the dimensions you need, then use a pixel size of like 300x300 (no less)

*Open up the image you want as a LAYER and match the size of the original canvas (above).
DONE!!!
I guess I should get my dentists license now.


text:
Q: docker network not working without link I have a mysql container and a service container that needs to connect to the mysql container.
I created a networking with docker network create chrisbolton
I am spinning up the mysql container with
docker run --name chrisbolton-mysql -v /Users/Bolton/chrisbolton-data:/var/lib/mysql --network chrisbolton -e MYSQL_ROOT_PASSWORD=password -e MYSQL_DATABASE=chrisbolton -d mysql:latest
I am spinning up the service container with
docker run -p 8080:8080 --name chrisbolton-service --network chrisbolton --link chrisbolton-mysql:mysql -d chrisbolton-service
However, I know that link is deprecated and I need to move to only using networks. But if I remove the link here the two containers cannot communicate.
I am connecting to mysql with the following config:
#disbale Spring banner
spring.main.banner-mode=off

spring.datasource.url=jdbc:mysql://mysql:3306/chrisbolton
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

I have done a docker network inspect chrisbolton to get the IPAddresses and have tried changing my config file to point to that directly. But still not sure why it won't connect.

A: datasource.url is not correct, you should specify the name of the container to which you want to connect. There are better options than using the name of service. You can use aliases or hostname.
While in this case, as you indicated in comments, datasource.url needs to be jdbc:mysql://chrisbolton-mysql:3306/chrisbolton


text:
Q: examine the convergence of the series $\sum_{n=0}^{\infty} \frac{(-1)^n}{n+(-1)^{n+1}}$ I have no idea how to examine the convergence of the series:
$$\sum_{n=0}^{\infty} \frac{(-1)^n}{n+(-1)^{n+1}}$$
We can see that $\frac{(-1)^n}{n+(-1)^{n+1}} \to 0$.
However we can't use criterium Leibniz and Dirichlet because of the fact that $\frac{1}{n+(-1)^{n+1}}$ is not monotonic.
The only thing that it is easy to check is that this series is not absolutely convergent:
$$\left| \frac{(-1)^n}{n+(-1)^{n+1}}\right|=\frac{1}{n+(-1)^{n+1}}\ge \frac{1}{n+1}$$

A: Hint. One may recall the Taylor series expansion, as $x \to 0$,
$$
\frac1{1-x}=1+x+O(x^2)
$$ giving, as $n \to \infty$,
$$
\frac{(-1)^n}{n+(-1)^{n+1}}=\frac{(-1)^n}n\frac{1}{1-\frac{(-1)^{n}}n}=\frac{(-1)^n}n+\frac1{n^2}+O\left( \frac1{n^3}\right)
$$ then, there exists some $n_0\ge1$ such that for all $N\ge n_0$, one has
$$
\sum_{n= n_0}^N\frac{(-1)^n}{n+(-1)^{n+1}}=\sum_{n= n_0}^N\frac{(-1)^n}n+\sum_{n= n_0}^N\frac1{n^2}+\sum_{n= n_0}^NO\left( \frac1{n^3}\right)
$$ leading to the convergence of the initial series by letting $N \to \infty$.

A: If $a_n\to 0$ then $\sum_{k=0}^{\infty} a_n$ converges if and only the series:
$$\sum_{k=0}^{\infty} (a_{2k}+a_{2k+1})$$ converges.
In your case, $a_{n}=\frac{(-1)^{n}}{n+(-1)^{n+1}}$, and $$a_{2k}+a_{2k+1}=\frac{1}{2k-1}-\frac{1}{2k+2}=\frac{3}{(2k-1)(2k+2)}$$
Use comparison test to show that $\sum \frac{3}{(2k-1)(2k+2)}$ converges, and hence your original series converges.


text:
Q: Configure Flink use S3 checkpoint with WebIdentityTokenCredentialsProvider I am running my flink cluster in EKS, and I need to use the WebIdentityTokenCredentialsProvider for authentication. According to the doc, there are 2 approaches:
Presto
I tried setting up this in flink conf:
presto.s3.credentials-provider: com.amazonaws.auth.WebIdentityTokenCredentialsProvider

but it shows error:
Caused by: java.lang.NoSuchMethodException: com.amazonaws.auth.WebIdentityTokenCredentialsProvider.<init>(java.net.URI, org.apache.hadoop.conf.Configuration)
    at java.lang.Class.getConstructor0(Class.java:3082) ~[?:1.8.0_292]
    at java.lang.Class.getConstructor(Class.java:1825) ~[?:1.8.0_292]
    at com.facebook.presto.hive.s3.PrestoS3FileSystem.getCustomAWSCredentialsProvider(PrestoS3FileSystem.java:845) ~[?:?]
    at com.facebook.presto.hive.s3.PrestoS3FileSystem.createAwsCredentialsProvider(PrestoS3FileSystem.java:833) ~[?:?]
    at com.facebook.presto.hive.s3.PrestoS3FileSystem.initialize(PrestoS3FileSystem.java:244) ~[?:?]
    at org.apache.flink.fs.s3.common.AbstractS3FileSystemFactory.create(AbstractS3FileSystemFactory.java:123) ~[?:?]
    at org.apache.flink.core.fs.PluginFileSystemFactory.create(PluginFileSystemFactory.java:62) ~[flink-dist_2.12-1.14.5.jar:1.14.5]
    at org.apache.flink.core.fs.FileSystem.getUnguardedFileSystem(FileSystem.java:508) ~[flink-dist_2.12-1.14.5.jar:1.14.5]
    at org.apache.flink.core.fs.FileSystem.get(FileSystem.java:409) ~[flink-dist_2.12-1.14.5.jar:1.14.5]
    at org.apache.flink.core.fs.Path.getFileSystem(Path.java:274) ~[flink-dist_2.12-1.14.5.jar:1.14.5]
    at org.apache.flink.runtime.state.filesystem.FsCheckpointStorageAccess.<init>(FsCheckpointStorageAccess.java:64) ~[flink-dist_2.12-1.14.5.jar:1.14.5]
    at org.apache.flink.runtime.state.storage.FileSystemCheckpointStorage.createCheckpointStorage(FileSystemCheckpointStorage.java:323) ~[flink-dist_2.12-1.14.5.jar:1.14.5]
    at org.apache.flink.runtime.checkpoint.CheckpointCoordinator.<init>(CheckpointCoordinator.java:321) ~[flink-dist_2.12-1.14.5.jar:1.14.5]
    at org.apache.flink.runtime.checkpoint.CheckpointCoordinator.<init>(CheckpointCoordinator.java:240) ~[flink-dist_2.12-1.14.5.jar:1.14.5]
    at org.apache.flink.runtime.executiongraph.DefaultExecutionGraph.enableCheckpointing(DefaultExecutionGraph.java:452) ~[flink-dist_2.12-1.14.5.jar:1.14.5]
    at org.apache.flink.runtime.executiongraph.DefaultExecutionGraphBuilder.buildGraph(DefaultExecutionGraphBuilder.java:315) ~[flink-dist_2.12-1.14.5.jar:1.14.5]
    at org.apache.flink.runtime.scheduler.DefaultExecutionGraphFactory.createAndRestoreExecutionGraph(DefaultExecutionGraphFactory.java:107) ~[flink-dist_2.12-1.14.5.jar:1.14.5]
    at org.apache.flink.runtime.scheduler.SchedulerBase.createAndRestoreExecutionGraph(SchedulerBase.java:335) ~[flink-dist_2.12-1.14.5.jar:1.14.5]
    at org.apache.flink.runtime.scheduler.SchedulerBase.<init>(SchedulerBase.java:191) ~[flink-dist_2.12-1.14.5.jar:1.14.5]
    at org.apache.flink.runtime.scheduler.DefaultScheduler.<init>(DefaultScheduler.java:140) ~[flink-dist_2.12-1.14.5.jar:1.14.5]
    at org.apache.flink.runtime.scheduler.DefaultSchedulerFactory.createInstance(DefaultSchedulerFactory.java:134) ~[flink-dist_2.12-1.14.5.jar:1.14.5]
    at org.apache.flink.runtime.jobmaster.DefaultSlotPoolServiceSchedulerFactory.createScheduler(DefaultSlotPoolServiceSchedulerFactory.java:110) ~[flink-dist_2.12-1.14.5.jar:1.14.5]
    at org.apache.flink.runtime.jobmaster.JobMaster.createScheduler(JobMaster.java:346) ~[flink-dist_2.12-1.14.5.jar:1.14.5]
    at org.apache.flink.runtime.jobmaster.JobMaster.<init>(JobMaster.java:323) ~[flink-dist_2.12-1.14.5.jar:1.14.5]
    at org.apache.flink.runtime.jobmaster.factories.DefaultJobMasterServiceFactory.internalCreateJobMasterService(DefaultJobMasterServiceFactory.java:106) ~[flink-dist_2.12-1.14.5.jar:1.14.5]
    at org.apache.flink.runtime.jobmaster.factories.DefaultJobMasterServiceFactory.lambda$createJobMasterService$0(DefaultJobMasterServiceFactory.java:94) ~[flink-dist_2.12-1.14.5.jar:1.14.5]
    at org.apache.flink.util.function.FunctionUtils.lambda$uncheckedSupplier$4(FunctionUtils.java:112) ~[flink-dist_2.12-1.14.5.jar:1.14.5]
    at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1604) ~[?:1.8.0_292]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[?:1.8.0_292]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[?:1.8.0_292]

As a result, I am using the fall back hadoop solution:
Hadoop
However, with Hadoop, I am able to successfully authenticate, but it always write 0 length data to checkpoint, I don't really find an error. There's only a WARNING in the log
2022-10-05 17:24:34,285 INFO  org.apache.flink.runtime.checkpoint.CheckpointCoordinator    [] - Checkpoint 1 of job 1a68f74acf0ccf403693e2f228fa62a6 expired before completing.
 2022-10-05 17:24:34,287 WARN  org.apache.flink.runtime.checkpoint.CheckpointFailureManager [] - Failed to trigger or complete checkpoint 1 for job 1a68f74acf0ccf403693e2f228fa62a6. (0 consecutive failed attempts so far)
 org.apache.flink.runtime.checkpoint.CheckpointException: Checkpoint expired before completing.
     at org.apache.flink.runtime.checkpoint.CheckpointCoordinator$CheckpointCanceller.run(CheckpointCoordinator.java:2000) [flink-dist_2.12-1.14.5.jar:1.14.5]
     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [?:1.8.0_292]
     at java.util.concurrent.FutureTask.run(FutureTask.java:266) [?:1.8.0_292]
     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) [?:1.8.0_292]
     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) [?:1.8.0_292]
     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [?:1.8.0_292]
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [?:1.8.0_292]
     at java.lang.Thread.run(Thread.java:748) [?:1.8.0_292]

I've also follow some suggestion found on google by setting parallelism to 1 but that is not help at all.
Ideally It would be nice to use presto, but for now, I am okay with either approach that would help on the checkpoint issue.  Thanks!

A: There are actually separate issues:
For s3a
The reason why it is not writing the checkpoint is because I am using Apache Beam portable runner, and the --checkpointing_interval is default to -1 , which means checkpointing is disabled. After setting this to a non zero value, the issue is fixed.
For s3p
Thanks vignesh kumar kathiresan on flink slack channel!
The solution is to configure
presto.s3.use-instance-credentials: "false"

and use the DefaultAWSCredentialsProviderChain (the default settings), The DefaultAWSCredentialsProviderChain will try multiple potential providers and WebIdentityTokenCredentialsProvider is one of it and will be picked up.
This works for me given that I have all my AWS configured correctly.  But for people who starts from fresh, Besides the s3 permission, you would also need kms:GenerateDataKey, kms:Decryptas well.


text:
Q: bash: sort files by a number inside them I need to generate 100 .txt files with a random number inside each one of them. Then I need to rename the files so that the file names are named from 1.txt to 100.txt in ascending order based on the value that is stored inside each file. The file named 1.txt should have the smallest number stored in it and the file named 100.txt shouild have the largest number stored in it
I tried this code:
#!/bin/bash
for i in $(seq 1 100)
do
echo $RANDOM > ${i}.txt
done
cat *.txt | sort

A: Make a new directory and name the directory whatever name you choose. Change directories with cd to the new directory that you made, so that all of the files that are created by the shell script will be created inside the new directory and only these newly created files will be renamed. Then run the following shell script.
#!/bin/bash
for i in $(seq 1 100)
do
echo $RANDOM > ${i}.txt # Put a random number inside each file.
mv ${i}.txt $(head -1 ${i}.txt).txt # Rename the files.
done
ls *.txt | sort -n # Sort the files in ascending order.

Your question is ambiguous because I could also rename the files in ascending order with new names that range from 1.txt to 100.txt.
If that's how your want the files to be renamed use this shell script instead.
#!/bin/bash
for i in $(seq 1 100)
do
echo $RANDOM > ${i}.txt # put a random number inside each file
mv ${i}.txt $(head -1 ${i}.txt).txt # rename files
done
# ls *.txt | sort -n # I commented out this line and added a new line after it.
i=1; for filename in `ls *.txt | sort -n`; do mv "$filename" "$((i++)).txt"; done

A: You could first generate all your random numbers, and then sort them before writing them to the files:
for i in {1..100}; do
    echo $RANDOM
done \
| sort -n \
| while read n; do
     (( x+=1 ))
     echo "$n" > "$x.txt"
  done

Or the same as a one-liner:
for i in {1..100}; do echo $RANDOM; done | sort -n | while read n; do (( x+=1 )); echo "$n" > "$x.txt"; done

Note also that to have sort sort strings of numbers numerically, you need its --numeric-sort (or -n) option.


text:
Q: C++ fstream << and >> operators with binary data I've always read and been told that when dealing with binary files that one should use read() and write() as opposed to the << and >> operators as they are meant for use with formatted data.  I've also read that it is possible to use them, but it is an advanced topic, which I can't find where anyone dives into and discusses.
I recently saw some code which did the following:

 std::ifstream file1("x", ios_base::in | ios_base::binary);
 std::ofstream file2("y", ios_base::app | ios_base::binary);

 file1 << file2.rdbuf();

When I pointed out the use of the << operator with the binary file, I was told that the rdbuf() call returns a streambuf * and that << overloads the streambuf* and does a direct copy with no formatting and is thus safe.
Is this true and also safe?  How about efficiency?  Any gotchas?  Details would be much appreciated.
Thanks!

A: Yes (see 27.6.2.5.3/6 where the overload of << for streambuf is described).

A: It's entirely safe and a reasonable way to copy streams.
Note that it also allows stuff like:
std::ifstream file_in1("x1", ios_base::in | ios_base::binary);
std::ifstream file_in2("x2", ios_base::in | ios_base::binary);
std::ofstream file_out("y", ios_base::app | ios_base::binary);

file_out << file_in1.rdbuf() << "\nand\n" << file_in2.rdbuf();

A: In § 27.7.3.6.3 of the C++ standard, it's mentioned that
basic_ostream<charT,traits>& operator<<
(basic_streambuf<charT,traits>* sb);
Effects: Behaves as an unformatted output function (as described in 27.7.3.7, paragraph 1).
 § 27.7.3.7 describes "unformatted input" which is basically a binary copy.  This means that "unformatted" ostream functions are safe for binary data.  The other "unformatted" functions mentioned in the standard that I can find are put, write and (officially) flush.


text:
Q: Grouping posts by day and user in Django I have a Post model in Django that looks like this:
class Post(models.Model):
post = models.TextField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now=True)

I would like to sort and display posts per day per user. So if one user made 20 posts on Monday and another made 15 posts on Tuesday and 4 on Wednesday they would be grouped together and displayed. I don't need the total count of posts per user or day just a way to separate all posts made per day by user to display them together.
Example (would like to display on one page):
Monday: user 1: post1, post2, post2. user 2: post1 post2, post3, post4, post5. Tuesday: user2: post1, post2, post3. user3: post1, post 2....for all posts and users
I've tried posts = Post.objects.all().order_by('-timestamp','user') it displays all posts but I can't figure out how to group the post by user per day.

A: You should order by truncated date first, and then by user, and then later by timestamp, for results to be always the same. No ordering of posts may change order of them in unpredictable manner. Like this:
posts = Post.objects.all().order_by(TruncDate('timestamp').desc(),'user','timestamp')

A: I figured it out. I needed to nest regroup. The following code works. This took me two days to figure out.

{% regroup posts by timestamp|date as date_list %}
{% for time in date_list %}
    {% regroup time.list by user as user_list %}
        {% for user in user_list %}

@{{user.grouper}}

{{ time.grouper}}

            {% for x in user.list %}

{{ x.post}}

            {% endfor %}

        {% endfor %}

{% endfor %}


text:
Q: Deserialize variable saved on GPU on GPU I saved the parameter variable on my computer (equipped with GPU and CUDA). The weights were saved with the GPU mode. Then when attempting to load the weights on the same computer, I still get an error:
RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location='cpu' to map your storages to the CPU.

The issue is related to the fact that torch.cuda.is_available() returns False.
The issue disappears after restarting the computer but then reappears after some time.

A: Try adding map_location argument to torch.load, i.e.,modify your code
from torch.load(model_weights)
to torch.load(model_weights, map_location=torch.device('cuda:0'))


text:
Q: How to typeset a math proof in beamer that displays line by line I'd like to display a step-by-step proof of a mathematics result. I want to have steps following other steps inside amsmath's align environment, except I want to \pause the slide after each line in the proof, i.e. show one step at a time so that my students do not get distracted or confusing looking ahead in a slide.
\documentclass{beamer}

\usepackage[protrusion,expansion,kerning,tracking,spacing]{microtype}

\usepackage[utf8]{inputenc}

\usepackage{multicol}

\usepackage{framed}

\usepackage{amsmath,amssymb,amsfonts}
\usepackage[T1]{fontenc}

\usepackage{xcolor}
\microtypecontext{spacing=nonfrench}
\nonfrenchspacing

\usetheme{Berkeley}

\usefonttheme{serif}

\begin{document}
    \section{Example 1}
    \begin{frame}[allowframebreaks]{\(u\)-substitution example}
        \begin{framed}
            Find the antiderivative of the function defined by \(f(x) = \frac{x}{\sqrt{x^2 + 4}}\).
        \end{framed}

        \begin{align}
            \intertext{Introduce the auxiliary variable $u$.}
            u &= x^2 + 4\\
            \intertext{Differentiate with respect to $x$.}
            \frac{du}{dx} &= 2x\\
            \intertext{Multiply through by the differential.}
            du &= 2x\,dx\\
            \intertext{Substitute $u$ into $f$.}
            f(x) &= \frac{x}{\sqrt{u}}\\
            \intertext{Substitute into antiderivative expression.}
            \int f(x)\,dx &= \int \frac{x}{\sqrt{u}}\,dx\\
            \intertext{Extract a constant.}
            &= \frac{1}{2}\int \frac{2x}{\sqrt{u}}\,dx
            \intertext{Rewrite differential in terms of $u$.}
            &= \frac{1}{2}\int \frac{1}{\sqrt{u}}\left(2x\,dx\right)\\
            &= \frac{1}{2}\int \frac{1}{\sqrt{u}}\,du
            \intertext{Apply the power rule for indefinite integration.}
            &= \frac{1}{2}\int u ^ {-\frac{1}{2}}\,du\\
            &= \frac{1}{2}\frac{\sqrt{u}}{1/2} + C\\
            &= \sqrt{u} + C
            \intertext{Substitute $u$.}
            \int f(x)\,dx &= \sqrt{x^2 + 4} + C
        \end{align}
    \end{frame}
\end{document}

A: You can use \uncover<x-y>, most probably \uncover<+-> (i.e., "uncover from here on") freely. It doesn't affect formatting in any way. Just make sure you don't introduce spurious spaces (the line end is a space for (La)TeX, unless the line ends with a comment started with %, spaces after a "protected" line end are ignored). E.g. I'd write something like:
\uncover<+->{%
   This is a step in my proof%
}%
\uncover<+->{%
   , continued here.
}

This way there is no stray space before the comma.

A: I am not certain I understand the question.  It does not look as though the proof will fit on one slide, but put the second line you want as the argument of \uncover<2->{.....} and the third as the argument of \uncover<3->{...} and so on.  Here is an actual frame from a talk I gave recently:
\begin{frame}{Some properties of $G$ and $K$}

\begin{itemize}[<+->]

\item\hiblue{$G(D)$ is a subring of the perfect closure of the field of
fractions of $D$.}

\item\hiblue{The inner adjunction $R\to K(R)$ is an injection.}

\item\hiblue{The inner adjunction $R\to K(R)$ is epic in semiprime
rings.}

\item\hiblue{The induced $\spec(K(R))\to\spec(R)$ is a bijection.}

\end{itemize}

\uncover<5->{\hired{$K$ is {\bf domain reflective} if it takes
domains to domains.}}

\uncover<6->{$K_\fld$ is not domain reflective.}

\end{frame}

The first four items were also displayed one by one.