text:
Q: delphi Activex and parented forms error i try to fix up my activex project and i had errors , i have 2 forms in my activex project first form hold tmemo and button to call second form as parented form every thing works fine till now but i cannot set any record from second form to first form control always get access violation so i decided to show result before set tmemo.text control in the first form and actually result is showing but but cannot be set into the first form here is my project code
unit main1;

{$WARN SYMBOL_PLATFORM OFF}

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  ActiveX, AxCtrls, embed_TLB, StdVcl, Vcl.StdCtrls;

type
  Tform1 = class(TForm, Iform1)
    Button1: TButton;
    Memo1: TMemo;
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }

  protected
    { Protected declarations }

  public
    { Public declarations }
    procedure showEmo(L,T:Integer);

  end;

  var
  Form1 : Tform1;

implementation

uses ComObj, ComServ, main2;

{$R *.DFM}

{ Tform1 }

procedure Tform1.Button1Click(Sender: TObject);
var
  Rect: TRect;
begin
  GetWindowRect(Self.button1.Handle, Rect);
  showEmo(Rect.Left + 70,(Rect.Top - 290));
end;

procedure Tform1.FormCreate(Sender: TObject);
begin
  Form2 := TForm2.Createparented(0);
end;

procedure TForm1.showEmo(L,T:Integer);
var
  Rect: TRect;
begin
  try
    GetWindowRect(button1.Handle, Rect);
    begin
      Form2.FormStyle := fsStayOnTop;
    end;
    Form2.Left := L;//Rect.Left;
    Form2.top := T;//Rect.Top - emo.Height;
  finally
    Form2.Visible := not (Form2.visible);
  end;

end;

initialization
  TActiveFormFactory.Create(
    ComServer,
    TActiveFormControl,
    Tform1,
    Class_form1,
    0,
    '',
    OLEMISC_SIMPLEFRAME or OLEMISC_ACTSLIKELABEL,
    tmApartment);
end.

Form 2
unit main2;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.OleCtrls, SHDocVw_EWB, EwbCore,
  EmbeddedWB, MSHTML_EWB, Vcl.StdCtrls;

type
  TForm2 = class(TForm)
    ewbpage: TEmbeddedWB;
    load: TMemo;
    procedure FormCreate(Sender: TObject);
    procedure ewbpageBeforeNavigate2(ASender: TObject; const pDisp: IDispatch;
      var URL, Flags, TargetFrameName, PostData, Headers: OleVariant;
      var Cancel: WordBool);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form2: TForm2;

implementation

uses main1;

{$R *.dfm}

procedure TForm2.ewbpageBeforeNavigate2(ASender: TObject; const pDisp: IDispatch;
  var URL, Flags, TargetFrameName, PostData, Headers: OleVariant;
  var Cancel: WordBool);
  var
  MousePos: TPoint;
  HtmlElement: IHTMLElement;
  iHTMLDoc: IHtmlDocument2;
begin
  if Pos('#sm',URL)>0 then
  begin
    if Supports(ewbpage.Document, IHtmlDocument2, iHTMLDoc) then
    begin
      if GetCursorPos(MousePos) then
      begin
        MousePos := ewbpage.ScreenToClient(MousePos);
        HtmlElement := iHTMLDoc.ElementFromPoint(MousePos.X, MousePos.Y);
        if Assigned(HtmlElement) then
          showmessage(HtmlElement.getAttribute('id', 0));
        form1.Memo1.Text :=  HtmlElement.getAttribute('id', 0);
        Cancel := True;
        Self.Close;
      end;
    end;
  end;
end;

procedure TForm2.FormCreate(Sender: TObject);
begin
  ewbpage.LoadFromStrings(load.Lines);
end;

end.

and the question is why i get this error

Access violation at address 07C734FC in module 'EMBEDA~1.OCX'. Read of
  address 000003B4.

at this line
form1.Memo1.Text :=  HtmlElement.getAttribute('id', 0);

why i cannot set result from second form to first form ? what i did wrong here is the full project for better understand
http://www.mediafire.com/download/zn7hzoxze2390a3/embeddedactivex.zip

A: You will see this issue once you start to format your code properly
procedure TForm2.ewbpageBeforeNavigate2(ASender: TObject; const pDisp: IDispatch;
  var URL, Flags, TargetFrameName, PostData, Headers: OleVariant;
  var Cancel: WordBool);
  var
  MousePos: TPoint;
  HtmlElement: IHTMLElement;
  iHTMLDoc: IHtmlDocument2;
begin
  if Pos('#sm',URL)>0 then
  begin
    if Supports(ewbpage.Document, IHtmlDocument2, iHTMLDoc) then
    begin
      if GetCursorPos(MousePos) then
      begin
        MousePos := ewbpage.ScreenToClient(MousePos);
        HtmlElement := iHTMLDoc.ElementFromPoint(MousePos.X, MousePos.Y);

        // if we have a valid HtmlElement ...
        if Assigned(HtmlElement)
        then // show a message
          showmessage(HtmlElement.getAttribute('id', 0));

        // now we do not care about if HtmlElement is valid or not
        form1.Memo1.Text :=  HtmlElement.getAttribute('id', 0);

        Cancel := True;
        Self.Close;
      end;
    end;
  end;
end;

To only solve your current access violation you simply put a begin end block around all the lines that will use HtmlElement.
        HtmlElement := iHTMLDoc.ElementFromPoint( MousePos.X, MousePos.Y );

        if Assigned( HtmlElement )
        then
          begin
            showmessage( HtmlElement.getAttribute( 'id', 0 ) );
            form1.Memo1.Text := HtmlElement.getAttribute( 'id', 0 );
          end;

But there are some more issues in your code. You should not use the global variables form1 and form2. Instead pass the form instance to the created TForm2 instance or even better a callback method.


text:
Q: How to return the current page url inside a wagtail app's model.py file I have a wagtail app in which I need to return the current page's url. The code for my model.py of my app is as follows
import urllib

from django.conf import settings
from django.db import models

from wagtail.core.models import Page
from django.http import HttpResponse

class PageUrl(Page):
    def returnPageUrl(self):
        page_url = """ i need the page url here """
        return page_url

A: A Page model has a field url_path. You thus can access the page URL with:
class PageUrl(Page):

    def returnPageUrl(self):
        return self.url_path
or you can make use of full_url to obtain the full url (including the hostname, etc.):
class PageUrl(Page):

    def returnPageUrl(self):
        return self.full_url
That being said, since it is already a field, I think there is not much use to define an extra method for this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get terminal access to a php/AngularJS app deployed using opsWorks Background: I have a php backend application (cakephp with dependencies resolved with composer), and javascript front end (AngularJS, using bower for dependency management), with the repository on bitbucket.
I was able to successfully deploy it using opsworks.
Problems:

*

*I need terminal access to the app layer to run shell commands such as composer install, bower install. How do I do this?

*Is it better to do a manual deployment (set up the ec2 instanstances mmanually and ssh into the VM) instead of using opsWorks?

*Generally what would be the best approach to deploy such an application?

Thankyou and apologies if my question has issues.

A: *

*This is basically missing the main point of OpsWorks (and configuration management in general). You should be using OpsWorks to do these things for you. http://docs.aws.amazon.com/opsworks/latest/userguide/customizing.html

*This is an opinion issue and depends mostly on you and your application.

*This is an opinion issue and depends mostly on you and your application.

A: You should be writing chef deployment recipes to do this!
Currently it is easier to get set up using s3 without opsworks however opsworks is more scalable and gives you a warm fuzzy feeling when your recipies automate deployment flawlessly! [citation needed]
You can still SSH into your instances much like you'd connect to an s3 instance. In Opsworks go to instances -> SSH and follow instructions, something like this
ssh -i ~/.ssh/aws-test.pem ubuntu@xx.xxx.xxx.xxx

EDIT:I explained that SSHing into opsworks boxes is usually a bad idea.


text:
Q: Unable to generate JNI .c file using javah -stubs I am trying to generate JNI code from my Java class.
I was able to generate the header without a problem using javah
Whenever I run javah with the -stubs command I get this error:

Error: JNI does not require stubs, please refer to the JNI documentation.

Does anyone know if there is a way to generate a JNI .c file for a class.
I can make the file from my header by hand, but it seems like something a tool should be able to do.
I found an unresolved bug request about this from 2000 so I'm not too hopeful.
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4368114

A: -stubs is a leftover from a long-obsolete first cut at JNI. It never generated anything useful for any version of Java used in the current century.
Just copy the header file into your .c file and add a function body to each function.
Or perhaps have a look at http://jna.java.net/.


text:
Q: How to open IE8 with factory settings? Is it possible to open IE8 with factory settings without actually resetting the settings? There is a way to disable plugin using iexplore.ext -extoff. Most of the linux programs allow some means to load the program without loading the settings.

A: While Internet Explorer supports several command-line options, there is not one that loads it using factory settings.  (An older blog post from the IE Dev team blog discusses the reset settings feature, but doesn't mention a way to do so temporarily.)
As far as -extoff goes, I'm not sure what you're asking.  By definition, it disables all plugins.  It doesn't provide a way to selectively disable individual plugins. (You have to do that manually.)
(I have noticed that some addons become more manageable if you uninstall them and re-install them, but that's anectodal at best.)
If there's a specific add-on you're having trouble with, it might be possible to provide more specific advice.
Hope this helps...
-- Lance


text:
Q: How else can I get my geolocation coordinates? This is how I get my latitude and longtitude.
Criteria criteria = new Criteria();
            LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            String provider = locationManager.NETWORK_PROVIDER;
            Location location = locationManager.getLastKnownLocation(provider);
            if(location==null)
            {
            //do nothing
            }else
            {
       double      longitude = location.getLongitude();
       double         latitude = location.getLatitude();
       saveCoordinates(location); // there goes another method

            }

here's list of permissions
on my device everything works ok, but on other devices (like tablets) this doesn't return any coordinates..
As I understand, it asks gps and network coordinates and this code doesn't return anything.
But when they use other apps like google maps , their location is determined correctly.
So, how else can I get coordinates?

A: You will have to ask for a new location. Add the following in your else statement
LocationListener ll = new mylocationlistener();
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);

and this outside your function.
private class mylocationlistener implements LocationListener {
    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
        Log.d("LOCATION CHANGED", location.getLatitude() + "");
        Log.d("LOCATION CHANGED", location.getLongitude() + "");
        Toast.makeText(MainActivity.this,
            location.getLatitude() + "" + location.getLongitude(),
            Toast.LENGTH_LONG).show();
        }
    }
    @Override
    public void onProviderDisabled(String provider) {
    }
    @Override
    public void onProviderEnabled(String provider) {
    }
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
    }

Note:-
Also instead of creating a new class you can always add implements LocationListener to your activity. Then too you will get the above 4 function. Add same code to them.


text:
Q: Intercepting Android Menu button in a PopupWindow I have a main activity that does not use option menu. I need to implement this behavior:
1. When the Android Menu button is pressed, a popup is shown
2. When the Android Menu button is pressed again, the popup is dismissed.
I know how to do #1 by overriding onKeyDown() in the main activity but don't know how to do #2. When the popup is shown, the onKeyDown() of the main activity is not triggered anymore.
How do I capture the Android Menu button when the main activity has an open popup?  (in my case, the popup is a PopupWindow with an inflated view).
BTW, I tried to set a key listener on the main view of the popup but it is not triggered
    mTopView.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            LogUtil.debug("*** Key: %d", keyCode);
            return false;
        }
    });

A: Answering my own question. Calling setFocusableInTouchMode() on the PopupWindow view does the trick and causes the listener to work.
PopupMenu popupMenu = ...
...
popupWindow.getContentView().setFocusableInTouchMode(true);
popupMenu.getContentView().setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyCode ==  KeyEvent.KEYCODE_MENU &&
                event.getRepeatCount() == 0 &&
                event.getAction() == KeyEvent.ACTION_DOWN) {
            // ... payload action here. e.g. popupMenu.dismiss();
            return true;
        }
        return false;
    }
});

A: try this
if (keyCode == KeyEvent.KEYCODE_MENU) {
        // Do Stuff
    }


text:
Q: JMeter: url encoded embedded resources I'm setting up some tests with JMeter, and I've seen that it's throwing out an error where trying to download embedded resources inside a web page, that have a path like the following:
www.mydomain.com/resources?getItem={someID}
The problem is that the characters need to be URL-encoded, so the following URL should follow this pattern:
www.mydomain.com/resources?getItem=%7BsomeID%7D
Now, how could instruct JMeter to replace these characters, when found on URLs from embedded resources in the web page? I've been looking at BeanShell PreProcessors, but I'm not sure how's the best way to handle this scenario.
Thanks!

A: You are facing this bug:

*

*https://bz.apache.org/bugzilla/show_bug.cgi?id=58137
Until bug is fixed, your option is to disable embedded download and use :

*

*CSS/ JQuery Post Processor to extract URLs

*Use ForEach Controller to iterate over urls
This will only simulate serial download not parallel one.
Update 15th july 2015:
Bug has been fixed yesterday night, you can give nightly build a try:

*

*http://jmeter.apache.org/nightly.html
Read:
Installing JMeter runtime
Download the _bin and _lib files
Unpack the archives into the same directory structure
The other archives are not needed to run JMeter.

A: What about this built in Jmeter function?
http://jmeter.apache.org/usermanual/functions.html#__urlencode


text:
Q: How to test a socket.io endpoint with cookie based authentication? I would like to perform integration tests on my socket.io namespaces, however all requests are piped through a middleware that checks for a valid session using the express-session module. What I am looking for is a way to either attach a cookie to the socket.io client before performing the request or if there is another way to perform tests would also like to hear about it.
Here is some server side code
const session = require('express-session')({
....
})
const Server = require('socket.io');

const io = new Server();

io.use(function(socket,next){
   session(socket.request, {}, next);
});

io.on('connection',...);

now on the client
const io = require('socket.io-client');

const cli1 = new io(); //Here is where I need to pass my connect.sid cookie.

I have skimmed the actual socket.io-client source and there doesn't seem to be anything, so if there are any alternatives I would love to hear about them.


text:
Q: GetProcAddress does not find function in DLL I have a DLL and I want to call a function in it. I check the DLL using Dependency Walker and the result I got is:
 void U2U_Test(void)

This is the code that I wrote, but GetProcAddress() returns NULL:
typedef void(*U2U_Test_pointer)();

void  check() {

    HINSTANCE hGetProcIDDLL1 = LoadLibrary(_T("my_dll.dll"));

    if (hGetProcIDDLL1 == NULL)
        return;

    U2U_Test_pointer addr = (U2U_Test_pointer)GetProcAddress(hGetProcIDDLL1, "U2U_Test");

    if (addr == NULL)
        return;

    return addr();
}

A: Depending on conventions and compiler used, the actual name exported in the DLL might not be exactly the same as the one you wrote in your source code.
This phenomenon is commonly called name decoration or name mangling.
In fact you are guaranteed to have exactly the same name only if

*

*Your compiler conforms to C conventions (probably it does)

*The function is exported in C and not C++. Use extern "C" to specify it.

*The calling convention is _cdecl (specify __cdecl in function declaration)

For example, when call convention is __stdcall instead of __cdecl, which is common for many windows DLLs (they often write WINAPI or CALLBACK instead of __sstdcall), the name of the exported function is often suffixed by @n where n is the number of bytes expected on the stack for parameters.
In your case, it could be U2U_Test@0.
Indications like __declspec(dllimport) and __declspec(dllexport) tell the compiler to automatically take care of that kind of thing when DLLs are imported/linked at compile time.
IN C++, complex name decoration is used in order to support methods, function overloading, templates and other features, and each compiler invented crazy naming schemes to make sure there won't ever be any clash.
Because at DLL level, there's no template, no classes, only a list of exported symbols indexed by their name or an ID.
That's the reason why most DLLs are exported in C and why most header files declare functions coming from DLL inside a extern "C" { ... } block.


text:
Q: Profiling C++ multi-threaded applications Have you used any profiling tool like Intel Vtune analyzer?
What are your recommendations for a C++ multi threaded application on Linux and windows? I am primarily interested in cache misses, memory usage, memory leaks and CPU usage.
I use valgrind (only on UNIX), but mainly for finding memory errors and leaks.

A: On Linux, try oprofile.
It supports various performance counters.
On Windows, AMD's CodeAnalyst (free, unlike VTune) is worth a look.
It only supports event profiling on AMD hardware though
(on Intel CPUs it's just a handy timer-based profiler).
A colleague recently tried Intel Parallel Studio (beta) and rated it favourably
(it found some interesting parallelism-related issues in some code).

A: VTune give you a lot of details on what the processor is doing and sometimes I find it hard to see the wood for the trees.  VTune will not report on memory leaks.  You'll need purify plus for that, or if you can run on a Linux box valgrind is good for memory leaks at a great price.
VTune shows two views, one is useful the tabular one, the other I think is just for sales men to impress people with but not that useful.
For quick and cheap option I'd go with valgrind.  Valgrind also has a cache grind part to it but i've not used it, but suspect its very good also.
cheers,
Martin.

A: You can try out AMD CodeXL's CPU profiler. It is free and available for both Windows and Linux.
AMD CodeXL's CPU profiler replaces the no longer supported CodeAnalyst tool (which was mentioned in an answer above given by timday).
For more information and download links, visit: AMD CodeXL web page.

A: I'll put in another answer for valgrind, especially the callgrind portion with the UI.  It can handle multiple threads by profiling each thread for cache misses, etc.  They also have a multi-thread error checker called helgrind, but I've never used it and don't know how good it is.

A: Following are the good tools for multithreaded applications. You can try evaluation copy.

*

*Runtime sanity check tool

*

*Thread Checker -- Intel Thread checker / VTune, here

*Memory consistency-check tools (memory usage, memory leaks)
    - Memory Validator, here

*Performance Analysis. (CPU usage)
    - AQTime , here
EDIT: Intel thread checker can be used to diagnose Data races, Deadlocks, Stalled threads, abandoned locks etc. Please have lots of patience in analyzing the results as it is easy to get confused.
Few tips:

*

*Disable the features that are not required.(In case of identifying deadlocks, data race can be disabled and vice versa.)

*Use Instrumentation level based on your need. Levels like "All Function" and "Full Image" are used for data races, where as "API Imports" can be used for deadlock detection)

*use context sensitive menu "Diagnostic Help" often.

A: The Rational PurifyPlus suite includes both a well-proven leak detector and pretty good profiler. I'm not sure if it does go down to the level of cache misses, though - you might need VTune for that.
PurifyPlus is available both on various Unices and Windows so it should cover your requirements, but unfortunately in contrast to Valgrind, it isn't free.

A: For simple profiling gprof is pretty good..


text:
Q: Plot 2d matrix with legend from another matrix So say I have the 2d following matrix:
a = [1,2,3,4,5;
     1,2,3,4,5;
     1,2,3,4,5;
     1,2,3,4,5]

and another matrix with the following values:
b = [0.3,0.4,0.6,0.9,1.2]

Not, I need to plot all the column vectors in a. I can very easily do this with :
plot(a)

However, I want a legend on the side which also shows just which line in the plot corresponds to what value from b.
I've done this using:
legend(b)

after the plot line. However, I wasn't sure if this is plotting the correct correspondence as in the first line color in the legend from b is pointing to the first line in a. Could someone tell me if I am right or at least rectify what I'm doing in that case.

A: You can get a handle from plot and pass it to legend. Also, you need to convert b to strings to use it in legend.
h = plot(a); % returns a vector of handles to the individual plots
legend(h,num2str(b(:)))


text:
Q: How to replace web.config with transformed for debug file when running WAP in Visual Studio? I want to replace web.config with transformed for debug config file when running in Visual Studio( I am NOT interesting in publishing project to some output directory). I want to keep original web.config in the root of web application in TFS, but on runtime (on IIS or Cassini) I want to use transformed debug version.
The best approach that I found so far (in Use Visual Studio web.config transform for debugging  and ASP.NET Web Projects: web.debug.config & web.release.config ) is to use web.template.config as a master file, and web.config as derived transformed file.
I am not fully happy with it, because developers use to consider web.config  as a master file.
I have an idea to output transformed file to ASP.Net temporary files directory, that ASP.NET used for cached files.
Does ASP.NET use web.config file from temporary cache folfder?
Will ASP.NET allow to have web.config file in cache directory different to web.config  in original folder?
I found a couple properties, related to ASP.Net temporary files directory.
MSBuild tempDirectory property of the CompilationSection can be used to replace root folder  of ASP.Net temporary files.
ClientBuildManager.CodeGenDir Property gives access to specific folder where current cache is located.
However I could not find, how to access path of the folder from MSBuild and will it allow me to output transformed web.config to cached folder.
Any suggestions/considerations will be appreciated.

A: The debug and release templates of the config file are used when you deploy the application.  Can you use the publish option to publish the application to another virtual directory on your machine for debugging purposes?  Then, you would have the transformed config file.


text:
Q: Android/XML - How to align an immobile layout to top of parent and have scrollview below? Please refer to example below. I want to have the top layout (below encased in red) to be unmoving in a scrollview in my activity. I have a scrollview as the parent layout and then I thought having a relative layout for the top one would work, and align it to the top, but that didn't really work out as it still remained within the scrollview. I would like to have the users have the red-layout box remain static when they scroll down.
I figure I would also have to put in a topMargin at the top of the scrollview or something in order to fit the redbox layout in.

XML Code posted here: http://pastebin.com/bxdREbeG

A: Do something like this (hand code, for reference only):
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:id="@+id/YourTopStaticView"
        android:layout_width="match_parent"
        android:layout_height="48dp"> //Or any other height you want

        //Contents of the top view

    </RelativeLyout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/YourTopStaticView">

        //Contents of the ScrollView

    </ScrollView>

</RelativeLayout>

As a side note, do not hardcode children into the ScrollView like that. Use the RecyclerView (which is an updated, modern replacement for ListView), which you will be expected to know how to use if you want to move into serious Android programming. It is actually super easy to use, once you get the hang of it :-)

A: You should use the ScrollView with only one child (official documentation - http://developer.android.com/reference/android/widget/ScrollView.html). According to your xml, your ScrollView is very complicated with a lot of child widgets.
The best option for you is to use a LinearLayout as the root for the whole container, a LinearLayout( or Relative) for the top layout containing the Reset and Save buttons, and a ListView for the long list that you have. ListView takes care of it's own scrolling. So you don't have to worry about that.
This will improve your code performance as well.

A: This should suit your needs:
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout android:id="@+id/topPanel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp">

        <TextView android:id="@+id/label"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:text="Multi TTS Implementation"/>

        <Button android:id="@+id/save"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:text="SAVE"/>

        <Button android:id="@+id/resetAll"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@id/save"
            android:layout_centerVertical="true"
            android:text="RESET ALL"/>

    </RelativeLayout>

    <ScrollView android:id="@id/scroll"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_below="@id/topPanel"
        android:layout_alignParentBottom="true"
        android:padding="5dp">

        <!-- Your scrollable content here -->

    </ScrollView>

</RelativeLayout>


text:
Q: Airflow/Amazon EMR: The VPC/subnet configuration was invalid: Subnet is required : The specified instance type m5.xlarge can only be used in a VPC I want to create an emr cluster triggered via Airflow on Amazon EMR. The emr cluster shows up in the UI of Amazon EMR but with an error saying:
"The VPC/subnet configuration was invalid: Subnet is required : The specified instance type m5.xlarge can only be used in a VPC"
Below is the code snippet and the config details in json format for this task that are used in the Airflow script.
My question is how can I incorporate the information (id codes) about VPC and subnet in the json (if this is even possible)? there are no explicit examples out there.
Hint: a network and an EC2 subnet is already created
JOB_FLOW_OVERRIDES = {
    "Name": "sentiment_analysis",
    "ReleaseLabel": "emr-5.33.0",
    "Applications": [{"Name": "Hadoop"}, {"Name": "Spark"}], # We want our EMR cluster to have HDFS and Spark
    "Configurations": [
        {
            "Classification": "spark-env",
            "Configurations": [
                {
                    "Classification": "export",
                    "Properties": {"PYSPARK_PYTHON": "/usr/bin/python3"}, # by default EMR uses py2, change it to py3
                }
            ],
        }
    ],
    "Instances": {
        "InstanceGroups": [
            {
                "Name": "Master node",
                "Market": "SPOT",
                "InstanceRole": "MASTER",
                "InstanceType": "m5.xlarge",
                "InstanceCount": 1,
            },
            {
                "Name": "Core - 2",
                "Market": "SPOT", # Spot instances are a "use as available" instances
                "InstanceRole": "CORE",
                "InstanceType": "m5.xlarge",
                "InstanceCount": 2,
            },
        ],
        "KeepJobFlowAliveWhenNoSteps": True,
        "TerminationProtected": False, # this lets us programmatically terminate the cluster
    },
    "JobFlowRole": "EMR_EC2_DefaultRole",
    "ServiceRole": "EMR_DefaultRole",
}

create_emr_cluster = EmrCreateJobFlowOperator(
    task_id="create_emr_cluster",
    job_flow_overrides=JOB_FLOW_OVERRIDES,
    aws_conn_id="aws_default",
    emr_conn_id="emr_default",
    dag=dag,
)

A: EmrCreateJobFlowOperator calls create_job_flow from emr.py which matches the same api from boto3 emr client.
Therefore you can put an item "Ec2SubnetId" with your subnet id as value within the "Instances" dictionary.
This works for me on Apache Airflow 2.0.2


text:
Q: Angularjs is not working after including dependancy on ui.bootstrap My html file is :

    <meta charset="utf-8">
    <title>example</title>

    <link rel="stylesheet" type="text/css" href="bootstrap_min_css" media="all">
    <link rel="stylesheet" type="text/css" href="bootstrap_responsive_min_css" media="all">
    <link rel="stylesheet" type="text/css" href="appcss">

            The value of ng-show is : {{is_new_user}}

And my app.js file is as :
var myApp = angular.module('myApp', ['ui.bootstrap']);

myApp.controller('parentCtrl', ['$scope', function($scope) {
    $scope.is_new_user = false;
}]);

myApp.controller('loginCtrl', ['$scope', function($scope) {
    $scope.is_new_user = $scope.$parent.is_new_user;
}]);

But when I remove ui.bootstrap, my angularjs works (showing "The value of ng-sho is : false"). But when I add ui.bootstrap, it shows {{is_new_user}} in browser (means angularjs does not work).
I have also checked that all the js and css files are getting loaded in browser.


text:
Q: Is there a recommended version of nvidia 8600gt drivers for Win 7? I've read on some forums that people recommend an specific version of drivers for X gfx card and Y operative system.
Does someone knows if an older version of Nvidia 8600GT drivers for Win 7 that works better than the last one?
I don't have any critical problems with the current latest driver but I am looking to get some fps improvement in a video game.

A: The best version of a graphics driver is the most recent one your card supports. I have never seen a permanent performance drop due to updating graphics drivers, if one does happen the issue that caused it is fixed in the next update.


text:
Q: Eclipse (+WTP) not filtering resource files Remark: I do have searched for similar questions but found no solution that worked, hence I dare to ask this again. Please bare with me!
I am using Eclipse (Version: 2022-12 (4.26.0) / Build id: 20221201-1913 which includes WTP) to work on a Maven project. I am trying to deploy from Eclipse directly to a local Tomcat 8.5 server.
What is currently blocking me is that some of my application's resource files (like application.properties and logback.xml) contain place-holders and obviously these are not "filtered" when Eclipse/WTP deploys them to the wtpwebapps-folder before starting Tomcat.
When I run the build in Maven on the command-line then the resource files are all properly filtered (i.e. all properties defined in my settings.xml file or in the pom.xml do get properly replaced in the copy of these resource files that gets placed in the target-folder and which are then wrapped up into a .war file).
So, deploying that .war file to Tomcat works but starting it directly from Eclipse would be so much easier and quicker.
However, when I build this project in Eclipse then the files that get "published" to
<workspace>/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/<project_name>/WEB-INF before it starts Tomcat still contain the original placeholders which then causes the application to crash during startup. :-(
I do have the resource folder defined in the pom.xml (this was one suggestion that I had found) as:
        <resources>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>

but this had no effect on the filtering for Eclipse/WTP.
I also tried to enable the maven-war-plugin's explode-goal in M2E's lifecycle mapping because the war-plugin's config contains a corresponding "filtering"-config:
                        ...
                        <resource>
                            <directory>${basedir}/src/main/resources</directory>
                            <filtering>true</filtering>
                            <targetPath>WEB-INF/classes</targetPath>
                        </resource>
                        ...

but with no effect, either.
Any other idea, hint or suggestion to convince Eclipse/WTP to "filter" these resource files before starting Tomcat?


text:
Q: Creating an android Application containing only static data I am going to work on an android application.
The basic flow should be like :
1. Main Activity

**-cat1**
  -subcategory 1
  -subcategory 2
**-cat2**
  -subcategory 1
  -subcategory 2
**-cat3**
  -subcategory 1
  -subcategory 2

this should be the flow of application. Every Page contains static data only.
If we consider subcategory under category, it may contain some images and some data.
All Pages would be of same scene.
So, I just want to know what would be the best way to do so??
Can I just have to use resources only or database would come into picture?
Thanks.
Let Me add that I am clear with the flow my confusion resides into data storing only that what should be the best way to display static data only.
Editing again and again because I am not satisfied.
For data taking scrollable textview would be convenient?? I will put whole data in String.xml

A: Different Tabs for Categories and activity for your subcategory page would be better in my opinion. You need not use any database since most of the data is static.


text:
Q: MySQL find where values do not exist when comparing two tables I have a series of employee numbers in two tables and I"m trying to find values in a table called HTG_ScheduleRequest that are not found in my images table when I compare columns that contain the employee numbers..
I've issued this command but it is displaying all values:
SELECT DISTINCT
HTG_ScheduleRequest.AssignedTech
FROM
HTG_ScheduleRequest ,
images
WHERE
HTG_ScheduleRequest.AssignedTech <> images.empno

A: Your question is not 100% clear, but here is my approach:
http://sqlfiddle.com/#!9/a8286ee/1
SELECT DISTINCT sr.AssignedTech
FROM HTG_ScheduleRequest sr
LEFT JOIN images i
ON sr.AssignedTech = i.empno
WHERE i.empno IS NULL

A: SELECT DISTINCT A.AssignedTech
FROM
HTG_ScheduleRequest A
WHERE NOT EXISTS (SELECT NULL FROM images B WHERE A.AssignedTech=B.empno);

See a Demo on SQL Fiddle.


text:
Q: Finding a specific character in a string I'm trying to create a function that takes a string input, and checks if it has "=" or ">" inside it, then returns a list after applying the built in string method "strip" to it on "=" or ">". In order to do this, I am writing an if and elif statement.
def split_list_math(a_str):
    if(contains("=") == True):
        a_str2 = a_str.split("=")
    elif(contains(">") == True):
        a_str2 = a_str.split(">")
    return a_str2

What can I replace "contain" with in my code in order to make this function work?

A: Use the in operator:
if "=" in a_str:

Demo:
>>> '=' in '!@#$%^'
False
>>> '=' in '=-0987'
True


text:
Q: Which Method For Verification ? REGEX or filter_var? What do you think, is there any difference (for performance, security,  reliability ) between this methods :
METHOD 1
eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)

METHOD 2
filter_var($email, FILTER_SANITIZE_EMAIL)
filter_var($email, FILTER_VALIDATE_EMAIL)

A: Method 2 is clearly easier to understand and more maintainable.  The regular expression just looks like line noise.

A: If method 2 is a good email validation then thats better.
Method 1 could be cleaned up if case insensitive to this (expanded)
Correction: did not read the regex close enough.
Stick with method 2 ..


text:
Q: Foramtting date in Smart Narrative PowerBI just wondering if you have any idea how I can make the date change to April 2019 instead of Monday, April 1, 2019? this happens when I generate a smart narrative in PowerBI.

Expetected result: Last year's Revenue had two low anomalies on April 2019


text:
Q: How to change column visibility by Column ID in javascript? I want to make a column visible if its checkbox is selected. I have this function:
function SaveTableSettings() {
    var notChecked = [], checked = [];
    var table = $('#data-table');
    $(":checkbox").each(function() {
        if(this.checked){
            checked.push(this.id);

        } else {
            notChecked.push(this.id);
        }
});

And I want to use the elements of the "checked" array and change corresponding column visibility with this function :
if (dataTableId == "data-table"&&toShow.length<1) {
    alert("in if");
    table.column(1).visible(false);
    table.column(2).visible(false);
    table.column(3).visible(false);
    table.column(4).visible(false);
} else {
    for (i = 0; i < toShow.length; i++) {

    }
}

where "toShow" is the same array with to "checked" I passed it as parameter. I want to make the column which is in the array visible .But I do not know what to do in the for loop. Thanks for any help

A: You can use the Buttons extension for that purpose, and to be more precise you should use the column visibility plug-in for Buttons.
Here is the basic usage example:
$(document).ready(function() {
    $('#example').DataTable( {
        dom: 'Bfrtip',
        buttons: [
            'colvis'
        ]
    } );
} );

You have to include the relevant JavaScript files, for example:

*

*https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js

*https://cdn.datatables.net/buttons/1.0.3/js/dataTables.buttons.min.js

*https://cdn.datatables.net/buttons/1.0.3/js/buttons.colVis.min.js
Alternatively, use Download builder and include DataTables with Buttons and Column visibility modules.
p.s In case that you use old datatables (1.9.x you should use the ColVis extension

A: It is hard to debug your code without the markup / HTML, but to me it somehow seems like you are trying to use a sledgehammer to crack a nut.
Instead of id's (?) simply use an attribute to bind the checkbox to a certain column :
<input type="checkbox" data-column="0" checked/>

And in your SaveTableSettings() or whatever :
$("[data-column]").each(function() {
    table.column($(this).data('column')).visible($(this).is(':checked'));
})

a small demo -> http://jsfiddle.net/c0o48jmv/1/

The above can easily be changed to target id's instead of column indexes. Simply add id's to your 's
columnHeader

and refer to those id's instead of the indexes
<input type="checkbox" data-column="#col0" checked/>

http://jsfiddle.net/d9q06cg0/


text:
Q: Error: Bad math evironment delimiter I am getting an Error: Bad math evironment delimiter for the following lines:`
\[ \sum\limits_{i=1}^{10} i z_{i}\equiv 0\)\ \textrm{mod}\ 11
\]

and
\[ z_{1} \equiv -  \(\sum \limits_{i=2}^{10} i z_{i}\)\ \textrm{mod}\ 11 0\leq z_{1}\leq 10
\]

The output is shown correctly

A: You can't have \( and \) terms, which serve to initiate and terminate an inline-style equation, inside a display-style math environment. That's what's giving you the "Bad math environment delimiter" error.
I'm not entirely sure, but I'm guessing you want to enclose the summation terms in large parentheses. If that's the case, I suggest you use \biggl( and \biggr) around the terms. Also, do use \mod (from the amsmath package) instead of \ \textrm{mod}\.

\documentclass{article}
\usepackage{amsmath} % for "\mod" macro
\begin{document}
\[
\biggl(\,\sum_{i=1}^{10} i z_{i}\equiv 0\biggr) \mod 11
\]
and
\[
z_{1} \equiv -\biggl(\,\sum_{i=2}^{10} i z_{i}\biggr) \mod 11 0\leq z_{1}\leq 10
\]
\end{document}


text:
Q: Spring Security-acl. Users do not receive permission It seems to be all right. Authorization is working, and users get the roles. I protected the methods of using annotations (for example @PreAuthorize("hasPermission(#post, 'READ')") ), it works and I get access denied. I created a database in which he described the rights of users to objects. I created a database which contains the user's permission on objects.
My problem is that after the user's authorization, it is not getting permissions, and even if the user has the authority to object, he gets access denied. Also, I noticed that after a user login in the log file of the server should get a string which will write what permission he got, but I have no such line.
Pieces of my files:
web.xml
...
<filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/spring-security.xml
        /WEB-INF/acl-context.xml
        /WEB-INF/mvc-dispatcher-servlet.xml
    </param-value>
</context-param>...

mvc-dispatcher-servlet.xml
    ...
<security:global-method-security pre-post-annotations="enabled">
    <security:expression-handler ref="expressionHandler" />
</security:global-method-security>

<context:annotation-config />

<tx:annotation-driven />
<tx:jta-transaction-manager />

<context:component-scan base-package="com.bla-bla.bla.controllers" />

<mvc:annotation-driven />
...

spring-security.xml
    ...
<security:http auto-config="true" use-expressions="true"
    access-denied-page="/auth/denied.html">
    <security:intercept-url pattern="/auth/login.html" access="permitAll" />
    <security:form-login login-page="/auth/login.html"
        authentication-failure-url="/auth/login.html?error=true"
        default-target-url="/index.html" />
    <security:logout invalidate-session="true"
        logout-success-url="/auth/login.html" logout-url="/auth/logout.html" />
</security:http>

<security:authentication-manager>
    <security:authentication-provider
        user-service-ref="userService">
        <security:password-encoder ref="pswEncoder" />
    </security:authentication-provider>
</security:authentication-manager>

<bean id="userService"
    class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl">
    <property name="dataSource" ref="jndiJboss" />
    <property name="usersByUsernameQuery"
        value="SELECT login, pass, enabled FROM accounts WHERE login=?" />
    <property name="authoritiesByUsernameQuery"
        value="SELECT login, authority FROM accounts WHERE login=?" />
</bean>

<bean
    class="org.springframework.security.authentication.encoding.Md5PasswordEncoder"
    id="pswEncoder" />
...

acl-context.xml
    ...
<bean id="expressionHandler" class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler"
    p:permissionEvaluator-ref="permissionEvaluator"
    p:roleHierarchy-ref="roleHierarchy" />

<bean class="org.springframework.security.acls.AclPermissionEvaluator" id="permissionEvaluator">
    <constructor-arg ref="aclService"/>
</bean>

<bean class="org.springframework.security.acls.jdbc.JdbcMutableAclService" id="aclService">
    <constructor-arg ref="jndiJboss"/>
    <constructor-arg ref="lookupStrategy"/>
    <constructor-arg ref="aclCache"/>
</bean>

<bean id="lookupStrategy" class="org.springframework.security.acls.jdbc.BasicLookupStrategy">
    <constructor-arg ref="jndiJboss"/>
    <constructor-arg ref="aclCache"/>
    <constructor-arg ref="aclAuthorizationStrategy"/>
    <constructor-arg ref="auditLogger"/>
</bean>

 <bean id="jndiJboss" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:/JBossDB"/>
</bean>

<bean id="aclCache" class="org.springframework.security.acls.domain.EhCacheBasedAclCache">
    <constructor-arg>
        <bean class="org.springframework.cache.ehcache.EhCacheFactoryBean">
            <property name="cacheManager">
                <bean class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"/>
            </property>
            <property name="cacheName" value="aclCache"/>
        </bean>
    </constructor-arg>
</bean>

<bean id="aclAuthorizationStrategy" class="org.springframework.security.acls.domain.AclAuthorizationStrategyImpl">
    <constructor-arg>
        <list>
            <bean class="org.springframework.security.core.authority.GrantedAuthorityImpl">
                <constructor-arg value="ROLE_ADMIN"/>
            </bean>
            <bean class="org.springframework.security.core.authority.GrantedAuthorityImpl">
                <constructor-arg value="ROLE_ADMIN"/>
            </bean>
            <bean class="org.springframework.security.core.authority.GrantedAuthorityImpl">
                <constructor-arg value="ROLE_ADMIN"/>
            </bean>
        </list>
    </constructor-arg>
</bean>

<bean id="auditLogger" class="org.springframework.security.acls.domain.ConsoleAuditLogger"/>

<bean id="roleHierarchy"  class="org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl">
    <property name="hierarchy">
        <value>
            ROLE_ADMIN > ROLE_USER
        </value>
    </property>
</bean>
...

An example of a protected method of the controller
@Override
@RequestMapping(value = "/post/delete.html", method = RequestMethod.GET)
@Transactional
@PreAuthorize("hasPermission(#post, 'READ')")
public String delete(final Post post) {
    //some actions
    return "post/view";
}

In what could be the problem?
UPD. My problem was in the wrong filling acl_object_identity

A: Post the code that uses the ACLs (secured method invocations) and also highlight those classes in the Spring config files. Also, why are you placing the <security:global-method-security /> element in your MVC config file?


text:
Q: Is the Realm method addOrUpdateObject() callable from Swift? According to the docs; https://realm.io/docs/objc/latest/api/Classes/RLMRealm.html the method - (void)addOrUpdateObject:(nonnull RLMObject *)object
is available via Obj-C
The Swift docs; https://realm.io/docs/swift/latest/api/Classes/Realm.html doesn't mention this method. Edit: It does, I didn't notice at first.
In my Swift app, if I try and call this method self.realm!.addOrUpdateObject(model) then I get a compiler error Value of type 'Realm' has no member 'addOrUpdateObject'
Yet I see other places online, e.g. How to properly map JSON properties to model properties in Realm.create where people are apparently using it from Swift.
I am using Realm via cocoapods - pod 'RealmSwift' - which brings down 2 pods; Realm and RealmSwift. I can see this method defined in RLMRealm.mm I tried adding #import <Realm/Realm.h> to my bridging header but that didn't work.
How do I call this method from Swift?

A: This is available in Swift, and is defined as:
public func add(object: Object, update: Bool = false)

So to get the same behaviour as the Obj-C Realm's method, you'd call it:
self.realm!.add(model, update: true)

A: Realm has two methods to add objects. One is addObjects and the other is addOrUpdateObjects.
with addObjects method, we can add objects without primaryKey.
Whereas addOrUpdateObjects must use the objects with primary key.


text:
Q: extract image from a list like dict I have a list, which my object detection prediction is stored like this.
[{'box': [tensor(28.36783, device='cuda:0'),
   tensor(32.88762, device='cuda:0'),
   tensor(41.10822, device='cuda:0'),
   tensor(44.73560, device='cuda:0')],
  'conf': tensor(0.91164, device='cuda:0'),
  'cls': tensor(0., device='cuda:0'),
  'label': 'pore 0.91',
  'im': array([[[124, 125, 125],
          [131, 131, 131],
          [128, 128, 128],
          ...,
          [ 45,  45,  44],
          [ 42,  43,  42],
          [ 42,  42,  41], dtype=uint8)}]

Can you please help me how can extract image array from this list just like?
img = array([[[124, 125, 125],
         [131, 131, 131],
         [128, 128, 128],
         ...,
         [ 45,  45,  44],
         [ 42,  43,  42],
         [ 42,  42,  41], dtype=uint8)

A: Like this:
img = my_list[0]['im']


text:
Q: How to get current language setting in the phone with react native I would like my app to support multiple languages, for example English and Chinese. Using react native, how do I find the language settings on the phone?

A: Try using this library -> https://github.com/AlexanderZaytsev/react-native-i18n
import I18n from 'react-native-i18n';
deviceLocale = I18n.currentLocale()

A: import { NativeModules, Platform } from 'react-native';

const deviceLanguage =
          Platform.OS === 'ios'
            ? NativeModules.SettingsManager.settings.AppleLocale ||
              NativeModules.SettingsManager.settings.AppleLanguages[0] // iOS 13
            : NativeModules.I18nManager.localeIdentifier;

console.log(deviceLanguage); //en_US

A: import { NativeModules, Platform } from 'react-native';

let deviceLanguage = Platform.OS === 'ios' ?
    NativeModules.SettingsManager.settings.AppleLocale:
    NativeModules.I18nManager.localeIdentifier;

if (deviceLanguage === undefined) {
    // iOS 13 workaround, take first of AppleLanguages array
    deviceLanguage = NativeModules.SettingsManager.settings.AppleLanguages[0]
    if (deviceLanguage == undefined) {
        return defaultLocalization // default language
    }
}

A: You can use react-native-localize and get current user's device language:
import * as RNLocalize from "react-native-localize";

console.log(RNLocalize.getLocales());


text:
Q: Move PictureBox using Timer My goal is to move a picturebox back and forth. My issue is how to do this.
I have written the following:
    int x = enemy.Location.X;
    int y = enemy.Location.Y;
    enemy.Location = new Point(x+-1, y);

This moves the picturebox off-screen, left. After moving left, I'd like it to move right, so that it moves back and forth - in a continuous loop.
The noob that I am, I tried:
    if (x < 40)
        enemy.Location = new Point(x - -100, y);
    else if (x > 400)
        enemy.Location = new Point(x - 5, y);

This proves unsuccessful - the box doesn't seem to move on reaching pixel 40.
Is there a simple solution that you can prod me towards, or have I dug an early grave for myself?!
I should specify: I am writing in C# per college assignment requirements.
Cheers.

A: When moving left, when the x location reaches 0, change direction and move right.
When moving right, you need to use the width of the screen minus the width of your picturebox.
System.Windows.SystemParameters.PrimaryScreenWidth

edit:
Or better yet, use the width of your form minus the width of the picturebox. Then it will still work if its not maximized.

A: Setup a variable that toggles between negative and positive values to make it go left and right.  You toggle the direction by multiplying by -1.  Then you simply add that variable to the current X value like this:
    private int direction = -1; // this can be values other than 1 to make it jump farther each move

    private void timer1_Tick(object sender, EventArgs e)
    {
        int x = enemy.Location.X + direction;
        if (x <= 0)
        {
            direction = -1 * direction;
            x = 0;
        }
        else if (x >= this.ClientRectangle.Width - enemy.Width)
        {
            direction = -1 * direction;
            x = this.ClientRectangle.Width - enemy.Width;
        }
        enemy.Location = new Point(x, enemy.Location.Y);
    }


text:
Q: How to use @media correctly in css How to use @media in css for certain resolution? So I want to make my sidebar changes depend on the user resolution, so I use @media.
This is the example code:
    @media (max-width: 1920px) and (min-width: 1080px){ /*for 1920 x 1080*/
  .logo1{
    margin-top: 70%;
  }

  .socmed a:nth-child(1), .socmed a:nth-child(2){
    margin-top: 100%;
  }
}

@media (max-width: 1680px) and (min-width: 1050px){ /*for 1680 x 1050*/
  .logo1{
    margin-top: 70%;
  }

  .socmed a:nth-child(1), .socmed a:nth-child(2){
    margin-top: 90%;
  }
}

@media (max-width: 1600px) and (min-width: 900px){ /*for 1600 x 900*/
  .logo1{
    margin-top: 50%;
  }

  .socmed a:nth-child(1), .socmed a:nth-child(2){
    margin-top: 40%;
  }
}

@media (max-width: 1440px) and (min-width: 900px){ /*for 1440 x 900*/
  .logo1{
    margin-top: 40%;
  }

  .socmed a:nth-child(1), .socmed a:nth-child(2){
    margin-top: 50%;
  }
}

@media (max-width: 1400px) and (min-width: 1050px){ /*for 1400 x 1050*/
  .logo1{
    margin-top: 70%;
  }

  .socmed a:nth-child(1), .socmed a:nth-child(2){
    margin-top: 90%;
  }
}

@media (max-width: 1366px) and (min-width:768px){ /*for 1366 x 768 until 1024 x 768*/
  .socmed a:nth-child(1), .socmed a:nth-child(2){
    margin-top: 20%;
  }
}

in those code I put comment of the uses resolution, it works well until I opened my web from 1366x768 and bellow, it was overwrite with @media (max-width: 1400px) and (min-width: 1050px). How I prevent it from this problem? thanks

A: You're making the tiny mistake to think the second parameter in the media query defines a certain height. It doesn't, it still defines the width.
@media (max-width: 1920px) and (min-width: 1080px){
// You're assuming the screen's maximal width to be 1920,
// and it's minimal width to be 1080px, which means this CSS
// is applied when the screen's width is 1080px or more,
// but less than 1920px;

  .logo1 {
    margin-top: 70%;
  }

  .socmed a:nth-child(1), .socmed a:nth-child(2) {
    margin-top: 100%;
  }
}

What you actually want is this:
@media (min-width: 1920px) { /*1920px or larger*/
  .logo1 {
    margin-top: 70%;
  }

  .socmed a:nth-child(1), .socmed a:nth-child(2){
    margin-top: 100%;
  }
}

@media (min-width: 1680px) { /*for 1680 x 1050*/
  .logo1{
    margin-top: 70%;
  }

  .socmed a:nth-child(1), .socmed a:nth-child(2){
    margin-top: 90%;
  }
}

@media (min-width: 1600px) { /*for 1600 x 900*/
  .logo1{
    margin-top: 50%;
  }

  .socmed a:nth-child(1), .socmed a:nth-child(2){
    margin-top: 40%;
  }
}

@media (min-width: 1440px) { /*for 1440 x 900*/
  .logo1 {
    margin-top: 40%;
  }

  .socmed a:nth-child(1), .socmed a:nth-child(2){
    margin-top: 50%;
  }
}

@media (min-width: 1400px) { /*for 1400 x 1050*/
  .logo1{
    margin-top: 70%;
  }

  .socmed a:nth-child(1), .socmed a:nth-child(2){
    margin-top: 90%;
  }
}

@media (min-width: 1366px) { /*for 1366 x 768 until 1024 x 768*/
  .socmed a:nth-child(1), .socmed a:nth-child(2){
    margin-top: 20%;
  }
}

Keep in mind that you're changing 'ranges' instead of specific viewports with these rules. You don't change the CSS based on a 1920x1080 screen, but you change it when a screen has enough space, namely 1920 pixels in width or more

A: You are specifying only the width and the queries overlap. "1080" in "1920x1080" stands for height.


text:
Q: PL/pgSQL functions: How to return a normal table with multiple columns using an execute statement I've got this PL/pgSQL function which must return some users information.
CREATE OR REPLACE FUNCTION my_function(
        user_id integer
    ) RETURNS TABLE(
            id integer,
            firstname character varying,
            lastname  character varying
        ) AS $$
    DECLARE
        ids character varying;
    BEGIN
        ids := '';
        --Some code which build the ids string, not interesting for this issue
        RETURN QUERY
            EXECUTE 'SELECT
                        users.id,
                        users.firstname,
                        users.lastname
                    FROM public.users
                    WHERE ids IN (' || ids || ')';
    END;
$$ LANGUAGE plpgsql;

The problem I'm facing is that the result of the function is a single columns table like this:
╔═══╦═════════════════════╗
║   ║my_function          ║
╠═══╬═════════════════════╣
║ 1 ║ (106,Ned,STARK)     ║
║ 2 ║ (130,Rob,STARK)     ║
╚═══╩═════════════════════╝

While I expected:
╔═══╦════════════╦════════════╦═════════════╗
║   ║ id         ║ firstname  ║ lastname    ║
╠═══╬════════════╬════════════╬═════════════╣
║ 1 ║ 106        ║ Ned        ║ STARK       ║
║ 2 ║ 103        ║ Rob        ║ STARK       ║
╚═══╩════════════╩════════════╩═════════════╝

I think (but not sure) the problem comes from the EXECUTE statement, but I can't see how to do otherwise.
Any ideas?

A: How are you executing that function? It works as a select statement.
Create a table: public.users
create table public.users (id int, firstname varchar, lastname varchar);

Insert some records:
insert into public.users values (1, 'aaa','bbb'),(2,'ccc','ddd');

function: my_function
CREATE OR REPLACE FUNCTION my_function(user_id integer) RETURNS TABLE(id integer, firstname character varying, lastname character varying) AS $$
    DECLARE
        ids INTEGER[];
    BEGIN
         ids := ARRAY[1,2];
         RETURN QUERY
             SELECT users.id, users.firstname, users.lastname
             FROM public.users
             WHERE users.id = ANY(ids);
    END;
$$ LANGUAGE plpgsql;

Now you can use with *
select * from my_function(1);

Result of query
 id | firstname | lastname
----+-----------+----------
  1 | aaa       | bbb
  2 | ccc       | ddd

Or with column names as well
select id,firstname,lastname from my_function(1);

Result
 id | firstname | lastname
----+-----------+----------
  1 | aaa       | bbb
  2 | ccc       | ddd

A: http://www.postgresqltutorial.com/plpgsql-function-returns-a-table/
there is a difference in the output received from the function depending on the syntax of the selection:
select * from myfunction();

and
select myfunction();

A: Call function like that :
select * from  my_function(123);

Not just with select. I did and It works


text:
Q: iOS6 Maps, MISSING the Detail Disclosure Button (the blue chevron) on all my maps! How to get it back My understanding was there was no problems moving to iOS 6 maps. But for some reason, the Detail Disclosure Button is now MISSING in my map App. Is there a way to get this back.  Wow, totally unexpected. This has been working for years, so all delegates are fine.
#pragma mark MKMapViewDelegate
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {

MKPinAnnotationView *pin = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"REUSEME"] autorelease];
UIButton *button = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];

if ([annotation isKindOfClass:[MKUserLocation class]]) {
    pin.animatesDrop = YES;
    return nil;
} else {
    [pin setPinColor:MKPinAnnotationColorGreen];
}

pin.rightCalloutAccessoryView = button;
pin.animatesDrop = YES;
pin.canShowCallout = YES;

return pin;
}

A: I had the same problem and setting the MapView delegate in the Storyboard did the trick for me, callout arrows now working:)

A: Now in iOS 6 you have to set the delegate before adding the annotation to the mapView
seen in here: http://www.openradar.me/12346693

A: I had the same problem, I only put the delegate after annotation and work perfectly!
mapView.delegate = self;
[self.mapView addAnnotation:ann];

Tks,
Cauca

A: I don't have this problem and the only difference I can see between your code and mine is in the creation of the MKPinAnnotationPinView object as I try to dequeue it first:
    MKPinAnnotationView *pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"CustomPinAnnotationView"];

A: I have the same problem and I use the same code as the first answer:
MKPinAnnotationView *MyPin =(MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"MyPin"];
I also noticed other problems since updating to xcode 4.5/iOS 6.

A: What I have noticed in mapKit for iOS 6 is that the timing is essential. Setting the MKMapView´s delegate to late (i.e. in viewDidLoad), the map will use default annotation style for annotations already added.
The solution for me was to move the mapView.delegate = self, to the -(void)loadView method.

A: @ErCa As per iOS documentation, you should never call loadView unless you are building a custom view.
The problem lies elsewhere. I have it as well and will post an answer once I find it.
@ed-potter Are you targeting iOS4? I'm asking because you autorelease the MKPinAnnotationView which is not necessary with ARC.

A: This happened to me as well.  It is true that the MKMapView delegate needs to be set earlier than viewDidLoad: now for some reason.  What I ended up doing is setting the mapView delegate within my setMapView: function.
So for the view controller that contains the MKMapView, I had the following property:
@property (nonatomic, weak) IBOutlet MKMapView *mapView;
and so I put within the setMapView function:
-(void)setMapView:(MKMapView *)mapView
{
_mapView = mapView;

self.mapView.delegate = self;//needed to move setting of the mapView delegate here because they changed when the viewForAnnotations delegate function is called when Apple went to iOS 6 and changed the maps App.  Now all of the annotations are loaded and the views for those annotations are set up before the View Controller even calls viewDidLoad.

[self updateMapView];

}

A: I had the same problem and was also setting self.mapView.delegate = self in viewDidLoad but mapView:viewForAnnotation: was not getting called, so my leftCalloutAccessoryView was not getting the UIImageView I specified.  I went back to review Ray Wenderlich's Introduction to MapKit in iOS 6 Tutorial and found this:

First select MainStoryboard.storyboard. Then set the View Controller
  (right at the top of the list) as the delegate of the map view by
  control clicking on the map view, and dragging a line from the
  delegate entry to the View Controller.


text:
Q: Como modificar uma lista dentro de um método em Python? Suponhamos que eu tenha o seguinte método e a seguinte lista:
def ModificaValores(Valores):
      dados = [6,5,4,3,2,1,0]

      Valores = dados

Valores = [0,1,2,3,4,5,6]

print(Valores)
ModificaValores(Valores)
print(Valores)

Por que na saída tenho o seguinte resultado:
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]

Se eu modifico elemento por elemento funciona, mas assim não. Me expliquem por que isso acontece!

A: Não funciona porque as alterações feitas dentro do escopo da função não são repletidas para o escopo externo - e nem deveria, pois isso poderia gerar efeitos colaterais e dificultar muito a manutenção do código. Ou seja, não faça isso a menos que realmente faça sentido.
Vamos por partes.
Fora da função, no escopo global, você define a lista Valores. Neste momento, o objeto Valores terá um identificador único que o representa que pode ser obtido via id(Valores). Em CPython, esse valor representa o endereço de memória do seu objeto. Este objeto é passado via parâmetro para a função ModificaValores e, como no Python o tipo list é um tipo mutável, o objeto será passado por referência, o que implica que dentro da função será o mesmo objeto que foi criado fora, com os mesmos valores e mesmo endereço de memória. O fato de ser passado via referência explica o porquê de refletir as alterações feitas elemento a elemento, pois você está apenas modificando o objeto. Mesmo que assim reflita as mudanças para o escopo externo, deve-se usar com muita cautela, apenas em casos que realmente isso faça sentido. No geral, o ideal seria retornar uma nova lista e atribuí-la ao objeto desejado. Algo como:
def ModificaValores(Valores):
    # Neste caso o parâmetro é desnecessário
    # mas mantive por questões didáticas
    dados = [6,5,4,3,2,1,0]
    return dados

Valores = [0,1,2,3,4,5,6]

print(Valores)
Valores = ModificaValores(Valores)
print(Valores)

Veja funcionando no Ideone | Repl.it
E por quê não funciona quando você atribui a nova lista?
Pois você, quando define dados sendo uma nova lista, define um novo objeto na memória, com um novo endereço, que existirá apenas no escopo da função. Quando você atribui dados para Valores, você quebra a referência que Valores tinha com o objeto externo e passa a referenciar o objeto dados local, porém essa alteração é feita no escopo local, não sendo refletida para o escopo externo - em outras palavras, você passa a ter um objeto Valores no escopo global e outro no escopo local, sendo diferentes entre si. As modificações que você faz em Valores, no escopo local, não serão refletidas em Valores do escopo global, pois são objetos diferentes.


text:
Q: Fourier transform integral I'm trying to calculate the 3D fourier transform of this function:
$$\frac{1}{(x^2+y^2+z^2)^{1/2}}$$
Any help would be appreciated, thanks.

A: Inserting the Jacobian $r^2\sin\theta$
and $\sqrt{x^2+y^2+z^2}=r$ in polar coordinates gives
\begin{equation}
\int_0^\infty r^2 dr \int_0^{2\pi} d\phi \int_0^\pi \sin\theta d\theta \frac{1}{r} e^{i\mathbf{k}\cdot \mathbf{r}}
\end{equation}
\begin{equation}
=
\int_0^\infty r^2 dr \int_0^{2\pi} d\phi \int_0^\pi \sin\theta d\theta \frac{1}{r} e^{ikr\cos\theta}
\end{equation}
and with $z=\cos\theta$, $dz=-\sin\theta d\theta$
\begin{equation}
=
2\pi \int_0^\infty r dr \int_0^\pi \sin\theta d\theta e^{ikr\cos\theta}
=
-2\pi \int_0^\infty r dr \int_{1}^{-1} dz e^{ikrz}
=
2\pi \int_0^\infty r dr \int_{-1}^{1} dz e^{ikrz}
\end{equation}
and with $t=ikrz$, $dz=dt/(ikr)$
\begin{equation}
=
2\pi \int_0^\infty r dr \frac{1}{ikr} \int_{-ikr}^{ikr} dt e^t
\end{equation}
\begin{equation}
=
2\pi \int_0^\infty r dr \frac{1}{ikr} [e^{ikr}-e^{-ikr}]
=
4\pi \int_0^\infty r dr \frac{1}{kr} \sin(kr)
=
\frac{4\pi}{k^2} \int_0^\infty kr d(kr) \frac{1}{kr} \sin(kr)
\end{equation}
\begin{equation}
=
\frac{4\pi}{k^2} \int_0^\infty d(kr) \sin(kr)
=
\frac{4\pi}{k^2} \int_0^\infty dz \sin z
\end{equation}
and this exists only in the theory of distributions.


text:
Q: Writing test case for Junit testing As a developer, I'm a newbie to Unit testing and have a requirement to write a test case to unit test the following code. Could somebody help me here and also give me some pointers on how to write unit tests in eclipse.
private void handle(final DocumentEvent e) {
    Document doc = e.getDocument();
    try {
       String text = e.getDocument().getText(0, doc.getLength());

       if (text.length() >= maxMessageSize) {
            try {
               component.getHighlighter()
                        .addHighlight(maxMessageSize, text.length() + 1, painter);
            } catch (BadLocationException ex) {
               System.out.println(ex.getMessage());
            }
       } else {
            component.getHighlighter().removeAllHighlights();
       }
    } catch (BadLocationException e1) {
       System.out.println(e1.getMessage());
    }
}

Thanks

Update
For some reason when I running the test case, I'm not getting any coverage at all. Am I doing something wrong here?? Further researching suggests that I need to use test.perform() method to call the method I want to test.. Is that correct?? Can you please suggest something?? Here is the code:
public class TestMaxLength {
  static final int maxMessageSize = 125;
  JTextPane textPane = new JTextPane();
  //***EasyMock varibles****
  private JTextComponent mockComponent;
  private MaxLength classUnderTest;
  private DocumentEvent mockEvent;
  private Document mockDocument;
  private Highlighter mockHighlighter;

  @Before public void setUp() {
    mockComponent = EasyMock.createMock(JTextComponent.class);
    mockEvent = EasyMock.createMock(DocumentEvent.class);
    mockDocument = EasyMock.createMock(Document.class);
    EasyMock.expect(mockEvent.getDocument()).andStubReturn(mockDocument);
    EasyMock.expect(mockDocument.getLength()).andReturn(256);
    mockHighlighter = EasyMock.createMock(Highlighter.class);
    EasyMock.expect(mockComponent.getHighlighter()).andReturn(mockHighlighter);
  }

  @Test public void testSetLength() {
    MaxLength maxListener = new MaxLength(125);
    maxListener.decorate(textPane);
  }

  @Test
  public void testEmptyText() {
    EasyMock.expect(mockDocument.getText(0, 1)).andStubReturn("");
    mockHighlighter.removeAllHighlights();
    EasyMock.replay(mockComponent, mockEvent, mockDocument, mockHighlighter);
    classUnderTest.handle(mockEvent);
    EasyMock.verify(mockComponent, mockEvent, mockDocument, mockHighlighter);
  }
}

The decorate(JtextComponent jComponent) method is present in the class to be tested (MaxLength) and is defined as :
public final void decorate(final JTextComponent c) {
  //TODO throw exception if already decorating
  this.component = c;
  component.getDocument().addDocumentListener(this);
}

#

UPDATE:
@Peter: Managed to find out that it is not the Component class that is the problem but instead I needed asm (http://forge.ow2.org/projects/asm). I've also change the code to combine the 2 methods into 1 method:
public void testEmptyText()
{
maxSizeListener.decorate(mockComponent);
//mockHighlighter.removeAllHighlights();
EasyMock.replay(mockComponent, mockEvent, mockDocument, mockHighlighter);
maxSizeListener.handle(mockEvent);
EasyMock.verify(mockComponent, mockEvent, mockDocument, mockHighlighter);
}

But now I'm having a different error on verify:
java.lang.AssertionError:
Expectation failure on verify:
getHighlighter(): expected: 1, actual: 0
at org.easymock.internal.MocksControl.verify(MocksControl.java:184)
at org.easymock.EasyMock.verify(EasyMock.java:2038)
at net.TestMaxLength.testEmptyText(TestMaxLength.java:98)

This is caused when executing EasyMock.verify() statement on mockComponent.

A: When you write a unit test, you try to test if (in this case) the method does what it is supposed to do. You should not look at the implementation and write your test from that. Instead, you should think about what inputs the method should be able to handle, and what should be the result (returned value and/or side effects) after the method has been called.
Then you should write one or more tests that calls the method with valid and and invalid inputs and make the test confirm that the results matched what you thought would happen.
This was a short and incomplete description, read more at Wikipedia and junit.org.
Here is an old (2005) but working guide to JUnit in Eclipse.

A: I recommend using a mocking framework, such as EasyMock. Mocks allow you to configure dependencies with the desired behaviour for your tests. In your case, you need a mock DocumentEvent and ideally another one for component, which I guess is a class member.
The two aspects to unit testing

*

*how to test, i.;e. the technical details of assembling the right set of objects in the right state required for the test to run properly (aka the _test fixture), and

*what to test, i.e. the scenarios to validate.

How to test
Eclipse supports JUnit out of the box, so you may quickly generate new JUnit testcases (in Project Explorer context menu: New -> (Other ->) JUnit -> JUnit Test Case), then run it by clicking on the Run button.
Setting up the test fixture in your case would look something like this, using EasyMock (and assuming you can pass the component as a constructor parameter to your tested class):
private Component mockComponent;
private ClassUnderTest classUnderTest;
private DocumentEvent mockEvent;
private Document mockDocument;
private Highlighter mockHighlighter;

@Before
public void setUp() {
    mockComponent = createMock(Component.class);
    classUnderTest = new ClassUnderTest(mockComponent);
    mockEvent = createMock(DocumentEvent.class);
    mockDocument = createMock(Document.class);
    expect(mockEvent.getDocument()).andStubReturn(mockDocument);
    expect(mockDocument.getLength()).andReturn(1);
    mockHighlighter = createMock(Highlighter.class);
    expect(mockComponent.getHighlighter()).andReturn(mockHighlighter);
}

@Test
public void testEmptyText() {
    expect(mockDocument.getText(0, 1)).andStubReturn("");
    mockHighlighter.removeAllHighlights();
    replay(mockComponent, mockEvent, mockDocument, mockHighlighter);

    classUnderTest.handle(mockEvent);

    verify(mockComponent, mockEvent, mockDocument, mockHighlighter);
}

This test assumes that maxMessageSize is at least 1 by default - setting maxMessageSize up for the test is left to you as an exercise as the code snippet you published gives no clue for that.
What to test
The method you show gets text from the document associated with the event, then based on its length, it does different things. I would write at least the following unit tests for this:

*

*empty document text with maxMessageSize == 0

*empty document text with maxMessageSize > 0

*nonempty document text with maxMessageSize == text.length()

*nonempty document text with maxMessageSize > text.length()

*nonempty document text with maxMessageSize < text.length() and addHighlight() throwing BadLocationException
Notes

*

*sensing the BadLocationException is a bit tricky, since all it produces is an output to stdout; luckily, you can easily reassign stdout via System.setOut. However, you may want to consider improving exception handling, at least by using a logging framework instead of printing to stdout.

*from the code it seems that other methods (such as removeAllHighlights() and/or getText()) may also throw BadLocationException, however the try-catch blocks are not well organized. I would consider adding more unit tests where those methods throw, and after that, refactoring the exception handling code.

Update

I thought there was something wrong that I was doing...Can you please provide me with the modified/corrected code please???

Your testSetLength method is not really testing anything - you need assert statements (and/or EasyMock verification) in order for your unit tests to actually verify some behaviour. However, it provides the missing clue for setting up the tested class. So I try to unify your two test methods to create one which is hopefully working (I am writing from memory, so I can't guarantee it will all compile and run perfectly at first try) :
  @Test
  public void testEmptyText() {
    // set up the test class with a specific max length
    classUnderTest = new MaxLength(125);
    // this shall be called from inside decorate()
    mockDocument.addDocumentListener(classUnderTest);
    // the mock document shall always return an empty text
    EasyMock.expect(mockDocument.getText(0, 1)).andStubReturn("");
    // we expect this to be called from inside handle()
    mockHighlighter.removeAllHighlights();
    // start replay mode
    EasyMock.replay(mockComponent, mockEvent, mockDocument, mockHighlighter);
    // inject mock component into tested object
    maxListener.decorate(mockComponent);

    // call the tested method
    classUnderTest.handle(mockEvent);

    // verify that all expected calls to the mocks have been made
    EasyMock.verify(mockComponent, mockEvent, mockDocument, mockHighlighter);
  }


text:
Q: Visual Studio encountered an unexpected network error and can't contact the Microsoft account service I confirgured my windows store DEV account couple of days ago. I have developed some store apps and I need to publish it in windows store. When I try to create the App packages using Visual studio 2012 Ultimate It gives me this error
Visual Studio encountered an unexpected network error and can't contact the Microsoft account service
I followed the solution mentioned in this link http://blogs.msdn.com/b/wsdevsol/archive/2013/01/15/visual-studio-2012-throws-an-error-saying-visual-studio-encountered-an-unexpected-network-error-and-can-t-contact-the-microsoft-account-service-when-you-try-to-create-app-packages-for-the-windows-store.aspx. But it didn't work out, still getting the same error.

A: To solve this problem, you need to open the Internet Explorer (not others browsers) and access https://login.live.com/oauth20_desktop.srf. A popup will appear. Check the option "In the future, do not show this warning" and click OK. You should be able to complete you task. For more details, check this post


text:
Q: How to give an object to an array, when two variables of the constructor are missing? Shopping Cart Program: How is it possible to create a new object in an Array (in this case at cart[0]) if the main method gives the constructor 5 variables, but it has only 3 variables in the constructor. It is not allowed to change the main method.
I tried something but I think that won´t work.
public class ShoppingCart {

public Item[] cart;
int temporary;
public ShoppingCart() {

}

 public void addItem(Item toAdd) {

     if(toAdd instanceof Grocery) {

         if(toAdd.pid==1) {

             cart[0]=new Grocery(toAdd.pid, toAdd.signifier, toAdd.pricePerUnit, ((Grocery) toAdd).getExpiryDate(), ((Grocery) toAdd).getPacketCount()+Grocery.packetCount);

         }

         if(toAdd.pid==2) {
            ............

main-method
public class ShoppingMall {

public static void main(String[] args){

    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Ihr digitaler Warenkorb:");

    boolean loop = true;
    int item = 0;
    String action = "";
    int pckg;
    float amount = 0.0f;

    ShoppingCart basket = new ShoppingCart();

    while (loop) {
        System.out.println("\nWelcher Artikel soll bearbeitet werden");
        System.out.println("------------------------------");
        System.out.println("1 Butter");
        System.out.println("2 Milch");
        System.out.println("3 Draht");
        System.out.println("4 Fliesen");
        System.out.println("\nSie haben den Einkauf abgeschlossen?\nWaehlen Sie zwischen: ");
        System.out.println("------------------------------");
        System.out.println("5 Warenkorb ausgeben");
        System.out.println("0 Exit\n");
        System.out.print("Ihre Eingabe bitte: ");

        try{
            item = Integer.valueOf(input.readLine());

            if((item < 5) && (item > 0))
            {
                //System.out.println("\n------------------------------");
                do{
                    System.out.print("Waehlen Sie + fuer hinzufuegen oder - fuer entfernen. ");
                    action = input.readLine();
                }while(!action.equals("+") && !action.equals("-"));
            }

            //if(action.equals("+") || action.equals("-"))
            //{
                switch (item) {
                    case 1: {
                        System.out.print("Wieviele Packungen Butter ? ");
                        pckg = Integer.valueOf(input.readLine());
                        Grocery groc = new Grocery(1,"Butter",1.59f,20180618,pckg);
                        if(action.equals("+"))
                            basket.addItem(groc);
                        else
                            basket.removeItem(groc);
                        break;
                    .....................

A: If I understand your problem correctly, you want to be able to pass 3 values to the Grocery constructor, even though it needs 5.
Try to overload the constructor with three parameters that make the rest of the values default and define a new function that will let you modify the data in a Grocery object, by identifying that object with a key. In your case, the key can be Grocery.pid
Hope this was helpful.


text:
Q: Leaflet maps. map disappears when changing coordinates I've embedded a custom svg map of the office with leafletjs. For some reason works with example coordinates:
As soon as I change this coordinates the map stops displaying on the browser, it disappears.
I'm using html file on the browser. Vanilla JavaScript and leafletjs library, you can try with any svg map you find on the internet. you'll get the same error.
here's the code: https://gist.github.com/Mschemmari/621d04639ff25c3be4d006f315dfa953
Expected result: to have my map displayed with its real latitud and longitude. Actual results: Map is not showing with actual lat Long coordinates.


text:
Q: C# reflection and instantiation - is there a way to do Activator.CreateInstance(myType){ X = x }? I'm not sure of the terminology for this kind of code, but I want to know if it's possible to instantiate variables after the parentheses, but whilst using reflection.
I have a map which gets loaded from an XML file. This is a collection of (int X, int Y, string S) where the X,Y is the position of some terrain, and S is a string representing the type of the terrain. I have a dictionary to pass between the strings and the relevant types; for example one key-value pair might be "Tree", typeof(Tree).
When using reflection, although I know it's possible to instantiate with parameters, the only way I'm comfortable is just by using Activator.CreateInstance(Type t), i.e. with an empty constructor.
When I had the maps hard coded, I would originally instantiate like this (within some i,j for loop):
case: "Tree"
 world.Add( new Tree(i,j) );

Whilst starting to think about reflection and my save file, I changed this to:
world.Add( new Tree() { X = i, Y = j }

However, I realised that this won't work with reflection, so I am having to do the following (Tree inherits from Terrain, and the dictionary just converts the XML save data string to a type):
Type type = dictionary[dataItem.typeAsString];
Terrain t = (Terrain)Activator.CreateInstance(type);
t.X = i;
t.Y = j;
world.Add(t);

I would prefer to do this using something like
Type type = dictionary[dataItem.typeAsString];
world.Add((Terrain)Activator.CreateInstance(type) { X = i, Y = j }

Is there any shortcut like this? I guess if not I could edit world.Add to take an X and Y and cast to Terrain in there to access those variables, but I am still curious as to a) what this {var1 = X, var2 = Y} programming is called, and b) whether something similar exists when using reflection.

A: This syntax is called Object Initializer syntax and is just syntactic sugar for setting the properties.
The code var result = new MyType { X = x } will be compiled to this:
MyType __tmp = new MyType();
__tmp.X = x;
MyType result = __tmp;

You will have to do that yourself using PropertyInfo.SetValue if you know the instantiated type only at runtime or use the normal property setters if the type is known at compile time.

A: The answer is no, because the object initialization syntax you mention (introduced with LINQ in 3.0) is an illusion of the compiler.  As in, when you type this
var foo = new Foo { Bar = "baz" };

the compiler actually converts it into CLS-compliant IL which equates to
var foo = new Foo();
foo.Bar = "baz";

Phil Haack has a great blog post which not only covers the details of this rewriting done by the compiler, but also some side effects it can cause when dealing with types that implement IDisposable
As all of this is nothing but a feint by the compiler, there is no equivalent using reflection (i.e., Activator.CreateInstance(Type t)).  Others will give you workarounds, but in the end there really is no direct equivalent.
Probably the closest generic hack you could manage would be to create a method that accepted an object, then used reflection in order to identify the properties of that object and their respective values in order to perform object initialization for you.  It might be used something like this
var foo = Supercollider.Initialize<Foo>(new { Bar = "baz" });

and the code would be something like (this is off the top of my head)
public sealed class Supercollider
{
    public static T Initialize<T>(object propertySource)
    {
        // you can provide overloads for types that don't have a default ctor
        var result = Activator.CreateInstance(typeof(T));
        foreach(var prop in ReflectionHelper.GetProperties(typeof(T)))
            ReflectionHelper.SetPropertyValue(
                result, // the target
                prop,  // the PropertyInfo
                propertySource); // where we get the value
    }
}

You'd have to get each property from the anonymous object, find a property in your target type with the same exact name and type, then get the value from that property in the anonymous object and set the value of your target's property to this value.  Its not incredibly hard, but its absolutely prone to runtime exceptions and issues where the compiler chooses a different type for the anonymous type's property, requiring you be more specific (e.g., new { Bar = (string)null }), which screws with the elegance of the thing.

A: (T)Activator.CreateInstance(typeof(T), param1, param2, ...);

As described HERE.

A: public sealed class ReflectionUtils
    {

        public static T ObjectInitializer<T>(Action<T> initialize)
        {
            var result = Activator.CreateInstance<T>();
            initialize(result);
            return result;
        }
    }

public class MyModel
{
    public string Name{get;set;}
}

And after that just make the call :
var myModel = ReflectionUtils.ObjectInitializer<MyModel>(m =>
   {
     m.Name = "Asdf"
   });

The advantage is that in this way you will have type safety and use reflection as minimum required, because we all know that reflection is an expensive operation that should be avoided as much as possible.

A: You could create a constructor which takes those arguments, then use
Activator.CreateInstance(type, i, j)
But you won't be able to use the object initialization syntax. Which is just sugar candy for setting the properties.


text:
Q: Disable "Prevent this page from creating additional dialogs" When I show some alert consecutive, checkbox "Prevent this page from creating additional dialogs" appear.
I know it's a browser feature, but i want disable it.
What solution!

A: Since this is a built-in browser feature you can't change it nor there is an option for this on Chrome. Other browsers may have this option but that is unlikely since this prevents alert spamming. You may also find a browser or an older browser version that may have this feature disabled or not have it at all, though I don't recommend using older browsers.
Also If you don't show alerts with much frequency the checkbox doesn't appear.
The best alternative may be to use a javascript/HTML solution prompting the user with a <div> that is above all others, kind of like what LightBox does.


text:
Q: Save check item data to session when page refresh How to save all my check box item after I click on next page?. This is my code to save the data inside session. But after next page, the session data will dissappear.
    Dim StrList As List(Of String) = New List(Of String)()

    For Each r As GridViewRow In GridView1.Rows
        Dim i As Integer = r.RowIndex
        Dim chk As CheckBox = CType(r.FindControl("ChkItem"), CheckBox)

        If chk.Checked = True Then
            Dim HyperLink2 As HyperLink = TryCast(GridView1.Rows(i).FindControl("HyperLink2"), HyperLink)
            StrList.Add(HyperLink2.Text)
        End If
    Next

    Dim countItemList As Integer = StrList.Count
    Dim combindedString As String = String.Join(";", StrList.ToArray())
    Session("itemsList") = combindedString
    Session("itemCount") = countItemList

This is my code to save the data. Its work when I not refresh the page. But otherwise when I do a seacrhing or go to next page.


text:
Q: Break ArrayList into ArrayList of ArrayLists dynamically I am trying to make a method to breakdown an arrayList of objects into multiple arrayLists based on an attribute value of the myObj class.
private static ArrayList<ArrayList<Ticket>> splitList(ArrayList<Ticket> arrayList){
    ArrayList<ArrayList<Ticket>> smallLists = new ArrayList<>();
    for(int i = 0; i < arrayList.size(); i++){
        for(Ticket eachTick: Ticket.getTickets()){
            if(arrayList.get(i).getCategory().equals(eachTick.getCategory())){
                smallLists.add(...);
            }
        }

    }
    return smallLists;
}

If there is a better way to do what I am attempting, please advise me.

A: Are you trying to create a list for each ticket category found in the input list? If that's the case, then I agree with Dawood ibn Kareem: use a map that looks up the proper list based on the category. Something like this:
private static ArrayList<ArrayList<Ticket>> splitList(ArrayList<Ticket> inputList) {
    Map<String, ArrayList<Ticket>> map = new HashMap<>();
    // your ticket categories here
    // (array used for simplicity; you should use a Set, and you should also maintain the valid categories inside your Ticket class, not here)
    String[] categories = new String[] {'a', 'b', 'c' };
    for (int i = 0; i < categories.length; i++) {
        map.put(categories[i], new ArrayList<Ticket>());
    }
    for (int i = 0; i < inputList.size(); i++) {
        Ticket t = inputList.get(i);
        map.get(t.getCategory()).add(t);
    }
    // Convert to list of lists
    return new ArrayList<>(map.values());
}


text:
Q: 500 internal server error when hosted in godaddy windows based server I am using Laravel 5 PHP framework and when I upload to godaddy I get the following PHP error
Parse error:  syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in G:\PleskVhosts\telligentts.com\httpdocs\audit1\public\index.php on line 50

A: Laravel 5
laravel docs
Laravel 5 requirements
PHP >= 5.4, PHP < 7
Check godaddy PHP version and update php version php supported versions


text:
Q: Swiper options is not reactive with vue I am using swiper with vue3 and vite. I have the following options for swiper8.
    <swiper
        :modules="modules"
        :slides-per-view="1"
        :space-between="0"
        :direction="'vertical'"
        :speed="1500"
        :mousewheel="{
        forceToAxis: true,
        sensitivity: 1,
        releaseOnEdges,
      }"
        :height="800"
        :prevent-interaction-on-transition="true"
        @slideChange="onSlideChange"
        @reachEnd="onReachEnd"
    >
        ...irrelevant stuff
    </swiper>

Also, I am controlling the releaseOnEdges with the following code.
    setup() {

    const releaseOnEdges = ref(true)

    const onSlideChange = (swiper) => {
      setTimeout(function () {
        releaseOnEdges.value = false
        console.log('swiper change: ', swiper)
      }, 500);
    }

    const onReachEnd = (swiper) => {
      setTimeout(function () {
        releaseOnEdges.value = true
        console.log('swiper end: ', swiper)
      }, 750)
    }

    return {
      releaseOnEdges,
      onReachEnd,
      onSlideChange,
      modules: [Mousewheel],
    }
    }

The last slide scrolls down so fast and the animation is not smooth. That's what I am trying to solve here.
Now, you see the console log in onSlideChange and onReachEnd. I am logging the swiper object. It's supposed to change the releaseOnEdges to false when onSlideChange happens. But it is always true even though the swiper options are reactive.
So, what am I doing wrong here?


text:
Q: Flatten a matrix into an array containing the index positions of the values Given a numpy matrix, my_matrix.
import numpy as np

my_matrix = np.array([[1.2,2.3,None],[4.5,3.4,9.3]])

How can you efficiently flatten it into the following array containing the index positions of my_matrix?
[[0,0],[0,1],[0,2],[1,0],[1,1],[1,2]]

A: you can try:
rows, cols = my_matrix.shape
[[i, j] for i in range(rows) for j in range(cols)]

output:
[[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2]]

A: You can use numpy.indices() and reshape the returned values a little bit
np.indices(my_matrix.shape).transpose(1, 2, 0).reshape(-1, 2)
# array([[0, 0],
#        [0, 1],
#        [0, 2],
#        [1, 0],
#        [1, 1],
#        [1, 2]])

A: You can create such a list easily with pure python:
from itertools import product
list(product(range(my_matrix.shape[0]), range(my_matrix.shape[1])))

Result is
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]

If you are not using the explicit list but only want to iterate over the indices, leave the list(...) away. This will save memory and computation time, as the indices will be generated when they are used only.
However, if you want to use the result to index a numpy array, it may be more convenient to use np.ix_:
np.ix_(np.arange(my_matrix.shape[0]), np.arange(my_matrix.shape[1]))

Output is
(array([[0],
        [1]]), array([[0, 1, 2]]))


text:
Q: Find $x_i$ and weights such that the following integration rule is exact for all polynomials of degree $\leq 5$ I'm going over an exam I failed. I was told that I can't use the method I used to solve the following question, and I don't know why.
Can you please explain and suggest a correct solution?
Question
Find $x_i$ and $A_i$ such that the following integration rule is exact for all polynomials of degree $\leq 5$:
$$
\int_{1}^{-1}f(x)|x| dx \approx A_0 f(x_0) + A_1 f'(x_1) + A_2 f'(x_2)
$$
My Attempt
I tried to choose $x_i$ as a Gaussian Quadrature (PDF, section 6.6) relative to the weight function $\omega(x) = |x|$ (which satisfies $\omega(x) \geq 0$ for all $x$ so we can use it to define a proper inner product).
Then I wrote a system of linear equations by applying the rule to $P_n(x) = x^n, n \in \{0..5\}$ and trying to solve it for $A_i$. I didn't have time to finish that part so I'm not sure why it doesn't work.
I assume my approach fails because the integration rule uses derivatives of $f$, is that correct?
What would be the correct approach for this problem?
Edit: Extended explanation for my approach
To find $x_i$ we look for a Gaussian Quadrature:

*

*We define the inner product $<f,g> = \int_{-1}^{1}f(x)g(x)|x|dx$. We can do this since $\omega(x) \geq 0$ for all $x$.

*Then we find a basis of orthogonal polynomials relative to that inner product using Gram-Schmidt.

*$x_i$ are the roots of the 3rd degree polynomial we get using this process.

Then we want to find $A_i$:

*

*For $n \in {0..5}$ we write the equation:
$$
P_n(x) = x^n \\
\int_{-1}^{1}P_n(x)|x|dx = A_0P_n(x_0) + A_1P'(x_1) + A_2P'(x_2)
$$

*The only thing we don't know how to calculate is the $A_i$'s so we get a system of linear equations that we can solve to find them.

Thanks! :)

A: A quick work would be as follows.  By symmetry ($x\mapsto -x$ in the integral), we can see that $x_0=0$ and $x_1+x_2=0$.  By integrating with $P_0$, we obtain $A_0=1$.  With $P_1$, we get $A_0+A_1=0$.  By integrating with $P_2$, $\frac{1}{2}=2A_1x_1+2A_2x_2$.  With $P_4$, we get $\frac13=4A_1x_1^3+4A_2x_2^3$.  Thus, $A_1x_1=\frac{1}{8}$ and $A_1x_1^3=\frac{1}{24}$, or $x_1^2=\frac{1}{3}$.  We can assume without loss of generality that $x_1=+\frac1{\sqrt3}$ and $x_2=-\frac1{\sqrt3}$.  Hence, $A_1=+\frac{\sqrt{3}}{8}$ and $A_2=-\frac{\sqrt{3}}{8}$.

A: Due to the fact that both the integration segment $[-1,1]$ and $\omega(x)$ are symmetric to the transformation $x \to -x$, one might look for a quadrature with the same symmetry. That is weights $A_i$ should satisfy (the minus comes from the fact that replacing $x$ with $-x$ also negates the first derivatives):
$$
A_1 = -A_2
$$
and the abscissae should satisfy
$$
x_1 = -x_2 \equiv, \quad x_0 = -x_0 = 0.
$$
Thus letting $A = A_0, B = A_1, \xi = x_1$
$$
\int_{-1}^{1} f(x) |x|dx = A f(0) + B \left(f'(\xi) - f'(-\xi)\right).
$$
Also, since we are already restricting ourselves to symmetric quadratures, we don't need to check every polynomial $x^{k}, k = 0,\dots, 5$, but only those, that are symmetric (there is a theorem for that fact, but it is quite obvious that $\int_{-1}^{1}x^{2m+1}|x|dx = 0$ both for the exact integration and the quadrature rule).
As I said, it is necessary to check only symmetric (even for the case) polynomials $P_1 = x^0 = 1, P_2 = x^2$ and $P_3 = x^4$. That will give three equations for three parameters - quite sane.
$$
\int_{-1}^1 |x| dx = 2\int_0^1 xdx = 1 = A \cdot P_1(0) = A,\quad \Rightarrow A = 1\\
\int_{-1}^1 x^2|x| dx = 2\int_0^1 x^3dx = \frac{1}{2} = B(2\xi + 2\xi) = 4\xi B,\quad \Rightarrow 4\xi B = \frac{1}{2}\\
\int_{-1}^1 x^4|x| dx = 2\int_0^1 x^5dx = \frac{1}{3} = B(4\xi^3 + 4\xi^3) = 8\xi^3 B,\quad \Rightarrow 8\xi^3 B = \frac{1}{3}\\
$$
Thus either $\xi = \frac{1}{\sqrt{3}}, B = \frac{\sqrt{3}}{8}$ or
$\xi = -\frac{1}{\sqrt{3}}, B = -\frac{\sqrt{3}}{8}$. Both gives essentially the same rule
$$
\int_{-1}^1 f(x) |x| dx \approx f(0) + \frac{\sqrt{3}}{8} \left(
f'\left(\frac{1}{\sqrt{3}}\right) - f'\left(-\frac{1}{\sqrt{3}}\right)
\right)
$$


text:
Q: Merging two pandas dataframe with column values I have a df1 which looks like this
  Company  SKU  Sales
1    A      X1   10
2    B      Y1   20
3    C      X1   30
4    D      Y1   40
5    E      X2   50
6    F      Y2   60

I have another df2 which only the list of SKU
    SKU
1    X1
2    Y1

I want to merge these 2 dfs into another dataframe and the resulting dataframe should have the SKUs in the df2
  Company  SKU  Sales
1    A      X1   10
2    B      Y1   20
3    C      X1   30
4    D      Y1   40

I tried Left join but it doesn't seem to be working
df3 = df1.merge(df2,how='Left',on='SKU')

I will appreciate your kind help.

A: I looks like you aren't trying to 'join' the dfs, but rather to select rows from the first where the SKUs match those in the second.
Try something like this:
df1.loc[df1['SKU'].isin(df2.SKU)]

See: Select rows from a DataFrame based on values in a column in pandas