text:
Q: Plot performance during training from lightGBM in TidyModels (tuning number of trees) I am trying to plot model performance of lightGBM models for training and validation sets using TidyModels.  I'd like to be able to extract metric (e.g. RMSE) performance on training & validation sets for every nth tree during training.
So for example I would like to plot RMSE for the 10th, 20th, 30th...500th trees for both training and validation sets, plot the curves, and then see where training performance flattens and/or validation deteriorates.
Apologies for no reprex with this, but the task is a generic one.
I have been using lightGBM (with the bonsai package) for my modelling & I've searched here and the Tidymodels sites, but can't find anything specific on this.  I'm assuming that this data is saved in an object somewhere, but I've not found it.  Thanks.

A: You're indeed correct that that data is saved inside the object. :)
The metrics you choose to evaluate with, as well as their values, are stored inside of the underlying lightgbm object that the tidymodels object wraps. After training with tidymodels, we can subset out the underlying engine fit with extract_fit_engine(), and then use lightgbm's interface to work with that object as usual. (An aside, though: be sure to use the tidymodels objects for prediction.)
In this reprex, I use bonsai's shorthand validation argument to allot 20% of the supplied training data for validation, which is what those resulting metrics are computed on. If you'd like to evaluate with non-default metrics, you can pass those to set_engine() as well with lightgbm's usual argument structure.
library(lightgbm)
#> Loading required package: R6
library(tidymodels)
library(bonsai)

# fit the model using tidymodels---note that we use the `validation`
# argument to interface with lightgbm validation sets
pars_fit <-
  boost_tree() %>%
  set_engine("lightgbm", validation = .2) %>%
  set_mode("regression") %>%
  fit(bill_length_mm ~ ., data = penguins)

pars_fit
#> parsnip model object
#>
#> <lgb.Booster>
#>   Public:
#>     add_valid: function (data, name)
#>     best_iter: 52
#>     best_score: 6.97993052849227
#>     current_iter: function ()
#>     dump_model: function (num_iteration = NULL, feature_importance_type = 0L)
#>     eval: function (data, name, feval = NULL)
#>     eval_train: function (feval = NULL)
#>     eval_valid: function (feval = NULL)
#>     finalize: function ()
#>     initialize: function (params = list(), train_set = NULL, modelfile = NULL,
#>     lower_bound: function ()
#>     params: list
#>     predict: function (data, start_iteration = NULL, num_iteration = NULL,
#>     raw: NA
#>     record_evals: list
#>     reset_parameter: function (params, ...)
#>     rollback_one_iter: function ()
#>     save: function ()
#>     save_model: function (filename, num_iteration = NULL, feature_importance_type = 0L)
#>     save_model_to_string: function (num_iteration = NULL, feature_importance_type = 0L)
#>     set_train_data_name: function (name)
#>     to_predictor: function ()
#>     update: function (train_set = NULL, fobj = NULL)
#>     upper_bound: function ()
#>   Private:
#>     eval_names: l2
#>     get_eval_info: function ()
#>     handle: lgb.Booster.handle
#>     higher_better_inner_eval: FALSE
#>     init_predictor: NULL
#>     inner_eval: function (data_name, data_idx, feval = NULL)
#>     inner_predict: function (idx)
#>     is_predicted_cur_iter: list
#>     name_train_set: training
#>     name_valid_sets: list
#>     num_class: 1
#>     num_dataset: 2
#>     predict_buffer: list
#>     set_objective_to_none: FALSE
#>     train_set: lgb.Dataset, R6
#>     train_set_version: 1
#>     valid_sets: list

Subsetting out the underlying engine fit:
# extract the underlying fit
lgb_fit <- extract_fit_engine(pars_fit)

lgb_fit
#> <lgb.Booster>
#>   Public:
#>     add_valid: function (data, name)
#>     best_iter: 52
#>     best_score: 6.97993052849227
#>     current_iter: function ()
#>     dump_model: function (num_iteration = NULL, feature_importance_type = 0L)
#>     eval: function (data, name, feval = NULL)
#>     eval_train: function (feval = NULL)
#>     eval_valid: function (feval = NULL)
#>     finalize: function ()
#>     initialize: function (params = list(), train_set = NULL, modelfile = NULL,
#>     lower_bound: function ()
#>     params: list
#>     predict: function (data, start_iteration = NULL, num_iteration = NULL,
#>     raw: NA
#>     record_evals: list
#>     reset_parameter: function (params, ...)
#>     rollback_one_iter: function ()
#>     save: function ()
#>     save_model: function (filename, num_iteration = NULL, feature_importance_type = 0L)
#>     save_model_to_string: function (num_iteration = NULL, feature_importance_type = 0L)
#>     set_train_data_name: function (name)
#>     to_predictor: function ()
#>     update: function (train_set = NULL, fobj = NULL)
#>     upper_bound: function ()
#>   Private:
#>     eval_names: l2
#>     get_eval_info: function ()
#>     handle: lgb.Booster.handle
#>     higher_better_inner_eval: FALSE
#>     init_predictor: NULL
#>     inner_eval: function (data_name, data_idx, feval = NULL)
#>     inner_predict: function (idx)
#>     is_predicted_cur_iter: list
#>     name_train_set: training
#>     name_valid_sets: list
#>     num_class: 1
#>     num_dataset: 2
#>     predict_buffer: list
#>     set_objective_to_none: FALSE
#>     train_set: lgb.Dataset, R6
#>     train_set_version: 1
#>     valid_sets: list

Some of the slots in the underlying fit have their names set by tidymodels, so you may need to poke around a bit to figure out how we've passed different lightgbm arguments.
It's my understanding that the plot_metrics functionality from the Python API is not yet ported over to R. We can put together our own plot with their other methods and some quick dplyr and ggplot, though:
# use lightgbm's interface to retrieve l2 for each iteration
eval_results <- lgb.get.eval.result(lgb_fit, data_name = "validation", eval_name = "l2")

# drop into data frame
tibble(l2 = eval_results, iteration = seq_along(eval_results)) %>%
  # subset out every 10th iteration, starting at 1
  slice(seq(from = 1, to = length(eval_results), by = 10)) %>%
  # plot
  ggplot() +
  aes(x = iteration, y = l2) +
  geom_point()

Created on 2022-11-02 with reprex v2.0.2


text:
Q: Can water in conduit cause an increase in voltage? I'm a electrical & solar contractor. We installed a 38 kW system consisting of 3 inverters and (120) 320 watt panels, 40 per inverter. When we energize each inverter the voltage increases all along the system. I've got all the voltages if you need them. The inverter company had us bypass all breakers, fuses and bussing to confirm no unacceptable resisatance when systems are rpoducing power. And the utility came out and reworked all connections from transformer to meter. Inverter company suggested all this and we complied. Voltage increase still exists. When 1st system turned on voltage goes from 244 to 251. When 2nd system turned on voltage goes from 251 to 259.5. When 3rd comes on it goes from 259.5 to 267.6. Any combination of inverters on and off produce like results. Now the inverter tech support people say water in the conduit can cause this.  The wire is 4/0 AL XHHW. The most amperage recorded is 111 but mostly it runs at about 80 amps. All new wire and equipment. I'm not an engineer. Do you have any suggestions as to the cause of this? I've googled this question and also looked in advance search in this forum.

A: Voltage at the inverter's output needs to be greater than grid voltage if the current has to flow into the grid. It depends on grid impedance how much this voltage will rise for the same current. Simple ohms law : U=R*I can be writen as (Uinverter-U_grid)=I_inverter * R_grid, then Uinverter = I_inverter * R_grid + U_grid. It is prety trivial that voltage rise will be greater if grid impedance is larger (long distance to the transformer or small wires cross section).
As long the voltage rise is in the tolerance (approx +10%) the inverter will not limit the output voltage. If the voltage is limited, then the system cannot deliver the full available power from PV array.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python Replace content in specific line at txt file I have a txt file with content as below:
name
password
number
location
the four items are separated into each line
I would like to change the content in the specific line, eg:
change the third line("number") to "phone number"
Problem I faced is not replacing the "number", "number" still there, and the "phone number" is appended at the last line
Output:
name
password
number
location
phone number

How should I fix the code, so it can replace the content in certain line?
Below is my code
userID = 1

print("Modify: ")
print("1. Username")
print("2. Password")
print("3. Contact number")
print("4. Location")
print()
print("Enter 'main' to back to main screen")
select = int(input())
change = input("Change to: ")

if select != 'main:':
    if int(select) <= 4:
        #save to individual file
        fhand = open("user_"+str(userID)+".txt",'r+')

        lineNo = 0 #line number
        for line in fhand():
            lineNo = lineNo + 1
            if lineNo == select:
                fhand.write(line.replace(line, change)) #replace the content
                print()
                print("Changed to:", change)
                print("Change successful")
                print("\n Bring you back to <customer main menu>")

        fhand.close()

I tried counting the line number, then when the line number reach the selection of the user, it starts to replace the line, and it doesn't work
Thanks for the helps

A: You can't edit or replace a single line in a file.
Try to open a second file (e.g.newtext = open("newtext.txt", "a+") and do something like this:
for line in fhand.readlines():
    if line != select:
        newtext.write(line)
    else:
        line = line.replace(line, change)
        newtext.write(line)

also, try using with open as statements, for example
with open("newtext.txt", "a+") as newtext:
    for line in fhand.readlines():
        if line != select:
            newtext.write(line)
        else:
            line = line.replace(line, change)
            newtext.write(line)

A: Quickest fix would be to read the whole file, close it, and rewrite with the correct data. This way you ensure that the new file has the correct contents.
I highly advise you to switch to using JSON files though. You won't have the same issue as you can load a JSON file as a dict, change the correct value, and rewrite the changed dict/JSON. Structured datafiles FTW...
Adjusting the current code, see below.
userID = 1

print("Modify: ")
print("1. Username")
print("2. Password")
print("3. Contact number")
print("4. Location")
print()
print("Enter 'main' to back to main screen")
select = int(input()) - 1 # offset difference between selection options and 0-based list
change = input("Change to: ")

if select != 'main:':
    if select < 4 and select >= 0:  # adjusted due to adjusting the select above
        filename = f'user_{str(userID)}.txt'
        # load file
        with open(filename) as infile:
            filecontents = infile.readlines()
        # make the change
        filecontents[select] = f'{change}\n'
        # save the result
        with open(filename, 'w') as outfile:
            outfile.writelines(filecontents)
        print()
        print("Changed to:", change)
        print("Change successful")
        print("\n Bring you back to <customer main menu>")

A: the filemode r+ is reading and appending, so if you want to change the existing contents of the file then you have to open the file in write mode.
userID = 1

print("Modify: ")
print("1. Username")
print("2. Password")
print("3. Contact number")
print("4. Location")
print()
print("Enter 'main' to back to main screen")
select = int(input())
change = input("Change to: ")

if select != 'main:':
    if int(select) <= 4:
        #save to individual file
        with open("user_"+str(userID)+".txt",'r') as f:
            lines = f.readlines()
        # fhand = open("user_"+str(userID)+".txt",'r+')

        lineNo = 0 #line number
        for line in lines:
            lineNo = lineNo + 1
            if lineNo == select -1:
                lines[lineNo] = line.replace(line, f'{change}\n')
                with open("user_"+str(userID)+".txt",'w') as f:
                    f.write("".join(lines)) #replace the content
                print()
                print("Changed to:", change)
                print("Change successful")
                print("\n Bring you back to <customer main menu>")
                break

        # fhand.close()

I have taken the liberty to change some variable names; do change to your usecase accordingly.

A: Instead of that, what you can do is go with this code for editing the text file
with open(path_to_text_file,'r') as txt:
    text=txt.readlines()
    text[3]='phone number\n'

    with open(path_to_text_file,'w') as txt:
        txt.writelines(text)

A: slight modifications:
userID = 1

print("Modify: ")
print("1. Username")
print("2. Password")
print("3. Contact number")
print("4. Location")
print()
print("Enter 'main' to back to main screen")
select = int(input())-1
change = input("Change to: ")

if select != 'main:':
    if int(select) <= 4:
        # save to individual file
        with open("user_" + str(userID) + ".txt", 'r+') as file:
            data = file.readlines()
        for index, line in enumerate(data):
            if index == select:
                data[index] = line.replace(line, f"{change}\n")
                break
        with open("user_" + str(userID) + ".txt", 'r+') as file:
            file.writelines(data)
        print("Changed to:", change)
        print("Change successful")
        print("\n Bring you back to <customer main menu>")


text:
Q: Ionic 2 Upload File to Server this is my upload file function:
uploadresume()
    {
        this.fileChooser.open()
        .then(uri =>
        {
            console.log(uri)
            const fileTransfer: TransferObject = this.transfer.create();

            let options1: FileUploadOptions = {
                fileKey: 'file',
                fileName: 'name.pdf',
                params: {resume:uri},
                chunkedMode : false,
                headers: { Authorization:localStorage.getItem('token') }

            }
            console.log (localStorage.getItem('token'))

            fileTransfer.upload(uri, "http://website.com/upload", options1)
            .then((data) => {
                // success
                alert("success"+JSON.stringify(data));
            }, (err) => {
                // error
                alert("error"+JSON.stringify(err));
            });

        })
        .catch(e => console.log(e));
    }

now my API endPoint takes in the parameter Resume with the file attached to it. But I keep getting 500 error. I am sure it's something to do with the way I am sending the file to the endpoint. Can someone please assist me ?

A: I think you need to add a mimeType parameter in your file upload options.


text:
Q: Jira - release deployment to UAT/Production Do you know how to mark a release that it is deployed to System test/UAT/Production? I would like to filter on stories deployed to different environments. Is it possible?
I do not want to handle this as workflow as I want to avoid cases when two stories are assigned to the same release but one story is on UAT while and other one is not.
Thanks
Zoltan

A: Your example is confusing, as if you have two stories in the same release I would see each story as being their own issue. You could then still use workflows as each issue can be in a different status than the other. Workflows are good if you are moving through environments in a specific order such as:
Open -> Dev in Progress -> QA -> UAT -> Pre-Prod -> Prod

If you want it so an issue could be on multiple environments at a time, then I would use a custom field like Checkboxes:
Deployed to:
  [*] Dev
  [ ] QA
  [*] UAT
  [ ] Pre-Prod
  [ ] Prd

Then you could do your filter for Issues like:
project = 'TEST' and release = '1.0' and Dev is not Empty and UAT is not Empty

To see all issues for the Test Project that are in Release 1.0 and are on Dev and UAT.


text:
Q: android bitmap not null but always make nullpointerexception i am implementing topcode for android + opencv for android.
topcode is use for get marker position in screen.
in topcode, scanning method only accept bitmap argument.
so i convert my mat to bitmap.
this is my code
private Scanner scanner;
private List<TopCode> codes;
//..........................
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
    // TODO Auto-generated method stub
    mRgb = inputFrame.rgba();

    Bitmap bmp = Bitmap.createBitmap(mRgb.cols(), mRgb.rows(),Bitmap.Config.ARGB_8888);

    try {
            Utils.matToBitmap(mRgb, bmp,true);

            if(bmp != null){

                codes = scanner.scan(bmp); ----> this giving null

            }

        } catch(Exception e) {

            e.printStackTrace();

    }

return mRgb;
}

this is error log
java.lang.NullPointerException
at com.example.ar.MainActivity.onCameraFrame(MainActivity.java:155)
at org.opencv.android.CameraBridgeViewBase.deliverAndDrawFrame(CameraBridgeViewBase.java:387)
at org.opencv.android.JavaCameraView$CameraWorker.run(JavaCameraView.java:328)
at java.lang.Thread.run(Thread.java:841)

i don't know what to do now. please help me.

A: You must initialise your scanner. Your bmp has no problem, you've checked that in your if statement. You can initialise it like this : (just add this line before your try catch statement)
Scanner scanner = new Scanner(System.in);

A: Try this following code
private Scanner scanner;
private List<TopCode> codes;
//..........................
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
    // TODO Auto-generated method stub
    mRgb = inputFrame.rgba();

    Bitmap bmp = Bitmap.createBitmap(mRgb.cols(), mRgb.rows(),Bitmap.Config.ARGB_8888);

    try {
            Utils.matToBitmap(mRgb, bmp,true);

            if(bmp != null){
               if(scanner ==null)
                scanner = new Scanner(System.in);

                codes = scanner.scan(bmp);

            }

        } catch(Exception e) {

            e.printStackTrace();

    }

return mRgb;
}


text:
Q: i need feedback on my PDO login function, will there be errors? and how is the structure? im new to PDO so im trying to figure stuff out
im making a login system
function validateLogin($db,$phone,$password)
{
    $stmt = $db->prepare("SELECT $password FROM reg WHERE phone = :phone ");
    $stmt->bindParam(':phone',$phone);
    $stmt->execute();
    $row = $stmt->fetch();
    if($row) {
        if( password_verify($password,$row)==false)
        {
           //password error message
        }
        else
           //redirect to another page or whatever
        }
        else
          //phone number not registered error message

how is this looking? thank you.

A: Just use column name inside your prepared statement and fetch column result from $row to verify value.
$stmt = $db->prepare("SELECT password_column_name FROM reg WHERE phone = :phone");


text:
Q: JSON on IE6 (IE7) Sorry for my inpatience but after weeks staying up late and just having put my web online, I just don't have any left energy to debug... I just can't Google how to implement JSON on IE6 & IE7... I'm using
JSON.stringify(...)

From what I understand JSON is not built in on IE6-7 and has to be dynamically added in in-line code... how do you do that?
I already have jQuery - is it my correct understanding that their JSON engine relies on the browser native one?
Then some comment on invalid JSON code that makes IE6-7 fail, but I thought it wasn't native in IE6-7?
Anyone?

A: There must be something misunderstood. The object notation has been in JavaScript for a while now (as far as I understand, it's a core concept of JavaScript). I mean, the ability to write code like var o= {a:"b"};
So, if you can do this, you can also call eval('var o= {a:"b"};') and that's the way you "implement JSON" in any browser.
UPDATE: Re-read your post and finally got the point that the problem is serializing objects, not deserializing them. Then you can use the JavaScript library for that: https://github.com/douglascrockford/JSON-js/blob/master/json2.js

A: Just include json2.js in your file to play around with JSON.
It'll also work in IE 9 .

A: Since you want to use the JSON.stringify method, you will need to include the JSON3 parser in order to support it on IE < 8.
This library complies with the standard methods of the ECMAScript 5th Edition specification and it checks if there is a native implementation available, so on modern browser this native implementation will be used.

A: "dynamically added in-line code" is using the functionality provided by Douglas Crockfords json2 library, or jQuery's own implementation if the browser version doesn't support it natively.
jQuery does not rely on any JSON decoding functionality provided by the browser. If the browser does support JSON decoding, then jQuery will use it.


text:
Q: Find all elements that appear more than n/k times Given an array of of size n and a number k, Find all elements that appear more than n/k times.
I believe this problem can be solved using the technique of moore's voting algorithm, by creating a map of size k which will store the number and their frequency.
Steps:
First create the map of size k and insert first k elements from array and update their corresponding frequencies.
for next k elements if the number exist in the map increase their count otherwise decrease the count of a existing number which has lowest count value (we can find this in constant time by keeping another map) If count ever drops to 0 delete that number of from map and add new number.
At the end check whether the numbers exist in map has frequency more than n/k or not.
I look forward for your counter example or comment.
eg: consider n = 10  and k=2
Consider the scenario
2,2,2,7,1,3,5,6,8,9
Map will have size 2.
For first element it will only contain 2 with count 3.
for 7 it will insert (since map has free blocks) and update it counts 1.
for 1 it is not in the map find the lowest count candidate in this case it is 7 decrease its count now count of 7 is 0 so update entry by inserting 1 and setting count 1.
This procedure will follow till the end of array at the end we have two candidates left in map 2 and 9 and their counts are 3 and 1.
We will check count of both element and return result which has count > n/k. (we don't need to loop through array k times we can store the count initially in some other map) so checking the counts of candidate at the end we will perform O(k) operations.

A: This does not work. Take a number a that appears int(n/k + 1) times at the start of the array, followed by some random mix of n-int(n/k+1) numbers not containing a anymore. Since n-int(n/k+1) for k>2 is larger than int(n/k+1), there is no guarantee that the array entry for a won't drop to zero.
An improved version of this algorithm, which doesn't produce false negatives (but can produce false positives) is in Data Streams: Algorithms and Applications
 By S. Muthukrishnan, section 5.1.2, "Frequent elements/heavy hitters sampling".


text:
Q: performing sql operation in rails console I have gem 'sqlite3' installed in my rails application. where do i perform a query to check whether some records exist in the table.
In my rails console i ran sqlite3.
C:\Sites\iAuth>sqlite3
SQLite version 3.8.2 2013-12-06 14:53:30
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> select * from users;
Error: no such table: users
sqlite>

I have a table with users, but how come it says no such table exists. I am using Devise for authentication. Below is my model.
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

A: You probably need to refer to your db file directly:
sqlite3 db/development.sqlite3

A: Are you looking for this command?
rails dbconsole

In this console you can run sql queries directly


text:
Q: how do I write to avlibs AVOptions from C I want to do the equivalent of the following command line from a C program.
ffmpeg ..... -movflags frag_keyframe

I have narrowed it down to setting some fields in priv_class in AVOutputFormat somehow. But I don't understand how AVOptions work, I could not find a good example that explains how AVOptions are set and used. I did come across av_opt_set but if I set the name field to "movflags" what is the val and do I set a separate option for frag_keyframe or is it embedded in the flags set for "movflags"?
Thanks in advance for your time.

A: Try this
AVFormatContext * _format_context = ...

AVDictionary * params = NULL;
av_dict_set(&params, "movflags", "frag_keyframe", 0);
avformat_write_header(_format_context, &params);


text:
Q: Using JAX-RS and trying to DELETE an item I am currently working in Enterprise Java and I'm a newbie. I am trying to create a method which should delete a selected item from a data table. My project contains Graphical User Interface elements from  "http://www.primefaces.org/showcase/".
The deletion is made through a web-service.
This is the method I created so far:
public boolean delete(String articleId) {
        Client client = ClientBuilder.newClient();
        WebTarget target
                = client.target(DELETE_URL);//this is a String

        //TODO call ws method delete
        try{
            target.request()....;
        } catch(Exception ex) {
            LOGGER.error("Delete Article Error ", ex);
        }
         return true;
    }

Could you tell me how can I handle the deletion in an appropiate way?
All the best!

A: In your case the following should do the trick.
target.request().delete(Response.class)


text:
Q: Why can't I draw a line on this D3.js using angular code? I'm trying to draw a graph using the D3.js graphical library for Javascript on my webpage. I can draw a line on an SVG using HTML. But when I try to draw a line using javascript, I get: ReferenceError: d3 is not defined
I get this even though I have included the D3.js file.
Please tell me how I can get around this problem.
Here is the Plunker: https://plnkr.co/edit/pdDCfYmCQxX56sBfjfzW?p=preview
Below are my files for your reference.
Javascript:
myApp = angular.module('myApp', ['ui.router'] );

myApp.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
    $stateProvider.state('myState', {url: '/myState', params: {slug: {value: null, squash: true} }, templateUrl: 'my-state-page1.html', controller: 'MyStateCtrl'} );
  }
);

myApp.controller('MyStateCtrl', function($scope, $http) {
      var self = this;

      $scope.$watch(function() {return self.myDataFromAPI}, function (objVal) {
          console.log('objVal = ', objVal);
          x = objVal.origin.split('.');
          console.log("X = ", x)

          var svgContainer = d3.select("body") .append("svg") .attr("width", 1000) .attr("height", 1000);

          var line = svgContainer.append("line") .attr("x1", x[0]) .attr("y1", x[1]) .attr("x2", x[2]) .attr("y2", x[3]) .attr("stroke-width", 2) .attr("stroke", "black");
        },
        true
      );

      self.httpFailure = function(response) {
        console.log('Failure');
        self.myDataFromAPI = null;
      }

      self.httpSuccess = function(response) {
        console.log('\n\n\nGot the data from the API!');
        self.myDataFromAPI = response.data;
        console.log('\n\n\self.myDataFromAPI =', self.myDataFromAPI);
      }

      $http.get(
        'https://httpbin.org/get'
      ).then(self.httpSuccess, self.httpFailure);
    }
);

myApp.directive('mypMyDirective',function(){
    return {
      restrict:'E',
      scope: {
        myDataFromAPI: '='
      },
      controller: 'MyStateCtrl',
      controllerAs: 'myStateCtrl',
      bindToController: true,
      templateUrl: 'myD3Diagram.html'
    };
  }
);

index.html:
<!DOCTYPE html>
<html ng-app="myApp">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.18/angular-ui-router.js"></script>
    <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    HELLO!
    <div ng-controller="MyStateCtrl as myStateCtrl">
      <myp-my-directive mydatafromapi="myStateCtrl.myDataFromAPI"></myp-my-directive>
    </div>
  </body>
</html>

myD3Diagram.html:
<svg id="my_svg_widget" width="500" height="500">
  <line x1="5" y1="5" x2="40" y2="40" stroke="gray" stroke-width="5"  />
</svg>

A: The problem is that you are accessing a non https library.
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>

it should have been
<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>

working plunk here


text:
Q: Invalid command 'OIDCCookieSameSiteNone', perhaps misspelled or defined by a module not included in the server configuration We are getting Invalid command 'OIDCCookieSameSiteNone', perhaps misspelled or defined by a module not included in the server configuration. We are using apache 2.4 version.
Which modules should we enable for this command in the http config file and what is the syntax for this command
We want to enable samesite none option on the HTTPD file so we dont need to guide every user to update setting on chrome


text: Q: incorrect modalities data in response to https://graph.microsoft.com/v1.0/communications/callRecords getting incorrect data from modalities in https://graph.microsoft.com/v1.0/communications/callRecords/{id}?$expand=sessions($expand=segments). getting "audio", "videoBasedScreenSharing", "screenSharing" for the participant who did not screen share while "audio","videoBasedScreenSharing" for the one who did.


text:
Q: separate Date and time with AM or PM? I have  8/28/2014 12:00:00 AM and i want to access Date= 8/12/2014 and time= 12:00 AM.
How can i separate this date and time in javascript?
I used the following code and got the date according to my requirement but i got time 0:00 but i need 12:00 AM.How it is possible?
 var date = new Date(starttime);
 var startday = date.getDate();
 var startmonth = date.getMonth() + 1;
 var startyear = date.getFullYear();
 var formatDate = startday + "/" + startmonth + "/" + startyear;
 var starttime = date.getHours() + ":" + date.getMinutes();

A: Here is how you can do it:
selectedDateTime = "2009-08-12 14:30:00 AM"   //This is what you currently have
var splitarray = new Array();
splitarray= selectedDateTime.split(" ");

var date = splitarray[0];
var time = splitarray[1] + splitarray[2];

alert("Date: "+ date + "  Time: " + time)

DEMO

A:   Calendar cal = Calendar.getInstance();
  SimpleDateFormat Date_Time = new SimpleDateFormat("HH:mm a / MMM dd EEE");
  SimpleDateFormat Date_Time = new SimpleDateFormat(temp_date_time);
  String Date_Time_dip = Date_Time.format(cal.getTime());

A: var Hours = date.getHours();
var Mins = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;

Source: How do you display javascript datetime in 12 hour AM/PM format?

A: Your code is perfectly fine.
The only thing is;
AM vs PM:
Each period consists of 12 hours numbered: 12 (acting as zero for AM),
AM-> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
PM-> 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23
You should write date as "8/28/2014 12:00:00 PM", not "8/28/2014 12:00:00 AM". Because 12 is PM, not AM, if you mean noon.
If you write 12:00:00 AM, javascript will understand it as 24:00 or 00:00. 12 is midnight for AM.


text:
Q: Иерархия Интерфейсов В книге вычитал, что иерархия интерфейсов отличается от иерархии классов, то бишь какая получается иерархия у интерфейса?

A: Не очень понятно что имелось в виду в приведённой цитате, но кратко дело вот как обстоит

*

*Каждый класс может наследоваться только от одного другого класса.

*Каждый класс может реализовать множество интерфейсов, вплоть до 65К штук

*Каждый интерфейс может наследоваться от множества интерфейсов


text:
Q: How to change axis labels using with visreg along with ggplot2 I'm using the visreg package with gg = TRUE (so it'll use ggplot2 graphics) to render my fitted model plots.
It automatically uses the names of the independent variable factors as the x axis labels, but I need them to appear slightly differently and tried to change the labels text using scale_x_discrete as can be seen here.
But when I do so, the x axis labels, the axis line and its title become blank.
I believe I'm failing to map the labels parameter to the breaks parameter.
I also get the message

Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale.

The problem probably lies within how visreg stores the variables (and its levels) information. When using ggplot2 alone, this information can be easily recovered from the used dataset using data$variablename. But by creating the basic plot through visreg this is not so straightforward.
What I've already tried:

*

*Using the variable's levels' names as plotted by default as the breaks.

*Trying to access the variable levels with fit$xlevels$Species.

*Guessing visreg could be ascribing integers as the levels and trying to use
breaks = c(as.factor("1","2","3")).

How to reproduce the problem:
library(visreg)
library(ggplot2)

data(iris)
fit <- lm(Sepal.Length ~ Species, data = iris)

visreg(fit, gg = T) +
  theme(axis.line = element_line(colour = "black")) +
  scale_x_discrete(breaks = c("setosa", "versicolor", "virginica"),
                   labels = c("SETOSA", "VERSICOLOR", "VIRGINICA"))

# ----------------------- OR the equivalent:

visreg(fit, gg = T) +
  theme(axis.line = element_line(colour = "black")) +
  scale_x_discrete(labels = c("setosa" = "SETOSA",
"versicolor" = "VERSICOLOR", "virginica" = "VIRGINICA"))

How the x axis looks without trying to change the labels:
library(visreg)
library(ggplot2)

data(iris)
fit <- lm(Sepal.Length ~ Species, data = iris)

visreg(fit, gg = T) +
  theme(axis.line = element_line(colour = "black"))

A: I suggest this simple solution:
library(visreg)
library(ggplot2)

data(iris)
iris$Species <- factor(iris$Species, labels=c("SETOSA", "VERSICOLOR", "VIRGINICA"))

fit <- lm(Sepal.Length ~ Species, data = iris)
visreg(fit, gg = T)


text:
Q: PHP Url Validation Error: http://https://example.com (aka https://https://example.com) I had this url regex pattern in place:
$pattern = "@\b(https?://[^\s()<>\[\]\{\}]{1,".$max_length_allowed_for_each_url."}(?:\([\w\d]+\)|([^[:punct:]\s]|/)))@";

It seemed to work pretty well at validating any URL I threw at it, until I realized that https://http://google.com (apparently even stackoverflow is considering that a valid URL (it made that URL clickable, not me, although it did remove one of the colons) so perhaps I am out of luck?) was a valid URL, when it certainly is not.
I did a little research... and learnt that I should be using filter_var instead of a regex for PHP URL validation anyways... and was disappointed to realize that it too is susceptible to this very same validation problem.
I could easily conquer it with:
str_replace(array("https://http://","http://https://"), array("http://","https://"), $url);

But... that just seems so wrong.

A: Well, it is a valid URI.  Technically.  Look at the RFC for URIs if you don't believe me.

*

*The path component of a URI can contain //.

*http is a valid host name.

*The port is allowed to be missing even if the : is present (it's specified as *digit, not 1*digit).  (This is why Stack Overflow removed the colon -- it thought you were using the default port, so it removed it from the URI.)

I suggest writing a special case for this.  In a separate step, check to see if the URI starts with https?://https?://, and fix it.


text:
Q: class loading error after adding application/services to zend framework site I'm trying to add a new folder to the application folder in zend framework, but none of the classes I create in the new folder can be found.
What I have is this structure:
application/
  models/
  modules/
  services/
    Test.php

I tried to call on the class Test.php:
class Service_Test{

}

$test = new Service_Test()

This results in the error:
PHP Warning:  include_once(): Failed opening 'Service/Test.php' for inclusion (include_path='...') in library/Zend/Loader.php on line 146.
(The include_path contains a list of directories, which I removed for privacy).
I thought that Services would be automatically found in the same way that Models are automatically found. Does anyone know how I can make Zend framework find the Services folder?

I tried this as well:
require_once('Zend/Loader.php');
Zend_Loader::registerAutoload();
    $resourceLoader = new Zend_Loader_Autoloader_Resource(array(
        'basePath'  => ROOT_PATH . '/application',
        'namespace' => 'Service',
    ));

PHP Fatal error:  Class 'Service_Test' not found

A: In your bootstrap
protected function _initNamespace(){
  Zend_Loader_Autoloader::getInstance()->registerNamespace('Service_');

}
Then you call call any class that starts with 'Service_'

A: Thanks everyone for your help. I finally figured out what was going on. The site I am working on has an atypical setup. It's not extending any Zend Framework bootstrap class, or calling Zend_Application. The way classes were being autoloaded is by using:
set_include_path(ROOT_PATH . '/application/models'.PATH_SEPARATOR .
             ROOT_PATH . '/library'.PATH_SEPARATOR .
         get_include_path());

require_once('Zend/Loader.php');
@Zend_Loader::registerAutoload();

I changed it to:
set_include_path(ROOT_PATH . '/application/models'.PATH_SEPARATOR .
             ROOT_PATH . '/library'.PATH_SEPARATOR .
         get_include_path());

require_once 'Zend/Loader/Autoloader.php';
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->setFallbackAutoloader(true);
$resources = new Zend_Loader_Autoloader_Resource(array(
          'namespace' => '',
          'basePath'  => ROOT_PATH . '/application/',
      ));
$resources->addResourceTypes(array(
          'service' => array(
              'path'      => 'services',
              'namespace' => 'Service',
          )));

Technically, I did not have to add the resource, but if I didn't, and just relied on putting /application/services into the include path, then I would not be able to prefix my classes with 'Service_'.
I'm not sure I would recommend this setup (no Bootstrap class extension or use of Zend_Application) for anyone else. It would be interesting to see what other people thought of this practice. Good or bad? In any case, that is how I solved the issue.


text:
Q: JavaScript code doesn't add display: block to the elements I have a wierd issue with Chrome / Safari when doing a "show more" feature.
jQuery(document).ready(function ($) {
    size_li = $("#grid .items .item").size();
        x=12;
    $('#grid .items .item:lt('+ x +')').show();
    $('#loadMore').click(function () {
         x= (x+5 <= size_li) ? x+5 : size_li;
         $('#grid .items .item:lt('+ x +')').show();
    });
});

The full code is here and works fine in Chrome on there but the exact same code doesn't work on my local pc or on a live server.
Firefox works fine, from looking at dev tools, the JavaScript isn't adding the display: block to the elements which is the following line:
$('#grid .items .item:lt('+x+')').show();

URL to see issue "live" - https://offtherailsmag.com/new (semi-risque images (lingerie etc.)
Any ideas to how to fix this?

A: You need to change
<script type="text/x-javascript">

to
<script type="text/javascript">


text:
Q: What is the role of cut at the base case? gcd(X,X,X):-
    !.
gcd(X,Y,Z):-
    X>Y,
    !,
    Inter is X - Y,
    gcd(Inter, Y, Z).
gcd(X,Y,Z):-
    Inter is Y - X,
    gcd(X,Inter,Z).

I get the if else nature of the second cut but I don't understand why program just aborts with the first cut.

A: It just means you've reached a state where you can get rid of all possible other solutions. Otherwise when asking for more solutions Prolog would run the third rule resulting in unwanted answers. You could alternatively rewrite it like this (assuming X and Y are unified):
gcd(X,X,X).
gcd(X,Y,Z):-
    X>Y,
    Inter is X - Y,
    gcd(Inter, Y, Z).
gcd(X,Y,Z):-
    X<Y,
    Inter is Y - X,
    gcd(X,Inter,Z).

The version with the cuts runs probably faster because it does not require as much RAM as the version without cuts. But the version without cuts does not require the strict order of the rules.


text:
Q: Converting Paperclip to Carrierwave | undefined method `exists?' I'm converting my app from paperclip to carrierwave based on the documentation on carrierwave's github:https://github.com/carrierwaveuploader/carrierwave and advice from this blog:http://bessey.io/blog/2013/04/07/migrating-from-paperclip-to-carrierwave/
However I'm getting a undefined method error for `exists?' in Articles#show.
Here is my _form.html.erb code
 <%= form_for(@article, html: {multipart: true}) do |f| %>
       .
       .
       .

            <% if @article.image.exists? %>
                <%= image_tag @article.image.url %>

            <% end %>
            <%= f.label :image, "Attach a New Image" %>

            <%= f.file_field :image %>

            <%= f.submit %>

        <% end %>

Here is Articles#show
def show
        @article = Article.find(params[:id])
    end

The Articles Model
class Article < ActiveRecord::Base
    mount_uploader :image, ImageUploader, :mount_on => :image
    default_scope -> { order('created_at DESC') }
    has_many :comments
    has_many :taggings
    has_many :tags, through: :taggings
    # has_attached_file :image
    # validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/gif", "image/png"]

    def total_pages
        @articles = Article.all
    end

    def tag_list
        self.tags.collect do |tag|
            tag.name
        end.join(", ")
    end

    def tag_list=(tags_string)
        tag_names = tags_string.split(",").collect{|s| s.strip.downcase}.uniq
        new_or_found_tags = tag_names.collect { |name| Tag.find_or_create_by(name: name) }
        self.tags = new_or_found_tags
    end
end

Let me know if you need to see anything else. I'm still learning rails and I'm not sure where I need to be looking to debug this particular error.

A: To check the presence of the image you can just use
<% if @article.image_url %>
     <%= image_tag @article.image.url %>

<% end %>

For more information about setting up carrier wave in your app check this episode of railscasts


text:
Q: How do I get list of the document ID's inside a collection without getting the content of the documents in Firestore? I want to do something like:
final collectionReference = Firestore.instance.collection('myCollection');
final List<String> documentList = collectionReference.getDocList();

OR
final query = collectionReference.orderBy('lastUpdated', descending: true).limit(100);
final List<String> documentList = query.getDocList();

Currently when we use get() or query.getDocuments() it will return the whole Document list and all contents along with it. But you know that we wanna optimize reads thus we make use of the 1MiB limit of each Documents. Thus we don't wanna download the whole document's contents. Rather we just need the IDs for other usage. Is there a way to do this ?
Thanks

A: There no way to do this with the Flutter APIs (or any of the web or mobile clients).
The only way is with backend code, where you have a method like select() (link to the nodejs API) on Query that lets you select which document fields to return.  So, you could have your app call a backend to return the document IDs, but not directly in the app.
If you must query from the client, consider moving fields unnecessary for queries to documents in anther collection with the same IDs, and request them only when needed.


text:
Q: How to define alias for command which will be available in shell script? Here is a part of my .bashrc
alias my_command="my_command -1 -2 -3"

and its my shell script
#!/bin/sh
my_command blah blah blah

It occurs into error
./aa: line 2: my_command: command not found

So, how to define aliases for the command in the right way?

A: Two things that happen in interactive shells (expansion of aliases and sourcing of your .bashrc) do not occur when you run a script. You could try adding the following to the top of your script:
source ~/.bashrc         # To get the alias
shopt -s expand_aliases  # To allow alias expansion in your script

You might consider changing mycommand to a shell function; then you wouldn't have to enable alias expansion in your script.
mycommand () {
    my_command -1 -2 -3 "$@"
}

A: alias my_command="/usr/lib/jvm/java-1.7.0-openjdk-1.7.0.9.x86_64/bin/java"
After this type
source .bashrc
After typing source .bashrc are you getting any error?

A: If your intention it to use a specific version of Java, then you might want to define JAVA_HOME and set PATH variable accordingly.
export JAVA_HOME=/usr/lib/jvm/java-1.7.0-openjdk-1.7.0.9.x86_64/bin/java
export PATH=$PATH:export PATH=$PATH:/usr/java/jdk1.5.0_07/bin

If it's about just setting an alias, then the syntax you used is correct (of course, with some valid commands)
alias lm="ls -l"


text:
Q: Upload Magento 2 to production server I created a store with Magento 2.2.5 in windows and I used as server xampp.
I installed Debian 9 and I want to move my project to it.

*

*I copied my project folder to /var/www/html

*I exported and imported my database

*I edited base_url in core_config_data

*I edited app/etc/env.php

Now when I want to access to my store through my web browser I got inaccessible page

My other php projects works perfectly.
Thanks.

A: There may be multiple things here.
Step 1: Put a HTML file name index.HTML and put some text like "Working!" and try to browse your the URL to make sure URL is working.
Step 2: If Step 1 works you can remove the index.html. Look into the root folder of Magento to see if you have .htaccess file available. If not then try to copy it from your local dev environment.
Step 3: Look for the server / PHP / Mysql requirement and your new server fulfill all. Same can be found on below URL.
https://devdocs.magento.com/guides/v2.2/install-gde/system-requirements-tech.html
Step 4: Make sure you have correct File permissions. Same can be found on below URL.
https://devdocs.magento.com/guides/v2.2/install-gde/prereq/file-sys-perms-over.html
Step 5: Clear cache, Compile and deploy your static site content.
Step 6: Make sure you keep the environment same as it was on your local server. For example if you have site setup on development then keep the environment set to development on Debian server.


text:
Q: AC single phase motor control with a TRIAC - failure to trigger I am trying to build speed control for 500W synchronous, single-phase AC induction motor. It is for a fan in my greenhouse.
Here is current design:

I am trying to verify it on breadboard with resistive load (100W lightbulb). The zero crossing detection circuit works well, but TRIAC trigerring does not work.
Notes:

*

*R5 is set such that there is ~12mA current going through the LED in the optotriac. It is above maximum triggering threshold for MOC3052 and well below its current rating (60mA)

*R8 is set such that the maximum current through the optotriac is always  below 1A limit (on 230VAC mains)

*I have tried with BT139-800E TRIAC (on schematic, with sensitive gate) as well as with BTA140-800
Where have I gone wrong? Could you recommend robust/reliable triggerring circuit?
Thank you,

A: Is it firing all the time? or not at all?
Short out U3 output to test the triac for full turn on.
Are you firing with a pulse or delayed DC after ZCS pulse.
To minimise noise pickup, keep gate connection length to a minimum.
Take the return directly to MT1 (or cathode).
If hard wired, use twisted pair or shielded cable.
Fit a resistor of 1kΩ or less between gate and MT1.
Fit a bypass capacitor in conjunction with a series resistor to the gate.
If 60mA is the worst case trigger current at low voltage with R8=470 this would be a trigger voltage of 28V should fire in all 4 quadrants.

A: Just some notes: \$I_F=\dfrac{V_{CC}-1.2V}{R}\$, you get \$ I_F=\dfrac{(5V-1.2V)}{330}\approx11.5mA\$ The reccomandation is to use a current between 10mA and 60mA, so your at the minimum. Consider that browning will reduce the CTR for 50% after years of use.
Using MOSFET may complicate things, since there is a need of only max. 60mA, a small signal BJT NPN transistor should be just fine, but it's up to you if you prefer MOSFETs....
Make sure that MT1 and MT2 aren't swapped, short the transitor Q1 so that LED will turn on - in such way  TRIAC can't remain turned off. Replace the MOC if it doesn't work.
At desired angle turn the LED on and turn it off at an angle close to zero cross, for example at 150 degrees. Add a bleeding resistor accross LED (1.1k) to reduce turn-off time, recalulate the series resitor.


text:
Q: How can I make the standard deviation appear in the status bar? Using Excel 2010, I want to be able to see the (population) standard deviation of the cells I select, in the status bar. I know you can alter the status bar, but I have no VB knowledge whatsoever, so I have no idea how to implement this. Is there anybody here that already has done this, or can tell me how to do this?
I've found the following code online, and it works, but it gives me the SD of the sample, not of the population (so I want to divide by N, not N-1, where is N is the number of selected cells).

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
   Dim sDev
  sDev = Selection.Address(0, 0)
  On Error GoTo errhandler
  Application.StatusBar = "Standard deviation is " & _
  Format(Application.StDev(Range(sDev)), "#.####")
  Exit Sub errhandler:
  Application.StatusBar = False
  End Sub

A: I haven't tested this in VBA, but you could try:
Format(Application.StDevP(Range(sDev)), "#.####")

In Excel(2007 and earlier) the standard deviation formulas are StDev() for a sample or StDevP() for the population


text:
Q: Using "Button" from Toolbox in Vector Panel Designer, for a CAPL I am writing testcases in CAPL and want to activate each test case by using "Button" from Panel Designer.
The problem is that whenever I pressed the Button, it reacted as if it were pressed twice.
I just simply add a code like this to make that problem visible.
(The system variable of "@sysvar::Test_Cases::TC1" is linked to the Button in the Panel Editor)
on sysvar sysvar::Test_Cases::TC1
{
    putValueToControl("Window","CAPL Output View",@sysvar::Test_Cases::TC1);
}

I expect to see only --> Value of @sysvar::Test_Cases::TC1 =1
But the output is like this:
Value of @sysvar::Test_Cases::TC1 =1
Value of @sysvar::Test_Cases::TC1 =0

A: on sysvar X{...} event procedure reacts to value change of X.So in case of button press (0->1) value will be set to one then on button release (1->0) value will be set to zero, so you change the value of X twice. This is why you are getting trigger twice.
To react only once on such button press event, and get notification only once, please use the keyword this  and condition statement.
on sysvar sysvar::Test_Cases::TC1
{
    if (this==1) /* Following block is called only once, on button press 0->1 */
    {
     putValueToControl("Window","CAPL Output View",@sysvar::Test_Cases::TC1);
    }
}


text:
Q: JQuery and multiple inputs,forms,submits I have a bunch of forms as rows in a table. There's a submit button at the end of each row. When this button is clicked, my JQuery function creates two text boxes and another submit button. I want the POST variables from the both forms, so I can ultimately pass it onto my php script via AJAX. What would be the best way of doing this?

The last JQuery function does not work as intended. Pressing the ajax-created submit reloads the page :S

A: As #ajax_form is not present initially. you should use .on:
$("#wrapper").on("submit", "form#ajax_form", function(e)
{
    e.preventDefault();
    alert("It is working...");
    // Your code for Ajax
});

You can use any element wrapping the new form, if not sure put "body" in stead of "#wrapper".
Documentation: http://api.jquery.com/on/
Code Added as per communication in comments:


text: Q: Experience with Blitzer's "Algebra and Trigonometry" Book? Does anyone have any experience with it? Heard its super good but the latest 6th edition costs like 250, you can find the 4th for 30 bucks used. Know of any major differences?


text:
Q: Programming the upgrade of Ubuntu at login session Right after my login session, I would like Ubuntu to execute sudo apt-get update & apt-get dist-upgrade , systematically / automatically. The terminal must be opened so that I can see the output of each of these executions. In particular, I want to be asked to type "y/n" due to the command apt-get dist-upgrade. I don't want to have to type my password : thus, Ubuntu must use it as input of the sudo execution instead of me.
The modifications involved must be independant of any upgrade and migration of Ubuntu.
Question
Which bash file should I edit and in which way ?

A: Create a Startup-Application like descriped in the askuubuntu forum: here.
As command use
<your-terminal> -x sh -c "sudo apt-get update; sudo apt-get dist-upgrade; sleep 30"

So in your case for example
gnome-terminal -x sh -c "sudo apt-get update; sudo apt-get dist-upgrade; sleep 30"

Afterwards the terminal should be opened and you have to enter your password.
Edit: Use sh -c "..." to get both commands run and the sleep command to prevent the terminal of closing immediately (read is not working here?)


text:
Q: Filling in missing dates using a linq group by date query I have a Linq query that basically counts how many entries were created on a particular day, which is done by grouping by year, month, day.  The problem is that because some days won't have any entries I need to back fill those missing "calendar days" with an entry of 0 count.
My guess is that this can probably be done with a Union or something, or maybe even some simple for loop to process the records after the query.
Here is the query:
from l in context.LoginToken
 where l.CreatedOn >= start && l.CreatedOn <= finish
 group l by
 new{l.CreatedOn.Year, l.CreatedOn.Month, l.CreatedOn.Day} into groups
 orderby groups.Key.Year , groups.Key.Month , groups.Key.Day
     select new StatsDateWithCount {
                                    Count = groups.Count(),
                                     Year =  groups.Key.Year,
                                    Month = groups.Key.Month,
                                      Day = groups.Key.Day
                                                                  }));

If I have data for 12/1 - 12/4/2009 like (simplified):
12/1/2009 20
12/2/2009 15
12/4/2009 16

I want an entry with 12/3/2009 0 added by code.
I know that in general this should be done in the DB using a denormalized table that you either populate with data or join to a calendar table, but my question is how would I accomplish this in code?
Can it be done in Linq? Should it be done in Linq?

A: I just did this today.  I gathered the complete data from the database and then generated a "sample empty" table.  Finally, I did an outer join of the empty table with the real data and used the DefaultIfEmpty() construct to deal with knowing when a row was missing from the database to fill it in with defaults.
Here's my code:
int days = 30;

// Gather the data we have in the database, which will be incomplete for the graph (i.e. missing dates/subsystems).
var dataQuery =
    from tr in SourceDataTable
    where (DateTime.UtcNow - tr.CreatedTime).Days < 30
    group tr by new { tr.CreatedTime.Date, tr.Subsystem } into g
    orderby g.Key.Date ascending, g.Key.SubSystem ascending
    select new MyResults()
    {
        Date = g.Key.Date,
        SubSystem = g.Key.SubSystem,
        Count = g.Count()
    };

// Generate the list of subsystems we want.
var subsystems = new[] { SubSystem.Foo, SubSystem.Bar }.AsQueryable();

// Generate the list of Dates we want.
var datetimes = new List<DateTime>();
for (int i = 0; i < days; i++)
{
    datetimes.Add(DateTime.UtcNow.AddDays(-i).Date);
}

// Generate the empty table, which is the shape of the output we want but without counts.
var emptyTableQuery =
    from dt in datetimes
    from subsys in subsystems
    select new MyResults()
    {
        Date = dt.Date,
        SubSystem = subsys,
        Count = 0
    };

// Perform an outer join of the empty table with the real data and use the magic DefaultIfEmpty
// to handle the "there's no data from the database case".
var finalQuery =
    from e in emptyTableQuery
    join realData in dataQuery on
        new { e.Date, e.SubSystem } equals
        new { realData.Date, realData.SubSystem } into g
    from realDataJoin in g.DefaultIfEmpty()
    select new MyResults()
    {
        Date = e.Date,
        SubSystem = e.SubSystem,
        Count = realDataJoin == null ? 0 : realDataJoin.Count
    };

return finalQuery.OrderBy(x => x.Date).AsEnumerable();

A: I made a helper function which is designed to be used with anonymous types, and reused in as generic way as possible.
Let's say this is your query to get a list of orders for each date.
var orders = db.Orders
             .GroupBy(o => o.OrderDate)
             .Select(o => new
             {
                OrderDate = o.Key,
                OrderCount = o.Count(),
                Sales = o.Sum(i => i.SubTotal)
             }
             .OrderBy(o => o.OrderDate);

For my function to work please note this list must be ordered by date. If we had a day with no sales there would be a hole in the list.
Now for the function that will fill in the blanks with a default value (instance of anonymous type).
    private static IEnumerable<T> FillInEmptyDates<T>(IEnumerable<DateTime> allDates, IEnumerable<T> sourceData, Func<T, DateTime> dateSelector, Func<DateTime, T> defaultItemFactory)
    {
        // iterate through the source collection
        var iterator = sourceData.GetEnumerator();
        iterator.MoveNext();

        // for each date in the desired list
        foreach (var desiredDate in allDates)
        {
            // check if the current item exists and is the 'desired' date
            if (iterator.Current != null &&
                dateSelector(iterator.Current) == desiredDate)
            {
                // if so then return it and move to the next item
                yield return iterator.Current;
                iterator.MoveNext();

                // if source data is now exhausted then continue
                if (iterator.Current == null)
                {
                    continue;
                }

                // ensure next item is not a duplicate
                if (dateSelector(iterator.Current) == desiredDate)
                {
                    throw new Exception("More than one item found in source collection with date " + desiredDate);
                }
            }
            else
            {
                // if the current 'desired' item doesn't exist then
                // create a dummy item using the provided factory
                yield return defaultItemFactory(desiredDate);
            }
        }
    }

The usage is as follows:
// first you must determine your desired list of dates which must be in order
// determine this however you want
var desiredDates = ....;

// fill in any holes
var ordersByDate = FillInEmptyDates(desiredDates,

                               // Source list (with holes)
                               orders,

                               // How do we get a date from an order
                               (order) => order.OrderDate,

                               // How do we create an 'empty' item
                               (date) => new
                               {
                                     OrderDate = date,
                                     OrderCount = 0,
                                     Sales = 0
                               });

*

*Must make sure there are no duplicates in the desired dates list

*Both desiredDates and sourceData must be in order

*Because the method is generic if you are using an anonymous type then the compiler will automatically tell you if your 'default' item is not the same 'shape' as a regular item.

*Right now I include a check for duplicate items in sourceData but there is no such check in desiredDates

*If you want to ensure the lists are ordered by date you will need to add extra code

A: Essentially what I ended up doing here is creating a list of the same type with all the dates in the range and 0 value for the count. Then union the results from my original query with this list.  The major hurdle was simply creating a custom IEqualityComparer.  For more details here: click here

A: You can generate the list of dates starting from "start" and ending at "finish", a then step by step check the number of count for each date separately


text:
Q: Consecutive SQL statements with state I'm writing a simple messaging program, where there is a table of messages, which can be claimed by users and have stuff done to them by that user. It isn't predestined which user will claim a given message and so I want a query to select the first of all the available messages, which I have, and then one to mark that message as take, which I also have. The problem is, that I don't want two users using it at the same time to claim the same message and so I want to run the two statements consecutively, without having to go back to the program to find out what to run next in between statements. I believe I can run two consecutive statements by separating them with semi-colons but I want to use data returned in the first query as part of the second. Variables would be perfect, but as far as I'm aware they don't exist in SQL. Is there any way I can preserve state between queries?

A: This is what BEGIN TRAN and COMMIT TRAN are for. Place the statements you want to protect within a transaction.

A:
Is there any way I can preserve state between queries?

No. SQL is not a procedural language. You can rewrite your two queries as a single query (not always possible, often not worth it even if it is possible), or glue them together with a procedural language. Many SQL servers provide a built-in language for this ("stored procedures"), or you can do it in your application.

The problem is, that I don't want two users using it at the same time to claim the same message

Use locks. I don't know what SQL server you are using, but using SELECT ... FOR UPDATE sounds like it would be just what you want, if it is available.

A: Transactions is a good way to go, like le dorfier says, but there are alernatives:
You could do the update first, i.e. tagging a message with the user id or similar. You dont mention which sql flavour youre using, but in mysql, i think it'd look something like this:
UPDATE message
SET    user_id = ...
WHERE  user_id = 0   -- Ensures no two users gets the same message
LIMIT 1

In ms sql, it'd be something along the lines of:
WITH q AS (
  SELECT TOP 1
  FROM message m
  WHERE user_id = 0
)
UPDATE q
SET    user_id = 1

/B

A: You could use a temporary table perhaps.

A: SQL itself doesn't have variables, but (almost?) all RDBMS SQL extensions do. But, I'm not really sure how that alone would solve your problem.
As mentioned, a transaction will do the trick - effectively grouping your 2 unrelated statements together. However, the default transaction level will not work. (Most?) RDBMS server's default transaction level is READ COMMITTED. That doesn't prevent User 2 from reading the same row that User 1 read. For that, you'd need to use REPEATABLE READ or SERIALIZABLE.
This is a classic concurrency issue. Generally, the 2 ways of handling it are pessimistic locking or optimistic checking. A REPEATABLE READ transaction would be pessimistic (incurring the locking expense whether or not it was needed), and checking @@ROWCOUNT is optimistic (assuming it'll work, but doing something sensible when @@ROWCOUNT = 0).
Usually, we use optimistic (locking is expensive), and either use a timestamp or combination of fields read to ensure that we're changing the data we thought. So, my suggestion is to include a rowversion or timestamp field, and pass that back in to your UPDATE statement. Then, check @@ROWCOUNT to see if you updated any records. If you didn't, then go back and pick another message. In pseudo-code:
int messageId, byte[] rowVersion = DB.Select(
  "SELECT TOP 1
      MessageId, RowVersion
   FROM Messages
   WHERE
      User IS NULL";

int rowsAffected = DB.Update(
   "UPDATE Messages SET
       User = @myUserId
    WHERE
       MessageId = @messageId
       AND RowVersion = @rowVersion",
    myUserId, messageId, rowVersion
);
if (rowsAffected = 0)
   throw new ConcurrencyException("The message was taken by someone else");

Depending on your particular statements, you may be able to get away with just repeating the "UserId IS NULL" WHERE clause in your UPDATE statement. That's similar to Brimstedt's solution - but you still must check @@ROWCOUNT to see if rows were actually updated.


text:
Q: yeoman call generator prompt from sub-generator I have yo someGen, that prompts few questions. one of the prompts, someQuestion is asking would you like to use smthng? and the user can choose from smthng1,smthng2 or no.
I have a a sub generator yo someGen:smthng that do something else(smthng1 or smthng2) , with regard to the answer from someQuestion.
Now if the user trying yo someGen:smthng, but earlier (in main gen) he answered no, I want to propmt someQuestion again. giving him the chance to decide smthng now, and then operate yo someGen:smthng according to the new answer, with the ability to regret and answer no again.
How would I do that?

A: Use the yeoman-generator configuration to store user choices. See the documentation http://yeoman.io/authoring/storage.html


text:
Q: PHP foreach issue when separating values I am basically trying to create where the end of the month form date = todays date but in this case 22/09/2016 where opmanager is stored in users get that email and foreach opmanager that has the end of the month date as 22/09/2016 send email. The email script i've done is ready to be implemented into the echo
However where the db fetchs two different opmanagers only one manager is getting the email and isn't been sent to foreach opmanager.
The code below:
<?php

include ("../dbconnect.php");

$sql='SELECT * FROM `clients` WHERE endofmonthform="22/09/2016"'; //TODAYS DATE BACK HERE!

$result=mysql_query($sql);

 while($row=mysql_fetch_array($result)){

    $enddate = $row['endofmonthform']; // End

    $startdate = $row['startofmonthform']; // Start

    $email = $row['email']; //Email to send email to

    $id = $row['id'];

    $formlevel = $row['formlevel']; //To update and check formlevel

    $sitegroupname = $row['mastersite'];

    $manager = $row['opmanager'];

}

$query="SELECT userEmail FROM `users` WHERE userName='".$manager."'";
$resultSet = mysql_fetch_all($query);
foreach ($query as $row) {
    echo $row['userEmail']; //Where send email function will be
}
?>

I need it to send an email to each manager

A: Apart from the coding mistakes, the reason it's only sending the email to a single manager is because the manager bit only gets executed once. Your 2nd query:
SELECT userEmail FROM `users` WHERE userName='".$manager."'

will return a set of users where the username is equal to the LAST $manager from the previous loop because this bit of code is NOT inside the first loop.
Simply moving this bit of code inside the loop will fix your initial issue. The rest of the fixes can be found below:
include ("../dbconnect.php");

$sql='SELECT * FROM `clients` WHERE endofmonthform="22/09/2016"'; //TODAYS DATE BACK HERE!

$result=mysql_query($sql);

 while($row=mysql_fetch_array($result)){

    $enddate = $row['endofmonthform']; // End

    $startdate = $row['startofmonthform']; // Start

    $email = $row['email']; //Email to send email to

    $id = $row['id'];

    $formlevel = $row['formlevel']; //To update and check formlevel

    $sitegroupname = $row['mastersite'];

    $manager = $row['opmanager'];

    $query="SELECT userEmail FROM `users` WHERE userName='".$manager."'";
    $result=mysql_query($query);

    while($row=mysql_fetch_array($result)){
        echo $row['userEmail']; //Where send email function will be
    }

}

That said, this is still bad code.... It uses a deprecated API (mysql_) and it's vulnerable to SQL injection. Take a look at mysqli or pdo for a better API and prepared statements for the SQL injection issue.
If you want to easily use a database with php you could have a look my pdoWrapper: https://github.com/Mastermindzh/pdoWrapper
Edit:
As pointed out in the comments one could, really should, use a join to get this data. This might be a little much for the TS/OP to understand at this point but I will add it anyways for the sake of completeness:
include ("../dbconnect.php");

$sql='SELECT c.endofmonthform, c.startofmonthform, c.email, c.id, c.formlevel, c.mastersite, c.opmanager, u.userEmail FROM `clients` as c LEFT JOIN `users` as u on c.opmanager = u.userName WHERE endofmonthform="22/09/2016"'; //TODAYS DATE BACK HERE!

$result=mysql_query($sql);

 while($row=mysql_fetch_array($result)){

    $enddate = $row['endofmonthform']; // End

    $startdate = $row['startofmonthform']; // Start

    $email = $row['email']; //Email to send email to

    $id = $row['id'];

    $formlevel = $row['formlevel']; //To update and check formlevel

    $sitegroupname = $row['mastersite'];

    $manager = $row['opmanager'];

    echo $row['userEmail']; //Where send email function will be

}


text:
Q: From where does the "Current Version" in the app Page gets displayed Current Version in the App Page is pulled from release dashboard of play Store. Please advise.
Thanks

A: build.gradle file has typically structured like this:
android {
compileSdkVersion 27
defaultConfig {
    minSdkVersion 16
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    ...

versionName is the version that displayed for all users. For more details you can see this answer.

A: If you have opened your project in Android View.
Then on you Left scroll to Gradle Scripts expand it.
Here you see build.gradle(Project:name) and build.gradle(Module:app)
Open build.gradle(Module:app).
On Top of it. you will see
android {
compileSdkVersion 27
defaultConfig {
    applicationId "com.company.app_name"
    minSdkVersion 18
    targetSdkVersion 27
    versionCode 1   //Change this to upgrade your app on PlayStore (Not shown there)
    versionName "1.1.0" //This was just to display on PlayStore
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

A: It's in the Android Manifest file. Though it's common to put it in the Gradle file, Android Gradle puts it into the Manifest file during compiling. The Manifest file starts off as a text file, but is compiled to binary.


text:
Q: Vertical centering in tabularx I am trying to get a text to center vertically within a tabularx. For centered and bottom text it works, but it fails for top text. What am I missing here?
        \begin{tabularx}{\textwidth}{ | X | c | }
            \hline
            \noindent\parbox[t]{\hsize}{\includegraphics[width=5cm]{img/image001}} & top\\
            \hline
            \noindent\parbox[c]{\hsize}{\includegraphics[width=5cm]{img/image001}} & center\\
            \hline
            \noindent\parbox[b]{\hsize}{\includegraphics[width=5cm]{img/image001}} & bottom\\
            \hline
        \end{tabularx}

A: Use valign from adjustbox.
I used also margin=4pt to put some space around the image, and I inverted the column types of your table, I don't think you want an X type for a column where there are only fixed-width images.
\documentclass{article}
\usepackage{tabularx}
\usepackage[export]{adjustbox}
\usepackage{graphicx}

\begin{document}
    \begin{table}\centering
        \begin{tabularx}{\linewidth}{ | c | X | }
            \hline
            \includegraphics[width=5cm, valign=t, margin=4pt]{example-image} & top\\
            \hline
            \includegraphics[width=5cm, valign=c, margin=4pt]{example-image} & center\\
            \hline
            \includegraphics[width=5cm,valign=b, margin=4pt]{example-image} & bottom\\
            \hline
        \end{tabularx}
    \end{table}
\end{document}

Your question may be a duplicate of this one: How to align picture top left in a table?.


text:
Q: Position fixed with translate3d and overflow hidden I'm creating a site with a mobile sidebar, usual stuff, you click the burger menu and the menu slides out from the side. This is all working great apart from one issue. I want the sidebar to fixed to the left hand side and only the main content to be scrollable; I'm using translate3d for the animation and I think i've pinpointed this as the issue.
Does anyone know of any reason why translate3d won't play nice with position fixed? I've done some searching but can't find a solution.
Basic setup..
A containing div around all the content, within this I then have the main content and the sidebar. I animate by toggling the class menu-closed on the sidebar (which changes the translate3d position) and adding menu-open to the outsider wrapper (also changing the translate3d value). The animation is smooth and works well.
HTML

          <form>
            <input class="form-control" type="search" placeholder="search" />

          </form>

link 1

link 2

link 3

link 4

link 5

              <button type="button" class="navbar-toggle" aria-expanded="false" aria-controls="navbar">
                Toggle navigation

              </button>

CSS
.container, .wrapper {
  @include transition(all 0.35s);

  &.menu-open, .menu-open {
    transform: translate3d(175px, 0, 0);
  }
}

.sidebar {
  position: fixed;
  transform: translate3d(0, 0, 0);
  left: 0;
  z-index: 1000;
  display: block;
  padding: 20px;
  overflow-x: hidden;
  overflow-y: auto;
  background: $sidebar-colour;
  border-right: none;
  width: 175px;
  height: 100%;
  @include transition(all 0.35s);

  &.menu-closed {
    transform: translate3d(-175px, 0, 0);
  }
}

@media (min-width: 768px) {
  .sidebar {
    &.menu-closed {
      transform: translate3d(0, 0, 0);
    }
  }
}

JS
window.toggleSidebar = (function(toggleSidebar, $, undefined) {

  /**
   * init
   */

  var init = function() {
    $('.navbar').on('click', '.navbar-toggle', function() {
      toggleClassname('#sidebar-toggle', 'menu-closed');
      toggleClassname('.wrapper', 'menu-open');
    });
  };

  var toggleClassname = function(elem, classname) {
    return $(elem).toggleClass(classname);
  };

  return {
    init: init
  };

})(window.toggleSidebar || {}, jQuery);

This issue is that the fixed sidebar now becomes scrollable and not fixed to the left hand side. I only want the main content to be scrollable and not the sidebar as well.
This is really annoying me so if anyone is able to shed some light then i'd be really grateful!


text:
Q: Is it possible to create a hyperlink which will activate a spreadsheet and run a macro? I currently generate email queries from an excel/vba interface. These emails are to query a specific transaction.
I would like to embed a hyperlink into these emails which would allow the user to navigate to the spreadsheet and trigger a macro with a parameter.
EG:
    investigate
The result of clicking this link should be that Excel is activated, the spreadsheet is opened, the ViewTrans subroutine within the macro is called with the paramater TransID = 1234.
All google search results relate to embedding hyperlinks WITHIN excel, which is of course very straightforward. My question is about how to create an EXTERNAL hyperlink, that can be sent over email. Thanks in advance for advice.

A: No, it is not.
It will not be working as you want. Even if you find a way (I don't think so) the Macro security settings can be set to not run macros on end user machines.
I'd suggest looking for another options.


text:
Q: Surge protection for differential amplifier How does one surge protect a differential amplifier circuit? Assuming the absolut maximum stresses on the amp IC input pins is Gnd-0.5V -> Vcc.
Clearly TVS alone are insufficient to clamp to Vcc. What is the usual solution for this? Say for a 1kA residual lightning protection assumption.

A: For reference, here is information for real-world protection units, meeting sets of safety regulation specification, as used in industrial plant settings, says, sensors and remote control wiring running hundreds meters on outdoor paths, subject to lightning strike.

As original poster suspects, cascaded protection is typically used inside these unit.
You may design your own unit, based on below general information, or buy off-the-shelf.
Gas discharge tube, with different rating specification, is used as the front, to take majority of the energy of the incoming lightning induced surge pulse. This example unit is rated 10kA for 8/20 surge timing profile.
The next is inductor to attenuate fast rising pulse. The current rating is 250mA in this example and can be used for sensor and power supply protection. Some units have lower current rating and limited to sensor use (like 20mA loop sensor/transmitter or near zero current like thermal couple).
Very fast semi conductor devices are used at the final stage to clamp the residual surge to the rated 6V, as in this example. Different unit has different voltage rating, choice depends on the expected operating voltage of the signal line (for thermal couple, near zero. a bit higher for power supply or 20mA transmitter)
For info at a randomly chosen example meeting safety regulation specifications
For info on test specification on pulse shape, like 8/20us, pulse shape info

A: You normally clamp the two inputs to their maximum allowable common-mode range using diodes and some sort of series impedance (resistance) to limit the fault current.
If you have more stringent limits on the allowed differential voltage input, you might apply additional clamping directly between the two inputs. This might take the form of back-to-back silicon diodes for low-level signals, or zener diodes or other technologies for higher-level signals.
If you need particularly low parasitic capacitance, JFETs can be configured to do the clamping, and they generally have much lower capacitance than general-purpose diodes.


text:
Q: EmguCV - Fisheye Calibration For a school project, I am trying to calibrate a Dahua IP Camera, which has Fisheye distortion.
We need to calibrate the camera to undistort the image, because we need a flat image to do image processing.
So far, we have managed to do the calibration in Python with OpenCV, but the rest of the script is written in C#, so we would like to convert the code to C# using the EmguCV wrapper (OpenCV for .NET)
Correct me if I'm wrong, but so far I have done these steps:

*

*I took 50 pictures of a Chessboard Grid, which is used to find the Corners

*I let OpenCV calculate the correct matrices, one called CameraMatrix and the other is the Distortion Coëfficiënts.

*With the 2 calculated matrices, we then Undistort an image, and the result is a flat image with no distortion.

In Python, this code works. I get 2 matrices that works to undistort.
I tried to copy these matrices in C#, without doing the rest of the Calibration. Since it's the same camera setup, the Distortion should be the same.
However, when I try to hardcode the matrices, the result is not what I want.
Could it be an issue related to EmguCV (The wrapper of OpenCV for .NET), or is it something related to my code?
Python Code
img = cv2.imread(filename)
K = np.array(...) # removed for brevity
D = np.array(...) # removed for brevity
DIM = (width, height) # image resolution
map1, map2 = cv2.fisheye.initUndistortRectifyMap(K, D, np.eye(3), K, DIM, cv2.CV_16SC2)
undistorted_img = cv2.remap(img, map1, map2, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)

C# code
Matrix<double> cameraMatrix = new Matrix<double>(3, 3);
Matrix<double> distortionCoeffs = new Matrix<double>(4, 1);
Mat outputMap1 = new Mat();
Mat outputMap2 = new Mat();
Mat r = new Mat(); // Can be empty, according to the documentation
Mat p = new Mat(); // Can be empty, according to the documentation
Fisheye.InitUndistorRectifyMap(cameraMatrix, distortionCoeffs, r, p, image.Size, DepthType.Cv32F, outputMap1, outputMap2);
CvInvoke.Remap(image, undistorted, outputMap1, outputMap2, Inter.Linear, BorderType.Constant);


text:
Q: How Do the KeyEvent.VK_REDO and Similar Constants Work in an Accelerator? I'm trying to create menu item accelerators for undo, redo, etc. in a Java application so I can access them with key commands. I also want to make it so that the proper key command appears on the proper platform. For some menu items, like "Undo", it's pretty simple because it's Cmd/Ctrl+Z:
this.undoMenuItem.setAccelerator(KeyStroke.getKeyStroke(
                    KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));

The method getMenuShortcutKeyMask() returns the Cmd key on a Mac and the Ctrl key on a Windows machine. So far so good.
But some menu items have drastically different key combinations on different platforms. To Redo on Mac OS, you do Cmd+Shift+Z, but on Windows you do Ctrl+Y. Thus the above code won't work unless you do an if/then statement to check what platform you are on and pass one of two sets of parameters into the function.
I noticed that in the KeyEvent class are constants such as KeyEvent.REDO. I'm presuming that this is a constant for the "Redo" key combination, although I'm not sure because there isn't any documentation about what it does. So I tried the following:
this.redoMenuItem.setAccelerator(KeyStroke.getKeyStroke(
                    KeyEvent.VK_REDO, 0));

I had hoped that this would result in the appropriate key combination applied as an accelerator, but instead no accelerator appears to be assigned (i.e. there isn't any indicator of the key combination next of the name of the menu item). Is this the proper use of KeyEvent.VK_UNDO and if so, what am I doing wrong?


text:
Q: curl request in R curl req:
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -d '{"username":"emailId","password":"passwrd"}' -X POST https://central.vizury.com/-/api/login

res:
HTTP/1.1 200 OK
Cache-Control: no-cache, no-store, must-revalidate
Content-Type: application/json; charset=utf-8
Date: Wed, 06 Sep 2017 10:47:00 GMT
Expires: 0
Pragma: no-cache
Set-Cookie: viz.sess3=SessionCookieHere; path=/; expires=Wed, 06 Sep 2017 10:49:01 GMT; secure; httponly
Set-Cookie: AWSELB=someval;PATH=/;EXPIRES=Wed, 06 Sep 2017 10:49:01 GMT;SECURE;HTTPONLY
Vary: Accept-Encoding
X-Powered-By: Express
Content-Length: 226
Connection: keep-alive

{"status":"OK","results":{"username":"email","role":"role","products":["webConvert","mobiConvert"],"needsNewPassword":false},"homePath":"/webConvert/#/dashboard/campaignName"}

I need to perform the same action in R:
This is what I have tried so far:
h <- basicHeaderGatherer()

loginUrl <- "https://central.vizury.com/-/api/login"
params <- list('username' = 'username',
               'password' = 'password')
loginRes <- postForm(loginUrl, .params=params, style="POST",  .opts=curlOptions(headerfunction=h$update, verbose=TRUE))
print("loginres")
print(loginRes)

In response,
print(h$value()['Set-Cookie'] )
I can access Set-Cookie. But how do I access the value of viz.sess3?

A: Example using curl package:
h <- curl::new_handle()
login_url <- 'https://central.vizury.com/-/api/login'
curl::handle_setform(
    handle = h,
    username = 'username',
    password = 'password'
)
resp <- curl::curl_fetch_memory(login_url, handle = h)
message(resp$status_code)
jsonlite::fromJSON(rawToChar(resp$content))


text:
Q: Delphi Parallel programming - multi threading slow Good day,
A webcam class has about 30 frames per second, and all of these frames will be saved in a vector(like a queue). Then 3 asynchronous threads will read the queue, and will try to do their jobs(to save these images). Why the queue is overflowing? So the problem is that these threads are slower than the webcam.
Procedure TSaveThread.Execute;
begin
   while not terminated  do
   begin
      elElement:=NIL;

      EnterCriticalSection(CritSect);
         if iElementsLength>=0 then
         begin
            elElement:=vElements[iElementsLength];
            Dec(iElementsLength);
         end;
      LeaveCriticalSection(CritSect);

      if elElement<>NIL then
      begin
         JpegImg.Assign(elElement.bmWebcam) ;
         JpegImg.SaveToFile('Save\'+elElement.sTime+'.jpg') ;
         elElement.Free;
      end;

      Sleep(20);
   end;
end;

Images added to the queue.
//------------------------------------------------------------------------------
Procedure TWebcam.OnSave(Sender:TObject; bmWebcam:TBitmap);
begin
   EnterCriticalSection(CritSect);
      inc(iElementsLength);
      vElements[iElementsLength]:=TElement.Create(bmWebcam);
   LeaveCriticalSection(CritSect);
end;

Creating the threads.
for i:=0 to 2 do
    TSaveThread.Create(false);

The thing is that, these threads are not able to save all these images. Why? How can I improve my threads?
Delphi Version: Delphi XE2
Webcam frame size: 1280x760 or 960x600
Entire source code here: http://pastebin.com/8SekN4TE

A: MultiThreadding will not speed up your Media (HardDrive).
In fact it can slow down with parallel write access.
At first you have to measure if your Media (HardDisk) is able to store an image in less than 33ms - because every 33.333ms you will get a new image from webcam.
If not, you can't expect to get this running.
You should have to (and/or)

*

*use more hard disks (e.g. one per thread)

*use more cache (e.g. Cache Controller)

*use faster hard disks (e.g. SSD)

*use smaller images (decrease resolution)

*drop some images

And don't loose time if you need to be fast
if elElement<>NIL then
  begin
     JpegImg.Assign(elElement.bmWebcam) ;
     JpegImg.SaveToFile('Save\' + elElement.sTime + '.jpg' );
     elElement.Free;
  end
else
  Sleep(20);

OTL will not help to get your media faster, but would be much cleaner :o)
So you should have a look at

A: I wrote the following program:
{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils, Vcl.Graphics, Vcl.Imaging.jpeg,
  System.IOUtils, System.Diagnostics;

var
  i: Integer;
  bmp: TBitmap;
  jpeg: TJPEGImage;
  Stopwatch: TStopwatch;

begin
  bmp := TBitmap.Create;
  bmp.SetSize(1280, 760);
  jpeg := TJPEGImage.Create;
  Stopwatch := TStopwatch.StartNew;
  for i := 1 to 100 do begin
    jpeg.Assign(bmp);
    jpeg.SaveToFile('C:\desktop\temp\'+TPath.GetRandomFileName);
  end;
  Writeln(Stopwatch.ElapsedMilliseconds);
  Readln;
end.

It converts 1280x760 pixel bitmaps to JPEG images, and then saves to disk. It does so 100 times. On my machine this takes 9 seconds. That's a throughput of 11 images per second. If I skip the convert to JPEG step and save the bitmap directly I can get a through put of 150 images per second. Clearly the conversion to JPEG is a bottleneck.
You are looking for 30 images per second. Whilst multi-threading helps, I suspect you have a quad core machine. One processor for the webcam, and three for the saving. So if you only have three threads available, then you are probably going to struggle to reach the required throughput of 30 frames per second. Theoretical peak on my machine would be 33. If you don't achieve 30 frames per second then your queue will obviously overflow.
The obvious conclusion is that you need to find a faster JPEG conversion library. I'm quite sure that such libraries exist. For example, I think that libjpeg should be a lot faster.
As for your existing code there are some obvious flaws:

*

*Sleep should usually be avoided. In your case it is suicidal to sleep if the last attempt to pull an image succeeded. Don't do that. You should use a real threaded queue. One that allow proper blocking waits on synchronization objects. It's actually pretty trivial to make one yourself using event objects and your favourite non-threaded queue.

*You are holding the lock whilst calling TElement.Create(bmWebcam). That is going to hinder scaling. Assign TElement.Create(bmWebcam) to a local variable, outside the lock. And then assign to the shared data inside the lock.

So, you could check these ideas out by first of all removing the call to Sleep. And then changing TWebcam.OnSave to look like this:
Procedure TWebcam.OnSave(Sender:TObject; bmWebcam:TBitmap);
var
  NewElement: TElement;
begin
  NewElement := TElement.Create(bmWebcam);
  EnterCriticalSection(CritSect);
    inc(iElementsLength);
    vElements[iElementsLength] := NewElement;
  LeaveCriticalSection(CritSect);
end;

These suggestions will help a little, but I think you'll need to tackle the fundamental problem, namely the JPEG conversion.


text:
Q: metronome in C# for WP7 I am a total newbie for app development with a little knowledge of c#. I have some free time in my hand ans was thinking of learning WP7 app development as well as c#. So, I figured I will build a metronome app in c# for WP7. I think learning by doing a project will me most effective.
But, I haven't been able to find much resources on how to accomplish this. On the web there are lots of tuts on how to build a metronome in JS but not in c#. So, If anyone can  point me to some resources to get me started, that would be great. I'll be trying hard learning bits by bits as I progress.

A: http://create.msdn.com/en-US/ You will find tutorials, videos & all sorts of other excellent good times on here.


text:
Q: how disallow only (a-zA-Z) in asp.net? how disallow only (a-zA-Z) in asp.net(C#) in textbox ?

A: You can use an ASP.NET validation control to limit the values that will be accepted by the textbox when it is submitted. I'd suggest using the RegularExpressionValidator.
The benefit of this approach is that it will work on both the server and the client-side ensuring that the input will be valid when processed on the server. Just be sure, on the server side, to call the page's Validate method and to check if the page is valid (IsValid) before processing the value of the textbox.
You can combine this approach with the AJAX control toolkit that safi mentions (or a jQuery plugin) to improve the experience for end users.
Using the ASP.NET RegularExpressionValidator would look something like this:
<asp:TextBox id="textBoxToValidate" runat="server"/>
<asp:RegularExpressionValidator id="regularExpressionValidator" ControlToValidate="textBoxToValidate" ValidationExpression="[^a-zA-Z]*" Display="Static" ErrorMessage="Alphabet characters are not allowed" runat="server"/>

Then on the server side:
private void Page_Load(Object sender, EventArgs e)
{
    Validate();  // force server-side validation controls to validate
    if (IsValid)
    {
        // validation successful
        // you can safely use textBoxToValidate.Text
    }
}

A: You can check key code when user types something in text box.
For example:
function checknumber(e, control) {
    isIE = document.all ? 1 : 0
    keyEntry = !isIE ? e.which : event.keyCode;
    if ((keyEntry > '47') && (keyEntry < '58'))
        return true;
    else if (keyEntry == '8')
        return true;
    else if (keyEntry == '46')
        return false;
    else
        return false;
}

and then call this function on key press:
onkeypress="return checknumber(event, this);"

This code allows only digits in textbox. You can change it as required.

A: While you can disallow it clientside via javascript, it isn't recommended to only use clientside validation. Just apply your validation server side, only way to be sure you only get what you want.

A: here you can see that in asp.net using ajax you can restrict the type of data you want to be in the text box
http://www.asp.net/AJAX/AjaxControlToolkit/Samples/FilteredTextBox/FilteredTextBox.aspx

A: Use, a code some thing like this in javascript
function isCharacter(evt) {
        var charCode = (evt.which) ? evt.which : event.keyCode
        if (charCode >= 65 && charCode <= 90) {
            return false;
        }
        else if (charCode >= 97 && charCode <= 122) {
            return false;
        }
        return true;
    }

and if you dont know i am passing the Textbox onkeypress event code also
onkeypress="return isCharacter(event)"


text:
Q: Sanity check on this DAC reconstruction filter design I've altered a reconstruction filter circuit to use the LTC728XT instead of the AD8608 op-amp used in the example circuit below. Is anyone able to see any issues with my attempt? This is being used as part of a dsp project and the recommended AD8606 is end of line from what I gather + way too expensive. I'll need 4 outputs hence the decision to use an op-amp with 14 pins.

Thanks in advance


text:
Q: PHP mailer setting from address in mail function Ok so I set up a php mailer on 2 separate pages on a site I am working on. I had previously worked through everything in the mailer on a site I built and it was straight forward how to set the email after setting all the variables:
mail("$email",
     "Receipt: $thesubject",
     "$message",
     "From: $replyemail\nReply-To: $replyemail");

So this was what was at the end of the contact (processing) page. I have $email and $replyemail being put into the $message and they come out correctly in the message that gets sent to my email specified by $email.
The part I don't really understand is the address the message says it is coming from is not that $replyemail but instead it says it is being sent from:
rtl.srv@gmail.com

I saw a few posts that were similar but none of them fixed the issue, I followed this and checked to make sure the servers php.ini files had SAFE_MODE = off. Then added
'-f $replyemail'

to the end of the mail function above like that link advised but it didn't change anything... I saw somewhere else that it explained you may have to add the email address to the file /etc/mail/trusted-users but the issue is that email is dynamic. Since that email name is whatever the user input as their email. Then the email is sent to the site admin to review, and I want the email to say it is from the users email that filled out the form.
I know the variables are set correctly because they are being printed out correctly inside the message of the email. So if anyone has any idea why this is happening or how I could go about fixing it I would appreciate any insight.
The project is built in wordpress but I just dropped the files onto the server through SSH, not sure if that has anything to do with it.
Thanks,
-Alan

A: There are a number of issues that can cause this, and I encountered this issue a while ago when I built my site. I solved it by first creating a function to handle the mailout for me:
function mailouthtml($to, $title, $body, $from){
    if(!isset($from)){
        $from = 'Default Sender<address@example.com>';
    }
    $header .= "Reply-To: $from\r\n";
    $header .= "Return-Path: $from\r\n";
    $header .= "From: $from\r\n";
    $header .= "Organization: Example.com, Inc.\r\n";
    $header .= "Content-Type: text/html\r\n";
    mail($to,$title,$body,$header,"-f $from");
}

Let me break this down a bit. The function calls for a To address, the email title, the email body, and the From address. The From address is used to add information to the email header. The header information of your email is what tells your mail server what to do with your email, and it needs a bit of info in order to handle the message properly.
The mail() function in PHP is formatted as follows:
mail($to,$title,$body,$headers,$additional_parameters);

The mailouthtml() function I've created here constructs the header manually, and adds the additional parameter "-f $from" to set the "From" field explicitly. The $from variable is optional in the function call; if it isn't present, it sets a default. You can find more information on the mail function Here.
Note the following:

*

*Most MTA's require a Reply-To, Return-Path and From field, or it may be flagged as spam.

*Content-Type is required tell what type of content the mail server is delivering, typically text/html or text/plain.

*I have an if(){} statement that sets a default address if none is specified. You can omit 'Default Sender' if you would rather not specify a name. You can also change that to whatever you'd like.

*Organization is optional.

I would also recommend you have SPF enabled on your domain name, and DKIM signing on your messages. These are both implemented via DNS entries for your domain name. If you don't have access to that, no big deal; they're meant to control spam.
Also, if you have a dedicated server and your own IP address, make sure you have a Reverse DNS record set up. This will also help foreign MTA's identify your message as authentic.

A: don't make this to yourself. Use some mature library like phpmailer or swiftmailer, they will help you to avoid these kind of troubles...I know there are more includes, etc, but there is not point to give fight to this. If you still want to do this, try setting the header Returh-path