text:
Q: Cannot assign value of generic type I have generic class - Class1.
class Class1<T> {
}

And I have Class2 with variable object1 of type Class1 and generic type UIView
class Class2 {
    var object1: Class1<UIView>?
}

When I create instance of Class2 and try to assign to object1 instance of type Class1 and generic type UITableView I got an error: "Cannot assign value of type Class1<UITableView> to type Class1<UIView>"
var c = Class2()
c.object1 = Class1<UITableView>()

However the same logic works for Array. Why?

A: Let me elaborate on Anton's comment. The question is when you can use a B for an A. Usually you can do that when B is a subtype of A. For instance, you can assign a UITableView to a variable of type UIView.
So when is something a subtype of something else?
For classes, this is straightforward: if you subclass B from A, B is a subtype of A.
For function types, you need to consider the argument types and the return type. A function type F2 is a subtype of function type F1 if F2's parameter types are supertypes of F1's parameter and F2's return type is a subtype of F1's return type. You could say that a function must not require more (i.e. it must not require subtypes as parameters but can require supertypes) and must not provide less (i.e. it must not return a supertype but can return a subtype) for its type to be a subtype. The terminology is that the parameter types must be contravariant and the return type must be covariant.
Example:
var f1: UIControl -> UIControl = ...

let f2: UIView -> UIControl = ...
let f3: UIControl -> UIButton = ...
let f4: UIView -> UIButton = ...
f1 = f2  // Fine, f2 takes UIView so it also takes UIControl
f1 = f3  // Fine, f3 returns UIButton which is a UIControl
f1 = f4  // Fine, both of the above

let f5: UIButton -> UIControl
let f6: UIControl -> UIView
let f7: UIButton -> UIView
f1 = f5  // Error, couldn't call with a UIControl because f5 demands at least a UIButton
f1 = f6  // Error, call would return only a UIView
f1 = f7  // Error, both of the above

So the types of f2, f3, and f4 are subtypes of f1's type and the types of f5, f6, and f7 are not.
Now what about generic types? In Swift, custom types with type parameters are all invariant. That is, in your example no Class1<T2> object can be used as a Class1<T1> object, no matter the relation between T1 and T2 (except when T1 and T2 are the same type).
However, Swift has indeed some built-in variance rules that makes your example with arrays work: [UITableView] (Array<UITableView>) is a subtype of [UIView] (Array<UIView>). Note that the same is true for optionals, i.e. UITableView? (Optional<UITableView>) is a subtype of UIView? (Optional<UIView>). So both arrays and optionals are covariant with their type parameter.
Further reading:

*

*Liskov Substitution Principle on Wikipedia

*Mike Ash on Covariance and Contravariance


text:
Q: Handling Unexpected return data in ResultSet I'm working with an old AS/400 application which uses DB2 as the underlying database.
I'm doing some SELECT's to get data out. There is a field called OHOREF which means Order Header Order Reference... ie. it's the order number's reference number for a give order. We use this to link website orders to order numbers generated by our vendor application. In the vendor's database guide, this field is listed as:
|  Field | Type | Length | Dec | Req. |                   Text                    |
+--------+------+--------+-----+------+-------------------------------------------+
| OHOREF |  A   |   15   |     |      | Customer/Suppliers Order Number Reference |

This seems to indicate this field is stored as an integer value, constrained to be no longer than 15 digits, and no decimal place allowed. So, like: 123456789012345
This vendor is very unhelpful and tries to "guard" their "IP" and does not provide better docs than I already have. (sigh)
The problem I'm facing, is when using:
int ohoref = resultSet.getInt(columnNumber);

I'm finding, when there is no reference number, this column is not null, but instead is max filled with padded spaces " ". So, like "               ". This results in a Data type mismatch exception being thrown. I do not know what field type "A" means in the table above, and I assume it has a special meaning for the vendor.
Is there no more elegant solution to dealing with this scenario other than to select everything out as a String? This seems awful, and makes the code have to do manual conversions all over the place, increasing potential risk of getting it wrong and/or causing problems elsewhere. Is type A a String or an Integer?

A: It's hard to say what your vendor means by the A data type but generally speaking I would expect to see I for an integer column. A is likely to stand for "alphanumeric", which isn't really a data type but rather the contents description, for which the data type would be CHAR(15) (based on the fact that empty values contain 15 spaces).
To be certain you could find out the actual data type from java.sql.ResultSetMetaData.

A: Don't know this might help or not but give this a try,
you can  get the InputStream objects pertaining to that column using below methods,
   rs.getAsciiStream(columnNumber)
   rs.getCharacterStream(columnNumber)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to load a module inside an OCaml file? I wish to use module Std inside my OCaml .ml file.
I tried #load "Std", but the compiler complains.
How can I load a module inside OCaml?

A: You must compile the module you wish to include first, provide the location of the compiled files to compilation commands of modules depending on it, then provide it in the final compilation command line.
Let's consider for instance file foo/moduleA.ml:
let v = 1

and file bar/moduleB.ml:
open ModuleA
let w = v

The commands:
$ cd foo
$ ocamlc -c moduleA.ml
$ cd ..

will produce moduleA.cmo and moduleA.cmi. The former is the bytecode object of the module (like a .o file in for native object files, but containing bytecode data and text), the later is a bytecode compiled header, produced from an automatically generated .mli file. This bytecode header is necessary for the compiler to compile files which depend on ModuleA.
$ cd bar
$ ocamlc -I ../foo -c moduleB.ml
$ cd ..

will succeed in producing moduleB.cmo, which depends on ModuleA, because the previous command has been successful, and because we indicate the compiler where to look for dependancies with the -I command line parameter, followed by the path of the first module.
The last command below will produce a bytecode executable from both modules:
$ ocamlc -I foo -I bar moduleA.cmo moduleB.cmo -o prog.byte

The modules must be provided in that order, to let the compiler know the dependancies first. The -I parameters this time indicate where to find the .cmo files.
In your case, you must therefore use the -I <location of std.cmi> for the compilation proper phase, and -I <location of std.cmo> (or std.cma, if it is a library) for the second phase (the link phase). If you can combine both phases in one command (ie. ocamlc -I foo foo/moduleA.ml bar/moduleB.ml -o prog.byte), and if both cmo and cmi files are in the same directory, only one parameter will suffice.


text:
Q: Checking for 'gee-0.8' >= 0.8.0 : not found I am trying to install pysoy and at the stage of configuration using
./waf configure
it gives an error as seen below

Checking for 'gee-0.8' >= 0.8.0          : not found

The configuration failed

(complete log in /home/mylap/Documents/coding/pysoy/libsoy/build/config.log)

I think this needs libgee needs to be installed..
My attempt to install libgee:

*

*downloaded libgee-0.11.4 from net

*set workspace to that directory and i ran ./configure

*./configure executed succesfully

*ran make command and encountered this error :

mylap@mylap-Inspiron-N5110:~/libgee-0.11.0$ make
make  all-recursive
make[1]: Entering directory `/home/mylap/libgee-0.11.0'
Making all in gee
make[2]: Entering directory `/home/mylap/libgee-0.11.0/gee'
make[2]: Leaving directory `/home/mylap/libgee-0.11.0/gee'
Making all in tests
make[2]: Entering directory `/home/mylap/libgee-0.11.0/tests'
  CCLD     tests
../gee/.libs/libgee-0.8.so: error: undefined reference to 'g_get_num_processors'
collect2: ld returned 1 exit status
make[2]: *** [tests] Error 1
make[2]: Leaving directory `/home/mylap/libgee-0.11.0/tests'
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory `/home/mylap/libgee-0.11.0'
make: *** [all] Error

*I couldn't find answer for  " undefined reference to g_get_num_processors
Please help

(Also, can someone add tag pysoy to this question. I don't have the privilege to make new tags..)

A: Please install first these packages:
libgee-0.8-2
libgee-0.8-dev

You can install them with this command:
sudo apt-get install libgee-0.8-2 libgee-0.8-dev

Or with this other:
sudo apt-get install libgee-0.8*


text:
Q: Is it possible to set Selenium Webdriver to take a screen capture upon encountering an error Is it possible to set up webdriver so that when an error is encountered, a screen capture can be taken?

A: If you are running JUnit, you can set up a Rule to take a screenshot on failure. There is a similar way to do this for TestNG.
Event.java
public static void takeScreenshot(WebDriver driver, String name) throws IOException {
if (driver instanceof TakesScreenshot) {
    File tempFile = ((TakesScreenshot) driver)
            .getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(tempFile, new File(String.format("screenshots/%s.png", name)));
    }
}

ScreenshotOnFailRule.java
public class ScreenshotOnFailRule extends TestWatcher {

    private static boolean shouldStopTests = false;

    @Override
    public void failed(Throwable e, Description d) {
        try {
            Event.takeScreenshot(yourDriver, "Failure");
        } catch (IOException ioe) {
            log.error("Test didn't finish due to hard failure.");
            shouldStopTests = true;
        }
        if (shouldStopTests) {
            System.exit(0);
        }
}

Then at the start of your test class:
    @Rule
    public TestRule screenshot = new ScreenshotOnFailRule();

A: Of course, it is possible. Here is the example:
WebDriver firefoxDriver = new FirefoxDriver();
firefoxDriver.get("http://www.google.com/");
File scrsht = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrsht, new File("your_path/screenshot.png"));


text:
Q: How do I retrieve an attribute's name using the nodeName property? You can easily retrieve the tag name of an element using the nodeName, like this:

var atnode = document.getElementById("link-test");
alert(atnode.nodeName);
link

But how do I use the nodeName to get the attribute of the element instead?
Using the getAttribute() does not do what I want, because you have to insert the name of the attribute first, and then it just gives you back the value of the attribute. I want to get the name of the attribute just like I did with nodeName. I know nodeName can be used with attribute nodes too, but how?

A:

const atnode = document.getElementById("link-test");
const nodes=[];
const values=[];

for (let att, i = 0, atts = atnode.attributes, n = atts.length; i < n; i++){
    att = atts[i];
    nodes.push(att.nodeName);
    values.push(att.nodeValue);
    console.log(att.nodeName + " - " + att.nodeValue);
}
link

After using attributes method you can use nodeName to get the attribute name and nodeValue to get the value of the attribute.
After pushing it to array you can get attribute and value of it using same index in both arrays.

A: You can get a list of the attributes with getAttributeNames() on the node. In your example, you could do like so:
atnode.getAttributeNames() This will return ["href", "id"].
Then you can loop through the list with getAttribute(<item from list as string>) to get the values of the element's attributes.

A: If I understood right, you just need to use the getAttributeNames method.
Follows an example:

const exampleElement = document.getElementsByTagName("example")[0];
console.log(exampleElement.getAttributeNames());
<example name="one" last="two"></example>


text:
Q: File name encoding issues System receives a zip file together with a list of file names (inside zip) that should be processed.
Problem: occasional "file not found error".
The file name specified in error message and the one visible in file system are visually identical, therefore it's an encoding issue.
The error does not occur if file open operation is retried with a normalized file name like so:
filename.Normalize(System.Text.NormalizationForm.FormD)

Current solution is :
bool TryProcessFile(string filename) {
    string[] filenamesToTry = new string[] {
        filename,
        filename.Normalize(System.Text.NormalizationForm.FormD)
    }
    foreach (string fname in filenamesToTry) {
        try {
            ProcessFile(fname);
            return true;
        }
        catch (FileNotFoundException) {
        }
    }
    return false;
}

function ProcessFile:
void ProcessFile(string filename) {
    string fullpath = Path.Combine(this.extractionDir, filename);
    byte[] fileBytes = File.ReadAllBytes(fullpath); // throws file not found
    ...
}

Is there a way to avoid an error in the first place?
In general how to tackle problems like this?


text:
Q: Passing value of selected radio button in Rails I'm working on an app in Rails that has teacher and student users. I want to list all the users that belong to a teacher and then let the teacher select a student to send a message to. I have a message model that has :content and :user_id for params. I want to set the :user_id based on the student selected. Here is my code:
<% @students = Student.all %>
    <% @students.each do |student| %>
          <% if student[:teacher_id] == @current_user.id %>
            <%= radio_button 'student', 'id', student.id %>
            <%= student.name %>
            <% @current_student = Student.find(student.id) %>
          <% end %>
    <% end %>

<%= form_for Message.new do |f| %>
   <%= f.text_area :content, class: 'messageTextarea' %> <br>
   <%= f.hidden_field :user_id, :value => @current_student.id %>
   <%= f.submit %>
<% end %>

So, I am looping through all students and printing those that have the same ID as the current user (the teacher) with a radio button. The radio button's value is the student's id. Then I want to pass that value to the :user_id of the message so it will then be retrievable for the student's view.
Currently, this code always passes in the value of the last student listed rather than the student selected. How can I change
<% @current_student = Student.find(student.id) %>

to find the student selected rather than the last one?
I did test this code using
 <%= f.hidden_field :user_id, :value => @current_user.id %>

and that did work, but I don't want the current_user's id, of course. Thanks for any help!

A: If you want one form with radio buttons for the students, You gonna need a little bit JavaScript(Or Jquery), All you have to do is to put a listener on these radio button and when user click on one of them you change the hidden input of user_id name.
User example in this link will help you to put listener on a bunch of radio buttons and change another field value, it will be something like this:
$('input[type=radio][name=student[id]]').change(function() {
    $('#user_id').val($(this).val());
});

all you have to do is to make sure of name=student[id] and #user_id, if you used this approach you won't need this line anymore:
<% @current_student = Student.find(student.id) %>

Hope it works.


text:
Q: Android Seek bar I'm just wondering if the seekbar changed in Android 2.1 . I tried to create one but it showing up as a green line with a circle on it instead of the usual yellow rectangle. If so, is there any other option to create a similar seekbar to control volume on 2.1? Thanks

A: You can use the setThumb() and setProgressDrawable() of SeekBar to customize the UI


text:
Q: How do I check that my edge normals in an arbitary triangle are inward (or outward)? I am considering an arbitary 2D triangle with points:
X1=(x1,y1), X2=(x2,y2), X3=(x3,y3).
I am then trying to compute the inward (or outward) normals to each edge such that they are all facing inward (or outward) but am strugling here.
Currently I have my normals by multiplying by a rotation matrix R=[0 -1;1 0] to give:
n12=R*(X1-X2)
n13=R*(X1-X3)
n32=R*(X3-X2)
but I have no idea if they are all facing inwards for an arbitary triangle.
The reason I need to keep this arbitary is so that I can compute this for multiple triangles in a mesh.
Any help will be appreciated.

A: To expand on Rahul's comments, before you can talk about "inward" and "outward" normals, you first have to determine where the inside and outside of the triangle lie. This is equivalent to figuring out whether traversing the vertices in numerical order corresponds to a clockwise or counterclockwise orientation of the vertices. So, examine the sign of the  determinant $$\Delta = \begin{vmatrix}x_1&y_1&1\\x_2&y_2&1\\x_3&y_3&1\end{vmatrix}.$$ If it is positive, then the vertices are in a counterclockwise arrangement; if negative, they are clockwise. (If the determinant vanishes, then the points are colinear—the triangle is degenerate.)
You can now find inward normals via a 90-degree rotation as in your question, but to do this you need to be careful to use the same orientation for all of the difference vectors. In your question, you use $X_1-X_2$ and $X_1-X_3$, which traverse the edges of the triangle in opposite directions. If you apply the same rotation to both of these, you will end up with one inward and one outward normal no matter which direction you rotate them in. For the three edge vectors to have consistent orientation, you need to take these differences in a consistent order: $X_2-X_1$, $X_3-X_2$ and $X_1-X_3$.
Your rotation matrix represents a counterclockwise 90-degree rotation, so if the triangle is oriented counterclockwise, multiplying each of the above differences by $R$ will produce inward normals; if it's clockwise they will be outward, and you can get inward normals by negating them. In short, $$\begin{align} n_{12} &= \operatorname{sgn}(\Delta)R(X_2-X_1) \\ n_{23} &= \operatorname{sgn}(\Delta)R(X_3-X_2) \\ n_{31} &= \operatorname{sgn}(\Delta)R(X_1-X_3) \end{align}$$ produces inward normals regardless of the order of the vertices.

A: The cross product of two vectors produces another vector perpendicular (aka "normal") to both. The "sign" of the resulting vector swaps as you swap the order of the vectors.
Now, you get $$v12=\{x2-x1, \quad y2-y1, \quad z2-z1\}$$ and $$v13=\{x3-x1, \quad y3-y1, \quad z3-z1\}$$
The cross-product $n= v12$ x $v13$ heads to the same direction as the right-hand rule from $v12$ to $v13$. And the other normal (opposite) is $no= v13$ x $v12$
You are in a $2D$ case (set all $zi=0$), so knowing if $v12$ towards $v13$ is clockwise or counter-clockwise is easy:
$$res = (y2 - y1)·(x3 - x1) - (x2 - x1)·(y3 - y1)$$
will give a positive value if $(x3,y3)$ is at right of line $X1 \to X2$  wich means that $X1,X2,X3$ order is clockwise.


text:
Q: Integrate Ehcache with Spring MVC and Hibernate Application I'm working on a java application which is being developed using Java (JDK 1.8), Spring MVC(Restful Web service Layer) 4.x, Hibernate 5.x, MYSQL Db and Tomcat Server 8. Everything is configured programmatically in java config and there are no XML Configuration files. I need to configure second level cache for hibernate. I'm planning to integrate EhCache with the application.

*

*Is this possible to achieve with Java Config (Without EhCache.xml file) ?

*Another question is what's the difference between spring cache and hibernate second level cache ?

A: Regarding configuring Ehcache as Hibernate second level cache programatically, no this is not possible out of the box when you are using Ehcache 2.x and net.sf.ehcache.hibernate.EhCacheRegionFactory. You will have to extend the factory class and make it configure the CacheManager to use.
For Hibernate 5.2 with JCache, using Ehcache 3.x as provider, there is a simpler path: make sure you configure first the JCache CacheManager and then have Hibernate use the one configured. As an alternative, you can extend the org.hibernate.cache.jcache.JCacheRegionFactory and adapt CacheManager and Cache creations. The following sample can help you figure it out.
On the second point:
Spring caching is a general abstraction that can be used at all layers of your application where you decide what is cached, from which call, etc ...
Hibernate second level cache is a dedicated cache sitting between your object model and the database access. You tell the framework what to cache with which semantics but then the actual work is hidden from you.
You can certainly combine both in a single application, where you would cache higher level results such as service call results or webpages with Spring Cache and entities / query results with Hibernate 2LC. Though I would recommend to use different Cache to well separate their content and lifecycle.


text:
Q: Pagination issue in ui-bootstrap-tpls.js I am working on angularJS project and implementing pagination using ui-bootstrap-tpls.js pagination directive. But I am facing one issue in this. next and previous buttons are clickable even if they are disabled.
You can see the demo here: http://plnkr.co/edit/94i0y0PJpHMDTSEF2kXt?p=preview

Can you please guide me on this? How to disable click on next and previous button if there is not page further.

A: The disable on next and previous works as intended - You can see that $scope.pageChanged isn't fired. $scope.test is fired because it's attached with ng-click="test()" to the paging container itself, and the container is not disabled.
<pagination total-items="totalItems" ng-model="currentPage" ng-change="pageChanged()" ng-click="test()"></pagination>


text:
Q: how to release memory of SQL Server? I have a server that saves 1000 record every minute, I wrote a trigger that does a series of jobs for every row and I used a lot of table and other variables in it. Now my SQL Server memory usage increases very fast and I can't manage it.
I set min server memory and max server memory but it can't help me, when I set max memory server my SQL Server performance decreased and save process interrupted.
I used these resources but these can't help me:
Great SQL Server Debates: Lock Pages in Memory
How to: Set a Fixed Amount of Memory (SQL Server Management)
I have to reset SQL Server Service every 4 hour but this is not a correct way.
How to release memory of SQL Server?


text:
Q: Create a measure in MDX for a set of Members I need something as following:
with member Measures.Test2 as (Measures.Test, {[Assets Monthly].[Disbursed Date].&[2014], [Assets Monthly].[Disbursed Date].&[2015]})
select Measures.Test2 on columns
from databaseX

It works only if I set it with only one member, ex:
with member Measures.Test2 as (Measures.Test, [Assets Monthly].[Disbursed Date].&[2014])

The error that I get in the first case is:

The  function expects a string or numeric expression for the
  argument. A tuple set expression was used.

A: Against AdvWrks:
WITH
  MEMBER Measures.Test2 AS
    Sum
    (
      {
        [Date].[Calendar].[Calendar Year].&[2006]
       ,[Date].[Calendar].[Calendar Year].&[2007]
      }
     ,[Measures].[Internet Sales Amount]
    )
SELECT
  Measures.Test2 ON COLUMNS
FROM [Adventure Works];

Your script:
WITH
  MEMBER Measures.Test2 AS
    Sum
    (
      {
        [Assets Monthly].[Disbursed Date].&[2014]
       ,[Assets Monthly].[Disbursed Date].&[2015]
      }
     ,Measures.Test
    )
SELECT
  Measures.Test2 ON COLUMNS
FROM databaseX;

This is prettier. Created a calculated member on the Date hierarchy and chuck the measures in the WHERE slicer:
WITH
  MEMBER [Date].[Calendar].[testPeriod] AS
    Aggregate
    (
      {
        [Date].[Calendar].[Calendar Year].&[2006]
       ,[Date].[Calendar].[Calendar Year].&[2007]
      }
    )
SELECT
  [Date].[Calendar].[testPeriod] ON COLUMNS
FROM [Adventure Works]
WHERE
  [Measures].[Internet Sales Amount];


text:
Q: OData query that uses .IncludeTotalCount() on a filtered (where clause) query Say I have the following query on the Netflix OData Endpoint:
Titles.Where(x=>x.AverageRating > 3.0)

Is there a way to use .IncludeTotalCount() to get the count of titles that fit the where clause?  (Not the total count of items in the Titles resource.)
I looked at the code provided here: http://msdn.microsoft.com/en-us/library/ee474390.aspx
But it does not seem to work with a where clause.

A: I tried this and it works just fine:
DemoService ctx = new DemoService(new Uri("http://services.odata.org/OData/OData.svc/"));
var query = (DataServiceQuery<Product>)ctx.Products.IncludeTotalCount().Where(p => p.Rating < 4);
QueryOperationResponse<Product> response = (QueryOperationResponse<Product>)query.Execute();
Console.WriteLine(response.TotalCount);
foreach (var i in response)
{
    Console.WriteLine(i.Name + ", " + i.Rating.ToString());
}

What does it mean "it does not work" in your case?

A: Based on @Vitek Karas' response and your comments, it looks like you need to cast the IQueryable you get back from the where clause to DataServiceQuery.


text:
Q: Show the total price with Woocommerce Force Sales I'm testing Woocommerce with the Force Sells extension. I need the price on the product page to be the total price including the forced products. Now it only shows the main products price and the forced products price will only be added when proceeding to the cart.
How can I display the combined price?


text:
Q: I need to know the disadvantages do keep Business Layer in Procedures  In my work, i have a friend that insists to keep the business logic inside the database using stored procedures ...
What are the arguments that i can use to convince him not to do such thing?
The reason he want to do this is because we have multiple systems with diferent plataforms (Web Application in .NET with VB.NET and another Desktop Application developed in Power Builder - Sybase).
Thanks!

A:
What are the arguments that i can use to convince him not to do such thing?

What are your arguments against it? Why do you necessarily want to stay away from stored procedures?
This is actually not a bad idea. If you have different systems written in different languages access the database, it may help to keep at least some of the business logic in the database.

A: I would go for the web service for several reasons:

*

*You can expose your services to all kind of clients to use it

*It's more flexible, more convenient for debugging, for testing

*You will gain a better source control support

*Your programming language will be probably more expressive than SQL

A: *

*Not strongly-typed.

*Cannot easily refactor, breaks clients at runtime.

*Not unit-testable.

*Most likely not all business logic can be a stored-proc so your logic is split amongst db and code.

*Stored procedures are not as capable or powerful as a programming language

*Harder to obtain the right level of encapsulation requiring your client to know the internals of your data schema

*Harder to version

*Business logic is tied to a database vendor which you'll be stuck with for life

Edit: other user-contributed points:

*

*harder and more expensive to scale

A: Pro web services, con database logic:

*

*If your database is shared by others your app will now be coupled both at the data and logical layers if you put the logic in the database.  That's usually a bad thing.

*I would be concerned about load on the database server.  If your relational database is getting hammered by queries and calculations you won't have the possibility to scale it as easily as you would if the middle tier is doing calculations.

Pro database logic, con web services:

*

*If the database is wholly owned by your app, perhaps putting the logic in it is an acceptable choice.

*I don't worry as much about the fear of switching databases, because that happens more rarely than middle tier changes.  Middleware fashions come and go, but the data is the crown jewel of any business.

*Web services have their downside, too.  Translating XML to objects and back is a waste of CPU cycles.  In-memory calls are orders of magnitude faster than network calls.  A single roundtrip to your "simple" service today might be 200 ms, but start adding those up and pretty soon your SLA will be gone.

Don't give in to dogma.  Consider the pros and cons of both and make a rational decision based on your app's particular situation.  Both you and your co-worker sound like you've make it a black or white emotional decision.  Remember: the outcome doesn't reflect on you as a person.  You'll find out about what it says about you as a designer after it's in production.

A: Define business logic
Anyway, you simply use the DB to do what it does best. Stuff like aggregation and data integrity.
But every system is a compromise. If you have 5 different sets of clients, then the DB might be the best place. Not every spreadsheet or Access DB can call your beautiful middle tier web services...


text:
Q: How can I draw this kind of hierarchy diagram? I apologize in advance if this question (or one which implies an answer to this) has already been asked. Any suggestions on how to draw in Latex a diagram of the following shape ?

Thank you very much !

A: There are countless possibilities to do that. I hope this gives you something to build on.
\documentclass[tikz,border=3.14mm]{standalone}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}[bullet/.style={circle,fill,inner sep=2pt}]
 \foreach \X in {1,2,3}
 {\node[bullet,label=above:$\Sigma_\X^0$] (S\X) at (3*\X,1){};
 \node[bullet,label=below:$\Pi_\X^0$] (P\X) at (3*\X,-1){};
 }
 \node[bullet,left=1.5cm of S1,label=above:$\{2^\omega\}$] (w){};
 \node[bullet,left=1.5cm of P1,label=below:$\{\emptyset\}$] (e){};
 \path (w) --(P1) node[midway,bullet,label=above:$\Delta^0_1$]{};
 \foreach \X [count=\Y] in {2,3}
 {\path (S\X) -- (P\Y) node[midway,font=\Large\bfseries,
  label=above:{$\omega_1\ifnum\X=3
  ^{\omega_1}
  \fi$ alternations}]{\dots};}
\end{tikzpicture}
\end{document}


text:
Q: How to get info window to pop up when user clicks on the marker? I have the following code that displays markers around a certain area and I want to have an info window pop up when the marker is clicked on. Currently, all the markers refresh when clicked on and the info window does not pop up. How can I change my code for the info window to pop up and display the name of each marker?
const mapStyles = {
  width: '100%',
  height: '100%'
};

export class MapContainer extends Component {

    constructor(props) {
        super(props)

        this.state = {
        selectedPlace : '',
        isSelected: false
        }
    }

  onClose = props => {
      this.setState({
        selectedPlace: '',
        isSelected: false
      });
  };

  render() {
    return (
      <Map
      google = {this.props.google}
      zoom = {16}
      style = {mapStyles}
      initialCenter = {
        { lat: 1.296643,
          lng: 103.776398}
        }>
          {data.carpark.map(park =>(
              <Marker
              key = {park.id}
              position = {{
                  lat: park.latitude,
                  lng: park.longitude
              }}
              name = {park.caption}
              onClick={() => {this.setState(
                {selectedPlace: park.caption,
                isSelected: true}
              )}}
              />
          ))}
          {this.selectedPlace && (
           <InfoWindow>park details</InfoWindow>

          ) }

      </Map>
    )
  }
}

A: Can you provide which library you are using?
I successfully implemented this on my code using the react-google-maps library. The logic I made involves storing the park.id to a parkid state handler every time the marker is clicked. Then I used a condition that check if the value of parkid state is equal to the park.id.
Here is my sample code and below is the snippet:
import React, { Component } from "react";
import {
  withGoogleMap,
  withScriptjs,
  GoogleMap,
  Marker,
  InfoWindow,
} from "react-google-maps";
import data from "./data.json";

class Map extends Component {
  constructor(props) {
    super(props);

    this.state = {
       parkid: "",
    };
  }

  render() {
    const GoogleMapExample = withGoogleMap((props) => (
      <GoogleMap
        defaultCenter={{ lat: 40.756795, lng: -73.954298 }}
        defaultZoom={13}
      >
        {data.map((park) => (
          <Marker
            position={{ lat: park.lat, lng: park.lng }}
            onClick={() =>
              this.setState({
                parkid: park.id,
              })
            }
          >
            {this.state.parkid === park.id && (
              <InfoWindow
                onCloseClick={this.props.handleCloseCall}
                options={{ maxWidth: 100 }}
              >
                {park.id}
              </InfoWindow>
            )}
          </Marker>
        ))}
      </GoogleMap>
    ));

    return (

        <GoogleMapExample
          containerElement={<div style={{ height: `500px`, width: "500px" }} />}
          mapElement={<div style={{ height: `100%` }} />}
        />

    );
  }
}

export default Map;

Note: To make the sample code work, change the value of YOUR_API_KEY in the index.js file.

A: You try to access this.selectedPlace when you probably meant to access this.state.selectedPlace:
{this.state.selectedPlace && (
    <InfoWindow>park details</InfoWindow>
)}


text:
Q: Controlling margins and icon for angulars mfb-menu I am new to angularJs and web app devlopment. Just trying to understand floating buttons of angular and its properties (http://nobitagit.github.io/ng-material-floating-button/). This is the small [plunkr][1] (http://plnkr.co/edit/4eFxqSg21U5ZR5H59rdK?p=preview) for the same. I am trying to to modify the plunkr to acheive the mentioned.
1.Factors that adjust the buttons vertical dsitance
2.Methods to add custom PNG instead of "ion-ios-star"
For controlling the dstance i tried altering the margins for it never worked out and oor controlling icon i still have no clue.
Request some guidance
Trail - 1 modifying mfb.css
  list-style: none;
  margin: 0;
  padding: 0; }
  .mfb-component__list > li {
    display: block;
    position: absolute;
    top: 0;
    right: 1px;
    padding: 30px 0; //changed padding from 0 - 60 does not give any effect
    margin: -10px 0;
   // (From 0 to 60*) Yes it had effect on distance between main menu and first child element.
//However, none of the other available give margin in the  class is giving effect
}

A: *

*The vertical distance between each <li> element is handled by the following css selector. .mfb-component__list > li which means select all <li> elements that are children of the .mfb-component__list class. You can make changes to the padding and margin of that selector to change the vertical spacing between icons.

*The glyph-icons built into the plunkr can be removed by swapping out the .ion-ios_## classes for your own custom glyphicon or css class. You could use background-image here to set a custom png. or you could even embed and image within the HTML.


text:
Q: Is there any toolkit , reference or library files for touchscreen windows form application in vb.net? I'm creating simple application for desktop application in which user can give input by pen/stylus as their signature. Is there any reference in .net for this features?

A: I rather found this class/namespace: System.Windows.Input.Stylus (http://msdn.microsoft.com/en-us/library/ms604577.aspx). Although it helps capturing stylus movements and system gestures, it is not clear how to make your own gestures.
Serge


text:
Q: HttpURLConnection .getInputStream() Crashes on Marshmallow not Oreo The following code works flawlessly on Android 8. On a tablet running 6 it crashes when getting the getinputstream with a file io error. I've tried for HOURS and HOURS without any luck. PLEASE help. Nothing works. Even trying a volley doesn't help. My Web API works great on a computer and a phone.
@Override
protected String doInBackground(String... args) {
    StringBuilder result = new StringBuilder();

    try {
        URL url = new URL("https://api.github.com/users/dmnugent80/repos");
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line;

        while ((line = reader.readLine()) != null) {
            result.append(line);
        }
    }
    catch(Exception e) {
        e.printStackTrace();
    }

    return result.toString();
}

LOG CAT HERE

06-24 02:01:21.813 22840-22890/com.marcusengineering.recipedatabase
  I/System.out: [CDS][DNS] getAllByNameImpl netId = 0 06-24 02:01:21.813
  22840-22890/com.marcusengineering.recipedatabase D/libc-netbsd:
  [getaddrinfo]: hostname=recipedatabase.gear.host; servname=(null);
  netid=0; mark=0
      [getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=4; ai_family=0 06-24 02:01:21.817
  22840-22890/com.marcusengineering.recipedatabase D/libc-netbsd:
  [getaddrinfo]: hostname=recipedatabase.gear.host; servname=(null);
  netid=0; mark=0 06-24 02:01:21.818
  22840-22890/com.marcusengineering.recipedatabase D/libc-netbsd:
  [getaddrinfo]: ai_addrlen=0; ai_canonname=(null); ai_flags=1024;
  ai_family=0 06-24 02:01:21.824
  22840-22890/com.marcusengineering.recipedatabase D/libc-netbsd:
  getaddrinfo: recipedatabase.gear.host get result from proxy gai_error
  = 0 06-24 02:01:21.824 22840-22890/com.marcusengineering.recipedatabase I/System.out: [CDS]rx
  timeout:0 06-24 02:01:21.826
  22840-22890/com.marcusengineering.recipedatabase I/System.out:
  [socket][0] connection
  recipedatabase.gear.host/204.246.56.80:80;LocalPort=43028(0)
      [CDS]connect[recipedatabase.gear.host/204.246.56.80:80] 06-24 02:01:21.826 22840-22890/com.marcusengineering.recipedatabase D/Posix:
  [Posix_connect Debug]Process com.marcusengineering.recipedatabase :80
  06-24 02:01:21.919 22840-22890/com.marcusengineering.recipedatabase
  I/System.out: [CDS]port[43028]
      [socket][/192.168.1.163:43028] connected 06-24 02:01:21.920 22840-22890/com.marcusengineering.recipedatabase I/System.out: [CDS]rx
  timeout:0
      [CDS]SO_SND_TIMEOUT:0 06-24 02:01:21.921 22840-22890/com.marcusengineering.recipedatabase I/System.out:
  [OkHttp] sendRequest>>
      [OkHttp] sendRequest<< 06-24 02:01:21.982 22840-22890/com.marcusengineering.recipedatabase W/System.err:
  java.io.FileNotFoundException:
  http://recipedatabase.gear.host/RestServiceImpl.svc/jsonfindtable/SELECT
  UnitID, UnitName, HiddenFlag FROM TblUnits ORDER BY UnitName FOR JSON
  PATH
          at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238)
          at com.marcusengineering.recipedatabase.MainActivity.getRestFromWebAsString(MainActivity.java:334)
          at com.marcusengineering.recipedatabase.MainActivity$MyAsyncInitialLoad.doInBackground(MainActivity.java:252)
          at com.marcusengineering.recipedatabase.MainActivity$MyAsyncInitialLoad.doInBackground(MainActivity.java:232)
          at android.os.AsyncTask$2.call(AsyncTask.java:295) 06-24 02:01:21.983 22840-22890/com.marcusengineering.recipedatabase
  W/System.err:     at
  java.util.concurrent.FutureTask.run(FutureTask.java:237)
          at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
          at java.lang.Thread.run(Thread.java:818)

A: FINNNNNNNALY FIGURED IT OUT!.
Not sure which ones were 100% needed but here's what I did to help any other poor souls.

*

*Ensure that your web api is fomratted without the extra wrapping added from WCF, i.e. is plain text. (not critical)

*Get rid of spaces in your URL. It appears OREO does this for you. Earlier versions must not. The code to do this is: URL url = new URL(query.replace(" ","%20"));

*Happy dance

In totality the call should be as follows:
            URL url = new URL(query.replace(" ","%20"));
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        int i = urlConnection.getResponseCode();
        InputStream inputs;
        if (i < HttpURLConnection.HTTP_BAD_REQUEST) {
            inputs = urlConnection.getInputStream();
        } else {
            // Error
            inputs = urlConnection.getErrorStream();
            return "-1";
        }

        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = "";

        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

To set the formatting to raw string in the WCF see the following.
In the *****.cs
[OperationContract]
    [WebGet( UriTemplate = "jsonFindTableBare/{id}")]
    Stream DoWork(string id);

In the svc.cs
public Stream DoWork(String id)
    {

        WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
        String str = "YOUR RESPONSE HERE";
        WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
        return new MemoryStream(Encoding.UTF8.GetBytes(str));
    }

Thanks for all the help, Mangal. Appreciate it.

A: You should first check response code to also handle the error input stream.
InputStream inputs;
if (urlConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
            inputs = urlConnection.getInputStream();
        } else {
            // Error
            inputs = urlConnection.getErrorStream();
        }

then call
   InputStream in = new BufferedInputStream(urlConnection);

I had also faced some app crashing experience because of handling error stream direclty.
Please do check always, It's a good practice.


text:
Q: Repeating Fields in Custom List During research and testing I came across some issues while trying to create repeating fields.
Intent: Create repeating fields in a custom list form
Problem: In the custom list I can create 5 columns asking for the same information but I don't like this way because my list will grow large with a lot columns.  I can create a InfoPath form but I do not want it in a form library because I don't want to item saved as a form.
Possible solutions:
Read in posts (that I don't understand) to

*

*If part of your content is repeating, consider flattening that schema
  so that it can repeat. For example, you could limit your book request
  form to no more than ten books per form.

*You can also use multiple
  lists and link them together using lookup fields and web part
  connections. This works well for master/detail scenarios where one
  list tracks all the items and another contains the specific details
  for each item.

2 above sounds good not sure how to do it.
Question:  Is there a way to create repeating fields in a custom list that will save into the list and not a InfoPath form? If using InfoPath will not give me that outcome, how can I do this just using SharePoint form?

A: SharePoint handles the concept of "repeating fields" through the use of "multi-item lookups" - in other words, create a Lookup Field and then check the box to "Allow Multiple Items". This gets your data schema "right".
From here, users can select as many items as necessary from the lookup list to add to the new item in your form - but they cannot create new items on the fly, and they will see ALL the records in the lookup list. You'll need to implement some sort of custom code solution (i.e. JSLink, popup window for entering new items, etc.) to streamline the UI further. There isn't anything OOB. I know my company has a product that provides similar functionality; there may be others as well.


text:
Q: help to calculate atan2 properly I need to calculate the angle between lines. I need to calculate atan. So I am using such code
static inline CGFloat angleBetweenLinesInRadians2(CGPoint line1Start, CGPoint line1End)
{
    CGFloat dx = 0, dy = 0;

    dx = line1End.x - line1Start.x;
    dy = line1End.y - line1Start.y;
    NSLog(@"\ndx = %f\ndy = %f", dx, dy);

    CGFloat rads = fabs(atan2(dy, dx));

    return rads;
}

But I can't get over 180 degrees(( After 179 deg going 178..160..150 and so on.
I need to rotate on 360 degrees. How can I do it? What's wrong?
maby this helps:
//Tells the receiver when one or more fingers associated with an event move within a view or window.
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSArray *Touches = [touches allObjects];
    UITouch *first = [Touches objectAtIndex:0];

    CGPoint b = [first previousLocationInView:[self imgView]]; //prewious position
    CGPoint c = [first locationInView:[self imgView]];          //current position

    CGFloat rad1 = angleBetweenLinesInRadians2(center, b);  //first angel
    CGFloat rad2 = angleBetweenLinesInRadians2(center, c);  //second angel

    CGFloat radAngle = fabs(rad2 - rad1);           //angel between two lines
    if (tempCount <= gradus)
    {
        [imgView setTransform: CGAffineTransformRotate([imgView transform], radAngle)];
        tempCount += radAngle;
    }

}

A: atan2 returns results in [-180,180] (or -pi, pi in radians).  To get results from 0,360 use:
float radians = atan2(dy, dx);
if (radians < 0) {
    radians += M_PI*2.0f;
}

It should be noted that it is typical to express rotations in [-pi,pi] and thusly you can just use the result of atan2 without worrying about the sign.

A: Remove the fabs call and simply make it:
CGFloat rads = atan2(dy, dx);

A: Use this function in Swift. This makes sure the angle from "fromPoint" to "toPoint" lands between 0 to <360 (not including 360). Please note, the following function assumes  that CGPointZero is at top left corner.
func getAngle(fromPoint: CGPoint, toPoint: CGPoint) -> CGFloat {
    let dx: CGFloat = fromPoint.x - toPoint.x
    let dy: CGFloat = fromPoint.y - toPoint.y
    let twoPi: CGFloat = 2 * CGFloat(M_PI)
    let radians: CGFloat = (atan2(dy, -dx) + twoPi) % twoPi
    return radians * 360 / twoPi
}

For the case where the origin is at the bottom left corner
let twoPi = 2 * Float(M_PI)
let radians = (atan2(-dy, -dx) + twoPi) % twoPi
let angle = radians * 360 / twoPi

A: Your problem is that the result of atan2 is between -180 and +180 degrees.
If you want it to be between 0 and 360 then move the result to sure be a positive value, and then do a modulo. For example:
let angle = fmod(atan2(dx,dy) + .pi * 2, .pi * 2)


text:
Q: How to wrap a text around an image using CSS Below is my code. I wished to wrap my text around the image. I used q {float: left; width: 100%}. However, the text appeared below the image.

  <q>TMNT is a fun, action-filled adventure that will satisfy longtime fans and generate a legion of new ones.</q>

Is there any other way to wrap my text around the image? Thank you!

A:

<q>TMNT is a fun, action-filled adventure that will satisfy longtime fans and generate a legion of new ones.</q>

A: Change the <q> display property to display:inline and remove the width property. That will align it next to the image

A: You actually need to float the image left. That will cause the behavior you want - having the text wrap around the image.

A: You can use span tages or use display:inline in your css:
Working demo
Hello!How are you!

A: You want to float the image not q

.review {width:100%;}
.review img {float:left; margin:7px; vertical-align:top;}

<q>TMNT is a fun, action-filled adventure that will satisfy longtime fans and generate a legion of new ones.</q>
  <q>TMNT is a fun, action-filled adventure that will satisfy longtime fans and generate a legion of new ones.</q>
  <q>TMNT is a fun, action-filled adventure that will satisfy longtime fans and generate a legion of new ones.</q>


text:
Q: Adding drag drop functionality in Vue Splitpanes I am trying to add Drag-drop functionality in Vue Splitpane. I was trying several drag-drop packages i.e. vue-smooth-dnd, Vue.Draggable, etc. But, those dnd packages were conflicting with the splitpane package as it strictly maintains the structure such as:
<splitpanes>
    <pane>
    </pane>
</splitpanes>

So, I was looking for options of adding drag-drop as directive to the element. I have found this, vue-draggable package and implemented it. Drag-drop is working now but it can't drag the splitpanes__splitter div after the <pane> element (div.splitpanes__pane). So, resizing option of the pane is not moving along the pane and that's why resizing option is not visible after every pane. How can make it work properly?
Codepen Demo

A: Due to how Vue works, I think you're going to really struggle getting those two components to place nice with one another.
You'll be much better off implementing your own drag+drop using the API, as in the long run, it'll be much quicker than trying, and inevitably failing, to mesh those two components together.


text:
Q: load a default url delphi i would like to load a default URL on form create event, i can load a url using a button click but i want it to load the URL when the app loads, when i run the program it wont load the url.
here is my code :
 unit launcher;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Imaging.pngimage, Vcl.ExtCtrls,
  Vcl.StdCtrls, Vcl.OleCtrls, SHDocVw;

type
  TForm1 = class(TForm)
    Image1: TImage;
    Button1: TButton;
    WebBrowser1: TWebBrowser;
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);

  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

 procedure TForm1.FormCreate(Sender: TObject);
  begin
 Webbrowser1.Navigate('http://www.digitalxeon.net');
 end;

procedure TForm1.Button1Click(Sender: TObject);
close;
end;

end.

A: What you report is not the whole story. Take the following steps:

*

*Create a new VCL forms project.

*Add a TWebBrowser component to the automatically generated form.

*Double click on the form to create an OnCreate event handler named FormCreate that is associated with the OnCreate event.

*Put your call to WebBrowser1.Navigate into the body of the FormCreate method.

*Run your application and observe that the browser control displays your page.

In other words, something else in your application is blocking this. Perhaps the OnCreate event handler is not assigned to FormCreate. Or perhaps something else is wrong. However, you can follow the steps above to prove to yourself that navigating from OnCreate works. Then all the remains is to diagnose where your application differs.
The bottom line is that calling Navigate from an OnCreate event is sufficient to show a web page on form startup.


text:
Q: Override interface type but keeping the shape with nested objects I have an interface I use to define the shape of a NoSQL document schema. This contains strings, arrays, nested objects, etc. For example, I have something like this:
interface IStudentSchema {
  name: string;
  age: string;
  foo: {
    a: number;
    b: [number, number];
    c: string;
  }
}

I want to create another interface which maintains the same shape, but the type of each values to be replaced by a certain interface (except when the type is object), For example, I want something like this below. Please note that it also maintains the original type, and uses it as a generic.
interface IStudentSchemaFieldInfo {
  name: ISchemaField<string>;
  age: ISchemaField<string>;
  foo: {
    a: ISchemaField<number>;
    b: ISchemaField<[number, number]>;
    c: ISchemaField<string>;
  }
}

Is there a way to do this so that I get a compile-time warning if I modify the original schema interface? So far, I had to manually keep them in sync.
I can almost do this there are no nested objects by using Record<keyof IStudentSchema, ISchemaField>, but this still also does not get the generics to be specified for the ISchemaField inteface. Any ideas?

A: If I understand the question correctly, you can do this by extending the child interface. I flipped the definition by the way, the Schema has the ISchemaField definition.
interface MysqlObject<T> {
  method<T>(): boolean;
}

type ISchemaField<T> = T | MysqlObject<T>;

interface IStudentSchema {
  name: ISchemaField<string>;
  age: ISchemaField<string>;
  foo: {
    a: ISchemaField<number>;
    b: ISchemaField<[number, number]>;
    c: ISchemaField<string>;
  }
}

interface IStudent extends IStudentSchema {
  name: string;
  age: string;
  foo: {
    a: number;
    b: [number, number];
    c: string;
  }
}

This maintains the shape of the base interface and will throw a compile-time error if it's changed.


text:
Q: bitmap to two dimensional array mapping error So I have one connection to a camera but I am pulling data at multiple locations in the code. By data I mean the current frame.
My plan is to display the 8 scale version on a (Aforge) videoSourcePlayer, so the user can zoom in and out and draw a box around the area they want, but then map that to a two dimensional array of 12 byte data.
I am having a problem with the mapping,  somehow when I draw the box on the videoSourcePlayer  the corresponding pixels location are not the same in the two dimensional array and I am not sure why.
Furthermore, when I do a zoom in, the x and y values became negative numbers and I do not know how to map that back to my two dimensional array.
Now this code works for I do everything as a bitmap:
 private Bitmap Andrew()
    {
        Bitmap tempBitmap = new Bitmap(videoSourcePlayer.Width, videoSourcePlayer.Height);
        Graphics.FromImage(tempBitmap);
        Graphics g = Graphics.FromImage(tempBitmap);
        Bitmap originalBmp = videoSourcePlayer.GetCurrentVideoFrame();
      while (originalBmp == null)
        {
            originalBmp = videoSourcePlayer.GetCurrentVideoFrame();
        }
        g.DrawImage(originalBmp, videoSourcePlayer.imagex, videoSourcePlayer.imagey, videoSourcePlayer.imgWidth, videoSourcePlayer.imgHeight);

        return tempBitmap;
    }

but when I try to do the two dimensional array my locations are off.
and again I do not know how to handle the negative numbers when it comes to zoom in and out .
here is my code :
    public double[,] GetSnapshot()
    {
        global_x = 0;
        global_y = 0;
        int rawImageSize = DetermineRawImageSize();
        byte[] temp = new byte[rawImageSize];

        float[] parameters = new float[1];
        parameters[0] = 1.5F;
        transfer.bits = new byte[getBufferSize()];
        FrameDescriptor frameDesc = new FrameDescriptor();
        //gets frame from camera
        ReturnCode rc = Api.GetNextFrame(m_hCamera, transfer.bits.Length, transfer.bits, ref frameDesc);
        int i4 = 0;
        int value2 = 0;
        global_y = (int)(videoSourcePlayer.imgHeight - videoSourcePlayer.imagey);
        global_x = (int)(videoSourcePlayer.imgWidth - videoSourcePlayer.imagex);
        double[,] returndata = new double[global_x, global_y];

        for (int x = (int)videoSourcePlayer.imagex; x < global_x; x++)
        {
          for (int y = (int)videoSourcePlayer.imagey; y < global_y; y++ )
            {
                int value = ((transfer.bits[i4] << 8) + transfer.bits[i4 + 1]);
                value2 = (value >> 4);
                returndata[x,y]= value2;
                i4 = i4 + 2;
            }
        }
        return returndata;
    }

but when I try and map it to the video player, so the user drawing a blue box on the video player and get the pixels locations of the box, the mapping are not matching up  :
    double zoomingetback(int i2)
    {
        double answer = 0D;
        double l = 0D;
        double tempD = 0D;
        double[,] data = GetSnapshot();

            for (int x = stIRList[i2].X; x <= endIRList[i2].X; x++)
            {
                for (int y = stIRList[i2].Y; y <= endIRList[i2].Y; y++)
                {
                tempD = data[x, y];
                answer = answer + tempD;
                    l++;
                }
            }

        answer = answer / l;
        return answer;

    }

can anyone help ?

A: That is a lot of code and without an example that is workable I can only offer a guess that might help.  It would be better if you could show how you are calling these methods and rather than a long explanation offer a working example.  But that aside:
I think you might be off on your initial assignment of global_x and global_y variables in the GetSnapshot method.  You mention that your coords end up being negative and I think you may need to rethink the assignment of
global_x = (int)(videoSourcePlayer.imgWidth - videoSourcePlayer.imagex);

I am not sure what you really want in global_x but later you are using it as a loop limit and with this assignment I don't see how it would ever come out positive.


text:
Q: one way sorted C++ node I'm trying to create one way node where inserted values are sorted. I tried do this like this, but i receive error on debuging. Please about help, its 's very important for me.
struct list {
int key;
list* next;
};

void add(list *&head, int key) {

list* tmp = new list;
tmp->key = key;

list* current = head;

if (current == NULL) {
    tmp->next = head;
    head = tmp;
    return;
}

while (current != NULL) {

    if (current->key == key) {
        cout << "Taki klucz juz istnieje" << endl;
        return;
    }
    cout << current->next << endl;

    if (key > current->key && current->next == NULL)  {
        cout << "---------" << endl;
            current->next = tmp;
            return;
    }
    if (key > current->key && current->next!=NULL && key < current->next->key) {
        list* currentNextCopy = current->next;
        current->next = tmp;
        tmp->next = currentNextCopy;
        return;
    }

    current = current->next;
}
    tmp->next = head;
    head = tmp;
}

int main()
{
srand(time(NULL));
list* head = NULL;
add(head, 2);
add(head, 4);
add(head, 3);
add(head, 1);
add(head, 5);

}

Maybe problem is very stupid, but I'm beginner at C++. Very please help.


text:
Q: How to run 'cfx xpi' after 'activate' via .bat? I'm trying to automatize installing of my addon. Mozilla says that it's very simple, but:

*

*I didn't find any while loops in .bat files or sleep for milisec.

*I can't understand, how to use activate.bat and cfx xpi in one CMD window sequentially, and also use wget in other CMD after all.

How can I do even if second part? I've tried something like:
START cmd /K "activate "cfx xpi"" && wget --post-file=tst-closing-cur-tab.xpi http://localhost:8888/
or
START cmd /K "activate && "cfx xpi"" && wget --post-file=tst-closing-cur-tab.xpi http://localhost:8888/
but it always run cfx in CMD, not in 'virtual CMD' after activate

A: I use this
call "c:\Firefox\Sdk\bin\activate.bat"
cd c:\dev-1.0.2.5-firefox\
cfx xpi


text:
Q: How to make arrays of same size in Python I would like to know is there an "easy" way to create two matching arrays inserting some dummy missing value in both arrays so they remain same size and indexes that are the same in both arrays remain the same, so for example:
["A", "B", "C", "D", "E", "F"] and ["B", "C", "E"]
Would be
["A", "B", "C", "D", "E", "F"] and ["N/A", "B", "C", "N/A", "E", "N/A"]
Thanks in advance :-)

A: One-liner in a list comprehension to do this:
array_1 = ["A", "B", "C", "D", "E", "F"]
array_2 = {"B", "C", "E"}

array_3 = [x if x in array_2 else "N/A" for x in array_1]

print(array_3)

result:
['N/A', 'B', 'C', 'N/A', 'E', 'N/A']

Note that I converted array_2 to a set for quicker lookup.

A: array_1 = ["A", "B", "C", "D", "E", "F"]
array_2 = ["B", "C", "E"]

array_3 = array_1

for n,x in enumerate(array_3):

    if x not in array_2:

        array_3[n] = np.nan

print (array_3)

out:
[nan, 'B', 'C', nan, 'E', nan]


text:
Q: How do I display recent News on silverstripe frontpage I am using the silverstripe/simple_news module from Arno Poot for my SilverStripe 3.5.3 CMS.
The news module works perfectly and news is saved and displayed normally. I am just not happy with the way it displays on the page.
I would like to put a news brief div on the front page with the last 10 news articles. But I have little documentation to go by. How would I get the last 10 news articles.
I also would like to create a sidebar on the news holder page listing the entire news archive in order / group links by:

---------------
| Year        |      Page Content listing of this month only
|   Month     |
|     Date    |
| Year        |
|  Month      |
|    Date     |
--------------

...etc. (pub date as dd-MM-yyyy)
I think the operation should be similar but since I am somewhat new at customizing SilverStripe, I have many questions yet.

A: Great question. Syndication of content is a really fundamental pattern in SilverStripe development, or really any content management system. A guiding principle of SilverStripe is that it would much rather empower you create exactly what you want by writing some code than give you 80% of what you want in some turnkey, out-of-the-box solution.
There's a lot written about this already. See https://docs.silverstripe.org/en/3/tutorials/extending_a_basic_site/#showing-the-latest-news-on-the-homepage.
What you'll want to do is create a method in your home page controller that returns a list of articles to your home page template.
public function RecentNews()
{
  return NewsArticle::get()->limit(5); // sort is already handled by default_sort
}

Then on the template:
<% loop $RecentNews %>
$Title / $Date / etc..
<% end_loop %>

Your second question about grouping them by year is a bit trickier. I did a tutorial on this a while back. Check out https://www.silverstripe.org/learn/lessons/beyond-the-orm-building-custom-sql?ref=hub
Needless to say, update all of those class names and field names to reflect the module you're using, e.g. ArticlePage -> NewsPage.


text:
Q: How to extract the value of last days from each year(1990-2011)? Question: Create a time series for every year with the sales volume listed for Apple (AAPL) on 31 December.
Screenshot of volume.csv data:

Screenshot of AAPL data only:

If the data does not contain a record for this date, then take the last known value that this known prior to that date.
My codes:
file = 'volume.csv'

apple = pd.read_csv(file)
apple_new = apple.drop(['AA', 'GE', 'IBM', 'JNJ', 'MSFT', 'PEP', 'SPX', 'XOM'], axis=1)

print(apple_new)

How to extract only "last days of the year" from each year(1990-2011)?

A: Once you have loaded the data into dataframe, create a column with only the year.
Assume your Date column is in date format. If not:
df['Date'] = pd.to_datetime(df['Date'])

Then create the year column:
df['year'] = df.Date.dt.year

Then extract all the records from df with drop_duplicates (keep=last). This will be the values you need.
dfX = df.drop_duplicates(['year'],keep='last')

This will give you the desired result (my data is from 1981 thru 2021):
            Date        AAPL
247   1981-12-31    0.098772
500   1982-12-31    0.133371
753   1983-12-30    0.108817
1006  1984-12-31    0.130022
1258  1985-12-31    0.098214
1511  1986-12-31    0.180804
1764  1987-12-31    0.375000
2017  1988-12-30    0.359375
2269  1989-12-29    0.314732
2522  1990-12-31    0.383929
2775  1991-12-31    0.503348
3029  1992-12-31    0.533482
3282  1993-12-31    0.261161
3534  1994-12-30    0.348214
3786  1995-12-29    0.284598
4040  1996-12-31    0.186384
4293  1997-12-31    0.117188
4545  1998-12-31    0.365513
4797  1999-12-31    0.917969
5049  2000-12-29    0.265625
5297  2001-12-31    0.391071
5549  2002-12-31    0.255893
5801  2003-12-31    0.381607
6053  2004-12-31    1.150000
6305  2005-12-30    2.567500
6556  2006-12-29    3.030000
6807  2007-12-31    7.074286
7060  2008-12-31    3.048214
7312  2009-12-31    7.526072
7564  2010-12-31   11.520000
7816  2011-12-30   14.464286
8066  2012-12-31   19.006071
8318  2013-12-31   20.036428
8570  2014-12-31   27.594999
8822  2015-12-31   26.315001
9074  2016-12-30   28.955000
9325  2017-12-29   42.307499
9576  2018-12-31   39.435001
9828  2019-12-31   73.412498
10081 2020-12-31  132.690002
10086 2021-01-08  132.050003


text:
Q: Powershell script to delete emails from mailbox older than an 7 month or specified dates I have problem with converting my Search-Mailbox command to another one. If you all know in the future as Search-Mailbox is retired. So I need to use another cmdlet for this command.
My working right now command with Search-Mailbox
Search-Mailbox -Identity test@test.comm -SearchQuery "(Received:01/12/2017..$((get-date).AddMonths(-7).ToString("MM/dd/yyy")))" -deletecontet

I read a lot of times https://docs.microsoft.com/en-us/exchange/policy-and-compliance/ediscovery/delete-messages?view=exchserver-2019#step-2-delete-the-message and try do step by step and get this code.
New-ComplianceSearch -Name "Remove older than 7 month messages" -ExchangeLocation test@test.com -ContentMatchQuery "(Received:01/12/2017..$((get-date).AddMonths(-7).ToString("MM/dd/yyy")))"

Start-ComplianceSearch -Identity "Remove older than 7 month messages"

New-ComplianceSearchAction -SearchName "Remove older than 7 month messages" -Purge -PurgeType SoftDelete

But its not work for me. getting error
Unable to execute the task. Reason: The search "Remove older than 8 month messages" is still running or it didn't

return any results. Please wait until the search finishes or edit the query and run the search again.

ADD my full PowerShell script
Start-Transcript

$smtpServer="smtp.office365.com" # Office 365 official smtp server
$from = "IT Support <test@test.com>" # email from
$logging = "Enabled" # Set to Disabled to Disable Logging
$testing = "Disabled" # Set to Disabled to Email Users
$testRecipient = "test@test.com"
$date = Get-Date -format ddMMyyyy

$Username = "test@test.com"
$Password = "test-" | ConvertTo-SecureString -AsPlainText -Force
$UserCredential = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$Password

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri  https://eur04b.ps.compliance.protection.outlook.com/powershell-liveid?PSVersion=5.1.17763.1007 -Credential $UserCredential -Authentication Basic –AllowRedirection

 Import-PSSession $Session

Get-ComplianceSearchAction
New-ComplianceSearch -Name "Remove older than 7 month messages" -ExchangeLocation test@test.com  -ContentMatchQuery "(Received:01/12/2017..$((get-date).AddMonths(-7).ToString("MM/dd/yyy")))"
Start-ComplianceSearch -Identity "Remove older than 7 month messages"
New-ComplianceSearchAction -SearchName "Remove older than 7 month messages" -Purge -PurgeType SoftDelete

A: I tested the compliance search in my lab environment,and I found that the search action(ComplianceSearchAction) couldn't be assigned to the search(ComplianceSearch) before the compliance search completed.
The following snapshot is my test result(After the status of the compliance search was changed from "Starting" to "Completed", the search action could be assigned to the search):

Therefore, if you create a compliance search and assign search action to it immediately(Use scripts to run these commands simultaneously), the "New-ComplianceSearchAction" command may not work.

A: Try:
New-ComplianceSearch -Name "Remove older than 7 month messages" -ExchangeLocation test@test.com -ContentMatchQuery "(Received >= 01/12/2017 -and Received <= $((get-date).AddMonths(-7).ToString("MM/dd/yyy")))"


text:
Q: How to check if the header contains the string "example@example.com"? I want to check if the From header contains the email address noreply@youtube.com:
if msg['From'] =='noreply@youtube.com':
  count+=1

This does not add one to the count because the header actually contains 'YouTube noreply@youtube.com'.
How can I adapt my code so it adds one to the counter, checking that it contains 'noreply@youtube.com' anywhere in the header?

A: Try using in.
>>> "noreply@youtube.com" in 'YouTube_noreply@youtube.com'
True


text:
Q: Scrambling words containing repeated letters If the goal was to find the number of different words that could be produced from scrambling a word that has different letters then that number would be n!,with n being the number of letters of that word.There is a way of finding that number in words where letters can be repeated.That way has to do with multiplying combinations using the "rule of product",or,in other words,dividing the permutations by a product of factorials.
Can anyone explain how that (the second) concept works,step-by-step?
Appreciate it!

A: Consider a word of length $n$, having $k$ distinct letters such that the first letter is repeated $r_1$ times, the second letter is repeated $r_2$ times, ....and the $k^{th}$ letter is repeated $r_k$ times.
First, we permute all $n$ letters. Then, notice that in any particular arrangement, shifting any of the repated letters among themselves wouldn't make a difference. In other words, corresponding to each of the $n!$ arrangements, there exist $(r_1) !$ identical arrangements due the the presence of the first letter, and so on for every letter. Thus, the total number of words will be $$\frac{n!}{\prod_{i=1}^k (r_i)!}$$


text:
Q: Heap has been corrupted In my main function I call inputHolding 5 times.  It goes through a couple loops and then it gives me an error saying the heap has been corrupted when it tries to read in the callNumber, usually on the third loop.  How do I fix this crash?
Holding* inputHolding() {
char selection;
char title[50];
int callNumber = 0;
char author[50];
char performer[50];
char format;

cout << "Enter B for book, R for recording: ";
cin >> selection;

if (selection == 'B') {
    cout << "Enter book title: ";
    cin >> title;

    cout << "Enter book author: ";
    cin >> author;

    cout << "Enter call number: ";
    cin >> callNumber;

    Book* muhbooksie = new Book(title, callNumber, author);
    return muhbooksie;
}
else  if (selection == 'R') {
    cout << "Enter recording title: ";
    cin >> title;

    cout << "Enter performer: ";
    cin >> performer;

    cout << "Enter format: (M)P3, (W)AV, (A)IFF: ";
    cin >> format;

    cout << "Enter call number: ";
    cin >> callNumber;

    Recording* muhbooksie = new Recording(title, callNumber, performer,     format);
    return muhbooksie;
}
else {
    cout << "Incorrect selection" << endl;
    return nullptr;
}
}

Book.cpp:
#include <iostream>
#include "Holding.h"
#include "Book.h"
#include "String.h"

using namespace std;

Book::Book() {

}

Book::Book(const Book& copy) : Holding(copy) {
author = new char[strlen(copy.author) + 1];

strcpy_s(author, sizeof(author), copy.author);
}

Book::Book(char* inputTitle, int inputCallNum, char* inputAuthor) : Holding(inputTitle,     inputCallNum) {
int len = strlen(inputAuthor) + 1;
author = new char[len];

strcpy_s(author, sizeof(author)*len, inputAuthor);
}

Book::~Book() {
delete [] author;
}

void Book::print() {
cout << "BOOK: " << author << " " << title << " " << callNumber << endl;
}

A: With everything said in the comment section of the question, you should (for the Book class):

*

*Overload the '=' operator,

*Implement the 'copy and swap' idiom,

*And initialize 'author' at nullptr in the default constructor and check the value in the destructor.

This way, your code will be cleaner and for example if the default constructor is used, the destructor will not delete an unspecified author.


text:
Q: How to upload a file to a specific folder in struts 2 I want to upload a file from a struts action. I need in that action the path for my folder:
I tried using
String contextPath = request.getContextPath();

but I'm getting java.lang.NullPointerException

A: Either store in Catalina which is parent folder to your project folder
      String rootPath = System.getProperty("catalina.home");
      File dir = new File(rootPath + File.separator + "yourfolderName");
      if (!dir.exists())
          dir.mkdirs();

      // Create the file on server
      java.util.Date date= new java.util.Date();
      String Path = dir.getAbsolutePath() + File.separator + (new Timestamp(date.getTime())).toString().replace(":", "").toString().replace(".", ".").toString().replace(" ","").toString().replace("-","").toString()+".pdf";

Or make a folder in your project and store there.
if (!file.isEmpty()) {
    //filter for checking file extewnsion
    if(file.getContentType().equalsIgnoreCase("image/jpg") || file.getContentType().equalsIgnoreCase("image/jpeg")){
        //if file is >2 MB or < 2MB
        double size = file.getSize();
        double kilobytes = (size / 1024);
        double megabytes = (kilobytes / 1024);
        if(megabytes<2){
    try {
        byte[] bytes = file.getBytes();
        String filePath = request.getRealPath("/")+"yourFolderName\\ProfileImages\\"+SessionManagement.getUserName()+".jpg";
        BufferedOutputStream stream =
                new BufferedOutputStream(new FileOutputStream(new File(filePath)));
        stream.write(bytes);
        stream.close();

        //console call
    }
    else{
        model.put("error", "Please select File less than 2 MB");
        return new ModelAndView("uploadPhotoTile");
    }
    }else{
        model.put("error", "Please select JPEG File");
        return new ModelAndView("uploadPhotoTile");
    }
} else {
    model.put("error", "Please select File");
    return new ModelAndView("uploadPhotoTile");
}


text:
Q: Notepad++ switch postions with regex Hello I need a help with my text which is like this

Text1|Text2|Text3|Text4|Text5|Text6|Text7|Text8|Text9|Text10

So the text need to change it to like this:

Text8|Text5|Text4|Text9|Text10|Text7

So change these texts postions and remove Text 1,2,3,6

A: With regex you can use capture groups to replace stuff. In your case it might look like
find
(Text1)\|(Text2)\|(Text3)\|(Text4)

replace
$2|$1|$4|$3

will result in
Text2|Text1|Text4|Text3

So just apply this technique to your longer string and it should work just fine. Assuming you know how to order the results.


text:
Q: jquery on('click', function()) triggering unexpectedly I am having a brain fart today or something, because when i set up an on('click') event it is firing like it has been clicked.
var myJsFunctions = {
    confirmDelete: function (index) {
        $('#deleteRecipient').modal('show');
        $('#confirmRecipientDeletion').on('click',myJsFunctions.deleteRecipient(index));
    },

    deleteRecipient: function (index) {
        $('#deleteRecipient').modal('hide');
        $('#recipientIsDeleted_' + index).val(true);
        $('#recipient_' + index).hide();
    }
}

but when i click the button that fires confirmDelete, it runs all the way through the myJsFunctions.deleteRecipient as well.

A: This happens because you actually invoking your function and you pass as a handler function execution result from return statement.
You should pass function handler instead:
$('#confirmRecipientDeletion').on('click', function() {
    myJsFunctions.deleteRecipient(index);
});

A: You have made the mistake in on click jquery syntax.
Change you code like this :
var myJsFunctions = {
confirmDelete: function (index) {
    $('#deleteRecipient').modal('show');
    $('#confirmRecipientDeletion').on('click',function(){
       myJsFunctions.deleteRecipient(index);
    });
},

deleteRecipient: function (index) {
    $('#deleteRecipient').modal('hide');
    $('#recipientIsDeleted_' + index).val(true);
    $('#recipient_' + index).hide();
}

}


text:
Q: Are there benefits to using a constexpr variable that is never intended to be used in a constant expression? This is a follow up question to this one.
From one of the answers in the question linked, it makes sense that the purpose of declaring a variable as constexpr is not truly to inform the compiler of the possibility of using that variable as a constant expression (although this is the end behavior of the compiler) but rather to convey to other programmers the intent that the variable can be used in a constant expression. My question is whether there is any benefit, performance or otherwise, to declaring a variable as constexpr if the variable is not intended to be used in a constant expression (e.g. a constant member variable of a class which only appears in non-constant expressions with other non-const member variables). Also assume that this is not for an embedded system.
I work with code where the previous developers seem to use constexpr like it's candy even when it's not clear that the intent is for the variable to be used in a constant expression (like in the example from the previous paragraph). I want to know if they knew something that I don't.

A:
but rather to convey to other programmers the intent that the variable can be used in a constant expression.

This is a matter of opinion but I beg to differ.
In principle, I think it is better to make everything that can be known and computed at compile time a constexpr. The fact that it can also be used in constant expressions is a side benefit. Use of constexpr may have performance related benefits too.
The key point I want to make is that "the value is known at compile time" is a characteristic of the variable/data. It is better to capture that characteristic by using a language provided feature. The only time one could justify not using it will be if there are any adverse side effects.

A: Yes, constexpr variables are useful for more than just conveying intent and using in other constant expressions.
If you mark a variable constexpr, the compiler will enforce that it itself is initialized with a constant expression.  You can use this to make sure that the things you expect to be evaluated at compile time actually are.  For example:
constexpr int constexpr_function() { return 123; }
int expensive_runtime_function() { return 123; }

void f()
{
    constexpr int good1 = constexpr_function(); // OK.
    // constexpr int good2 = expensive_runtime_function(); // Good: error.

    const int bad1 = constexpr_function(); // OK.
    const int bad2 = expensive_runtime_function(); // Bad: unexpected runtime cost.
}


text:
Q: How to remove the path with an nginx proxy_pass in http and https? I have read the similar issue below but got a problem that will explain later in the question:

*

*How to remove the path with an nginx proxy_pass
I have a config like below that proxy_pass to an upstream:
location /api2/ {
    client_max_body_size 10m;

    if ($scheme = 'https') {
        proxy_pass https://api.example.com;
    }

    if ($scheme = 'http') {
        proxy_pass http://api.example.com;
    }

    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
}

Here the api2 section is sent to the upstream. In the question I've linked above uses / at the end of proxy_pass to omit the api2 part. When I add the / at the end of proxy_pass I get the below error:
nginx: [emerg] "proxy_pass" cannot have URI part in location given by regular expression, or inside named location, or inside "if" statement, or inside "limit_except" block in /etc/nginx/sites-enabled/mysite:160

When I searched for the above error, the community says that you need to remove / in proxy_pass to solve the error.
So the question is why I'm getting api2 in the upstream? How should I remove api2 when proxying?
When I change the config to:
location /api2/ {
    client_max_body_size 10m;

    proxy_pass http://api.example.com/;

    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
}

It works, but the https requests have problem sending request.
In the upstream section I get the below error:
GET //api2/my_endpoint HTTP/1.1" 404

A: Well, the thing is that proxy_pass when you don't explicitly specify the URI you are proxying to, doesn't touch it too. At all. So you get the exact input URI, e.g. /api2/.
If you need to tamper with URI while proxying it, you need to use rewrite directive. The most simple solution would be doing something like this inside your location clause:
rewrite ^/api2/(.*) /$1 break;

Also not that proxying to the same URL but with two different schemes look redundant. I'd say that you should either terminate TLS on your proxy, or, if the intermediate transport is the subject of compromising, get rid of the plain HTTP.


text:
Q: Adding paging to and ASP ListView working with VB I'm trying to set up paging for a site I'm working on, I'm using a list view. I've done a lot of reading but nothing seems to make sense to me. below is the type of code query I am doing, I'm working in VB and oracle:
<ItemTemplate>

<%#Eval("lead_name")%>

<%# Eval("leadcode")%>

EMAILS
                    <asp:Image ID="EmailsTickCross" runat="server" ImageUrl="/Images/Layout/Tick.jpg" />

CALLS
                    <asp:Image ID="CallsTickCross" runat="server" ImageUrl="/Images/Layout/Cross.jpg" />

POSTAL
                    <asp:Image ID="PostalTickCross" runat="server" ImageUrl="/Images/Layout/Tick.jpg" />

LATEST INSIGHT VISIT:

<%# CType(Eval("last_insight"), Date).ToString("dd-MMM-yy")%>

                <asp:Button ID="ActiveProfileBtn" CommandArgument='<%# Eval("leadcode")%>' runat="server" Text="VIEW PROFILE" CssClass="viewProfile right" />

LATEST HPB ACTIVITY:

NA

NOTES:

<%# GetNotes(Eval("leadcode"))%>

</ItemTemplate>

VB:
        Dim DT As New DataTable
        Dim oCnn As New OracleConnection(OracleConnectionString)
        Dim da As New OracleDataAdapter("select * from web_table", oCnn)
        Try
            oCnn.Open()
            da.Fill(DT)
        Catch ex As Exception
        Finally
            oCnn.Close()
        End Try

        ActiveLeadsListView.DataSource = DT
        ActiveLeadsListView.DataBind()

Any help with this would be great, I'm really stuck with this one. There are around 20000 rows so I definitely need paging.


text:
Q: How to deal with a covariance of base pointers, casting from derived to base class for using methods of containers I have the following classes:
class base{};
class derived1:public base{};
class derived2:public base{};

I also have an implemented container pool to which I have no editing access. In each of the 3 .h files, I define the following pool respectively:
typedef pool<base> basesPool;
typedef pool<base> derived1Pool;
typedef pool<base> derived2Pool;

At some point in the flow, I am getting an object out of the pool, and assigning it to a general pointer of type base with respect to a flag:
derived1Pool d1pool;
derived1Pool d2pool;
base* element;

if(flag){
  d1pool = new derived1Pool();
  element = d1pool ->alloc();
}
else{
  d2pool = new derived2Pool();
  element = d2pool ->alloc();
}

Later on, I am trying to clean using the following code:
if(flag){
  d1pool->free(element);
}
else{
  d2pool->free(element);
}

I am getting an error due to a covariance problem:

error: no matching function for call to
'pool<derived1Pool>::free(base*&)'

An easy solution would be to define two pointers. I am trying to avoid this. Is there an elegant option to convert from the base pointer to the derived pointer? I have seen this post and tried all variations of dynamic_casting I could think of to no avail.

A: The issue you have is that you cannot cast (dynamically or otherwise) a non-lvalue base class pointer to a non-const reference to a pointer to a derived class, which is what is required as the argument to your free calls.
As you have stated that you cannot change the pool class definition (or its free member function's argument type), you could get round this by creating local (to the if and else blocks) pointers of the correct type, initialize them by dynamically casting the element pointer, and use those as the arguments to the free calls:
if(flag){
    derived1* d1p = dynamic_cast<derived1*>(element);
    d1pool->free(d1p);
    element = d1p; // See note below
}
else{
    derived2* d2p = dynamic_cast<derived2*>(element);
    d2pool->free(d2p);
    element = d2p; // See note below
}

Note: The reason why I have included the assignments back to element after each call is that it is likely that the free function modifies its given pointer (probably setting it to nullptr, but I can't be sure). So, we need to manually propagate that change, because we have passed local/temporary pointers and the free function's changes will only apply to those.


text:
Q: How can I make basket icon responsive for mobile in Navbar? I want to make navbar responsive and the only thing I can't fix it is basket icon which always moves to the sides depends on size of the screen, how can I make it in the middle position does not matter what size of the screen?

Here is css code:
/* Nav Bar Styling */

a {
  text-decoration: none;
}
li {
  list-style-type: none;
}
.navbar {
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 70px;
  box-shadow: rgba(50, 50, 93, 0.23) 0px 30px 30px -20px;
  /* max-width: 100vw;
  overflow: hidden; */
}
.logo {
  font-size: 30px;
}
.nav-links {
  display: flex;
  justify-content: flex-end;
  width: 75%;
  margin: 30px;
}

.nav-links li {
  color: black;
  font-size: 20px;
  padding: 10px 20px;
  margin: 10px;
  cursor: pointer;
  text-transform: capitalize;
}
.hero {
  text-align: center;
  margin-top: 15%;
}
.hero h1 {
  text-align: center;
  font-size: 80px;
}
.mobile-menu-icon {
  display: none;
}
button {
  border: none;
  text-decoration: none;
  font-size: 20px;
  background: none;
}
/* Creating a circle with number of items */
.num-items {
  color: #fff;
  width: 1.5rem;
  height: 1.5rem;
  position: absolute;
  bottom: 0;
  right: 18px;
  /* transform: translate(-425%, -2095%); */
  border-radius: 50%;
  background-color: red;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* basket */
#basket {
  background-color: #fff;
  width: 2rem;
  height: 2rem;
  position: relative;
  border: none;
  border-radius: 50%;
  outline: none;
  color: #4d77ff;
  margin: 10px 30px;
}

.basket {
  margin-top: 10px;
  position: relative;
}

/* =======Mobile====== */
@media (max-width: 768px) {
  .logo {
    display: flex;
    position: absolute;
    top: 15px;
    left: 35px;
  }
  .nav-links {
    display: none;
  }
  .nav-links-mobile {
    position: absolute;
    display: flex;
    flex-direction: column;
    list-style: none;
    box-shadow: rgba(50, 50, 93, 0.23) 0px 50px 100px -20px;
    top: 10%;
    transition: all 0.5s ease-in-out;
    width: 100%;
    background-color: white;
    padding-bottom: 50px;
    z-index: 10;
  }
  ul li {
    padding: 52px;
    width: 100%;
    transition: all 0.5s ease-in-out;
    text-align: center;
    color: var(--secondary-dark-color);
  }
  .mobile-menu-icon {
    position: absolute;
    display: block;
    /* justify-content: center; */
    right: 20px;
  }
  .hero h1 {
    font-size: 50px;
  }
  .basket {
    position: relative;
    display: block;
    top: 70%;
    transition: all 0.5s ease-in-out;
    width: 50px;
    margin-left: 320px;
  }

  .num-items {
    right: -20px;
  }
}

@media (max-width: 700px) {
  .basket {
    margin-left: 290px;
  }
  .num-items {
    right: -20px;
  }
}
@media (max-width: 570px) {
  .basket {
    margin-left: 100px;
  }
  .num-items {
    right: -20px;
  }
}

And here JS code:
import React, { useState } from "react";
import { Link } from "react-router-dom";
import { useSelector } from "react-redux";
import { AiOutlineUser } from "react-icons/ai";
import { BsFillCartFill } from "react-icons/bs";
import { FaBars } from "react-icons/fa";
import { ImCross } from "react-icons/im";
import "./styles/Navbar.css";

function Navbar() {
  const [mobile, setMobile] = useState(false);

  const state = useSelector((state) => state.basketReducer);

  return (
    <>

Logo

 setMobile(false)}
        >
          <Link to="/" className="home">

Home

          </Link>
          <Link to="/products" className="about">

All Clothing

          </Link>
          <Link to="/signup" className="signup">

Sign Up

          </Link>

            <Link to="/basket">
              <BsFillCartFill id="basket" />

{state.length}

            </Link>

        <button className="mobile-menu-icon" onClick={() => setMobile(!mobile)}>
          {mobile ? <ImCross /> : <FaBars />}
        </button>

    </>
  );
}

export default Navbar;

I tried to write media queries for different sizes of screen but it is just 10px less and basket again in wrong position. Maybe

A: Just add this CSS code to keep it centered on mobile devices.
.basket {
  position: relative;
  display: table;
  top: 70%;
  transition: all 0.5s ease-in-out;
  width: 50px;
  margin:0 auto;
}


text:
Q: Is it possible to join two entities with panache? I want to get two values from two different sql tables.
In sql we would do "Select a.value, b.value from A a inner join B b on a.id = b.id where ..."
Is it possible to do it with panache? Like join two entities or something like that?
Can't really find much about joins with quarkus panache.

A: Panache doesn't have any specific way to deal with joins.
You can still load specific fields using HQL and projections:
List<EntitiesView> results = EntityA
    .find("Select a.value, b.value from A a inner join B b on a.id = b.id where ...")
    .project(EntitiesView.class)
    .list();

Where EntitiesView is:
@RegisterForReflection
class EntitiesView {
   public final Object valueA;
   public final Object valueB;

   public EntitiesView(Object valueA, Object valueB) {
       this.valueA = valueA;
       this.valueB = valueB;
   }
}

You can find more details about projections on the Panache guide.


text:
Q: Test exceptions using espec in Elixir app I'm just started to learn Elixir.
I'm trying to test exception with espec (https://github.com/antonmi/espec) and I stucked.
Here is my function
defp call_xml(request_body) do
 resp = HTTPotion.post("http://foo.bar", [body: request_body, headers: ["Content-Type": "text/xml"]])
 if resp.status_code in [200, 201] do
  {:ok, elem(XMLRPC.decode(resp.body), 1).param}
 else
  raise AbpError, message: "Message body"
 end
end

def create_some_stuff(a, b, c) do
 req = %XMLRPC.MethodCall{method_name: "Foo.Bar",
                          params:[a, b, c]} |> XMLPRC.encode!
 call_xml(req)
end

# tests

use ESpec
use HyperMock
import :meck

context "when exception rised" do
 it "returns err message" do
   # stubbed with :meck
   expect(MyModule, : create_some_stuff, fn("foo", "bar", "baz") -> raise CustomError end)
   expect(MyModule. create_some_stuff("foo", "bar", "baz")).to eq("???")
 end # it
end

In that case I'm getting error raised in my expectation
    ** (AbpError) Error occured!
spec/lib/ex_abpclient_spec.exs:135: anonymous fn/7 in ExAbpclientSpec.example_returns_created_payback_eqcpjlrszudikwyovtmxbgfnha/1
(ex_abpclient) ExAbpclient.create_payment_payback("tr-TR", 10966, 10, "R", 495, 10, "DESC")
spec/lib/ex_abpclient_spec.exs:136: ExAbpclientSpec.example_returns_created_payback_eqcpjlrszudikwyovtmxbgfnha/1
(espec) lib/espec/example_runner.ex:33: ESpec.ExampleRunner.run_example/2
(elixir) lib/enum.ex:1088: Enum."-map/2-lists^map/1-0-"/2
(elixir) lib/enum.ex:1088: Enum."-map/2-lists^map/1-0-"/2
(espec) lib/espec/runner.ex:70: ESpec.Runner.run_examples/1
(espec) lib/espec/runner.ex:43: ESpec.Runner.do_run/2

How can I get stubbed exception?
Thanks in advance.
UPDATE
I tried to use HyperMock (https://github.com/stevegraham/hypermock) to stub the request, but with no luck too
context "when payback created" do
  it "returns created payback" do
    HyperMock.intercept do
      request = %Request{body: "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodCall>.....",
                         headers: ["Content-Type": "text/xml"],
                         method: :post,
                         uri: "http://foo.bar/webApiXmlRpcServlet"}
      response = %Response{body: "fooooo", status: 500}
      stub_request request, response
      expect MyModule.create_some_stuff("a", "b", "c") |> to(raise_exception AbpError, "fooooo")
    end
  end # it
end # exception

Here is the result
/Users/retgoat/workspace/offside/ex_abpclient/spec/lib/ex_abpclient_spec.exs:135
** (AbpError) Error: "fooooo"
(ex_abpclient) lib/ex_abpclient.ex:55: ExAbpclient.call_xml/1
spec/lib/ex_abpclient_spec.exs:143: ExAbpclientSpec.example_returns_created_payback_nqfwohpurlvtzskdjxigeybamc/1
(espec) lib/espec/example_runner.ex:33: ESpec.ExampleRunner.run_example/2
(elixir) lib/enum.ex:1088: Enum."-map/2-lists^map/1-0-"/2
(elixir) lib/enum.ex:1088: Enum."-map/2-lists^map/1-0-"/2
(espec) lib/espec/runner.ex:70: ESpec.Runner.run_examples/1
(espec) lib/espec/runner.ex:43: ESpec.Runner.do_run/2
(espec) lib/espec/runner.ex:28: ESpec.Runner.handle_call/3

10 examples, 1 failures

Finished in 1.28 seconds (0.14s on load, 1.14s on specs)

Exception is rised, but I can't test it.

A: Roman!
You must pass a function to expect, not a result of a function call.
So, just wrap MyModule.create_some_stuff("a", "b", "c") by fn -> end like you do in the ExUnit expample:
elixir
it "raises exception" do
  expect(fn -> MyModule.create_some_stuff("a", "b", "c") end)
  |> to(raise_exception AbpError, "fooooo")
end


text:
Q: Intercept BIG application execution after DLL injection I must intercept execution in very big application in many places.
What programs I can use to do this? What techniques exists for this problems?
Manually reverse engineering and adding hooks is maybe not optimal solution for this problem, because application is very big and some part of application can be updated in some time, i think with some tools or good practices for this problem i can do this faster, anyone know how to do?
Anybody help me?

A: seeing as the tools part has been covered, here is something for the techniques.
Depending what it is you need to hook and whether or not there is protection invloved, there are a few methods:

*

*Relative call/jmp patching in the virtualized binary: this is the simplest, but also a lot of work if you can't automatically find all references to a function, this probably won't work in this cause due to your criteria.

*IAT/EAT hooking: this is use for imports(IAT) and exports(EAT), great if your targeting a known importted/exported set of API functions. a good example of this can be found here or here

*Hot-Patching: Windows XP SP2 introduced something called "hot-patching" (used for realtime system function updates), where all its (the WinAPI) functions start with a 'mov edi,edi', allowing a relative jump to be patched into the free space created above every hot-patchable function(one can do it too). this is generally used for programs that checksum there IAT's or have other funny forms of protection, more info can be found here and here

*Code-Caving: capturing execution flow by placing redirections in arbitrary code space. see here, here or here

*VFT/COM Redirection: basically overwriting entries in a objects virtual function table, useful for OOP/COM based applications. see this
There are a lot of 3rd party libraries, most famous would probably be MS Detours, one can also look at APIHijack or a mini-hook engine.
Ofcourse nothing can substitute for the initial poking you'll need to do with a debugger like ollydbg, but knowing the method your gonna use can drastically short them amount time time spent poking around

A: Some details on what exactly you need to do (e.g. how do you determine where to break) would be nice. Depending on your situation, something like Pin might work.

A: I suggest using Deviare API Hook. It's the easiest way you can do what you need. It has some COM objects that you can use to hook an application from a different process. In your process you get full parameter information and you can use it in any programming language (I'm using C# and it works like a charm).
If you need to intercept registry API I suggest using Deviare to debug what you need to intercept but then you will have to make your own hooks, otherwise, you'll find performance issues.

A: You can do API Hooking if you are interested in intercepting method calls.
Or use some disassembler like softice or ollydbg or win32dasm.


text:
Q: $|z_1-z_2|\le|1-z_1\overline{z_2}|$? Is the following inequality true?
Let $z_1,z_2\in \mathbb{C}$ such that $|z_1|=1,|z_2|=1$. Then $$|z_1-z_2|\le|1-z_1\overline{z_2}|.$$ Is there a good way to try to prove(or disprove) this other than writing $z_1=a+bi$ and $z_2=c+di$ and try to see whether the inequality hold?

A: Observe
\begin{align}
|z_1-z_2| = |z_2||z_1z_2^{-1}-1|
\end{align}
but $z_2^{-1} = \bar z_2$ since $|z_2|=1$.


text:
Q: Override Devise Invitable `invite!` method in order to add attachment to invitation email - Rails I have devise_invitable gem and an invitations controller InvitationsController < Devise::InvitationsController. I invite my user with this method User.invite!(user, inviter) from the gem.
Now, I would like to add pdf attachment to this invitation but I am not able to override the mailer method in order to do stuff like this: attachments['terms.pdf'] = File.read('/path/terms.pdf').
My invitation email is working fine and I would like to keep it like that but with an attachment.
Here my routes.rb:
devise_for :users, controllers: { invitations: 'api/v1/users/invitations' }

What am I missing?
Thanks

A: DeviseInvitable has a usefull skip_invitation option.
With the following method you can easily use your own mailer and add attachment in it :
def invite_and_notify_user(email)
  user = User.invite!({ email: email }) do |u|
    u.skip_invitation = true
  end
  notify_by_email(user)
end

def notify_by_email(user)
  MyUserMailer.invited_user_email(user).deliver
end

In MyUserMailer class:
  def invited_user_email(user)
    @user = user
    attachments['terms.pdf'] = File.read('/path/terms.pdf')
    mail(to: user.email, from: 'contact@mail.com', subject: "Your subject")
  end

A: You can override the devise mailer like so...
class MyMailer < Devise::Mailer
  helper :application # gives access to all helpers defined within `application_helper`.
  include Devise::Controllers::UrlHelpers # Optional. eg. `confirmation_url`
  default template_path: 'devise/mailer' # to make sure that your mailer uses the devise views
  # If there is an object in your application that returns a contact email, you can use it as follows
  # Note that Devise passes a Devise::Mailer object to your proc, hence the parameter throwaway (*).
  default from: ->(*) { Class.instance.email_address }
end

You can then  in your config/initializers/devise.rb, set config.mailer to "MyMailer". Note that this overrides the mailer used for all devise modules.
Then in that class add your attachment to invited_user_instructions...
def invited_user_instructions(*args)
  attachments['terms.pdf'] = File.read('/path/terms/pdf')
  super
end

This is devise's instructions https://github.com/heartcombo/devise/wiki/How-To:-Use-custom-mailer