Q: How to prioritize two change events in select element I have two change events handler for one select elemet. Let's call the functions Func1 and Func2. When I initialize these handlers I do the Func1 and then Func2 but when the change event happens in select element the Func2 get called before Func1.
Is there any way to prioritize this two functions. Just to let you know the initializations for each function is in different scripts.
This is the layout of my code
Script1:
$("select#myDropdownlist").change(function(){
    $(this).parents('form:first').submit();
   // form submit sends post request to update an object which is in session
}

Script2:
$("select#myDropdownlist").change(function(){
    Send an ajax request and return json result based on the changes happened to the object in script1 function
}

Although I initialized these by sequence it doesn't call the function in order. Because it calls Func2 first the object is not updated yet so result is not correct, it will then call Func1 and object will be updated which is too late as the Func2 has already returned the result based on previous version of object.
Please also note that Script1 is very generic and it's supposed to work for any form data entry page, where the Script2 is specific to a particular page and I want to do an extra thing once the select element is changed only in a page. This means I cannot call Func2 inside Func2.
Any help would be highly appreciated
Regards
Behnam Divsalar

A: The simple answer to order functions after an event would be to add a single event handler function that runs the 2 functions one after the other.
$("select#myDropdownlist").change(function(){
    callFirstFunction();
    callSecondAjaxFunction();
}

A: How about putting the contents of the first function in a method:
$("select#myDropdownlist").change(function(){
  submitPostFunction1();
}

submitPostFunction1 = function() {
  //do function 1 stuff here
}

then in your more specific function - function2:
$("select#myDropdownlist").change(function(){
  $("select").unbind();
  submitPostFunction1();
  //do function 2 stuff
  $("select").bind("change", function() {
    submitPostFunction1();
  })
}

keep in mind that i used $("select") in function 2 because you said it was a more generic call, so that means you wont be using the id in the first function call.

A: Events are not specified to fire in any specific order.
If you want a specific order, you need to either invoke them from a meta handler, or chain them by calling one from the other. The meta handler is more flexible in the long run though.
$("select#myDropdownlist").change(function(){
    firstHandler();
    secondHandler();
}

or
function firstHandler() {
    ...
    secondHandler();
}
function secondHandler() {
    ...
}

$("select#myDropdownlist").change(firstHandler);


Q: JLabel translation I have a JLabel (with an icon) and I would like to translate this JLabel when the JLabel is clicked. I have added a mouseListener to the JLabel however I didn't come up with anything on how I can execute a translation from coordinates (x, y) to cordinates (x', y')
class MyMouseListener extends MouseAdapter {
    @Override
    public void mouseClicked(MouseEvent e){

        final JLabel label = (JLabel) e.getSource();
        System.out.println("Player hit label -> " + label.getName() );

        // Code for translating JLabel

    }
}

A: As far as translating (ie moving) your JLabel:
First, you must make sure that the layout manager of its parent is set to null, or uses a customized layoutmanager that can be configured to do your translation.
Once you have that in place, it's a simple matter:
public void mouseClicked(MouseEvent ae) {
  JLabel src = (JLabel) ae.getSource();
  src.setLocation(src.getLocation().x + delta_x, src.getLocation().y + delta_y);
  src.getParent().repaint();
}


Q: Checking if 2 nodes on a graph are connected recursively C# I'm trying to create a simple implementation of Depth-First Search recursively.
Here is the graph I've set up, searching for a path between Node 1 and Node 5:
int[][] graph = new int[5][];
graph[0] = new int[] { 1, 2 };
graph[1] = new int[] { 1, 3 };
graph[2] = new int[] { 2, 4 };
graph[3] = new int[] { 3, 4 };
graph[4] = new int[] { 4, 5 };

if (FindNode(graph, 1, 5))
{
    //Success
}

Node 1 is connected to Nodes 2 and 3, Node 2 to Node 4, Node 3 to Node 4, and Node 4 to 5.
Here is the recursion method:
public static Boolean FindNode(int[][] graph, int start, int end)
{
    if (start == end)
    {
        return true;
    }
    for (int i = 0; i < graph.Length; i++)
    {
        if (graph[i][0] == start)
        {
            start = graph[i][1];
            if (FindNode(graph, start, end))
            {
                return true;
            }
        }
    }
    return false;
}

Essentially it's looking for the starting value in the 'left column' of the graph data, and then changes the starting node to be its associated node.
The code works as intended for this graph example (i.e. it finds the path 1 -> 2 -> 4 -> 5), but when it has to go back up the recursive loop it can't find the solution (e.g. if graph[4] was {3,5}).
I'm not too familiar with recursion so I'm not sure how to fix it.
I'm not too concerned about optimising it to ignore previously visited nodes.
I would like to return the path as a list (e.g. 1,2,4,5).
Thanks

A: The logic in your answer is correct but displaying the path would require you to push the successful links onto a stack or onto the beginning of a list.
If you can only add to the end of a list (as is the case with trying to just Console.WriteLine each step) then you can do this without remembering (or returning) the path, but you have to be clever by building path in reverse order.  (find the last step of the chain first)
If you have a link from n -> end, and there is a path from start -> n.  Then you can display the link from n -> end.  In so determining that there is a path from start -> n, you will have displayed all those links already.
using System;

class Program
{
    public static Boolean FindNode(int[][] graph, int start, int end)
    {
        if (start == end) {
            return true;
        }
        for (int i = 0; i < graph.Length; i++) {
            if (graph[i][1] == end) {
                if (FindNode(graph, start, graph[i][0])) {
                    Console.WriteLine("{0} -> {1}", graph[i][0], end);
                    return true;
                }
            }
        }
        return false;
    }
    static void Main(string[] args)
    {
        int[][] graph = new int[5][];
        graph[0] = new int[] { 1, 2 };
        graph[1] = new int[] { 1, 3 };
        graph[2] = new int[] { 2, 4 };
        graph[3] = new int[] { 3, 4 };
        graph[4] = new int[] { 4, 5 };

        if (FindNode(graph, 1, 5)) {
            //Success
        }
    }
}


Q: How to clear GridView while working with Firestore? The problem is that I can't refresh my gridView and when I make changes in Firestore, my gridView doesn't clear and just adds new values(images) from Firestore. I have tried lots of methods that I could find on "stackoverflow" but with no success. Maybe the problem is with ImageAdapter or with how I call addSnapshotListener, I really don't know. Right now I just want that I can refresh my gridView when data changes on Firestore, but in best case scenario I want that, when I get new values from Firestore, it only updates that part of gridView where was the image,  and not the whole gridView.
public class MainActivity extends AppCompatActivity {

private FirebaseFirestore db;
private ArrayList<Items> arrayList;
private ImageAdapter imageAdapter;
private GridView gridView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    gridView = findViewById(R.id.gridViewList);
    db = FirebaseFirestore.getInstance();
    arrayList = new ArrayList<>();
    //arrayList.clear();

    getUrls();

    imageAdapter = new ImageAdapter(MainActivity.this, arrayList);
    gridView.setAdapter(imageAdapter);

}

private void getUrls(){
    gridView.setAdapter(null);
    db.collection("images").addSnapshotListener(new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(QuerySnapshot value, FirebaseFirestoreException e) {
            if (e != null){
                Toast.makeText(getApplicationContext(), "No images returned", Toast.LENGTH_SHORT).show();
                return;
            }
            for (DocumentSnapshot document : value){
                refresh();
                if (document.get("imageUrl") != null){
                    arrayList.add(new Items(document.get("imageUrl").toString()));
                    refresh();
                }
            }
        }
    });
}

public void refresh() {
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            imageAdapter.notifyDataSetChanged();
            gridView.invalidate();
        }
    });
}

public class ImageAdapter extends BaseAdapter {

private ImageView imageView;
private Context context;
private LayoutInflater inflater;
private ArrayList<Items> list;

public ImageAdapter(Context context, ArrayList<Items> list){
    this.context = context;
    this.list = list;
}

@Override
public int getCount() {
    return list.size();
}

@Override
public Object getItem(int position) {
    return position;
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null){
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.image_layout, parent, false);
        imageView = convertView.findViewById(R.id.singleImageView);
    }

    /** https://futurestud.io/tutorials/glide-caching-basics */
    Glide.with(context).load(list.get(position).getImageUrl()).apply(RequestOptions.skipMemoryCacheOf(true).centerCrop()).into(imageView);
    return convertView;
}

A: The FirebaseUI-Android/Firestore project has an adapter that does what you want. This does the heavy lifting of managing a RecyclerView for you. In order to have a layout like in GridView, you can create an instance of GridLayoutManager in onCreate and pass that to RecyclerView.setLayoutManager
If you want to hack it yourself, the QuerySnapshot has a property documentChanges that you can check for REMOVED - cf. View changes between snapshots. To get an idea of how it would be implemented with a GridView you can look at the source code of RecyclerView.Adatper - epecially the notifyItemXXX methods.


Q: Run Web Application in Virtual Directory I am trying to run my web application for test purposes in a virtual directory.
I have done this steps from this MS Site

*

*In Visual Studio, open an existing Web application project, or create a new one.

*In the Project menu, click Properties, and then click Web.

*Click Use Local IIS Web server.

*Enter a URL for the project, and then click Create Virtual Directory.

But after this configuration I get a HTTP-Error 500.19 - Internal Server Error
Details: There are duplicate entries in the web.config File
But the web.config file hasn't changed. Without the Virtual Directory the site is starting up as expected.
any ideas?


Q: IO Error 22 python infile1 = open("D:/p/non_rte_header_path.txt","r")
infile2 = open("D:/p/fnsinrte.txt","r")
for line in infile1:
    for item in infile2:
         eachfile = open(line,"r")

For the above code I am getting the below error. infile1 contains paths of may files like D:/folder/Src/em.h but here \n is automatically at the end of the path.I am not sure why it happens. Please help.
IOError: [Errno 22] invalid mode ('r') or filename: 'D:/folder/Src/em.h\n'

A: Everyone has provided comments telling you what the problem is but if you are a beginner you probably don't understand why it's happening, so i'll explain that.
Basicly, when opening a file with python, each new line (when you press the Enter Key) is represented by a "\n".
As you read the file, it reads line by line, but unless you remove the "\n", it your line variable will read

thethingsonthatline\n

This can be useful to see if a file contains multiple lines, but you'll want to get rid of it. Edchum and alvits has given a good way of doing this !
Your corrected code would be :
infile1 = open("D:/p/non_rte_header_path.txt","r")
infile2 = open("D:/p/fnsinrte.txt","r")

for line in infile1:
    for item in infile2:
         eachfile = open(line.rstrip('\n'), "r")


Q: jHipster - simplify generation of the new APP if the DB already exists does any tool exist that can simplify generation of the new APP if the DB already exists? I can create JDL file for new app manually base on existing DB - but I prefer to automate the process. This DB is part of old Spring Roo app.
Thank you.

A: The spring Roo 1.x version provides the "Database Reverse Engineering" functionality. This add-on allows you to create an application tier of JPA 2.0 entities based on the tables in your database. DBRE will also incrementally maintain your application tier if you add or remove tables and columns.
After generate the entities, you could execute the necessary web mvc commands to generate the complete application.
However, remember that the Spring Roo 1.x is not beeing maintained, because uses old technologies.
See more about the DBRE process here:
http://docs.spring.io/spring-roo/reference/html/base-dbre.html
Hope it helps,

A: There's a JHipster module that is being developed for this purpose: https://github.com/bastienmichaux/generator-jhipster-db-helper
It is probably not ready yet but could be a good start.


Q: How to create a socket that is accessible across different networks Below I have two scripts that work when I bind the server.py to my computers IPV4 address and connect the client.py to that same address. The next step I'm trying to take is the ability to use this socket across different networks. I thought that it would be as simple as changing the value of SERVER to my public IP address (which can be found by clicking this link). When I make that change, I get this error upon running server.py:
Traceback (most recent call last):
  File "C:\Users\gmbra\Downloads\Python Programs\Concepts\Sockets\server.py", line 13, in <module>
    server.bind(ADDRESS)
OSError: [WinError 10049] The requested address is not valid in its context

server.py
import socket
import threading

PORT = 5050
# SERVER = '192.168.0.30'
SERVER = socket.gethostbyname(socket.gethostname())  # Change this to the public IP address to allow access across multiple networks
ADDRESS = (SERVER, PORT)
HEADER = 64  # The number of bytes expected to get from the client
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT"

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # AF_INET is the type of addresses we are looking for
server.bind(ADDRESS)

def handle_client(conn, address):
    print(f"[NEW CONNECTION] {address} connected.")

    while True:
        msg_length = conn.recv(HEADER).decode(FORMAT)  # This line also blocks until it receives a message
        if msg_length:
            msg_length = int(msg_length)
            msg = conn.recv(msg_length).decode(FORMAT)
            if msg == DISCONNECT_MESSAGE:
                conn.close()
                break

            print(f'[{address}] {msg}')
            conn.send("Message Received".encode(FORMAT))

def start():
    server.listen()
    print(f'[LISTENING] Server is listening on {SERVER}.')
    while True:
        conn, address = server.accept()  # This line will wait until it finds a connection.
        thread = threading.Thread(target=handle_client, args=(conn, address))
        thread.start()
        print(f"[ACTIVE CONNECTIONS] {threading.active_count() - 1}.")

print("[STARTING] Server is starting...")
start()

client.py
import socket

HEADER = 64
PORT = 5050
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = '!DISCONNECT'
SERVER = "192.168.0.30"
ADDRESS = (SERVER, PORT)

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDRESS)

# The pickle module could be used to send objects instead of strings.
def send(msg):
    message = msg.encode(FORMAT)
    # For some reason we have to send a byte string first with the integer size of the message, concatenated with spaces
    # until it hits the length of the header.
    send_length = str(len(message)).encode(FORMAT)
    send_length += b' '*(HEADER - len(send_length))
    client.send(send_length)
    client.send(message)
    print(client.recv(2048).decode(FORMAT))

while True:
    message_ = input('Message: ')
    send(message_)
    if message_ == "!DISCONNECT":
        break

What must I do to make this work across different networks?

A: The server socket can bind only to an IP that is local to the machine it is running on (or, to the wildcard IP 0.0.0.0 to bind to all available local IPs). Clients running on the same network can connect to the server via any LAN IP/Port the server is bound to.
However, when the server machine is not directly connected to the Internet, but is running behind a router/proxy, the server socket cannot bind to the network's public IP. So, for what you are attempting, you need to bind the server socket to its local LAN IP (or wildcard) and Port, and then configure the network router to port-forward inbound connections from its public WAN IP/Port to the server's private LAN IP/Port. Then, clients running on other networks can connect to your public WAN IP/Port, and then be forwarded to the server.
If the router supports UPnP (Universal Play-by-play) and it is enabled, the server code can programmably setup the port forwarding rules dynamically. Otherwise, the rules  need to be configured manually in the router's configuration by an admin.


Q: OrientDB: How can I filter Edge by node in orientdb How can I filter the edges by node condition? Below is my query, I would like to further filter the path by ending node with id 222

SELECT $path as path FROM (
      TRAVERSE bothE(),bothV() FROM (select * from Node where  (id in ['111']))
      WHILE $depth <= 6 )
  where @rid in (select @rid from Node where (id in ['222']))

However, the query only returns one path. But I know, there are several paths.


Q: regular expressions in Java i attempted to port the code in this answer to Java:
PHP VIN number validation code
i understand that String.matches in Java is a bit temperamental and i'm very unfamiliar with regular expressions.  here is the code:
public boolean validateVIN(String vin) {
    vin = vin.toLowerCase();

    if(!vin.matches("/^[^\\Wioq]{17}$/")) { //the offending code, always fails
        Log.e("vininfo", "did not pass regex");
        return false;
    }

    int[] weights = { 8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2 };

    //array positions coorespond to the 26 letters of the alphabet
    int[] transliterations = { 1, 2, 3, 4, 5, 6, 7, 8, 0, 1, 2, 3, 4, 5, 0, 7, 0, 9, 2, 3, 4, 5, 6, 7, 8, 9 };

    int sum = 0;
    String checkdigit = ".";

    for(int i=0; i < vin.length(); i++) {
        //add transliterations * weight of their positions to get the sum
        int temp = 0;
        temp = vin.charAt(i);
        if(temp < 58) {
            sum += (temp-48)*weights[i];
            Log.e("vinsum.num", String.valueOf(sum));
        } else {
            sum += transliterations[temp-97]*weights[i];
            Log.e("vinsum.chr", String.valueOf(sum));
        }
    }

    if(checkdigit.equals("10")) {
        checkdigit = "x";
    } else {
        //find checkdidgit by taking the mod of the sum
        checkdigit = String.valueOf(sum % 11);
    }

    Log.i("vininfo", "checkdigit: "+checkdigit+" ... VIN[8]: "+vin.substring(8,9));
    return (checkdigit.equals(vin.substring(8, 9)));
}

anyone familiar with a proper way to use this regex in Java?

A: Remove the slashes from the regex.  In other words:
if(!vin.matches("^[^\\Wioq]{17}$")) {

A: Try this at home:
class Vin {
   public static void main( String ... args ) {
      String vin = "1M8GDM9A_KP042788";
      if(!vin.matches("[^\\Wioq]{17}")) { //the offending code, always fails
        System.out.println("vininfo did not pass regex");
      } else {
        System.out.println("works");
     }
   }
}

Prints:
$java Vin
works

You don't need the /^ and $/


Q: PHP Composer Autoloader Simple Structure I have Composer working and I'd like to use its autoloader to load my classes, but it's not working. Here's my directory structure. I'm keeping it really simple to start with.
index.php
composer.json
Vendor
controllers/webgl.php

Inside webgl.php I have:

namespace controllers;

class webgl {
    public function lesson1() {

    }
}

In index.php I have:
require('vendor/autoload.php');
//require_once('controllers/webgl.php');

$webglController = new \controllers\webgl;

And my composer.json defines this for autoloading:
"autoload": {
    "psr-4": {
        "controllers\\": "controllers/"
    }
}

If I uncomment the second require, the script works, otherwise I get "Fatal error: Class 'controllers\webgl' not found in /vagrant/index.php on line 5".
I thought that the folder structure, class namespace and class name all conformed to psr-4. But I must be misunderstanding something. I've read loads of similar questions but none have been able to sort it for me.
Can anyone tell me why my class isn't loading and what I should do to fix it?

A: Did you define an autoload directive?
You need to add this to your composer.json file:
"autoload": {
    "psr-4": {
        "controllers\\": "controllers/"
    }
}

to point the autoloader in the right direction and then run
composer update

from the terminal in your project directory. Now the class will load without explicitly requiring its file.

A: Make sure you run at least composer dump-autoload after making changes to your composer.json. composer install or composer update will also do it.
From your question and the comments it seems like you didn't run the command after you added the autoloading definition for your own code.


Q: android generic SQLite database i developed a small java.lang.reflect.InvocationHandler that intercepts method calls (from a json webservice) and cache the results to a local SQLite db. if there is no internet connection results are read from local cache.
everything works fine; my problem is the following:
every method intercepted can return a different entity, and i save using reflection each entity on a different table. i don't know in advance all the tables i need to create, so every time i create a SQLiteOpenHelper that "create table if not exists {ENTITY_NAME}", and every time i increase the database version by 1 so the method onUpgrade is called.
this works on development environment but i don't like that at all.
someone can recommend a better solution to update the database with new tables?
thank you

A: Try  mYourDbHelper.getWritableDatabase().execSQL("CREATE TABLE ....") from where you need to create another table


Q: How do I use extensions in incognito I wanna use python selemium incognito with extensions but none worked so far
Anyone got a fix?
I tried:
options.add_extension('plugin.crx')
        #options.add_argument("--incognito")
        #options.add_argument("user-data-dir=C:\\Users\\Maxva\\AppData\\Local\\Google\\Chrome\\User Data\\Profile 9")
        options.add_experimental_option('excludeSwitches', ['enable-logging'])
        driver = webdriver.Chrome(options=options)

        #driver.get('chrome://extensions/?id=lncaoejhfdpcafpkkcddpjnhnodcajfg')

        #driver.execute_script("return document.querySelector('extensions-manager').shadowRoot.querySelector('#viewManager > extensions-detail-view.active').shadowRoot.querySelector('div#container.page-container > div.page-content > div#options-section extensions-toggle-row#allow-incognito').shadowRoot.querySelector('label#label input').click()")

A: My favourite trick is to use the keyboard:
options.add_argument("--incognito")
options.add_extension('Google-Translate.crx')

driver.get("chrome://extensions")
time.sleep(1)
action = ActionChains(driver)

# Open the extension:
for _ in range(2):
    action.send_keys(Keys.TAB).perform()
action.send_keys(Keys.RETURN).perform()

# Flip the switch that enables it in incognito
for _ in range(4):
    action.send_keys(Keys.TAB).perform()
action.send_keys(Keys.RETURN).perform()


Q: Complex shape with rainbow gradient I'm trying to draw a figure on a canvas, to be filled with a rainbow-colored gradient. The wanted result is something like this:

Creating the shape itself is pretty easy, just creating a path and drawing the lines. However, actually filling it with a gradient appears to be somewhat more difficult, as it seems only radial and linear gradients are supported.
The closest I have gotten is this:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var gradient=ctx.createLinearGradient(0,0,0,100);
gradient.addColorStop (0, 'red');
gradient.addColorStop (0.25, 'yellow');
gradient.addColorStop (0.5, 'green');
gradient.addColorStop (0.75, 'blue');
gradient.addColorStop (1, 'violet');
ctx.moveTo(0,40);
ctx.lineTo(200,0);
ctx.lineTo(200,100);
ctx.lineTo(0, 50);
ctx.closePath();
ctx.fillStyle = gradient;
ctx.fill();

   <canvas id="canvas" width="400" height="300"></canvas>

The gradient colors and such are correct, but the gradient should of course be more triangular-like, rather than being rectangular and cropped.

A: Native html5 canvas doesn't have a way to stretch one side of a gradient fill.
But there is a workaround:
Create your stretch gradient by drawing a series of vertical gradient lines with an increasing length.

Then you can use transformations to draw your stretched gradient at your desired angle

Example code and a Demo:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var length=200;
var y0=40;
var y1=65
var stops=[
    {stop:0.00,color:'red'},
    {stop:0.25,color:'yellow'},
    {stop:0.50,color:'green'},
    {stop:0.75,color:'blue'},
    {stop:1.00,color:'violet'},
];

var g=stretchedGradientRect(length,y0,y1,stops);

ctx.translate(50,100);
ctx.rotate(-Math.PI/10);
ctx.drawImage(g,0,0);

function stretchedGradientRect(length,startingHeight,endingHeight,stops){
    var y=startingHeight;
    var yInc=(endingHeight-startingHeight)/length;
    // create a temp canvas to hold the stretched gradient
    var c=document.createElement("canvas");
    var cctx=c.getContext("2d");
    c.width=length;
    c.height=endingHeight;
    // clip the path to eliminate "jaggies" on the bottom
    cctx.beginPath();
    cctx.moveTo(0,0);
    cctx.lineTo(length,0);
    cctx.lineTo(length,endingHeight);
    cctx.lineTo(0,startingHeight);
    cctx.closePath();
    cctx.clip();
    // draw a series of vertical gradient lines with increasing height
    for(var x=0;x<length;x+=1){
        var gradient=cctx.createLinearGradient(0,0,0,y);
        for(var i=0;i<stops.length;i++){
            gradient.addColorStop(stops[i].stop,stops[i].color);
        }
        cctx.beginPath();
        cctx.moveTo(x,0);
        cctx.lineTo(x,y+2);
        cctx.strokeStyle=gradient;
        cctx.stroke();
        y+=yInc;
    }
    return(c);
}
#canvas{border:1px solid red; margin:0 auto; }

Stretched gradient made from vertical strokes

<canvas id="canvas" width=300 height=200></canvas>


Q: .Net HttpClient Class within Xamarin only works in Full Debug info mode I'm new in Xamarin development.I build a small demo which use .Net Httpclient to send and receive message from remote server.Everything is fine except the httpclient segament
If I choose Debug and output full debug info the response is "Success".
If I choose Debug and output pdb-only or none then I got into the Exception.
Things are same when I build Release, but if I output none debug info with Release mode the App will crash on my cell phone.
Does anybody have the similar problem ?
What should I do? I will greatly appreciate a solution.
The related code is:
    string response = string.Empty;
    var client = new HttpClient();
    client.MaxResponseContentBufferSize = 1024 * 1024;
    //client.Timeout = new TimeSpan( 0, 0, 0, 5 );
    Task<string> result = null;
    try
    {
        result = client.GetStringAsync( reqInfo_ );
        response = result.Result;
        response = "Success";
    }
    catch ( Exception e )
    {
        //output the exception
    }

Exception is:

A: http://forums.xamarin.com/discussion/7327/system-net-webexception-error-nameresolutionfailure
Owen's solution works for me:
"For me, in release mode, I checked the box marked Internet in the Required permissions section of the AndroidManifest.xml file found under the Properties folder. Debug mode doesn't need this checked but Release mode does - which you need if sending the APK by email for installation - which works great by the way. In case anyone is interested, you also have to sign your app and produce the private key following these instructions here: http://developer.xamarin.com/guides/android/deployment,testing,_and_metrics/publishing_an_application/part_2-_publishing_an_application_on_google_play/"


Q: Anomaly Detection Using Keras - Low Prediction Rate I built an Anomaly detection system using Autoencoder, implemented in keras.
My input is a normalized vector with length 13.
My dataset contains about 25,000 non anomaly inputs which dedicated for learning.
I get about 10^-5 MSE after learning with 1-3 epochs.
The problem is that although I get to a small MSE my AE can't detect anomalies good enough..
Model class:
class AutoEncoder:
    def __init__(self, inputLen, modelName,Batch,epochs):
        self.modelName       = modelName
        self.DL_BATCH_SIZE   = Batch
        self.DL_EPOCHS       = epochs
        self.DL_LAYER1       = 200
        self.DL_LAYER2       = 150
        self.DL_LAYER3       = 100
        self.DL_LAYEROUT     = 13
        self.DL_LOADMODEL    = None
        #self.DL_SAVEMODEL    = fileConfig.getConfigParam(DL_SAVEMODEL)
        #print(tensorflow.version.VERSION)

        if self.DL_LOADMODEL == None or self.DL_LOADMODEL == 0:
            my_init = keras.initializers.glorot_uniform(seed=1)
            self.dlModel = keras.models.Sequential()

            self.dlModel.add(keras.layers.Dense(units=self.DL_LAYER1, activation='tanh', input_dim=inputLen,kernel_initializer=my_init))
            self.dlModel.add(keras.layers.Dense(units=self.DL_LAYER2, activation='tanh',kernel_initializer=my_init))
            self.dlModel.add(keras.layers.Dense(units=self.DL_LAYER3, activation='tanh',kernel_initializer=my_init))
            self.dlModel.add(keras.layers.Dense(units=self.DL_LAYER2, activation='tanh',kernel_initializer=my_init))
            self.dlModel.add(keras.layers.Dense(units=self.DL_LAYER1, activation='tanh',kernel_initializer=my_init))
            self.dlModel.add(keras.layers.Dense(units=self.DL_LAYEROUT, activation='tanh',kernel_initializer=my_init))
            #sgd = keras.optimizers.SGD(lr=0.0001, decay=0.0005, momentum=0, nesterov=True)
            #adam = keras.optimizers.Adam(learning_rate=0.005,decay=0.005)
            simple_adam=keras.optimizers.Adam()
            self.dlModel.compile(loss='mse', optimizer=simple_adam, metrics=['accuracy'])
        else:
            self.dlModel = keras.models.load_model(self.DL_LOADMODEL + ".h5")

After training I find the max reconstruction MSE on a specific dataset of 2500 non anomalies.
Then i test my Anomaly detector and mark as anomaly every input that its reconstruction has more than the max MSE*0.9 value.
find max error:
N = len(non_anomaly)
max_se = 0.0;
max_ix = 0
second_max=0
predicteds = kerasNN.predict(non_anomaly)
for i in range(N):
  curr_se = np.square(np.subtract(non_anomaly[i],predicteds[i])).mean()
  if curr_se > max_se:
    second_max=max_se
    max_se = curr_se;
    max_ix = i

Testing the model:
    predicteds=kerasNN.predict(x_train_temp)

#errors vector generation
anomaly_binary_vector = []
i=0
anomalies=0
for x_original,x_reconstructed in zip(x_train_temp,predicteds):
    MSE=np.square(np.subtract(x_original,x_reconstructed)).mean()
    if(MSE>=0.95*max_se):
        anomaly_binary_vector.append(1)
    else:
        anomaly_binary_vector.append(0)
    i+=1

Output:
anomalies 2419
not detected anomalies   2031
non anomaly but marked as anomaly   2383
percentage of non anomaly instructions that marked as anomalies out of non anomalies : 0.3143384777733808
percentage of  anomaly instructions that wasn't detected out of anomalies: 0.8396031417941298

How can I Improve My anomaly detection?

A: A problem can be that you are "blowing up" you're autoencoder. You have an input of 13 and than map that to 200, 150, 100 and 13 again. There is no bottleneck in the network where it has to learn a compressed representation of the input.
Maybe try 13 -> 6 -> 4 -> 6 -> 13 or something like that. Than it lears a compressed representation and the task to reconstruct the input is not trivial anymore.
Additionally play around with other hyperparameters like the activation function. Maybe change it to 'relu' in the intermediate models.


Q: Saving of Numeric with decimal to txt File from datagridview in vb.net This is my code for saving the values from data grid view to text file:
Private Sub TextFileToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles TextFileToolStripMenuItem.Click
    Dim filename As String = String.Empty
    Dim sfd1 As New SaveFileDialog()

    sfd1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
    sfd1.FilterIndex = 2
    sfd1.RestoreDirectory = True
    sfd1.Title = "Save Text File"

    If sfd1.ShowDialog() = DialogResult.OK Then
        If sfd1.FileName = String.Empty Then
            MsgBox("Please input filename")
        Else
            filename = sfd1.FileName.ToString
            Saveto_TextFile(dvList, filename)
        End If
    End If
End Sub

Sub Saveto_TextFile(ByVal dvList As DataGridView, ByVal filename As String)
    Dim numCols As Integer = dvList.ColumnCount - 1
    Dim numRows As Integer = dvList.RowCount
    Dim strDestinationFile As String = "" & filename & ".txt"
    Dim tw As TextWriter = New StreamWriter(strDestinationFile)

    For dvRow As Integer = 0 To numRows - 1
        'checking if the checkbox is checked, then write to text file
        If dvList.Rows(dvRow).Cells.Item(0).Value = True Then
            tw.Write("True")
            tw.Write(", ")
        Else
            tw.Write("False")
            tw.Write(", ")
        End If

        'write the remaining rows in the text file
        For dvCol As Integer = 1 To numCols
            tw.Write(dvList.Rows(dvRow).Cells(dvCol).Value)
            If (dvCol <> numCols) Then
                tw.Write(", ")
            End If
        Next
        tw.WriteLine()
    Next
    tw.Close()
End Sub

This code is perfectly working, but my only concern is that I set up the property of my data grid view to Numeric with 2 decimal places. When I'm saving it to the text file, it removes the decimal places.
What can I do to keep the decimal places in the text file?

A: I modified your SaveTo_TextFile method. I added two columns to my dvList [Column1] and [Column2]. I was able to save the decimal value I entered in [Column2] successfully.
I do not know how you formatted your DataGridView column but mine is only a DataGridViewTextBoxCell with no formatting.
If I used formatting, this is what I would set my numeric column's row cellstyle to:
dvList.Columns("Column2").DefaultCellStyle.Format = "N2"

SaveTo_TextFile method
Private Sub Saveto_TextFile(ByVal dvList As DataGridView, ByVal filename As String)
    Dim numCols As Integer = dvList.ColumnCount - 1
    Dim numRows As Integer = dvList.RowCount
    Dim strDestinationFile As String = "" & filename & ".txt"
    Dim tw As TextWriter = New StreamWriter(strDestinationFile)

    For dvRow As Integer = 0 To numRows - 1
        'checking if the checkbox is checked, then write to text file
        If dvList.Rows(dvRow).Cells("Column1").Value = True Then
            tw.WriteLine(dvList.Rows(dvRow).Cells("Column2").Value) 'Column2 is the name of the column ... You can also use an index here
        Else
            tw.WriteLine("Not Checked")
        End If

        'write the remaining rows in the text file
        For dvCol As Integer = 1 To numCols
            tw.WriteLine(dvList.Rows(dvRow).Cells(dvCol).Value)
            If (dvCol <> numCols) Then
                tw.WriteLine("???")
            End If
        Next
        tw.WriteLine()
    Next
    tw.Close()
End Sub


Q: Link to current page does nothing in AngularJS if I am on the /contact page on my website, if my nav bar has a link to the /contact and  I click it, nothing happens. But if I click any other link that isn't the current url, Angular responds correctly. How do I make it reload the current page when clicking a link to itself in AngularJS?

A: Create function which reloads controller and attach that function to view
$scope.reloadController = function ({
      $state.go($state.current, {}, { reload: true });
})

And atach it to link:
<a ng-click="reload()">Contacts</button>

A: If the link is to the current page it's actually smart that it doesn't reload. Try using a JavaScript function e.g. reload
http://www.w3schools.com/jsref/met_loc_reload.asp


Q: onchange event not alerting Could someone help me figure out why this isn't triggering?
$("input:radio[name=cm-fo-ozlkr]").change( function(){
             alert('Handler for .change() called.');
    });

HTML
<input type="radio" checked="checked" class="styled" value="1397935" id="cm1397935" name="cm-fo-ozlkr"><input type="radio" class="styled" value="1397934" id="cm1397934" name="cm-fo-ozlkr">

A: Your attribute selector was missing quotes;
$("input:radio[name='cm-fo-ozlkr']").change( function(){
             alert('Handler for .change() called.');
    });

A: Is the radio button HTML getting generated dynamically e.g. on an ajax refresh? If so, you want to use jQuery live:
$("input:radio[name=cm-fo-ozlkr]").live('change', function () {
    alert('Handler for .change() called.');
 });

A: Use the click event instead of change.
Also, the correct selector is input[name=cm-fo-ozlkr]:radio.

A: Try this....
$(document).ready(function(){
$("input:radio[name='cm-fo-ozlkr']").change( function(){
             alert('Handler for .change() called.');
    });
});

A: if you haven't already done so...
$(document).ready(function() {
  $("input:radio[name=cm-fo-ozlkr]").change( function(){
             alert('Handler for .change() called.');
    });

});


Q: Working with API's in Node, security of var I'm a php developer learning how to work with Node.
When you work with php and a private API which requires an API key, you're kind of safe since you can't view PHP code in the developers console.
But now I'm working with an API in Node which has this structure.
var AdwordsUser = require('node-adwords-es5');

var user = new AdwordsUser({
    developerToken: 'INSERT DEVELOPER TOKEN', //your adwords developerToken
    userAgent: 'Geen', //any company name
    clientCustomerId: 'INSERT CLIENT ID', //the Adwords Account id (e.g. 123-123-123)
    client_id: 'INSERT_OAUTH2_CLIENT_ID_HERE', //this is the api console client_id
    client_secret: 'INSERT_OAUTH2_CLIENT_SECRET_HERE',
    refresh_token: 'INSERT_OAUTH2_REFRESH_TOKEN_HERE'
});

Since this is JavaScript I assume you will be able to see all of this in the developers console. Which is not safe?
How do people usually solve this, or am I worrying for nothing?

A: Node runs on server side so its not possible to view it in the web console. you can only view the data coming from node server on HTTP or socket call.so relax and happy coding .


Q: ZF2 dont validate element inside a collection i have problems validating a Form with a element of type Collection,
First, I create a "Collection" type element and then I add several text type elements.
the form is rendered correctly, The problem is that the Form is always valid.
How i can validate a collection type element?
Form class:
class TestForm extends Form {

private $inputFilter;

public function __construct($name = null) {

    parent::__construct($name);

    $this->add(array(
        'name' => 'submit',
        'type' => 'Zend\Form\Element\Submit',
        'options' => array(
            'label' => 'Submit',
        ),
        'attributes' => array(
            'class' => 'form-control',
            'value' => 'submit'
        ),
    ));

    $docs = array(
        array('name' => "doc A"),
        array('name' => "doc B")
    );

    // add collection of docs.

    $collection = new \Zend\Form\Element\Collection();
    $collection->setName('docs');

    foreach ($docs as $key => $doc) {

        $element = new \Zend\Form\Element\Text($key);

        $element->setOptions(array(
            'label' => $doc['name'],
        ));

        $element->setAttributes(array(
            'class' => 'form-control input-sm',
        ));

        $collection->add($element);
    }

    $this->add($collection);
}

public function getInputFilter() {

    $this->inputFilter = new InputFilter();

    $this->inputFilter->add(array(
        'name' => "docs",
        'required' => true,
        'filters' => array(
            array('name' => 'StripTags'),
            array('name' => 'StringTrim'),
        ),
    ));

    return $this->inputFilter;
}

}
Controller class:
class IndexController extends AppController {

public function indexAction() {

    $form = new \Application\Model\Form\TestForm();

    $request = $this->getRequest();

    if ($request->isPost()) {

        $data = $this->params()->fromPost();
        $form->setData($data);
        $form->setInputFilter($form->getInputFilter());

        if ($form->isValid()) {
            pr("is valid");
        } else {
            pr($form->getMessages());
        }
    }

    return new ViewModel(array(
        'form' => $form
    ));
}

View class:
<?php
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formRow($form->get('docs'));
echo $this->formRow($form->get('submit'));
echo $this->form()->closeTag();
?>

A: Your Collection is always valid, because it contains fields. You can't do this that way.
You should considering to add Validators to DocAand DocBfields instead. This will work as follow to set correct input filters :
$form->getInputFilter()->get('docs')->get('DocA')->getValidatoChain()->attachByName('YourValidatorName');

for a custom validator.
OR :
$form->getInputFilter()->get('docs')->get('DocA')->setRequired(true);
$form->getInputFilter()->get('docs')->get('DocA')->setAllowEmpty(false);

And you can also add Zend validators to them.
$form->getInputFilter()->get('docs')->get('DocA')->getValidatorChain()->attach(new NotEmpty([with params look docs for that])

Careful if you don't use ServiceManager for retrieve validators you'll need to set the translator as options.
Don't forget to set your validationGroup correctly or don't specify one to use VALIDATE_ALL.
The same way as validators you can also add Filters as follow :
$form->getInputFilter()->get('docs')->get('DocA')->getFilterChain()->getFilters()->insert(new StripTags())->insert(new StringTrim())


Q: where i can get blacklist spam email domain dataset? I wanna create an email classifier
the classifier will be divide by email, subject, content classifier
for email classifier, I need a list of blacklist domain such as @blablabla.com @cacacaca.com etc.
like this set here
but I need an up to date domain, so where I can get them? thanks

A: I wonder if a good way might be to go to mxtoolbox, do a blacklist test, then get a list of blacklist sites and see if you can contact them to get a list?
I suspect that such companies may consider those datasets their intellectual property and probably won't publish these - it may not be possible.
Good luck!
Also Akismet may have such a dataset?
Additionally, the more powerful email classifying software works by using patterns that you can make. Check out MailMarshall88 for example. You could use this to build your own dataset, but remember that just because someone is on a blacklist today, doesn't mean that they're always bad. For example, you might get a virus outbreak in your company which spams people and gets your IP blacklisted. You then fix the virus and are now incorrectly blacklisted. In this scenario a pattern would work much better.


Q: Error 0x800706F7 "The stub received bad data" on Windows XP SP3 In my VB6 application I make several calls to a COM server my team created from a Ada project (using GNATCOM). There are basically 2 methods available on the COM server. Their prototypes in VB are:
Sub PutParam(Param As Parameter_Type, Value)
Function GetParam(Param As Parameter_Type)

where Parameter_Type is an enumerated type which distinguishes the many parameters I can put to/get from the COM server and 'Value' is a Variant type variable. PutParam() receives a variant and GetParam() returns a variant. (I don't really know why in the VB6 Object Browser there's no reference to the Variant type on the COM server interface...).
The product of this project has been used continuously this way for years without any problems in this interface on computers with Windows XP with SP2. On computers with WinXP SP3 we get the error 0x800706F7 "The stub received bad data" when trying to put parameters with the 'Long' type.
Does anybody have any clue on what could be causing this? The COM server is still being built in a system with SP2. Should make any difference building it on a system with SP3? (like when we build for X64 in X64 systems).
One of the calls that are causing the problem is the following (changed some var names):
Dim StructData As StructData_Type

StructData.FirstLong = 1234567
StructData.SecondLong = 8901234
StructData.Status = True

ComServer.PutParam(StructDataParamType, StructData)

Where the definition of StructData_Type is:
Type StructData_Type
    FirstLong As Long
    SecondLong As Long
    Status As Boolean
End Type

(the following has been added after the question was first posted)
The definition of the primitive calls on the interface of the COM server in IDL are presented below:
// Service to receive data
HRESULT PutParam([in] Parameter_Type Param, [in] VARIANT *Value);

//Service to send requested data
HRESULT GetParam([in] Parameter_Type Param, [out, retval] VARIANT *Value);

The definition of the structure I'm trying to pass is:
struct StructData_Type
{
   int FirstLong;
   int SecondLong;
   VARIANT_BOOL Status;
} StructData_Type;

I found it strange that this definition here is using 'int' as the type of FirstLong and SeconLong and when I check the VB6 object explorer they are typed 'Long'. Btw, when I do extract the IDL from the COM server (using a specific utility) those parameters are defined as Long.
Update:
I have tested the same code with a version of my COM server compiled for Windows 7 (different version of GNAT, same GNATCOM version) and it works! I don't really know what happened here. I'll keep trying to identify the problem on WinXP SP3 but It is good to know that it works on Win7. If you have a similar problem it may be good to try to migrate to Win7.

A: I'll focus on explaining what the error means, there are too few hints in the question to provide a simple answer.
A "stub" is used in COM when you make calls across an execution boundary.  It wasn't stated explicitly in the question but your Ada program is probably an EXE and implements an out-of-process COM server.  Crossing the boundary between processes in Windows is difficult due to their strong isolation.  This is done in Windows by RPC, Remote Procedure Call, a protocol for making calls across such boundaries, a network being the typical case.
To make an RPC call, the arguments of a function must be serialized into a network packet.  COM doesn't know how to do this because it doesn't know enough about the actual arguments to a function, it needs the help of a proxy.  A piece of code that does know what the argument types are.  On the receiving end is a very similar piece of code that does the exact opposite of what the proxy does.  It deserializes the arguments and makes the internal call.  This is the stub.
One way this can fail is when the stub receives a network packet and it contains more or less data than required for the function argument values.  Clearly it won't know what to do with that packet, there is no sensible way to turn that into a StructData_Type value, and it will fail with "The stub received bad data" error.
So the very first explanation for this error to consider is a DLL Hell problem.  A mismatch between the proxy and the stub.  If this app has been stable for a long time then this is not a happy explanation.
There's another aspect about your code snippet that is likely to induce this problem.  Structures are very troublesome beasts in software, their members are aligned to their natural storage boundary and the alignment rules are subject to interpretation by the respective compilers.  This can certainly be the case for the structure you quoted.  It needs 10 bytes to store the fields, 4 + 4 + 2 and they align naturally.  But the structure is actually 12 bytes long.  Two bytes are padded at the end to ensure that the ints still align when the structure is stored in an array.  It also makes COM's job very difficult, since COM hides implementation detail and structure alignment is a massive detail.  It needs help to copy a structure, the job of the IRecordInfo interface.  The stub will also fail when it cannot find an implementation of that interface.
I'll talk a bit about the proxy, stub and IRecordInfo.  There are two basic ways a proxy/stub pair are generated.  One way is by describing the interfaces in a language called IDL, Interface Description Language, and compile that with MIDL.  That compiler is capable of auto-generating the proxy/stub code, since it knows the function argument types. You'll get a DLL that needs to be registered on both the client and the server.  Your server might be using that, I don't know.
The second way is what VB6 uses, it takes advantage of a universal proxy that's built into Windows.  Called FactoryBuffer, its CLSID is {00000320-0000-0000-C000-000000000046}.  It works by using a type library.  A type library is a machine readable description of the functions in a COM server, good enough for FactoryBuffer to figure out how to serialize the function arguments.  This type library is also the one that provides the info that IRecordInfo needs to figure out how the members of a structure are aligned.  I don't know how it is done on the server side, never heard of GNATCOM before.
So a strong explanation for this problem is that you are having a problem with the type library.  Especially tricky in VB6 because you cannot directly control the guids that it uses.  It likes to generate new ones when you make trivial changes, the only way to avoid it is by selecting the binary compatibility option.  Which uses an old copy of the type library and tries to keep the new one as compatible as possible.  If you don't have that option turned on then do expect trouble, especially for the guid of the structure.  Kaboom if it changed and the other end is still using the old guid.
Just some hints on where to start looking.  Do not assume it is a problem caused by SP3, this COM infrastructure hasn't changed for a very long time.  But certainly expect this kind of problem due to a new operating system version being installed and having to re-register everything.  SysInternals' ProcMon is a good utility to see the programs use the registry to find the proxy,  stub and type library.  And you'd certainly get help from a COM Spy kind of utility, albeit that they are very hard to find these days.

A: If it suddenly stopped working happily on XP, the first culprit I'd look for is type mismatches. It is possible that "long" on such systems is now 64-bits, while your Ada COM code (and/or perhaps your C ints) are exepecting 32-bits. With a traditionally-compiled system this would have been checked for you by your compiler, but the extra indirection you have with COM makes that difficult.
The bit you wrote in there about "when we compile for 64-bit systems" makes me particularly leery. 64-bit compiles may change the size of many C types, you know.

A: This Related Post suggests you need padding in your struct, as marshalling code may expect more data than you actually send (which is a bug, of course). Your struct contains 9 bytes (assuming 4 bytes for each of the ints/longs and one for the boolean). Try to add padding so that your struct contains a multiple of 4 bytes (or, failing that, multiple of 8, as the post isn't clear on the expected size)

A: I am also suggesting that the problem is due to a padding issue in your structure. I don't know whether you can control this using a #pragma, but it might be worth looking at your documentation.
I think it would be a good idea to try and patch your struct so that the resulting type library struct is a multiple of four (or eight). Your Status member takes up 2 bytes, so maybe you should insert a dummy value of the same type either before or after Status - which should bring it up to 12 bytes (if packing to eight bytes, this would have to be three dummy variables).


Q: How can I introduce my VS 2019 to Unreal Engine? I have installed VS 2019 and UE4 v.4.11.0 but when I want to open a C++ project in UE4 I see that it can not recognize my VS2019 compiler.
How can I fix it?

A: Support for Visual Studio 2019 has been added to Unreal Engine 4.22: Release Notes.
After updating to Unreal Engine 4.22 or newer, ensure that you have set the Source Code Editor to Visual Studio 2019 in the Editor Preferences.
Additionally, if you have created your project with an earlier version of Visual Studio, you have to regenerate your project files: right click your .uproject file and click Generate Visual Studio project files.


Q: How to set an array in json response goLang-gin I have an array of stucts stored a variable my array.
Struct is
  type myStruct struct {
    id          int64   `db:"id" json:"id"`
    Name        string  `form:"name" db:"name" json:"name" binding:"required"`
    Status     string     `form:"status"  db:"status" json:"status" binding:"required"`

My array looks like this and is stored in a variable 'myArray'. This array is formed by iterating over a set of rows coming from database.
[{1 abc default} {2 xyz default}]

I am using gin as http server. How do I set this array into JSON reponse using c.JSON. Something like
[
   {
      id: 1,
      name : 'abc'
      status: 'default'
   },
   {
      id: 2,
      name : 'xyz'
      status: 'default'
   }
]

A: ok c.JSON(http.StatusOK, myArray) worked. But I cannot see the Id field in the response. Any reason why? Is it because of 'int64' dataType?


Q: Rebuild existing EC2 instance from snapshot? I have an existing linux EC2 instance with a corrupted root volume.  I have a snapshot of the root that is not corrupted.   Is it possible with terraform to rebuild the instance based on the snapshot ID of the snapshot ?

A: Of course it is possible, this simple configuration should do the job:
resource "aws_ami" "aws_ami_name" {
name = "aws_ami_name"
virtualization_type = "hvm"
root_device_name = "/dev/sda1"

    ebs_block_device {
        snapshot_id = "snapshot_ID”
        device_name = "/dev/sda1"
        volume_type = "gp2"
    }
}

resource "aws_instance" "ec2_name" {
    ami = "${aws_ami.aws_ami_name.id}"
    instance_type = "t3.large"
}

A: It's not really a Terraform-type task, since you're not deploying new infrastructure.
Instead, do it manually:

*

*Create a new EBS Volume from the Snapshot

*Stop the instance

*Detach the existing root volume (make a note of the device identifier such as /dev/sda1)

*Attach the new Volume with the same identifier

*Start the instance


Q: NetworkX: structuring a simple flow study on a graph If you consider the following graph:
from __future__ import division
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
from numpy.linalg import inv

G = nx.Graph()

pos={1:(2,3),2:(0,0),3:(6,0)}
G.add_nodes_from(pos.keys())
nx.set_node_attributes(G, 'coord', pos)

PE={1:0,2:60,3:40}
nx.set_node_attributes(G,'PE',PE)
q={1:100,2:0,3:0}
nx.set_node_attributes(G,'q',q)

G.add_edge(1,2)
G.add_edge(1,3)
G.add_edge(2,3)

import math
lengths={}
inv_lengths={}
for edge in G.edges():
    startnode=edge[0]
    endnode=edge[1]
    lengths[edge]=round(math.sqrt(((pos[endnode][1]-pos[startnode][1])**2)+
                                      ((pos[endnode][0]-pos[startnode][0])**2)),2)
    inv_lengths[edge]=round(1/lengths[edge],3)
nx.set_edge_attributes(G, 'length', lengths)
nx.set_edge_attributes(G, 'inv_length', inv_lengths)
nx.draw(G,pos,node_size=1000,node_color='r',with_labels=True)
nx.draw_networkx_edge_labels(G,pos)
plt.show()

And the following flow problem:

where 1 is a supply-only node and 2 and 3 are demand-only, how come that the following solution yields weird values of flow through each edge? It seems like q1=100 is not even considered, and I expect L2 to have flow=0.
m=nx.laplacian_matrix(G,weight='inv_length')
a=m.todense()

flow={}
res2=np.dot(a,b) #No inverse is required: x=ab
res2=[round(item,3) for sublist in res2.tolist() for item in sublist]
print res2
for i,e in enumerate(G.edges()):
   flow[e]=res2[i]

b=[]
for i,v in enumerate(PE.values()):
    b.append(v)
res2=np.dot(a,b) #No inverse is required: x=ab
res2=[round(item,3) for sublist in res2.tolist() for item in sublist]
print res2

#res2=[-24.62, 19.96, 4.66]

A: I have taken the liberty to compute edge lengths in a simpler way:
from scipy.spatial.distance import euclidean
lengths = {}
inv_lengths = {}
for edge in G.edges():
    startnode = edge[0]
    endnode = edge[1]
    d = euclidean(pos[startnode], pos[endnode])
    lengths[edge] = d
    inv_lengths[edge] = 1/d

And this is how I implemented the matrix equation   :
E = np.array([[0],
              [60],
              [40]], dtype=np.float64)

L1 = lengths[(1, 2)]
L2 = lengths[(2, 3)]
L3 = lengths[(1, 3)]

L = np.array([[1/L1 + 1/L3,       -1/L1,       -1/L3],
              [      -1/L1, 1/L1 + 1/L2,       -1/L2],
              [      -1/L3,       -1/L2, 1/L2 + 1/L3]], dtype=np.float64)

qLE = np.dot(L, E)

The code above yields the same result (approximately) than yours:
In [55]: np.set_printoptions(precision=2)

In [56]: qLE
Out[56]:
array([[-24.64],
       [ 19.97],
       [  4.67]])

In summary, I think this is not a programming issue. Perhaps you should revise the flow model...


Q: Starting apache derby programmatically I am a newbie to java. In, my project, I have used JDBC. It worked fine till netbeans was on. But, when I turned off netbeans and executed the jar file, I got the following error :-
java.sql.SQLNonTransientConnectionException: java.net.ConnectException : Error
connecting to server localhost on port 1527 with message Connection refused.

I read this answer at -> https://stackoverflow.com/a/9725496/2464420,but I could not achieve the desired result. I got the following:-

Please help me.

A: There is a compilation error in your project
You must add derbynet.jar dependency in your classpath in order to embed the server.
http://db.apache.org/derby/papers/DerbyTut/ns_intro.html#ns_config_env
Client and server dependencies are two different jar.


Q: Cakephp 3 Appending args variable in all pagination links I am using CakePHP V3.5.10
Once I cake bake my code any paginator works because is appending this args
a variable that looks like this:
domain.com/admin/categories?args=&page=3
So when I var_dump it I get this : var_dump($this->request->params);
array(9) {
    ["controller"]=>
    string(10) "Categories"
        ["pass"]=>
    array(0) {
    }
    ["action"]=>
    string(5) "index"
        ["prefix"]=>
    string(5) "admin"
        ["plugin"]=>
    NULL
        ["_matchedRoute"]=>
    string(18) "/admin/:controller"
        ["?"]=>
    array(1) {
        ["args"]=>
        string(0) ""
    }
    ["_ext"]=>
    NULL
        ["isAjax"]=>
    bool(false)
}

if you can see the place where normally should be "page" is "args" instead
so I check a diff application of mine and how normally should look is like this:
Healthy URL: domain.com/admin/categories?page=3
array(9) {
    ["controller"]=>
    string(10) "Categories"
        ["pass"]=>
    array(0) {
    }
    ["action"]=>
    string(5) "index"
        ["prefix"]=>
    string(5) "admin"
        ["plugin"]=>
    NULL
        ["_matchedRoute"]=>
    string(18) "/admin/:controller"
        ["?"]=>
    array(1) {
        ["page"]=>
        string(1) "2"
    }
    ["_ext"]=>
    NULL
        ["isAjax"]=>
    bool(false)
}

As you can see here I have
array(1) {
   ["page"]=>
   string(1) "2"

So that is why paginator doesn't work because can't read the ?page plus is passing this ?args that is empty... but what is not known is why paginator will behave in this way? and what to do to make it work?
If is there someone could help with this I'll be really thankful. I've been comparing even codes of the paginator and certainly no idea why this is happening.

A: OK if you find this error is because of the way the data is being passing
Ex:  ?page=1&sort=name&direction:asc is not a CakePHP way of handling params.
A right format url in cake should be nice looking like this:  domain.com/2/name/asc
The way I end it up passing the params in routes.php:
$routes->connect('/productoptions/:page/:sort/:direction', ['controller' => 'Productoptions', 'action' => 'index'], ['param' => ['page'], 'param2' => ['sort'], 'param3' => ['direction'] ]);

So I can use $this->request->params['page] , $this->request->params['direction] etc...
In this way, I use CakePHP way of passing and handling params instead of $_GET


Q: How to add a prefix to every row of a particular column in a CSV file via command line on Linux I am trying to achieve the following.
File before editing.
column-1,  column-2,  column-3,  column-4,  column-5
Row-1-c1,  Row-1-c2,  Row-1-c3,  Row-1-c4,  Row-1-c5
Row-2-c1,  Row-2-c2,  Row-2-c3,  Row-2-c4,  Row-2-c5
Row-3-c1,  Row-3-c2,  Row-3-c3,  Row-3-c4,  Row-3-c5
Row-4-c1,  Row-4-c2,  Row-4-c3,  Row-4-c4,  Row-4-c5
Row-5-c1,  Row-5-c2,  Row-5-c3,  Row-5-c4,  Row-5-c5

File after editing
column-1,   column-2,   column-3,           column-4,   column-5
Row-1-c1,   Row-1-c2,   Prefix-Row-1-c3,    Row-1-c4,   Row-1-c5
Row-2-c1,   Row-2-c2,   Prefix-Row-2-c3,    Row-2-c4,   Row-2-c5
Row-3-c1,   Row-3-c2,   Prefix-Row-3-c3,    Row-3-c4,   Row-3-c5
Row-4-c1,   Row-4-c2,   Prefix-Row-4-c3,    Row-4-c4,   Row-4-c5
Row-5-c1,   Row-5-c2,   Prefix-Row-5-c3,    Row-5-c4,   Row-5-c5

Notice that column-3 is the column that the prefix is added to each individual row except the column heading.
I was wondering which editor would be the best editor to use and find out how to use the commands to get the desired result.

A: Maybe a better question would be "How many different tools could you use for the job?"
I'd probably go with awk as the easiest tool that does the job reasonably simply:
awk -F, 'NR == 1 { print; OFS="," } NR > 1 { sub(/^ +/, "&Prefix-", $3); print }'

The sub operation adds Prefix- after the spaces at the start of column 3.  The code does not attempt to adjust the content of line 1 (the heading); if you want spaces added after $3, then I suppose this does the job (because of the placement of commas, you prefix the extra spaces to column 4 of line 1):
awk -F, 'NR == 1 { OFS=","; $4 = "       " $4; print }
         NR  > 1 { sub(/^ +/, "&Prefix-", $3); print }'

Do you know how to do the same thing with sed?

Yes, like this:
sed -e '  1s/^\(\([^,]*,[[:space:]]*\)\{3\}\)/\1       /' \
    -e '2,$s/^\(\([^,]*,[[:space:]]*\)\{2\}\)/\1Prefix-/' "$@"

The first expression deals with the first line; it puts as many spaces as there are in the prefix (here that's "Prefix-" so it's 7 spaces) after the third column.  The second expression deals with the remaining lines; it adds the prefix before the third column.
To deal with column N instead of column 3, change the 3 to N and the 2 inside \{2\} to N-1.
I rechecked the second Awk script; it produces the correct output for me on the sample data from the question.  So, within its limitations, does the first Awk script.  Make sure you're using something other than the C shell (it gets upset by multi-line quoted strings), and that you were careful with your copying.
Example output
$ cat data
column-1,  column-2,  column-3,  column-4,  column-5
Row-1-c1,  Row-1-c2,  Row-1-c3,  Row-1-c4,  Row-1-c5
Row-2-c1,  Row-2-c2,  Row-2-c3,  Row-2-c4,  Row-2-c5
Row-3-c1,  Row-3-c2,  Row-3-c3,  Row-3-c4,  Row-3-c5
Row-4-c1,  Row-4-c2,  Row-4-c3,  Row-4-c4,  Row-4-c5
Row-5-c1,  Row-5-c2,  Row-5-c3,  Row-5-c4,  Row-5-c5
$ bash manglesed.sh data
column-1,  column-2,  column-3,         column-4,  column-5
Row-1-c1,  Row-1-c2,  Prefix-Row-1-c3,  Row-1-c4,  Row-1-c5
Row-2-c1,  Row-2-c2,  Prefix-Row-2-c3,  Row-2-c4,  Row-2-c5
Row-3-c1,  Row-3-c2,  Prefix-Row-3-c3,  Row-3-c4,  Row-3-c5
Row-4-c1,  Row-4-c2,  Prefix-Row-4-c3,  Row-4-c4,  Row-4-c5
Row-5-c1,  Row-5-c2,  Prefix-Row-5-c3,  Row-5-c4,  Row-5-c5
$ bash mangleawk.sh data
column-1,  column-2,  column-3,         column-4,  column-5
Row-1-c1,  Row-1-c2,  Prefix-Row-1-c3,  Row-1-c4,  Row-1-c5
Row-2-c1,  Row-2-c2,  Prefix-Row-2-c3,  Row-2-c4,  Row-2-c5
Row-3-c1,  Row-3-c2,  Prefix-Row-3-c3,  Row-3-c4,  Row-3-c5
Row-4-c1,  Row-4-c2,  Prefix-Row-4-c3,  Row-4-c4,  Row-4-c5
Row-5-c1,  Row-5-c2,  Prefix-Row-5-c3,  Row-5-c4,  Row-5-c5
$ cat manglesed.sh
sed -e '  1s/^\(\([^,]*,[[:space:]]*\)\{3\}\)/\1       /' \
    -e '2,$s/^\(\([^,]*,[[:space:]]*\)\{2\}\)/\1Prefix-/' "$@"
$ cat mangleawk.sh
awk -F, 'NR == 1 { OFS=","; $4 = "       " $4; print }
         NR  > 1 { sub(/^ +/, "&Prefix-", $3); print }' "$@"
$ awk -F, 'NR == 1 { print; OFS="," } NR > 1 { sub(/^ +/, "&Prefix-", $3); print }' data
column-1,  column-2,  column-3,  column-4,  column-5
Row-1-c1,  Row-1-c2,  Prefix-Row-1-c3,  Row-1-c4,  Row-1-c5
Row-2-c1,  Row-2-c2,  Prefix-Row-2-c3,  Row-2-c4,  Row-2-c5
Row-3-c1,  Row-3-c2,  Prefix-Row-3-c3,  Row-3-c4,  Row-3-c5
Row-4-c1,  Row-4-c2,  Prefix-Row-4-c3,  Row-4-c4,  Row-4-c5
Row-5-c1,  Row-5-c2,  Prefix-Row-5-c3,  Row-5-c4,  Row-5-c5
$


Q: NSMutableArray addObject freezes my app Tons of similar questions, but none of their answers seem to answer mine...
I'm creating my array as such:
imgArray = [NSMutableArray arrayWithCapacity:10];

Later (in another function) I am trying to add an object to it:
Attachment newAttachment = [[[Attachment alloc] init] autorelease];
newAttachment.fileName = filename;
newAttachment.file = file;
[imgArray addObject:newAttachment];

This results in the iPhone app freezing up.  The simulator seems fine; the clock on the status bar keeps ticking, I don't get any error messages, but my app is no longer responding.
What am I doing wrong?

A: It seems you are not retaining imgArray. Are you? Try,
imgArray = [[NSMutableArray alloc] initWithCapacity:10]

if not.

A: just do
imgArray = [[NSMutableArray arrayWithCapacity:10] retain];

all class methods if return an object is returned with retain count 1 and object already in autorelease pool so if want to use that object beyond the current working block the you should always retain that object because then reference is lost outside the block.


Q: How to assign weight for a word? I have a list of words for four categories. There are 10 words for each category. Now I want to assign a weight for each word in the list. For example if one category has words:
 disease
 fall
 have
 ventilator
 tumour
 country
 sewing
 demo
 precaution
 analysis

Now for each of these words I want to give a weight. For example disease should be given weight 1(by dividing 10 by 10), fall should be given weight 0.9 (by dividing 9 by 10), have should be given 0.8 and so on. How to write this code in R? Can anyone help me in this regard? Thanks in advance.
I want my output to be:
Death               Malfunction         Weight
distance             malformed             1
fall                 unformed             0.9
have                 intensive            0.8
ventilator           malfunctioned        0.7
tumour               front                0.6
country              icu                  0.5
sewing               injury               0.4
demo                 care                 0.3
precaution           disease              0.2
analysis             diagnosis            0.1


Q: C# Saving Panel as image at Multithread I don't have any problem saving panel as image with UI thread but i have only a black rectangle when i save this panel at another thread except UI thread :
using (Bitmap bmp = new Bitmap(panel1.Width, panel1.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb))
        {
            if (panel1.InvokeRequired)
            {
                panel1.BeginInvoke((MethodInvoker)delegate ()
                {
                    panel1.DrawToBitmap(bmp, new System.Drawing.Rectangle(Point.Empty, bmp.Size));

                });
                Bitmap bb = bmp.Clone(new System.Drawing.Rectangle(0, 0, 1016, 648), PixelFormat.Format24bppRgb);
                bb.Save(@"C:\sample.bmp", ImageFormat.Bmp);
            }
            else
            {
              panel1.DrawToBitmap(bmp, new System.Drawing.Rectangle(Point.Empty, bmp.Size));
              Bitmap bb = bmp.Clone(new System.Drawing.Rectangle(0, 0, 1016, 648), PixelFormat.Format24bppRgb);
              bb.Save(@"C:\sample.bmp", ImageFormat.Bmp);
            }

        }

This problem is related with locking mechanism? Or how can i solve this problem?
Thanks in advance.

A: Universal answer (with explanation):
BeginInvoke is function that send a message 'this function should be executed in different thread' and then directly leaves to continue execution in current thread.
The function is executed at a later time, when the target thread has 'free time' (messages posted before are processed).
When you need the result of the function, use Invoke. The Invoke function is 'slower', or better to say it blocks current thread until the executed function finishes. (I newer really tested this in C#, but it s possible, that the Invoke function is prioritized; e.g. when you call BeginInvoke and directly after it Invoke to the same thread, the function from Invoke will probably be executed before the function from BeginInvoke.)
Use this alternative when you need the function to be executed before the next instruction are processed (when you need the result of the invoked function).
Simple (tl;dr): When you need to need to only set a value (e.g. set text of edit box), use BeginInvoke, but when you need a result (e.g. get text from edit box) use always Invoke.
In your case you need the result (bitmap to be drawn) therefore you need to wait for the function to end. (There are also other possible options, but in this case the simple way is the better way.)


Q: How to import csv files with sorted file names? I am trying to import multiple csv files and when I run the below code it does work.
allfiles = glob.glob('*.csv')
allfiles

However, this results in:
['file_0.csv',
'file_1.csv',
'file_10.csv',
'file_100.csv',
'file_101.csv,
...
]

As you can see, the imported files are not sorted numbers. What I want is to have my numbers in my file names to be in ascending order:
['file_0.csv',
'file_1.csv',
'file_2.csv',
'file_3.csv',
...
]

How do I solve the problem?

A: allfiles = glob.glob('*.csv')
allfiles.sort(key= lambda x: int(x.split('_')[1].split('.')[0]))

A: You can't do that with glob, you need to sort the resultant files yourself by the integer each file contains:
allfiles = glob.iglob('*.csv')

allfiles_sorted = sorted(allfiles, key=lambda x: int(re.search(r'\d+', x).group()))

Also note that, i've used glob.iglob instead of glob.glob as there is no need to make an intermediate list where an iterator would do the job fine.

A: Check with natsort
from natsort import natsorted
allfiles=natsorted(allfiles)

A: os.listdir() will give the list of files in that folder and sorted will sort it
import os
sortedlist = sorted(os.listdir())

EDIT: just specify key = len to count the length of an element
 sorted(os.listdir(),key = len)

A: This is also a way to do that. This algorithm will sort with length of file name string.
import glob

all_files = glob.glob('*.csv')

def sort_with_length(file_name):
    return len(file_name)

new_files = sorted(all_files, key = sort_with_length )

print("Old files:")
print(all_files)
print("New files:")
print(new_files)

Sample output:
Old files:
['file1.csv', 'file101.csv', 'file102.csv', 'file2.csv', 'file201.csv', 'file3.csv']
New files:
['file1.csv', 'file2.csv', 'file3.csv', 'file101.csv', 'file102.csv', 'file201.csv']


Q: Ionic Build iOS - Fail I've been workign on this project for months now with no major issues. Today I can't even get it to build out. I ran "$ionic resources" and now I can't get my build to work at all.
I'm getting this error:
    ** BUILD FAILED **

The following build commands failed:
    CompileAssetCatalog build/emulator/Stopper.app Stopper/Images.xcassets
(1 failure)
ERROR building one of the platforms: Error code 65 for command: xcodebuild with args: -xcconfig,/Users/colemanjeff/GitHub/StopperRC1/platforms/ios/cordova/build-debug.xcconfig,-project,Stopper.xcodeproj,ARCHS=i386,-target,Stopper,-configuration,Debug,-sdk,iphonesimulator,build,VALID_ARCHS=i386,CONFIGURATION_BUILD_DIR=/Users/colemanjeff/GitHub/StopperRC1/platforms/ios/build/emulator,SHARED_PRECOMPS_DIR=/Users/colemanjeff/GitHub/StopperRC1/platforms/ios/build/sharedpch
You may not have the required environment or OS to build this project
Error: Error code 65 for command: xcodebuild with args: -xcconfig,/Users/colemanjeff/GitHub/StopperRC1/platforms/ios/cordova/build-debug.xcconfig,-project,Stopper.xcodeproj,ARCHS=i386,-target,Stopper,-configuration,Debug,-sdk,iphonesimulator,build,VALID_ARCHS=i386,CONFIGURATION_BUILD_DIR=/Users/colemanjeff/GitHub/StopperRC1/platforms/ios/build/emulator,SHARED_PRECOMPS_DIR=/Users/colemanjeff/GitHub/StopperRC1/platforms/ios/build/sharedpch

I'm not sure what caused the problem or how to fix it. Anyone have any idea?

A: Turns out I actually did need to uninstall the platform, remove the plugin json file, and then reinstall everything.

A: Run (this will remove the old ionic ios platform)
sudo ionic platform rm ios

Then (this will install a new platform with privileges)
sudo ionic platform add ios

Then build your code ios/android
ionic build ios
ionic build android

This fixed it for me!
Might be that you should also run
sudo ionic resources

to generate new icon and splash screens.

A: Basically, re-installation of Platform and Plugins once again resolves the issue.


Q: Total the hours worked, then filter out 30mins where the segment per datekey contains lunch I have a table called Shifts, below is a sample of the data
ID Key  DateKey  Start                End                  Hours     Segment
1  1001 20210101 2021-01-01 09:00:00  2021-01-01 09:00:00  4.000000  On-Call
2  1001 20210101 2021-01-01 11:00:00  2021-01-01 11:15:00  0.250000  Break
3  1001 20210102 2021-01-02 13:00:00  2021-01-01 19:00:00  6.000000  On-Call
4  1001 20210102 2021-01-02 15:00:00  2021-01-01 15:15:00  0.250000  Break
5  1001 20210102 2021-01-02 17:00:00  2021-01-01 17:30:00  0.500000  Lunch
6  1001 20210103 2021-01-03 09:00:00  2021-01-03 16:00:00  7.000000  On-Call
7  1001 20210103 2021-01-03 11:00:00  2021-01-03 11:15:00  0.250000  Break
8  1001 20210103 2021-01-03 13:00:00  2021-01-03 13:30:00  0.500000  Lunch
9  1002 20210104 2021-01-04 09:00:00  2021-01-04 09:00:00  4.000000  On-Call
10 1002 20210104 2021-01-04 11:00:00  2021-01-04 11:15:00  0.250000  Break
11 1002 20210105 2021-01-05 07:00:00  2021-01-05 14:00:00  7.000000  On-Call
12 1002 20210105 2021-01-05 09:00:00  2021-01-05 09:15:00  0.250000  Break
13 1002 20210105 2021-01-05 11:00:00  2021-01-05 11:30:00  0.500000  Lunch

I'm trying to:

*

*Total the hours per DateKey e.g DateKey 20210101 and ID 1 and 2 total hours worked is 4.250000.

*After totalling the hours worked for that day subtract 30mins from the total work hours if the segment for that datekey contains lunch e.g 20210102 total hours worked ( ID 3,4,5 ) is 6.750000 subtract 30mins.

A: --Group data on datekey, then sum it without lunch
select datekey,sum(hours)[total]
from newtbl
where segment!='lunch'
group by datekey

A: to find total hours per columns, I would use something like this:
Select Key,sum(hours) from Shifts where DateKey == 20210101;

to exclude the lunchtime from total work:

SELECT  key,sum(hours) FROM Shifts where  seg <> "lunch" GROUP by key


Q: Getting incorrect creation dates using 'aws s3' I have two buckets. In the AWS Console they have the following "Date created"
2017-11-22 14:07:03 i-repo
2018-01-12 17:16:31 l-repo

Using the AWS CLI (aws-cli/1.16.90 Python/3.7.2 Darwin/17.7.0 botocore/1.12.80) command aws s3 ls, I get the following:
2018-02-08 12:49:03 i-repo
2018-12-19 15:55:29 l-repo

Using the AWS CLI command aws s3api list-buckets, I get the same incorrect dates. I have confirmed that the dates that the AWS CLI reports relate to the date of the most recent bucket policy change, NOT the bucket create date. Am I missing something, or is this a bug?

A: Looks like this is a known issue/intended. See below:

After further investigation and discussion with the S3 team, I have found that this is expected behavior due to the design of the service. The GET Service call in S3 (s3api list-buckets or s3 ls with no further arguments in the CLI) works differently when being run against different regions. All bucket creations are mastered in us-east-1, then replicated on a global scale - the resulting difference is that there are no "replication" events to the us-east-1 region. The Date Created field displayed in the web console is according to the actual creation date registered in us-east-1, while the AWS CLI and SDKs will display the creation date depending on the specified region (or the default region set in your configuration).
When using an endpoint other than us-east-1, the CreationDate you receive is actually the last modified time according to the bucket's last replication time in this region. This date can change when making changes to your bucket, such as editing its bucket policy. This experienced behavior is result of how S3's architecture has been designed and implemented, making it difficult to change without affecting customers that already expect this behavior.
S3 does intend to change this behavior so that the actual bucket creation date is shown regardless of the region in which the GET Service call is issued, however to answer your question we do not yet have an ETA for the implementation of this change. This change would most likely be announced in the AWS Forums for S3 if you'd like to know when it takes place.

Source


Q: "Compile Server Error." while building OpenCL kernels I am trying to compile OpenCL kernels on OS X. Everything is ok when there are just a few lines. However, after the code grows over 1.5k lines, clGetProgramBuildInfo with CL_PROGRAM_BUILD_LOG flag returned "Compile Server Error." every time. I googled but found nothing about it. Could anyone help me?

A: You can learn the meaning of OpenCL error codes by searching in cl.h. In this case, -11 is just what you'd expect, CL_BUILD_PROGRAM_FAILURE. It's certainly curious that the build log is empty. Two questions:
1.) What is the return value from clGetProgramBuildInfo?
2.) What platform are you on? If you are using Apple's OpenCL implementation, you could try setting CL_LOG_ERRORS=stdout in your environment. For example, from Terminal:
$ CL_LOG_ERRORS=stdout ./myprog
It's also pretty easy to set this in Xcode (Edit Scheme -> Arguments -> Environment Variables).
Please find the original answer by @James

A: This unhelpful error message indicates that there is bug in Apple's compiler. You can inform them of such bugs by using the Apple Bug Reporting System.


Q: Azure App Service - Site Not Found Only From Specific Locations We have a website hosted via Azure App Service that we can access from many of our locations throughout the world.
Yet there are some locations that return

"This site can't be reached" (ERR_NAME_RESOLUTION_FAILED).

Any ideas?
Cannot ping the IP address from the client PC either.
In Azure, I have all IP Addresses open in the Firewall.
I feel like I have exhausted everything so far.
I also activated the site through another server that is not part of Azure and I was able to access it from locations that cannot access the Azure Site.  Why I'm pretty sure it is an Azure issue (unless it is their provider blocking something)?

A: ERR_NAME_RESOLUTION_FAILED is a DNS failure error. If you have recently changed the DNS of your domain, it should take a while to become available in all regions.
If you've already changed for quite a time, check if the computer where you are trying to access is having any other DNS errors / change DNS servers to known public service (Google/Cloudflare/OpenDNS).
As you can see here, your DNS is failing in several regions:
https://www.whatsmydns.net/#A/www.scaleitusa.com


Q: Export Cronbach Alpha Results - R I'm following THIS R Blogger tutorial to calculate Cronbach alpha, which works perfectly.  I'd like to learn how to export the results, either into a data.frame or text file.  Any ideas how I might be able to export the results from the following code: psych::alpha(d)?  Note, I looked at the stargazer package, but couldn't get it work work with Cronbach outputs only regression and descriptive statistics.  Thank you.

A: The output can be saved as a txt file this way. You can also subset the object created with the alpha function using the $ operator to get only the information you are interested in.
setwd("~/Desktop")
out <- psych::alpha(d)
capture.output(out,file = "alpha.txt")

A: As is true of everything R, there are many ways of doing what you want to do.  The first thing is to look at the help menu for the function (in this case ?alpha).  There you will see that a number of objects are returned from the alpha function.  (This is what is listed in Values part of the help file.)
When you print the output of alpha you are shown just a subset of these objects.  However, to see the entire list of objects that are returned, use the "str" command
my.results <- alpha(my.data)
str(my.results)     #or just list the names of the objects
 names(my.alpha)
 [1] "total"         "alpha.drop"    "item.stats"    "response.freq" "keys"          "scores"        "nvar"          "boot.ci"
 [9] "boot"          "Unidim"        "Fit"           "call"          "title"

You can then choose to capture any of those objects for your own use.
Thus
my.alpha <- alpha(ability) #use the ability data set in the psych package
my.alpha #will give the normal (and nicely formatted output)
totals <- my.alpha$total   #just get one object from my.alpha
totals                     #show that object

will  produce a single line (without the fancy output):
raw_alpha std.alpha   G6(smc) average_r      S/N         ase      mean        sd
 0.8292414 0.8307712 0.8355999 0.2347851 4.909159 0.006384736 0.5125148 0.2497765

You can do this for any of the objects returned.  Most of us who write packages print what we think are the essential elements of the output of the function, but include other useful information. We also allow for other functions (such as summary) to print out other information.
So, using the example from above,
summary(my.alpha)  #prints the rounded to 2 decimals my.alpha$total object
Reliability analysis
 raw_alpha std.alpha G6(smc) average_r S/N    ase mean   sd
      0.83      0.83    0.84      0.23 4.9 0.0064 0.51 0.25

A final word of caution.  Many of us do  not  find alpha a particularly useful statistic to describe the structure of a scale.  You might want to read the tutorial on how to find coefficient omega using the psych package at
http://personality-project.org/r/psych/HowTo/R_for_omega.pdf


Q: SQL Server 2008 CLR vs T-SQL: Is there an efficiency/speed difference? I'm a C# developer who has done some basic database work in T-SQL. However, I need to write a very complicated stored procedure, well above my T-SQL knowledge.
Will writing a stored procedure in C# using the .net CLR as part of SQL Server 2008 cause my stored procedure to be less efficient than if it were written in T-SQL? Is the difference (if any) significant? Why?

A: CLR require some communication overhead (to pass data between the CLR and SQL Server)
Rule of thumb is:

*

*If your logic mostly includes transformations of massive sets of data, which can be performed using set operations, then use TSQL.

*If your logic mostly includes complex computations of relatively small amounts of data, use CLR.
With set operations much more can be done than it seems. If you post your requirements here, probably we'll be able to help.

A: Please see Performance of CLR Integration:

This topic discusses some of the
  design choices that enhance the
  performance of Microsoft SQL Server
  integration with the Microsoft .NET
  Framework common language runtime
  (CLR).

A: The question of "Will writing a stored procedure in C# using the .net CLR as part of SQL Server 2008 cause my stored procedure to be less efficient than if it were written in T-SQL?" is really too broad to be given a meaningful answer. Efficiency varies greatly depending on not just what types of operations are you doing, but also how you go about those operations. You could have a CLR Stored Procedure that should out-perform an equivalent T-SQL Proc but actually performs worse due to poor coding, and vice versa.
Given the general nature of the question, I can say that "in general", things that can be done in T-SQL (without too much complexity) likely should be done in T-SQL. One possible exception might be for TVFs since the CLR API has a very interesting option to stream the results back (I wrote an article for SQL Server Central--free registration required--about STVFs). But there is no way to know for certain without having both CLR and T-SQL versions of the code and testing both with Production-level data (even poorly written code will typically perform well enough with 10k rows or less).
So the real question here boils down to:

I know C# better than I know T-SQL. What should I do?

And in this case it would be best to simply ask how to tackle this particular task in T-SQL.  It could very well be that there are non-complex solutions that you just don't happen to know about yet, but would be able to understand upon learning about the feature / technique / etc. And you can still code an equivalent solution in SQLCLR and compare the performance between them.  But if there is no satisfactory answer for handling it in T-SQL, then do it in SQLCLR.
That being said, I did do a study 3 years ago regarding SQLCLR vs T-SQL Performance and published the results on Simple-Talk.


Q: Xcode with .cxx_construct I have a little problem with Xcode.
I import a header which contains this :
- (id).cxx_construct;
- (void).cxx_destruct;

so I try to set GCC_OBJC_CALL_CXX_CDTORS to yes in my build Settings on User-Defined !
But I still have this error :
Expected selector for Objective-C method

What can i do ?
Thanks,

A: these selectors are generated by the compiler. they are the reserved selectors for c++ ivar construction and destruction.
furthermore, the runtime calls these methods for you when GCC_OBJC_CALL_CXX_CDTORS is enabled. there is no need to call or declare them yourself.
declaring them would result in a compilation error.

What can i do?

choose a unique name for your selectors, and don't implement the ones which are generated for you (when GCC_OBJC_CALL_CXX_CDTORS is enabled).
what is it you are trying to do here?


Q: Color reproduced on screen is different between platforms I have an both on the Android and iOS. Both are using the exact same render code with OpenGL ES. I noticed that even when using the same RGBA values, the colour reproduced on screen by the devices are not the same.
I want suggestions on what might be the cause. I have considered that it might be just the display hardware, and if so, how would you recommend handling this case and if this is usually handled at all.
Thanks.

A: Take a screenshot on both devices, email it to a PC and compare the actual colours in photoshop.
It's probably just the screen, they can vary wildly, I wouldn't worry about it unless your app has some special specific reason to be concerned about exact colour reproduction.
Even on a single device there are sometimes settings which change the look completely, e.g. the Samsung Galaxy S6: http://www.phonearena.com/news/Samsung-Galaxy-S6-Review-of-the-various-display-modes_id69968


Q: Android Calculator - Editview cannot input decimal places I am new to Android code development...I am developing a Android calculator apps and does not understand why the two EditTexts (first input and second input) cannot accept decimal places but can only input integers...Here attached as follows are the codes:
Thanks!
=============Main Activity===============================
package com.trial.jm4_calculator;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.support.v4.app.NavUtils;

public class MainActivity extends Activity {

    private TextView output;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

    Button btn1 = (Button) findViewById(R.id.button1);
    btn1.setOnClickListener(btn1Listener);
    output = (TextView) findViewById(R.id.lblOutput);
    }

View.OnClickListener btn1Listener = new View.OnClickListener() {
    public void onClick(View v) {
       double opd1, opd2;
       double result = 0.0;
       EditText txtOpd1, txtOpd2;
       RadioButton rdbAdd, rdbSubtract, rdbMultiply, rdbDivide;
       CheckBox chkDivide;

       txtOpd1 = (EditText) findViewById(R.id.txtOpd1);
       txtOpd2 = (EditText) findViewById(R.id.txtOpd2);

       opd1 = Double.parseDouble(txtOpd1.getText().toString());
       opd2 = Double.parseDouble(txtOpd2.getText().toString());

       rdbAdd = (RadioButton) findViewById(R.id.rdbAdd);
       if (rdbAdd.isChecked()) {
           result = opd1 + opd2;
       }
       rdbSubtract = (RadioButton) findViewById(R.id.rdbSubtract);
       if (rdbSubtract.isChecked()) {
           result = opd1 - opd2;
       }
       rdbMultiply = (RadioButton) findViewById(R.id.rdbMultiply);
       if (rdbMultiply.isChecked()) {
           result = opd1 * opd2;
       }
       rdbDivide = (RadioButton) findViewById(R.id.rdbDivide);
       if (rdbDivide.isChecked()) {

              result = opd1 / opd2;
       }
       output.setText("Answer = " + result);
    }
};
}

====================Main.xml===================================
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <LinearLayout
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:orientation="horizontal">
        <TextView
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="First Input: "/>
        <EditText
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:inputType="number"
            android:id="@+id/txtOpd1"/>
    </LinearLayout>
    <RadioGroup
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:orientation="horizontal"
        android:id="@+id/rdgOp">
        <RadioButton
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="+ "
            android:id="@+id/rdbAdd"/>
        <RadioButton
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="- "
            android:id="@+id/rdbSubtract"/>
        <RadioButton
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="* "
            android:id="@+id/rdbMultiply"/>
        <RadioButton
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="/ "
            android:id="@+id/rdbDivide"/>
    </RadioGroup>
    <LinearLayout
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:orientation="horizontal">
        <TextView
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="Second Input: "/>
            <EditText
                android:layout_height="wrap_content"
                android:layout_width="fill_parent"
                android:inputType="number"
                android:id="@+id/txtOpd2"/>
     </LinearLayout>
     <Button
         android:layout_height="wrap_content"
         android:layout_width="wrap_content"
         android:text="Compute"
         android:id="@+id/button1"/>
     <TextView
         android:layout_height="wrap_content"
         android:layout_width="wrap_content"
         android:id="@+id/lblOutput"/>
</LinearLayout>

A: If you want to use Decimal Number only on your EditText
use the xml attribute android:inputType="numberDecimal" in your EditText widget your EditText declaration will be like this:
<EditText
    android:id="@+id/editText1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="numberDecimal" />

If you want to use Signed Decimal Number than combine the two Xml attributes android:inputType="numberDecimal" and android:inputType="numberSigned". Your EditText declaration will be like this:
<EditText
    android:id="@+id/editText1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="numberDecimal|numberSigned" >

</EditText>

A: Change android:inputType from "number" to "numberDecimal". See the documentation for even more options for inputType.

A: inputType="number" doesnt allow floats. try changing:
android:inputType="number"

to:
android:numeric="integer|decimal"

A: You need to change the input type of your EditText in the XML code.
Change the inputType attribute of the EditText from
android:inputType="number"
to
android:inputType="numberDecimal"
<EditText
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:inputType="numberDecimal"
            android:id="@+id/txtOpd1"/>


Q: TWCS is not generating the SStables according to the window_size and window_unit I need to generate the SSTables after a certain time like 10 minutes, but using TWCS and setting up the "compaction_window_size" and "compaction_window_unit", I am not able to understand when the SSTables would be getting generated.
I have tried all many combinations but I am not able to figure out the when the SSTables will be created
CREATE TABLE twcs.twcs2 (
    id int PRIMARY KEY,
    age int,
    name text
) WITH bloom_filter_fp_chance = 0.01
    AND caching = {'keys': 'ALL', 'rows_per_partition': 'NONE'}
    AND comment = ''
    AND compaction = {'class': 'org.apache.cassandra.db.compaction.TimeWindowCompactionStrategy', 'compaction_window_size': '1', 'compaction_window_unit': 'MINUTES', 'max_threshold': '32', 'min_threshold': '4'}
    AND compression = {'chunk_length_in_kb': '64', 'class': 'org.apache.cassandra.io.compress.LZ4Compressor'}
    AND crc_check_chance = 1.0
    AND dclocal_read_repair_chance = 0.1
    AND default_time_to_live = 3600
    AND gc_grace_seconds = 60
    AND max_index_interval = 2048
    AND memtable_flush_period_in_ms = 0
    AND min_index_interval = 128
    AND read_repair_chance = 0.0
    AND speculative_retry = '99PERCENTILE';

Here I have set the 'compaction_window_unit'='MINUTES' and 'compaction_window_size': '1' , So according to this the SSTables should  be generated after every 1 minute if some operation is performed on the table(insertion/deletion/updation of data), but this is not happening.

A: TWCS is a compaction strategy. Compaction strategies have nothing to do with sstables being generated. It's a reconcile and cleanup "algorithm" once they are created. The way that TWCS works is that sstables will be consolidated into windows. The key word here is "consolidated". There is no guarantee that sstables will be "generated" in that timeframe, but whatever IS generated, after the window expires, will be consolidated together. So if you have, say, hourly windows/buckets, during that hour sstables may or may not get generated. If multiple sstables are created during the window they are compacted/consolidated/reconciled using STCS (similar sized sstables consolidated together). After the hour passes, any sstables that remain for that window will be compacted together into a single sstable. Over time you will see one sstable per window (or none if nothing was generated during that window). After your TTL and gc_grace passes, entire windows simply get removed (instead of the large effort of merging with others and then removing expired records).
TWCS works very well if there is no overlap for rows within windows. If there is overlap, then the oldest windowed sstable will be unable to be removed until the newest sstable with overlapped records expire. In other words, TWCS works well for INSERTS that do not cross windows (remember updates and deletes are also considered inserts). You need to be sure to use TTL for cleanup (i.e. don't run delete statements as that will cause overlap). Also, from what I have discovered from  using this, ensure to turn off repair for the tables that have TWCS as that can cause big problems (unseen overlap).
So in short, TWCS does not cause sstables to get generated (there are rules for when sstables are created that have nothing to do with compaction strategies), it simply another method of keep things "clean".
Hope that helps.

A: There are several resources that may help you:

*

*https://academy.datastax.com/units/21017-time-window-compaction-dse-operations-apache-cassandra

*https://www.youtube.com/watch?v=PWtekUWCIaw

*https://thelastpickle.com/blog/2016/12/08/TWCS-part1.html


Q: An alternative to CodeTabs B+ Im looking for an alternative to the jquery library CodeTabs B+.
It should be possible to drag-and-drop the tab-navigation (important for mobile users). Do you know any?

A: I found http://owlgraphic.com/. It fits some of the features CodeTabs B+ has.