text:
Q: Open source BPM out of box notification feature I am trying to find whether JBPM or any other open source BPM softwares such as Camunda, Activiti has notification feature (i.e. email, mobile notifications) out of the box.
I am trying to find this in their documentation. However, I couldn't find much information.
If someone has used these tools, please share your thoughts.


text:
Q: Why is my program outputting 178 instead of 183?" Write a program to calculate how many months it will take you to save up enough money for a down
payment. You will want your main variables to be floats, so you should cast user inputs to floats.
Your program should ask the user to enter the following variables:

*

*The starting annual salary (annual_salary)

*The portion of salary to be saved (portion_saved)

*The cost of your dream home (total_cost)

*Call the cost of your dream home total_cost.

*Call the portion of the cost needed for a down payment portion_down_payment. For
simplicity, assume that portion_down_payment = 0.25 (25%).

*Call the amount that you have saved thus far current_savings. You start with a current
savings of $0.

*Assume that you invest your current savings wisely, with an annual return of r (in other words,
at the end of each month, you receive an additional current_savings*r/12 funds to put into
your savings – the 12 is because r is an annual rate). Assume that your investments earn a
return of r = 0.04 (4%).

*Assume your annual salary is annual_salary.

*Assume you are going to dedicate a certain amount of your salary each month to saving for
the down payment. Call that portion_saved. This variable should be in decimal form (i.e. 0.1
for 10%).

*At the end of each month, your savings will be increased by the return on your investment,
plus a percentage of your monthly salary (annual salary / 12).
Expected case
Enter your annual salary: 120000
Enter the percent of your salary to save, as a decimal: .10
Enter the cost of your dream home: 1000000
Number of months: 183

My code text output
Number of months = 178

r = 0.04
current_savings = 0
potion_down_payment = 0.25
annual_salary = input('Enter your annual salary: ')
print(int(annual_salary))
monthly_salary = (int(annual_salary) / 12)
potion_saved = input('Enter the percent of your salary to save, as a decimal: ')
print(float(potion_saved))
cost_dream_home = input('Enter the cost of your dream home : ')
print(int(cost_dream_home))
invest_return = ((float(r) * float(annual_salary)) / 12)
amount_to_save = (float(potion_down_payment) * int(cost_dream_home))
potion_saved_f = (float(monthly_salary) * float(potion_saved))
total_saved = (float(invest_return) + potion_saved_f)
number_of_months = (float(amount_to_save) // float(total_saved))
print(int(number_of_months))

A: I did this quickly, but you need a while loop, like:
months = 0
target = 250000
monthly_save = 1000.0
saved = 0.0
rate = .04
subtotal = 0.0

while subtotal < target:
    saved += monthly_save
    subtotal = (subtotal + monthly_save) * (1+(rate/12))
    months += 1
    print(months), print(int(subtotal))

A: OK, I have more time now. I think that you are just lucky that your code came out so close to the expected answer because your computations are off base.  Unless you know of a better formula, you really need a loop in order to compute compound interest month by month. I have analyzed your method below.
invest_return = ((float(r) * float(annual_salary)) / 12)  #.04*120000/12=400
amount_to_save = (float(potion_down_payment) * int(cost_dream_home))#.25*1000000=250000
potion_saved_f = (float(monthly_salary) * float(potion_saved))#10000*.1=1000
total_saved = (float(invest_return) + potion_saved_f)      #400+1000
number_of_months = (float(amount_to_save) // float(total_saved))  #250000//1400 = 178
print(int(number_of_months))

redpajama_set_name: RedPajamaStackExchange


text:
Q: upload files to S3 bucket using jenkinsfile I wanted to upload files to S3 bucket using jenkinsfile. I am using s3Upload like below
 s3Upload bucket: "sample-abc-test1", path: ".", includePathPattern: "flink-**/build/libs/*-all.jar"

files are being uploaded to S3 but its also including the file source path. In this case it uploads to S3 with file structure like
sample-abc-test1 (bucket name) - > . (current dir) -> flink-export -> build -> libs -> flink-export.jar

but I don't want source path to be included. I wanted to store file on S3 with file structure like
sample-abc-test1(bucket name) -> flink-export.jar

Any suggestions on how to ignore the file source path when uploading ?
Thanks!


text:
Q: In where condition split with comma separated string values How to pass a comma separated text to a where condition. I have a query scenario like below
select *
from employees
where employeeid in ('PER5AZ,SF4MDD,WQERR') -- This will not work

Here I need to filter the employeeid by PER5AZ, SF4MDD and WQERR which I get as a comma separated string from front end.
How to do this in SQL Server 2016?

A: try this using STRING_SPLIT function.
select *
from employees
where employeeid in (select value from STRING_SPLIT ('PER5AZ,SF4MDD,WQERR', ','))

Note: STRING_SPLIT works SQL server 2016 or above


text:
Q: Not Storing the value of silver light control in MS CRM 2011 I have used the silverlight control in CRM 2011.It also published on form but the problem is i am not able to store its value in CRM.In general if we create any field and publish that field in Form then its value will be stored after clicking on Save button.and after that when we open that record,we can see control value that was stored previously.but in my case i published that silver light control on form but after save the record when i click on Record i cant see its value again.means silverlight control value was not going to stored in CRM.I have just simply used the textbox of silverlight...

A: You will need to call a JavaScript function on your form from Silverlight. Take a look at the HTML Bridge for communicating between the page and Silverlight.  There's an example in the MSDN of registering and calling a JavaScript function from Silverlight.
In Silverlight it looks like:
HtmlPage.Window.Invoke("myJSMethod", myParam);


text:
Q: Setting up a basic Vlan on Cisco switch? I have a basic Cisco 2960 switch, and I'm trying to figure out how to setup Vlans.
Basically I want to create a very simple Vlan layout, Vlan 1 for management, Vlan 2 for servers.
Despite my efforts I am unable to route both Vlans to the internet.  I do not have access to switches or routers above my network.  I've also installed the latest firmwared for the Cisco 2960 12.2 that allows static IP routing.
The issue here is I have let's say port gi51 as my uplink to my provider, gi1 - remote server, gi2-gi48 are my servers.  When I set Vlan 2 to gi2-gi48 as untagged, they immediately loose internet, since gi51 is the uplink and set to untagged Vlan 1.
My question is, how can I route multiple untagged Vlans to the internet?  Or am I going about this completely wrong?  My basic goal is to segregate my servers broadcast domain in anyway possible.  Thank you for any help offered.

A: I think you are confusing your terms. Tagging and routing occur at different network layers.
You'll need to configure vlan interfaces on your switch, and you need to enable routing if you have not done that already.
Lets say for example that

*

*vlan 1 is subnet 1.1.1.0/24

*vlan 2 is subnet 2.2.2.0/24

*the 'inside' interface of your internet router is 1.1.1.254

You need something like this on your router...
ip routing

interface vlan 1
ip address 1.1.1.1 255.255.255.0
no shut

interface vlan 2
ip address 2.2.2.1 255.255.255.0
no shut

ip route 0.0.0.0 0.0.0.0 1.1.1.254

Servers on vlan 2 would then need their IP addressing & gateway updating to reflect the vlan 2 address schema. Since you say vlan 1 already has internet connectivity, I would suppose that the interface & routing for vlan 1 is in place already.
As an aside I would recommend not using vlan 1 for anything as different vendors interpret traffic tagged into vlan 1 in different ways.


text:
Q: Eclipse war export: optimize for a specific server runtime In eclipse, when exporting a web project to war/ear file there is this option

"Optimize for a specific server runtime"

What does happen under the hood when this option is selected? Couldn't find an explanation about that so far.
I am running Eclipse Indigo 3.7.

A: Eclipse itself doesn't do anything with that option. What happens is dependent on a particular server adapter. Many of the adapters don't do anything with this option either, but they might in the future.
If a server adapter does support export optimization, it has the option of displaying custom options beneath that pop-up list of runtimes, so that's a good cue to use to see if something will actually happen.
For instance, when targeting WebLogic Server, you will see this:

A: maybe pre-compiles JSPs - this is the first typical thing to do=) ?


text:
Q: How to retry job until fail in laravel? I have a number of jobs on my queue table. I want to run a job until fail. After that job, the queue polls next job.
Currently Laravel Queue pulls all jobs to run row by row. But I don't want to pull next job unless first job is succeed.

A: If you can detect if your first job is done or not, you can use:
$this->release(10);

inside the job to release the job 10 seconds if the first is not finished.
This way allows you to process a job if you want or not and return to the queue if it's necessary.


text:
Q: Recurrence Relation Master Theorem T(n) = 6T(n/3) + n * (n-1)
T(1) = 4

If we have a recurrence relation like above, what should we do?
   --> a*T(n/b) + f(n)
   --> a*T(n/b) + O(n^d)
   --> 6*T(n/3) + O((n^2) - n)
   --> 6*T(n/3) + O(n^2)

It seems to like we should use O(n^d). If we go through that way, result is O(n^2).
But I cannot be sure of that. It's like something is missing. Can anyone help to tell is this way true, how to solve this step by step? Thanks in advance.

A: In my opinion you can continue to apply the theorem to the next step :

with

*

*

*

*

According to the 1rst generic form of the master theorem : wikipedia


text:
Q: Calling webmethod in code behind from client jQuery I am trying to use jQuery to directly call ASP.NET AJAX page methods. I'm using encosia.com as a reference. My inline javascript is

Click here for the time.

with my webmethod being
<WebMethod()> _
Public Shared Function GetDate() As String
    Return DateTime.Now.ToString()
End Function

I would use FF and check POST sent, but since where I'm at currently only has IE 7 this is a little hard to do. Other relevent information, ASP.net 2.0. Does anyone know what I'm doing wrong?

Update
web.config - pre-existing still not working
<httpModules>
  <remove name="FormsAuthentication" />
  <remove name="PassportAuthentication" />
  <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</httpModules>

A: Since you're using ASP.NET 2.0, you'll need to install the ASP.NET AJAX Extensions, like Joe Enos mentioned. I have a bit more info on the necessary configuration work here: http://encosia.com/asmx-scriptservice-mistakes-installation-and-configuration/
Additionally, the .d wrapper around the response is an addition that didn't come until ASP.NET 3.5. So, even if you've got everything else working right, your msg.d will be undefined in ASP.NET 2.0. Omit the .d and just make that:
success: function(msg) {
  // Replace the div's content with the page method's return.
  $("#Result").text(msg);
}

A: In .NET 2.0, you need to make sure you install the ASP.NET AJAX extensions. In .NET 3.5 and 4.0, the encosia solution works without any modifications.
I don't remember exactly what you need to install, but it might be this.

A: Have you checked your web.config to allow page methods?
<system.web>
  <httpModules>
    <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  </httpModules>
</system.web>

There is a similar issue here at this post here


text:
Q: How to get the current rounded hour in MySQL? select current_time() gives:
16:43:16

how can I modify it to get:
16:00

I tried to play with it a bit and I wrote this:
select TIMESTAMPDIFF(HOUR,CURDATE(),current_timestamp())

Which gives:
16

I can convert it to string and add :00 but I think there might be easier way to get what I want.
Any ideas?

A: Personally, I'd use DATE_FORMAT with appropriate format including literals e.g.
 SELECT DATE_FORMAT( CURRENT_TIME() ,'%H:00')

MySQL also provides equivalent TIME_FORMAT function
 SELECT TIME_FORMAT( CURRENT_TIME() ,'%H:00')

https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_time-format


text:
Q: Oracle XML query returns NULL I need to convert XML data to field/value pair but my query for the value is returning nulls
I have an XML type column in Oracle that I am trying to parse to get the field/value pair. I'm not sure if the structure of the XML is the cause but I cannot extract the value.
Here is a sample of the XML data:
<SaleFile BRANCH_ID="ABCZ7" name="FILE20190523_BN0016_MAIN.DAT" File_Type="MAIN" id="574455888ABCYY7" type="ACCOUNT">
    <FIELD Type="ACCOUNT BALANCES AND CORRESPONDING DATES" Redact_ind="FALSE"  Name="POSTED_PMT_AMT">-673.00</FIELD>
    <FIELD Type="CONSUMER CONTACT INFORMATION" Redact_ind="FALSE" Name="SECONDARY CUSTOMER">N</FIELD>
    <FIELD Type="CONSUMER IDENTIFYING INFORMATION" Redact_ind="FALSE" Name="SECONDARY CUSTOMER NAME"></FIELD>
</SaleFile>

I am trying to get the posted amount returned in my query.
SELECT xt.*
FROM SALES_DATA x,
     XMLTABLE('/SaleFile/FIELD'
     PASSING x.SELLER_DATA
     COLUMNS
       FIELD_VAL VARCHAR2(500) PATH 'FIELD'
     ) xt

The query runs without error but all I get back are NULLs.

A: Consider a different approach with xmlSequence and extractValue() with conditional in XPath expression:
select
    extractValue(value(e), '//FIELD[@Type=''ACCOUNT BALANCES AND CORRESPONDING DATES'']') AS "amount"
from SALES_DATA x,
    table (xmlSequence(extract(xml, '/SaleFile'))) e

Rextester Demo

A: Figured out by just trying some different codes:
SELECT xt.* FROM SALES_DATA x,
XMLTABLE('/SaleFile/FIELD'
PASSING x.Seller_DATA
COLUMNS
FIELD_VAL VARCHAR2(500) PATH '/' ) xt
this gave me the list of values for each FIELD node.

A: You have few FIELD elements, so a filter based on the Name="POSTED_PMT_AMT" attribute will be helpful.

SQL

SELECT xt.*
FROM SALES_DATA x,
     XMLTABLE('/SaleFile/FIELD[@Name="POSTED_PMT_AMT"]'
     PASSING x.SELLER_DATA
     COLUMNS
       PMT_AMT NUMERIC(10,2) PATH './text()'
     ) xt


text:
Q: Vagrant multi-machine provisions every machine If I try vagrant up secondmachine against this Vagrantfile below, Vagrant will only create one Ubuntu VM named "secondmachine". However, Vagrant will still try to run the "firstmachine" script on it.
How can I convince Vagrant to only provision machines it's actually brought up, and/or that have been specified on the command-line? Is there a right way and a wrong way to loop through multiple machine definitions?
# coding: utf-8
# -*- mode: ruby -*-
# vi: set ft=ruby :

nodes = [

  {
    :name      => "firstmachine",
    :autostart => false,
    :box       => "centos/7",
    :provisioners => [
      {
        :script  => "cat /etc/redhat-release",
      },
    ],
  },

  {
    :name      => "secondmachine",
    :autostart => false,
    :box       => "ubuntu/trusty64",
    :provisioners => [
      {
        :script  => "apt-get update",
      },
    ],
  },

]

Vagrant.require_version ">= 2.0.2"

Vagrant.configure("2") do |config|
  nodes.each do |node|

    # Will ignore any node without a name!
    next if node[:name].empty?

    config.vm.define node[:name], autostart: node[:autostart] do |machine|
      machine.vm.box = node[:box]

      node[:provisioners].each do |provisioner|

        config.vm.provision
          type: "shell",
          privileged: privileged,
          inline: provisioner[:script]

      end

    end

  end

end

A: The mistake is that the provisioner is assigned to the config object, not the subsequent machine instances. In short, changing config.vm.provision to machine.vm.provision clears up the trouble.


text:
Q: Android error signal 11 when a movie draws into a canvas I'm developing an Android application in which I'm trying to display a GIF image.
For that I am using the Movie class and created a class GIFView that extends View. I getting a Movie instance from Movie.decodeFile method.
I am getting an error when Movie.draw(canvas) is called.
04-28 13:44:18.001: A/libc(24883): Fatal signal 11 (SIGSEGV) at 0x00000000 (code=1), thread 24883 (mple.channel002)

There is the concerned code :
    public void setGif(File gif)
    {
        movie = Movie.decodeFile(gif.getAbsolutePath());
    }

    @Override
    public void draw(Canvas canvas) {
        // TODO Auto-generated method stub
        super.draw(canvas);
        canvas.drawColor(0xFFCC3C6C);

        if(movie != null)
        {
            if(movieStart == 0)
                movieStart = android.os.SystemClock.uptimeMillis();
            int duration = Math.max(movie.duration(), 1000);
            movie.setTime((int)(duration - ((android.os.SystemClock.uptimeMillis() - movieStart)%duration)));

            movie.draw(canvas, 10, 10);//TODO CRASH

            invalidate();
        }
    }

I  create a GIFView in the main, call setGIF method above to give it the path and add it to the layout with FillParent parameter.
It works when I print this image in an ImageView.
Drawing a drawable in the canvas instead of the GIF works too.
So the problem seems to deals with the Movie instance.
I used these links to make the GIFView
http://weavora.com/blog/2012/02/07/android-and-how-to-use-animated-gifs/
I also tried it this way but same error on movie.draw
Info about the Movie class for Android
EDIT1:
I do my tests on an Oppo Find 7a on Android 4.4.2 / snapdragon 801 / 2GB
Changing movie.draw(canvas, 10, 10) to movie.draw(canvas, 10f, 10f) doesn't change anything.
EDIT2:
I just tested on an old ZTE device with Android 2.3.5 and it worked..
So something is wrong when launching on Find7a device but I can't figure out what :(

A: FINALLY!
I found the answer, it appears that on some Android version or devices hardware acceleration needs to be disabled.
I just added this this to my manifest:
<application android:hardwareAccelerated="true" ...>

More information on using enabling/disabling hardware acceleration can be found here.

A: I found another solution - you have to disable hardware accelerator only on this specific view you draw movie. Use next line:
view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

Reference (view level)
https://developer.android.com/guide/topics/graphics/hardware-accel.html#controlling


text:
Q: Корзина angular.js Нужно сменить значок $ на руб в корзине, два дня ищу не могу найти, и убрать две цифры после точки.
Вот ссылка на jsfiddle.

A: Спасибо всем за помощь, ответ
это {{ ngCart.totalCost() | currency: }}
заменить на это {{ ngCart.totalCost() | currency: "RUB" }}


text:
Q: Hashtable using generic lists implementation Can anyone please help me with an implementation of a hashtable using generic lists? So far, I got this, can anyone please tell me if this is the right way to go?
typedef struct HashTable {
    int key_len;
    int data_len;
    int num_buckets;
    HashEntry *buckets;
} HashTable;

typedef struct HashEntry {
    void* key;
    void* data;
    HashEntry* next; //list for collision resolution
} HashEntry;

A: This looks a lot more like a linked list than a hash table IMHO.  A hash table should be something like an associative array with the hash as the key and the record as the value.


text:
Q: Java Compiler Cannot Find Kafka Class I'm having problem using the last answer of this question in my Java code.
Kafka: Get broker host from ZooKeeper
Specifically, it fails finding the last argument on this line:
ZkClient client = new ZkClient("localhost:2181", 10000, kafka.utils.ZKStringSerializer);

I'm using Maven and these are the dependencies in the pom.xml if it matters.
<dependencies>
        <dependency>
                <groupId>org.apache.kafka</groupId>
                <artifactId>kafka_2.11</artifactId>
                <version>0.8.2.2</version>
        </dependency>
        <dependency>
                <groupId>com.101tec</groupId>
                <artifactId>zkclient</artifactId>
                <version>0.7</version>
        </dependency>
</dependencies>

A: You have to use like this
ZkClient client = new ZkClient("localhost:2181", Integer.MAX_VALUE,10000, kafka.utils.ZKStringSerializer$.MODULE$);

kafka.utils.ZKStringSerializer is a scala object. To use scala object in java you have to use like above.


text:
Q: how to show hidden files using j2me LWUIT api I'm making a FileBrowser using LWUIT.
The problem is when I hide a file using setHidden(true) the application can never display it
any more using the listfiles() so I can't unhide it.

A: This seems to be an omission in LWUIT4IO. I fixed it in Codename One so it should work as expected there.


text:
Q: Amplitude Calibration for Pulse Amplitude Modulated (PAM) Infrared (IR) Link with Relative Motion Between Emitter and Receiver I have a project on the drawing board that requires information from some sensors to be passed from a rotating platform via IR link.
This is basically going to be inside the generator next to the windings and I was worried about RF interference and the changing magnetic fields so I thought that going with IR would be better than RF.
The distance between emitter and receiver should be no more than 20 cm (it could be low as 10cm, depending on the mechanics of the generator, but I'm being conservative).
The bandwidth requirements (0.8 Mbps average rate per data channel, with possibly 3-4 data channels) necessitate some method of modulation that allow more bits per symbol.
I was considering PAM but it seems that one issue is how to calibrate for the change in brightness as the transmitter moves toward and away from the receiver. It doesn't seem I can use a reference calibration pulse at the beginning of the transmission since the distance between transmitter and receiver distance vary the entire transmission.
How is this normally handled? Is it just not possible with this PAM?

A: Maybe use a discrete ring of IR emitters and possibly this IR Rx, but you don't have enough system specs to choose anything yet.
https://www.digikey.ca/product-detail/en/vishay-semiconductor-opto-division/TFDU8108-TR3/751-1087-2-ND/1681221
But these are rapidly going or are obsolete.
A bigger picture of the actual measurement problem might be helpful.

A: Forget about PAM. 800 kbps is easily handled with simple binary modulation, using multiple emitters and/or multiple detectors.


text:
Q: Why go through the trouble of static_cast-ing a number to a double? Ran across this in code I'm working through:
double part2 = static_cast<double>(2) * somthing1
  * ( static_cast<double>(1) + something2 )
  + ( static_cast<double>(1) / static_cast<double>(2) ) * something3
  + ( static_cast<double>(1) / static_cast<double>(2) ) * pow ( something4, 3 );

(The somethings are doubles.)
I suspect that there's a really good reason for going through the trouble of doing
static_cast<double>(1)
and the like, but it seems like I could get by with a lot less typing.
What am I not understanding?
Thanks in advance.

A: Many of these static_casts are unnecessary, because of automatic numeric promotion. The ones that are extremely necessary are the ones used on constructing the number 1/2, although in this case there's no obvious reason not to just say 0.5 instead. In any case a compiler that's paying attention will remove all of these and replace them with compile-time constants.

A: I agree with the previous answer that 2.0 would be much better here.
However, I found another red flag in the code, namely pow(something, 3). The pow function is designed to take two arbitrary values, x and y and return x^y. As this function must handle arbitrary values, it will do an approximation. However, this 1) is complex to calculate and 2) sometimes miss the mark. In this case, you would be much better of simply using something4 * something4 * something4.

A: This is equivalent to the much more readable
double part2 = 2 * somthing1 * (1 + something2)
  + 0.5 * something3 + 0.5 * something4 * something4 * something4

since integers are promoted to doubles each time an arithmetic operation has one double operand. The 0.5 double litteral is enough to promote everything to double.


text:
Q: How to deal with Terraform destroy operation when azure policy requires NSG on all subnets? We have a policy on our subscription that forces all subnets to have an NSG.  Terraform works well when creating the Subnet / NSG.  However, it encounters policy error when doing terraform destroy because it tries to remove the NSG from the subnet first.  This gets blocked because of the policy for requiring NSGs on all subnets.  Is there a way to work around this in terraform or possibly make the subnet / nsg removal an atomic operation?
Terraform v0.11.13
+ provider.azurerm v1.25.0

A: This is a difficult problem to solve, and there are only sloppy solutions.  I am speaking generically to handling policy with terraform.  Essentially you want to inject the exclusion of a scope on the fly to the resource:
Options

*

*Simply go to the Azure Portal and exclude the policy on the resource prior to the destroy.  If you disable the policy you need to put it back.

*Build an on the fly terraform for the policy assignment in a pipeline prior to a run which would add a not_scope for the targeted resource. Since the policy assignment is already deployed, a step of importing it will be required.

*Come up with a way of signaling a policy engine (what ever you are using automate your Azure policy).  Add a not_scope that to your pipeline.

*Skip using terraform use Azure CLI or REST interface to update the scope.

For options 2, 3 or 4 a pause is needed for the policy assignment to become active.  My experience is it will vary and sometimes fail, but if you are executing a pipeline you can alert on it and rerun.


text:
Q: How can I Add sub menus to dropdown menus? I am having extreme dificulties to add a sub-menu to my dropdown, but I am not a pro on css. I would like to put a submenu on the part it says "10º ano" and "11º ano" in the dropdown "projects", but everything I do doesn't work ! How can I put submenus and open on the right side when cursor is placed ?
---------------------------------------Here is the HTML -------------------------

Sobre mim

Sobre o curso

                Projectos ▼

10∘  Ano ▶

11∘  Ano ▶

Contactos

--------------------------------------------------and here is css ----------------------------------

A:

 .clearfix:after {
    display:block;
    clear:both;
}
/*----- Menu Outline -----*/
 .menu-wrap {
    width:100%;
    box-shadow:0px 1px 3px rgba(0, 0, 0, 0.2);
    background:#3e3436;
}
.menu {
    width:1000px;
    margin:0px auto;
}
.menu li {
    margin:0px;
    list-style:none;
    font-family:'Ek Mukta';
}
.menu a {
    transition:all linear 0.15s;
    color:#919191;
}
.menu li:hover > a, .menu .current-item > a {
    text-decoration:none;
    color:#be5b70;
}
.menu .arrow {
    font-size:11px;
    line-height:0%;
}
/*----- Top Level -----*/
 .menu > ul > li {
    float:left;
    display:inline-block;
    position:relative;
    font-size:19px;
}
.menu > ul > li > a {
    padding:10px 40px;
    display:inline-block;
    text-shadow:0px 1px 0px rgba(0, 0, 0, 0.4);
}
.menu > ul > li:hover > a, .menu > ul > .current-item > a {
    background:#3e3436;
    border-radius: 10px;
}
/*----- Bottom Level -----*/
 .menu li:hover .sub-menu {
    z-index:1;
    opacity:1;
}
.sub-menu {
    width:130%;
    text-align: center;
    padding:5px 0px;
    position:absolute;
    top:100%;
    left:0px;
    z-index: -1;
    opacity:0;
    transition:opacity linear 0.15s;
    box-shadow:0px 2px 3px rgba(0, 0, 0, 0.2);
    background:#2e2728;
    border-radius: 10px;
}
.sub-menu li {
    display:block;
    font-size:16px;
    position: relative;
}
.sub-menu li a {
    padding:10px 7px;
    display:block;
}
.sub-menu li a:hover, .sub-menu .current-item a {
    background:#3e3436;
    border-radius: 10px;
}
.sub-menu li:hover a, .menu .current-item a {
    text-decoration: none;
    color:#E68268;
}
/* li.sub-menu li {
        display:none;
        position: absolute;
        left: 100%;
        top:0;
    }
    li.sub-menu:hover li {
        display: block;
    }*/
 .sub-menu li ul {
    display: none;
}
.sub-menu li:hover ul {
    display: block;
    width: 100%;
    position: absolute;
    left: 100%;
    top: 0;
    text-align: center;
    padding:5px 0px;
    transition:opacity linear 0.15s;
    box-shadow:0px 2px 3px rgba(0, 0, 0, 0.2);
    background:#2e2728;
    border-radius: 10px;
}

Sobre mim

Sobre o curso

                Projectos ▼

10∘  Ano ▶

1Ano

1Ano

11∘  Ano ▶

1Ano

1Ano

Contactos


text:
Q: Apply function on each cell in a column and add the result to a new column I have a data.table as shown below. What I want is to apply a function to each of the elements in column C. The function will take in a vector(since Col C contains vector elements) and return another vector. This resultant vector should be added to a new column.
     A   B         C
1:  16  151 c(2579, 2659, 2752)
2:  16  152 c(2580, 2660, 2753)
3:  16  153 c(2581, 2661, 2754)
4:  16  154 c(2582, 2662, 2755)
5:  16  155 c(2583, 2663, 2756)
6:  16  156 c(2584, 2664, 2757)

For example let us consider a function 'isOdd' that takes in a vector and returns a logical vector. The output table after applying this function should look like
     A   B           C            isOdd
1:  16  151 c(2579, 2659, 2752)  c(T,T,F)
2:  16  152 c(2580, 2660, 2753)  c(F,F,T)
3:  16  153 c(2581, 2661, 2754)  c(T,T,F)
4:  16  154 c(2582, 2662, 2755)  c(F,F,T)
5:  16  155 c(2583, 2663, 2756)  c(T,T,F)
6:  16  156 c(2584, 2664, 2757)  c(F,F,T)

How do I achieve this?

A: Using R's apply functions, we can easily accomplish your goal.  Lets say that d is your data.table you are working with.  Basically lapply passes each row of column "C" to the anonymous function, which then further passes each element of the passed in row to the function, isOdd.
isOdd <- function(x) {
    if (x %% 2 == 0) return("F")
    else return("T")
}

d$isOdd <- lapply(d$C, function(x) sapply(x, isOdd))

A: DT = data.table(A=letters[1:3], B=list(1:3,4:6,7:8))
DT
   A     B   # notice B is list column containing vectors of different lengths
1: a 1,2,3   # it isn't a character vector, although it prints like one
2: b 4,5,6
3: c   7,8

> DT[,L:=sapply(B,length)][]
   A     B L
1: a 1,2,3 3
2: b 4,5,6 3
3: c   7,8 2

> isOdd = function (x) x%%2 == 0

> DT[,odd:=lapply(B,isOdd)][]
   A     B L              odd
1: a 1,2,3 3 FALSE,TRUE,FALSE
2: b 4,5,6 3  TRUE,FALSE,TRUE
3: c   7,8 2       FALSE,TRUE


text:
Q: Apache POI Java program working fine in IDE (Eclipse) but encounter NoClassDefFoundError when I tried to run it as a runnable jar I got a very strange problem that my program runs in Eclipse but doesn't run well wen exported as a runnable jar. I am getting ClassNotFoundException.
C:\Users\43156557\workspace\CAF3_IDE\MFTRelease>java -jar MSDocWriter.jar
Exception in thread "main" java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoa
der.java:58)
Caused by: java.lang.NoClassDefFoundError: org/dom4j/DocumentException
        at org.apache.poi.openxml4j.opc.OPCPackage.init(OPCPackage.java:149)
        at org.apache.poi.openxml4j.opc.OPCPackage.<init>(OPCPackage.java:136)
        at org.apache.poi.openxml4j.opc.Package.<init>(Package.java:54)
        at org.apache.poi.openxml4j.opc.ZipPackage.<init>(ZipPackage.java:81)
        at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:220)
        at org.apache.poi.util.PackageHelper.open(PackageHelper.java:39)
        at org.apache.poi.xwpf.usermodel.XWPFDocument.<init>(XWPFDocument.java:1
11)
        at com.hsbc.glt.automation.test.mft.util.MSDocumentWriter.initializeDocu
ment(MSDocumentWriter.java:92)
        at com.hsbc.glt.automation.test.mft.util.MSDocumentWriter.main(MSDocumen
tWriter.java:70)
        ... 5 more
Caused by: java.lang.ClassNotFoundException: org.dom4j.DocumentException
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 14 more

C:\Users\43156557\workspace\CAF3_IDE\MFTRelease>

A: ClassNotFoundException usually depicts that JVM is not able to load the required class file from the defined classpath (either the path is not correct or the class / jar is not present at the path).
The Error in current scenario might be cause have missed to include the Dependency libraries when creating the jar file. Since on eclipse you have the class-path correctly including those its working perfectly.
Make sure that you check "Package Required Jar into generated JAR" , this will include the jar files automatically from your eclipse build path.
for detailed info this might come handy Include Dependent Jars in Executable Jar


text:
Q: SQL Select query to select data between to dates where from date month is higher than the to date month and year difference is >1 I want to select all the records from a table where the query params is something  like:
from_month: 09
to_month : 03
from year: 2011
to_year: 2014
I am trying the below query:
Select * from Table
where month(created_at) between '09' and '03'
     and year(created_at) between '2011' and '2014'

Although the data is there it returns me zero records as the from_month is greater than the to month.
I even tried the query to directly compate the dates instead of month and year seperately, but it still returns me zero records.

A: Can you try it? I think You are between done this way. Its got maximum to minimum between
where month(created_at) between '09' and '03'

instead
where month(created_at) between '03' and '09'

or Use greater than and less than way
SELECT * FROM tbl WHERE month(created_at)>='09' AND month(created_at)<='11'

A: Your query fails for two reasons. First, between needs to have lower limit first, then the upper one. beween 9 and 3 will therefore always get you 0 records.
Second, it will miss for example the records between '2012-01-01' and '2012-02-28' and the records between '2012-10-01' and '2013-02-28'.
Don't make it more complicated as it is.
SELECT * FROM table1
WHERE created_at BETWEEN '2011-09-01' AND '2014-03-31'

It's also better to do it this way, since MySQL can not use indexes on the columns where you apply a function.
If you don't know, if the upper date's day is 30, 31, 28 or even 29, you can do it this way:
SELECT * FROM table1
WHERE created_at BETWEEN '2011-09-01' AND LAST_DAY('2014-03-01');

Also note, that you have to append a time, when your created_at column is of type timestamp or datetime. Otherwise you'll miss the last day's records.
SELECT * FROM table1
WHERE created_at BETWEEN '2011-09-01' AND '2014-03-31 23:59:59'

When you don't append a time, it automatically becomes 00:00:00, therefore you'd miss 2014-03-31.


text:
Q: QGIS WMS clipping issue I'm using QGIS 3.22.5 Version Białowieża and I am having troubles in clipping a WMS raster with level curves. When I use the function for clipping rasters by polygon (draw area on map) or by a layer mask, the following error message occurs:
ERROR 4: `contextualWMSLegend=0&crs=EPSG:32633&dpiMode=7&featureCount=10&format=image/png&layers=CB.IGM25000.32&layers=CB.IGM25000.33&styles&styles&url=http://wms.pcn.minambiente.it/ogc?map%3D/ms_ogc/WMS_v1.3/raster/IGM_25000.map' does not exist in the file system, and is not recognized as a supported dataset name.
The process resulted in error 1
Execution completed in 0.30 seconds
Results:
{'OUTPUT': 'C:/Users/Tommaso/AppData/Local/Temp/processing_aHllSD/fa7a86805d8a443f92ed9a8faa03f765/OUTPUT.tif'}

Load layer
The following layers were not created correctly•
 C:/Users/Tommaso/AppData/Local/Temp/processing_aHllSD/fa7a86805d8a443f92ed9a8faa03f765/OUTPUT.tif

Even by trying to save smaller areas, the clipping process does not work.
I also tried to save the layer as GeoTiff but it saves a file map which is shown without any level curves.
An alternative solution could be downloading different maps of the area related to the municipalities. However, there are about 30 municipalities in the area and it might take me too much effort.


text:
Q: implementing image swap animation using jquery I want to implement the animation over the thumbnails of the portfolio section as shown in the following template.
http://ironsummitmedia.github.io/startbootstrap-freelancer/#
I had planned to implement that by swapping the image src using Jquery on mouseenter() and mouseleave().
            $(".pictures .thumbnail").mouseenter ( function () {
                $(this).attr("src","glass.png");
            });

I am unable to find a way of storing the src of the original thumbnail the mouse is pointing at, so that i can use it on the mouseleave() function.
html code for the thumbnails, just in case.

                    <text>PORTFOLIO</text>

Any ideas on how to do that?
Thanks in advance!

A: add data attribute on your  elements.

$(".pictures .thumbnail").mouseenter ( function () {
      $(this).find('img').attr("src","glass.png");
});

$(".pictures .thumbnail").mouseleave ( function () {
      var $this = $(this);
      $this.find('img').attr("src", $this.find('img').attr("data-src");
});

A: This will work as expected:
$('.pictures .thumbnail img').on('mouseenter mouseleave', function(event){
    var originalimage = $(this).attr("src");
    $(this).attr("src", $(this).attr("data-src"));
    $(this).attr("data-src", originalimage);
});

Here's the fiddle: https://jsfiddle.net/gwkyupup/5/


text:
Q: CSS :hover wont work if there's an absolute div behind it?

footer {
  width: 960px;
  height: 100px;
  background-color: #121212;
  line-height: 100px;
  color: white;
  font-size: 10px;
  position: relative;
}

#copyright {
  margin-left: 3%;
  opacity: 0.4;
}

#icon {
  background-image: url('../img/icon.png');
  background-repeat: no-repeat;
  width: 85px;
  height: 86px;
  opacity: 0.050;
  position: absolute;
  right: 0;
  margin-top: 7px;
  margin-right: 5px;
  display: block;
}

#top {
  background-image: url('../img/backtop.png');
  background-repeat: no-repeat;
  width: 29px;
  height: 29px;
  margin-top: 4%;
  margin-right: 6%;
  float: right;
}

#top:hover {
  background-image: url('../img/tophover.png');
  background-repeat: no-repeat;
  width: 29px;
  height: 29px;
}

  GGLex is copyrighted &copy 2014, All rights reserved.

What it looks like:

(source: gyazo.com)
I am trying to add a faded out icon, on the right side on my footer. I did it, works just fine, but when I tried to add back to top button with hover, it failed.
Basically, when I hover, it won't work, but if I remove the div "icon", it will work easily (the hover).
Why does it happen & how can I make it work?

A: Unfortunately this happens sometimes when css styles overlaps. You can use javascript to solve this...
onmouseover="window.location='URL HERE'"
Example

Hope this helps and please comment back if this doesn't work or you need more help
the below works...

 GGLex is copyrighted &copy 2014, All rights reserved.

URL TO top of page. ID any element at top of page for example id="top" then replace URL with  www.YOUR_WEB_NAME.CO.UK/#top

A: You can try to add pointer-events: none; to the absolutely positioned element. That way clicks/"pointer events" can go "through it", affecting the element behind it.


text:
Q: Folium map KeyError ATA while saving when trying to save my map i get the following error
'KeyError                                  Traceback (most recent call last)
<ipython-input-31-65c9bba51b6f> in <module>()
  7 # Create Folium plot
  8 #map.save('plot_data.html')
----> 9 map.save(outfile= "test.html")
KeyError: 'ATA'

this is my code, here i am trying to bind the pandas data frame and the json geometries to create an overlay for visualisation of data
import folium
import pandas as pd
country_geo  = './world-development-indicators/world-countries.json'
data = pd.read_csv('world-development-indicators/Indicators.csv')
hist_indicator = 'CO2 emissions \(metric'
hist_year = 2011
mask1 = data['IndicatorName'].str.contains(hist_indicator)
mask2 = data['Year'].isin([hist_year])
stage = data[mask1 & mask2]
plot_data = stage[['CountryCode','Value']]
hist_indicator = stage.iloc[0]['IndicatorName']
map = folium.Map(location=[100, 0], zoom_start=1)
map.choropleth(geo_path=country_geo, data=plot_data,
         columns=['CountryCode', 'Value'],
         key_on='feature.id',
         fill_color='YlGnBu', fill_opacity=0.7, line_opacity=0.2,
         legend_name=hist_indicator)
map.save('plot_data.html')


text:
Q: json.net error (windows 10) i have a app in windows 8.1 universal app working fine.
in upgrade to windows 10, i have a error:

Assenbly 'Newtonsoft.json' invokes
  'Attribute.GetCustomAtributtes(Assembly)' which is not in the windows
  store profile.

and

Assenbly 'Newtonsoft.json' invokes
  'Attribute.GetCustomAtributtes(MemberInfo, bool)' which is not in the windows
  store profile.

and

Assenbly 'Newtonsoft.json' invokes
  'Attribute.GetCustomAtributtes(ParameterInfo, bool)' which is not in the windows
  store profile.

json.net is not compatible with windows 10?

A: Yes JSON.NET works with Windows 10, I had to use the Source Code from GitHub and add that code to a Windows 10 Class Library with a few warnings it compiles fine, and warnings are regards to some Method decorators, the Nuget package did produce some errors similar to this but got it to work fine.


text:
Q: FastApi Users Auth, can't add extra fields for register I'm using Fastapi, Fastapi Users and TortoiseOrm for auth on my project.
FastApi Users
Tortoise
I followed the example on FastApi Users website and when I try to add some extra fields at register users, get this error:

RuntimeError: no validator found for <class 'tortoise.fields.data.CharField'>, see arbitrary_types_allowed in Config

Here is my code, thanks for your help!
from tortoise import fields
from tortoise.contrib.pydantic import pydantic_model_creator
from fastapi_users import models
from fastapi_users.db import TortoiseBaseUserModel, TortoiseUserDatabase
from tortoise.contrib.starlette import register_tortoise

class User(models.BaseUser):
 nombre = fields.CharField(max_length=100)
 apellidos = fields.CharField(max_length=100)

class UserCreate(models.BaseUserCreate):
  pass

class UserUpdate(User, models.BaseUserUpdate):
  pass

class UserDB(User, models.BaseUserDB):
  pass

class UserModel(TortoiseBaseUserModel):
  pass

 user_db = TortoiseUserDatabase(UserDB, UserModel)

A: I faced a similar error while using FastAPI Users with SQlAlchemy. What worked for me was to add the custom fields (nombre and appelidos in your case) to each of  the 4 user models AND to the UserModel table while defining it
schemas.py file
from fastapi_users import models

class User(models.BaseUser):
    sid: int
    fname: str
    lname: str

class UserCreate(models.BaseUserCreate):
    sid: int
    fname: str
    lname: str

class UserUpdate(User, models.BaseUserUpdate):
    sid: int
    fname: str
    lname: str

class UserDB(User, models.BaseUserDB):
    sid: int
    fname: str
    lname: str

models.py file
from sqlalchemy import Column, Integer, String
from fastapi_users.db import SQLAlchemyBaseUserTable
from db import Base

class UserTable(Base, SQLAlchemyBaseUserTable):
    sid = Column(Integer)
    fname = Column(String)
    lname = Column(String)

A: This worked for me, it requires the tortoise ORM format for the field:
class UserModel(TortoiseBaseUserModel):
    name = fields.CharField()


text:
Q: Double Linked list and using a reverse search Ok Ive never used lists at all but Ill do my best to explain what im trying to do.

struct node {
 node(int value=0) { data=value; next=prev=this; }
 int data;
 node *next;
 node *prev;
};

class list {
 public:
 list(int N=0, int value=0);
 ˜list();
 bool empty() const { return N == 0; }
 bool full() const { return false; }
 int size() const { return N; }
 void resize(int);
 void clear();
 void insert(int, const int &);
 void remove(int);
 void push_back(const int &din) { insert(N, din); }
 void pop_back() { remove(N-1); }
 const int & back();
 int & operator[](int);
 private:
 int N;
 node *head;
 node *findnode(int);
}

_________________________________________
inline
node *list::findnode(int i) {
 if (i == -1)
 return head;
 node *p = head->next;
 while (i--)
 p = p->next;
 return p;
}

I am supposed to rewrite the findnode() function to do a forward search when i<(N/2) and do a reverse search when i>(N/2). Ive tried but I keep getting segmentation errors. I think I just dont exactly get whats going on. All the other functions listed in the list class are correctly written.
Ive corrected my Node struct. Sorry ahead of time im very lost when it comes to these object pointers and whats really going on. Here's what I tried.
 97 inline
 98 node *list::findnode(int i) {
 99         if (i == -1)
100                 return head;
101
102         if (i < N/2){
103                 node *p = head->next;
104                 while (i--)
105                         p = p->next;
106
107                 return p;
108         }
109
110
111         if (i > N/2){
112                 node *p = head->prev;
113
114                 i =( i - N/2 );
115                 while (i--)
116                         p = p->prev;
117
118                 return p;
119         }
120 }

A: I won't give the full answer. But essentially use an if-else to split between your two cases. In the first case search forwards like above. In the second case search in reverse. But in order to do this you should augment your node class to have a prev member, to make it actually a doubly linked list. Have the list store the tail of the list. You'll have to modify most of your list functions to accomplish this.
inline
node *list::findnode(int i) {
 if(i < size()/2) {
   //search from beginning of list
 }
 else {
   //search from end of list by starting at tail
   node *p = tail;
   i = i-size/2;
   while(i--) {
     p = p->prev;
   }
   return p;
 }


text:
Q: How to turn my custom controller into root controller programmatically in SWIFT? (Could not load NIB) I dynamically created a XCode project in iOS 14 without StoryBoard. HomeViewController is my custom class. I get this error:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle with name 'HomeViewController''
Here is my Scene Delegate Class:
class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
        guard let windowScene = (scene as? UIWindowScene) else { return }

        window = UIWindow(frame: windowScene.coordinateSpace.bounds)
        window?.windowScene = windowScene
        window?.rootViewController = HomeViewController(nibName: "HomeViewController", bundle: nil)
        window?.makeKeyAndVisible()
    }

A: Instead of initializing your View Controller like this:
window?.rootViewController = HomeViewController(nibName: "HomeViewController", bundle: nil)

Initialize it like that:
window?.rootViewController = HomeViewController()

This is because when you specify nibName iOS thinks you are trying to initialize from Storyboard or somewhere else.
finished code:
class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
        guard let windowScene = (scene as? UIWindowScene) else { return }

        window = UIWindow(frame: windowScene.coordinateSpace.bounds)
        window?.windowScene = windowScene
        window?.rootViewController = HomeViewController()
        window?.makeKeyAndVisible()
    }


text:
Q: How to change File Permissions in Liferay 6.2 sync (Liferay Sync Connector plugin) I am using Liferay Sync Connector plugin in liferay 6.2
For accessing document and media folder data on my computer I am using Liferay Sync.
Liferay Sync Connector plugin provide permission like,

*

*View Only

*View and Add Discussion

*View, Update, and Add Discussion

*Full Access (Add Discussion, Delete, Update, View)

By default, this permission applies to the Site Member role.
How can I apply the above permission on custom created role or other then Site Member role ??


text:
Q: find xpath for a repeated angularJs Item how is possible to find the xpath for an angularJs element? for instance i discovered that all links in my page have the same xpath due to the repeated items in angularJs -->
.//*[@id='div_1_1_1_2']/div/div[1]/div[2]/div[2]/div/div[2]/div[1]/div/div[2]/a

but i  have 10 of  element , they are differente for text, so i tried with `"
so i tried with contains but it never find it
.//[@id='div_1_1_1_2']/div/div[1]/div[2]/div[2]/div/div[2]/div[1]/div/div[2]/a[contains(@aria-label='Creazione Prodotto')]"`

i use selenium, junit4 , firefox webDriver
this is my code
public class PB01_TTT {
  private WebDriver driver;
  private String baseUrl;
  private boolean acceptNextAlert = true;
  private StringBuffer verificationErrors = new StringBuffer();
  WebElement element;

    @Before()
      public void setUp() throws Exception {

    FirefoxProfile fxProfile = new FirefoxProfile();
    fxProfile.setPreference("browser.download.folderList", 2);
    fxProfile.setPreference("browser.download.manager.showWhenStarting", false);

    fxProfile.setPreference("browser.helperApps.alwaysAsk.force", false);
    fxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk",
            "application/pdf, application/x-pdf, application/octet-stream");
    fxProfile.setPreference("pdfjs.disabled", true);
    driver = new FirefoxDriver(fxProfile);
    baseUrl = "https://w8aon2bpm.replynet.prv:9443";
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
  }

     @Test
      public void testPBO1TTT() throws Exception {

            driver.get(baseUrl + "/ProcessPortal/login.jsp");
          //    driver.get(baseUrl + "/ProcessPortal/dashboards/SYSRP/RESPONSIVE_WORK");

            driver.findElement(By.id("username")).clear();
            driver.findElement(By.id("username")).sendKeys("user");
            driver.findElement(By.id("password")).clear();
            driver.findElement(By.id("password")).sendKeys("password");

            String columnToDisplay=driver.findElements(By.xpath(".//*[@id='div_1_1_1_2']/div/div[1]/div[2]/div[2]/div/div[2]/div[1]/div/div[2]/a[contains(@aria-label='Creazione Prodotto')]"));

        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

                   element = (WebElement) driver.findElements(By.xpath(columnToDisplayXpath));

                   Assert.assertNotNull(element);

it always return me a notFoundElement, any suggestions ?
Thank you

A: If you have 10 links, then there is a high chance they are different in a way even if the path is the same, in this case you need to construct an path based on the thing that is different.
For example: use href, text or other any part that differs
//a[contains(@href, 'part_of_href')]
//a[contains(text(), 'part_of_text')]
//a[@title='title']
//a[contains(@aria-label='Creazione Prodotto')]

If you need any help in getting the selector please add the html section of the links, you can change the url if needed.

Tip: avoid using absolute xpaths and attributes that do not suggest anything and they can change like: .//*[@id='div_1_1_1_2']/div/div[1]/div[2]/div[2]/div/div[2]/div[1]/div/div[2]/a[contains(@aria-label='Creazione Prodotto')]"
  This will give you a lot of work in the future.


text:
Q: self updating renewal term date I am looking to create a fromula that takes a contracts intial end date, and compares it to todays date. If the contracts intial end date is less then todays date then the contract should automatically update the new end date to 1 or 2 years (depending on the contracts auto renewal) past the previous end date.
The formual I created is:
=IF($D$9>(IF($D$9>F11,(DATE(2015,7,24)+365*(1)),(F11))),((DATE(2015,7,24)+365*(2))),((DATE(2015,7,24)+365*(1))))

$D$9= todays date.
The problem with this formula is I have to manualy enter each DATE( year, month, day) formula per client, and if the clients contract has been renewed more then once the formula doesnt update.

A: "have to manualy enter each DATE( year, month, day) " <-- you can always put year, month, day as a saperate cell, then link it to the formula.
"if the clients contract has been renewed more then once the formula doesnt update" <--- 2 things :

*

*with only using non-vba formula, it will update only once.

*you can always use extra rows/column to indicate/do the extension.. add built a formula around it. Eg. if( <renewBox1> = 1 , <renewOnce>, <noRenew>) then if( <renewBox2> = 1 , <renewOnce_based on previousExtendedDate>, <noRenew>)
Hope that helps.


text:
Q: UDP broadcast send from PHP and receive in C# I'm trying to send a broadcast UDP message to a C# application. I have tried the following code to send the message. Which I found on the php.net website as a comment to the socket_sendto manual page.
<?php
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, 1);
socket_sendto($sock, $broadcast_string, strlen($broadcast_string), 0, '255.255.255.255', $port);
?>

This doesn't work for me, maybe it's my network.
But it does work if I replace the broadcast IP '255.255.255.255' to my specific IP e.g. '192.168.1.128'. I can see this message coming in with Wireshark, while I can't see this using the above code. This leads me to believe there is something wrong with the PHP side of the code. I really want to use broadcasting or some kind of multicasting for my program, so I'm a bit stuck at the moment ;)
I use the following on the (C#) receiving end (for testing):
UdpClient subscriber = new UdpClient(15000);

IPEndPoint ep = new IPEndPoint(IPAddress.Any, 15000); ;

byte[] pdata = subscriber.Receive(ref ep);
string data = Encoding.ASCII.GetString(pdata);
MessageBox.Show(data);
subscriber.Close();

Any idea what could be the cause of this?

A: 255.255.255.255 is a "limited" broadcast whereas your 192.168.1.255 is a "directed" broadcast.
Limited in simple terms means that it is only send within the LAN. LAN as defined by directly connected hosts, i.e. with no router in between. Routers--with a few exceptions--do not pass a limited broadcast but a directed broadcast.
Now, with your initial problem and question, I can only guess that you are sending your broadcast across a router.

A: Try specifying the MSG_DONTROUTE flag in your script. Taking inspiration from this CodeGuru post, if this isn't specified the routers make the decision on whether or not to broadcast your message.
socket_sendto($sock, $broadcast_string, strlen($broadcast_string), MSG_DONTROUTE, '255.255.255.255', $port);


text:
Q: JavaScript Assignment Operator in 'while' loop I have a script:
<script>
var text = "";
var i = 0;
while (i < 10) {
text += i;
i++;
}
document.getElementById("demo").innerHTML = text;
</script>

This script will write the numbers 0 ....9
Why I have to use the "text += i" assignment?
why can't I code "text = i" instead?
How would you explain this code line?
Thanks for your time!
ps. I know text += i is equivalent to
text = text + i

this is not a question here. ;)
and I also know if I type "text = i" I will get just the last number: 9.

A: The plain assignment operator = sets the variable (or object property) on the left side to the value on the right. The former value of the left side variable is lost.
The += operator performs an addition between the current left side value and the right side value, and then assigns that result to the left side. If you want to accumulate a series of addition operations into a variable, then, you would use +=.
If you just use =, then, the variable text will retain only the last value assigned.
That's the way the assignment operator works in a vast number of languages like JavaScript.

A: First of all its good that you know how operators works ...so let me clarify why the script is using
text+=i
Lets walk through the loop
Initially text=''
For first time it comes in
Text='0'
So now if you were appending the text to div, then you could have set it to blank string again or used text=i
But you are not adding the text to div.
So if we use text =i  the text becomes 0
And in next becomes 1 and so on at the end its value will be 9
But we wanted 0...9 so we have to keep appending the string value of numbers
To get 0...9


text:
Q: VSTest console doesn't work from another base directory I have a Windows 2012 Server with TFS2015 and VS2015. Somehow my tfs build doesn't generate unit-test results. I pin pointed the problem. I logged on the server and execute the following command in a "MSBuild Command Prompt for VS2015" (exactly the same as TFS does):
C:\Program Files (x86)\Microsoft Visual Studio 14.0>"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe" "C:\_tfsWork\05894744\SoftwareDevelopment\ConsoleTest1\ConsoleTest1.UnitTest\bin\Debug\ConsoleTest1.UnitTest.dll"

I got no errors, but there is also no result. If i use the /ListTest parameter it does find the test.
When I change my path in the prompt to the folder that contains the test assembly and execute the command again, it works. Can anybody explain what I'm doing wrong here? (or what TFS is doing wrong)

A: It's solved. The problem was the file filter for the test dll's. It included the
Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll

When I removed this file by excluding all Microsoft.*.dll, the test worked in TFS.

A: For me the path to vstest.console.exe was:
C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\CommonExtensions\Microsoft\TestWindow\


text:
Q: Compactness of $K(S)$, if $K$ is an infinite-dimensional compact operator in Hilbert space
$H$ is infinite-dimensional Hilbert space. $K: H \rightarrow H$ is infinite-dimensional compact operator. Let $S$ be a unit sphere in H. The task is to proof that $K(S)$ couldn't be compact.

I know that:
Really we need to proof that $K[S]$ is not closed. If B is unit ball, $[B]$ - closure, then $K([B])$ is also closed(for compact operator in Hilbert space).
If $\mathrm{Ker} B$ is empty, i.e. $0 \notin K(S)$ then there is a sequence in $K(S)$ converging to $0$, so $K(S)$ isn't compact. But I don't understant how to proof noncompactness of $K(S)$ even if one of the basis vectors is mapped to $0$.
On the other side we can try to proof that if $K(S)$ is compact, then $\mathrm{Im}(K)=K(H)$ shuold have finite dimension. It is easy if $K(B)$ contains some ball(like a subspace in $K(H)$), but it's far from being true.

A: In fact, $K(S)$ can be compact. Let $H = \ell^2(\mathbb{N})$, i.e.
$$H = \Biggl\{ f \colon \mathbb{N} \to \mathbb{C} \biggm\vert \sum_{k = 0}^{\infty} \lvert f(k)\rvert^2 < +\infty\Biggr\}$$
(using function notation to make indexing of sequences in $H$ clearer) and $K = C \circ D$, where
$$(Df)(k) = f(k+1)$$
and
$$(Cf)(k) = 2^{-k}f(k)\,.$$
Then $K(S)$ is closed, hence compact.
Let $g \in \overline{K(S)}$, and $(f_n)_{n \in \mathbb{N}}$ a sequence in $S$ with $K(f_n) \to g$. If $g = 0$, then we have $K(e_0) = g$ where $e_m(k) = \delta_{m,k}$, hence we can assume $g \neq 0$. For every fixed $k$ we have
$$f_n(k+1) \to 2^kg(k)$$
and therefore
$$\sum_{k = 0}^{m} 2^{2k}\lvert g(k)\rvert^2 = \lim_{n \to \infty} \sum_{k = 0}^{m} \lvert f_n(k+1)\rvert^2 \leqslant 1$$
for all $m$. It follows that $h \in H$, where
$$h(k) = 2^kg(k)\,.$$
Furthermore, we have $\lVert h\rVert \leqslant 1$, hence there is $h_1 \in S$  with $h = Dh_1$. By construction, $Ch = g$, thus
$$g = Kh_1 \in K(S)\,.$$

A: Actually, if $K \colon X\to Y$ is a compact operator and $X$ is reflexive, then   $K(S)$ is    compact.  Notice that since $K$ is compact, it must be completely continuous, i.e., if $x_n \to x$ weakly in $X$, then $||K(x_n)-K(x)||\to 0$.
(This is a corollary of  Banach-Steinhaus's Theorem.)
To see that  $K(S) $ is compact,  let $ (K(x_n))_n $ be a sequence in $K(S)$. Since $X$ is reflexive, $S$ is weakly compact and thus (by Eberlein-Smulian's Theorem), we can find a weakly convergent subsequence,  $x_{n_k} \to x \in X$ weakly. By the complete continuity of $K$, it follows that $K x_{n_k} \to Kx \in K(S)  $ (so, it has a (norm) convergent subsequence).


text:
Q: Mxmlc generates different binary on same source I'm compiling a single .as file into swf using mxmlc.
Whenever I run mxmlc, results are different in size even when the source code is not changed.
For example,
// Test.as
package
{
    public class Test
    {
    }
}

And generates .swf using mxmlc :
mxmlc Test.as

and result size differs from 461 to 465 bytes.
I suppose that it's because of timestamp-like things in compiler, but I could not find how to fix or disable that. Any ideas on generating "same binary from same source" ? Thanks!

A: Finally, I found that metadata tag (Tag Type = 77) and undocumented 'product info' tag (Tag Type = 41) both contains compliation time.
I succeeded to remove timestamps by following steps :
1. open swf and un-zlib
2. clear timestamps in metadata tag and product info tag
3. re-zlib and make new .SWF

But I'm not happy with that, thus this needs extra work on SWF file. I want to find the easier way. there may be 'bypass product info' option on mxmlc..
You can find more information on SWF File structure and metadata tag on http://www.adobe.com/devnet/swf.html and product info on http://wahlers.com.br/claus/blog/undocumented-swf-tags-written-by-mxmlc/

A: You need to override the metadata the compiler is writing into the resulting swf file. You can do this with the -raw-metadata compiler aguement.
Usage:
mxmlc -raw-metadata <XML_String> Test.as

Example:
mxmlc -raw-metadata '' Test.as

(Resulting swf is always 190 bytes).

A: 1 : date in metadata:
mxmlc:
 <metadata date=" " />
 <raw-metadata></raw-metadata>

2 : timestamp in ProductInfo
download sdk source code,and modify the  ProductInfo.java,let the timestamp keep same.and then update the ProductInfo.class  in  your_sdk_dir\lib\swfutils.jar
However,when i have done,Mxmlc also generates different binary on same source.
I think i can't change the  compiler link order.


text:
Q: HTML & Javascript - how to detect and put an alert on when fullscreen Video is on How to put an alert when video full screen is on? i want an output like this thanks.

when the full screen mode is on i want an alert and the popup must alert like 2 seconds and then it will popup. is there a way how can i do that?
here is my code for HTML
<!DOCTYPE html>

<video width="320" height="240" controls src="flashtrailer.mp4">
  Your browser does not support the video tag.
</video>

Note: The .ogg fileformat is not supported in IE and Safari.

Note: The video tag is not supported in Internet Explorer 8 and earlier versions.

Script

A: Here is how to listen to full screen enabled video on Chrome 63:
  function fullScreenListener() {
    if (document.webkitFullscreenElement === this) {
      console.log("Full screen enabled");
    }
  }
  const video = document.querySelector("video");
  video.addEventListener("webkitfullscreenchange", fullScreenListener);

A more cross-platform solution would be:
  function fullScreenListener() {
    if (document.webkitFullscreenElement === this ||
        document.mozFullScreenElement === this ||
        document.fullScreenElement === this) {
      console.log("Full screen enabled");
    }
  }
  const video = document.querySelector("video");
  if (typeof video.onwebkitfullscreenchange !== "undefined") {
    video.addEventListener("webkitfullscreenchange", fullScreenListener);
  } else if (typeof video.onmozfullscreenchange !== "undefined") {
    video.addEventListener("mozfullscreenchange", fullScreenListener);
  } else if (typeof video.fullscreenchange !== "undefined") {
    video.addEventListener("fullscreenchange", fullScreenListener);
  }

More info about Fullscreen API: https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API
PS: Calling window.alert() in full-screen mode causes the video tag to get out of the full-screen mode.

A: It is not possible with just alert. There are different api for fullscreen video mode.
for Mozilla -  https://wiki.mozilla.org/index.php?title=Gecko:FullScreenAPI or https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API
Here you will find good summary https://www.thecssninja.com/javascript/fullscreen
How to DO
You just need to add one div with z-index in video or canvas tag


text:
Q: How to create a new variable with values depending on another variable containing specific words? I have this dataset with information on a bunch of articles:
ID number, Header, Rubric, Article Text, Date.

I would like to sort the articles based on content, i.e. I would like to create a new variable using an "if" statement:

*

*"if" the variable 'Article Text' contains the string 'Second World War'  "then" 'New Variable'= 1 and

*"if" the variable 'Article Text' contains the word 'Syria' "then" 'New Variable'= 2.

*Hereafter I want to create new datasets depending on the value of 'New Variable'.

I would like to be able to try out different methods to see what works the better/gives me the more correct sorting of the aricles - like conditioning on

*

*one word

*several words around same topic (all in text)

*several words around same topic (one or more in text)

*a word string

So what I am asking for is help to understand the basic setup I need to create, to be able to use different very simple text analysis tools to sort my dataset.
Thanks in advance

A: A minimal Example would be this:
# An example data.frame containing some combinations of letters:
data <- data.frame(a=paste0(LETTERS[1:3],LETTERS[3:5]))

# Replace this with the strings you want to search for:
strings <- c("A", "C")
# And this with the names for the new columns:
names(strings) <- c("colA", "colB")

# Search for the strings and create new columns, replace $a according to your column-names:
data <- cbind(data, data.frame(lapply(strings, grepl, data$a)))

What this does:
grepl searches for the pattern defined in the first argument in the character-vector in the second argument and returns TRUE or FALSE if the pattern matched or not.
lapply applies the function in the second argument to all the elements of the list in the first element and uses all further agruments as additional agruments to the function in the second arguemnt. Lapply returns a list.
as.data.frame makes a data.frame out of the list.
cbind finally does a column-bind of the new dataframe to the old one.
As alsways, run the Code line by line and output intermediate values and look at the help-entries of the used functions.


text:
Q: Live streaming video in Qt I am making a "simple" software that can streaming video (without audio) from pc to pc. I am a newbie in Qt so I have some questions:

*

*Does Qt 5.1 have any class to Encode and Decode video?

*If not, can I use other libraries (such as gstreamer) to Codec the video? And how can I import them into a Qt based project.

I need all of your advice. Thank you very much.

A: Decoding is no problem. You can use the QMediaPlayer class. Under Linux it actually uses the gstreamer libs. Encoding is not implemented. This is a bit beyond the scope of Qt5. And don't let the classes QMediaRecorder or QVideoEncoderSettings confuse you. They are mainly helper classes for QCamera or QRadioTuner, which provide an already encoded stream from their devices. If you need to encode single images into video frames and put them into a container, you need a 3rd party lib like ffmpeg.
Streaming a video from on pc to another is easily implemented with Qt5. Encoding or transcoding cannot be done with Qt5 alone.


text:
Q: изменение положение блока Хотелось бы что бы сайдбар прилипал к верху как только прячется "верх" сайдабара , а сейчас получается когда мы доходим до низа сайдбара
код:
var change = document.getElementById('sidebar');

var SourceBottom = change.getBoundingClientRect().bottom + window.pageYOffset;

window.onscroll = function() {
    if (change.classList.contains('fixed') && window.pageYOffset < SourceBottom) {
        change.classList.remove('fixed');
    } else if (window.pageYOffset > SourceBottom) {
        change.classList.add('fixed');
    }
};

https://jsfiddle.net/dirkdirk/ugcpv9pg/27/

A: Вот таким образом решилось
var change = document.getElementById('sidebar');
var top = document.getElementById('top');
var SourceBottom = top.getBoundingClientRect().bottom + window.pageYOffset;
window.onscroll = function() {
    if (change.classList.contains('fixed') && window.pageYOffset < SourceBottom) {
        change.classList.remove('fixed');
    } else if (window.pageYOffset > SourceBottom) {
        change.classList.add('fixed');
    }
};

A:

var change = document.getElementById('sidebar');

var SourceTop = change.getBoundingClientRect().top + window.pageYOffset;

window.onscroll = function() {
    if (change.classList.contains('fixed') && window.pageYOffset < SourceTop) {
        change.classList.remove('fixed');
    } else if (window.pageYOffset > SourceTop) {
        change.classList.add('fixed');
    }
};
.top{
  width:100%;
  height:50px;
  background:black;
}

#sidebar{
  width:50px;
  background:blue;
  height:100px;
  display:inline-block;
  margin-left: 0;
}
.content{
  float:right;
  height:4000px;
  width:80%;
  background:red;
}
.fixed {
      position: fixed;
      top: 0;
      margin-left: 0;
    }


text:
Q: keep header button inline with table I'm a little stuck on this / new with html and css.
I am trying to keep my button inline with the edge of the table.
When I resize my window, so it becomes smaller, the table stops resizing but my button keeps moving in / sticking to window edge.
How can I stop this from happening?
Below is my code snippet.

* {
  font-family: sans-serif; /* Change your font family */
}

.header {
  height: 60px;
  /* background: #e6e6e6; */
  /* border-radius: 5px; */
  /* padding: 5px; */
}

.header .title {
  display: inline-block;

  font-size: 26px;
  margin: 14px 0px;
}

.header .addNewButton {
  float: right;
  margin: 10px 0px;

  height: 40px;
  width: 100px;

  border: 0;
  background: #009879;
  box-shadow: none;
  border-radius: 5px;
  color: #fff;
}

.content-table {
  border-collapse: collapse;
  margin: 8px 0;
  font-size: 0.9em;
  min-width: 100%;
  border-radius: 5px 5px 0 0;
  overflow: hidden;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);
}

.content-table thead tr {
  background-color: #009879;
  color: #ffffff;
  text-align: left;
  font-weight: bold;
}

.content-table thead tr th:last-of-type {
  width: 20px;
}

.content-table th,
.content-table td {
  padding: 12px 15px;
}

.content-table tbody tr {
  border-bottom: 1px solid #dddddd;
}

.content-table tbody tr:nth-of-type(even) {
  background-color: #f3f3f3;
}

.content-table tbody tr:last-of-type {
  border-bottom: 2px solid #009879;
}

.content-table tbody tr.active-row {
  font-weight: bold;
  color: #009879;
}

#actions {
  /* width: 500px; */
  border: 1px solid black;
  display: flex;
  /* flex-direction: row; */
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="./css/style.css">

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone|Material+Icons+Round|Material+Icons+Sharp">

Parameters

      <button type="button" class="addNewButton">
        + Add New
      </button>

          Name
          Points
          Team
          Action

          1
          Domenic
          88,110
          dcode
          close

          2
          Sally
          72,400
          Students

delete

          3
          Nick
          52,300
          dcode
          delete

A: I have figured out a way for your add new button to stay fixed when you are resizing the page,hope that was what you were looking for.
first thing you should do is jumping into css and remove the float property form your ".header .addNewButton" selector.
after that you should go to ".header" selector and add display property to it and set it to flex.
finally, in your .header you should add another property named "justify-content" and set to space-around.


text:
Q: How to access UserManager instance from WebApplication instance app in program.cs in asp.net core 7.0 I need to access UserManager instance to seed IdentityUser data, I am doing in program.cs file
Below is given code snippet
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services
    .AddDefaultIdentity<MyIdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<AppDbContext>();

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
});

builder.Services.AddRazorPages();
builder.Services.AddControllersWithViews();

builder.Services.AddScoped(typeof(IRepository<>), typeof(Repository<>));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseMigrationsEndPoint();
}
else
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.MapControllers();

app.MapControllerRoute(
        name: "default",
        pattern: "{controller = Home}/{action = Index}/{Id?}"
    );
app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapDefaultControllerRoute();
app.MapRazorPages();

var scopeFactory = app.Services.GetRequiredService<IServiceScopeFactory>();
var scope = scopeFactory.CreateScope();
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<MyIdentityUser>>();

SeedInitialData.SeedData(roleManager, userManager);

app.Run();

and I receive this exception

InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' has been registered.
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)

Please help me, how to find this issue. regards
I read many articles, and I tried some of them, none of them worked for me.

A: I create a simple demo to show how to seed data to identity in asp.net core, You can refer to it.
public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        //.........

        builder.Services.AddIdentity<IdentityUser,IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores<ApplicationDbContext>();

        var app = builder.Build();

        // Configure the HTTP request pipeline.
        //........
        app.UseAuthorization();

        using (var scope = app.Services.CreateScope())
        {
            //Resolve ASP .NET Core Identity with DI help
            var userManager = (UserManager<IdentityUser>)scope.ServiceProvider.GetService(typeof(UserManager<IdentityUser>));
            var roleManager = (RoleManager<IdentityRole>)scope.ServiceProvider.GetService(typeof(RoleManager<IdentityRole>));
            // do you things here

            MyIdentityDataInitializer.SeedData(userManager, roleManager);
        }

       //........

        app.Run();
    }
}

MyIdentityDataInitializer class
public static  class MyIdentityDataInitializer
    {
        public static void SeedData(UserManager<IdentityUser> userManager,RoleManager<IdentityRole> roleManager)
        {
            SeedRoles(roleManager);
            SeedUsers(userManager);
        }

        public static void SeedUsers(UserManager<IdentityUser> userManager)
        {
            if (userManager.FindByNameAsync("user1").Result == null)
            {
                IdentityUser user = new IdentityUser();
                user.UserName = "user1";
                user.Email = "user1@localhost";
                IdentityResult result = userManager.CreateAsync(user, "Password123!!!").Result;

                if (result.Succeeded)
                {
                    userManager.AddToRoleAsync(user,
                                        "NormalUser").Wait();
                }
            }

            if (userManager.FindByNameAsync("user2").Result == null)
            {
                IdentityUser user = new IdentityUser();
                user.UserName = "user2";
                user.Email = "user2@localhost";
                IdentityResult result = userManager.CreateAsync(user, "Password123!!!").Result;

                if (result.Succeeded)
                {
                    userManager.AddToRoleAsync(user,
                                        "Administrator").Wait();
                }
            }
        }

        public static void SeedRoles(RoleManager<IdentityRole> roleManager)
        {
            if (!roleManager.RoleExistsAsync("NormalUser").Result)
            {
                IdentityRole role = new IdentityRole();
                role.Name = "NormalUser";

                IdentityResult roleResult = roleManager.CreateAsync(role).Result;
            }

            if (!roleManager.RoleExistsAsync("Administrator").Result)
            {
                IdentityRole role = new IdentityRole();
                role.Name = "Administrator";

                IdentityResult roleResult = roleManager.CreateAsync(role).Result;
            }
        }
    }

Now when I run my project, The data will be seeded successfully.


text:
Q: How does data get stored in online exams or tests in real time when the connection's OFFLINE? I'd like to know how or where data gets stored in an online TIMED exam or test when the network connection becomes offline! I've seen scenarios where the network connection suddenly drops down and when the user logs into his account again, finds that the he can resume his test from the point the connection went offline! So, where does the data of his answers to his previous questions actually get stored? Is it in the client or server side? Do the test providers use any offline storage for these?
I was just curious about this (and kinda new to this) and couldn't find any accurate explanations for this in any search engine. A li'l guidance would be much helpful! [This could really be some kinda basic question I'm sorry for my ignorance- but I really don't know]

A: Without knowing the particular exam/system in question, the answer will be a bit generalized. Here goes:
The client side (code running in the browser most likely) must be saving the answers directly to the server as they come in.
The client side can also be linked to the server where the test results are stored. This can be done via a live link such as websockets. Once the server detects that the client is 'down' (for whatever reason) the server may or may not stop the timing of the test. It all depends on the specifics of the particular test. Care to share which?


text:
Q: Scraping Javascript Generated Content in R I find web scraping tasks in R can often be achieved with easy to use rvest package by fetching the html code that generates a webpage. This "usual" approach (as I may call it), however, seems to miss some functionality when the website uses Javascript to display the relevant data. As a working example, I would like to scrape news headlines from this website. The two main obstacles for the usual approach include the "load more" button at the bottom and the extraction of the headlines using xpath. In particular:
library(rvest)
library(magrittr)

url = "http://www.nestle.com/media/news-archive#agregator-search-results"
webs = read_html(url)

# Headline of the first news based on its xpath
webs %>% html_nodes(xpath="//*[@id='agregator-search-results']/span[2]/ul/li[1]/a/span[2]/span[1]") %>% html_text
#[1] ""

# Same for the description of the first news
webs %>% html_nodes(xpath="//*[@id='agregator-search-results']/span[2]/ul/li[1]/a/span[2]/span[2]") %>% html_text
#[1] ""

Maybe someone can shed light on (one of) the following questions:

*

*Do I miss something obvious here? That is, is it possible to scrape the headlines using the usual approach based on rvest in this case? As to my current understanding, however, that is not the case.

*Is RSelenium and phantom JS the only way to go here? To put it different, can the task be achieved without the use of RSelenium and phantomJS, in particular? This could include either the extraction of the headlines or loading more headlines (or both).

Any input is appreciated.

A: Imo, it's sometimes better to look for the raw data in the background:
library(jsonlite)
library(RCurl)
n <- 8 # number of news items to pull
useragent <- "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0"
url <- sprintf("http://www.nestle.com/_handlers/advancedsearch.ashx?q=Nestle%%2Bdaterange%%3A..2016-01-05&index=0&num=%d&client=Nestle_Corp&site=Nestle_Corp_Media&requiredfields=MediaType:/media/pressreleases/allpressreleases|MediaType:/Media/NewsAndFeatures|MediaType:/Media/News&sort=date:D:R:d1&filter=p&access=p&entsp=a&oe=UTF-8&ie=UTF-8&ud=1&ProxyReload=1&exclude_apps=1&entqr=3&getfields=*", n)
json <- getURL(url, useragent=useragent)
res <- fromJSON(json)
df <- res$GSP$RES$R
head(cbind(df[, c("U", "T")], df$FS$'@VALUE'))
#                                                                                U                                                                                T df$FS$"@VALUE"
# 1                                   http://www.nestle.com/media/newsandfeatures/nestle-150-years 'Good Food, Good Life': Celebrating 150 years of Nestlé ...     2016-01-01
# 2                                   http://www.nestle.com/media/newsandfeatures/2015-in-pictures                                           2015 in pictures | Nestlé Global     2015-12-23
# 3                         http://www.nestle.com/media/news/nescafe-dolce-gusto-expands-in-brazil                Coffee superstar: Nescafé Dolce Gusto expands in Brazil ...     2015-12-17
# 4                        http://www.nestle.com/media/news/nestle-waters-new-bottling-plant-italy  Nestlé Waters needs youth, for its new bottling plant in Italy ...     2015-12-10
# 5 http://www.nestle.com/media/news/nestle-launch-wellness-club-personalised-health-service-japan     Matcha made in nutritional heaven: Nestlé launches Wellness ...     2015-12-08
# 6        http://www.nestle.com/media/news/nestle-completes-chf-8-billion-share-buyback-programme          Nestlé completes CHF 8 billion share buyback programme ...     2015-12-07

df contains more information, some of which prly has to be unnested if you want to use it.


text:
Q: Can't send mail through ssl with my virtual domains from an external webmail I having issues with postfix to send mail through SSL from an external webmail.
I have several domain setup on my server configured in postfix with mysql. When I send mail with my main domain domain1.com everything works fine but if send mail from domain2.com I get this into my log:
Note that if I disable SSL on the webmail it works.
connect from unknown[78.209.78.XXX]
timeout after UNKNOWN from unknown[78.209.78.XXX]
disconnect from unknown[78.209.78.XXX]

Here is my main.cf:
smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
biff = no
disable_vrfy_command = yes
smtpd_helo_required = yes
append_dot_mydomain = no

mydomain= domain1.com
myhostname = domain1.com
myorigin = $mydomain
mydestination = XXX.kimsufi.com, localhost.kimsufi.com, localhost
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128

alias_maps = hash:/etc/aliases
queue_directory = /var/spool/postfix
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all

virtual_mailbox_domains = mysql:/etc/postfix/mysql/mailbox-domains.cf
virtual_mailbox_base = /home/vmail
virtual_mailbox_maps = mysql:/etc/postfix/mysql/mailbox-maps.cf
virtual_alias_maps = mysql:/etc/postfix/mysql/alias-maps.cf
virtual_uid_maps = static:5000
virtual_gid_maps = static:5000

smtpd_use_tls = yes
smtpd_tls_key_file = /etc/postfix/ssl/smtpd.key
smtpd_tls_cert_file = /etc/postfix/ssl/smtpd.crt
smtpd_tls_CAfile = /etc/postfix/ssl/cacert.pem
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
tls_random_source = dev:/dev/urandom

mail local si actif
smtpd_recipient_restrictions = permit_sasl_authenticated,
 permit_mynetworks,
 reject_unauth_destination,
 check_policy_service unix:private/policy, # SPF
 permit
 #check_relay_domains

smtpd_sasl_auth_enable  = yes
smtpd_sasl_type         = dovecot
smtpd_sasl_path         = private/authnoactive, mutual_auth
broken_sasl_auth_clients = yes

# DKIM
milter_default_action = accept
milter_protocol = 6
smtpd_milters = inet:127.0.0.1:8891
non_smtpd_milters = inet:127.0.0.1:8891

Note that on the webmail, I've set the smtp server to mail.domain1.com since I've read that I have to use the domain defined as Common Name in the tls certificate .
What I want is to make it work with SSL. Any idea about why it's not working ?
Edit

Here is new informations:
It seem that the problem is not related to domain1 or domain2 but occur only with new configurations. I had a domain that was setup since more than a year and everything was working fine. I removed it from my webmail and reconfigured it and now, I can't send mail.
While I was configuring it, I saw that it was asking me to use my https certificat and not the postfix one. So maybe the problem come from there but I don't know how to solve it.
Here is my apache conf:
<VirtualHost _default_:80>
  include /etc/apache2/domain.conf

</VirtualHost>

<VirtualHost _default_:443>
  include /etc/apache2/domain.conf

  SSLEngine on
  SSLCertificateFile /etc/apache2/ssl/cert-domain.com.crt
  SSLCertificateKeyFile /etc/apache2/ssl/domain.com.key
  SSLCACertificateFile /etc/apache2/ssl/GandiStandardSSLCA.pem
  SSLVerifyClient None
</VirtualHost>

Also if I do openssl s_client -connect localhost:465 I get that:
CONNECTED(00000003)
11508:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:s23_clnt.c:607:

I don't know if it's normal for a self signed certificat.

A: Postfix is not listening in smtpd_tls_wrappermode on port 465, but rather as a standard smtp server.
Your master.cf should contain a (multipart) line simliar to

smtps     inet  n       -       n       -       -       smtpd
    -o syslog_name=postfix/smtps
    -o smtpd_tls_wrappermode=yes
    -o smtpd_sasl_auth_enable=yes
    -o smtpd_client_restrictions=permit_sasl_authenticated,reject

However, it likely only has

smtps     inet  n       -       n       -       -       smtpd


text:
Q: npm install throwing expected "0.15.7" but got "" on new vite project I just created a new vite project and i am getting the following error when executing npm install.
node.js: 16.17.0
npm: 8.15.0
npm ERR! C:\xxx\GIT\NewTestProject\node_modules\esbuild\install.js:93
npm ERR!     throw new Error(`Expected ${JSON.stringify("0.15.7")} but got ${JSON.stringify(stdout)}`);
npm ERR! C:\xxx\GIT\NewTestProject\node_modules\esbuild\install.js:93
npm ERR!
npm ERR! Error: Expected "0.15.7" but got ""
npm ERR!     at validateBinaryVersion (C:\xxx\GIT\NewTestProject\node_modules\esbuild\install.js:93:11)
npm ERR!     at C:\xxx\GIT\NewTestProject\node_modules\esbuild\install.js:240:5

package.json
{
  "name": "newtestproject",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "vue": "^3.2.37"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^3.1.0",
    "vite": "^3.1.0"
  }
}

A: Running cmd as admin solved the issue.


text:
Q: No value accessor for form control with name - Angular 5 this is the exact error being faced :

QuizComponent.html:11 ERROR Error: No value accessor for form control
  with name: 's'

I'm trying to create a quiz app with 4 options(buttons) using JSON.The user-provided answer is compared with JSON provided answer on click of Next button.I've seen other search results here regarding this error which asks to use Forms, but since I'm not creating anything having explicit input but simple value of button,I guess Forms shouldn't be used.
PS: This code was working perfectly before I implemented clickable buttons in HTML for quiz options. I was using radio buttons earlier.Something is wrong with ngModel two way binding and really not sure what is it as the HTML code is displayed correctly if I remove ngModel tag from buttons or otherwise the buttons are not shown if I write ngModel inside them.
HTML:

        {{actiVar.QuestionID}}.{{actiVar.Question}}

        <button type="button" name="s" id="oneans" [(ngModel)]="hello" [value]="actiVar.OP[j+0]" [disabled]="permission">{{actiVar.OP[j+0]}}</button>

        <button type="button" name="s" id="oneans" [(ngModel)]="hello" [value]="actiVar.OP[j+1]" [disabled]="permission">{{actiVar.OP[j+1]}}</button>

        <button type="button" name="s" id="oneans" [(ngModel)]="hello" [value]="actiVar.OP[j+2]" [disabled]="permission">{{actiVar.OP[j+2]}}</button>

        <button type="button" name="s" id="oneans" [(ngModel)]="hello" [value]="actiVar.OP[j+3]" [disabled]="permission">{{actiVar.OP[j+3]}}</button>

<button type="button" class="btn btn-light" id="button1" *ngIf="this.fLoop != this.questArray.length" (click)="filterAnswer(hello)">Next</button>

.TS:
filterAnswer(i: any) //Comparing Answer submitted by user with JSON provided answer
  {
    this.correctAns = this.activeArray[0].isRight;
    this.lastIndex = this.activeArray[0].QuestionID;
    if (this.correctAns == i && this.correctAns != this.storeArray[this.storeCounter - 1]) {
       console.log(i);

      this.storeArray[this.storeCounter] = i; //Only the correct answer provided by user gets stored here.
      this.storeCounter++;

      this.scoreCounter++;
}
    }

A: I would not use ngModel on buttons. Use simple (click) event and store data in variable. Do something like this:
<button type="button" name="s" id="oneans" [disabled]="permission" (click)="getUsersAnswer(actiCar,OP[j+0])">{{actiVar.OP[j+0]}}</button>

and in your .ts file just store that value in some variable:
getUsersAnswer(answer: any) {
   this.i = answer;
}


text:
Q: How to make key value pair array when chekbox checked using jquery? I have multiple checkbox, when i check a checkbox two key value pair will generate.
Like this : Object {id: "101", name: "example"}
This will generate for every checkbox checked and i want for multiple checkbox checked array. look like this :
[{id:"id1",name:"name1"},{id:"id2",name:"name2"}]

What I have done
$('.chkCompare').click(function(event) {
    var value = [],
        projectName = {},
        span = $(this).attr('id'),
        value = $('.chkCompare:checked').map(function() {
            $('#span' + span).text('ADDED').css({
                "color": "green"
            });
            projectName['id'] = $(this).attr('id');
            projectName['name'] = $(this).attr('title');
            return value.push(projectName);
        }).get();
});

When I uncheck checkbox they will be remove from array and want to prevent check maximum 3 checkbox if >3 then show an alert box.

A: You can check the length property of :checked checkbox's. Based on your  condition and use event.preventDefault() to cancel the default action.

$('.chkCompare').click(function(event) {
  var checkedElemets = $('.chkCompare:checked');
  if (checkedElemets.length > 3) {
    event.preventDefault();
    alert('Only 3 checkbox can be checked');
  }

  var values = checkedElemets.map(function() {
    return {
      id: this.id,
      name: this.title
    };
  }).get();

  console.log(values)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="chkCompare" title='t1' id='i1' />
<input type="checkbox" class="chkCompare" title='t2' id='i2'/>
<input type="checkbox" class="chkCompare" title='t3' id='i3'/>
<input type="checkbox" class="chkCompare" title='t4' id='i4'/>
<input type="checkbox" class="chkCompare" title='t5' id='i5'/>

A:     $("input[type='checkbox']").change(function(){
      var arr = {};
       var count = 0;
      $.each($("input[type='checkbox']:checked"), function(){
         if(count++<3){
           arr[this.id] =this.name;
         }else{
           $(this).prop('checked', false);
         }

      });
      console.log(JSON.stringify(arr));
    });


text:
Q: ¿Como MOSTRAR un PDF traido de JAVA en HTML-JAVASCRIPT? Necesito MOSTRAR un pdf que llega desde JAVA.
Eso lo hago con un servlet.
function descargarCarta(){
console.log("entra a descargar");
           var settings = {
               "async": true,
   "crossDomain": true,
   "url": "http://localhost:8080/StaffingApp/accesoServlet?resource=reporteCartaLaboral&codigoVinculacion=00959158-01-TL",
   "method": "GET"
   }

   $.ajax(settings).done(function (response) {
   console.log(response);
   });
}

asi lo envio del servlet
byte[] reporteCarta = null;
reporteCarta = generarReporteCartaLaboral(request, response);
ServletOutputStream servletOutputStream = response.getOutputStream();
response.reset();
String codigo = request.getParameter("codigoVinculacion");
System.out.println("codigo" + codigo);
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "inline; filename=\"Carta_Laboral_" + codigo + ".pdf\"");
servletOutputStream.write(reporteCarta);
servletOutputStream.close();

Y a se genera como pdf, pero necesito mostrarlo como PDF en un poryecto HTML
Gracias por su ayuda.

A: Si lo que necesitas es obtener un archivo, simplemente desde el servidor seteas el tipo de contenido de la respuesta y envias el contenido:
public void download() throws IOException {
    // Prepare.
    byte[] pdfData = getItSomehow();
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();

    // Initialize response.
    response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    response.setContentType("application/pdf"); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
    response.setHeader("Content-disposition", "attachment; filename=\"name.pdf\""); // The Save As popup magic is done here. You can give it any filename you want, this only won't work in MSIE, it will use current request URL as filename instead.

    // Write file to response.
    OutputStream output = response.getOutputStream();
    output.write(pdfData);
    output.close();

    // Inform JSF to not take the response in hands.
    facesContext.responseComplete(); // Important! Else JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Desde html solo necesitarais un link a la página que genera el contenido a partir del arreglo de bytes, en este caso un pdf.
El código es de ejemplo, talvez te pueda ayudar.


text:
Q: Can we print the charts, pdfs and other grid reports in ext.js? I am new to Ext.js,going to develop application using Ext.js, As per requirement need to print charts, pdfs and other grid reports. Can anybody tell me is it possible by ext.js? if it possible means can let me know how to achieve? please provide me related links else give me hints?. Great appreciate thank you.

A: ExtJS does not allow any feature to print anything.
You need to use other libraries like aspos or open xml to generate excel sheets, pdf files in which you can draw charts, grids.
I hope this clarifies your questions.