Q: Draw with canvas Javascript Maybe you can advice me, I need to draw with canvas using the coordinates of images as vertex, but I have the images into a table(html table) so I don't know how to do that, how to do the draw inside the table or over the table. For example you have an image on coordinates(60,90) another on (79,45) and other on (70,64), i need to make a triangle with that coordinates, but the images are into a table(each image in different cells.
This is my draw code:
function draw(elem) { //elem is the image

var image= elem;
var position = image.getBoundingClientRect();
//alert(posicion.top+" "+ posicion.right+" "+posicion.bottom+" "+posicion.left);

var canvas = document.getElementById('myCanvas');
var contexto = canvas.getContext('2d');
       contexto.beginPath();
       contexto.moveTo(position.top,50);
       contexto.lineTo(position.top,150);
       contexto.lineTo(position.top+100,150);
       contexto.fill();
}

and this is my canvas:
<canvas id="myCanvas" width="700" height="700">Your browse don't support canvas</canvas>

I put it under the table code and I call the function in other function. If you could help me it would be great.
Thanks!

A: I hope I understand your question correctly: you have images in an actual Table element (

) and images in some cells. You have a canvas placed below it which you want to draw lines on to connect the images in the table.
To do this just subtract the canvas element's absolute position from the image's absolute position. This will make the image's position relative to the canvas.
For example
var canvas = document.getElementById('myCanvas');
var canvasPos = canvas.getBoundingClientRect();
var position = image.getBoundingClientRect();

var x = position.left - canvasPos.left;
var y = position.top - canvasPos.top;

var contexto = canvas.getContext('2d');
contexto.beginPath();
contexto.moveTo(x, y);
... next image

A: jsBin demo
Let's say you have a table and canvas inside a parent like:

  <canvas id="lines"></canvas>

#wrapper{
  position:relative;
  margin:0 auto;
  width: 700px;
  height:700px;
}
#wrapper canvas{
  display:block;
  position:absolute;
}
#wrapper table{
  position: absolute;
}
#wrapper table td{
  background: rgba(0,0,0,0.1);
  width: 100px;
  height: 100px;
  vertical-align: middle;
}
#wrapper table td img{
  display: block;
  opacity:0.4;
}

You need to connect your images using lines,
you're probably interested for the image center but you need also to account the parent offset, so you need to subtract that position from the brc (getBoundingClientRect) of each image and it's td parentNode height/width:
var table = document.getElementById("table");
var images = table.getElementsByTagName("img");
var canvas = document.getElementById("lines");
var ctx = canvas.getContext("2d");
var x, y; // Remember coordinates

canvas.width  = table.offsetWidth;
canvas.height = table.offsetHeight;

function connect( image ) {
  var im = new Image();
  im.onload = function(){ // make sure image is loaded
    var tabBcr = table.getBoundingClientRect();
    var imgBcr = image.getBoundingClientRect();
    ctx.beginPath();
    ctx.moveTo(x, y);
    x = imgBcr.left + (image.parentNode.offsetWidth / 2) - tabBcr.left;
    y = imgBcr.top + (image.parentNode.offsetHeight / 2) - tabBcr.top;
    ctx.lineTo(x, y);
    ctx.stroke();
  };
  im.src = images[i].src;
}

for(var i=0; i<images.length; i++){
  connect( images[i] );
}


Q: Install self signed Certificates via ADB I'm trying to install self-signed Certificates(created by Charles) via ADB
I've pushed it to /sdcard/xxx.pem , And then failed to open it with Browsers that I could find, And Since the device removes the Setting Application, I could not install cert under the Setting App.
Then I searched And try
am start -n com.android.certinstaller/.CertInstallerMain -a android.intent.action.VIEW -t application/x-x509-ca-cert file:///sdcard/test.cer

But just shown
01-07 17:47:56.442 12889-12889/com.android.certinstaller E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.certinstaller, PID: 12889
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.certinstaller/com.android.certinstaller.CertInstallerMain}: java.lang.NullPointerException: uri
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5418)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:731)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:621)
 Caused by: java.lang.NullPointerException: uri
    at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:60)
    at android.content.ContentResolver.openInputStream(ContentResolver.java:645)
    at com.android.certinstaller.CertInstallerMain.startInstallActivity(CertInstallerMain.java:139)
    at com.android.certinstaller.CertInstallerMain.onCreate(CertInstallerMain.java:119)
    at android.app.Activity.performCreate(Activity.java:6270)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1115)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5418)
    at java.lang.reflect.Method.invoke(Native Method)

I'm not familiar with this com.android.certinstaller app, Is there any reference How I could use it to install a cert?

A: Please try below:
adb shell am start -n com.android.certinstaller/.CertInstallerMain -a android.intent.action.VIEW -t application/x-x509-ca-cert -d file:///sdcard/test.cer
if throw
com.android.certinstaller E/CertInstaller: Failed to read certificate: java.io.FileNotFoundException: /sdcard/cer (Permission denied)
please root your devices and push cer to  /system/etc/
adb shell am start -n com.android.certinstaller/.CertInstallerMain -a android.intent.action.VIEW -t application/x-x509-ca-cert -d file:///system/etc/test.cer

A: You need to make sure the file is readable if you are getting "Permission denied" or "Cloud not find the file" toast.
chmod o+r /sdcard/test.cer
and then
adb shell am start -n com.android.certinstaller/.CertInstallerMain -a android.intent.action.VIEW -t application/x-x509-ca-cert -d file:///sdcard/test.cer


Q: New custom action in Alfresco I want to do a custom action associated to rule.
I have used a guide http://wiki.alfresco.com/wiki/Custom_Action_UI but I don't get I need. I'm really newby using Alfresco...
My problem:
I have created my custom action. I select it in Alfresco UI and when I press the button "Set Values and Add" the application doesn't show any window to add any value to parameter that I have defined in method addParameterDefinitions:
protected void addParameterDefinitions(List<ParameterDefinition> paramList) {
        paramList.add(new ParameterDefinitionImpl(PARAM_CUSTOM_URL, DataTypeDefinition.TEXT, true, getParamDisplayLabel(PARAM_CUSTOM_URL)));

}

I'm not sure if I need a jsp, all I want is a text box to type a parameter.
I have created a jsp and its ActionHandler, defining it in the web-client-config-custom.xml file, but Alfresco don't recognise the jsp. I don't know the location where I have to put the jsp.


Q: How to get data from many tables I am building a patient profile that has many tables such as medicines, treatments, x-ray, patient info, etc. all of them shared a patient ID, but I feel like it will have a big load on the service and take time, I searched a lot but I don't know if this approach is good or it could be better. here is an example of my eloquent code.
 $patient = Patient::with(['country' => function ($q) {
            $q->select('id', 'name');}])
        ->with(['city' => function ($q) {
            $q->select('id', 'name');}])
        ->with(['recourse' => function ($q) {
            $q->select('id', 'name');}])
        ->find($id);

$appointments = Appointment::where('patient_id', $id)
->with(['branch' => function ($q) {
    $q->select('id', 'name');}])
->with(['doctor' => function ($q) {
    $q->select('id', 'first_name');}])
->with(['service_cat' => function ($q) {
    $q->select('id', 'name');}])
->orderBy('id', 'ASC')
->get();

$invoices = Invoice::select('id', 'creditor_cat_id', 'final_price', 'status')->where('patient_id', $id)
->with(['service_cat' => function ($q) {
    $q->select('id', 'name');}])
->get();

$medicine = Medicine::select('id', 'medicines_cats', 'start', 'end', 'status')->where('patient_id', $id)
->with(['medicinescats' => function ($q) {
    $q->select('id', 'name');}])
->orderBy('status', 'ASC')
->get();

$medicine_cat = Medicine_cat::all();

$disease = Disease::select('id', 'disease_cats', 'start', 'end', 'status')->where('patient_id', $id)
->with(['diseasecats' => function ($q) {
    $q->select('id', 'name');}])
->orderBy('status', 'ASC')
->get();

$disease_cat = Disease_cat::all();

$treatment = Treatment::select('id', 'treatment_cat_id', 'sessions', 'sessions_done', 'start', 'end', 'status')->where('patient_id', $id)
->with(['treatment_cat' => function ($q) {
    $q->select('id', 'name');}])
->orderBy('status', 'ASC')
->get();

$treatment_cat = Treatment_cat::all();

$session_pat = Session_pat::select('id', 'services_cat_id', 'treatment_id', 'invoice_id', 'status')->where('patient_id', $id)
->with(['service_cat' => function ($q) {
    $q->select('id', 'name');}])
->with(['treatment' => function ($q) {
    $q->select('id', 'sessions');}])
->with(['invoice' => function ($q) {
    $q->select('id', 'code', 'status');}])
->orderBy('status', 'ASC')
->get();

$service_cat_treat = Service_cat::where('type', 2)->get();

edited: in case I used hasMany, these tables have other tables connected as shown, so I did not know how to make it, for example, the patient table has treatment table, treatment table has 2 tables connected which are invoice and treatment category, and I did what is above to get all data from these connected tables

A: So you have a few options to choose from:

*

*Combine all your queries into a single query (Make a larger query, which will join together all the tables you need in your example)

*Create a view (Create a view of these tables within the database, then query using the view)

*Create a materialized view (Creating a materialized view has it's benefits, though the upkeep of it is a bit tougher. Since materialized views actually hold real data, it means they need to be synced with the tables. They are only intended to be used when you need data fast and the data does not change often. In your case it could actually work, if you sync the materialized view every 5 min.) - Warning: MySQL does not directly support materialized views.
If you are trying to go for speed, then cache your results and only retrieve what was inserted after it.


Q: Python: Fix DecodeError when receiving data I've searched other post but from what I can tell they all have control of the data being sent to them. In this case I have no control over the data being sent to me. I'm receiving data from an IRC server that I cannot encode specifically to UTF-8 before it is sent. I was wondering if there is anyway to avoid UTF-8 decode errors when receiving data from the socket connected to the IRC channel.
I'm using python and the line of code I use for receiving is:
data = socket.recv(2048).decode('UTF-8')
Any help is appreciated: Thank You


Q: Clojure Spec on a vararg function I am trying to write a spec for a merge function which takes a function and maps as an input and uses function to resolve the conflicts. However the spec i wrote for the function fails. I am trying to figure out how to write spec for such functions.
Below is the code snippet.
(require '[clojure.spec.test :as stest])
(require '[clojure.spec :as spec])

(defn deep-merge-with [func & maps]
  (let [par-func (partial deep-merge-with func)]
    (if (every? map? maps)
        (apply merge-with par-func maps)
        (apply func maps))))

(spec/fdef deep-merge-with
           :args (spec/cat :func (spec/fspec :args (spec/cat :maps (spec/* map?))
                                             :ret map?)
                           :maps (spec/cat :maps (spec/* map?)))
           :ret map?)

(stest/instrument `deep-merge-with)

(deep-merge-with (fn [f s] s) {:a 1} {:a 2})

The spec error i am getting is:
clojure.lang.ExceptionInfo: Call to #'boot.user/deep-merge-with did not conform to spec:
    In: [0] val: () fails at: [:args :func] predicate: (apply fn),  Wrong number of args (0) passed to: user/eval22001/fn--22002
                                :clojure.spec/args  (#function[boot.user/eval22001/fn--22002] {:a 1} {:a 2})

A: In your [:args :func] spec:
(spec/fspec :args (spec/cat :maps (spec/* map?)) :ret map?)

You're saying that the function must accept as arguments any number of maps and return a map. But the function you pass to deep-merge-with does not conform to that spec:
(fn [f s] s)

This function takes exactly two arguments, not an arbitrary number of maps.


Q: Issue with chromedriver in RobotFramework I started with python and Robot Framework.
I'm having this strange exception while trying to run a test case in Robot Framework.

WebDriverException: Message: Service chromedriver unexpectedly exited. Status code was: -1073741819

I tried changing the chromedriver versions, also checked the chrome browser it was updated to the last version.
I'm sure it's in it's place "Python27\Scripts" which is added to the environment variables as well.
Has anyone else had this issue, or know how to solve it?


Q: Pass Object from one Aspx to another from Javascript Correct me if I am doing wrong.
I have a Login page which uses a Webservice to process login. In my Login page I use Jquery with JSon to consume the webservice.
After the login is processed I recieve an object and I want to redirect the recieved object to home page.
Let me know how.
Thanks
Samuel

A: POST redirect the received JSON to server, and deserialize the JSON to your typed object. You can consider keeping the object in your SESSION and access it when required.
UPDATE
put a hidden field in your aspx/ascx page

Once you receive your JSON Data from your service. Just put your response to the hidden field. (USE JQUERY)
$("input[id$=jsonResponse]").val(responseFromService);

On your Page_Load method on your home.aspx
Use JavaScriptSerializer to deserialize your JSON data
JavaScriptSerializer serializer = new JavaScriptSerializer();

LoginData loginDataObject = serializer.Deserialize<LoginData>(jsonResponse.Value);

Now you can consider putting your loginDataObject to SESSION and access through out your application scope
// to store in session
Request.Session["loginData"] = loginDataObject;
// to retrieve from session
LoginData loginDataObject = (LoginData) Request.Session["loginData"];

A: You could store the object in a cookie and change the url with location.href or something similar?


Q: How to create Up and Down Methods using migrations? I am new to Code first, can you tell me how i can have all Up and Down methods for all tables in the database like below(given for one table)
public partial class abc: DbMigration
    {
        public override void Up()
        {
            AddColumn("dbo.UserTasks", "ServiceTechReason", c => c.Long());
        }

        public override void Down()
        {
            DropColumn("dbo.UserTasks", "ServiceTechReason");
        }
    }

i want all three types for a table viz .cs , .Designer.cs , .resx.
2) Can you explain the above example, i pick it from somewhere on internet i was searching for this but found nothing. is abc is my table name in database?
Provide me link if it is already answered.
EDIT
As mentioned by @scheien i already tried those commands they do not automatically override up and down methods for a table

A: Creating migrations is done by running the command Add-Migration AddedServiceTechReason.
This assumes that you have already enabled migrations using the Enable-Migrations command.
To apply the current migration to the database, you'd run the Update-Database. This command will apply all pending migrations.
The point of Code-First migrations is that you make the changes you want to your Entity(ies), and then add a new migration using the Add-Migration command. It will then create a class that inherits DbMigration, with the Up() and Down() methods filled with the changes you have made to your entity/entities.
As per @SteveGreenes comment: It does pick up all changes to your entities, so you don't need to run it once per table/entity.
If you want to customize the generated migration files, look under the section "Customizing Migrations" in the article listed.
All these commands are run in the package manager console.

View -> Other windows -> Package Manager Console.

Here's a great article from blogs.msdn.com that explains it in detail.


Q: What is the best way of reading/writing structured binary data in C# Like in C we could use structure pointers to read or write structured binary data like file headers etc, is there a similar way to do this in C#?

A: Using BinaryReader and BinaryWriter over a MemoryStream tends to be the best way in my opinion.
Parsing binary data:
byte[] buf = f                     // some data from somewhere
using (var ms = new MemoryStream(buf, false)) {   // Read-only
    var br = new BinaryReader(ms);

    UInt32 len = br.ReadUInt32();
    // ...
}

Generating binary data:
byte[] result;
using (var ms = new MemoryStream()) {   // Expandable
    var bw = new BinaryWriter(ms);

    UInt32 len = 0x1337;
    bw.Write(len);
    // ...

    result = ms.GetBuffer();   // Get the underlying byte array you've created.
}

They allow you to read and write all of the primitive types you'd need for most file headers, etc. such as (U)Int16, 32, 64, Single, Double, as well as byte, char and arrays of those.  There is direct support for strings, however only if

The string is prefixed with the length, encoded as an integer seven bits at a time.

This only seems useful to me if you wrote the string in this way from BinaryWriter in this way. It's easy enough however, say your string is prefixed by a DWord length, followed by that many ASCII characters:
int len = (int)br.ReadUInt32();
string s = Encoding.ASCII.GetString(br.ReadBytes(len));

Note that I do not have the BinaryReader and BinaryWriter objects wrapped in a using() block. This is because, although they are IDisposable, all their Dispose() does is call Dispose() on the underlying stream (in these examples, the MemoryStream).
Since all the BinaryReader/BinaryWriter are is a set of Read()/Write() wrappers around the underlying streams, I don't see why they're IDisposable anyway. It's just confusing when you try to do The Right Thing and call Dispose() on all your IDisposables, and suddenly your stream is disposed.

A: To read arbitrarily-structured data (a struct) from a binary file, you first need this:
public static T ToStructure<T>(byte[] data)
{
    unsafe
    {
        fixed (byte* p = &data[0])
        {
            return (T)Marshal.PtrToStructure(new IntPtr(p), typeof(T));
        }
    };
}

You can then:
public static T Read<T>(BinaryReader reader) where T: new()
{
    T instance = new T();
    return ToStructure<T>(reader.ReadBytes(Marshal.SizeOf(instance)));
}

To write, convert the struct object to a byte array:
public static byte[] ToByteArray(object obj)
{
    int len = Marshal.SizeOf(obj);
    byte[] arr = new byte[len];
    IntPtr ptr = Marshal.AllocHGlobal(len);
    Marshal.StructureToPtr(obj, ptr, true);
    Marshal.Copy(ptr, arr, 0, len);
    Marshal.FreeHGlobal(ptr);
    return arr;
}

...and then just write the resulting byte array to a file using a BinaryWriter.

A: Here is an simple example showing how to read and write data in Binary format to and from a file.
using System;
using System.IO;
namespace myFileRead
{
    class Program
     {
       static void Main(string[] args)
       {
           // Let's create new data file.
           string myFileName = @"C:\Integers.dat";
            //check if already exists
            if (File.Exists(myFileName))
               {
                Console.WriteLine(myFileName + " already exists in the selected directory.");

                return;
            }

            FileStream fs = new FileStream(myFileName, FileMode.CreateNew);

            // Instantialte a Binary writer to write data

            BinaryWriter bw = new BinaryWriter(fs);

            // write some data with bw

            for (int i = 0; i < 100; i++)

            {
                    bw.Write((int)i);
            }

            bw.Close();
            fs.Close();

            // Instantiate a reader to read content from file
            fs = new FileStream(myFileName, FileMode.Open, FileAccess.Read);

            BinaryReader br = new BinaryReader(fs);

            // Read data from the file

            for (int i = 0; i < 100; i++)
            {
                //read data as Int32
                Console.WriteLine(br.ReadInt32());
            }
            //close the file
            br.Close();
            fs.Close();
       }

    }

}


Q: How do I skip methods using @AfterMethod in TestNG I have a set of tests as follows.
@Test
public void testX(){
}

@Test
public void testY(){
}

@Test
public void testZ(){
}

I have another test which I should run after each of the test is executed.
I hope I could do that with
@AfterMethod
public void testA(){
}

Now I need to skip testA for testX. Which means I don't need testA to run after testX. How do I do it? Also how to specify multiple test cases to skip in the above manner?

A: One way to do that would be to add to the same group every method you want testA to execute.
In the following example, testY and testZ are added to the "myGroup" group so the testA after method, which also belongs to this group, will only be executed for those tests.
@Test
public void testX(){
}

@Test(groups = { "myGroup" })
public void testY(){
}

@Test(groups = { "myGroup" })
public void testZ(){
}

@AfterMethod(groups = { "myGroup" })
public void testA(){
}


Q: how to get two item from a List<> in every get request in ASP.NET Core MVC How can I get two value per get request from a List<>, For example,
I have a Person List<> with six Person Ordered by ID in that List<> now in every get request using JQuery ajax() I want to get only two item from the list<>, first request will return Person with ID 1 & 2, second request will return Person with ID 3 & 4, and so forth.
I've tried
public IEnumerable<PersonViewModel> GetAllStudents()
    {
        IEnumerable<Person> dbPersons = _repo.getPersons().OrderBy(s => s.ID).Take(2);

        List<PersonViewModel> persons = new List<PersonViewModel>();
        foreach(var p in dbPersons)
        {
            persons.Add(MapDbPieToPersonViewModel(p));
        }

        return persons;
    }

But this only return first two item.

A: You should use Enumerable.Skip(Int32)
public IEnumerable<PersonViewModel> GetAllStudents(int page)
{
    const int PageSize = 2;
    IEnumerable<Person> dbPersons = _repo.getPersons().OrderBy(s => s.ID).Skip(page * PageSize).Take(PageSize);

    List<PersonViewModel> persons = new List<PersonViewModel>();
    foreach(var p in dbPersons)
    {
        persons.Add(MapDbPieToPersonViewModel(p));
    }

    return persons;
}


Q: Can a NSDictionary take in NSSet as key? I know you can use any object as key for NSDictionary but the problem is will it be able to retrieve the correct value? Support I have an entry where the key = {1,3,5} and value = { @"hello" }. Will I be able to retrieve from this dictionary entry by passing in the set {3,5,1}?
In order words, is the key matched based on the pointer or does it actually compare the contents of the set? (And if it is the former, how can I overcome this?)

A: The equality of keys is done using isEqual on the keys in question. Thus, the comparison of {1,3,5} and {3,5,1} (assuming that the numbers are represented by NSNUmber instances) will be YES.

A: Yep it seems to work nicely (not sure if there are any gotchas).
NSMutableDictionary * dict = [NSMutableDictionary dictionary];

NSSet * set;
set = [NSSet setWithObjects:@"a", @"b", @"c", @"d", nil];
[dict setObject:@"1" forKey:set];

set = [NSSet setWithObjects:@"b", @"c", @"d", @"e", nil];
[dict setObject:@"2" forKey:set];

id key;
NSEnumerator * enumerator = [dict keyEnumerator];
while ((key = [enumerator nextObject]))
    NSLog(@"%@ : %@", key, [dict objectForKey:key]);

set = [NSSet setWithObjects:@"c", @"b", @"e", @"d", nil];
NSString * value = [dict objectForKey:set];
NSLog(@"set: %@ : key: %@", set, value);

Outputs:
2009-12-08 15:42:17.885 x[4989] (d, e, b, c) : 2
2009-12-08 15:42:17.887 x[4989] (d, a, b, c) : 1
2009-12-08 15:42:17.887 x[4989] set: (d, e, b, c) : key: 2

A: Yes (since a set conforms to NSCopying and implements isEqual:), with one catch: Do not use a mutable set, or any other mutable object, as a key. You will mutate it, whereupon you will break your ability to look up its value in the dictionary.

A: Yes.
Try this in irb:
require 'osx/cocoa'
abc=OSX::NSSet.setWithArray([1,2,3])
cba=OSX::NSSet.setWithArray([3,2,1])
dict=OSX::NSMutableDictionary.dictionary
dict[abc] = 'hello'
puts dict[cba]

(it works, because isEqual: for NSSet is true when you'd expect it to be and NSDictionary bases its actions on that)


Q: How to return var parameter in Delphi ASM I'm far from having knowledge about ASM, so forgive me if this is a stupid question.
I have this function:
function SwapDWord(const AValue: DWORD): DWORD;
asm
  BSWAP EAX
end;

How would I convert it to a procedure in ASM:
procedure SwapDWordVar(var AValue: DWORD);
asm
  // ???
end;

I do not want to use AValue := SwapDWord(AValue); which I could. I want to do this in ASM.
I tried many silly things by looking at system.pas and tried to understand which register(s) to use. but nothing worked. It always return back the original AValue.

A: Possible variant:
procedure SwapDWordVar(var AValue: DWORD);
asm
  mov edx, [eax]
  bswap edx
  mov [eax], edx
end;

You might find useful Guido Gybels articles

A: Just try
procedure SwapDWordVar(var AValue: DWORD);
asm
  mov edx, dword ptr [AValue]
  bswap edx
  mov dword ptr [AValue], edx
end;

Note that this version will compile and work for both Win32 and Win64.
But note that it won't be faster than AValue := SWapDWord(AValue) since most of the time will be spent calling the function, not accessing the memory.


Q: How to run custom mysql script for Laravel app in test pipeline in CodeShip Basic? Relative newbie to PhpUnit and testing in general.  We do not use migrations in our project, but have a couple of scripts that I need to run in order to set up the database for testing.  How can I run mysql scripts from the project in the test pipeline?  I also need to create a new database with a specific name before running those scripts.
Thanks!

A: The commands that you use on your local machine are the same commands you can run in CodeShip Basic. CodeShip Basic is just a build machine with Ubuntu Bionic and it will run through the setup, test, and deploy commands as if you were entering each line into your CLI. :)
We also have some documentation about mysql: https://documentation.codeship.com/basic/databases/mysql/

A: OK, after some digging I found out how to do all this.  Below is the script I used for testing with a new mysql schema created with specific user from a sql script.  Hope this helps someone in the future.
mysql -u $MYSQL_USER -p$MYSQL_PASSWORD -e "CREATE USER 'myuser'@'%' IDENTIFIED BY 'testpassword';"
mysql -u $MYSQL_USER -p$MYSQL_PASSWORD -e "CREATE SCHEMA myschemaname;"
mysql -u $MYSQL_USER -p$MYSQL_PASSWORD -e "GRANT ALL PRIVILEGES ON *.* TO 'myuser'@'%' IDENTIFIED BY 'testpassword';"
mysql -u $MYSQL_USER -p$MYSQL_PASSWORD myschemaname < ./app/Ship/Migrations/1of2-schema.sql
mysql -u $MYSQL_USER -p$MYSQL_PASSWORD myschemaname < ./app/Ship/Migrations/2of2-seed.sql
php artisan passport:install
./vendor/bin/phpunit

$MYSQL_USER and $MYSQL_PASSWORD are replaced by Codeship - these are the env variables for the user and password for the mysql that exists in the build container.
the -e switch on the mysql call runs the script given and exits.  Had to do it this way since I couldn't interact with the mysql client.


Q: replace 0 into dash in Fast Report Is it Possible to replace 0 value and turn it into dash in fast report?
like:
No.   turns to
1         1
2         2
0         -
3         3
0         -
0         -

A: Yes.
Use a built-in script engine.
Assuming you have a dataset DS and a field FIELD_NAME then instead of [DS."FIELD_NAME"] you should write [IIF(<DS."FIELD_NAME"> = 0, '-',  <DS."FIELD_NAME">)] as your frxMemoView text.


Q: databricks init script to mount dbfs on adls I am using a python notebook to mount dbfs on adls , now I want to add this to the init scrip so this can be done during the job cluster start
this is the python code I am using how to make this run as the init script please:
environment = "development"
scopeCredentials = "test-" + environment

# Secrets
# ADLS
app_id = dbutils.secrets.get(scope=scopeCredentials, key="app_id")
key = dbutils.secrets.get(scope=scopeCredentials, key="key")
adls_name = dbutils.secrets.get(scope=scopeCredentials, key="adls-name")

# Configs
# ADLS
adls_configs = {
  "dfs.adls.oauth2.access.token.provider.type": "ClientCredential",
  "dfs.adls.oauth2.client.id": app_id, #id is the AppId of the service principal
  "dfs.adls.oauth2.credential": key,
  "dfs.adls.oauth2.refresh.url": "url"
}

mount_point="mount_point"
if any(mount.mountPoint == mount_point  for mount in dbutils.fs.mounts()):
  print("Storage: " + mount_point + " already mounted")
else:
  try:
    dbutils.fs.mount(
      source = "source",
      mount_point = "mount_point",
      extra_configs = adls_configs)
    print("Storage: " + mount_point + " successfully mounted")
  except:
    print("Storage: " + mount_point + " not mounted")
    pass

any idea how to change this to make it as a bash init script ?

A: Mounting of the storage needs to be done once, or when you change credentials of the service principal.  Unmount & mount during the execution may lead to a problems when somebody else is using that mount from another cluster.
If you really want to access storage only from that cluster, then you need to configure that properties in the cluster's Spark Conf, and access data directly using abfss://...  URIs (see docs for details).  Mounting the storage just for time of execution of the cluster doesn't make sense from the security perspective, because during that time, anyone in workspace can access mounted data, as mount is global, not local to a cluster.


Q: Spring Reactive MVC vs @EnableAsync I'm a newbie to Spring Reactive Modules. What I got is basically, at its core it enable reactive programming and we can develop end to end reactive service.
But, suppose I just want to make my controller as Async, so that I can do work on multiple threads and send a reply like "Task Started" (not particularly this) and have my work going on and close the HTTP link.
I also got to know about @EnableAsync and @Async to make a method Async.
What if I just use @Async above my controller method that I want to make async. It worked but, is this a good practice? And can we use this in production codes?

A: I do not see any problem using @Asyncas this will release the request thread. But this is a simple approach and it has a lot of limitations. Note that if you want to deal with reactive streams, you do not have an API capable of that. For instance, if an @Async method calls another, the second will not be async.
The Webflux instead will bring the most complete API (in Java) to deal with things the reactive way. What you cannot do with only @Async. With Flux, for instance, you can process or access with multiple layers reactively and this you cannot reach the way you doing.
Nevertheless, it will bring a new universe for you, so if you just want to release the thread of the request, your approach is just fine, but if you need more you will have to deal with it in a more complex way.
Now, if you want to answer the HTTP request and then do the work asyncly, this is not what you want. I recommend that you have a JMS provider (like ActiveMQ), where your controller sends the message to be processed by a job and answers the request.
Hope it helps!


Q: Why search in .Net Dictionary is slower than in .Net List I tried to solve this task:
We have an array, eg. [1, 1, 2, 3, 5, 2, 7, 8, 1], find and output duplicates. For this array the result is
1, 2.
I wrote code to try "slow" and "fast" solutions.
"Slow" solution with inner loop and searching via list
   public uint[] InnerLoops(uint[] arr)
    {
        var timer = new Stopwatch();
        timer.Start();

        var result = new List<uint>();
        for (int i = 0; i < arr.Length; i++)
        {
            for (int j = i + 1; j < arr.Length; j++)
            {
                if (arr[i] == arr[j] && result.All(a => a != arr[j]))
                    result.Add(arr[j]);
            }
        }

        timer.Stop();

        Console.WriteLine($"Seconds: {timer.Elapsed}");

        return result.ToArray();
    }

I would estimate the solutions as O(n^2) and O(n) inside each inner loop. Sorry, I am not good at estimating complexity. Anyway, I thought, the following solution would be better
 public uint[] OneLoopDictionary(uint[] arr)
    {
        var timer = new Stopwatch();
        timer.Start();

        var dictionary = new Dictionary<uint, bool>();
        for (int i = 0; i < arr.Length; i++)
        {
            // Key - number, value - true if duplicates
            if (dictionary.ContainsKey(arr[i]))
            {
                dictionary[arr[i]] = true;
            }
            else
            {
                dictionary[arr[i]] = false;
            }
        }

        var result = new List<uint>();
        foreach (var item in dictionary)
        {
            if (item.Value)
                result.Add(item.Key);
        }

        timer.Stop();

        Console.WriteLine($"Seconds: {timer.Elapsed}");

        return result.ToArray();
    }

The complexity is O(2n) - one loop and loop via dictionary.
I was surprised that the fist solution with loop was faster that the second one. Could anyone explain me why?

A: Thanks to all! Espesially to who gave an advice to try with bigger array. I tryied with 100, 1000 and 100000 and I was surprised, that the dictionary was faster. Of course, previously, I tryied not just with array from my first post, bur with array of about 50 numbers, but the dictionary was slower.
With aaray of 100 or more numbers the dictuinary is much more faster. The result for 100000 items is:
list - 31 seconds,
dicionary - 0.008 seconds


Q: angularJs directive to format date I want to have a functionality in angular which help to enter date and show it in proper format and don't allow invalid values in it. also able to show server returned '20140314T00:00:00Z' json string for date.
Can anyone help me ?

A: Angular.js already have date filter {{20140314 | date}} //  Jan 1, 1970 9:35:40 AM
Angular Date Docs

A: This works for me,
   .directive('myDate', ['$timeout', '$filter', function ($timeout, $filter)
    {
        return {
            require: 'ngModel',

            link: function ($scope, $element, $attrs, $ctrl)
            {
                var dateFormat = 'mm/dd/yyyy';
                $ctrl.$parsers.push(function (viewValue)
                {
                    //convert string input into moment data model
                    var pDate = Date.parse(viewValue);
                    if (isNaN(pDate) === false) {
                        return new Date(pDate);
                    }
                    return undefined;

                });
                $ctrl.$formatters.push(function (modelValue)
                {
                    var pDate = Date.parse(modelValue);
                    if (isNaN(pDate) === false) {
                        return $filter('date')(new Date(pDate), dateFormat);
                    }
                    return undefined;
                });
                $element.on('blur', function ()
                {
                    var pDate = Date.parse($ctrl.$modelValue);
                    if (isNaN(pDate) === true) {
                        $ctrl.$setViewValue(null);
                        $ctrl.$render();
                    } else {
                        if ($element.val() !== $filter('date')(new Date(pDate), dateFormat)) {
                            $ctrl.$setViewValue($filter('date')(new Date(pDate), dateFormat));
                            $ctrl.$render();
                        }
                    }

                });
                $timeout(function ()
                {
                    $element.kendoDatePicker({

                        format: dateFormat
                    });

                });
            }
        };
    }])


Q: How can I solve my foreign key constraint error when I know I created the relationships right?

-- MySQL Workbench Forward Engineering

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

-- -----------------------------------------------------
-- Schema BrendasDMS
-- -----------------------------------------------------
DROP SCHEMA IF EXISTS `BrendasDMS` ;

-- -----------------------------------------------------
-- Schema BrendasDMS
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `BrendasDMS` DEFAULT CHARACTER SET utf8 ;
SHOW WARNINGS;
USE `BrendasDMS` ;

-- -----------------------------------------------------
-- Table `Customers`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Customers` ;

SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `Customers` (
  `Customer_ID` INT NOT NULL AUTO_INCREMENT,
  ` FirstName` VARCHAR(45) NOT NULL,
  `LastName` VARCHAR(45) NOT NULL,
  `Email` VARCHAR(45) NOT NULL,
  `Phone` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`Customer_ID`),
  UNIQUE INDEX `CustomerID_UNIQUE` (`Customer_ID` ASC))
ENGINE = InnoDB;

SHOW WARNINGS;

-- -----------------------------------------------------
-- Table `Employees`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Employees` ;

SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `Employees` (
  `Employee_ID` INT NOT NULL AUTO_INCREMENT,
  `FirstName` VARCHAR(45) NOT NULL,
  `LastName` VARCHAR(45) NOT NULL,
  `Address` VARCHAR(45) NOT NULL,
  `City` VARCHAR(45) NOT NULL,
  `State` VARCHAR(45) NOT NULL,
  `Zip` VARCHAR(45) NOT NULL,
  `County` VARCHAR(45) NOT NULL,
  `PhoneNumber` VARCHAR(45) NOT NULL,
  `BirthDate` DATE NOT NULL,
  `SSN` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`Employee_ID`),
  UNIQUE INDEX `FirstName_UNIQUE` (`FirstName` ASC))
ENGINE = InnoDB;

SHOW WARNINGS;

-- -----------------------------------------------------
-- Table `Shops`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Shops` ;

SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `Shops` (
  `Shop_ID` INT NOT NULL AUTO_INCREMENT,
  `Address` VARCHAR(45) NOT NULL,
  `County` VARCHAR(45) NOT NULL,
  `Zip` VARCHAR(45) NOT NULL,
  `Phone Number` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`Shop_ID`),
  UNIQUE INDEX `ID_UNIQUE` (`Shop_ID` ASC))
ENGINE = InnoDB;

SHOW WARNINGS;

-- -----------------------------------------------------
-- Table `Sales`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Sales` ;

SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `Sales` (
  `Sale_ID` INT NOT NULL AUTO_INCREMENT,
  `SaleDate` DATE NOT NULL,
  `Employee_ID` INT NOT NULL,
  `Customer_ID` INT NOT NULL,
  `Shop_ID` INT NOT NULL,
  `Quantity` INT NOT NULL,
  `Price` DECIMAL NOT NULL,
  `UnitOfMeasure` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`Sale_ID`, `Customer_ID`, `Employee_ID`, `Shop_ID`),
  INDEX `fk_Sale_Employee1_idx` (`Employee_ID` ASC),
  INDEX `fk_Sale_Customer1_idx` (`Customer_ID` ASC),
  INDEX `fk_Sale_Shops1_idx` (`Shop_ID` ASC),
  CONSTRAINT `fk_Sale_Employee1`
    FOREIGN KEY (`Employee_ID`)
    REFERENCES `Employees` (`Employee_ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Sale_Customer1`
    FOREIGN KEY (`Customer_ID`)
    REFERENCES `Customers` (`Customer_ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Sale_Shops1`
    FOREIGN KEY (`Shop_ID`)
    REFERENCES `Shops` (`Shop_ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

SHOW WARNINGS;

-- -----------------------------------------------------
-- Table `Products`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Products` ;

SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `Products` (
  `Product_ID` INT NOT NULL AUTO_INCREMENT,
  `ProductName` VARCHAR(45) NOT NULL,
  `UnitOfMeasure` VARCHAR(45) NOT NULL,
  `Price` DECIMAL NOT NULL,
  `Quantity` INT NOT NULL,
  PRIMARY KEY (`Product_ID`),
  UNIQUE INDEX `RecipeID_UNIQUE` (`Product_ID` ASC))
ENGINE = InnoDB;

SHOW WARNINGS;

-- -----------------------------------------------------
-- Table `SaleLineItems`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `SaleLineItems` ;

SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `SaleLineItems` (
  `Sale_ID` INT NOT NULL,
  `Quantity` INT NOT NULL,
  `Product_ID` INT NOT NULL,
  PRIMARY KEY (`Sale_ID`, `Product_ID`),
  INDEX `fk_Sale_has_Product_Sale1_idx` (`Sale_ID` ASC),
  INDEX `fk_SaleLineItem_Product1_idx` (`Product_ID` ASC),
  CONSTRAINT `fk_Sale_has_Product_Sale1`
    FOREIGN KEY (`Sale_ID`)
    REFERENCES `Sales` (`Sale_ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_SaleLineItem_Product1`
    FOREIGN KEY (`Product_ID`)
    REFERENCES `Products` (`Product_ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

SHOW WARNINGS;

-- -----------------------------------------------------
-- Table `Vendors`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Vendors` ;

SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `Vendors` (
  `Vendor_ID` INT NOT NULL AUTO_INCREMENT,
  `FirstName` VARCHAR(45) NOT NULL,
  `LastName` VARCHAR(45) NOT NULL,
  `VendorType` VARCHAR(45) NOT NULL,
  `Address` VARCHAR(45) NOT NULL,
  `Zip` VARCHAR(45) NOT NULL,
  `PhoneNumber` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`Vendor_ID`),
  UNIQUE INDEX `ID_UNIQUE` (`Vendor_ID` ASC))
ENGINE = InnoDB;

SHOW WARNINGS;

-- -----------------------------------------------------
-- Table `Orders`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Orders` ;

SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `Orders` (
  `Order_ID` INT NOT NULL AUTO_INCREMENT,
  `Date` DATE NOT NULL,
  `Vendor_ID` INT NOT NULL,
  `Quantity` INT NOT NULL,
  `UnitOfMeasure` VARCHAR(45) NOT NULL,
  `Price` DECIMAL NOT NULL,
  PRIMARY KEY (`Order_ID`, `Vendor_ID`),
  UNIQUE INDEX `ID_UNIQUE` (`Order_ID` ASC),
  INDEX `fk_Orders_Vendor1_idx` (`Vendor_ID` ASC),
  CONSTRAINT `fk_Orders_Vendor1`
    FOREIGN KEY (`Vendor_ID`)
    REFERENCES `Vendors` (`Vendor_ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

SHOW WARNINGS;

-- -----------------------------------------------------
-- Table `EmployeeShop`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `EmployeeShop` ;

SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `EmployeeShop` (
  `Shop_ID` INT NOT NULL,
  `Employee_ID` INT NOT NULL,
  PRIMARY KEY (`Shop_ID`, `Employee_ID`),
  INDEX `fk_Shop_has_Employee_Employee1_idx` (`Employee_ID` ASC),
  INDEX `fk_Shop_has_Employee_Shop1_idx` (`Shop_ID` ASC),
  CONSTRAINT `fk_Shop_has_Employee_Shop1`
    FOREIGN KEY (`Shop_ID`)
    REFERENCES `Shops` (`Shop_ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Shop_has_Employee_Employee1`
    FOREIGN KEY (`Employee_ID`)
    REFERENCES `Employees` (`Employee_ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

SHOW WARNINGS;

-- -----------------------------------------------------
-- Table `Ingredients`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Ingredients` ;

SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `Ingredients` (
  `Ingredient_ID` INT NOT NULL,
  `IngredientName` VARCHAR(45) NOT NULL,
  `UnitOfMeasure` VARCHAR(45) NOT NULL,
  `Quantity` INT NOT NULL,
  `Price` DECIMAL NOT NULL,
  PRIMARY KEY (`Ingredient_ID`))
ENGINE = InnoDB;

SHOW WARNINGS;

-- -----------------------------------------------------
-- Table `OrderLineItems`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `OrderLineItems` ;

SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `OrderLineItems` (
  `Quantity` INT NOT NULL,
  `Order_ID` INT NOT NULL,
  `Ingredient_ID` INT NOT NULL,
  PRIMARY KEY (`Order_ID`, `Ingredient_ID`),
  INDEX `fk_OrderLineItems_Orders1_idx` (`Order_ID` ASC),
  INDEX `fk_OrderLineItems_Ingredients1_idx` (`Ingredient_ID` ASC),
  CONSTRAINT `fk_OrderLineItems_Orders1`
    FOREIGN KEY (`Order_ID`)
    REFERENCES `Orders` (`Order_ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_OrderLineItems_Ingredients1`
    FOREIGN KEY (`Ingredient_ID`)
    REFERENCES `Ingredients` (`Ingredient_ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = ndbcluster;

SHOW WARNINGS;

-- -----------------------------------------------------
-- Table `Recipes`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `Recipes` ;

SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `Recipes` (
  `Recipe_ID` INT NOT NULL,
  `Directions` VARCHAR(45) NOT NULL,
  `Product_ID` INT NOT NULL,
  PRIMARY KEY (`Recipe_ID`, `Product_ID`),
  UNIQUE INDEX `Recipe_ID_UNIQUE` (`Recipe_ID` ASC),
  INDEX `fk_Recipes_Products1_idx` (`Product_ID` ASC),
  CONSTRAINT `fk_Recipes_Products1`
    FOREIGN KEY (`Product_ID`)
    REFERENCES `Products` (`Product_ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

SHOW WARNINGS;

-- -----------------------------------------------------
-- Table `RecipeIngredients`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `RecipeIngredients` ;

SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `RecipeIngredients` (
  `Quantity` INT NOT NULL,
  `Ingredient_ID` INT NOT NULL,
  `UnitOfMeasure` VARCHAR(45) NOT NULL,
  `Price` DECIMAL NOT NULL,
  `Recipe_ID` INT NOT NULL,
  PRIMARY KEY (`Ingredient_ID`, `Recipe_ID`),
  INDEX `fk_RecipeIngredients_Ingredients2_idx` (`Ingredient_ID` ASC),
  INDEX `fk_RecipeIngredients_Recipes1_idx` (`Recipe_ID` ASC),
  CONSTRAINT `fk_RecipeIngredients_Ingredients2`
    FOREIGN KEY (`Ingredient_ID`)
    REFERENCES `Ingredients` (`Ingredient_ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_RecipeIngredients_Recipes1`
    FOREIGN KEY (`Recipe_ID`)
    REFERENCES `Recipes` (`Recipe_ID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

SHOW WARNINGS;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

I have created a lot of tables and I am now trying to forward engineer my logical model into a physical database, but I am having trouble when it keeps saying "Can't add a foreign key constraint".
However, I know that the error is related to the Products referencing the Recipe_ID, but when I click on the relationship line from Recipes table to RecipeIngredients table, I see that the FK Recipe_ID IS REFERENCING the Recipe_ID primary key column in the Recipes table, not the Product table.

If that is the case, why is problem occurring? Any suggestions except recreating all of the tables again. Here is my picture model and picture of my problem.


Q: Swagger-play2 - hiding internal parameters I have configured swagger-play2 library version 1.7.1 (for play framework version 2.7) and have it up and running successfully. Our controller methods have an additional input: Http.Request request which is passed across the application for some logging and monitoring purposes. I need to hide this from the swagger specs, tried using @ApiParam(hidden = true) but it still shows up in specs. Is this flag not working as expected? how do I hide the input in this case? I'd like to know whether @ApiParam(hidden = true) has worked for anyone with swagger-play2 plugin, not with Spring.
Thanks.


Q: Flutter - AndroidManifest.xml corrupted after Flutter Upgrade I've just upgraded to Flutter 2 and upgraded an application along with it. I followed all the steps to upgrade the application, but now I can't seem to run the app because my AndroidManifest.xml file seems corrupted.
Here is the xml file (I've also added comments where the errors are appearing).
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.finances_management">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <application
        android:name="io.flutter.app.FlutterApplication" <-- Unresolved class 'FlutterApplication'
        android:label="finances_management"
        android:icon="@mipmap/ic_launcher"> <-- Cannot resolve symbol '@mipmap/ic_launcher'
        <activity
            android:name=".MainActivity" <-- Unresolved class 'MainActivity'
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme" <-- Cannot resolve symbol '@style/LaunchTheme'
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme" <-- Cannot resolve symbol '@style/NormalTheme'
              />
            <!-- Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. -->
            <meta-data
              android:name="io.flutter.embedding.android.SplashScreenDrawable"
              android:resource="@drawable/launch_background" <-- Cannot resolve symbol '@drawable/launch_background'
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>

I've seen elsewhere that people are just completely rebuilding their projects (as in completely generating a new project, stripping business logic from their Flutter 1.x app and copying it across to a Flutter 2.x app). Does anyone know what's happened to my XML file?

A: The best solution is to downgrade the Flutter . after that update AndroidManifest file


Q: Regarding GetProcAddress I have got MyDll.dll and its function defined as below
void pascal Myfunction(BOOL);

when I'm trying to use the function in another project i am unable get the address of the function with GetProcAddress(). Here is my code:
void callMyDll()
{
 HINSTANCE hDll;

 hDll=LoadLibrary(_T("MyDll.dll");

 if(hDll!=NULL)
 {
  cout<<"\n DLL Loaded \n";
 }
 else
  cout<<"\n DLL Not loaded\n"

 typedef void (__stdcall *MyFunction)(bool)

 Myfunction mf1 = (MyFunction) GetProcAddress(hDll, "MyFunction");

 if (mf1!=NULL)
  cout<<"\n Function Loaded Successfully \n";
 else
  cout<<"\n Function not loaded \n";

 FreeLibrary(hDll);
}

I'm getting output as:
DLL Loaded
Function not loaded

But when I'm trying with known DLLs like glut32.dll and its functions it is working fine.
I think it may be problem with its function like
void pascal MyFunction(BOOL);

Can anybody help me in this regard?

A: You need to use extern "C" to prevent name mangling and ensure the function is exported:
extern "C" __declspec(dllexport) void Myfunction(BOOL);

To view the exports from your DLL you can use dumpbin.exe utility that is shipped with Visual Studio:
dumpbin.exe /EXPORTS MyDll.dll

This will list the names of all exported symbols.
In addition to this do not have either of the following compiler switches specified:
Gz __stdcall calling convention: "Myfunction" would be exported as Myfunction@4
Gr __fastcall caling convention: "Myfunction" would be exported as @Myfunction@4

Note: I think last symbol is dependent on compiler version but is still not just "Myfunction".

A: The DLL export process is subject to name mangling and decoration. The long obsolete 16 bit pascal calling convention is equivalent to stdcall on 32 bit platforms.
First of all you should use extern "C" to specify C linkage and disable name mangling.
However, your function will still be subject to name decoration. If you export it with __declspec(dllexport) then it will in fact be exported with the name _Myfunction@4. If you wish to export it by its true name then you need to use a .def file.
However, the possibility still remains that you did not export the function from the DLL at all. Use Dependency Walker to check whether it was exported, and if so by what name.

A: Why are you using the pascal calling-convention? Perhaps that alters the names of symbols, and if so you might need to take that into account.

A: The symbol is going to be decorated, so it will never be called MyFunction, its more likely _MyFunction@4. you can quickly check this using something like dumpbin.
You can read up more on mangling here, if you want to avoid mangling, you need to use a def file to specify symbol names (or ordinals).


Q: i am dumping a piped data , but when i try to read using pickle.loads i get an error this code works fine thats piping out
    allWriteNodes=nuke.allNodes("Write")
    test = nuke.allNodes()
    for index,each in enumerate(test):
        wrtNodelst.insert(index,each.name())
        print index, each.name()
    sys.stdout.write(pickle.dumps(wrtNodelst))
    quit()
except RuntimeError:
  sys.stderr.write('could not find %s\n' % target_file)
  raise

but this line that is going to read in different file causes error:
print pickle.loads(process.stdout.read())

giving IndexError : list index out of range... any idea what might be causing it and out to read pickled stdout data ?
The Traceback  error
Traceback (most recent call last):
File "\RenderUI.py", line 384, in execApp
print pickle.loads(process.stdout.read())
File "D:\Python26\lib\pickle.py", line 1374, in loads
return Unpickler(file).load()
File "D:\Python26\lib\pickle.py", line 858, in load
dispatch[key](self)
File "D:\Python26\lib\pickle.py", line 1203, in load_setitems
mark = self.marker()
File "D:\Python26\lib\pickle.py", line 874, in marker
while stack[k] is not mark: k = k-1
IndexError: list index out of range

A: use
print pickle.load(process.stdout)

does this work?
read may not return the whole string.

A: This line:
   print index, each.name()

Causes issues, as it is sending debug output to stdout before the pickle is sent.


Q: Decimal/double to integer - round up (not just to nearest) How would you round up a decimal or float to an integer. For instance...
0.0 => 0
0.1 => 1
1.1 => 2
1.7 => 2
2.1 => 3

Etc.

A: Simple, use Math.Ceiling:
var wholeNumber = (int)Math.Ceiling(fractionalNumber);

A: Something like this?
int myInt = (int)Math.Ceiling(myDecimal);

A: Before saying it does not work, you have to check that ALL VALUES in the operation are double type.
Here is an example in C#:
 int speed= Convert.ToInt32(Math.Ceiling((double)distance/ (double)time));

A: Math.Ceiling not working for me, I use this code and this work :)
int MyRoundedNumber= (int) MyDecimalNumber;
                if (Convert.ToInt32(MyDecimalNumber.ToString().Split('.')[1]) != 0)
                    MyRoundedNumber++;

and if you want to round negative number to down for example round -1.1 to -2 use this
  int MyRoundedNumber= (int) MyDecimalNumber;
                    if (Convert.ToInt32(MyDecimalNumber.ToString().Split('.')[1]) != 0)
                        if(MyRoundedNumber>=0)
                           MyRoundedNumber++;
                        else
                           MyRoundedNumber--;

A: var d = 1.5m;
var i = (int)Math.Ceiling(d);
Console.Write(i);


Q: Node.js bindings for a Digital Asset Ledger Project I am working through Digital Asset Getting Started with Node.js bindings.
Running
npm install @da/daml-ledger

causes the following error message
npm ERR! code E401
npm ERR! 401 Unauthorized: @da/daml-ledger@latest

npm ERR! A complete log of this run can be found in:
npm ERR!     /...../.npm/_logs/2019-02-22T17_48_44_560Z-debug.log

here are the contents of that log file:
0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/lib/nodejs/node-v10.15.1-linux-x64/bin/node',
1 verbose cli   '/usr/local/lib/nodejs/node-v10.15.1-linux-x64/bin/npm',
1 verbose cli   'install',
1 verbose cli   '@da/daml-ledger' ]
2 info using npm@6.4.1
3 info using node@v10.15.1
4 verbose npm-session 99e5e60df68735cb
5 silly install loadCurrentTree
6 silly install readLocalPackageData
7 http fetch GET 401 https://api.bintray.com/npm/digitalassetsdk/npm/@da%2fdaml-ledger 411ms
8 silly fetchPackageMetaData error for @da/daml-ledger@latest 401 Unauthorized: @da/daml-ledger@latest
9 timing stage:rollbackFailedOptional Completed in 4ms
10 timing stage:runTopLevelLifecycles Completed in 515ms
11 verbose stack Error: 401 Unauthorized: @da/daml-ledger@latest
11 verbose stack     at fetch.then.res (/usr/local/lib/nodejs/node-v10.15.1-linux-x64/lib/node_modules/npm/node_modules/pacote/lib/fetchers/registry/fetch.j
s:42:19)
11 verbose stack     at tryCatcher (/usr/local/lib/nodejs/node-v10.15.1-linux-x64/lib/node_modules/npm/node_modules/bluebird/js/release/util.js:16:23)
11 verbose stack     at Promise._settlePromiseFromHandler (/usr/local/lib/nodejs/node-v10.15.1-linux-x64/lib/node_modules/npm/node_modules/bluebird/js/relea
se/promise.js:512:31)
11 verbose stack     at Promise._settlePromise (/usr/local/lib/nodejs/node-v10.15.1-linux-x64/lib/node_modules/npm/node_modules/bluebird/js/release/promise.
js:569:18)
11 verbose stack     at Promise._settlePromise0 (/usr/local/lib/nodejs/node-v10.15.1-linux-x64/lib/node_modules/npm/node_modules/bluebird/js/release/promise
.js:614:10)
11 verbose stack     at Promise._settlePromises (/usr/local/lib/nodejs/node-v10.15.1-linux-x64/lib/node_modules/npm/node_modules/bluebird/js/release/promise
.js:693:18)
11 verbose stack     at Async._drainQueue (/usr/local/lib/nodejs/node-v10.15.1-linux-x64/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:133:
16)
11 verbose stack     at Async._drainQueues (/usr/local/lib/nodejs/node-v10.15.1-linux-x64/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:143
:10)
11 verbose stack     at Immediate.Async.drainQueues [as _onImmediate] (/usr/local/lib/nodejs/node-v10.15.1-linux-x64/lib/node_modules/npm/node_modules/blueb
ird/js/release/async.js:17:14)
11 verbose stack     at runCallback (timers.js:705:18)
11 verbose stack     at tryOnImmediate (timers.js:676:5)
11 verbose stack     at processImmediate (timers.js:658:5)
12 verbose cwd /home/vantage/DAnodeBindings
13 verbose Linux 4.15.0-45-generic
14 verbose argv "/usr/local/lib/nodejs/node-v10.15.1-linux-x64/bin/node" "/usr/local/lib/nodejs/node-v10.15.1-linux-x64/bin/npm" "install" "@da/daml-ledger"
15 verbose node v10.15.1
16 verbose npm  v6.4.1
17 error code E401
18 error 401 Unauthorized: @da/daml-ledger@latest
19 verbose exit [ 1, true ]

I followed the instructions in step 1 and step 2.  my .npmrc is updated with the response I received from entering
curl -umehul@digitalassetsdk:<API_KEY> https://api.bintray.com/npm/digitalassetsdk/npm/auth/scope/da

and I entered the command
npm config set @da:registry https://api.bintray.com/npm/digitalassetsdk/npm

What is causing the error?

A: From the comments it appears you missed a step of the setup, namely as the instructions tell you to paste the response of curl to ~/.npmrc.

The response should be pasted in the ~/.npmrc (in Windows %USERPROFILE%/.npmrc) file.

As an alternative, on Linux and MacOS you can just pipe the output of curl to ~/.npmrc as follows:
curl -u<USERNAME>:<API_KEY> https://api.bintray.com/npm/digitalassetsdk/npm/auth/scope/da >> ~/.npmrc

Using the >> operator will preserve the current content of ~/.npmrc and append the output of curl to the file (or create it if it's not there yet). If you want to overwrite the current ~/.npmrc file, just use the > operator instead.

A: The Bintary 'Set Me Up' Instructions (referenced in step 1.3 of https://docs.daml.com/app-dev/bindings-js/getting-started.html) say to run a curl command and the to run
npm config set @<SCOPE>:registry https://api.bintray.com/npm/digitalassetsdk/npm

When I skip the npm config step I have no problems.


Q: vue.js - Is there any way to render elements in two different divs using one v-for loop? The goal is to make the output look like this:

        tab 1
        tab 2

        tab 3

Currently I'm using this solution (using two v-for loops):
tabs.js (current)
export default {
    data() {
        return {
          tabs: {
              first: [{ name: 'tab1' }, { name: 'tab2' }],
              second: [{ name: 'tab3' }],
          }
        }
    }
    template: `

                {{ tab.name }}

                {{ tab.name }}

    `
}

I had an idea to do something like this but it performs more iterations than in the case with two loops:
tabs.js (idea)
export default {
    data() {
        return {
          tabs: {
              test: [
                  { name: 'tab1', category: 'first' },
                  { name: 'tab2', category: 'first' },
                  { name: 'tab3', category: 'second' }
              ]
          }
        }
    }
    template: `

                <template v-for="tab in tabs.test">
                    {{ tab.name }}
                </template>

    `
}

I read this topic but it contains slightly different solutions, which unfortunately didn't work in this case.

A: I did not see any harm in using two v-for (one for the object keys and another for the array elements) as far as it is all dynamic. You can give a try to this solution by using of Object.keys() :

new Vue({
  el: '#app',
  data: {
    tabs: {
      first: [{ name: 'tab1' }, { name: 'tab2' }],
      second: [{ name: 'tab3' }],
    }
  }
})

      {{ tab.name }}

A: There's no problem using more than one v-for loops. And there's no problem using nested v-for loops.
The problem I see with your current code is that it's not scalable. You're hard-coding the exact values of your tabs in <template />(e.g: first, second).
The main idea here is to loop through tabs and, inside each tab, to loop through each contents, without the <template> needing to know what the tab is or how many there are.
So that when you change your tabs to, say...
{
   tab1: [{ name: 'intro'}],
   tab2: [{ name: 'tab2-1' }, { name: 'tab2-2' }],
   tab3: [{ name: 'tab3' }]
}

template still works, without needing any change.

To achieve this type of flexibility, you need to use a nested v-for loop:

Demo:

new Vue({
  el: '#app',
  data: () => ({
    tabs: {
      tab1: [{
        name: 'intro'
      }],
      tab2: [{
        name: 'tab2-1'
      }, {
        name: 'tab2-2'
      }],
      tab3: [{
        name: 'tab3'
      }]
    }
  })
})
#tabs a { padding: 3px 7px }

      <a v-for="(link, key) in links"
         :key="key"
         :href="`#${link.name}`"
         v-text="link.name">

But I'd take it one step further and change the tabs to be an array:
data: () => ({
  tabs: [
    [{ name: 'intro'}],
    [{ name: 'tab1' }, { name: 'tab2' }],
    [{ name: 'tab3' }]
  ]
})

And use :id="'tab-' + name" on tab divs if you really need those unique ids. (Hint: you don't).
It makes more sense to me.

A: You could add a computed property being the .concat from both and loop for it
export default {
    data() {
        tabs: {
            first: [{ name: 'tab1' }, { name: 'tab2' }],
            second: [{ name: 'tab3' }],
        }
    },
    computed: {
       tabsCombined () {
          return this.tabs.first.concat(this.tabs.second)
       }
    },
    template: `

                <template v-for="tab in tabs.test">
                    {{ tab.name }}
                </template>

    `
}


Q: Changing Activity to Fragment with sqlite db I have recently tried to change a working sqlite populated listview activity into a fragment. I have made the changes needed but I continue to get errors that i dont understand. If any of you could help it would relieve serious frustration.
Here is my main activity
public class FoursFragment extends Fragment {

private DbHelper mHelper;
private SQLiteDatabase dataBase;

private ArrayList<String> userId = new ArrayList<String>();
private ArrayList<String> user_fName = new ArrayList<String>();
private ArrayList<String> user_lName = new ArrayList<String>();

private ListView userList;
private AlertDialog.Builder build;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.display_activity, container, false);

    userList = (ListView) view.findViewById(R.id.List);

    mHelper = new DbHelper(getActivity());

    //add new record
    getView().findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() {

        public void onClick(View v) {

            Intent i = new Intent(getActivity(),
                    AddActivity.class);
            i.putExtra("update", false);
            startActivity(i);

        }
    });

    //click to update data
    userList.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {

            Intent i = new Intent(getActivity(),
                    AddActivity.class);
            i.putExtra("Fname", user_fName.get(arg2));
            i.putExtra("Lname", user_lName.get(arg2));
            i.putExtra("ID", userId.get(arg2));
            i.putExtra("update", true);
            startActivity(i);

        }
    });

    //long click to delete data
    userList.setOnItemLongClickListener(new OnItemLongClickListener() {

        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                final int arg2, long arg3) {

            build = new AlertDialog.Builder(getActivity());
            build.setTitle("Delete " + user_fName.get(arg2) + " "
                    + user_lName.get(arg2));
            build.setMessage("Do you want to delete ?");
            build.setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog,
                                int which) {

                            Toast.makeText(
                                    getActivity(),
                                    user_fName.get(arg2) + " "
                                            + user_lName.get(arg2)
                                            + " is deleted.", 3000).show();

                            dataBase.delete(
                                    DbHelper.TABLE_NAME,
                                    DbHelper.KEY_ID + "="
                                            + userId.get(arg2), null);
                            displayData();
                            dialog.cancel();
                        }
                    });

            build.setNegativeButton("No",
                    new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog,
                                int which) {
                            dialog.cancel();
                        }
                    });
            AlertDialog alert = build.create();
            alert.show();

            return true;
        }
    });
    return view;
}

@Override
public void onResume() {
    displayData();
    super.onResume();
}

/**
 * displays data from SQLite
 */
private void displayData() {
    dataBase = mHelper.getWritableDatabase();
    Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
            + DbHelper.TABLE_NAME, null);

    userId.clear();
    user_fName.clear();
    user_lName.clear();
    if (mCursor.moveToFirst()) {
        do {
            userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
            user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
            user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));

        } while (mCursor.moveToNext());
    }
    DisplayAdapter disadpt = new DisplayAdapter(getActivity(),userId, user_fName, user_lName);
    userList.setAdapter(disadpt);
    mCursor.close();
}

}
Here is adapter that is called.
public class DisplayAdapter extends BaseAdapter {

 private Context mContext;
private ArrayList<String> id;
private ArrayList<String> firstName;
private ArrayList<String> lastName;

public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname) {
    this.mContext = c;

    this.id = id;
    this.firstName = fname;
    this.lastName = lname;
}

public int getCount() {
    // TODO Auto-generated method stub
    return id.size();
}

public Object getItem(int position) {
    // TODO Auto-generated method stub
    return null;
}

public long getItemId(int position) {
    // TODO Auto-generated method stub
    return 0;
}

public View getView(int pos, View child, ViewGroup parent) {
    Holder mHolder;
    LayoutInflater layoutInflater;
    if (child == null) {
        layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        child = layoutInflater.inflate(R.layout.listcell, null);
        mHolder = new Holder();
        mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
        mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
        mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
        child.setTag(mHolder);
    } else {
        mHolder = (Holder) child.getTag();
    }
    mHolder.txt_id.setText(id.get(pos));
    mHolder.txt_fName.setText(firstName.get(pos));
    mHolder.txt_lName.setText(lastName.get(pos));

    return child;
}

public class Holder {
    TextView txt_id;
    TextView txt_fName;
    TextView txt_lName;
}

}
And here is the DBhelper.
public class DbHelper extends SQLiteOpenHelper {
static String DATABASE_NAME="userdata";
public static final String TABLE_NAME="user";
public static final String KEY_FNAME="fname";
public static final String KEY_LNAME="lname";
public static final String KEY_ID="id";
public DbHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);

}

@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT)";
    db.execSQL(CREATE_TABLE);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
    onCreate(db);

}

}
The error i receive is as follows
03-20 13:15:50.108: E/AndroidRuntime(795): FATAL EXCEPTION: main
03-20 13:15:50.108: E/AndroidRuntime(795): java.lang.NullPointerException
03-20 13:15:50.108: E/AndroidRuntime(795):  atapp.norman.tennis.FoursFragment.onCreateView(FoursFragment.java:52)
03-20 13:15:50.108: E/AndroidRuntime(795):  at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:795)
03-20 13:15:50.108: E/AndroidRuntime(795):  at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:998)
03-20 13:15:50.108: E/AndroidRuntime(795):  at android.app.BackStackRecord.run(BackStackRecord.java:622)
03-20 13:15:50.108: E/AndroidRuntime(795):  at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1330)
03-20 13:15:50.108: E/AndroidRuntime(795):  at android.app.FragmentManagerImpl$1.run(FragmentManager.java:417)
03-20 13:15:50.108: E/AndroidRuntime(795):  at android.os.Handler.handleCallback(Handler.java:605)
03-20 13:15:50.108: E/AndroidRuntime(795):  at android.os.Handler.dispatchMessage(Handler.java:92)
03-20 13:15:50.108: E/AndroidRuntime(795):  at android.os.Looper.loop(Looper.java:137)
03-20 13:15:50.108: E/AndroidRuntime(795):  at android.app.ActivityThread.main(ActivityThread.java:4340)
03-20 13:15:50.108: E/AndroidRuntime(795):  at java.lang.reflect.Method.invokeNative(Native Method)
03-20 13:15:50.108: E/AndroidRuntime(795):  at java.lang.reflect.Method.invoke(Method.java:511)
03-20 13:15:50.108: E/AndroidRuntime(795):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-20 13:15:50.108: E/AndroidRuntime(795):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-20 13:15:50.108: E/AndroidRuntime(795):  at dalvik.system.NativeStart.main(Native Method)

I really don't mind if it is something stupid but really cant figure out what is going on! Thankyou!

A: Replace
//add new record
getView().findViewById(...

with
//add new record
view.findViewById(...

getView() in onCreateView() is too early - you haven't yet returned the view to the framework for getView() to return.


Q: Rollback not happening for ForEach container in SSIS I have the following use case:
I am trying to move the files in one folder to another folder. If any file is corrupt then whole process should be rolled back and no files should be moved.
For achieving this I am making use of one data flow task and one file system task. Data flow task would check for the integrity of the file and file system task would then move the file. These two tasks are in foreach container.
The transaction property of foreach is set to required and for the two tasks inside it, i am keeping it as supported.
Issue: There are 6 files in one folder which are to be moved. The file # 4 is corrupt. I want the whole task to rollback when system detects the corrupt file. However, this is not happening and files uptil file no 3 get moved.
Screen shot attached.


Q: Check type a variable I'm making a call to os/Create function and want to make sure in one of my test cases that the response is indeed of type *os.File.
Below is my code snippet. Though I made a lot of iterations but the motivation for these lines was this post.
//somevar -- gets *os.File from a function
var varType *os.File
tpe := reflect.TypeOf(varType).Elem()
fmt.Println(reflect.TypeOf(somevar).Implements(tpe)) // I expect a true or false

When I run this code I get a panic:
panic: reflect: non-interface type passed to Type.Implements [recovered]
    panic: reflect: non-interface type passed to Type.Implements

Please suggest what wrong I'm doing. All I want to check for is - some variable is of type *os.File - yes or no.

A: I think you may just be looking for
var varType *os.File
tpe := reflect.TypeOf(varType).Elem()
fmt.Println(tpe == reflect.TypeOf(somevar).Elem())


Q: python django ORM error/bug?: ...Cannot resolve keyword 'id' into field. Choices are: id,  i found the answer! this happened if i named a script exactly like the app name!
this is a corrected (simplified) version of the post.
i'm trying to run this standalone script (or even located in the app directory):
#!/usr/local/bin/python -W ignore
# coding: utf-8

import sys, os
sys.path.append('/usr/home/code')
os.environ['DJANGO_SETTINGS_MODULE'] = 'tuppy.settings'
from tuppy.tup.models import *

some_dict={}
print UserProfile.objects.filter(id=1)
print 'lallala'
print some_dict['unexisting_key']

and get the following error. mind that the script first prints the correct request result to UserProfile, and only facing another error prints incorrect error description:
# ./tup.py
[<UserProfile: 115>]
lallala
Traceback (most recent call last):
  File "./tup.py", line 10, in <module>
    p = UserProfile.objects.filter(id=1)
  File "/usr/local/lib/python2.6/site-packages/django/db/models/manager.py", line 141, in filter
    return self.get_query_set().filter(*args, **kwargs)
  File "/usr/local/lib/python2.6/site-packages/django/db/models/query.py", line 556, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "/usr/local/lib/python2.6/site-packages/django/db/models/query.py", line 574, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "/usr/local/lib/python2.6/site-packages/django/db/models/sql/query.py", line 1152, in add_q
    can_reuse=used_aliases)
  File "/usr/local/lib/python2.6/site-packages/django/db/models/sql/query.py", line 1045, in add_filter
    negate=negate, process_extras=process_extras)
  File "/usr/local/lib/python2.6/site-packages/django/db/models/sql/query.py", line 1215, in setup_joins
    "Choices are: %s" % (name, ", ".join(names)))
django.core.exceptions.FieldError: Cannot resolve keyword 'id' into field. Choices are: credit_limit, id, insured_order_limit, mob_tel, resale_limit, sec_tel, status, user, voice_psw

#

A: I had the same issue on trying to get the first group from auth_group (Django v. 1.3.5)
Group.objects.get(name='First Group')
gave the same FeildError.
Stangerly this worked:
try:
    Group.objects.get(name="Active Rater")    #crazily not working
except django.core.exceptions.FieldError as e:
    group = Group.objects.get(name="Active Rater")    #crazily works

I have not yet dug into the django code to figure out why.


Q: visual c++ 2005 dll project and prerequisites needs to be installed on target machine i wrote a simple dll and i included below header files:
#include <windows.h>
#include <sddl.h>
#include <winsock.h>
#include <stdio.h>
#include <stdlib.h>
#include <mprapi.h>
#include <raserror.h>
#include <mprerror.h>
#include <strsafe.h>

so my dll works fine in my computer but in another computer not working. i installed vcredist_x86 on target machine but nothing changed. i also used setup deploy wizard and nothing happend. but when i installed visual studio 2005 on target machine my dll works perfectly.
so here is the question, how can i retrieve which prerequisites needs to be installed on target machine?
also i must mention that i compiled my code as c code "Compile as C Code (/TC)".
sorry for my poor english and thanks for your helps in advance.


Q: How to ensure that gid in /etc/passwd also exist in /etc/group Background: The Unclassified RHEL 6 Security Technical Implementation Guide (STIG), a DoD guide, specifies in (STID-ID) RHEL-06-000294 that all user primary GIDs appearing in /etc/passwd must exist in /etc/group.
Instead of running the recommended 'pwck -rq' command and piping to a log then forcing the admin to manually remediate, it makes more sense to programmatically check if the users GID exists and, if not, simply set it to something which does exist such as "users" or "nobody"
I've been beating my head against this and can't quite get it.  I've failed at sed, awk, and some piping of grep into sed or awk.  The problem seems to be when I attempt to nest commands.  I learned the hard way that awk won't nest in one-liners (or possibly at all).
The pseudo-code for a more traditional loop looks something like:
# do while not EOF /etc/passwd
#   GIDREF = get 4th entry, sepparator ":" from line
#   USERNAMEFOUND = get first entry, separator ":" from line
#   grep ":$GIDREF:" /etc/group
#   if not found then
#      set GID for USERNAMEFOUND to "users"
#   fi
# end-do.

This seems like it should be quite simple but I'm apparently missing something.
Thanks for the help.
-Kirk

A: List all GIDs from /etc/passwd that don't exist in /etc/group:
comm -23 <(awk -F: '{print $4}' /etc/passwd | sort -u) \
         <(awk -F: '{print $3}' /etc/group  | sort -u)

Fix them:
nogroup=$(awk -F: '($1=="nobody") {print $3}' /etc/group)
for gid in $(
 comm -23 <(awk -F: '{print $4}' /etc/passwd | sort -u) \
          <(awk -F: '{print $3}' /etc/group  | sort -u)); do
  awk -v gid="$gid" -F: '($4==gid) {print $1}' /etc/passwd |
   xargs -n 1 usermod -g "$nogroup"
done

A: I'm thinking along these lines:
if ! grep "^$(groups $USERNAME | cut -d\  -f 1):" /etc/group > /dev/null; then
  usermod -g users $USERNAME
fi

Where
groups $USERNAME | cut -d\  -f 1

gives the primary group of $USERNAME by splitting the output of groups $USERNAME at the first space (before the :) and
grep ^foo: /etc/group

checks if group foo exists.
EDIT: Fix in the code: quoting and splitting at space instead of colon to allow the appended colon in the grep pattern (otherwise, grep ^foo would have also said that group foo existed if there was a group foobar).


Q: Access object in Typescript/Javascript class ResistorColor {
  private colors: string[]

  public colorValues = {
    black: 0,
    brown: 1,
    red: 2,
    orange: 3,
    yellow: 4,
    green: 5,
    blue: 6,
    violet: 7,
    grey: 8,
    white: 9
  }

  constructor(colors: string[]) {

    if( colors.length > 2)
    {
      for( key in this.colorValues)
      {
        if (this.colorValues[key].indexOf(colors[0]) !== -1)
        {
          return key;
        }
      }
    }

    this.colors = colors

  }
}

Idea is to find whether the color that has been input by the user is present in the object colorValues or not.
I referred to this: Find a value in a JavaScript object
I am getting the error of cannot find name key. I am using a Typescript, online editor.
Please explain to me what am I doing wrong here.

A: Look at @Owl 's answer, it fixes the other problems in your code too.
In your loop the variable key is not defined. You'd have to write it like this:
for (const key in this.colorValues) {
  ...
}

Although I wouldn't use a for-in loop, since objects have their own prototype properties, which you would also receive in a for-in loop. A better solution would be this:
for (const key of Object.keys(this.colorValues) {
  ...
}

But since you don't need the keys and just use them to retreive the values in the colorValues object, you could also use this:
for (const color of Object.values(this.colorValues) {
  ...
}

A: The cannot find name key error is answered by @MrCodingB
A nicer way to write this:
class ResistorColor {
  private colors: string[]

  public colorValues = {
    black: 0,
    brown: 1,
    red: 2,
    orange: 3,
    yellow: 4,
    green: 5,
    blue: 6,
    violet: 7,
    grey: 8,
    white: 9
  }

  constructor(colors: string[]) {

    const colorValues = Object.keys(this.colorValues);
    // colorValues is ["black", "brown", "red", ...]

    const isValid = colors.every(c => colorValues.includes(c));
    // `every` is used to tests whether all elements in the array pass the test implemented by the provided function,
    // in this case, we check whether each value exists in `colorValues`

    if (isValid) {
      this.colors = colors
    } else {
      throw new Error("Invalid Color(s)");
    }
  }
}

const resistorColor = new ResistorColor(["black", "brown"]); // correct
console.log("resistorColor has correct color");

const resistorColor2 = new ResistorColor(["black", "brown", "gold"]); // throws error
console.log("resistorColor2 has correct color");

Typescript playground

It's also possible to print out the incorrect colors value by using .filter()
class ResistorColor {
  private colors: string[]

  public colorValues = {
    black: 0,
    brown: 1,
    red: 2,
    orange: 3,
    yellow: 4,
    green: 5,
    blue: 6,
    violet: 7,
    grey: 8,
    white: 9
  }

  constructor(colors: string[]) {

    const colorValues = Object.keys(this.colorValues);
    const invalidColors = colors.filter(c => !colorValues.includes(c));

    if (invalidColors.length === 0) {
      this.colors = colors
    } else {
      throw new Error(`Invalid Color -> ${invalidColors.join(", ")}`);
    }
  }
}

const resistorColor = new ResistorColor(["black", "brown"]); // correct
console.log("resistorColor has correct color");

const resistorColor2 = new ResistorColor(["black", "brown", "gold", "foo"]); // throws error "Invalid Color -> gold, foo"

Typescript playground

A: Some of the errors that you are trying to prevent at run-time can be avoided at compile-time with stricter types.  You can create a type that only allows specific string literal color names and you can also enforce a minimum length on the colors array using tuple types.
It looks like this.colorValues might just be an enum?
enum COLOR_VALUES {
    black = 0,
    brown = 1,
    red = 2,
    orange = 3,
    yellow = 4,
    green = 5,
    blue = 6,
    violet = 7,
    grey = 8,
    white = 9
}

type ColorNames = keyof typeof COLOR_VALUES;

class ResistorColor {

    // can have two or more colors
    constructor(private colors: [ColorNames, ColorNames, ...ColorNames[]]) {
    }
}

Now you can only call the constructor with valid arguments.
const a = new ResistorColor(["black", "blue"]); // ok
const b = new ResistorColor(["black", "blue", "red"]); // ok
const c = new ResistorColor(["black"]); // error: Source has 1 element(s) but target requires 2.
const d = new ResistorColor(["white", "cyan"]); // error: Type '"cyan"' is not assignable to type

Typescript Playground Link
If this.colorValues is an instance variable I would create the initial value outside of the class so that we can use typeof.
const initialValues = {
    black: 0,
    brown: 1,
    red: 2,
    orange: 3,
    yellow: 4,
    green: 5,
    blue: 6,
    violet: 7,
    grey: 8,
    white: 9
  }

type ColorNames = keyof typeof initialValues;

class ResistorColor {

    public colorValues = initialValues;

    // can have two or more colors
    constructor(private colors: [ColorNames, ColorNames, ...ColorNames[]]) {
    }
}

Typescript Playground Link


Q: iOS Keychain data after renewing distribution certificate My distribution certificate is about to expire & I am planning to submit a new update of app to AppStore. My question is what happens to my app's keychain data after updating the distribution certificate ?
I have read this questionwhich describes that
On iPhone, Keychain rights depend on the provisioning profile used to sign your application. Be sure to consistently use the same provisioning profile across different versions of your application.

But as I am not updating my provisioning profiles but distribution certificate , can anybody tell me what happens after updating distribution certificate ?
Any kind of information will be very helpful. Thanks in advance

A: Apple removed this sentence from the docs, because it's not true. Team ID and keychain-access-groups are the most important things that should match.
Check the github link below a code example of two apps reading and writing the same keychain item:
https://github.com/evgenyneu/keychain-swift/issues/103#issuecomment-491986324


Q: loosing pointers on vector of struct instances, with pointers in the struct Not sure if the title is right or not, but here it goes:
If I have for example the following structure:
struct strA{
    int x;

    strA(int x);
}

strA::strA(int x){
    this->x = x;
}

And another structure that uses a pointer to the previous one:
#include strA

struct strB{
    int y;
    strA *var_strA;

    strB(int y);
    ~strB(){
        delete var_strA;
    }
};

strB::strB(int y){
    this->y = y;
    var_strA = new strA(123);
}

Then if I do from the main aplication a vector of strB items:
std::vector<strB> vectB;

main(){
    strB *itemB = new strB(456);
    vectB.push_back(*itemB);
    delete itemB;

    //more code
}

If I try to access the var_strA on the item in the vector, is empty. And also, I get an error when by deleting the item on the vector, since the destructor tries to delete var_strA again.
Comming from Java... I'm really getting lost with the damn pointers.
thanks in advance

A: You need a copy constructor and a copy assignment operator on that pointer-holding type, i.e. follow the rule of three. Here's a great resource here on SO: What is The Rule of Three?


Q: performSelector unable to run while UITableView is dragged? I have a UITableViewController with its default UITableView. I begin slowly dragging the table with my finger to scroll, i.e. not flicking it with my finger. Every time the table moves on-screen the scrollViewDidScroll method of the controller is called; when some conditions I've specified are met, one of these calls to scrollViewDidScroll uses performSelector:withObject:afterDelay to schedule some action at a later time.
However, I'm finding that the action will not execute until I release my finger. For example, if I set the afterDelay parameter to 2 seconds, but hold my finger for 5 seconds, when I release my finger and the action executes it's 3 seconds too late. Is there any way to allow the action (which is to update the UI and so must run in the main thread) to execute while the finger is still against the screen?
Thanks!

A: This is because when a UIScrollView (UITableView's superclass) is scrolling, it changes its runloop in order to prioritize the scrollView over whatever the application was doing. This is happening to make sure scrolling is as smooth as it can be.
try using this version of delayed method:
- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay inModes:(NSArray *)modes;

for the modes, I'd suggest starting with an array that contains the following:
[[NSRunloop currentRunLoop] currentMode],
NSDefaultRunLoopMode


Q: Java get each digit from 2 strings and calculate it The task is asking me to insert 2 strings of a very huge number and sum them from right to left like the way we studied in primary school like:
23 + 28 =
(2 + 2 + <1> (this is the left 1 >>> keep reading ))(3 + 8 (give the left <1> from 11 sum with the two front numbers)) =
 51.
The algorithm is ok but when I try to do like (just default that the 2 number has the same length so I get lenA and not greater than 10 to make easier):
 int len = a.length();
 String result="";
 for(int i = len; i>0 ; i--) { //<- We only need it to loop how many times
      result = Integer.valueOf( a.charAt(len-1) ) + Integer.valueOf( b.charAt(len-1) ) + "" + result;//<<<because we sum them from right to left
      lenA--; lenB--;
 }

and that (<<<) line always give me the error.
This is just one of a many ways I tried if it's wrong and you have a solution, please just guide me, sometimes i think too much and forgot a lot of small details :))
So the question here is how can i change it from a digit of String to Integer, calculate it and print out String again. But after I read the .charAt() info it said: "Returns the char value at the specified index." so the question maybe confuse between the first question and Convert from a digit from String use charAt -> become Char then convert Char to Integer to calculate and finally convert back to String so that I can + with String result.
I tried a lot of way but still can't solve it.

A: int lena = a.length();
int lenb = b.length();
int inta[] = new int[lena];
int intb[] = new int[lenb];
int result[];
int carry = 0, maxLen = 0, tempResult;

if(lena >lenb)
   maxLen = lena + 1;
else
   maxLen = lenb + 1;

result = new int[maxLen];

for(int i = lena - 1; i>=0 ; i--) {
   inta[i] = Integer.valueOf( a.charAt(i) );
}

for(int i = lenb - 1; i>0 ; i--) {
   intb[i] = Integer.valueOf( b.charAt(i) );
}

for(int i = maxLen - 1; i >= 0; i--) {
   result[i] = 0;
}

for(int i = 1; i < maxLen - 1; i++) {
   tempResult = 0;
   if(lena > i)
       tempResult += inta[lena - i];
   if(lenb > i)
       tempResult += intb[lenb - i];
   result[maxSize - i] += tempResult % 10;
   result[maxSize - i - 1] = tempResult / 10;
}

String res = "";
for(int i = 0; i < maxLen; i++) {
   res += result[i];
}

System.out.println(res);

I think that would do what you want and will avoid most simple mistakes (couldn't try it, no acces to an IDE).
I actually separate the two string into their inside number and then add them into the result tab.
Then I put the result tab into a string that I print.


Q: Deserialize ISO 8601 date time string to C# DateTime I'm trying to use:
JsonConvert.DeserializeObject<DateTime>( "2009-02-15T00:00:00Z", new IsoDateTimeConverter() )

But it gives me a FormatException: Input string was not in a correct format.
What am I doing wrong?

A: If you're parsing a single value, the simplest approach is probably to just use DateTime.ParseExact:
DateTime value = DateTime.ParseExact(text, "o", null);

The "o" pattern is the round-trip pattern, which is designed to be ISO-8601:

The "O" or "o" standard format specifier corresponds to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string for DateTime values and to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz" custom format string for DateTimeOffset values.

I haven't specified a format provider, as it doesn't matter:

The pattern for this specifier reflects a defined standard (ISO 8601). Therefore, it is always the same regardless of the culture used or the format provider supplied.

If you need Json.NET to handle this transparently while deserializing other values, it may be a trickier proposition - others may know more.
Additionally, just as a plug, you may wish to consider using my Noda Time project, which supports ISO-8601 and integrates with JSON.NET - albeit not in a pre-packaged way just yet.


Q: jquery ajax return value and done function I found this little example on jquery documentation page. I always tried returning value from ajax function and I was always told that there is some problem of sync and async thing and I can't return value out of $.ajax function without making it async.
$.ajax({
  url: "test.html",
  context: document.body
}).done(function() {
  $(this).addClass("done");
});

In the example above, on what this done function is applied(whats being used as $(this) in example).
one more thing, as the ajax function can't set global variables, can't the be set in this done too? cant I return value out of done function either?

A:
what this done function is applied

$.ajax returns a jqXHR object (see first section after the configuration parameter description) wich implements the promise interface and allows you to add callbacks and get notified of changes of the Ajax call.

whats being used as $(this) in example

Inside the callbacks for $.ajax, this refers to the object context refers to in the configuration or the jqXHR instance if context was not set. In this case it refers to document.body:

context: This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax).

This and more is all explained in the documentation: http://api.jquery.com/jQuery.ajax/

as the ajax function can't set global variables

That is not correct, any function can set global variables. The problem with asynchronous functions is that you are likely accessing the variable before it was set.

can't the be set in this done too

See above

cant I return value out of done function either

You can return a value (as in putting a return statement inside the callback), but you cannot return it to your code, since jQuery is calling the callback internally and just ignoring the return value.


Q: Making Python Logging work async with Celery I have logging setup. In particular, I have SMTPHandler. I would like to have it happen async. I'd like to use celery to make that happen. Is that possible?
import logging
logger = logging.getLogger("logger")

mail_handler = STMPHandler(...)
mail_handler.setLevel(logging.ERROR)
...
logger.addHandler(mail_handler)


Q: Record Screen's Happenings(Audio+Video) i am new baby in WebRTC and want to implement system like video conferencing , live streaming or you can skype using WebRTC and NodeJS.
i am confused with one thing , as its our one of client's requirement , suppose on page whatever is happening it may be video conferencing say one moderator answering to many audiences one by one , so there should be one video created , which continuously recording all this stuff together and sending live stream to server to save in our database.
is this kind of stuff implementable or not?
any help please.

A: You can capture video through grabbing Jpeg images from a canvas element. You could also capture the entire page(if numerous videos in the same page) through grabbing the page itself through chrome.
For audio, recording remote audio with the Audio API is still an issue but locally grabbed audio is not an issue.

*

*RecordRTC and my Modified Version for recording streams either to file or through websockets respectively.

*Capture a page to a stream on how to record or screenShare an entire page of Chrome.

If you have multiple different videos not all in the same page but want to combine them all, I would suggest recording them as above and then combining and syncing them up server side(not in javascript but probably in C or C++).
If you MUST record remote audio, then I would suggest that you have those particular pages send their audio data over websockets themselves so that you can sync them up with their video and with the other sessions.