text:
Q: Emberjs/data Object "has no method '_create'" I am trying to use Ember and Ember/Data to display simple JSON returned from REST API.
Here is my js:
window.ManageClients = Em.Application.create();

ManageClients.store = DS.Store.create({
  revision: 4,
  adapter: DS.RESTAdapter.create({
    bulkCommit: false,
    namespace: "api"
  })
});

ManageClients.Client = DS.Model.extend({
  url: '/clients',
  name: DS.attr('string'),
  slug: DS.attr('string'),
  programs: DS.attrArray('string'),
  selfserve: DS.attrArray('string')
});

ManageClients.Clients = ManageClients.store.findAll(ManageClients.Client);

ManageClients.ClientsView = Em.View.create({
  templateName: 'client-template'
});

ManageClients.ClientsView.appendTo('#ManageClients');

My template:

Errors:
Uncaught TypeError: Object ManageClients.Client has no method '_create' ember-data.js:1811
DS.Store.Ember.Object.extend.materializeRecord ember-data.js:1811
DS.Store.Ember.Object.extend.findByClientId ember-data.js:1204
DS.RecordArray.Ember.ArrayProxy.extend.objectAtContent ember-data.js:45
Ember.wrap.newFunc ember.js:949
Ember.ArrayProxy.Ember.Object.extend.objectAt ember.js:9204
Ember.wrap.newFunc ember.js:949
Ember.Array.Ember.Mixin.create.arrayContentDidChange ember.js:6946
Ember.ArrayProxy.Ember.Object.extend.arrangedContentArrayDidChange ember.js:9227
invokeAction ember.js:3174
iterateSet ember.js:3156
sendEvent ember.js:3273
Ember.Array.Ember.Mixin.create.arrayContentDidChange ember.js:6941
Ember.Mixin.create.replace ember.js:9616
Ember.MutableArray.Ember.Mixin.create.insertAt ember.js:7410
Ember.MutableArray.Ember.Mixin.create.pushObject ember.js:7458
DS.Store.Ember.Object.extend.updateRecordArray ember-data.js:1618
DS.Store.Ember.Object.extend.updateRecordArrays.manyArrays ember-data.js:1586
DS.Store.Ember.Object.extend.updateRecordArrays ember-data.js:1584
DS.Store.Ember.Object.extend.load ember-data.js:1744
DS.Store.Ember.Object.extend.loadMany ember-data.js:1763
DS.RESTAdapter.DS.Adapter.extend.findAll.ajax.success ember-data.js:4580
f.Callbacks.o jquery-1.7.2.min.js:2
f.Callbacks.p.fireWith jquery-1.7.2.min.js:2
w jquery-1.7.2.min.js:4
f.support.ajax.f.ajaxTransport.send.d

And:
Uncaught TypeError: Object ManageClients.Client has no method '_create' ember-data.js:1811
DS.Store.Ember.Object.extend.materializeRecord ember-data.js:1811
DS.Store.Ember.Object.extend.findByClientId ember-data.js:1204
DS.RecordArray.Ember.ArrayProxy.extend.objectAtContent ember-data.js:45
Ember.wrap.newFunc ember.js:949
Ember.ArrayProxy.Ember.Object.extend.objectAt ember.js:9204
Ember.wrap.newFunc ember.js:949
Ember.CollectionView.Ember.ContainerView.extend.arrayDidChange ember.js:14651
Ember.CollectionView.Ember.ContainerView.extend._contentDidChange ember.js:14582
Ember.CollectionView.Ember.ContainerView.extend.init ember.js:14553
Ember.wrap.newFunc ember.js:949
Ember._Metamorph.Ember.Mixin.create.init ember.js:18038
Ember.wrap.newFunc ember.js:949
Class ember.js:8259
Ember.Mixin.create.create ember.js:8398
Ember.View.Ember.Object.extend.createChildView ember.js:13320
Ember.View.states.inBuffer.appendChild ember.js:13762
Ember.View.Ember.Object.extend.invokeForState ember.js:12402
Ember.View.Ember.Object.extend.appendChild ember.js:13199
EmberHandlebars.ViewHelper.Ember.Object.create.helper ember.js:18873
(anonymous function) ember.js:19030
(anonymous function) ember.js:19229
(anonymous function) ember.js:19366
(anonymous function)
(anonymous function) handlebars.js:1879
Ember.View.Ember.Object.extend.render ember.js:12368
Ember.View.Ember.Object.extend.renderToBuffer ember.js:13017
Ember.View.Ember.Object.extend.createElement ember.js:12814
Ember.View.states.preRender.insertElement ember.js:13702
Ember.View.Ember.Object.extend.invokeForState ember.js:12402
invoke ember.js:3377
iter ember.js:3424
RunLoop.flush ember.js:3480
RunLoop.end ember.js:3396
Ember.run.end ember.js:3588
autorun

A: This error has been addressed in later versions of ember and is no longer relevant.


text:
Q: How can i support different measurements for screens in android I basically want to accomplish an adequate size of my layouts depending on the screen size of the device. I am using dp as unit, but it doesn't seem to work. How can i do that?

A: For sure dp is the most adequat unit to accomplish that goal. There in addition to that, you have to define several values folders where you define dimensions for scaling tablets or phones. E.g. define two values folders like:
values-large
   values-xlarge
Now define a dimen.xml file inside this folders, where you can put your measurements in (unit dp) for the corresponding screensize. Define a measurement like this:
17dp
Then embedd this sizes in your layout xml, like:
android:layout_height="@dimen/value1"
Depending on the screensize, the system will load the correct measurements from this folders, e.g. if you have a screen size large only the defined values in folder values-large will be loaded. For more information, also have a look at https://developer.android.com/distribute/essentials/quality/tablets.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jquery trigger click event not working for a P element Im trying to "make a para (in a div) editable and automatically show cursor in para" when clicked on edit icon. The para does becomes editable but cursor stays with the edit icon. I've read almost all answers regarding click event on SO, nothing helped.
This is my code
JS:
//Add a icon in para containing div when hover on div
$(document).on('mouseenter', '.editable', function () {
    $(this).append('')
})

//Make para content editable and show cursor in para
$(document).on('mousedown touchdown', '.edit-content-icon', function (e) {
    $(this).prev('p').prop('contentEditable', 'true')
    $(this).prev('p').click()
})

HTML:

My Para...


text:
Q: Imports in node js im extremely new to node js.
When you use an import statement in node js, what is the search algorithm like?
So here the person is importing React from 'react'
Does it first look in the node_modules folder always?
What if i had an alternative folder in the same level as node_modules containing react module?
Thanks

A: The resolving algorithm is described in the book Node.js Design Pattern here.

The resolving algorithm can be divided into the following three major
branches:
File modules: If moduleName starts with "/" it's considered
already an absolute path to the module and it's returned as it is. If
it starts with "./", then moduleName is considered a relative path,
which is calculated starting from the requiring module.
Core modules: If moduleName is not prefixed with "/" or "./", the
algorithm will first try to search within the core Node.js modules.
Package modules: If no core module is found matching moduleName, then
the search continues by looking for a matching module into the first
node_modules directory that is found navigating up in the directory
structure starting from the requiring module. The algorithm continues
to search for a match by looking into the next node_modules directory
up in the directory tree, until it reaches the root of the filesystem.


text:
Q: LINQ Expression to get member value and can be translated to SQL? I have a complex query where certain DateTime members of a model entity are being used multiple times, but not always the same members. I'd like to know if I can put the "getting" of the member in an Expression, so I don't have to repeat that piece of code.
A simplified version of my current code looks like this:
var getTargetDate = ((Expression<Func<Order, DateTime>>)(o => o.OrderDate)).Compile();
if (delivery)
    getTargetDate = ((Expression<Func<Order, DateTime>>)(o => o.DeliveryDate)).Compile();

return orders.Where(o => getTargetDate(o) >= fromDate && getTargetDate(o) < toDate);

This code compiles, but gives me the runtime Exception:

Exception thrown: 'System.NotSupportedException' in System.Data.Linq.dll
Additional information: Method 'System.Object DynamicInvoke(System.Object[])' has no supported translation to SQL.

Is there a way to put the "getting" of the DateTime in a variable or method that can be translated to SQL?

A: This does not literally answer the question, but it does provide a way around the code duplication posed in it.
Put the desired member and the entity itself in an anonymous object, perform the relevant part of the original query on the member, then select out the original entity:
orders = orders.Select(o => new { o,
    TargetDate = delivery ? o.DeliveryDate : o.OrderDate
})
.Where(o => o.TargetDate >= fromDate && o.TargetDate < toDate)
.Select(o => o.o);


text:
Q: Flask app not connecting to the port I'm following the Flask Web Development Tutorial by Miguel Grinberg, and I've copied this code
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
    return '
Hello World!
'
if __name__ == '__main__':
    app.run(debug=True)

And on Jupyter I get this result:
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
An exception has occurred, use %tb to see the full traceback.
SystemExit: 1
If I open http://127.0.0.1:5000/ the page is just loading forever, same thing if I run the code on the Powershell (but without giving the error).
I've tried to look for similar questions but I wasn't able to find something, can you please tell me what I'm doing wrong and what I can do to solve the problem? Thanks in advance.
EDIT:
As Mariusz asks, here there is the error I get by add %tb at the beginning of the cell:
SystemExit                                Traceback (most recent call last)
<ipython-input-4-5757c6364c65> in <module>()
      8     return '
Hello World!
'
      9 if __name__ == '__main__':
---> 10     app.run(debug=True)

C:\Users\Antonio\Anaconda3\lib\site-packages\flask\app.py in run(self, host, port, debug, **options)
    841         options.setdefault('passthrough_errors', True)
    842         try:
--> 843             run_simple(host, port, self, **options)
    844         finally:
    845             # reset the first request information if the development server

C:\Users\Antonio\Anaconda3\lib\site-packages\werkzeug\serving.py in run_simple(hostname, port, application, use_reloader, use_debugger, use_evalex, extra_files, reloader_interval, reloader_type, threaded, processes,     request_handler, static_files, passthrough_errors, ssl_context)
    690         from ._reloader import run_with_reloader
    691         run_with_reloader(inner, extra_files, reloader_interval,
--> 692                           reloader_type)
    693     else:
    694         inner()

C:\Users\Antonio\Anaconda3\lib\site-packages\werkzeug\_reloader.py in run_with_reloader(main_func, extra_files, interval, reloader_type)
    248             reloader.run()
    249         else:
--> 250             sys.exit(reloader.restart_with_reloader())
    251     except KeyboardInterrupt:
    252         pass

SystemExit: 1

A: Can you pls try this code and see if it works
app.run(debug=True, use_reloader=False)


text:
Q: Remove a widget generated with for loop I work on a python project, and I would like to create a history where each history is erasable with a "delete" button placed in the Frame of the widget
I tried to add the « delete » button in the loop where the widget was generated but it didn't work as planned
history_files = os.listdir(history_directory)
history_files.sort(reverse=True)
number_of_h = 0
for file in history_files:
    file_dat = open(history_directory+"\\"+file)
    file_dat_lines = file_dat.readlines()
    action_amount_h = file_dat_lines[0]
    h_comment = file_dat_lines[1]
    h_date = file_dat_lines[2]
    h_time = file_dat_lines[3]
    history_f = Frame(history_win_f, bg=bg_theme, height=120, width=485, highlightbackground=bg_theme_2, highlightthickness=1)
    history_f.grid_propagate(False)
    history_f.columnconfigure(1, weight=70)
    history_f.columnconfigure(2, weight=30)
    history_f.rowconfigure(1, weight=60)
    history_f.rowconfigure(2, weight=40)
    action_h_f = LabelFrame(history_f, bg=bg_theme, width=390, height=120, font='Courrier 13 bold', labelanchor="n")
    action_h_f.grid_propagate(False)
    action_h_f.rowconfigure(1, weight=30)
    action_h_f.rowconfigure(2, weight=70)
    action_h_f.columnconfigure(1, weight=100)
    action_h_f.grid(row=1, column=1, sticky="w")
    date_h_f = LabelFrame(history_f, bg=bg_theme, height=120, width=95, text=' Date ', labelanchor="n", font='Courrier 10 bold')
    date_h_f.grid(row=1, rowspan=2, column=2, sticky="nesw")
    date_h_f.rowconfigure(1, weight=50)
    date_h_f.rowconfigure(2, weight=50)
    date_h_f.columnconfigure(1, weight=100)
    date_l = Label(date_h_f, text="Le "+h_date, bg=bg_theme, fg=fg_theme_2, font='Courrier 8').grid(row=1, column=1, sticky="nesw")
    time_l = Label(date_h_f, text="A "+h_time, bg=bg_theme, fg=fg_theme_2, font='Courrier 8').grid(row=2, column=1, sticky="nesw")
    date_h_f.grid_propagate(False)
    h_edit_a = Label(action_h_f, bg=bg_theme, font="Courrier 11", justify="center")
    h_edit_a_str = ""

I would appreciate any explanation, and if the code is simple, because I'm still a newbie. Thanks !

A: It's hard to know what do you wish to accomplish. I can't see any button on your code and I'm not clear what do you wish to delete when the delete button is clicked.
As per my understanding, If the delete button is on the history_f, and you wish to remove or delete the Labels i.e. date_l and time_l then following is how you can do it.
for file in history_files:
    file_dat = open(history_directory+"\\"+file)
    file_dat_lines = file_dat.readlines()
    action_amount_h = file_dat_lines[0]
    h_comment = file_dat_lines[1]
    h_date = file_dat_lines[2]
    h_time = file_dat_lines[3]
    history_f = Frame(history_win_f, bg=bg_theme, height=120, width=485, highlightbackground=bg_theme_2, highlightthickness=1)
    history_f.grid_propagate(False)
    history_f.columnconfigure(1, weight=70)
    history_f.columnconfigure(2, weight=30)
    history_f.rowconfigure(1, weight=60)
    history_f.rowconfigure(2, weight=40)
    action_h_f = LabelFrame(history_f, bg=bg_theme, width=390, height=120, font='Courrier 13 bold', labelanchor="n")
    action_h_f.grid_propagate(False)
    action_h_f.rowconfigure(1, weight=30)
    action_h_f.rowconfigure(2, weight=70)
    action_h_f.columnconfigure(1, weight=100)
    action_h_f.grid(row=1, column=1, sticky="w")
    date_h_f = LabelFrame(history_f, bg=bg_theme, height=120, width=95, text=' Date ', labelanchor="n", font='Courrier 10 bold')
    date_h_f.grid(row=1, rowspan=2, column=2, sticky="nesw")
    date_h_f.rowconfigure(1, weight=50)
    date_h_f.rowconfigure(2, weight=50)
    date_h_f.columnconfigure(1, weight=100)
    date_l = Label(date_h_f, text="Le "+h_date, bg=bg_theme, fg=fg_theme_2, font='Courrier 8').grid(row=1, column=1, sticky="nesw")
    time_l = Label(date_h_f, text="A "+h_time, bg=bg_theme, fg=fg_theme_2, font='Courrier 8').grid(row=2, column=1, sticky="nesw")
    date_h_f.grid_propagate(False)
    h_edit_a = Label(action_h_f, bg=bg_theme, font="Courrier 11", justify="center")
    h_edit_a_str = ""

    ############################################
    #assume button is on action_h_f
    ttk.Button(action_h_f, text="delete", command=lambda :
                           delete_record(date_l, time_l)

def delete_record(widget1, widget2):
    widget1.destroy()
    widget2.destroy()

you must pass the reference of both the label to the delete_record() function.
Just my guess, correct me if I am wrong.

A: Create the delete button inside history_f frame as well and destroy history_f when it is clicked.  Note that you do not call any layout function on history_f, so it will not be shown and you will get a blank window.
Below are the required changes:
...
for file in history_files:
    ...
    history_f = Frame(history_win_f, bg=bg_theme, height=120, width=485, highlightbackground=bg_theme_2, highlightthickness=1)
    history_f.pack() # call layout function on history_f
    ...
    h_edit_a_str = ""

    # create delete button and destroy history_f when clicked
    Button(history_f, text="Delete", command=history_f.destroy).grid(row=1, column=4)


text:
Q: Printer MAC Addresses I have three printers that I have to put on our internal network using the printers' internal NICs.  They are all currently attached to Windows XP machines and shared via the OS.
So I need to submit details to the networking folks to get IP addresses for each printer.
How do I find the MAC addresses of these printers (they are all HP LaserJets)?
Edit:
Printers:

*

*HP LaserJet 3050

*HP LaserJet 1600

*HP LaserJet 2420

All are attached via USB currently.
Edit:
None of the printers currently have IP addresses.  They all have the capability but currently are not setup.

A: When you did a 'test page', did you do it from the client machine or the printer?... if you did it from the client machine, I doubt you'll get good information about network settings of the printer (specially if you're connecting through USB).
Doing a quick google you can find the manual for your 3050, check for others:
Network configuration page
The Network configuration page lists the current settings and properties of the all-in-one. To print the Network configuration page from the all-in-one, complete the following steps:

*

*On the control panel, press Menu.

*Use the < or the > button to select
Reports, and then press .

*Use the
< or the > button to select Network
report, and then press .

A: Print a test page with the network configuration from the printers.  If they have a NIC in them the test page should display the mac.  I believe LaserJets also have the mac printed on one of the physical labels on the case.  You might have to open a drawer or lift a lid somewhere to find it, depending on what model LJ.

A: HP LaserJet 3050
page 271
http://bizsupport2.austin.hp.com/bc/docs/support/SupportManual/c00495173/c00495173.pdf

HP LaserJet 2420
page 85
http://h20000.www2.hp.com/bc/docs/support/SupportManual/c00224567/c00224567.pdf

A: I would try a broadcast ping to 255.255.255.255 from a linux box (Windows does not allow this) given they are on the same switch. Then have a look at the arp-cache for any responses using
arp -a

The arp cache lookup will also work if you can somehow connect to the device using a configuration tool (even if does not show you the MAC address).

A: There should be a menu choice to print configuration (on the printer itself). Other than that (or using an application that might have come with the printer for configuration, that might report a MAC address), I do not know.


text:
Q: Search for used columns in Crystal Reports Background:
We have two directories of Crystal Reports for both the web side of an application and Win32 side.  Both front-ends share the same database and for the most part, the same reports....it just so happens they are in different locations.
Question:
We have to change a column in many of the reports from one to another and want to know if there is an application, technique or way to search all the reports for the existence of this column so that we know how many reports we have to change?

A: You may be able to make use of this project: RptToXml.

A: We ended up getting the report definitions done for each report (which we needed to do anyway) and save them in one area.  We then used the program available at this website: http://www.ml-consult.co.uk which is called Crystal Reports Documentor which will build us a comma delimited file in which we can search for reports that use specific columns.


text:
Q: Fritz!Box cannot use mailserver that uses ECDSA X.509-certificate My Fritz!Box 6590 using current Fritz!OS 7.12 cannot use my mail server to send out push service notifications. The problem is, that my mail server uses ECDSA certificates. I see in the TLS client hello message from the Fritz!Box that only RSA certificates are supported, neither DSA nor ECDSA certificates are accepted by Fritz!Box. So the mailserver is correctly rejecting the TLS handshake with "no shared cipher".

postfix/smtpd[22491]: SSL_accept error from unknown[xxx.xxx.xxx.xxx]: -1
postfix/smtpd[22491]: warning: TLS library problem: error:1417A0C1:SSL routines:tls_post_process_client_hello:no shared cipher:ssl/statem/statem_srvr.c:2259:
postfix/smtpd[22491]: lost connection after STARTTLS from unknown[xxx.xxx.xxx.xxx]

Is there any way to enable support for ECDSA certificates in the Fritz!Box? I mean actually there aren't that uncommon, it's a standard type of TLS certificate.
Is there any reason why Fritz!Box shouldn't support this type of certificates?

A:
Is there any way to enable support for DSA certificates in the Fritz!Box? I mean actually there aren't that uncommon, it's a standard type of TLS certificate.

There is no option for this. I think it would not also make any sense to actually support ECDSA certificate but have this support disabled by default.

Is there any reason why Fritz!Box shouldn't support this type of certificates?

I can think of no sane reason. But note that Fritz!Box is a commercial closed source product so it is impossible to tell what the real reason is. Please contact the vendor to get an answer and maybe an improvement in the future.


text:
Q: Get distance between two finger on mediapipe using javascript relative to z position I am trying to detect if the tip of thumb and index finger has touched each other. But I am not sure if I am doing this correctly.
const hand = result.multiHandLandmarks[0]; //Returns {x,y,z} of each landmark.
//hand[4] is the tip of the thumb  - Returns {x,y,z} of the tip of thumb.
//hand[8] is the tip of the index finger - Returns {x,y,z} of the tip of index finger.

//I don't know exactly if I am doing this right to get the distance between two tip of fingers.
const x = hand[4].x - hand[8].x;
const y = hand[4].y - hand[8].y;
const z = hand[8].z;

const distance = Math.sqrt(x * x + y * y);

const element = document.getElementById("card")

//--Here I want to check if the user's index and thumb finger is touching each other.
//if it is, then move the element based on the position of index finger.

I have tried doing it this way, but it seems like not the best way to do it.

//I'm not sure about 0.045, if it's enough distance to detect a touch between two finger.
if (distance <= 0.045) {
     element.style.left = `${indexFinger.x - element.offsetWidth / 2}px`;
     element.style.top = `${indexFinger.y - element.offsetHeight / 2}px`;
     console.log("grabbing");
} else {
     console.log("NOT Grabbing", distance, z);
}

Also I want to consider the Z position of index finger, if the hand is too close to the camera, then I want to popup some alert to notify the user to move his hand away in a perfect position. Because I think, the X and Y depends on the Z position. If a hand is too close to the camera the x and y returns higher number.

A: Try this concept.
1.Get the (X1 and Y1) cordinate of the first finger and do same for the second finger (X2 and Y2).
2.Now plug the values into this formular.
Distance = int(sqrt(((X2 - X1) * (X2 - X1)) + ((Y2 - Y1) * (Y2 - Y1))))


text:
Q: My Quit Button is not playing the sound when i click it, except this all the button are playing sound. Can anyone solve this problem? //     This is my app exit button it destroys the activity and exits the user from an app. I want to //play a sound when I click this button but unfortunately, the sound is not playing and the activity //destroys. Please help me in solving this issue. Except for this button, all my button sound is working.
//   This is my second activity, in this activity, I have used a button for quitting the app but I also //want the button to play a sound when the button is clicked by user. But it is not playing the sound and //quits the app which destroys activity. please tell me how to play the sound on my exit button during //the click
      mExitApp = (Button)findViewById(R.id.exit_app);

           final MediaPlayer mp = MediaPlayer.create(this, R.raw.sample2);

            mExitApp.setOnClickListener(new View.OnClickListener() {

                @Override

                public void onClick(View v) {

                    mp.start();

                    ScoreActivity.this.finish();

                    System.exit(0);

                }
            });

A: A quick and dirty way would be to wait for the sound to end playing before finishing the activity/process.
    public void onClick(View v) {
                    mp.start();
                    final Handler handler = new Handler(Looper.getMainLooper());
                    handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ScoreActivity.this.finish();
                        System.exit(0);
                      }
                    }, 300);
                }

A more cleaner solution would probably involve a MediaPlayer.OnCompletionListener.
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    public void onCompletion(MediaPlayer mp) {
        finish(); // finish current activity
    }
});

Or you could play the sound in a foreground/background service. But then you shouldn't kill the entire process (System.exit(0)) like you do now ofc.


text:
Q: compile only new code (C++) I downloaded the sourcecode of a big project from github. I want to learn a little bit more about c++ (and the project) by reading and playing around with some parts of the code.
"./configure" and "make" takes way to long for compilation.
How can I recompile without compilation of all files?
And what is the right way to work in such projects? Right now I compile through bash, I would really like to do everything from my normal c++ IDE (Clion).

A: just use make - it should process only changed files. Usually configure is needed to be executed only once to gather system configuration.
You can read in make man pages:

make  updates  a target if it depends on prerequisite files that
  have been modified since the target was last modified, or if the
  target does not exist.


text:
Q: How to extract class name or id from the object? From my understanding it's good practice to keep all your DOM selectors inside an object, because if the html is modified, you only need to change that object instead of looking through the entire code. However, how do you get a class name or a id from that object?
Example of what I used to do.
https://codepen.io/anon/pen/vvLoqJ?editors=1111
What I'am trying to do:
Obviously is not going to work because I attempting to add string with object. But if there is a way to add that string class place so that button 2 would work without modifying elements object. Thank you in advance.
https://codepen.io/anon/pen/WLweom?editors=1111
HTML
<button class = "button--roll">First Roll</button>
<button class = "button--roll-2">Second Roll</button>

SCRIPT
const elements = {
    buttonRoll: document.querySelector(".button--roll"),
};
class buttonRoll{
    constructor(){
        // Properties
        this.buttonRoll = elements.buttonRoll;
        //    Methods
        this.events;
    }
    events(){
        let roll = "-2";
        // this.buttonRoll + roll.addEventListener('click', () => this.buttonRoll2());
        console.log(this.buttonRoll);
    }
    buttonRoll2(){
        console.log("second button is clicked");
    }
}
buttonRoll = new buttonRoll;
buttonRoll.events();

A: you're looking for something like that ?

    class buttonRoll {
      constructor(base_ClassName) {
        this.button_1 = document.querySelector('.'+base_ClassName);
        this.button_2 = document.querySelector('.'+base_ClassName+'-2');

        this.button_1.onclick = (e)=>this.button_1_click(e);
        this.button_2.onclick = (e)=>this.button_2_click(e);

      }
      button_1_click(e){
        console.log('button_1_click');
      }
      button_2_click(e){
        console.log('button_2_click');
      }
    }

    buttonRolls = new buttonRoll('button--roll');
    <button class = "button--roll">First Roll</button>

    <button class = "button--roll-2">Second Roll</button>

A: in this case, by using your  const element :

    const elements = {
        buttonRoll: document.querySelector(".button--roll"),
    };

    class buttonRoll {
      constructor() {

        let base_ClassName = elements.buttonRoll.className;

        this.button_1 = elements.buttonRoll;
        this.button_2 = document.querySelector('.'+base_ClassName+'-2');

        this.button_1.onclick = (e)=>this.button_x_click(e);
        this.button_2.onclick = (e)=>this.button_x_click(e);
      }
      button_x_click(e){
        console.log(e.target.className);
      }
    }

    buttonRolls = new buttonRoll();
    <button class = "button--roll">First Roll</button>

    <button class = "button--roll-2">Second Roll</button>


text:
Q: Trying to animate height but getting error that height is NaN Been trying to create an animation to dynamically adjust height. I found this info that helped but when I try to use it I get an error: 'System.Windows.Media.Animation.DoubleAnimation' cannot use default destination value of 'NaN'.
If I specify the height I get that error.
Style:
<Style x:Key="bdrSlideIn"
   TargetType="{x:Type Border}">
        <Style.Resources>
            <Storyboard x:Key="storyBoardIn">
                <DoubleAnimation BeginTime="00:00:00"
                                 From="0"
                                 Duration="00:00:00.65"
                                 Storyboard.TargetName="{x:Null}"
                                 Storyboard.TargetProperty="(FrameworkElement.Height)"
                                 DecelerationRatio="1" />
            </Storyboard>

            <Storyboard x:Key="storyBoardOut">
                <DoubleAnimation BeginTime="00:00:00"
                                 To="0"
                                 Duration="00:00:00.65"
                                 Storyboard.TargetName="{x:Null}"
                                 Storyboard.TargetProperty="(FrameworkElement.Height)"
                                 AccelerationRatio="1" />
            </Storyboard>
        </Style.Resources>

        <Style.Triggers>
            <DataTrigger Binding="{Binding SearchExecuted}"
                         Value="True">
                <DataTrigger.EnterActions>
                    <BeginStoryboard Storyboard="{StaticResource storyBoardIn}"
                                     Name="SlideStoryboard" />
                </DataTrigger.EnterActions>
                <DataTrigger.ExitActions>
                    <BeginStoryboard Storyboard="{StaticResource storyBoardOut}" />
                </DataTrigger.ExitActions>
            </DataTrigger>
        </Style.Triggers>
    </Style>

Border:
<Border VerticalAlignment="Top"
    Style="{StaticResource bdrSlideIn}">
        <WPFToolKit:DataGrid Name="dgSearchResults"
                             ItemsSource="{Binding SearchResults}"
                             MaxHeight="280"
                             VerticalAlignment="Top">...

A: If you want to keep Height dynamic then you can't animate Height directly: As you've seen, unless you explicitly assign it WPF will try to interpolate to NaN.Instead, give your element a LayoutTransform <ScaleTransform/>, and animate the ScaleX and ScaleY parameters of that transformation.

A: You could always create an attached property for the height that does nothing other than set the height property on the target control, that way you can animate using To on your attached property.
public class AnimatedPanelBehavior
{
   public static double GetAnimatedHeight(DependencyObject obj)
   {
      return (double)obj.GetValue(AnimatedHeightProperty);
   }

   public static void SetAnimatedHeight(DependencyObject obj, double value)
   {
      obj.SetValue(AnimatedHeightProperty, value);
   }

   public static readonly DependencyProperty AnimatedHeightProperty =
            DependencyProperty.RegisterAttached("AnimatedHeight", typeof(double), typeof(AnimatedPanelBehavior), new UIPropertyMetadata(0d, new PropertyChangedCallback((s, e) =>
   {
       FrameworkElement sender = s as FrameworkElement;
       sender.Height = (double)e.NewValue;
   })));
}

Then to animate it you would use a normal animation, just tried it now and it works fine but I've not investigated any further than "it works".
<DoubleAnimation Storyboard.TargetProperty="(local:AnimatedPanelBehavior.AnimatedHeight)" To="100" Duration="0:0:5"/>

use AnimatedHeight instead of height on anything that you want to be able to animate.

A: Since your TargetProperty is Height, you can just set a default value of Height and it will work. In my case as soon as I have put a number for Height on the actual control itself,
<TextBlock Height="30"  ..
  <TextBlock Style ..
     ...
       <StoryBoard ..

and then had the animation (which were to make toggle the height) it worked fine.


text:
Q: fork() failing with Out of memory error The parent process fails with errno=12(Out of memory) when it tries to fork a child. The parent process runs on Linux 3.0 kernel - SLES 11. At the point of forking the child, the parent process has already used up around 70% of the RAM(180GB/256GB). Is there any workaround for this problem?
The application is written in C++, compiled with g++ 4.6.3.

A: Maybe virtual memory over commit is prevented in your system.
If it is prevented, then the virtual memory can not be bigger than sizeof physical RAM + swap. If it is allowed, then virtual memory can be bigger than RAM+swap.
When your process forks, your processes (parent and child) would have 2*180GB of virtual memory (that is too much if you don't have swap).
So, allow over commit by this way:
 echo 1 > /proc/sys/vm/overcommit_memory

It should help, if child process execves immediately, or frees allocated memory before the parent writes too much to own memory. So, be careful, out of memory killer may act if both processes keep using all the memory.
man page of proc(5) says:

/proc/sys/vm/overcommit_memory
This file contains the kernel virtual
  memory accounting mode. Values are: 0: heuristic overcommit (this is
  the default) 1: always overcommit, never check 2: always check, never
  overcommit
In mode 0, calls of mmap(2) with MAP_NORESERVE are not checked, and
  the default check is very weak, leading to the risk of getting a
  process "OOM-killed". Under Linux 2.4 any nonzero value implies mode
  1. In mode 2 (available since Linux 2.6), the total virtual address space on the system is limited to (SS + RAM*(r/100)), where SS is the
  size of the swap space, and RAM is the size of the physical memory,
  and r is the contents of the file /proc/sys/vm/overcommit_ratio.

More information here: Overcommit Memory in SLES

A: fork-ing requires resources, since it is copy-on-writing the writable pages of the process. Read again the fork(2) man page.
You could at least provide a huge temporary swap file. You could create (on some file system with enough space) a huge file $SWAPFILE with
  dd if=/dev/zero of=$SWAPFILE bs=1M count=256000
  mkswap $SWAPFILE
  swapon $SWAPFILE

Otherwise, you could for instance design your program differently, e.g. mmap-ing some big file (and munmap-ing it just before the fork, and mmap-ing it again after), or more simply starting at the beginning of your program a popen-ed shell, or a p2open-ed one or making explicitly the pipe-s to and from it (probably a multiplexing call à la poll would also be useful), and later issue commands to it.
Maybe we could help more if we had an idea of what your program is doing, why does it consume so much memory, and why and what is it forking...
Read Advanced Linux Programming for more.
PS.
If you fork just to run gdb to show the backtrace, consider simpler alternatives like recent GCC's libbacktrace or Wolf's libbacktrace...

A: A nicer solution on Linux would be to use vfork or posix_spawn (as it will try to use vfork if possible): vfork "creates new processes without copying the page tables of the parent process", so it will work even if your application uses more than 50% of RAM available.
Note that std::system and QProcess::execute also use fork under the hood, there is even a ticket about this problem in Qt framework: https://bugreports.qt.io/browse/QTBUG-17331


text:
Q: how to encrypt using a private key I have a Private key file that looks like this
-----BEGIN PRIVATE KEY-----
[content]
-----END PRIVATE KEY-----
i want to encrypt String data using this key
i am trying like this :
fun encryptData(txt: String, pk: String): String {
    var encoded = ""
    var encrypted: ByteArray? = null
    try {
        val publicBytes: ByteArray = Base64.decode(pk, Base64.DEFAULT)
        val keySpec = X509EncodedKeySpec(publicBytes)
        val keyFactory: KeyFactory = KeyFactory.getInstance("RSA")
        val pubKey: PrivateKey = keyFactory.generatePrivate(keySpec)
        val cipher: Cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING")
        cipher.init(Cipher.ENCRYPT_MODE, pubKey)
        encrypted = cipher.doFinal(txt.toByteArray())
        encoded = Base64.encodeToString(encrypted, Base64.DEFAULT)
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return encoded
}

i am getting a InvalidKeySpecException everytime i try to encode
can someone help ?


text:
Q: MVVM MediatorLiveData observer onchanged called multiple times I am using MVVM + LiveData + Dagger 2.11 on my app.On SignInFragment click on a textview send request to server and show respopnse on snackbar. It works fine on first time click of textview.If I click again,it sends request(inbetween shows snackbar response message here) and ViewModel MediatorLiveData observer onChanged method called muliple times.Is it default behaviour of MediatorLiveData?
SignInViewModel.java
public class SignInViewModel extends AndroidViewModel {

    @Inject
    MediatorLiveData mediatorLiveData;

    @Inject
    SnackbarMessage mSnackbarTextLiveData = new SnackbarMessage();

    @Inject
    public SignInViewModel(Application application,SignInRepository signInRepository) {
        super(application);
        this.signInRepository = signInRepository;
    }

    public MediatorLiveData<ResendActivationCodeResponse> resendActivationCode(final String phoneNumber, final String countryCode) {
        final MutableLiveData<NetworkResponse> connectViaPhoneResponseMutableLiveData = signInRepository.resendActivationCode(phoneNumber, countryCode);

        mediatorLiveData.addSource(connectViaPhoneResponseMutableLiveData, new NetworkResponseObserver() {
            @Override
            public void onSuccess(Object data) {
                mediatorLiveData.setValue(data);
            }

            @Override
            public void onBadRequest(Object data, String errorMessage) {
                mSnackbarTextLiveData.setValue(errorMessage);
            }

            @Override
            public void onUnAuthorisedError(Object data) {
                mSnackbarTextLiveData.setValue(data.toString());
            }

            @Override
            public void onFailure(Object data, String errorMessage) {
                mSnackbarTextLiveData.setValue(errorMessage);
            }

            @Override
            public void onNoNetworkAvailable(Object data, String errorMessage) {
                mSnackbarTextLiveData.setValue(data.toString());
            }

            @Override
            public void onLoading(Object data) {

            }
        });
        return mediatorLiveData;
    }
}

SignInFragment.java
@Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mSignInViewModel = ViewModelProviders.of(mActivity, mViewModelFactory).get(SignInViewModel.class);
        setupSnackbar();
    }

    private void setupSnackbar() {
        mSignInViewModel.getSnackbarMessage().observe(this, new SnackbarMessage.SnackbarObserver() {
            @Override
            public void onNewMessage(String snackbarMessage) {
                ActivityUtils.showSnackbar(getView(), snackbarMessage);
            }
        });
    }

    @OnClick(R.id.resend_activation_code_textview)
    public void reSendActivationCode() {
        showProgress(true);

        final MediatorLiveData<ResendActivationCodeResponse> resendActivationCodeResponseMediatorLiveData = mSignInViewModel.resendActivationCode(mPhoneNumber, mCountryCode);

        Observer<ResendActivationCodeResponse> resendActivationCodeResponseObserver = new Observer<ResendActivationCodeResponse>() {

            @Override
            public void onChanged(@Nullable ResendActivationCodeResponse resendActivationCodeResponse) {
                if (resendActivationCodeResponse != null) {
                    showProgress(false);
                    ActivityUtils.showSnackbar(getView(), activationCodeResentMessage);
                    //resendActivationCodeResponseMediatorLiveData.removeObserver(this);
                }
            }
        };

        resendActivationCodeResponseMediatorLiveData.observe(PhoneNumberActivationFragment.this, resendActivationCodeResponseObserver);
    }

A: It looks like you're calling addSource with different LiveData associated with different phone numbers every time your resend_activation_code_textview is clicked. These different LiveData sources are also all associated with different NetworkResponseObservers, that call setValue(). setValue() is what updates your listening fragments and what is what is called too many times.
I believe the issue is because you call addSource every time resend_activation_code_textview is clicked and you never remove any sources.
If you click resend_activation_code_textview 10 times, your mediatorLiveData will have 10 different sources, when you probably only wanted one.
When a source is added, it does an initial trigger of your mediatorLiveData, so you will always trigger setValue() at least once. When any of the 10 added sources are updated, it will also update your mediatorLiveData, and call setValue(). Depending on what signInRepository.resendActivationCode does and if it updates any of the other 10 LiveData sources, this will trigger multiple setValue() calls for one click.

There's a removeSource() method which you could call to make sure you never have more than one source at a time, this likely getting rid of the multiple onChanged calls. But there's a built in solution for what I think you're trying to do (which uses MediatorLiveData under the hood) -- it's the switchMap Transformation.
switchMap allows you to change the underlying source that a LiveData is listening to, without updating the observers. So instead of clicking resend_activation_code_textview 10 times and adding 10 different sources, you can have it so that every time you click resend_activation_code_textview the previous source will be swapped for a new source.
The example scenario for switchMap is that you have a method to look up a userById(). You make a normal LiveData to store the user id, and then use the switchMap transformation so that you have another LiveData for the current user. As the id changes, the current user is swapped out and updated:
MutableLiveData userIdLiveData = ...;
 LiveData userLiveData = Transformations.switchMap(userIdLiveData, id ->
     repository.getUserById(id));

 void setUserId(String userId) {
      this.userIdLiveData.setValue(userId);
 }

I think you're doing something similar with the phone number and country code. This is like your "id". You'll want to create an object which contains a phone number and country code, let's call it FullPhoneNumber. Then you'll make a LiveData<FullPhoneNumber> phoneNumberLiveData, which is similar to the userIdLiveData in the previous example. Then:
LiveData<ResendActivationCodeResponse> reactivationLiveData =
Transformations.switchMap(phoneNumberLiveData, currentPhoneNumber ->
     signInRepository.resendActivationCode(currentPhoneNumber.getNumber(), currentPhoneNumber.getCountryCode());

Hope that helps or at least points you in the right direction!


text:
Q: MVC 4 adding a custom class to a html after unsuccessful validation I am new to MVC 4, while analyzing the 'Register' View of, default internet MVC web application, provided in Visual studio i found that for the username input element, it was initally like this
<input id="UserName" type="text" value="" name="UserName"></input>

but after an unsuccessful validation it changed to
<input id="UserName" class="input-validation-error" type="text" value="" name="UserName"></input>

I disabled the ClientValidation and UnobtrusiveJavascript in the Web.config file.
I want to to know

*

*how this class attribute is added to the input element. Is there a javascript involved for this?

*How can i change the class name in the class attribute rendered in the input element.

A: If You want to change class name then you can do this with jquery as :
$(document).ready(function () {
   $("input[class='input-validation-error']").removeClass("input-validation-error").addClass("errorclass")
 });

in place of "errorclass" you can have any class name of your choice


text:
Q: Why is either casting or the use of generics necessary for adding Strings to ArrayLists in Java? I'm trying to understand ArrayLists and in the process have realized I also need to understand generics, raw types, and more about type casting. I'm reading the Oracle tutorial and this is the example they give for why generics are helpful:

The following code snippet without generics requires casting:

List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);

What I don't understand is why type casting is necessary here because as far as I can tell 'list.get(0)' is of type 'String' before and after the typecasting. I used the code here to check the type, not sure if it's correct or not.
List list = new ArrayList();
list.add("hello");

Object obj= list.get(0);

Class cls=obj.getClass();

String answer = cls.getSimpleName();
System.out.println(answer);

String s = (String) list.get(0);

Object obj2= list.get(0);

Class cls2=obj2.getClass();
System.out.println(cls2);

String answer2 = cls2.getSimpleName();
System.out.println(answer2);

So I'm asking for an explanation as to why type casting is necessary here and in here non generic-ed Arraylists in general.

A: The run-time type is String, but the compile-time type is Object. The compiler doesn't know what a raw ArrayList holds, so when you call get() it assigns a compile-time type of Object. An Object can't be assigned directly to a String, thus the cast.
The cast is the developer's way of saying to the compiler, "You think it's a list of Objects, but trust me, the thing I'm pulling out is definitely a String."


text:
Q: Replace space with hyphen in links I need like this
https://play.google.com/store/apps/details?id=com.abc.abcc%26reffer=M1%26name=ABC-DEF-GHI  but now it's Coming https://play.google.com/store/apps/details?id=com.abc.abcc%26reffer=M1%26name=ABC
DEF  GHI
My Code As Follows
https://play.google.com/store/apps/details?id=com.abc.abcc%26reffer=M{{$data['shopID']}}%26name={{$datastr_replace['-','name']}}

A: Given the following array:
$data = [
  'shop_id' => 'M',
  'name' => 'ABC DEF GHI'
];

You can use the str_replace() method to replace all of your ' ' with -:
Link

A: You have to change as like str_replace(' ', '-', $data['name']) , may be you have mistaken like name={{$datastr_replace['-','name']}}


text:
Q: Assigning Table/Header names in Sort Functions I have a code that works when I assign ranges manually, but this is a bit cumbersome especially when it's unclear if the sheet will be modified and therefore make the values in the code incorrect.
My original code
Const ProcName As String = "Filter_Ascending_Descending"
On Error GoTo Whoa

Dim WsCP As Worksheet: Set WsCP = Sheets("Cross Platform Database")
Dim WsDND As Worksheet: Set WsDND = Sheets("DO NOT DELETE")
Dim Header As Variant: Header = WsCP.Range("D36").Value
Dim CriteriaOp As Variant: CriteriaOp = WsCP.Range("C38").Value     '<< This will be the Data Value
Dim Criteria As Variant: Criteria = WsCP.Range("D38").Value         '<< This will be the Data Value
Dim Order As Variant: Order = WsCP.Range("C36").Value               '<< Expected to be Ascending/Descending
Dim OrderHeader As Variant: OrderHeader = "Table1[[#Headers],[Sales]]"

    With Application
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
        .EnableEvents = False
    End With

    'This code will sort the data in the relevant column according to the user selection
    If WsDP.Range("C26") = "Ascending" Then
        Sheets("Cross Platform Database").Range("S24:S71499").Sort _
          Key1:=Sheets("Cross Platform Database").Range("S23"), Order1:=xlAscending, Header:=xlYes

    ElseIf WsDP.Range("C26") = "Descending" Then
        Sheets("Cross Platform Database").Range("S24:S71499").Sort _
          Key1:=Sheets("Cross Platform Database").Range("S23"), Order1:=xlDescending, Header:=xlYes
    Else

    End If

SafeExit:
    With Application
        .EnableEvents = True
        .Calculation = xlCalculationAutomatic
        .ScreenUpdating = True
    End With

    Exit Sub

Whoa:
    Debug.Print "'" & ProcName & "' Run-time error '" _
      & Err.Number & "':" & vbLf & "    " & Err.Description
    Resume SafeExit

End Sub

I tried to change all ranges to table names but my code jumps to error and returns

error 5 "Invalid procedure call or arguement"

'This code will sort the data in the relevant column according to the user selection
If Order = "Ascending" Then
    WsCP.ListObjects("Table1").Range("Table1[Sales]").Sort _
      Key1:=WsCP.Range(OrderHeader), Order1:=xlAscending, Header:=xlYes

A: Sort an Excel Table
Option Explicit

Sub TestSortTable()

    Dim WsCP As Worksheet: Set WsCP = Worksheets("Cross Platform Database")
    Dim AscDesc As String: AscDesc = CStr(WsCP.Range("C26").Value) ' unclear

    Dim tbl As ListObject: Set tbl = WsCP.ListObjects("Table1")
    Dim lcl As ListColumn: Set lcl = tbl.ListColumns("Sales")

    Select Case LCase(AscDesc)
    Case "ascending"
        tbl.Range.Sort _
            Key1:=lcl.Range, Order1:=xlAscending, Header:=xlYes
    Case "descending"
        tbl.Range.Sort _
            Key1:=lcl.Range, Order1:=xlDescending, Header:=xlYes
    Case Else ' do nothing
    End Select

End Sub


text:
Q: How to do "Type Definition" I'm using a math library Eigen and I use a lot of dynamic vector with a template type Eigen::Vector<T, -1, 1> in a lot of files. With this notation my code is really dense, so I have two questions :
Should I do a type definition in order to get a shorter and more proper code using Vector<T> = Eigen::Vector<T, -1, 1>? But my code will be more difficult to understand with this modification.
And If I do this type definition, where should I do? Because I use an external library (Eigen) modifying the library files is not a good solution, but a custom file just for this looks dirty.

A: Learn to love the verbose notation Eigen::Vector. That way, you know exactly what you're dealing with.
Using using statements, particularly in header files, tends to lead to code that's more difficult to read in the long run (can you ever remember which namespace you are referring to?), and also causes potential namespace clashes.
The same style applies to things from the std namespace.


text:
Q: What is "localhost" server in Azure redirect URL I have an App registered in Azure AD, and in the redirectUrl I want to use localhost, when I use localhost which server it will look for?

A: As per this Document it says,

localhost is a domain reserved for documentation and testing purposes.
If you access "http://localhost" in the browser, the request will remain in your own system.

*

*Localhost refers to the machine/device where we are running our Application

*Instead of localhost we can access with IP address 127.0.0.1

*

*Thanks @HarshithaVeeramalla-MT for the comment, If we give RedirectURI as http://localhost:portnumber the request will be sent to the same device where we are accessing the app

As per this MSDoc there are some exceptions for localhost redirect URIs

http and https URI's are acceptable for localhost

Taken References from:
https://www.ionos.com/digitalguide/server/know-how/localhost/
https://learn.microsoft.com/en-us/azure/active-directory/develop/reply-url#localhost-exceptions


text:
Q: Create a mailto link with Razor I have a view with a model that has an email address.  How do I create an anchor? to allow the user to simply click on it an open Outlook?  I could create an anchor manually but then how do I include the email address?
Email

A: Just use the @ syntax
Email

A: I found an answer to my problem:
@{ var email = "mailto:" + Model.CreatorEmail;}
            Email

A: Adding the email address attribute to your model:
  [EmailAddress(ErrorMessage = "Must be a valid email address")]

And using a Html.DisplayFor in your razor view
  @Html.DisplayFor(x => x.EmailAddress)

Should render it as an a tag with

mailto:

before it's value


text:
Q: Shell tweak to show current path in addition I'm using ubuntu 10.10 and now I got in the shell something like that:
machine1user@mylinux:~:

how can i change it to
machine1user@mylinux:/my/current/path :~: ?

A: the '~' at the end IS your current path. :)

A: Open ~/.bashrc in your text editor. Search for this:
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt

# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
    PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"

and change it to this:
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:$PWD\$ '
fi
unset color_prompt force_color_prompt

# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
    PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: $PWD\a\]$PS1"

Specifically, you're replacing \w with $PWD. The first reference sets the text for your command prompt; the second sets the title which is usually shown in the menu bar of your terminal.


text:
Q: How can I use variables when constructing a URL string? I've been given some JavaScript that creates a digital clock to go onto a webpage. This is working perfectly, however, I'm trying to amend it to wrap the am/pm suffix (or Diem in this code) in span or bold tags so that I can style it differently to the rest of the time in the CSS.
I'm sure this would be really simple for someone that knows what they're doing but I'm really struggling.
Any help would be appreciated, the JavaScript is below:
function renderTime() {
    var currentTime = new Date();
    var diem = "AM";
    var h = currentTime.getHours();
    var m = currentTime.getMinutes();
    var s = currentTime.getSeconds();
    setTimeout('renderTime()',1000);
    if (h == 0) {
        h = 12;
    } else if (h > 12) {
        h = h - 12;
        diem="PM";
    }

    if (m < 10) {
        m = "0" + m;
    }
    if (s < 10) {
        s = "0" + s;
    }
    var myClock = document.getElementById('clockDisplay');
    myClock.textContent = h + ":" + m + " " + diem;
    myClock.innerText = h + ":" + m + " " + diem;
    var diem = document.createElement('span');
}
renderTime();

So, I want to do the same thing, but in a URL style, like this: http://example.com/example?h="10"&m="42"

A: Just concatenate the hour and minute to the URL prefix and return that as a string.
Also, your code produces the wrong diem for times between noon and 12:59, since those should be 12PM.

function getTimeURL() {
    var currentTime = new Date();
    var diem = "AM";
    var h = currentTime.getHours();
    var m = currentTime.getMinutes();
    var s = currentTime.getSeconds();
    if (h == 0) {
        h = 12;
    } else if (h > 12) {
        h = h - 12;
        diem="PM";
    } else {
        diem = "PM";
    }

    if (m < 10) {
        m = "0" + m;
    }
    var url = `http://example.com/example?h=${h}${diem}&m=${m}`;
    return url;
}

console.log(getTimeURL());

A: I added a bunch of comments to your code that'll hopefully make it easier to understand. I also added a global variable that will store your linkText value as it's changed by the function.

// create a global variable that stores our text for the link.
// Your renderTime() function will update it every second.
var linkText = "";

function renderTime() {
  //grab the new date
  var currentTime = new Date();
  //set diem (whatever that means) to "AM"
  var diem = "AM";
  //get the hours from our current time
  var h = currentTime.getHours();
  //get the minutes
  var m = currentTime.getMinutes();
  //get the seconds
  var s = currentTime.getSeconds();

  //run this function every 1000 milliseconds
  setTimeout('renderTime()', 1000);

  //if the hour is 0, set it to twelve instead
  if (h == 0) {
    h = 12;
    //else if the hour is any number higher than 12,
    //subtract 12 from its value and change diem to "PM"
  } else if (h > 12) {
    h = h - 12;
    diem = "PM";
  }
  //if the minutes are 0-9 add a 0 before.
  if (m < 10) {
    m = "0" + m;
  }
  //if the seconds are 0-9 add a 0 before.
  if (s < 10) {
    s = "0" + s;
  }
  //get our clock element
  var myClock = document.getElementById('clockDisplay');

  //populate our clock element
  myClock.textContent = h + ":" + m + ":" + s + " " + diem;
  myClock.innerText = h + ":" + m + ":" + s + " " + diem;
  //not sure why you're writing over your AM/PM variable at the end here,
  //so I commented it out
  //var diem = document.createElement('span');

  //set our linkText value to be the current hour and minute
  linkText = 'http://example.com/example?h="' + h + '"&m="' + m + '"';

}

//run that thang!
renderTime();


text:
Q: .ism/manifest format on apple tv Can I play video stream with format .ism/manifest on AppleTV?
I use AVFoundation and AVQueuePlayer. I keep my player in ViewController scope, not in function scope. I've tried to add "(format=m3u8-aapl,audio-only=false)" in the end of url but video has lags after starts. So my code is:
let url = "http://vodstreaming.dev.mr.tv3ce.com/3ba7e5c5-277a-4c4b-b5ae-d06d2524a290/hv5_After_Earth_1080i29_noAudioPCR_6Mbps_fixed_GOP.ism/manifest(format=m3u8-aapl,audio-only=false)"
let playerItem = AVPlayerItem(url: url)
player.insert(playerItem, after: nil)
player.play()

I've read that for iOS exists AVAssetDownloadURLSession but for TvOS don't. Maybe exist other solution for streaming on TvOS?

A: Looks like you are using Azure Media Services for that stream. Using the format parameter will return a m3u8 manifest, which is generally playable on tvOS, iOS and macOS - provided the codec is correct.
However, you manifest only has a single quality of approx 5 mbit/s. Best practice is to have lower qualities available also. So you might run into buffering issues (if that is what you mean by "has lags after start").
Apple has a set of Best Practices available regarding video streams.


text:
Q: How do I break out of this loop in bash I want to break out of this loop when grep doesn't match its pattern. The "higher" goals here were:

*

*see the output (stdout be unaffected)

*grep it for a pattern

*stop processing once a pattern is not found

.
#!/bin/bash
set -ex
i=1
RERUN=0
while [ ${RERUN} == 0 ]
do
   ((i++))
   echo -n "Rerun${i}"| tee >(grep --color=always 'Rerun[123]' ; export RERUN=$?)
   echo ${RERUN}
   sleep 1
done

My guess why its not working is that is has to do with different shell levels

A: I might write this like so:
#!/bin/bash

generate_output() {
  local i=0
  while :; do
    (( ++i ))
    printf 'Rerun%s\n' "$i"
    sleep 1
  done
}

while IFS= read -r line; do
  printf '%s\n' "$line"
  [[ $line = Rerun[123] ]] || break
done < <(generate_output)

Note that there's no need to communicate between the two processes with a shared variable -- sending a SIGPIPE to generate_output by closing the file descriptor it's writing to suffices.

A: I found a solution:
#!/bin/bash
# set -x
i=0
RERUN_FILE=$(mktemp)
declare -a TESTDATA=("run" "run" "run" "last" "run" "run" "run" )
while ! $(grep -q 1 ${RERUN_FILE})
do
   echo -n ${TESTDATA[$i]}| tee >(grep --color=always 'run'; echo -n $? >${RERUN_FILE})
   ((i++))
   sleep 1
done
rm ${RERUN_FILE} # do your dishes after the meal


text:
Q: How to check if the string is empty? Does Python have something like an empty string variable where you can do:
if myString == string.empty:

Regardless, what's the most elegant way to check for empty string values? I find hard coding "" every time for checking an empty string not as good.

A: I once wrote something similar to Bartek's answer and javascript inspired:
def is_not_blank(s):
    return bool(s and not s.isspace())

Test:
print is_not_blank("")    # False
print is_not_blank("   ") # False
print is_not_blank("ok")  # True
print is_not_blank(None)  # False

A: if stringname: gives a false when the string is empty. I guess it can't be simpler than this.

A:
I find hardcoding(sic) "" every time for checking an empty string not as good.

Clean code approach
Doing this: foo == "" is very bad practice. "" is a magical value. You should never check against magical values (more commonly known as magical numbers)
What you should do is compare to a descriptive variable name.
Descriptive variable names
One may think that "empty_string" is a descriptive variable name. It isn't.
Before you go and do empty_string = "" and think you have a great variable name to compare to. This is not what "descriptive variable name" means.
A good descriptive variable name is based on its context.
You have to think about what the empty string is.

*

*Where does it come from.

*Why is it there.

*Why do you need to check for it.

Simple form field example
You are building a form where a user can enter values. You want to check if the user wrote something or not.
A good variable name may be not_filled_in
This makes the code very readable
if formfields.name == not_filled_in:
    raise ValueError("We need your name")

Thorough CSV parsing example
You are parsing CSV files and want the empty string to be parsed as None
(Since CSV is entirely text based, it cannot represent None without using predefined keywords)
A good variable name may be CSV_NONE
This makes the code easy to change and adapt if you have a new CSV file that represents None with another string than ""
if csvfield == CSV_NONE:
    csvfield = None

There are no questions about if this piece of code is correct. It is pretty clear that it does what it should do.
Compare this to
if csvfield == EMPTY_STRING:
    csvfield = None

The first question here is, Why does the empty string deserve special treatment?
This would tell future coders that an empty string should always be considered as None.
This is because it mixes business logic (What CSV value should be None) with code implementation (What are we actually comparing to)
There needs to be a separation of concern between the two.

A: The only really solid way of doing this is the following:
if "".__eq__(myString):

All other solutions have possible problems and edge cases where the check can fail.

*

*len(myString) == 0 can fail if myString is an object of a class that inherits from str and overrides the __len__() method.

*myString == "" and myString.__eq__("") can fail if myString overrides __eq__() and __ne__().

*"" == myString also gets fooled if myString overrides __eq__().

*myString is "" and "" is myString are equivalent. They will both fail if myString is not actually a string but a subclass of string (both will return False). Also, since they are identity checks, the only reason why they work is because Python uses String Pooling (also called String Internment) which uses the same instance of a string if it is interned (see here: Why does comparing strings using either '==' or 'is' sometimes produce a different result?). And "" is interned from the start in CPython
The big problem with the identity check is that String Internment is (as far as I could find) that it is not standardised which strings are interned. That means, theoretically "" is not necessary interned and that is implementation dependant.
Also, comparing strings using is in general is a pretty evil trap since it will work correctly sometimes, but not at other times, since string pooling follows pretty strange rules.

*Relying on the falsyness of a string may not work if the object overrides __bool__().
The only way of doing this that really cannot be fooled is the one mentioned in the beginning: "".__eq__(myString). Since this explicitly calls the __eq__() method of the empty string it cannot be fooled by overriding any methods in myString and solidly works with subclasses of str.
This is not only theoretical work but might actually be relevant in real usage since I have seen frameworks and libraries subclassing str before and using myString is "" might return a wrong output there.
That said, in most cases all of the mentioned solutions will work correctly. This is post is mostly academic work.

A: How about this?  Perhaps it's not "the most elegant", but it seems pretty complete and clear:
if (s is None) or (str(s).strip()==""): // STRING s IS "EMPTY"...

A: From PEP 8, in the "Programming Recommendations" section:

For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

So you should use:
if not some_string:

or:
if some_string:

Just to clarify, sequences are evaluated to False or True in a Boolean context if they are empty or not. They are not equal to False or True.

A: if you want to check if a string is completely empty
if not mystring

which works because empty strings are false
but if a string is only whitespace it will be true so you might want to
if not mystring.strip()

A: Responding to @1290. Sorry, no way to format blocks in comments. The None value is not an empty string in Python, and neither is (spaces). The answer from Andrew Clark is the correct one: if not myString. The answer from @rouble is application-specific and does not answer the OP's question. You will get in trouble if you adopt a peculiar definition of what is a "blank" string. In particular, the standard behavior is that str(None) produces 'None', a non-blank string.
However if you must treat None and (spaces) as "blank" strings, here is a better way:
class weirdstr(str):
    def __new__(cls, content):
        return str.__new__(cls, content if content is not None else '')
    def __nonzero__(self):
        return bool(self.strip())

Examples:
>>> normal = weirdstr('word')
>>> print normal, bool(normal)
word True

>>> spaces = weirdstr('   ')
>>> print spaces, bool(spaces)
    False

>>> blank = weirdstr('')
>>> print blank, bool(blank)
 False

>>> none = weirdstr(None)
>>> print none, bool(none)
 False

>>> if not spaces:
...     print 'This is a so-called blank string'
...
This is a so-called blank string

Meets the @rouble requirements while not breaking the expected bool behavior of strings.

A: I did some experimentation with strings like '', ' ', '\n', etc. I want isNotWhitespace to be True if and only if the variable foo is a string with at least one non-whitespace character. I'm using Python 3.6. Here's what I ended up with:
isWhitespace = str is type(foo) and not foo.strip()
isNotWhitespace = str is type(foo) and not not foo.strip()

Wrap this in a method definition if desired.

A: The most elegant way would probably be to simply check if its true or falsy, e.g.:
if not my_string:

However, you may want to strip white space because:
 >>> bool("")
 False
 >>> bool("   ")
 True
 >>> bool("   ".strip())
 False

You should probably be a bit more explicit in this however, unless you know for sure that this string has passed some kind of validation and is a string that can be tested this way.

A: a = ''
b = '   '
a.isspace() -> False
b.isspace() -> True

A: Empty strings are "falsy" (python 2 or python 3 reference), which means they are considered false in a Boolean context, so you can just do this:
if not myString:

This is the preferred way if you know that your variable is a string.  If your variable could also be some other type then you should use:
if myString == "":

See the documentation on Truth Value Testing for other values that are false in Boolean contexts.

A: The clearest approach is:
if s == "":

Benefits:

*

*Additional indication to the programmer what the type of s should be.

*"" is not "hard-coding" a magic value any more than x == 0 is.
Some values are fundamental and do not need a named constant; e.g. x % 2 to check for even numbers.

*Cannot incorrectly indicate that any falsy value (e.g. []) is an empty string.

Consider how one checks if an integer is 0:
if x == 0:

One certainly should not do:
if not x:

Both integers and strings are primitive value types. Why treat them differently?

A: Test empty or blank string (shorter way):
if myString.strip():
    print("it's not an empty or blank string")
else:
    print("it's an empty or blank string")

A: I would test noneness before stripping. Also, I would use the fact that empty strings are False (or Falsy). This approach is similar to Apache's StringUtils.isBlank or Guava's Strings.isNullOrEmpty
This is what I would use to test if a string is either None OR Empty OR Blank:
def isBlank (myString):
    return not (myString and myString.strip())

And, the exact opposite to test if a string is not None NOR Empty NOR Blank:
def isNotBlank (myString):
    return bool(myString and myString.strip())

A: If you want to differentiate between empty and null strings, I would suggest using if len(string), otherwise, I'd suggest using simply if string as others have said.  The caveat about strings full of whitespace still applies though, so don't forget to strip.

A: not str(myString)

This expression is True for strings that are empty. Non-empty strings, None and non-string objects will all produce False, with the caveat that objects may override __str__ to thwart this logic by returning a falsy value.

A: You may have a look at this Assigning empty value or string in Python
This is about comparing strings that are empty. So instead of testing for emptiness with not, you may test is your string is equal to empty string with "" the empty string...

A: for those who expect a behaviour like the apache StringUtils.isBlank or Guava Strings.isNullOrEmpty :
if mystring and mystring.strip():
    print "not blank string"
else:
    print "blank string"

A: When you are reading file by lines and want to determine, which line is empty, make sure you will use .strip(), because there is new line character in "empty" line:
lines = open("my_file.log", "r").readlines()

for line in lines:
    if not line.strip():
        continue

    # your code for non-empty lines

A: If you are not totally sure, that your input is really a string, I would recommend to use isinstance(object, classinfo) link in addition, as shown in the example.
If not, lists or a True bool value could also be evaluated as True.

<script type="text/javascript" src="//cdn.datacamp.com/dcl-react.js.gz"></script>

<div data-datacamp-exercise data-lang="python">
  <code data-type="sample-code">
def test_string(my_string):
    if isinstance(my_string, str) and my_string:
      print("It's a me, String! -> " + my_string)
    else:
      print("Nope. No, String")

def not_fully_test_string(my_string):
    if my_string:
      print("It's a me, String??? -> " + str(my_string))
    else:
      print("Nope. No, String")

print("Testing String:")
test_string("")
test_string(True)
test_string(["string1", "string2"])
test_string("My String")
test_string(" ")

print("\nTesting String or not?")
not_fully_test_string("")
not_fully_test_string(True)
not_fully_test_string(["string1", "string2"])
not_fully_test_string("My String")
not_fully_test_string(" ")

  </code>
</div>

A: As prmatta posted above, but with mistake.
def isNoneOrEmptyOrBlankString (myString):
    if myString:
        if not myString.strip():
            return True
        else:
            return False
    return False

A: Below is an elegant solution for any number of spaces.
def str_empty(s: str) -> bool:
    """Strip white space and count remaining characters."""
    return len(s.strip()) < 1

>>> str_empty(' ')
True

A: If you just use
not var1

it is not possible to difference a variable which is boolean False from an empty string '':
var1 = ''
not var1
> True

var1 = False
not var1
> True

However, if you add a simple condition to your script, the difference is made:
var1  = False
not var1 and var1 != ''
> True

var1 = ''
not var1 and var1 != ''
> False

A: In case this is useful to someone, here is a quick function i built out to replace blank strings with N/A's in lists of lists (python 2).
y = [["1","2",""],["1","4",""]]

def replace_blank_strings_in_lists_of_lists(list_of_lists):
    new_list = []
    for one_list in list_of_lists:
        new_one_list = []
        for element in one_list:
            if element:
                new_one_list.append(element)
            else:
                new_one_list.append("N/A")
        new_list.append(new_one_list)
    return new_list

x= replace_blank_strings_in_lists_of_lists(y)
print x

This is useful for posting lists of lists to a mysql database that does not accept blanks for certain fields (fields marked as NN in schema.  in my case, this was due to a composite primary key).


text:
Q: Kendo Validation, How to Ensure That an End Date is Greater Than or Equal to Start Date I have two input fields on a webpage for a Start Date and an End Date and I am using kendo validation to ensure they are formatted properly; and that the End Date is greater than or equal to the Start Date. I have used the data-greaterdate-field attribute to successfully ensure that the End Date is greater than the Start Date; but what I really need is to ensure that it is greater than or equal to the Start Date. The data-greaterdate-field attribute corresponds to
validationtype = greaterdate

Is there a validationtype for greater than or equal to?
Here is sample of the code:
<input id="startdate" name="Start Date">
<input id="enddate" name="End Date" data-greaterdate-field="Start Date" data-greaterdate-msg='End date should be after start date'>

A: Handle this into rules section of Kendo Validator.
function initializeValidator(){
return $('#FormElement').kendoValidator({
    rules: {
     greaterdate: function (input) {
      if (input.is('[data-greaterdate-msg]') && input.val() != "") {
            var date = kendo.parseDate(input.val()),
            otherDate = kendo.parseDate($("[name='" + input.data('greaterdateField') +  "']").val());
    return otherDate == null || otherDate.getTime() <= date.getTime();
  }
  return true;
}

Note: "<=" does the trick inside rule's section. I've used Kendo version 2016.1.412


text:
Q: PM2: Deploy multiple environments on a single server? I am using PM2 for deployment / process management, and the application handles lots of DNS tasks, and so it's easiest if I run the development app from the remote server, and either Rsyncing or SFTPing on save (still sorting this out).
This being the case, it is the idea case for the dev app to be on the same VM as the production app. However, the structure of the PM2 deployment configuration file (ecosystem.config.js) doesn't seem to make this possible, as when I run pm2 deploy development, the development version overtakes the production process on the VM.
Here is what I have:
module.exports = {
  apps: [
    {
      name: "APP NAME",
      script: "app.js",
      env_development: {
        NODE_ENV: "development",
        ...
      },
      env_production: {
        NODE_ENV: "production",
        ...
      }
    }
  ],
  deploy: {
    production: {
      user: "user",
      host: ["123.123.123.123"],
      ref: "origin/master",
      repo: "git@gitlab.com:me/repo.git",
      path: "/var/www/app",
      "post-deploy":
        "npm install && pm2 reload ecosystem.config.js --env production"
    },
    development: {
      user: "user",
      host: ["123.123.123.123"],
      ref: "origin/master",
      repo: "git@gitlab.com:me/repo.git",
      path: "/var/www/app-dev",
      "post-deploy":
        "npm install && pm2 reload ecosystem.config.js --env development"
    }
  }
};

Any thoughts for the best way to go about accomplishing this?

A: After referencing this PR, I'm thinking you should be able to add append_env_to_name: true as a property to the object in the apps array of the ecosystem.config.js:
So your updated ecosystem.config.js file would be as follows:
module.exports = {
  apps: [
    {
      name: "APP NAME",
      append_env_to_name: true // <===== add this line
      script: "app.js",
      env_development: {
        NODE_ENV: "development",
        ...
      },
      env_production: {
        NODE_ENV: "production",
        ...
      }
    }
  ],
  deploy: {
    production: {
      user: "user",
      host: ["123.123.123.123"],
      ref: "origin/master",
      repo: "git@gitlab.com:me/repo.git",
      path: "/var/www/app",
      "post-deploy":
        "npm install && pm2 reload ecosystem.config.js --env production"
    },
    development: {
      user: "user",
      host: ["123.123.123.123"],
      ref: "origin/master",
      repo: "git@gitlab.com:me/repo.git",
      path: "/var/www/app-dev",
      "post-deploy":
        "npm install && pm2 reload ecosystem.config.js --env development"
    }
  }
};


text:
Q: Find the area of the surface given by $0 \leq x \leq 1$, $y=2x$, $z= e^{x+y}$. Im trying to parametrize the surface in order to propose an integral to find the area. However, Im not sure about how to set the limits of $u$ and $v$. This is my attempt: $x=u$, $y=v$, $z= e^{u+v}$, where $0 \leq u \leq 1$ and $0 \leq  v \leq 2$. Is this okay? Or should I change it for
$0 \leq  v \leq 2x$?

A: $x = t, y = 2t, z = e^{3t},\\
\int_0^1 e^{3t} \sqrt {\frac {dx}{dt}^2 + \frac {dy}{dt}^2}\ dt$


text:
Q: XML Serialization Windows Phone 8 I'm trying to serialize my ObservableCollection<Memos> in an XML file.
The Memos class is like this:
[DataContract]
public class Memos
{
    [DataMember]
    public string Date { get; set; }

    [DataMember]
    public string Event { get; set; }

    public BitmapImage Photo { get; set; }

    [DataMember]
    public string Path { get; set; }
    public Memos() { }

    public static async Task<BitmapImage> LoadImage(StorageFile file)
    {
        //code
    }
}

If I leave the Photo field, it works properly. But I don't understand why, because I don't mark it with the [DataMember] attribute.
My code goes like this:
using (var file = storage.CreateFile("Memos.xml"))
{
    var serializer = new XmlSerializer(typeof(ObservableCollection<Memos>));
    serializer.Serialize(file, MainPage.ListMemos);
}

A: Try to mark the property with XmlIgnore to prevent it from being serialized :
[XmlIgnore]
public BitmapImage Photo { get; set; }


text:
Q: Default document in Google App Engine Is it possible to specify the equivalent of a default document for directories in Google App Engine so that navigating to that directory automatically redirects to its index.html for example, if it contains one?
If I have this in my app.yaml:
- url: /demos
  static_dir: demos

and the demos directory contains an index.html page, how can I tell App Engine to automatically redirect to that page?

A: I got this to work by using this in my yaml.
- url: /(.+)
  static_files: static/\1
  upload: static/(.+)

- url: /
  static_files: static/index.html
  upload: static/index.html

Replace static with demos and you should be set. It redirects the blank domain to index.html and al others to the static folder.

A: App Engine uses regular expression matches on the request path to determine what script to call or document to serve. If you just have the one index document, you can do it like this:
- url: /demos/
  static_files: demos/index.html
  upload: demos/index\.html

More generally, you can define static files for paths ending in slashes ('directories') like this:
- url: /(.*)/
  static_files: \1/index.html
  upload: .*/index\.html

A: For GAE/J, add the following to your web.xml file.
<welcome-file-list>
    <welcome-file>index.html</welcome-file>
</welcome-file-list>

www.example.com/test/ will now serve www.example.com/test/index.html

A: - url: /demos(/.+|)/
  static_files: demos\1/index.html
  upload: demos/(.+/|)index\.html
- url: /demos/
  static_dir: demos


text:
Q: GLM model selection using AICc with Tweedie distribution I have two questions regarding use of Tweedie GLM in R. I am new in using this distribution and despite a thorough search on different forums, I could not find my answers.
I am now running several GLM models using Tweedie distribution because of compound Poisson-Gamma distribution of my data with a spike around zero.
I can successfully run the models but firstly, AIC is not provided in the model results. There is a command for AIC calculation (AICtweedie) but I could not find anything calculating AICc (as my data points are few). Is this just matter of lack of enough interest in Tweedie that such a command doesn't exist or there is some logical or technical constraints behind it?
Second, use of packages such as MuMin or glmulti is not possible when using Tweedie distribution (because AIC values are not calculated in Tweedie models). Has anyone got any similar packages to run multiple models and rank them based on AIC(c) when using Tweedie? Running around 500 models and type down the AIC values is not easily possible.

A: You can use AICtweedie directly in MuMIn's functions, just specify it as a rank argument. Alternatively, you could write a wrapper around AICtweedie.


text:
Q: How to display a report by Department wise How to display a report by Department wise
Using Crystal Report 8.5
ID Name Department

001 raja IT
002 Vijay IT
003 Ram CSE
So on...

Display an Each Page by Department wise.
Once IT Department is completed then go to new page and display CSE Department, like that I need.
How to make in crystal report?

A: Insert -> Group -> Department.
Once you have a group section, right click on it. It should show you checkboxes on right side which should have an option which could be "print on new page".
See if that helps.

A: Like others have said. Create a group for the Department field. Go to the section expert for the group footer, enter this into the "New Page After" formula.
not onlastrecord

this will prevent the blank last page.

A: use sql group by department

A: Add group in the crystal report or use group by in the Sql query like that is is possible
and set every group comes in the new page in th section expert->select group section and set new page after.


text:
Q: When creating a order via Woocommerce Rest API order note showing two notes for order status and also Not sending a correct email Facing an issue when creating a order via WooCommerce rest API. There are two issues:

*

*Order Note
When creating order via Desktop:-
New Order of "BANK Transfer" as a payment creating two order note

*Order status changed from pending payment to on hold

*For order stock reduced

When creating order via Mobile:-
New order with "Bank Transfer" as a payment method creating three order note:-
1. Order status changed from pending payment to processing
2. Order stock reduced
3. Order status changed from pending payment to on hold

*Customer Receiving a email with status processing, while the order status is on-hold

I tried to pass order status=on-hold from API when creating a order and updating a order payment details. But issue is still persist.
Order create api
POST wc-api/v3/orders/
Body
{
  "order": {
    "customer_id": 6925,
    "billing_address": {
      "first_name": "Android",
      "last_name": "Testing",
      "address_1": "Address of Developer",
      "address_2": "Cengkareng",
      "city": "Jakarta Barat",
      "state": "6",
      "postcode": "12345",
      "country": "ID",
      "email": "ankurgecr@gmail.com",
      "phone": "1234567890"
    },
    "shipping_address": {
      "first_name": "Android",
      "last_name": "Testing",
      "address_1": "Address of Developer",
      "address_2": "Cengkareng",
      "city": "Jakarta Barat",
      "state": "6",
      "postcode": "12345",
      "country": "ID"
    },
    "line_items": [
      {
        "product_id": 32776,
        "quantity": 1,
        "subtotal": 10000,
        "total": 10000,
        "variations": {
          "Color": "Blue"
        }
      }
    ],
    "fee_lines": [
      {
        "title": "Rp",
        "total": 846
      }
    ],
    "shipping_lines": [
      {
        "method_id": "OKE",
        "method_title": "JNE OKE",
        "total": 29500
      }
    ],
    "is_vat_exempt": false
  }
}
Order update API
POST  wc-api/orders/[orderID]
BODY
{
  "order": {
    "status": "on-hold",
    "payment_details": {
      "method_id": "bacs",
      "method_title": "Bank Transfer BCA / MANDIRI",
      "paid": true
    },
    "set_paid": true
  }
}
Custoemr should receive a email of order status= on-hold.
I'm attaching a image for actual result.
Note: Is is working fine if we are placing a orde from website checkout, only the issue is with rest API.


text:
Q: How should I express this set of statements with Entity Framework? I set up a complex application which uses Entity Framework related to some Microsoft SQL Server databases. While it seems simple to express some common queries with Linq, I wonder how should I express this set of statements correctly (it is returning a scalar):
DECLARE @TZ SMALLINT;

SELECT @TZ = DATEPART(TZ, SYSDATETIMEOFFSET());
SELECT CAST(@TZ / 60 AS VARCHAR(5));

A: Why not use the c# equivalent:
DateTime n = DateTime.Now;
int tz = (n - n.ToUniversalTime()).Hours;

Of cource is assumes that your server and the program is in the same timezone.

A: This is the full code I mentioned above:
Create Function dbo.TimeZone(@dummy varchar) returns varchar(5)
as
begin
    Declare @tz varchar(5)
    Select @tz = CAST(DATEPART(TZ, SYSDATETIMEOFFSET()) / 60 AS VARCHAR(5))
    return @tz
End
Go

Create Table x ( i int,
tz as (dbo.Timezone(''))
)
Go

Insert into x(i) Values(5);

Select * from x;

Or using a view:
Create View y as Select dbo.TimeZone('') Tz
Go

Select * From y


text:
Q: k8s pod readiness probe fails with connection refused, but pod is serving requests just fine I'm having a hard time understanding why a pods readiness probe is failing.
  Warning  Unhealthy  21m (x2 over 21m)  kubelet, REDACTED  Readiness probe failed: Get http://192.168.209.74:8081/actuator/health: dial tcp 192.168.209.74:8081: connect: connection refused

If I exec into this pod (or in fact into any other I have for that application), I can run a curl against that very URL without issue:
kubectl exec -it REDACTED-l2z5w /bin/bash
$ curl -v http://192.168.209.74:8081/actuator/health
$ curl -v http://192.168.209.74:8081/actuator/health
* Expire in 0 ms for 6 (transfer 0x5611b949ff50)
*   Trying 192.168.209.74...
* TCP_NODELAY set
* Expire in 200 ms for 4 (transfer 0x5611b949ff50)
* Connected to 192.168.209.74 (192.168.209.74) port 8081 (#0)
> GET /actuator/health HTTP/1.1
> Host: 192.168.209.74:8081
> User-Agent: curl/7.64.0
> Accept: */*
>
< HTTP/1.1 200
< Set-Cookie: CM_SESSIONID=E62390F0FF8C26D51C767835988AC690; Path=/; HttpOnly
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< Content-Type: application/vnd.spring-boot.actuator.v3+json
< Transfer-Encoding: chunked
< Date: Tue, 02 Jun 2020 15:07:21 GMT
<
* Connection #0 to host 192.168.209.74 left intact
{"status":"UP",...REDACTED..}

I'm getting this behavior from both a Docker-for-Desktop k8s cluster on my Mac as well as an OpenShift cluster.
The readiness probe is shown like this in kubectl describe:
    Readiness:  http-get http://:8081/actuator/health delay=20s timeout=3s period=5s #success=1 #failure=10

The helm chart has this to configure it:
    readinessProbe:
      failureThreshold: 10
      httpGet:
        path: /actuator/health
        port: 8081
        scheme: HTTP
      initialDelaySeconds: 20
      periodSeconds: 5
      successThreshold: 1
      timeoutSeconds: 3

I cannot fully rule out that HTTP proxy settings are to blame, but the k8s docs say that HTTP_PROXY is ignored for checks since v1.13, so it shouldn't happen locally.
The OpenShift k8s version is 1.11, my local one is 1.16.

A: Describing events always show the last event on the resource you are checking. The thing is that the last event logged was an error while checking the readinessProbe.
I tested it in my lab with the following pod manifest:
apiVersion: v1
kind: Pod
metadata:
  name: readiness-exec
spec:
  containers:
  - name: readiness
    image: k8s.gcr.io/busybox
    args:
    - /bin/sh
    - -c
    - sleep 30; touch /tmp/healthy; sleep 600
    readinessProbe:
      exec:
        command:
        - cat
        - /tmp/healthy
      initialDelaySeconds: 5
      periodSeconds: 5

As can be seen, a file /tmp/healthy will be created in the pod after 30 seconds and the readinessProbe will check if the file exists after 5 seconds and repeat the check after every 5 seconds.
Describing this pod will give me that:
Events:
  Type     Reason     Age                    From                 Message
  ----     ------     ----                   ----                 -------
  Normal   Scheduled  7m56s                  default-scheduler    Successfully assigned default/readiness-exec to yaki-118-2
  Normal   Pulling    7m55s                  kubelet, yaki-118-2  Pulling image "k8s.gcr.io/busybox"
  Normal   Pulled     7m55s                  kubelet, yaki-118-2  Successfully pulled image "k8s.gcr.io/busybox"
  Normal   Created    7m55s                  kubelet, yaki-118-2  Created container readiness
  Normal   Started    7m55s                  kubelet, yaki-118-2  Started container readiness
  Warning  Unhealthy  7m25s (x6 over 7m50s)  kubelet, yaki-118-2  Readiness probe failed: cat: can't open '/tmp/healthy': No such file or directory

The readinessProbe looked for the file 6 times with no success and it's completely right as I configured it to check every 5 seconds and the file was created after 30 seconds.
What you think is a problem is actually the expected behavior. Your Events is telling you that the readinessProbe failed to check 21 minutes ago. It means actually that your pod is healthy since 21 minutes ago.


text:
Q: How do you encrypt large files / byte streams in Go? I have some large files I would like to AES encrypt before sending over the wire or saving to disk. While it seems possible to encrypt streams, there seems to be warnings against doing this and instead people recommend splitting the files into chunks and using GCM or crypto/nacl/secretbox.

Processing streams of data is more difficult due to the authenticity requirement. We can't encrypt-then-MAC: by it's nature, we usually don't know the size of a stream. We can't send the MAC after the stream is complete, as that usually is indicated by the stream being closed. We can't decrypt a stream on the fly, because we have to see the entire ciphertext in order to check the MAC. Attempting to secure a stream adds enormous complexity to the problem, with no good answers. The solution is to break the stream into discrete chunks, and treat them as messages.

*

*https://leanpub.com/gocrypto/read

Files are segmented into 4KiB blocks. Each block gets a fresh random 128 bit IV each time it is modified. A 128-bit authentication tag (GHASH) protects each block from modifications.

*

*https://nuetzlich.net/gocryptfs/forward_mode_crypto/

If a large amount of data is decrypted it is not always possible to buffer all decrypted data until the authentication tag is verified. Splitting the data into small chunks fixes the problem of deferred authentication checks but introduces a new one. The chunks can be reordered... ...because every chunk is encrypted separately. Therefore the order of the chunks must be encoded somehow into the chunks itself to be able to detect rearranging any number of chunks.

*

*https://github.com/minio/sio
Can anyone with actual cryptography experience point me in the right direction?
Update
I realized after asking this question that there is a difference between simply not being able to fit the whole byte stream into memory (encrypting a 10GB file) and the byte stream also being an unknown length that could continue long past the need for the stream's start to be decoded (an 24-hour live video stream).
I am mostly interested in large blobs where the end of the stream can be reached before the beginning needs to be decoded. In other words, encryption that does not require the whole plaintext/ciphertext to be loaded into memory at the same time.

A: Using HMAC after encryption is a valid method. However, HMAC can be pretty slow, especially if SHA-2 is used. You could actually do the same with GMAC, the underlying MAC of GCM. It may be tricky to find an implementation but GMAC is over the ciphertext, so you can simply perform it separately if you really want. There are other methods as well such as Poly1305 with AES as used for TLS 1.2 and 1.3.
For GCM (or CCM or EAX or any other authenticated cipher) you need to authenticate the order of the chunks. You could do this by creating a separate file encryption key and then using the nonce input (the 12 byte IV) to indicate the number of the chunk. This will solve the storage of the IV and make sure that the chunks are in order. You can generate the file encryption key using a KDF (if you have a unique way to indicate the file) or by wrapping a random key with a master key.

A: As you've already discovered from your research, there isn't much of an elegant solution for authenticated encryption of large files.
There are traditionally two ways to approach this problem:

*

*Split the file into chunks, encrypt each chunk individually and let each chunk have its own authentication tag.  AES-GCM would be the best mode to use for this.  This method causes file size bloating proportionate to the size of the file.  You'll also need a unique nonce for each chunk.  You also need a way to indicate where chunks begin/end.

*Encrypt using AES-CTR with a buffer, call Hash.Write on an HMAC for each buffer of encrypted data.  The benefit of this is that encrypting can be done in one pass.  The downside is that decryption requires one pass to validate the HMAC and then another pass to actually decrypt.  The upside here is that the file size remains the same, plus roughly ~48 or so bytes for the IV and HMAC result.
Neither is ideal, but for very large files (~2GB or more), the second option is probably preferred.
I have included an example of encryption in Go using the second method below.  In this scenario, the last 48 bytes are the IV (16 bytes) and the result of the HMAC (32 bytes).  Note the HMACing of the IV also.
const BUFFER_SIZE int = 4096
const IV_SIZE int = 16

func encrypt(filePathIn, filePathOut string, keyAes, keyHmac []byte) error {
    inFile, err := os.Open(filePathIn)
    if err != nil { return err }
    defer inFile.Close()

    outFile, err := os.Create(filePathOut)
    if err != nil { return err }
    defer outFile.Close()

    iv := make([]byte, IV_SIZE)
    _, err = rand.Read(iv)
    if err != nil { return err }

    aes, err := aes.NewCipher(keyAes)
    if err != nil { return err }

    ctr := cipher.NewCTR(aes, iv)
    hmac := hmac.New(sha256.New, keyHmac)

    buf := make([]byte, BUFFER_SIZE)
    for {
        n, err := inFile.Read(buf)
        if err != nil && err != io.EOF { return err }

        outBuf := make([]byte, n)
        ctr.XORKeyStream(outBuf, buf[:n])
        hmac.Write(outBuf)
        outFile.Write(outBuf)

        if err == io.EOF { break }
    }

    outFile.Write(iv)
    hmac.Write(iv)
    outFile.Write(hmac.Sum(nil))

    return nil
}


text:
Q: shortcode in snippet plugin not work add_filter( 'woocommerce_product_tabs', 'wpb_new_product_tab' );
function wpb_new_product_tab( $tabs ) {
    // Add the new tab
    $tabs['test_tab'] = array(
        'title'       => __( 'Size Chart', 'text-domain' ),
        'priority'    => 50,
        'callback'    => 'wpb_new_product_tab_content'
    );
    return $tabs;
}

function wpb_new_product_tab_content() {
    // The new tab content
    echo 'Size Chart';
    echo '[table id=2 responsive=collapse responsive_breakpoint="phone" /]
" /.';
}