Q: Java BeanUtils Unknown property with underscore (_) I cannot get the property with underscore (ex: User_Name) from a class using BeanUtils.getProperty(bean, property), it always throw error:

"Unknown property 'User_Name' on class 'User'".

But when I debug the bean, it has User_Name property.
BeanUtils.getProperty(bean, propertyName);

The User class is
public class User {
    private String ID;
    private String User_Name;

    public void setID(String ID) {
        this.ID = ID;
    }

    public String getUser_Name() {
        return this.User_Name;
    }

    public void setUser_Name(String user_Name) {
        this.User_Name = user_Name;
    }
}

A: It is a matter of naming convention. You can refer to Where is the JavaBean property naming convention defined? for reference. From section 8.8 of JavaBeans API specification

...
Thus when we extract a property or event name from the middle of an existing Java name, we normally convert the first character to lower case*case 1. However to support the occasional use of all
upper-case names, we check if the first two characters*case 2 of the name are both upper case and if
so leave it alone. So for example,

'FooBah" becomes 'fooBah'
'Z' becomes 'z'
'URL' becomes 'URL'

We provide a method Introspector.decapitalize which implements this conversion rule

Hence for your given class, the property deduced from getUser_Name() and setUser_Name()
is "user_Name" instead of "User_Name" according to *case1. And calling getProperty(bean, "ID") is working according to *case 2.
To solve the problem, please update the naming according to the Java naming convention, we should start with lower case for property and method, and use camelCase instead of snake_case to separate word. Keep in mind that following convention is really important in programming. The following is the updated class as an example.
import java.lang.reflect.InvocationTargetException;

import org.apache.commons.beanutils.BeanUtils;

public class User {
    private String ID;
    private String userName;

    public String getID() {
        return ID;
    }

    public void setID(String ID) {
        this.ID = ID;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public static void main(String[] args)
            throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        User bean = new User();
        bean.setUserName("name");
        System.out.println(BeanUtils.getProperty(bean, "userName"));
    }
}


Q: why we need to use get method inside a java file @RequestMapping(method = RequestMethod.GET) In generally while sending form data from the ui pages we are using method="GET" or method="POST" in the form tag then what is the use of these methods in the server side programs. I am using these methods in spring while calling the methods in the controller @RequestMapping(method = RequestMethod.GET)
Can anyone explain what is the real use of get or post methods in server side code

A: Loosely speaking, if the purpose of your method is to retrieve data from the server use GET. e.g. getting information to display on the client.
If you are sending data to the server use POST. e.g. sending information to the server to be saved on a database somewhere.
There is a limit to the size of data you can send to the server with a GET request.

A: The server side GET or POST is used to specify what the server expects to receive in order to accept the request. The client side GET or POST is used to specify what will be sent to the server. These two must match. You cannot send a GET request when server expects a POST and vice-versa.
When you are building a server application, it is important to know the appropriate request type to use, which by itself is a whole big different topic which you should research if it is you the one that builds the server side part.


Q: Group By dynamic list with Count I'm using a simple case statement to count the occurrences of breakcode in my data and grouping by Seller and SaleDate.
However it seems like an inelegant solution. The breakcode could and quite possibly will expand and I would need to update my code when it does. How can this be done?
Additionally, while using NULL gives me the right answers, I would like to know is there a better approach to how I am counting my instances of breakcode, putting 0 in place of NULL returns the incorrect results?
SELECT seller,
saledate,
COUNT(CASE WHEN breakcode = 1 then 1 ELSE NULL END) as [Perfect],
COUNT(CASE WHEN breakcode = 2 then 1 ELSE NULL END) as [Simple],
COUNT(CASE WHEN breakcode = 3 then 1 ELSE NULL END) as [Medium],
COUNT(CASE WHEN breakcode = 4 then 1 ELSE NULL END) as [Dual1],
COUNT(CASE WHEN breakcode = 5 then 1 ELSE NULL END) as [Dual2],
COUNT(CASE WHEN breakcode = 6 then 1 ELSE NULL END) as [Hard],
COUNT(CASE WHEN breakcode = 7 then 1 ELSE NULL END) as [Difficult]
FROM test
GROUP BY seller, sale date

Thanks.
SQLFiddle: http://sqlfiddle.com/#!3/26f6d/2

A: Final version developed through comments:
DECLARE @sql AS NVARCHAR(MAX)
DECLARE @cols AS NVARCHAR(MAX)

SELECT @cols= ISNULL(@cols + ',','') + QUOTENAME(case when breakname like 'Perfect%' then 'Perfect' else breakname end)
FROM (select * from breaks where breakname not like 'Perfect - 90') a
group by id, breakname
order by id

SET @sql =
  N'SELECT seller, saledate, ' + @cols + '
    FROM (select seller, saledate, case when breakname like ''Perfect%'' then ''Perfect'' else breakname end breakname from test
    inner join breaks on case when breakcode = 8 then 1 else breakcode end = id) derived
    PIVOT(count(breakname)
          FOR derived.breakname IN (' + @cols + ')) AS PVTTable
        ORDER BY seller, saledate'

EXEC sp_executesql @sql

SQL Fiddle


Q: Printing variables with incrementing suffixes What I'm trying to do would be a lot easier to understand by looking at the code:
suffix = 1
prefix1="success"
prefix2="success"
prefix3="success"
prefix4="success"
while suffix<5:
    temp = "prefix"+str(suffix)
    print temp
    suffix+=1

So what I'm trying to do is to print the value of prefix1, prefix2 etc which is "success" as opposed to "prefix1","prefix2" etc. I fully understand why my code is working how it is, but I want to know if there is a way to print the values of the variables prefix+suffix.

A: I think using a dict would make more sense:
d = {
      'prefix1' : 'success',
      'prefix2' : 'success',
      'prefix3' : 'success',
      'prefix4' : 'success'
    }

for i in range(1,5):
    temp = "prefix%s" % i
    print d[temp]


Q: Copying text from RichTextBox to WebBrowser I am trying to copy text from a RichTextBox and paste it into a WebBrowser.
I use this code:
WebBrowser wb = new WebBrowser();
wb.Navigate("about:blank");

richTextBox1.SelectAll();
richTextBox1.Copy();

wb.Document.ExecCommand("Paste", false, null);

wb.Document always shows an empty document. DocumentText gives  \0 and Document.Body is null.
What am I doing wrong?

A: The content of a RichTextBox is not HTML, so an incompatible clipboard format may be part of the issue.  If you are happy with the text only, try assigning the plain text to the clipboard:
Clipboard.SetText(RichTextBox1.Text);

If you want formatted text, you will need to convert the RTF to HTML.  This article may help: http://www.codeproject.com/Articles/27431/Writing-Your-Own-RTF-Converter

A: Because your page html is null,try this example
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            webBrowser1.DocumentText = "";
        }

        void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            webBrowser1.Document.Body.InnerText = richTextBox1.Text;
        }
    }


Q: How can i determine color my drawn line and my drawn image? I have the following code:
private void DrawImage(PaintEventArgs e)
{
    newImage = Image.FromFile(bmpPath);
    e.Graphics.DrawImage(newImage, new Rectangle(0, 0, 200, 200));
    e.Graphics.DrawLine(new Pen(Color.Yellow, 20), 20, 20, 200, 200);

}

How can I find the intersection by color, I mean intersection with my
drawn line and with my drawn image?
private void Button2_Click(object sender, EventArgs e)
{
    Bitmap b = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.Height);
    pictureBox1.DrawToBitmap(b, pictureBox1.ClientRectangle);

    int[,] pixels = new int[pictureBox1.Width, pictureBox1.Height];
    for (int i = 0; i < pictureBox1.Width; i++)
    {
        for (int j = 0; j < pictureBox1.Height; j++)
        {
            if(Color.Black == b.GetPixel(i,j) && Color.Red == b.GetPixel(i,j))
            {
                count++;
            }
        }
    }
}

A: Bitmap have array of every pixel which is an object that contains information about pixels. You can use it for your advantage.
Pixel have 3 channels which contains informations about intensity of red, green, blue as channels.
public Color GetPixel(int x, int y)
{
    Color clr = Color.Empty;

    // Get color components count
    int cCount = Depth / 8;

    // Get start index of the specified pixel
    int i = ((y * Width) + x) * cCount;

    if (i > Pixels.Length - cCount)
        throw new IndexOutOfRangeException();

    if (Depth == 32) // For 32 bpp get Red, Green, Blue and Alpha
    {
        byte b = Pixels[i];
        byte g = Pixels[i + 1];
        byte r = Pixels[i + 2];
        byte a = Pixels[i + 3]; // a
        clr = Color.FromArgb(a, r, g, b);
    }
    if (Depth == 24) // For 24 bpp get Red, Green and Blue
    {
        byte b = Pixels[i];
        byte g = Pixels[i + 1];
        byte r = Pixels[i + 2];
        clr = Color.FromArgb(r, g, b);
    }
    if (Depth == 8)
    // For 8 bpp get color value (Red, Green and Blue values are the same)
    {
        byte c = Pixels[i];
        clr = Color.FromArgb(c, c, c);
    }
    return clr;
}


Q: local variable 'final_result' referenced before assignment I am making an django calculator web app and i got stuck with this error Currently, I am  building  a django powered  UI Caculator app and I got stuck with this error..
I can't able to debug it.
Whatever I'm to trying is not working at all.
I mean i don't why it is telling me final result referenced before it gets assgined while i have already assigned final_result and then i have reference  final_result
Views.py
 def index(request):
    if request.method=="POST":
        values=request.POST['values']
        print(values)
        vals=re.findall(r"(\d+)",values)
        operators=['+','x','÷','-','%']
        opr=[]
        for v in values:
            for o in operators:
                if v==o:
                    opr.append(o)
        print(opr)
        print(re.findall(r"(\d+)",values))
        for o in opr:
            if o=='÷':
                i=opr.index(o)
                res=float(vals[i])/float(vals[i+1])
                vals.remove(vals[i+1])
                opr.remove(opr[i])
                vals[i]=str(res)
                print(vals)
                print(opr)
            elif o=='x':
                i=opr.index(o)
                res=float(vals[i])*float(vals[i+1])
                vals.remove(vals[i+1])
                opr.remove(opr[i])
                vals[i]=str(res)
                print(vals)
                print(opr)
            elif o=='+':
                i=opr.index(o)
                res=float(vals[i])+float(vals[i+1])
                vals.remove(vals[i+1])
                opr.remove(opr[i])
                vals[i]=str(res)
                print(vals)
                print(opr)
            else:
                i=opr.index(o)
                res=float(vals[i])-float(vals[i+1])
                vals.remove(vals[i+1])
                opr.remove(opr[i])
                vals[i]=str(res)
                print(vals)
                print(opr)
        if(len(opr)!=0):
            if opr[0]=='÷':
                result = float(vals[0])/float(vals[1])
            elif opr[0]=='x':
                result = float(vals[0])*float(vals[1])
            elif opr[0]=='+':
                result = float(vals[0])+float(vals[1])
            else :
                result = float(vals[0])-float(vals[1])
        final_result=result
        print(final_result)
    res=render(request,'index.html'{'result':final_result,'values':values})
    return res

A: If request.method is not "POST", then final_result isn't assigned to before it is used the the call to render.

A: You should initialize final_result before
final_result = 0
if request.method == "POST":

Just as @SLDem said.
or else declare it in the function
def index(request, final_result=0)
This will also work.


Q: Pseudo-streaming in Flash - Apache and httpd.conf Setup? I installed and setup JW Player 6 plugin to my wordpress. I am using licensed mod. Anyway If I choose rendering mode:"Flash" i can't skip to time. I installed and activated Apache module h264_streaming and restart apache server, but nothing changed.
Render Mode : "HTML5" is fine but i dont want to use html5. because video is loading slowly , i can skip to time in html5 but skip time is slow too in html5.


Q: three.js: How to get multiple materials working for one mesh I have a big problem with three.js:
I want a simple cube with a different color on each face. I have tried this way:
// set the scene size
    var WIDTH = jQuery('#showcase').width() - 20, HEIGHT = jQuery('#showcase').height();

    // set some camera attributes
    var VIEW_ANGLE = 45, ASPECT = WIDTH / HEIGHT, NEAR = 0.1, FAR = 10000000;

    this.container = jQuery('#showcase');

    this.renderer = new THREE.WebGLRenderer();
    this.camera = new THREE.PerspectiveCamera(VIEW_ANGLE, ASPECT, NEAR, FAR);
    this.scene = new THREE.Scene();
    this.scene.add(this.camera);

    // camera start position
    this.camera.position.z = this.model.radius;
    this.camera.position.y = this.model.cameraY;
    this.camera.position.x = 0;
    this.camera.lookAt(this.scene.position);

    this.renderer.setSize(WIDTH, HEIGHT);
    this.container.append(this.renderer.domElement);

    //Multiple Colors
    var materials = [new THREE.MeshBasicMaterial({
        color : 0xFF0000
    }), new THREE.MeshBasicMaterial({
        color : 0x00FF00
    }), new THREE.MeshBasicMaterial({
        color : 0x0000FF
    }), new THREE.MeshBasicMaterial({
        color : 0xAA0000
    }), new THREE.MeshBasicMaterial({
        color : 0x00AA00
    }), new THREE.MeshBasicMaterial({
        color : 0x0000AA
    })];

    this.geometry = new THREE.CubeGeometry(100, 100, 100, materials);

    this.mesh = new THREE.Mesh(this.geometry,  new THREE.MeshFaceMaterial());

    this.scene.add(this.mesh);

    // create a point light
    this.pointLight = new THREE.PointLight(0xFFFFFF);
    this.pointLight.position = this.scene.position;
    this.scene.add(this.pointLight);

    this.renderer.render(this.scene, this.camera);

But I get this error message:
"Uncaught TypeError: Cannot read property 'map' of undefined" from line 19152 in three.js.
To me it seems to be a problem of the webgl renderer. In most topics I have found here and somewhere else, they were using the canvas renderer. But I want to stay with the webgl renderer.
Does anyone know something about this problem?
Thanks a lot:-)

A: Try this
this.geometry = new THREE.CubeGeometry(100, 100, 100);
this.mesh = new THREE.Mesh(this.geometry, new THREE.MeshFaceMaterial(materials));

A: maybe try to work with an array.
With three.js 49 (dont of if it works with 57) i used this code for a skybox with different materials:
var axes = new THREE.AxisHelper();
scene.add( axes );

var materialArray = [];
    materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'textures/himmel.jpg' ) }));
    materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'textures/himmel.jpg' ) }));
    materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'textures/himmel.jpg' ) }));
    materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'textures/himmel.jpg' ) }));
    materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'textures/himmel.jpg' ) }));
    materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'textures/himmel.jpg' ) }));
    var skyboxGeom = new THREE.CubeGeometry( 5000, 5000, 5000, 1, 1, 1, materialArray );
    var skybox = new THREE.Mesh( skyboxGeom, new THREE.MeshFaceMaterial() );
    skybox.flipSided = true;
    scene.add( skybox );

A: Try this also, applying the vertexcolors.
var geom = new THREE.BoxGeometry(20, 20, 20);
var faceIndices = ['a', 'b', 'c'];
var vertexIndex, point;
mat = new THREE.MeshBasicMaterial({
vertexColors: THREE.VertexColors
});
mesh = new THREE.Mesh(geom, mat);
scene.add(mesh);
geom.faces.forEach(function (face) { // loop through faces
for (var i = 0; i < 3; i++) {
vertexIndex = face[ faceIndices];
point = geom.vertices[vertexIndex];
color = new THREE.Color(
point.x + 0.5,
point.y + 0.5,
point.z + 0.5
);
face.vertexColors[ i ] = [![the output will be as in the attached picture][1]][1]color;
}
});


Q: Anchor Imageview at view bottom on scrollview layout I have a scrollview layout with several linear layouts inside. The last view of the scrollview is an ImageView which I need to appear always at the bottom of the screen.
The content of the view is dynamic, and sometimes the screen does need to be scrolled and sometimes not.
If the screen needs to be scrolled, the ImageView is shown correctly at the bottom. Take a look at the picture. This is an example of a scrolled screen, the imageView is the green bar.

And this is an example of a screen that doesn't need to be scrolled, and as you can see, the image view is shown just below the textview.

And here is my current XML file:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
  >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
      >

       <ImageView
            android:id="@+id/imagen_view11"
            android:layout_width="fill_parent"
            android:layout_height="60dp"
            android:scaleType="fitXY"
            android:src="@drawable/sector1" />

        <ImageView
            android:id="@+id/imagen_view"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:scaleType="fitXY"
            android:src="@drawable/actpercusion" />

        <TextView
            android:id="@+id/titulo_label"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:gravity="center_horizontal"
            android:text="TextView TextView TextView TextView"
            android:textSize="25sp"
            android:textStyle="bold" />

<TextView
        android:id="@+id/lugar_label"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="TextView" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

   <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:gravity="right" >

        <ImageButton
            android:id="@+id/boton_web"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_alignParentRight="true"
            android:scaleType="fitXY"
            android:src="@drawable/web"
            android:text="Button web" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@+id/boton_web"
            android:orientation="vertical" >

            <ImageButton
                android:id="@+id/boton_mapa"
          android:layout_width="80dp"
            android:layout_height="80dp"
            android:scaleType="fitXY"
            android:src="@drawable/maps"
            android:onClick="openMapa"
                android:text="Button mapa" />
        </LinearLayout>
    </RelativeLayout>

</LinearLayout>

<TextView
    android:id="@+id/descripcion_texto"
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:text="TextView" />
 <ImageView
            android:id="@+id/imagen_v"
            android:layout_width="fill_parent"
            android:layout_height="60dp"
            android:scaleType="fitXY"
            android:layout_alignParentBottom="true"
            android:src="@drawable/sector3" />

    </LinearLayout>

</ScrollView>

I would need to change my layout file so that the image view always appears at the bottom of the screen, independently if the screen needs to be scrolled or not.
Any help is welcome.

A: You will need to use android:fillViewport
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scroller"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true" >

See this blog page written by Romain Guy.


Q: Objective-C retain counts clarification I kind of understand what's retain counts for. But not totally. I looked on google a lot to try to understand but still I don't.
And now I'm in a bit of code (I'm doing iPhone development) that I think I should use them but don't know totally how.
Could someone give me a quick and good example of how and why using them?
Thanks!

A: If you haven't already I highly recommend you familiarize yourself with the Memory Management Programing Guide from Apple
In there you will find a section specifically on retain counts

A: The best explanation I ever heard was from Aaron Hillegass:
Think of the object as a dog.  You need a leash for a dog to keep it from running away and disappearing, right?
Now, think of a retain as a leash.  Every time you call retain, you add a leash to the dog's collar.  You are saying, "I want this dog to stick around."  Your hold on the leash insures that the dog will stay until you are done with it.
Think of a release as removing one leash from the dog's collar.  When all the leashes are removed, the dog can run away.  There's no guarantee that the dog will be around any longer.
Now, say you call retain and put a leash on the dog.  I need the dog, too, so I walk along with you and start training him.  When you are done with the dog, you call release and remove your leash.  There are no more leashes and the dog runs away, even though I was still training him!
If, instead, I call retain on the dog before I start training him, I have a second leash on the collar.  When you call release and remove your leash, I still have one and the dog can't go away just yet.
Different objects can "own" the dog by calling retain and putting another leash on its collar.  Each object is making sure that the dog doesn't go away until it is done with it.  The dog can't go away until all of the leashes have been removed.
Autorelease pools get more complicated, but simplistically you can think of calling autorelease as handing your leash to a trainer.  You don't need the dog anymore, but you haven't removed your leash right away.  The trainer will take the leash off later; there is still no guarantee that the dog will be around when you need him.


Q: Error on setting "user-type" type: org.jadira.usertype.dateandtime.joda.PersistentDateTime I am new on Grails (2.4.1). I am trying to use joda time (1.5). When I put the script below to my Config.groovy an error occurrs.
grails.gorm.default.mapping = {
    "user-type" type: org.jadira.usertype.dateandtime.joda.PersistentDateTime, class: org.joda.time.DateTime
    "user-type" type: org.jadira.usertype.dateandtime.joda.PersistentLocalDate, class: org.joda.time.LocalDate
    // … define as many other user type mappings as you need
}

error: Error | 2014-07-12 23:45:31,632 [localhost-startStop-1] ERROR
  context.GrailsContextLoaderListener  - Error initializing the
  application: Error creating bean with name
  'transactionManagerPostProcessor': Initialization of bean failed;
  nested exception is
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'transactionManager': Cannot resolve reference
  to bean 'sessionFactory' while setting bean property 'sessionFactory';
  nested exception is
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'sessionFactory': Invocation of init method
  failed; nested exception is java.lang.NoClassDefFoundError:
  org/hibernate/engine/SessionImplementor Message: Error creating bean
  with name 'transactionManagerPostProcessor': Initialization of bean
  failed; nested exception is
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'transactionManager': Cannot resolve reference
  to bean 'sessionFactory' while setting bean property 'sessionFactory';
  nested exception is
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'sessionFactory': Invocation of init method
  failed; nested exception is java.lang.NoClassDefFoundError:
  org/hibernate/engine/SessionImplementor

etc.

A: I fixed the same error by upgrading the Jadira Usertype library dependency that the plugin was using.
The Joda Time plugin recommends "org.jadira.usertype:usertype.jodatime:1.9", which only works for Hibernate 3. Try switching to "org.jadira.usertype:usertype.core:3.2.0.GA" when using Hibernate 4.


Q: Accessing a value from Server.R into .js file I think's it's quite an easy one but I can't find a way to solve it myself.
I'd like to access the value of a variable in my Server.R file (I'm using Shiny) in my javascript file. My var "i" in myFile.js should take the value of my R variable "number". How should I proceed ?
Example :
Server.R
...
number <- 5
...

myFile.js
...
var i = ??? // var i = number *is not working*
...

Thanks for your help,
Matt

A: Thanks to jdharrison, it works when I add the following code in myFile.js :
Server.R
number <- 5
observe({
   session$sendCustomMessage(type='myCallbackHandler', number)
})

myFile.js
var i ;
Shiny.addCustomMessageHandler("myCallbackHandler",
    function(number) {
     i = number;
    }
);

var i now takes the value 5 in my javascript file.


Q: SQL JOB Output File - Remove Header I am trying to create a job that outputs the data into a file for manipulation later. I can easily output the file In the Job Type I have it set up for T-SQL for my query and this is the advanced tab for the Job step.

It's working fine, except for the data that is being exported is coming out with a header, any ideas how I can get rid of this?

A: Thanks to AlwaysLearning for pointing me in the right direction, went with the PowerShell solution
Invoke-Sqlcmd

Thanks again!!


Q: How to use 'strict' mode in Chrome 'JavaScript Console' I am practicing JavaScript on Chrome's 'JavaScript Console' ( version: 35.0) and I am unable to use the 'use strict' clause as expected.
For the following code snippet :
var obj={x:1,y:2}

//Define new property with 'writable' flag as false.
Object.defineProperty(obj, "z", {value:3, writable:false, enumerable:false, configurable:false})

// Try to change the property 'z',
"use strict"; obj["z"]=4

Output: 4

As per my understanding, changing value of a 'non-writable' property will silently fail in non-strict mode and throw 'TypeError' in strict mode, But I don't see the exception.
console.log(obj)

Object {x: 1, y: 2, z: 3}

Even though the property value is not changed but I am expecting a exception.
Please correct if I am doing something wrong ?

A: The easiest way to use strict mode is to use an IIFE (immediately Invoked Function Expression) like so:
(function()
{
    'use strict';
    var foo = 123;//works fine
    bar = 345;//ReferenceError: bar is not defined
}());

To create a new-line in the console, use shift + enter, or write your code in a separate editor first, then copy-paste it to the console. Setting up a fiddle is all fine and dandy, but just test your code with the markup it was written for (ie: just clear the browser cache and test).
However, I'd urge you to install node.js, still. It's a lot easier to test your code, or validate it (both syntactically and coding-style wise) using JSHint. There are also a lot of ways to examine and your code that run out of node.js, so it's a really good development tool to have


Q: How to check session timeout configured in Jboss application I am using a spring based application with MS SQL server and using hibernate or native sql to fetch data from the database. However one of the problems I am facing is session timeout after around 2 minutes. The session timeout configured for the application in web.xml is 20 minutes. Ideally if session is idle it does not get logged out. But whenever there is a database related operation that would take more than 2 minutes to execute the session is killed. Can someone help me with this?
Using Jboss 7.3


Q: Create grid data in SAS using info from another dataset I need to get a dataset of a uniform grid 20x20 using info from SASHELP.CARS so that x and y variables are obtained as follows:
do y = min(weight) to max(weight) by  (min(weight)+max(weight))/20;
    do x =  min(horsepower) to max(horsepower)  by (min(horsepower)+max(horsepower))/20;
        output;
    end;
end;

Weight and HorsePower are variables of SASHELP.CARS. Furthermore the grid dataset has to have two more columns  EnginSizeMean LengthMean with the same value in each row that equals mean(EnginSize) and mean(Length) from SASHELP.CARS (need all this to build dependency graph for regression model).

A: First calculate the statistics you need to use.
proc summary data=sashelp.cars ;
  var weight horsepower enginesize length ;
  output out=stats
    min(weight horsepower)=
    max(weight horsepower)=
    mean(enginesize length)=
    / autoname
  ;
run;

Then use those values to generate your "grid".
data want;
  set stats;
  do y = 1 to 20 ;
    weight= weight_min + (y-1)*(weight_min+weight_max)/20;
    do x =  1 to 20 ;
      horsepower  =  horsepower_min + (x-1)*(horsepower_min+horsepower_max)/20;
      output;
    end;
  end;
run;


Q: XML to Powershell Hashtable <Test>
    <TLC>FWE</TLC>
    <Crew3LC>KMU</Crew3LC>
    <MyText>Hello World</MyText>
</Test>

Hello there,
above you see me .xml with the name "test.xml". Down below you see my powershell beginnings.
What I want do to is the following, but I don't know where exactly to begin.
I want to retrieve the data from the .xml file and save the values into my hashtable. The hashtable itself is more like a template, which needs to be filled.
The XML has got the same naming like the hashtable TLC = TLC etc, but I need the Value from the XML in my hashtable.
I would do it with foreach and a -matching operator and my filtered selections (Hashkey, XML Name, XML Name Value).
Matching the Hashkey with XML Name and if $true save XML.Name.Value to Hashtable.
I Hope you get my point... I tried some of my knowledge but everything faild so far.
My you guys could help me?!
# XML Path
$XMLSource = "C:\Test\Test.xml"

# Tempalte Hashtable
$XMLTemplatevalues = @{

    TLC      = 'TLC'
    Crew3LC  = 'Crew3LC'
    MyText   = 'MyText'

}

# Get XML Content
[xml]$GetXMLContent = Get-Content $XMLSource

#HashKey
$XMLTemplatevalues.Keys

#XML Name
$GetXMLContent.DocumentElement.ChildNodes.Name

#XML Name - Value
$GetXMLContent.DocumentElement.ChildNodes.'#text'

A: A simple solution that works with simple documents such as the one in your question (PSv4+):
$xmlDoc = [xml] (Get-Content -Raw "C:\Test\Test.xml")

# Initialize the results hashtable; make it ordered to preserve
# input element order.
$ht = [ordered] @{}

# Loop over all child elements of <Test> and create matching
# hashtable entries.
$xmlDoc.Test.ChildNodes.ForEach({ $ht[$_.Name] = $_.InnerText })

# Output the resulting hashtable.
$ht

With your sample document this yields:
Name                           Value
----                           -----
TLC                            FWE
Crew3LC                        KMU
MyText                         Hello World


Q: How can I render an image to the browser rather than force it to download? I'm using Azure blob storage to house images and DOMPdf to create PDF files. The issue I'm facing is that DOMPdf will not "Download files" to display them. My current controller, contacts Azure blob storage, grabs the file and spits it out as a download.
Instead, I have tried to use the response()->file() method in Laravel to display the image instead:
// Assume $file holds the file content from Azure Blob Storage
\Illuminate\Support\Facades\File::append(Storage::disk('local')->path("chunks/{$fileToken}"), $file);
$mimeType = mime_content_type(Storage::disk('local')->path("chunks/{$fileToken}"));

# Check if we can render this as an image
if (in_array($mimeType, ['image/jpeg','image/gif','image/png','image/bmp','image/svg+xml'])) {
    $headers = [
        'Content-Type' => $mimeType,
        'Content-Disposition' => sprintf('inline; filename="%s"', $realPath->filename)
    ];

    $response = response()->file(Storage::disk('local')->path("chunks/{$fileToken}"), $headers);

    # Delete from local disk
    \Illuminate\Support\Facades\File::delete(Storage::disk('local')->path("chunks/{$fileToken}"));

     return $response;
}

# Delete from local disk
\Illuminate\Support\Facades\File::delete(Storage::disk('local')->path("chunks/{$fileToken}"));

// Do normal download functionality

Now, the mime_content_type successfully identifies the PNG I am trying, it creates the file in the chunks directory and if I remove the delete, I can open it as the PNG perfectly fine. The issue I'm getting is the browser is not rendering the image. Infact, it is rendering the headers?

How can I render this image out to the browser so I can then access the image in DOMPdf?


Q: Develop PhoneGap app for old android device I have a simple, but useful app for an old android device I want to develop with Cordova PhoneGap. Going through their tutorial, by default, the current version of cordova requires android level 14 api to build apps, but I've done the following to get the app to build on my old 2.3.6 device...
In /config.xml add the following in the platform->android tag
<platform name="android">
      <allow-intent href="market:*" />
      <preference name="android-minSdkVersion" value="10" />
      <preference name="android-targetSdkVersion" value="10" />
</platform

Edit these lines in the /platforms/android/AndroidManifest.xml file
<manifest android:hardwareAccelerated="true" android:versionCode="10000" android:versionName="1.0.0" package="fi.blogspot.codinginthecold" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">

<uses-sdk android:minSdkVersion="10" android:targetSdkVersion="10" tools:overrideLibrary="org.apache.cordova" />

Like I said, the HelloWorld app compiles on the device without error, but when I actually run the app, it says the app has unfortunately stopped.
My question: As the above method failed to run the simplest app, what is best way to develop PhoneGap apps for old android devices?
Thanks.


Q: Getting data from JSON with React mapping I know this is probably a question that is easily answered, but I cannot figure it out after a few hours. I am trying to map over this JSON but it keeps saying "props.shows.map" is not a function, however the same works for another bit of data. I am trying to get things like 'id' and 'name' from the data.
The mapping works with this link: https://api.tvmaze.com/search/shows?q=\%22Terrance%20House\%22
Here is the JSON that doesn't work/can't seem to get the information from: https://api.tvmaze.com/shows/34275/episodes
import Layout from '../components/MyLayout'
import fetch from 'isomorphic-unfetch'
import Link from 'next/link'

const ShowLink = ({ show }) => (

          <Link as={`/episode/${show.id}`} href={`/episodes/id=${show.id}`}>
            {show.name}
          </Link>

)
/*

{props.show.name}

{props.show.summary.replace(/<[/]?p>/g, '')}

*/
const Post =  (props) => (
    <Layout>

Terrace House Episodes

            {props.shows.map(({show}) => (
                <ShowLink key={show} value={show} />
            ))}

    </Layout>
)

Post.getInitialProps = async function () {
   //const { id } = context.query
   //const res = await fetch(`https://api.tvmaze.com/shows/${id}`)
   //const show = await res.json()
   //const res = await fetch(`http://api.tvmaze.com/seasons/34275/episodes`);
    const res = await fetch('https://api.tvmaze.com/shows/34275/episodes');
    const data = await res.json()

    return {
      shows: data
    }
}

export default Post

A: The problem is you are attempting to destructure a property (namely the 'show' property) which doesnt exist in your json object when you make your map call.
Heres an example of destructuring (in case you arent familiar):
const example= {
  show: 'Seinfeld',
};

const { show } = example;

In the last line the show property is being taken from the example object and assigned to a variable named show (so the variable show would hold the value 'Seinfeld').
In your code below you are also destructuring a property named show from each json object in the map function call:
props.shows.map(({show}) => (
            <ShowLink key={show} value={show} />
        ));

In the working json each object has a show: property which itself is an object containing data you want.
In the not working json there is no show: property so you are attempting to access a property that doesnt exist which would return null.
So to solve the issue  in the case of the not working url, you simply need to remove the destructuring:
props.shows.map((show) => (
            <ShowLink key={show} value={show} />
        ));


Q: How can I debug the vim part of the poshcomplete vim plugin? As I love vim, I found two posts that are interesting in order to use PS with vim:

*

*Help starting vim from PSISE with the file edited in PSISE.

*

*I found this following line:
$psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add("edit with Vim",{$cur=$psISE.CurrentFile; saps "C:\Program Files (x86)\vim\vim74\gvim.exe" $cur.FullPath -wait; $psise.currentpowershelltab.files.remove($cur); $psISE.currentpowershelltab.files.add($cur.fullpath) },'Ctrl+Alt+v')

*open PSISE:
psise> ise $profile

Paste the line in the file that PSISE opens. After that you can open the current file with vim by pressing Ctrl-Alt-V.

*poshcomplete helps to complete PowerShell language once in vim.

*

*I've installed the poshcomplete vim plugin. I've installed webapi-vim and vimproc.vim as per this link.

PROBLEM:
After starting the server with the command
:call poshcomplete#StartServer()

everything is OK. The function is found in poshcomplete, the variables for port or other detail were declared.
If then I try to call the completion Ctrl-X,Ctrl-O after, for instance, the word "write" I receive the following error:

: omni completion(^O^N^P) Pattern not found.

But if I check what poshcomplete is returning from server (I use httprequester with the line "http://localhost:1234/poshcomplete?text=write") I can see that the answer from the web server is correct. Indeed I can see all the commands that have "write" in it.
I don't understand what's going on from the vim side that recover that data to show it for completion, because I had two times the plugin working, but then it stopped working.
I think there's a problem of sync between the moment the result is exposed by the server and the moment vim try to get it. I'm probably wrong, but I'd like to correct this if someone can help.

A: Could you modify autoload/poshcomplete.vim in your vimfiles directory like this?
  let res = webapi#http#post("http://localhost:" . g:PoshComplete_Port . "/poshcomplete/",
  \                                  {"text": buffer_text}, {}, s:noproxy_option)
+ echo 'Response: ' . res.content
  return webapi#json#decode(res.content)

Press <C-X><C-O> with this code, show response from server.


Q: Updating and Resolving Comments in Google Sheet I would like to update/resolve comments on google spreadsheets using a service account. Currently following the GDrive V3 API guide;
The API explorer on the page works well but I am unable to replicate it on Python.
GET and LIST methods work fine but PATCH keeps returning the old content and wouldn't update.
Heres my code:
from googleapiclient.discovery import build
from google.oauth2 import service_account

credentials_file = './.config/gspread/service_account.json'
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.file','https://www.googleapis.com/auth/drive.appdata']
credentials = service_account.Credentials.from_service_account_file(credentials_file, scopes=scope)
service = build('drive', 'v3', credentials = credentials)
service.comments().update(commentId=<<commentId>>, fileId=<<fileId>>, fields='content', body={'content': 'new comment', 'resolved': True}).execute()

>>> returns {'content': 'old comment'}

Any idea what's wrong? Appreciate your help!

A: As suggested by Mateo, patching of comments works when using the OAuth 2.0 Client Credentials (Secret key file)


Q: find time shift between two similar waveforms I have to compare two time-vs-voltage waveforms. Because of the peculiarity of the sources of these waveforms, one of them can be a time shifted version of the other.
How can i find whether there is a time shift? and if yes, how much is it.
I am doing this in Python and wish to use numpy/scipy libraries.

A: This function is probably more efficient for real-valued signals. It uses rfft and zero pads the inputs to a power of 2 large enough to ensure linear (i.e. non-circular) correlation:
def rfft_xcorr(x, y):
    M = len(x) + len(y) - 1
    N = 2 ** int(np.ceil(np.log2(M)))
    X = np.fft.rfft(x, N)
    Y = np.fft.rfft(y, N)
    cxy = np.fft.irfft(X * np.conj(Y))
    cxy = np.hstack((cxy[:len(x)], cxy[N-len(y)+1:]))
    return cxy

The return value is length M = len(x) + len(y) - 1 (hacked together with hstack to remove the extra zeros from rounding up to a power of 2). The non-negative lags are cxy[0], cxy[1], ..., cxy[len(x)-1], while the negative lags are cxy[-1], cxy[-2], ..., cxy[-len(y)+1].
To match a reference signal, I'd compute rfft_xcorr(x, ref) and look for the peak. For example:
def match(x, ref):
    cxy = rfft_xcorr(x, ref)
    index = np.argmax(cxy)
    if index < len(x):
        return index
    else: # negative lag
        return index - len(cxy)

In [1]: ref = np.array([1,2,3,4,5])
In [2]: x = np.hstack(([2,-3,9], 1.5 * ref, [0,3,8]))
In [3]: match(x, ref)
Out[3]: 3
In [4]: x = np.hstack((1.5 * ref, [0,3,8], [2,-3,-9]))
In [5]: match(x, ref)
Out[5]: 0
In [6]: x = np.hstack((1.5 * ref[1:], [0,3,8], [2,-3,-9,1]))
In [7]: match(x, ref)
Out[7]: -1

It's not a robust way to match signals, but it is quick and easy.

A: scipy provides a correlation function which will work fine for small input and also if you want non-circular correlation meaning that the signal will not wrap around. note that in mode='full' , the size of the array returned by signal.correlation is sum of the signal sizes minus one (i.e. len(a) + len(b) - 1), so the value from argmax is off by (signal size -1 = 20) from what you seem to expect.
from scipy import signal, fftpack
import numpy
a = numpy.array([0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3, 4, 3, 2, 1, 0, 0, 0, 0, 0])
b = numpy.array([0, 0, 0, 0, 0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3, 4, 3, 2, 1, 0])
numpy.argmax(signal.correlate(a,b)) -> 16
numpy.argmax(signal.correlate(b,a)) -> 24

The two different values correspond to whether the shift is in a or b.
If you want circular correlation and for big signal size, you can use the convolution/Fourier transform theorem with the caveat that correlation is very similar to but not identical to convolution.
A = fftpack.fft(a)
B = fftpack.fft(b)
Ar = -A.conjugate()
Br = -B.conjugate()
numpy.argmax(numpy.abs(fftpack.ifft(Ar*B))) -> 4
numpy.argmax(numpy.abs(fftpack.ifft(A*Br))) -> 17

again the two values correspond to whether your interpreting a shift in a or a shift in b.
The negative conjugation is due to convolution flipping one of the functions, but in correlation there is no flipping. You can undo the flipping by either reversing one of the signals and then taking the FFT, or taking the FFT of the signal and then taking the negative conjugate. i.e. the following is true: Ar = -A.conjugate() = fft(a[::-1])

A: It depends on the kind of signal you have (periodic?…), on whether both signals have the same amplitude, and on what precision you are looking for.
The correlation function mentioned by highBandWidth might indeed work for you.  It is simple enough that you should give it a try.
Another, more precise option is the one I use for high-precision spectral line fitting: you model your "master" signal with a spline and fit the time-shifted signal with it (while possibly scaling the signal, if need be).  This yields very precise time shifts.  One advantage of this approach is that you do not have to study the correlation function.  You can for instance create the spline easily with interpolate.UnivariateSpline() (from SciPy).  SciPy returns a function, which is then easily fitted with optimize.leastsq().

A: Here's another option:
from scipy import signal, fftpack

def get_max_correlation(original, match):
    z = signal.fftconvolve(original, match[::-1])
    lags = np.arange(z.size) - (match.size - 1)
    return ( lags[np.argmax(np.abs(z))] )

A: If one is time-shifted by the other, you will see a peak in the correlation. Since calculating the correlation is expensive, it is better to use FFT. So, something like this should work:
af = scipy.fft(a)
bf = scipy.fft(b)
c = scipy.ifft(af * scipy.conj(bf))

time_shift = argmax(abs(c))

A:
Blockquote

(A very late answer) to find the time-shift between two signals: use the time-shift property of FTs, so the shifts can be shorter than the sample spacing, then compute the quadratic difference between a time-shifted waveform and the reference waveform. It can be useful when you have n shifted waveforms with a multiplicity in the shifts, like n receivers equally spaced for a same incoming wave. You can also correct dispersion substituting a static time-shift by a function of frequency.
The code goes like this:
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft, ifft, fftshift, fftfreq
from scipy import signal

#  generating a test signal
dt = 0.01
t0 = 0.025
n = 512
freq = fftfreq(n, dt)

time = np.linspace(-n * dt / 2, n * dt / 2, n)
y = signal.gausspulse(time, fc=10, bw=0.3) + np.random.normal(0, 1, n) / 100
Y = fft(y)
# time-shift of 0.235; could be a dispersion curve, so y2 would be dispersive
Y2 = Y * np.exp(-1j * 2 * np.pi * freq * 0.235)
y2 = ifft(Y2).real

# scan possible time-shifts
error = []
timeshifts = np.arange(-100, 100) * dt / 2  # could be dispersion curves instead
for ts in timeshifts:
    Y2_shifted = Y2 * np.exp(1j * 2 * np.pi * freq * ts)
    y2_shifted = ifft(Y2_shifted).real
    error.append(np.sum((y2_shifted - y) ** 2))

# show the results
ts_final = timeshifts[np.argmin(error)]
print(ts_final)

Y2_shifted = Y2 * np.exp(1j * 2 * np.pi * freq * ts_final)
y2_shifted = ifft(Y2_shifted).real

plt.subplot(221)
plt.plot(time, y, label="y")
plt.plot(time, y2, label="y2")
plt.xlabel("time")
plt.legend()

plt.subplot(223)
plt.plot(time, y, label="y")
plt.plot(time, y2_shifted, label="y_shifted")
plt.xlabel("time")
plt.legend()

plt.subplot(122)
plt.plot(timeshifts, error, label="error")
plt.xlabel("timeshifts")
plt.legend()

plt.show()

See an example here


Q: SCSS + Vue Components I am using <style lang="scss"> inside my single file Vue components. But in every single component using my color variables, I need to import the file, ie: @import "./../../../sass/variables";. I am using Laravel Mix to compile the sass + js.
Is there any way to make the varaible accessible without needing to import them?

A: Please check this related issue on github, I think it has the right answer for you:
https://github.com/vuejs/vue-loader/issues/328
Specially look for mister shaun-sweet's answer.


Q: Access to the webpage was denied Django template
{{image.name|slice:":25"}}

settings.py
MEDIA_ROOT = '/tmp/'
MEDIA_URL = '/media/'

urls.py
 (r'^media/(?P<path>.*)$', 'incident.views.media_serve_protected'),

def media_serve_protected(request, path):
    if path.startswith("{id}/".format(id=request.user.id)):
        return serve(request, path, settings.MEDIA_ROOT)
    else:
        return HttpResponseForbidden()

I am able to upload the images.The uploaded images are get saved in tmp folder.I can see the image name with image url,but for viewing if i click the image url i am getting the error "Access to the webpage was denied You are not authorized to access the webpage at http://192.168.100.12/media/root/16/20130816235304-photo0015.jpg. You may need to sign in."

A: Your media_serve_protected function is returning a Forbidden response if the url does not start with media/<id>. But your url is in the form media/root/<id>.


Q: Can't access parent form's button properties through user control form I have parent form called MainBackground and a user control named LoginUI. LoginUI is docked into the MainBackground.
I need to change enability of a button (InfoButton) located in parent form to "true" when user clicks on the button "Log in" in the control form.
But I can't access the parent button's properties.
Control form's button clicking event code:
private void button1_Click(object sender, EventArgs e)
        {
            MainBackground.infoButton.Enabled = true;
        }

I tried solving it with parent controls, but still it doesn't seem to work.
Thanks for any help!

A: You can't access MainBackground.infoButton from LoginUI because infoButton is not static.
to solve this you could inject MainBackground trough a property like the example below
public partial class LoginUI : UserControl
{
    public MainBackground MainBackground { get; set; }
    ...
}

in MainBackground you should initalize your LoginUI.MainBackground propery
loginUI1.MainBackground = this;

Make sure to make infoButton public
by setting the modifiers property to public
Now you can access MainBackground.loginUI1
private void login_Click(object sender, EventArgs e)
{
   MainBackground.InfoButton.Enabled = true;
}

A: The method described in your question of Enabling the MainBackground forms InfoButton when the Login button is pressed is a common action. However, instead of directly binding the two items where the LoginUI Control is now forever bound to the MainBackground Form, you should de-couple the two by using Events.
The LoginUI Control should publish an event, perhaps called, LoginClicked. The MainBackground form can then subscribe to this event and execute whatever actions are required when the Login button is clicked.
In the LoginUI Control, declare an event:
    public event EventHandler LoginClicked;

And, raise it whenever the Login button is pressed:
    private void login_Click(object sender, EventArgs e)
    {
        OnLoginClicked(EventArgs.Empty);
    }

    protected virtual void OnLoginClicked(EventArgs e)
    {
        EventHandler handler = LoginClicked;
        if (handler != null)
        {
            handler(this, e);
        }
    }

Finally, in the MainBackground form class, subscribe to the LoginClicked event
    loginUI.LoginClicked += this.loginUI_LoginClicked;

Handle the LoginClicked event like this:
    private void loginUI_LoginClicked(object sender, EventArgs e)
    {
        InfoButton.Enabled = true;
    }


Q: How can I handle some special character being returned as such on my razor page? I have the following razor syntax on my view page that will return a label as the following format: "Recherce d  & # 3 9 ;  address" but it should be: "Recherce d'address". This is caused by a é in my translation file.

@xxx.Tools.Language.Translate(xxx.Tools.Language.Keys.Address_Search,
ViewBag):

I'm not sure how to resolve the following syntax to prevent this. My intuition was to use HTML.Encode.Text but I'm getting lost with the syntax...

A: @Html.Raw() is your friend here. See: https://learn.microsoft.com/en-us/aspnet/core/mvc/views/razor?view=aspnetcore-2.2
Note that this presents a bit of a security risk in that if a user enters an address containing JavaScript, iFrame, etc they can produce an undesired effect.


Q: LoadLibrary fails with lasterror 0x43 The network name cannot be found My program dynamically loads a number of DLL's using LoadLibrary and (on literally all machines) these load successfully, on one machine some of these DLL's do not get loaded.  I added code to trace lasterror and this reports "0x43 The network name cannot be found.".
The machine in question is running Windows 7 Enterprise x64, the DLL is a 32 bit DLL, this shouldn't be an issue and (in fact) this is my development environment.
I also tried converting the name of the DLL (which includes the path) to a short filename and used that in the call to LoadLibrary, I still got the same error.
Any ideas?
//*eggbox

A: Download Procmon let it run and filter for you dll name. This will immediately give you the locations where the dll was searched and which access path did return 0x43.
You get even the call stacks if you have the pdbs for your code as well (C/C++ only no managed code).

A: Run the program through Dependency Walker in its Profile mode and let that fine tool tell you exactly what is going wrong.


Q: Lengthy Japanese Filenames sent as attachment using javamail are getting corrupted We are sending files with lengthy Japanese filenames ( >30 characters) as attachments with mails.
We are using Javamail to send mails. Before adding the attchment to the mail, the fielnames are being encoded in Shift-JIS using the following piece of code.
fileName=MimeUtility.encodeText(fileName,"SJIS",null);
This however works fine if the name of the file is small (Japanese). It works fine in windows, not in unix. Even I tried with utf-8 encoding as well.
Any pointers/solutions to the above problem?
Thank you,


Q: How to fix layout management I'm doing a clone of Minesweeper in Java. Everything was fine, but I wanted to add a counter at the top. And now, some buttons are off the screen. What layouts I have to change to repair it?
Before adding counter:
(https://i.imgur.com/cSKmCGr.jpg)
After adding "counter"
(https://i.imgur.com/fbMQqQz.jpg)
And here's my code:
public static JPanel generate() {
            i2w = row*row-ilosc_min;

            przyc = new Sap[row][row];
            JPanel all = new JPanel();      //panel that contains counter and buttons
            JPanel licznik = new JPanel();  //Counter
            licznik.setBackground(Color.red);
            licznik.setPreferredSize(new Dimension(MyFrame.wym-50, 50));    //counter takes 50 px height and full width of frame

            all.add(licznik);

            JPanel panel = new JPanel();    //Buttons panel
            panel.setVisible(true);
            panel.setLayout(new GridLayout(row, row));

            for(int x = 0; x < row; x++) {  //creating buttons
                for(int y = 0; y < row; y++) {
                    Sap sp = new Sap(x, y); //My buttons that extends JButton
                    przyc[x][y] = sp;
                    panel.add(sp);          //Adding button to panel
                }
            }
            all.add(panel);                 //All contains counter and buttons

            return all;                     //Returning it
        }

When I don't create a counter panel, buttons are like in the second photo.
Sorry for any mistakes, English is not my main language.

A: first do you know what was the default layout for both of your panel's ?
and the shortest work solution is to make the root panel use BorderLayout and when adding the counter call on your root panel object
add(BorderLayout.NORTH,theCounterObject);

and for the button's panel call this on the root panel too
add(BorderLayout.CENTER,theButtonsPanel);

this would solve it in shortened version but it's better to learn not a sip or part but all about layout managers as they are very important for swing , here is start A Visual Guide to Layout Managers.
the pack() method is not necessary but it's a great way to fetch the perfect size it was a good idea from the comment but the problem was about your layout witch was FlowLayout and it's the default for panel but you should do it after changing the layout .


Q: Presenting a new window/view controller in Swift import UIKit

class StartUp: UIViewController {

var window: UIWindow = UIWindow(frame: UIScreen.mainScreen().bounds)
var window2: UIWindow = UIWindow(frame: UIScreen.mainScreen().bounds)
var window3: UIWindow = UIWindow(frame: UIScreen.mainScreen().bounds)
var window4: UIWindow = UIWindow(frame: UIScreen.mainScreen().bounds)
var startController: UIViewController?
var startController2: UIViewController?
var startController3: UIViewController?
var startController4: UIViewController?
var newViewController = false

let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

override func viewDidLoad() {
    super.viewDidLoad()

    var currentUser = PFUser.currentUser()

    //Get current app config (position codes and check if app is active)

    if (checkInternetConnection() == true) {

        PFConfig.getConfigInBackgroundWithBlock {
            (parseConfig: PFConfig?, error: NSError?) -> Void in

            //Determine where to start app

            //Already logged in
            if (currentUser != nil) {

                self.startController = self.mainStoryboard.instantiateViewControllerWithIdentifier("TabBar") as TabBar

            }

            //Not logged in
            else {

                self.startController = self.mainStoryboard.instantiateViewControllerWithIdentifier("loginStart") as UINavigationController

            }

            self.window.rootViewController = self.startController

            self.window.makeKeyAndVisible()

            //If the app is disabled, display the inactive/disabled/error screnen.
            if (parseConfig?["active"] as Bool? == false) {

                self.startController = self.mainStoryboard.instantiateViewControllerWithIdentifier("block") as AppBlock

                self.window2.rootViewController = self.startController

                self.window2.makeKeyAndVisible()
            }
        }
    }

    else {

        //Already logged in
        if (currentUser != nil) {

            self.startController = self.mainStoryboard.instantiateViewControllerWithIdentifier("TabBar") as TabBar

        }

            //Not logged in
        else {

            self.startController = self.mainStoryboard.instantiateViewControllerWithIdentifier("loginStart") as UINavigationController

        }

        self.window3.rootViewController = self.startController

        self.window3.makeKeyAndVisible()

        self.startController = self.mainStoryboard.instantiateViewControllerWithIdentifier("block") as AppBlock

        self.window4.rootViewController = self.startController

        self.window4.makeKeyAndVisible()
    }
}
}

I have what I think is a weird situation. If the first if statement ,checkInternetConnection(), is true, I go on to continue figuring out what window/view to present. Everything here works perfectly. However, in the else part, no windows/views are presented. I can't figure out why this is happening....it's really weird that it works in one section but not the other....
Any ideas?
Also in some cases two windows/views are created. Would this be a problem? I don't think so since if the parseConfig is false, the two windows are created and displayed correctly.


Q: WampServer HTTPS Hello I want to learn more about WampServer an HTTPS.
I have this website.
But if i give the command:

openssl genrsa -des3 -out server.key 1024

it will give me an error called:

he ordinal 3807 could not be located in the dynamic link libary
  LIBEAY32.dll

I have Look on my directory:

wamp\bin\apache\Apache2.4.4\bin

there was a file called libeay.dll.
What coud be the problem?

A: The openssl executable that is distributed with Apache for Windows and therefore WAMPServer does not seem to work very well. I have never had the time to work out exactly why!
My solution was to download OpenSSL from Shining Light Products They are linked to from the Openssl Binaries page so I assume it is a stable and unhacked distribution of a windows binary etc that does the job for windows users.


Q: 8078 bytes in 8060 B datapage (SQL Server)? It is written everywhere that data in SQL Server is written in pages of 8K (8192 B) each with 8060 bytes for data and the rest is overhead (system info).
Though, the recent article [1] gives code example illustrating, as I understood, that 8078 bytes of data fit into a page.
What do I miss in understanding 8,060 B per per page?
I verified the code on x86 SQL Server 2008 R2...

Update:
Did I see an answer telling about follow-ups to [1]? I pity that I did not mark that as helpful (to me) and comment immediately...  I just wanted to investigate more myself before responding...

Update2:
I posted subquestion [2]
[1]
How table design can impact your SQL Server performance?
http://sqlserver-training.com/how-table-design-can-impact-your-sql-server-performance/-
[2]
How to come to limits of 8060 bytes per row and 8000 per (varchar, nvarchar)?
How do you get to limits of 8060 bytes per row and 8000 per (varchar, nvarchar) value?

A: Long answer short, the limit is 8060 bytes per row, but 8096 bytes per page. The rows in the article you linked have a row size of ~4000 bytes, so they are well under the limit per row. However, that does not answer the question of how many such rows fit on a page.
See "Estimating the size of a heap" in Books Online:
http://msdn.microsoft.com/en-us/library/ms189124.aspx
If you do the calculation for the tables in the article, you'll see that the first table has a physical row size of 4048 bytes, which is exaclty half the 8096 limit for a page.

A: *

*The maximum row size is 8060 bytes

*In this case, there are two rows each of 4039 bytes


Q: Walking (tic-toc) clock with js and php Have a script with "walkin" clock on javascript and php (i need server-side time - it's important), but it's stop and don't count until refresh a page. What i'm doing wrong, please help. Thank you.
<?php $Hour = date("H");
$Minute = date("i");
$Second = date("s");
$Day = date("d");
$Month = date("m"); ?>

Date & time

A: Your issue:

*

*PHP serves on page request the respective date values.

*You store those values into JS

*You loop all over again the same values. Therefore the loop works but the values are unchanged.

Instead what you should:

*

*Create a var D = new Date("<?php echo date('D M d Y H:i:s O');?>");
outside of your function.

*On every timeout, add one second to your initial PHP Date
DATE = PHP:initial + JS:now - JS:initial

function zero(n) { return n > 9 ? n : "0" + n; }
var months = [
  "января", "февраля", "марта", "апреля", "мая", "июня",
  "июля", "августа", "сентября", "октября", "ноября", "декабря",
];
var jsDate = new Date(); // Store JS time

// I'll hardcode a date string for demo purpose:
var phpDate = new Date("Sun Sep 09 2018 23:59:55 +0000");
// You, use this instead:
// var phpDate = new Date("<?php echo date('D M d Y H:i:s O');?>");

function clock() {
  var diff = +new Date() - +jsDate;     // Get seconds difference
  var date = new Date(+phpDate + diff); // Add difference to initial PHP time

  var y = date.getFullYear(),
    M = date.getMonth(),
    d = zero(date.getDate()),
    h = zero(date.getHours()),
    m = zero(date.getMinutes()),
    s = zero(date.getSeconds());

  document.getElementById("doc_time").innerHTML = `
    Дата: ${d} ${months[M]} ${y}.
    Время: ${h}:${m}:${s}
  `;

  setTimeout(clock, 1000);
}

clock();

A: The php code runs once on page load so hour, minute and seconds will always remain same in each call of clock() function.
If you really need to do such a thing, you have to use AJAX to request a php script each second to get current time from server but remember these requests will have delay and also can put a huge load on server if multiple users open the page at the same time.


Q: Problems with NSMutableArray Why do I get this warning in Xcode 4.3.1?

Thanks.

A: You are allocating an NSArray instead of an NSMutableArray ?

A: Just change
NSMutableArray *array = [[NSArray alloc] initWithObjects:@"About", nil];

With
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"About", nil];

A: You should instead be creating your array like this:
NSMutableArray *array = [NSMutableArray arrayWithObjects:@"About", nil];

Notice we send the message to NSMutableArray's class, not NSArray's, so we get a mutable version of the array created.

A: Just Replace the convenience constructor for NSArray with NSMutableArray..
    [[NSMutableArray alloc] initWithObjects:@"About", nil;


Q: How do i deal with this? trying to get the outcome to produce the names of the hostvars #!/usr/bin/env python3

'''
Custom dynamic inventory script for ansible, in python
'''

# Importing modules needed
import os
import sys
import argparse

try:
    import json
except ImportError:
    import simplejson as json

class ExampleInventory(object):

    def __init__(self):
        self.inventory = {}
        self.read_cli_args()

        # Called with --list
        if self.arg.list:
            self.inventory = self.example_inventory()
        # Called with --host [hostname]
        elif self.arg.host:
            # Not implemented, since we return _meta info --list
            self.inventory = self.empty_inventory()
            # If no groups or vars are present, return an empty inventory
        else:
            self.inventory = self.empty_inventory()

        print: json.dumps(self.inventory);

    # Example inventory for testing
    # This is hard coded, a more elegant one will probe an API which might be

provided by cloud providers
def example_inventory(self):
return {
"group": {
"hosts": [
"172.31.30.220"
"172.31.28.102"
"172.31.32.33"
"172.31.41.111"
],
"vars": {
"example_variable": "value"
}
},
"_meta":{
"hostvars": {
"172.31.30.220": {
"host_specific_vars": "web1"
},
"172.31.28.102": {
"host_specific_vars": "web2"
},
"172.31.32.33": {
"host_specific_vars": "db1"
},
"172.31.41.111": {
"host_specific_vars": "db2"
}
}
}
}
    # Empty inventory for testing:
    def empty_inventory(self):
        return {'_meta': {'hostvars': {}}}

    # Read the command line args passed to the script
    # Every inventory must provide this
    def read_cli_args(self):
        parser = argparse.ArgumentParser()
        parser.add_argument('--list', action = 'store_true')
        parser.add_argument('--hosts', action = 'store')
        self.args = parser.parse_args()

# Get the inventory.
ExampleInventory()

> Keep getting this error
...
Traceback (most recent call last):
  File "dynamic_inventory_example.py", line 84, in <module>
    ExampleInventory()
  File "dynamic_inventory_example.py", line 26, in __init__
    if self.arg.list:
AttributeError: 'ExampleInventory' object has no attribute 'arg'

A: Used as self.arg but set as self.args. Use the same name in both places.


Q: error in google map integration i am trying to integrate the google api i have found some codes for that
API Script

<link rel="stylesheet" type="text/css" href="css/jquery-gmaps-latlon-picker.css"/>

html code
<fieldset class="gllpLatlonPicker">
    <input type="text" class="gllpSearchField">
    <input type="button" class="gllpSearchButton" value="Search">

Google Maps

    lat/lon:
        <input type="text" name="gllpLatitude" class="gllpLatitude" value="30.44867367928756"/>
        /
        <input type="text" name="gllpLatitude" class="gllpLongitude" value="70.6640625"/>
    zoom: <input type="text" name="gllpZoom" class="gllpZoom" value="4"/>
    <input type="button" class="gllpUpdateButton" value="update map">

</fieldset>

this code working fine separately but when i integrate in my application it
shows me that error

A:

In the above script the tag sensor is not required in "src" instead of that please provide a googlemapapi key, it will work!!
eg:

Get your key:
https://developers.google.com/maps/documentation/javascript/get-api-key#key
Thanks!!!


Q: QProcess not emitting its signals when not waitForFinished() In the following code omitting the waitForFinished() makes the QProcess stop emitting its signal. What the heck is wrong with it? Is this a Qt Bug? (5.7). Note this code is run parallel with QtConcurrent run. But this should not change anything, should it? Afaik sending signals in other threads is fine, though they will be queued.
QProcess *process = new QProcess;
process->setReadChannel(QProcess::StandardOutput);

connect(process, &QProcess::readyReadStandardOutput, [](){
    qDebug()<< "readyReadStandardOutput";
});

connect(process, &QProcess::stateChanged, [](QProcess::ProcessState state){
    qDebug()<< "stateChanged"<< state;
});

connect(process, static_cast<void(QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished),
    [=](){
    qDebug()<< "finsished";
});

connect(process, static_cast<void(QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished),
    [this, process](int exitCode, QProcess::ExitStatus exitStatus){
    qDebug()<< "finsished";
    if (exitStatus == QProcess::NormalExit && exitCode == 0){
        while (process->canReadLine()) {
           QString line = QString::fromLocal8Bit(process->readLine());
           QRegularExpression regex("\"(.*)\" {(.*)}");
           QRegularExpressionMatch match = regex.match(line);
           names_.push_back(match.captured(1));
           uuids_.push_back(match.captured(2));
        }
    }
    process->deleteLater();
});
process->start("VBoxManage",  {"list", "vms"});
process->waitForFinished(); // This line changes everything
qDebug()<< "leftWaitForFinished";

A: You're not running an event loop in the thread where the QProcess instance lives. Any QObject in a thread without an event loop is only partially functional - timers won't run, queued calls won't be delivered, etc. So you can't do that. Using QObjects with QtConcurrent::run requires care.
At the very least, you should have a temporary event loop for as long as the process lives - in that case you should hold QProcess by value, since deleteLater won't be executed after the event loop has quit.
QProcess process;
...
QEventLoop loop;
connect(process, &QProcess::finished, &loop, &QEventLoop::quit);
loop.exec();

Otherwise, you need to keep the process in a more durable thread, and keep that thread handle (QThread is but a handle!) in a thread that has an event loop that can dispose of it when it's done.
// This can be run from a lambda that runs in an arbitrary thread

auto thread = new QThread;
auto process = new QProcess;

...

connect(process, static_cast<void(QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished),
    [this, process](int exitCode, QProcess::ExitStatus exitStatus){
    ...
    process->deleteLater();
    process->thread()->quit();
});

process->start("VBoxManage",  {"list", "vms"});
process->moveToThread(thread);

// Move the thread **handle** to the main thread
thread->moveToThread(qApp->thread());
connect(thread, &QThread::finished, thread, &QObject::deleteLater);
thread->start();

Alas, this is very silly since you're creating temporary threads and that's expensive and wasteful. You should have one additional worker thread where you take care of all low-overhead work such as QProcess interaction. That thread should always be running, and you can move all QProcess and similar object instances to it, from concurrent lambdas etc.


Q: Dialog not pulling info from EditText box Hello I am trying to write a small app and when the day is Sunday on the system it is supposed to pull up a dialog box which it is doing just fine.  However when I put info in the boxes in the dialog and click submit it is still showing the second dialog for the emptyBox I have set up.
So to recap all items of the dialog box are working except the system is still seeing the EditText boxes as empty but there is a value in there.  The value will only ever be numbers.
final Dialog sundayDialog = new Dialog(this);

    sundayDialog.setContentView(R.layout.sunday_dialog);
    Button sundaySubmitBtn = (Button) sundayDialog
            .findViewById(R.id.sundayDialogSubmitBtn);
    Button sundayCancelBtn = (Button) sundayDialog
            .findViewById(R.id.sundayDialogCancelBtn);

    sundaySubmitBtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // Submit Button
            setContentView(R.layout.sunday_dialog);
            final EditText etAmountBought = (EditText) findViewById(R.id.amountBoughtET);
            final EditText etCost = (EditText) findViewById(R.id.pricePaidET);
            String amountBought = etAmountBought.getText().toString();
            String cost = etCost.getText().toString();
            if (amountBought.isEmpty() || cost.isEmpty()) {

                //sundayDialog.dismiss();
                emptyETDialogCall();
            } else {
                try {

                    mAmountBought = Integer.parseInt(amountBought);
                    mPricePaid = Integer.parseInt(cost);

                } catch (NullPointerException e) {
                    Log.e(TAG, "Error in sunday dialog in try/catch");
                }
            }
            if (mPricePaid >= 250) {
                costTooHighDialogCall();
                mPricePaid = 0;
            }

            // textBlockDisplay(); // Update the text block with input.
        }

    });

    sundayCancelBtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // Cancel Button
            sundayDialog.dismiss();
            sundayCancelDialog();

        }
    });

    sundayDialog.show();
}

this is the only this that shows in logcat:
 08-04 11:42:44.780: W/IInputConnectionWrapper(1209): finishComposingText on inactive InputConnection

A: I'm not sure if this is the reason, but each time, you're resetting the contentview. This should only be called once in onCreate, otherwise just remove the elements and use an inflater to add new ones. I think every time it resets the contentview, it will reset the textboxes.

A: I think, i got your problem .
sundayDialog.setContentView(R.layout.sunday_dialog);
this is View you are setting for your custom Dialog. this is fine.

And after sunday click button again you are resetting your Layout
  which again creates all views and you are getting everything reset.

final Dialog sundayDialog = new Dialog(this);
sundayDialog.setContentView(R.layout.sunday_dialog);
Button sundaySubmitBtn = (Button) sundayDialog
        .findViewById(R.id.sundayDialogSubmitBtn);
Button sundayCancelBtn = (Button) sundayDialog
        .findViewById(R.id.sundayDialogCancelBtn);

sundaySubmitBtn.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // Submit Button

// Here i have removed setContent View....
        final EditText etAmountBought = (EditText) findViewById(R.id.amountBoughtET);
        final EditText etCost = (EditText) findViewById(R.id.pricePaidET);
        String amountBought = etAmountBought.getText().toString();
        String cost = etCost.getText().toString();
        if (amountBought.isEmpty() || cost.isEmpty()) {

            //sundayDialog.dismiss();
            emptyETDialogCall();
        } else {
            try {

                mAmountBought = Integer.parseInt(amountBought);
                mPricePaid = Integer.parseInt(cost);

            } catch (NullPointerException e) {
                Log.e(TAG, "Error in sunday dialog in try/catch");
            }
        }
        if (mPricePaid >= 250) {
            costTooHighDialogCall();
            mPricePaid = 0;
        }

        // textBlockDisplay(); // Update the text block with input.
    }

});

sundayCancelBtn.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // Cancel Button
        sundayDialog.dismiss();
        sundayCancelDialog();

    }
});

sundayDialog.show();

}


Q: C++ declaration is incompatible These are the code files for my swapchain, I am using dx11 BTW, so you guys dont get lost on why I'm using d3d device, etc.
//Header
#pragma once
class SwapChain
{
public:
    SwapChain();
    bool init(HWND hwnd, UINT width, UINT height);
    bool release();
    ~SwapChain();
private:
    IDXGISwapChain* m_swap_chain;
};

//cpp
#include "SwapChain.h"
#include "GraphicsEngine.h"

SwapChain::SwapChain()
{
}

bool SwapChain::init(HWND hwnd, UINT width, UINT height)
{
    ID3D11Device*device= GraphicsEngine::get()->m_d3d_device;
    DXGI_SWAP_CHAIN_DESC desc;
    ZeroMemory(&desc, sizeof(desc));
    desc.BufferCount = 1;
    desc.BufferDesc.Width = width;
    desc.BufferDesc.Height = height;
    desc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    desc.BufferDesc.RefreshRate.Numerator = 60;
    desc.BufferDesc.RefreshRate.Denominator = 1;
    desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    desc.OutputWindow = hwnd;
    desc.SampleDesc.Count = 1;
    desc.SampleDesc.Quality = 0;
    desc.Windowed = TRUE;

    HRESULT hr=GraphicsEngine::get()->m_dxgi_factory->CreateSwapChain(device, &desc, &m_swap_chain);
    if (FAILED(hr))
    {
        return false;
    }

    return true;
}

bool SwapChain::release()
{
    return true;
}

SwapChain::~SwapChain()
{
}

I am trying to make a swapchain for my graphics engine, and I have the same params as in the header file. Can someone please explain why I am getting this error?

Severity  Code    Description Project Path    File    Line    Suppression State
Error
(active)  E0147   declaration is incompatible with "bool SwapChain::init( hwnd,  width,  height)" (declared at line 6 of "C:\Users\sudo\source\repos\DX 3D\DX 3D\SwapChain.h")    DX 3D   C:\Users\sudo\source\repos\DX 3D\DX 3D  C:\Users\sudo\source\repos\DX 3D\DX 3D\SwapChain.cpp    8

I am new to C++, by the way.


Q: how to return activity based on timedate mysql 5.7 this is my fiddle https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=5422fb347abaf2bde082eb522f5be4fb
table data2
+--------------------------------------+-----------------+----------------+----------+
|               user_id                | event_timestamp |   event_name   | level_id |
+--------------------------------------+-----------------+----------------+----------+
| 895A8F53-C61C-471A-B934-CC2795286E19 | 2020-01-01      | level_complete |        1 |
| 895A8F53-C61C-471A-B934-CC2795286E19 | 2020-01-02      | level_complete |        2 |
| 895A8F53-C61C-471A-B934-CC2795286E19 | 2020-01-02      | level_complete |        3 |
| 895A8F53-C61C-471A-B934-CC2795286E19 | 2020-01-02      | level_complete |        4 |
+--------------------------------------+-----------------+----------------+----------+

table data3
+--------------------------------------+-----------------+------------+----------+
|               user_id                | event_timestamp | event_name | level_id |
+--------------------------------------+-----------------+------------+----------+
| 895A8F53-C61C-471A-B934-CC2795286E19 | 2019-12-31      | level_end  |        1 |
| 895A8F53-C61C-471A-B934-CC2795286E19 | 2020-01-01      | level_end  |        2 |
| 895A8F53-C61C-471A-B934-CC2795286E19 | 2020-01-01      | level_end  |        3 |
| 895A8F53-C61C-471A-B934-CC2795286E19 | 2020-01-01      | level_end  |        4 |
+--------------------------------------+-----------------+------------+----------+

so i have 2 tables, if user_id has completed the level, then that data come to data2 table, but if failed the level, then the data come to data3 table. so i want to order by the event_timestamp so the expected results was like this
+--------------------------------------+-----------------+------------------+----------+
|               user_id                | event_timestamp |    event_name    | level_id |
+--------------------------------------+-----------------+------------------+----------+
| 895A8F53-C61C-471A-B934-CC2795286E19 | 2019-12-31      | level_end        |        1 |
|                                      | 2020-01-01      | level_completed  |        1 |
|                                      | 2020-01-01      | level_end        |        2 |
|                                      | 2020-01-01      | level_end        |        3 |
|                                      | 2020-01-01      | level_end        |        4 |
|                                      | 2020-01-02      | level_compeleted |        2 |
|                                      | 2020-01-02      | level_completed  |        3 |
|                                      | 2020-01-02      | level_completed  |        4 |
+--------------------------------------+-----------------+------------------+----------+

i've tried with this query
select * from data2
inner join data3 on data2.user_id = data3.user_id
order by data2.event_timestamp, data3.event_timestamp;

but the output was not like i expected

A: Something like this:
select * from data2 union
select * from data3
order by event_timestamp, level_id;

Using UNION and order by event_timestamp, level_id;
https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=03b02e0d079011aa4f9e3af7974a98f1


Q: Is there any way in Powershell to find ADF slices that completed in last 1 hour for example? Given certain dataset, I want to find out how many of its slices actually became Ready in last 1 hour (or say 2 hours, it's just an example). This gives me idea of cluster health. Because out of dozens of datasets, if no Ready slice was produced in last couple of hours, it's surely alarming for me.
I know Powershell has a cmdlet to get slice status which returns actual start and end time of slices -- but the problem is it finds that only on the basis of slice information. I don't care if the slice date is 1 year back -- I want the status on the basis of actual start and end time for that slice -- and I want to do it programmatically.
Worst case is -- one will need to get status for all possible slices and then get actual start and end time, but this is very inefficient -- there is also limit on how many API calls one can in an hour.

A: I think the cmdlet your looking for here is Get-AzureRmDataFactoryActivityWindow this accepts a run window and will return the result of a time slice either Ready, Waiting, Failed etc.
Example of use:
Get-AzureRmDataFactoryActivityWindow `
    -DataFactoryName $ADFName.DataFactoryName `
    -ResourceGroupName $ResourceGroup `
    | ? {$_.WindowStart -ge $Now} `
    | SELECT ActivityName, ActivityType, WindowState, RunStart, InputDatasets, OutputDatasets `
    | Sort-Object ActivityName

Use this with the required params to return a list of the information you want. I might then stick it into a SQL table for wider monitoring etc. But you could use an array in PowerShell to get the count value and produce the alert. Next wrap it up in something that polls on the hour maybe.
Here's a link to all ADF PowerShell cmdlets available in the Azure module: https://learn.microsoft.com/en-gb/powershell/module/azurerm.datafactories/?view=azurermps-4.0.0
Hope this helps


Q: What pull parser implementation to use and when? I need to use a xml pull parser. I can find stax-api.jar which seems to be already part of com.sun.xml.* and it seems that there is already something stax related implemented.
com.sun.xml unfortunately has no sources in JDK 6, so I can't tell.
Also there are xmlpull, stax.codehaus.org and apache axiom, that kinda implements stax-api. stax.codehaus.org seems to be a stax reference implementation. Xmlpull seems to be done by the same people as the reference implementation and Apache Axiom seems to be a StAX based parser that was created for Apache Axis2.
Could you please clarify what are the main differences, what API to use and when would you use one of these implementations and why ?
Edit: Before you decide to close this question, notice that xmlpull.org and stax.codehaus.org releases are pretty old (5 years) and one really can't say if the stax parser implementation is part of sun.com.xml.*.
I'd just need someone with pull parser experience to tell me, what to use and why.
For instance, Apache Abdera project (I'm parsing atom feeds too) is using Axiom implementation that seems to be implementing its Axiom-api and also geronimo-stax-api_1.0_spec

A: Aside from pointing out that JDK/JRE bundles Sun's SJSXP which works ok at this point, I would recommend AGAINST using Stax ref impl (stax.codehaus.org) -- do NOT use it for anything, ever. It has lots of remaining bugs (although many were fixed, initial versions were horrible), isn't particularly fast, doesn't implement even all mandatory features. Stay clear of it.
I am partial to Woodstox, which is by far the most complete implementation for XML features (on par with Xerces, about the only other Java XML parser that can say this), more performant than Sjsxp, and all around solid parser and generator -- this is why most modern Java XML web service frameworks and containers bundle Woodstox.
Or, if you want super-high performance, check out Aalto. It is successor to Woodstox, with less features (no DTD handling) but 2x faster for many common cases.
And if you ever need non-blocking/async parsing (for NIO based input for example), Aalto is the only known Java XML parser to offer that feature.
As to Axiom: it is NOT a parser, but tree model built on top of Stax parser like Woodstox, so they didn't reinvent the wheel. XmlPull predates Stax API by couple of years; basically Stax standardization came about people using XmlPull, liking what they saw, and Sun+BEA wanting to standardize the approach. There was some friction in the process, so in the end XmlPull was not discontinue when Stax was finalized, but one can think of Stax as successor -- XmlPull is still used for mobile devices; I think Android platform includes it.
(disclaimers: I am involved in both Aalto and Woodstox projects; as well as provided more than a dozen bug fixes to both SJSXP and Stax RI)

A: As of Java 1.6, there is a StaX implementation inside the plain bundled JRE. You can use that. If you don't like the performance, drop in woodstox.
Axiom is something else entirely, much more complex. Xmlpull seems to be going by the wayside in favor of one Stax implementation or another.


Q: org.joda.DateTime returning wrong month DateTimeFormatter d_t = DateTimeFormat.forPattern("DD-MMM-YYYY HH:mm");
String date = "02-Mar-2003 00:01";
DateTime dateTime = DateTime.parse(date, d_t);

When I am running the code its returning 02-Jan-2003 12:01

A: Your date format string is wrong. Use dd instead of DD for the days.
According to the documentation, DD means "day of year", while you need dd, which means "day of month".
Change the first line to:
DateTimeFormatter d_t = DateTimeFormat.forPattern("dd-MMM-YYYY HH:mm");


Q: How to clone div content and append only one at the time? I have form that should allow user to click on the Add Row and create another identical row. This will required new row to give an option to the user to delete that row if created accidentally. Here is my code that doesn't works correct. After I click on add row second time code will insert another 3 rows. Somethings odd is going on with the way I insert and clone new rows.

$("#add_row").on('click', addRow);
function addRow() {
    $(".data-bug-item").clone().insertAfter(".data-bug-item");
};
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

      <button type="button" class="btn" name="add_row" id="add_row">
                                                         Add Row
                                                    </button>

    Column & Description:

        <select class="form-control" name="frm_column" id="frm_column" required>
          <option value="">--Choose--</option>
          <option value="1">Location</option>
          <option value="2">Name</option>
          <option value="3">Year</option>
          <option value="4">City</option>
        </select>

        <input class="form-control" type="text" name="frm_descr" id="frm_descr" placeholder="Enter Description" required>

I would like to see only one row at the time and button on the end of the Description input field for Delete.

A: The simplest way to do that, it's to clone a minor part of html.
You're cloning everything including the cloned part.
After data-bug-item create a div with same name just to identify and clone JUST the form and not all informations inside the div.
Example:

$("#add_row").on('click', addRow);
function addRow() {
    $("#form-data-bug-item").clone().insertAfter(".data-bug-item");
};
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

   <button type="button" class="btn" name="add_row" id="add_row">
               Add Row
             </button>

  Column & Description:

   <select class="form-control" name="frm_column" id="frm_column" required>
     <option value="">--Choose--</option>
     <option value="1">Location</option>
     <option value="2">Name</option>
     <option value="3">Year</option>
     <option value="4">City</option>
   </select>

   <input class="form-control" type="text" name="frm_descr" id="frm_descr" placeholder="Enter Description" required>

Now you just need to clone form-data-bug-item
PS: I'm not considering another things on your code, just the solution.


Q: Double pointer in the function I am trying to insert strings in the binary search tree.
So what I am to trying is,
parsing strings from a file(contains instruction set) and then inserting in the function
insertOpcodeFromFile().
So this function will execute
(*node) = Node_insert(&node,instruction).
the node will be the root of binary tree which is located in main function.
So in simple way to explain, I want to manipulate(insert) the root pointer in the main function by using double pointer in the other function contain insert function.
I have a simple understanding about the pointer, but in this situation, I need to use more than double pointer I think.
please explain me about the double pointer clearly using this example.
Here is my code(I commenting out insert_node)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifndef BINARYTREE_H_
#define BINARYTREE_H_

typedef struct node *NodePtr;

typedef struct node {
  char   *word;
  int     count;
  NodePtr left;
  NodePtr right;
    } Node;

NodePtr Node_alloc();
NodePtr Node_insert(NodePtr node_ptr, char *word);
void clearArray(char a[]);
void insertOpcodeFromFile(FILE *opcodeFile, NodePtr *node);

void    Node_display(NodePtr);
char   *char_copy(char *word);

#endif

int main(int argc, const char * argv[]) {

FILE * opFile;
FILE * progFile;
struct node *root = NULL;

if ( argc != 4) {               // # of flag check
    fprintf(stderr, " # of arguments must be 4.\n" );
    exit(1);
}

opFile = fopen ( argv[1], "r");
if(opFile == NULL)
        {
            fprintf(stderr,"There is no name of the opcode file\n");
            exit(1);
        }
progFile = fopen ( argv[2], "r");
if(progFile == NULL)
    {
            fprintf(stderr,"There is no name of the program file \n");
            exit(1);
    }

insertOpcodeFromFile(opFile, &root);
//Node_display(root);

}/* main is over */

void insertOpcodeFromFile(FILE *opcodeFile, NodePtr *node)
{
int fsize = 0;
int lengthOfInst = 0;
int c;
int i;
char buffer[100];
fsize = getFileSize(opcodeFile);
enum flag {ins,opc,form};
int flag = ins;
char instruction[6];
unsigned int opcode = 0;
unsigned char format;
 while (c != EOF)
{
    c = fgetc(opcodeFile);
    buffer[i++] = c;

    if (c == 32){
        switch (flag) {

        case ins:
            flag = opc;

            memcpy(instruction,buffer,i);
            instruction[i] = '\0';
            clearArray(buffer);
            i = 0;
           // printf("인스트럭션 : %s\n",instruction );
             break;

        case opc:
            flag = form;
            opcode = atoi(buffer);
            clearArray(buffer);
            i = 0;
           // printf("옵코드 : %d\n",opcode );
            break;

        default:
             break;
        }/* end of switch */
    }/* end of if(space) */
    if((c == 10) || (c == EOF))
    {
        if (flag == form)
        {
            format = buffer[0];
            clearArray(buffer);
            i = 0;
           // printf("포멧: %c\n", format);

        }
        flag = ins;
       //node = Node_insert(node,instruction);

    }
}
//Node_display(node);
}
int getFileSize(FILE *opcodeFile)
{   int fsize = 0;
fseek(opcodeFile,0, SEEK_SET);
fseek(opcodeFile,0, SEEK_END);
fsize = (int)ftell(opcodeFile);
fseek(opcodeFile,0, SEEK_SET);
return fsize;
}
int countUntilSpace(FILE *opcodeFile, int currentPosition)
{   char readword[1];
char *space = " ";
char *nextLine = "/n";
int i = 0;
//printf("현재: %d\n",currentPosition );
while(1)
{
    fread(readword, sizeof(char),1,opcodeFile);
    i++;

    if(strcmp(readword,space) == 0 || strcmp(readword,nextLine) == 0)
    {
        //printf("break\n");
        break;
    }
}

fseek(opcodeFile,currentPosition ,SEEK_SET);
//printf("끝난 현재 :%d\n",ftell(opcodeFile) );
//printf("%I : %d\n",i );
return i - 1;
}
void clearArray(char a[])
{
memset(&a[0], 0, 100);
}

NodePtr Node_alloc()
{
return (NodePtr) malloc(sizeof(NodePtr));
}

NodePtr Node_insert(NodePtr node_ptr, char *word)
{
int cond;

if (node_ptr == NULL) {
    node_ptr = Node_alloc();
    node_ptr->word  = char_copy(word);
    node_ptr->count = 1;
    node_ptr->left  = node_ptr->right = NULL;
} else if ((cond = strcmp(word, node_ptr->word)) == 0) {
    node_ptr->count++;
} else if (cond < 0) {
    node_ptr->left = Node_insert(node_ptr->left, word);
} else {
    node_ptr->right = Node_insert(node_ptr->right, word);
}
return node_ptr;
}

void Node_display(NodePtr node_ptr)
{
if (node_ptr != NULL) {
    Node_display(node_ptr->left);
    printf("%04d: %s\n", node_ptr->count, node_ptr->word);
    Node_display(node_ptr->right);
}
}

char *char_copy(char *word)
{
char *char_ptr;

char_ptr = (char *) malloc(strlen(word) + 1);
if (char_ptr != NULL) {
    char_ptr = strdup(word);
}
return  char_ptr;
}

A: In this case, in main(),
Node *root;

Why do you need to use a "double" pointer ( Node ** ) in functions that alter root is because root value as to be set in these functions.
For instance, say you want to allocate a Node and set it into root.
If you do the following
void alloc_root(Node *root) {
   root = malloc(sizeof (Node));
   // root is a function parameter and has nothing to do
   // with the 'main' root
}
...
   // then in main
   alloc_root( root );
   // here main's root is not set

Using a pointer to pointer (that you call "double pointer")
void alloc_root(Node **root) {
   *root = malloc(sizeof (Node)); // note the *
}
...
   // then in main
   allow_root( &root );
   // here main's root is set

The confusion comes probably from the Node *root in main, root being a pointer to a Node. How would you set an integer int i; in a function f? You would use f(&i) to call the function f(int *p) { *p = 31415; } to set i to the value 31415.
Consider root to be a variable that contains an address to a Node, and to set its value in a function you have to pass &root. root being a Node *, that makes another *, like func(Node **p).


Q: JAR program not allowed to open/save under MacOS Catalina ("the open file operation failed to connect to the open and save panel service") I am having the following problem:
I am using Catalina (10.15.7) on a MacBook and recently I downloaded a JAR executable file (called JKnobMan) but apparently it doesn't have access to the open and save operations, even though the program runs normally otherwise, and it even lets me export. But naturally, what I want is to be able to save my progress and open it later on.
The message I get when I click 'open' is: "The open file operation failed to connect to the open and save panel service". I don't get this message when I 'save' but the saved file contains none of the information it should have (I checked this by opening the saved file on the web version of the KnobMan program).
I tried going to the Security & Privacy settings to give this program all necessary access but for some reason the JAR file is not selectable when I browse the items.
I expect this to be an easy fix, but so far I have been unable to find a solution. Some people experience a similar problem with email services and they're usually easily solved, so this must be straightforward as well?
Any help appreciated.
EDIT: Note that I'm not asking for help with THIS particular program. I assume that I would have the same issue with any other JAR executable trying to open/save in a Catalina environment. So, knowledge of said program is probably not necessary to know the solution.