text:
Q: Alternative to hashed SSN as a key in MySQL I have a problem similar to the following:
A person begins working as a consultant for "Company A". Their HR person sets up an account for them. A record is created for the person in a "person" table and a "person-company" one.
The person is also working for "Company B" (which Company A may or may not know about). When Company B enters their info they should NOT create a record in "person" but SHOULD create one in "person-company".
The person is required to do training for the state, so if they are logged into either company's site when they do the training, we want the total hours to remain with the person.
I can set up a PK for the person table the joins them to each company, but I think I need something like a hash of the person's SSN with some extra "xyz" tacked on to be able to do a lookup. Company B would have the SSN for the person, which should be universal.
Questions:
1) Is there some other method to join that one of you think would work better?
2) If I do go with a hashed SSN approach, what's the best encryption to use for MySQL/PHP for one-way encryption?
I read elsewhere that a public/private key solution may be best, but since the person is not setting up their own account initially I'm not sure how this would work.
Thanks

A: PKI would be overly complicated for your use case, and could possibly increase the number of security holes in the system. Using hashed SSN's would be quick and fairly portable - I would recommend SHA-2. It is infact recommended as a part of the Federal Information Processing Standard.

A: For hashing to be secure, you really need a random salt in order to prevent rainbow attacks. However, a random salt would preclude the ability to use it as a lookup value.
Salting the hash with the person's last name would be better than nothing, and it would still allow you to perform the lookup.
PKI algorithms are generally weaker than a good symmetric algorithm using the same key length, so if you're thinking about using a reversible encryption algorithm, you wouldn't want to use PKI.
A randomly salted one way hashing algorithm would be ideal, and SHA1 and above should be fine, though PBKDF2 would be better.
SHA2 is supported in MySQL 5.5+, and both SHA1 and SHA2 return a hex encoded hash value, so it could be stored in an indexed fixed-length CHAR column.

A: I think this article may be very relevant to what you are doing. If indeed you wish to "anonymize" the SSNs for security reasons and legal liability, then simply hashing them is not enough.
Just hashing them would be a completely deterministic process, so to effectively "mask" individual SSNs, the process needs to be randomized. Otherwise you could simply brute force through all possible combinations of SSNs (which would be much less work required than trying to brute force the hash function) and look for a matching value.
To see why this holds take the most simplistic example that a SSN could just take on two values, 0 and 1. Regardless of the quality and strength of the hash function, in the end there will only be two possible outcomes and it's easy to see which is which.
It's the old game of why you shouldn't hash e.g. passwords directly without performing some preprocessing on them first. The underlying data just doesn't contain enough entropy and will therefore be an easy target for lookups in a precomputed table.
The minute your SSNs become private and confidential (they are not in every country, so forgive my stupid question in the comments :), the same best practices that are also used for password storage should also be applicable to your particular case, i.e. a slow adaptive hashing algorithm that compensates for the lack of initial entropy such as bcrypt, scrypt and PBKDF2 (which was already recommended by Marcus Adams).


text:
Q: grails getting lazzy initialization exception in transactional service I'm getting a typical hibernate Lazy initialization exception in my transactional service while accessing propert of an object of a SET.
org.hibernate.LazyInitializationException: could not initialize proxy - no Session

class ProductService {
  static transactional = true
  def xyz() {
    def products = Product.list()
    products.each { product ->
      def category = product.categories.asList().first()
      def title = category.title
    }
  }
}

I'm getting exception when accessing the title property of category

A: xyz is a Closure being invoked by Groovy as if it were a method, but it's not a method. So it's not proxied by Spring (it's just a field), and you get no transactional behavior. There's almost never a good reason to have a public closure in a Service class (inner utility closures are fine).
This should work:
void xyz() {
   for (product in Product.list()) {
       def category = product.categories.asList().first()
       def title = category.title
   }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Which is the preferred MVVM framework for Xamarin development? Which is the preferred MVVM framework for Xamarin cross platform development? Any suggestions from experience will be helpful.
thanks!

A: Traditional Xamarin.iOS / Xamarin.Android
There are many MVVM Frameworks available for Xamarin.iOS and Xamarin.Android development: MVVMCross, MvvmLight, PrismMVVM, ReactiveUI.
I've had the most success using ReactiveUI for MVVM and Splat for IoC.
The best feature about ReactiveUI is that it doesn't require any ViewModel Navigation. You may think that ViewModel-based Navigation is a good thing, but it can make your life much more difficult when implementing complex navigation patterns. iOS and Android have view-based navigation built-in, and I recommend leveraging those instead of trying to re-create the wheel by using ViewModel-based navigation.
Xamarin.Forms
You mentioned in the comments that you're not using Xamarin.Forms, but I wanted to include this in case another developer has a similar question for Xamarin.Forms.
Don't use an MVVM Framework with Xamarin.Forms.
Xamarin.Forms has a binding engine included. I've seen many developers over-complicate their Xamarin.Forms projects by implementing heavy frameworks like MVVMCross into Xamarin.Forms without receiving much benefit.
Xamarin.Forms doesn't include an IoC container, and you may want to add one to your project: TinyIoC, Autofac, Ninject, Splat.
I have had the most success using Splat.


text:
Q: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 35: invalid start byte I am new to Python, I am trying to read csv file using below script.
Past=pd.read_csv("C:/Users/Admin/Desktop/Python/Past.csv",encoding='utf-8')

But, getting error "UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 35: invalid start byte", Please help me to know issue here, I used encoding in script thought it will resolve error.

A: The following works very well for me:
encoding = 'latin1'

A: Its an old question but shows up while searching for solutions to this error. So I thought to answer for all who still stumble on this thread.
The encoding for the file can be checked before passing the correct value for the encoding argument.
To get the encoding, a simple option in Windows is to open the file in Notepad++ and look at the encoding. The correct value for the encoding argument can then be found in the python documentation.
Look at this question and the answers on stackoverflow for more details on different possibilities to get the file encoding.

A: Using the code bellow works for me:
with open(keeniz_dir + '/world_cities.csv',  'r', encoding='latin1') as input:

A: df = pd.read_csv( "/content/data.csv",encoding='latin1')

Just add ,encoding='latin1' and it will work

A: Try using :
pd.read_csv("Your filename", encoding="ISO-8859-1")

The code that I parsed from some website was converted in this encoding instead of default UTF-8 encoding which is standard.

A: Use this solution it will strip out (ignore) the characters and return the string without them. Only use this if your need is to strip them not convert them.
with open(path, encoding="utf8", errors='ignore') as f:

Using errors='ignore' You'll just lose some characters. but if your don't care about them as they seem to be extra characters originating from a the bad formatting and programming of the clients connecting to my socket server. Then its a easy direct solution. reference

A: Don't pass encoding option unless you are sure about file encoding. Default value encoding=None passes errors="replace" to open() function called. Characters with encoding errors will be substituted with replacements, you can then figure out correct encoding or just use the resulting Dataframe. If wrong encoding is provided pd will pass errors="strict" to open() and get ValueError if encoding is incorrect.

A: This happens because you chose the wrong encoding.
Since you are working on a Windows machine, just replacing
Past=pd.read_csv("C:/Users/.../Past.csv",encoding='utf-8')

with
Past=pd.read_csv("C:/Users/.../Past.csv",encoding='cp1252')

should solve the problem.


text:
Q: Booting barely working, Windows 8 can't sleep/restart/shutdown without crashing I'm getting some strange issues on a lenovo laptop, it goes like this

*

*It barely boots, I get the lenovo BIOS logo and then sometimes I see the win8 loading dot-circle but then sometimes don't and the only way to actually but into the OS is by going into the BIOS menu, do nothing and then reboot. Still takes a lot of time despite having a SSD

*When it boots it might freeze a bit after login into windows, but once inside it works normally and fast as always

*...but then if I put the computer to sleep it might do it well once but by the second time it just crashes. If instead I restart or shutdown it it crashes on the first go.

I already did a windows boot repair both automatic and through command line, fixed the bcd and every other run of the mill command, any ideas that don't involve a fresh reinstall from scratch?


text:
Q: jQuery tree view plugin for selecting multiple categories (checkboxes) I'm looking for a jQuery plugin that'll be used for selecting categories assigned to a product.  I've checked out the jsTree plugin, but it's overkill.  Would anyone recommend a simple, lightweight tree plugin or something similar?
Thanks!


text:
Q: Return value in DropDownMenu on selection? I'm new to Xcode and Swift. I am using this library: https://github.com/PhamBaTho/BTNavigationDropdownMenu to create DropDownMenu in my app. I followed the demo from Github and everything works fine. I am trying to get the selected value and assign it to a string outside didSelectItemAtIndexHandler function. This is my code:
 var menuView: BTNavigationDropdownMenu!

 var items = ["San Francisco", "New York", "LA", "Chicago"]

 menuView = BTNavigationDropdownMenu(navigationController: self.navigationController, containerView: self.navigationController!.view, title: BTTitle.index(0), items: items)

    menuView.didSelectItemAtIndexHandler = {(indexPath: Int) -> Void in

        self. myCity = items[indexPath]
        //print(myCity) // prints the correct city every time
    }

 self.navigationItem.titleView = menuView

I am trying to get the following outside menuView.didSelectItemAtIndexHandler :
 var test = String()
 test = myCity
 print(test)

Any help will be appreciated. Thanks in advance!
I am trying to pass the data from here to TopFiveViewController.
 menuView.didSelectItemAtIndexHandler = {(indexPath: Int) -> Void in

 let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
 let vc = storyboard.instantiateViewController(withIdentifier: "TopFiveViewController") as! TopFiveViewController
 vc.myCity = self!.items[indexPath]
 print(myCity) // prints the correct city every time but it doesn't pass the value to TopFiveViewController!

}

In the TopFiveViewController I have:
var myCity = String()

override func viewDidLoad() {
    super.viewDidLoad()

      if self.myCity == "San Francisco" {

        // load SF json file

    } else if myCity == "New York" {

        // load NY json file

      }

A: As you mentioned that everything is happening in your viewDidLoad() I think it's important to understand what is happening.
The view loads and test as well as myCity are set to nil.
When the user selects an item from the dropdown menu the code within menuView.didSelectItemAtIndexHandler will be called and myCity will now be set to the selected value although test will still be nil as the completion handler setting the value of myCity has no effect on test.
You should execute whatever code you want to execute when the value is selected within the completion handler (where self. myCity = items[indexPath] is located).


text:
Q: Getting more information from CvHoughCircles I am using the HoughCircles function of OpenCV.
Is there any way I can get more information about the results besides an ordered list of circle center and radius?
I'd like to get the score of each circle, and perhaps the hough space matrix itself
I am using the openCvdotnet C# wrapper, but I am not adverse to modifying the wrapper.
I tried implementing my own hough gradient circle transform, but the results are not as robust as the native openCV function.

A: Quite simple, no there isn't. I've needed something like this in the past and decided it was simpler to implement my own (based on one of the freely available matlab examples) than to modify the opencv code.


text:
Q: Problem parallel to Goldbach Conjecture Let, $\Bbb{P}$ denote the set of all odd prime numbers and $\Bbb{N}$ be the set of all natural numbers. Let, $2a,2b$ be two even numbers both greater than $4$.
Define, $A=\{(p,q)\in\Bbb{P}\times\Bbb{P}:p+q=2a\}$ and $B=\{(r,s)\in\Bbb{P}\times\Bbb{P}:r+s=2b\}$. Let, $X'=\{A,B\}$
Define, $n:X'\to \Bbb{N}$ by, $$n(Y)=\max_{(x,y)\in Y}\{x^2+y^2\},\forall Y\in X'=\{A,B\}$$
My claim is, $n(A)=n(B)\implies A=B$
I have no proof as well as no counterexample for my claim. If anyone has any idea about how to prove this or have seen any paper on this or it is very trivial to prove or has a counterexample for this claim please give.
Thanks in advance!
P.S.: I am "in danger of being blocked from asking any more".

A: I'm afraid the question is not well defined; or at least, not proven to be well defined. In your definition for the sets $A$ and $B$, you essentially say they are the sets of all pairs of odd primes which sum to $2a$ and $2b$, which are even numbers. The Goldbach Conjecture asserts that every even number ($>4$) can be expressed as the sum of two odd primes, and this unfortunately hasn't been proven. Hence, if the Goldbach Conjecture happens to be false, your sets $A$, $B$ become null sets, and so the question becomes ill-defined and doesn't make sense; indeed, asserting the well-definition of $A$, $B$ would be asserting Goldbach! (This is of course unless you're willing to define $\max(x^2+y^2)$ to mean something else in this case, in which case your conjecture comes down to asserting that there is exactly one even positive integer that can't be expressed as a sum of odd primes, an equally tough problem to prove.)


text:
Q: Javascript variable value doesn't change once after page loaded I initialize a property within the Controller's Constructor.
public MyController()
{
  SessionProvider.IntializeMethod = false;
}

I have an Action Method which reset the property again on a button click event.
public ActionResult Initialize(int Id)
{
  SessionProvider.IntializeMethod  = true;
  // remaining code
  return Json(Id, JsonRequestBehavior.AllowGet);
}

Following javascript code is in my view which is called when the button is clicked.
var MyHandler = {
  $("#btnInit").click(function (e) {
    $.ajax({
      url: "@Url.Action("Initialize", "My")",
      dataType: 'json',
      type: 'POST',
      data: {
        'Id': MyHandler.getItemId()
      },
      success: function (response) {
        var Id = response;
        var isInitilize = "@MyProject.Presentation.MVC.App_Start.SessionProvider.IntializeMethod ";
        // code
        window.open("@Url.Action("Index", "OtherPage", new {Initialize = "_initialize"}).replace('_initialize', isInitilize ), tabId);
      },
      error: function () {
        //
      }
    });
  });
}

My problem is when I click the button, value of property  changes in the Controller. But it doesn't change in my javascript code.Please see the screen capture of the developer tool.

does Anyone has a clue on this?

A: It should not change. because it is already written when View is loaded..
var isInitilize = "@MyProject.Presentation.MVC.App_Start.SessionProvider.IntializeMethod ";
This will be declared at rendering of view and it will not be changed.. If you want the updated value from your action then you should return that as JSON (as you are using jquery ajax for calling the Controller's Action).
As per your explanation, you should use something like :
public ActionResult Initialize(int Id)
{
  SessionProvider.IntializeMethod  = true;
  // remaining code
  return Json(new { Id = 1, Name = "Sachin" }, JsonRequestBehavior.AllowGet);   ////I changed here ////
  //return Json(Id, JsonRequestBehavior.AllowGet);
}

whereas you can get that in javascript like :
var MyHandler = {
  $("#btnInit").click(function (e) {
    $.ajax({
      url: "@Url.Action("Initialize", "My")",
      dataType: 'json',
      type: 'POST',
      data: {
        'Id': MyHandler.getItemId()
      },
      success: function (response) {
        var Id = response.Id;            ////I changed here ////
        var isInitilize = response.Name; ////I changed here ////

        // code
        window.open("@Url.Action("Index", "OtherPage", new {Initialize = "_initialize"}).replace('_initialize', isInitilize ), tabId);
      },
      error: function () {
        //
      }
    });
  });
}

If I were you then I should return the URL of action like
return Json(new { Id = 1, URL = "/controller/action/param" }).


text:
Q: Program to calculate binary number for an integer - need help reversing output string I'm writing a program to calculate the binary number from an integer input. I cannot figure out how to reverse the output code to show what the binary number would be. The program below works but does not output the bits in the right order.
For example, when I enter 156, the answer should be the reverse of 00111001, but I cannot get the program to output this backwards to show 10011100.

*

*This should be a program to calculate binary number from an integer.
It should prompt a user to enter an integer number = int(input("Enter number: ")) and calculate the binary number or give a warning if an incorrect number type was entered.
if number > 0:
  while number != 0:
    if number % 2 == 0:
        code = "0"
        new_number = number //2
        number = new_number
    else:
        code = "1"
        new_number = number //2
        number = new_number
    reverse_code = code[::-1]
    print(reverse_code, end='') else:
  print ("Invalid Input. System will now self-destruct.")

A: You are printing each element (1 or 0) into the loop. You should concatenate all the 1/0s and reverse at the end.
Pay attention when you program loops. You are trying to set a value which is built along iterations in a specific iteration. When your script calculates code value (for example 1), it reverses that number and jumps to the next iteration, repeating the process.
The solution would be to build an inverse string along all iterations, incrementally. The next code defines an empty string and concatenates 0 or 1 before the previous result.
Example:
# Initialize reverse_code variable
reverse_code = ""

while number != 0:
    if number % 2 == 0:
        code = "0"
        new_number = number //2
        number = new_number
    else:
        code = "1"
        new_number = number //2
        number = new_number
    reverse_code = code + reverse_code
print(reverse_code)

If number = 10:

1010

Explanation
When while loop starts iterating, it divides by 2 the number and we want to reverse the result of the division to obtain binary code. Instead of calculate the result we can create the result in calculation time. For this we define reverse_code as an empty string. In each iteration we will put the new item (1 or 0) before the string, obtaining the inverse string.
reverse_code values in iterations when number=10:
Iteration 0:
code = 0
reverse_code = code+ reverse_code = "0" + "" = "0"
Iteration 1:
code = 1
reverse_code = code+ reverse_code = "1" + "0" = "10"
....
Iteration N:
code = 1
reverse_code = code+ reverse_code = "1" + "010" = "1010"
Another question to comment is your code optimization. Watching your code, if the else-if you have new_number and number variables assignation which is not affected by the previous variables code. You can extract common factor and simplify the code. The code should be as follows:
# Initialize reverse_code variable
reverse_code = ""

while number != 0:

    # Calculate the `code` value
    if number % 2 == 0:
        code = "0"
    else:
        code = "1"

    # Putting this here simplifies duplicate instructions
    new_number = number //2
    number = new_number

    # Putting 0 or 1 (code) before semi-built string (reverse_code)
    reverse_code = code + reverse_code

print(reverse_code)


text:
Q: Getting an error message from a sql server driver in my symfony project I have tried to install the ODBC driver 18 for SQL Server in my symfony project. I am getting the following error messages. I wanted to ask if anyone could knows the solution for these.

An exception occurred in the driver: SQLSTATE[08001]: [Microsoft][ODBC
Driver 18 for SQL Server]SSL Provider: [error:16000069:STORE
routines::unregistered scheme:scheme=file][error:80000002:system
library::No such file or direc     tory:calling
stat(/usr/local/etc/openssl@3/certs)][error:16000069:STORE
routines::unregistered scheme:scheme=file]

Environment details:
symfony version: 5.4.16
php8.1
Homebrew 3.6.16
apache 2.4.54

A: @AlwaysLearning's answer did help me.From the article linked, I checked the openssl@3 folder and I did see there was a cert.pem file. I then created a certs directory and copied the cert.pem file into that directory. That got of rid of my error message.

I did encounter an additional issue where I needed to add TrustServerCertificate parameter to the end of my connection string that is used to connect to the SQL server.
;TrustServerCertificate=1


text:
Q: How to have two alarms start two services? I am trying to have two alarms start their own separate services. They seem to be interfering with each other though, because only one of them work at a time. Is there something I should change in my code? Or is it not possible to do this?
public void setAlarm(){
    AlarmManager alarmMgr1 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(this, DrawOverAppsService.class);
    Float alpha2 = alpha.getProgress()/100f;
    intent.putExtra("alpha", alpha2);

    PendingIntent alarmIntent1 = PendingIntent.getService(MainActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    if(start.isChecked()) {
        alarmMgr1.cancel(alarmIntent1);
        java.util.Calendar calendar = java.util.Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(java.util.Calendar.HOUR_OF_DAY, 19);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        alarmMgr1.setRepeating(AlarmManager.RTC_WAKEUP,
                calendar.getTimeInMillis(),
                AlarmManager.INTERVAL_DAY, alarmIntent1);
        Log.d("a","b");
    }
    if(start.isChecked() == false) {
        alarmMgr1.cancel(alarmIntent1);
    }
}
public void stopAlarm(){
    AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent intent5 = new Intent(this, stopOverlay.class);
    PendingIntent alarmIntent = PendingIntent.getService(MainActivity.this, 2, intent5, 0);
    if(stop.isChecked()) {
        alarmMgr.cancel(alarmIntent);
        java.util.Calendar calendar = java.util.Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(java.util.Calendar.HOUR_OF_DAY, 5);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,
                calendar.getTimeInMillis(),
                AlarmManager.INTERVAL_DAY, alarmIntent);
    }
    if(stop.isChecked() == false) {
        alarmMgr.cancel(alarmIntent);
    }
}

A: This code will schedule two alarms to start two separate services at different times.
The alarms are set for 60 and 120 seconds from the time the MainActivity's onCreate method completes. (Note: the alarm will not necessarily fire exactly 60 and 120 seconds later because of AlarmManager's inexact scheduling. Sometimes it takes a surprising amount of patience to see the alarms go off.)
You can see that the two service's onStart commands are being executed by watching the app's log output.
MainActivity.java
public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

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

        setAlarm(Service1.class, 60);
        setAlarm(Service2.class, 120);

    }

    public void setAlarm(Class serviceClass, int delay){
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, serviceClass);
        PendingIntent alarmIntent = PendingIntent.getService(MainActivity.this,
                0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager.cancel(alarmIntent);
        java.util.Calendar calendar = java.util.Calendar.getInstance();
        calendar.add(Calendar.SECOND, delay);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                calendar.getTimeInMillis(),
                AlarmManager.INTERVAL_DAY, alarmIntent);

        Log.d(TAG,"alarm set:" + serviceClass.getSimpleName());
    }
}

Service1.java
public class Service1 extends Service {

    private static final String TAG = "service1";

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.v(TAG, "service started");
        return super.onStartCommand(intent, flags, startId);
    }

}

Service2.java
public class Service2 extends Service {

    private static final String TAG = "service2";

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.v(TAG, "service started");
        return super.onStartCommand(intent, flags, startId);
    }

}


text:
Q: Shouldn't particles lose energy after collisions? I read that particles gain energy after collisions i.e they hit a wall, but bounce back faster than before. According to my common sense, shouldn't the particle lose energy, as hitting the wall would consume its energy.
How does it gain energy from collisions?
And how do they constantly bounce around without running out of energy?
Sorry if the answer is really obvious, but this question has bugged me for a long time. I could not find a good answer on the internet. Could anyone explain it simply please?

A: Unless the wall you are talking about is moving, the particle will never gain energy. A collision can either be elastic or inelastic, but never super-elastic (where the total kinetic energy increases).
Of course if a wall is moving toward the colliding particle, momentum will be transferred to it from the wall thereby increasing its kinetic energy. As Feynman specifically stated in the text you referred to in the comments,
"What happens when an atom hits the moving piston? Evidently it picks up speed from the collision. You can try it by bouncing a ping-pong ball from a forward-moving paddle, for example,
and you will find that it comes off with more speed than that with
which it struck."
I think that is where your misinterpretation arises.
The total energy after a collision will never increase, and in fact, the total energy of any (isolated) system remains the same. This is a fundamental property of nature called conservation of energy. In the case of inelastic collisions, kinetic energy is usually lost to friction, sound, heat etc.

A: I am quoting the excerpt from Six Easy Pieces that OP is presumably referring to in the comments.

Suppose that the piston moves [inward] so that the atoms are slowly compressed into a smaller space. What happens when an atom hits the moving piston? Evidently[,] it picks up speed from the collision. You can try it by bouncing a ping-pong ball from a forward-moving paddle, for example,
and you will find that it comes off with more speed than that with
which it struck. (Special example: if an atom happens to be standing still and the piston hits it, it will certainly move.) -- Richard Feynman ("Six Easy Pieces". Chapter $1$, Atoms in Motion. Page $8$.)

In the context, it is self-explanatory as to why Feynman is saying what he is saying. The particles gain energy after colliding with the wall because the wall is moving (against the pressure created by the collisions of the particles of the gas against it) and the mechanical energy that is being used to drive the wall is converted into the (microscopic) kinetic energy of the particles.

A: If you throw a ball against a stationary wall, you are right. Some of the kinetic energy of the ball will be converted to heat. The ball will bounce back with less energy.
An ideal ball bouncing off an ideal wall can have no loss. In that case the ball bounces back with the same energy.
But think of a ping pong ball bouncing off a paddle, or a golf ball bouncing off a club. If the "wall" is moving, the ball can gain energy. The "wall" will lose some.


text:
Q: Messed Up Layout in Deployed Qt Application on Windows 10 When I launch my deployed application from the .exe file the layout is messed up. When I launch the app from Qt Creator, the layout is fine.
Here are the details about how I deployed my app. I am using Qt 5.5 and MinGW 32 bit 4.9.2. I am running Windows 10.
First in Qt Creator I built for release.
Next, I opened the Qt 5.5 for Desktop (MinGW 4.9.2 32 bit) console.
I navigated to my project folder and ran
windeployqt.exe --release ./APPNAME.exe

It copied all the necessary .dll and created some folders as expected.
Now when I run the app, it seems to work just fine. But the layouts are all wrong. Again, when launching the app from Qt Creator it looks great! Proper spacing and sizing of my widgets. When I launch the .exe every thing is smooshed, the ratios of my sliders are all wrong, and some text is hidden because of crowding.
What could cause this bad layout? Am I missing some dependency somehow?

A: I figured out my own question. The issue was not my build or my layout but that many sizePolicy parameters don't seem to take effect when launching the app from QtCreator. Not 100% sure on the explanation but I think that when launching the .exe the OS is managing interpreting some of those size policy parameters and it does it differently (perhaps more strictly it appears) than QtCreator does. (To be clear I'm not talking about how the app looks in the Design tab. I'm actually talking about launching the app from within QtCreator)
So to fix the appearance of the app I have to play around with the size policies and parameters, build, and then launch the app from the executable.


text:
Q: Recurring invoice generation i have a question regarding softlayer billing. Wondering how many recurring invoices are generated in a given month for a softlayer customer account. I was under the impression that there can be one recurring invoice generated per month for a customer account. But for our account 976633 i see two recurring invoices generated for the month of Feb 2017 - one on Feb 15th and one on Feb 16th. The anniversary day for the account is 15th of every month.
Appreciate your help.
thanks
reddy

A: The recurring invoices are generated once each month in your aniversay, in this case your aniversary is gonna be each 16th of each month and a new recurring invoice should be generated. also you can see the date of your next recurring invoice in the Softlayer's control portal, you just need to go to Account->Biling->Invoices

Regards

A: Some times there exists two RECURRING invoices, you need to look into the items which belongs for each one.
There exists some cases in which these items got created too late for batch to pick them up, so the batch will still pick up those billing items just the next day. If you need further assistance, got doubts with these items or the RECURRING invoices, submit a ticket please


text:
Q: In Rails, how can I make ActiveRecord associations for two models that reference each other in different ways? I'm using Rails 3.1. I have a model Tree and a model TreeNode, and I've set up a has_many/belongs_to association between Tree and TreeNodes.
# The initial models and associations.

class Tree < ActiveRecord::Base
  has_many :tree_nodes
end

class TreeNode < ActiveRecord::Base
  belongs_to :tree
end

I want to add the concept of a root node, which isn't necessarily the node that was created first. I can't implicitly determine the root node through created_date, primary key (id), or an order (since there isn't a concept of order with nodes). I'm trying to wrap my head around how to set up this association in Rails.
I started off by adding a root_node column with a foreign key on the Tree table, but my Active Record association would then be Tree belongs_to Node and Node has_one Tree. This is because the class that has the foreign key should have the "belongs_to" association, and the other class should have the "has_one" association. This doesn't sound right to me.
# This code didn't work.

class Tree < ActiveRecord::Base
  has_many :script_steps
  belongs_to :root_tree_node, :class => 'TreeNode'
end

class TreeNode < ActiveRecord::Base
  belongs_to :tree
  has_one :tree
end

I also tried creating a join table with has_one :through, but the associations wouldn't work either.
# This code didn't work.

class Tree < ActiveRecord::Base
  has_many :script_steps
  has_one :root_node, :class => 'TreeNode', :through => :root_tree_node
end

class TreeNode < ActiveRecord::Base
  belongs_to :tree
  has_one :root_tree_node
end

# This represents the join table.
class RootTreeNode < ActiveRecord::Base
  belongs_to :tree
  belongs_to :tree_node
end

What's the best way to model this relationship generally speaking, and what's the best way to set up the associations in ActiveRecord? At the end of the day, I want to be able to do something like this.
tree = Tree.create
some_node = tree.tree_nodes.create
another_node = tree.tree_nodes.create

tree.root_node = another_node
tree.save

A: Hmm... If you trying to get normal tree structure like for example category tree one way to do this in rails is this:
def Category < ActiveRecord::Base
  belongs_to :parent, :class_name => "Category", :foreign_key => :parent_id
end

This means that each row has reference to its parent.
Root node is the one with
parent_id == nil

Leaf node is when it's id is never used as parent_id. For more information check out acts_as_tree plugin (not sure if it works with rails 3).
Other option that you can find more usefull is nested_set (read more here)


text:
Q: Combine two list of tuples depending on name I have two lists of tuples:
a=[(name_2,array_2),(name_7,array_7),...,(name_n,array_n)]
b=[(name_3,arr_3),(name_12,arr_12),...,(name_n,arr_n)]

I want to combine them depending on their name which is the first value of each tuple in each set. The lists are not sorted by name. The result shall look like:
combined=[(name_1,array_1,arr_1),(name_2,array_2,arr_2),...,(name_n,array_n,arr_n)]

Is there any more effective solution than iterating with two pointers?

A: sorted_a = sorted(a, key=lambda x: x[0])
sorted_b = sorted(b, key=lambda x: x[0])

combined = [(sorted_a[idx][0], sorted_a[idx][1], sorted_b[idx][1]) for idx in range(len(a))]

A: I assume the two lists have the same number of elements and the names are in the same order (by the way it looks from your example). In that case
[(x[0], x[1], y[1]) for x, y in zip(a, b)]

A: Since you're saying they are pairs, most of the answers here are perfectly fine you just need to sort on the first item in the tuple before joining them together.
[(x[0], x[1], y[1]) for x, y in zip(sorted(a, key=lambda x: x[0]),
                                    sorted(b, key=lambda x: x[0]))]

A: A solution to avoid sorting is to pass through dictionaries:
names = [x[0] for x in a]
ad = dict(a)
bd = dict(b)
combined = list({k: [ad[k], bd[k]] for k in names}.items())

On my machine, with vectors a and b of size 1000, this takes 384 us against 667 us when sorting the two arrays. NB: The final combined list is not sorted.

A: With pandas
list(pd.concat([pd.DataFrame(a).set_index(0) for x in (a , b)],axis=1).reset_index().itertuples(index=False,name=None))
[('name_1', 'array_1', 'array_1'), ('name_2', 'array_2', 'array_2')]


text:
Q: Unable to get current location with google map I'm using google map in a project, where I want to get my current location which is not working correctly,
MyActivity.java code:
 LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        boolean enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (enabled) {
            Criteria criteria = new Criteria();
            String bestProvider = locationManager.getBestProvider(criteria, true);
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            Location location = locationManager.getLastKnownLocation(bestProvider);
            if (location != null) {
                lat = location.getLatitude();
                lng = location.getLongitude();
                return;
            }
        }

but it returns null every time, first i want know what's the problem and what's the best way to get my current location?
AndroidManifest.xml code
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

  <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
  <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />

A: Use this Google Map API v2 Method
private void getCurrentLocation() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            mMap.setMyLocationEnabled(true);
            // Check if we were successful in obtaining the map.
            if (mMap != null) {

             mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {

           @Override
           public void onMyLocationChange(Location arg0) {
            // TODO Auto-generated method stub

             mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("It's Me!"));
           }
          });

            }
        }
    }

A: Well, this is how I did it in my app:
First declare:
private Location mylocation;
private GoogleApiClient googleApiClient;
private final static int REQUEST_CHECK_SETTINGS_GPS = 0x1;
private final static int REQUEST_ID_MULTIPLE_PERMISSIONS = 0x2;

public double latitude, longitude;

Then, in your code write:
implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener

Finally,
if (googleApiClient.isConnected()) {
                LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
        LocationRequest locationRequest = new LocationRequest();
        locationRequest.setInterval(3000);
        locationRequest.setFastestInterval(3000);
                locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                        .addLocationRequest(locationRequest);
         builder.setAlwaysShow(true);
         LocationServices.FusedLocationApi
                        .requestLocationUpdates(googleApiClient, locationRequest, this);
         PendingResult<LocationSettingsResult> result =
                        LocationServices.SettingsApi
                                .checkLocationSettings(googleApiClient, builder.build());
         result.setResultCallback(new ResultCallback<LocationSettingsResult>() {

                    @Override
                    public void onResult(LocationSettingsResult result) {
                        final Status status = result.getStatus();
                        switch (status.getStatusCode()) {
                            case LocationSettingsStatusCodes.SUCCESS:
                                    mylocation = LocationServices.FusedLocationApi
                                            .getLastLocation(googleApiClient);
                                    latitude = mylocation.getLatitude();
                                    longitude = mylocation.getlongitude();
                                }
                                break;
                    }
             }
       }

Try This, Hope it works.
                 }

A: Here you can found the documentation about that how to use Location Data from Google Maps -> https://developers.google.com/maps/documentation/android-sdk/location
And here you can found how to get last known location (it can be null if your device use it for the first time and for now it hasn't been saved) -> https://developer.android.com/training/location/retrieve-current#java

A: private static final int REQUEST_LOCATION = 1;
private LocationManager locationManager;
//...

// In your onCreate
locationManager = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);

//...

void getLocation() {
    if (ActivityCompat.checkSelfPermission(this,
            android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this,
                    android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(this,
                new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION,
                        android.Manifest.permission.ACCESS_FINE_LOCATION},
                REQUEST_LOCATION);

    } else {

        Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

        if (location != null) {
            double lati = location.getLatitude();
            double longi = location.getLongitude();

            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            try {

             //You can retrieve any address you want like this...
                List<Address> addresses = geocoder.getFromLocation(lati, longi, 1);
                String address = addresses.get(0).getAdminArea() + ", " + addresses.get(0)
                        .getCountryName();

                location_text.setText(address);
                System.out.println(address);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

//Create the location request and set the parameters
//To store parameters for requests to the fused location provider, create a LocationRequest.
// The parameters determine the level of accuracy for location requests.
//Create the location request and set the parameters
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    switch (requestCode) {
        case REQUEST_LOCATION:
            getLocation();
            break;
    }
}


text:
Q: Performing ajax Checks Before Form Sumbit via Javascript I have a simple form which is used to sign up a new user . I want to prevent users from submitting the same email id again . So before the form gets submitted , I want to do an Ajax check if the email id exists or not . If the email id exists , I alert the user . If it doesnt , I let the form be submitted .
$("#sign_in_form").submit(function(event){

event.preventDefault();
$.post("http://xyz.com/check_if_user_exists", {
        email : $("#contact_person_email").val()
    }).done(function(data) {

var res = parseInt(data);
if(res==1){

//Email Exists
alert("Email exists . Please use different email " );
return false; //----------------------------1)

}else{
  //Email doesnt exist
return true;   //--------------------------- 2)
}

});

//end of function

});

The problem with this code is due to async nature of Javascript , the function ends even before the result is returned from the ajax post statement . Hence the  return false or return true statement at 1) and 2) have no effect . Whats the correct way to handle this ?

A: Submit form using js native event if check is valid:
$("#sign_in_form").submit(function (event) {

    event.preventDefault();
    $.post("http://xyz.com/check_if_user_exists", {
        email: $("#contact_person_email").val()
    }).done(function (data) {

        var res = parseInt(data);
        if (res == 1) {

            //Email Exists
            alert("Email exists . Please use different email ");

        } else {
            document.getElementById('sign_in_form').submit();
        }

    });

    //end of function

});


text:
Q: nginx 403 when serving static files + reverse proxy I'm trying to serve a node app through nginx, but first attempt to serve static files that may be in a /public folder. I've got that much working -- but when accessing domain.tld/ or the index of static folders, I get a 403; directory index of "/var/www/domain.tld/" is forbidden. All the permissions seem to correct, so I'm rather confused.
This is my server block;
server {
    server_name domain.tld;

    location / {
        root /var/www/domain.tld/public;
        try_files $uri $uri/ @proxy;
        access_log off;
    }

    location @proxy {
        proxy_pass http://127.0.0.1:3000;
    }
 }

Accessing any random page (including assumed sub-directories) properly proxies to the node app. In the case of the root / and root of any existing static directory, however, 403.
Any ideas?

A: That's because the directory exists, and therefore the try_files check
try_files $uri $uri/ @proxy;

succeeds. But there is no directory index file (typically index.html, see index), and autoindex is not turned on either (see autoindex).
Depending on what you want to happen, consider the following options:

*

*Leave it as is (and may be tune which index files are used).

*Always pass directories to a backend. Remove $uri/ from try_files to do it, i.e.:
location /
    root /var/www/domain.tld/public;
    try_files $uri @proxy;
}

*Check for a particular index file via try_files (and the request will go to a backend if it's not found):
location /
    root /var/www/domain.tld/public;
    try_files $uri $uri/index.html @proxy;
}

*Enable autoindex:
location /
    root /var/www/domain.tld/public;
    try_files $uri $uri/ @proxy;
    autoindex on;
}


text:
Q: Identify day of the week and time constrain and loop through the range I'm trying to loop through a specific range to identify if the date + time (each cell format is dd/mm/yyyy HH:mm:ss) equals a specific day of the week and is between specific time.
Each cell has a different date and time, so I guess Time = each cell in D looped one by one?
Sub looper()

    Dim Time As Date, cel As Range
    Time = ThisWorkbook.Sheets("Test1").Range("D1")

    For Each cel In Range("D1:D26")
        If IsEmpty(cel.Value) Then Exit For

        If Weekday(ThisWorkbook.Sheets("Test1").Range("D1")) = 5 And _
          Time < TimeValue("17:59:59") And _
          Time > TimeValue("06:00:00") _
          Then cel.Offset(0, 1).Value = "yes"

    Next

End Sub

A: If I understand the problem correctly, it can be implemented as follows:
Option Explicit

Sub looper()
    Dim cel As Range

    Dim Time As Date, minTime As Date, maxTime As Date
    minTime = TimeSerial(6, 0, 0)
    maxTime = TimeSerial(17, 59, 59)

    With ThisWorkbook.Sheets("Test1")
        For Each cel In Range("D1:D26")
            If IsEmpty(cel) Then Exit For
            Time = TimeValue(cel)   'extract time
            If Weekday(cel) = 5 And Time > minTime And Time < maxTime Then
                cel.Offset(0, 1) = "yes"
            End If
        Next
    End With
End Sub

A: try this, hope it helps :)
Sub looper()
Dim Time As Date, cel As Range

For Each cel In Range("D1:D26")
    Time = cel.Value
    If Not IsEmpty(Time) Then
        If Weekday(Time) = 5 And TimeValue(Time) < TimeValue("17:59:59") And TimeValue(Time) > TimeValue("06:00:00") _
        Then cel.Offset(0, 1).Value = "yes"
    End If

Next

End Sub


text:
Q: Changing width/height moves rotated element When changing the width/height of a rotated elements, the element moves!
Here's an example
JSFiddle
When I change the width for example, the object loses its original position, this is effecting jQueryUI Resizable and making it unusable.
CSS:
.test{
    position: absolute;
    top: 200px;
    left; 200px;

    width: 400px;
    height: 200px;
    background: red;

    transform: rotate(-90deg);
}

JSFiddle
Is there a library or a function that corrects this issue by reversing this effect.
Edit:
I made a jQuery function that corrects the top-left position upon resizing a rotated element, added as answer.
Also this is a patch for jqueryui resizable

A: This jQuery function will change the size of the element and make necessary correction to preserve the top-left corner position
JSFiddle
/**
* Resizes rotated set of elements and preserves top-left corner position
* @param {Number} new_width
* @param {Number} new_height
* @param {Number} angle in degrees
* @returns {object} the current jQuery set
*/
$.fn.rotSize = function(new_width, new_height, angle){

    //Convert angle from degrees to radians
    var angle = angle * Math.PI / 180

    $(this).each(function(i, elem){
        var $elem = $(elem);
        //initial CSS position.
        var pos = {left: parseInt($elem.css('left')), top: parseInt($elem.css('top'))};
        var init_w = $elem.width();
        var init_h = $elem.height();
        //Get position after rotation with original size
        var x = -init_w/2;
        var y = init_h/2;
        var new_x = y * Math.sin(angle) + x * Math.cos(angle);
        var new_y = y * Math.cos(angle) - x * Math.sin(angle);
        var diff1 = {left: new_x - x, top: new_y - y};

        //Get position after rotation with new size
        var x = -new_width/2;
        var y = new_height/2;
        var new_x = y * Math.sin(angle) + x * Math.cos(angle);
        var new_y = y * Math.cos(angle) - x * Math.sin(angle);
        var diff2 = {left: new_x - x, top: new_y - y};

        //Get the difference between the two positions
        var offset = {left: diff2.left - diff1.left, top: diff2.top - diff1.top};
        //Calculate the correction
        var new_pos = {left: pos.left - offset.left, top: pos.top + offset.top};

        //Apply
        $elem.css(new_pos);
        $elem.css({width: new_width, height: new_height});
    });
}

Another useful function:
/**
* Calculate the size correction for resized rotated element
* @param {Number} init_w
* @param {Number} init_h
* @param {Number} delta_w
* @param {Number} delta_h
* @param {Number} angle in degrees
* @returns {object} correction css object {left, top}
*/
$.getCorrection = function(init_w, init_h, delta_w, delta_h, angle){
    //Convert angle from degrees to radians
    var angle = angle * Math.PI / 180

    //Get position after rotation with original size
    var x = -init_w/2;
    var y = init_h/2;
    var new_x = y * Math.sin(angle) + x * Math.cos(angle);
    var new_y = y * Math.cos(angle) - x * Math.sin(angle);
    var diff1 = {left: new_x - x, top: new_y - y};

    var new_width = init_w + delta_w;
    var new_height = init_h + delta_h;

    //Get position after rotation with new size
    var x = -new_width/2;
    var y = new_height/2;
    var new_x = y * Math.sin(angle) + x * Math.cos(angle);
    var new_y = y * Math.cos(angle) - x * Math.sin(angle);
    var diff2 = {left: new_x - x, top: new_y - y};

    //Get the difference between the two positions
    var offset = {left: diff2.left - diff1.left, top: diff2.top - diff1.top};
    return offset;
}

A: transform-origin is set to centre by default, and when you change the width/height of the element, the original centre moves, thus moving your object.
see this updated fiddle, with a fix for changing width http://jsfiddle.net/ww8k4hy4/6/
EDIT
Set both values of transform-origin to be half of width -- see this: http://jsfiddle.net/ww8k4hy4/10/
(figuring this out proved to be very helpful for me too, so thanks :) )


text:
Q: JUSTIFY A TEXTBOX IN SSRS REPORT BUILDER V. 2016 I'm trying to justify a textbox to insert on footer's page.
For the moment i've tried these technics:

*

*Create the footer as an image.

*Create the placeholder and interpreter the textbox with the HTML's tags

*:( recreate the spaces manually (very bad idea).

For each of these tips, nothing it works, have you ideas?


text:
Q: Axios not sending as post method I'm trying to get a simple post form setup in React with Axios, but it doesn't seem to be sending as a post request for some reason, so Django keeps throwing a 405 error.
This is the react code that calls axios and handles the form:
handleSubmit(e) {
    console.log('Form state: ', this.state);
    e.preventDefault();

    const username = this.state.username;
    const password = this.state.password;
    const formData = {
        username: username,
        password: password,
    }
    // Django backend currently running on localhost:8000
    axios('http://localhost:8000/login', {
        method: 'POST',
        data: formData,
    }).then(res=> {
            console.log('res', res);
            console.log('res.data', res.data);
        }
    )

}

This is the django login view.  I have it required to be post, so it automatically throws the 405 error when not using post method.
Django:
import json, re
from django.shortcuts import get_object_or_404, redirect
from django.http import HttpResponse, HttpResponseForbidden, HttpResponseNotFound
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from django.contrib.auth import login as auth_user
from django.contrib.auth import logout as logout_user
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt

from api.utils import render

def home(request):
    return render(request, 'api/home.html')

@csrf_exempt
@require_http_methods(['POST'])
def login(request):
    if request.method == "POST":
        username = request.POST['username']
        password = request.POST['password']

        if re.compile('.+@.+\..+').match(username):
            user = authenticate(email=username, password=password)
        else:
            user = authenticate(username=username, password=password)

        if user is not None:
            auth_user(request, user)
            return HttpResponse(json.dumps(True), content_type="application/json")
        else:
            response = {
                'success': False,
                'error': True,
                'message': "The username/email or password was incorrect.",
            }
            return HttpResponseForbidden(json.dumps(response))

    else:
        return HttpResponseForbidden("Post method required.")

A: The OPTIONS request is a pre-flight request. See this issue for more details.
Your view is using request.POST, so expects the data to use application/x-www-form-urlencoded instead of application/json. If you configure axios to use application/x-www-form-urlencoded then you won't have to configure CORS.
If you do use application/json then you'll have to configure CORS.

A: I think the problem is related to Django configuration of your app. Axios related code seems correct. Sample code of allowed https verbs.
class TheView(View):

self.allowed_methods = ['get', 'post', 'put', 'delete', 'options']
def options(self, request, id):
    response = HttpResponse()
    response['allow'] = ','.join([self.allowed_methods])
    return response

Can you check your server configuration once.


text:
Q: Inno setup: hide files How can I hide the files while installing my application using an Inno Setup made package? It can be hidden by
"[files]
attribs : hidden"
but it again can be seen by activating the windows option
"Show hidden file"
How can I hide it permanently to avoid user tampering with EXE file?

A: Can't be done. If you nee a detailed explanation why, see this blog post:
http://blogs.msdn.com/oldnewthing/archive/2005/04/19/409620.aspx

A: If you are really ambitious and you really have an issue with people "tampering" with your exe files you can perhaps encrypt your exe files, play with the PE (portable executable) and loader, or other stuff.
I doubt any of that is worth it.  EXEs have been distributed by many software companies over the years.  Your application is probably not that special to warrant anything out of the ordinary.
Set those flags, and concentrate on more important issues.


text:
Q: how can I show time like whatsApp chat I build chat application using firestore as backend. Now I want when some user send a message there should be a time of that message.
there is some error ie.

react-dom.development.js:14887 Uncaught Error: Objects are not valid as a React child (found: object with keys {seconds, nanoseconds}). If you meant to render a collection of children, use an array instead. at throwOnInvalidObjectType (react-dom.development.js:14887:1)

react_devtools_backend.js:4012 The above error occurred in the  component:

I wrote this code to send data on firebase
messages: arrayUnion({
  id: uuid(),
  text,
  img: downloadURL,
  senderId: currentUser.uid,
  date: Timestamp.now(),
  // time: Date().get
});

and when a fetch data from firebase

    {message.text}
    {message.date && {message.date}}

  {message.img && }

;

I want to show message time with message.
Note: I map through messages like :
messages.map(message => {})

A: Note: Edited
In your original code, you have:
message.date && {message.date}

But according to the error message, message.date is a JavaScript object which React does not know how to display. If your message object comes directly from Firestore, message.date would be a JavaScript object that looks something like this:
{
  nanoseconds: <something>,
  // some other Timestamp properties
}

React does not know how to display this. Thus, try turning message.date into a string and then displaying it. This could involve many methods depending on how you want to implement it and format the final string. Many ways are provided in  How do I convert a Firestore date/Timestamp to a JS Date()? when accessing the time.


text:
Q: Вывод слова по цифре Python Напишите программу, которая проходит по всем числам от 1 до 100 и для каждого числа выводит это число, но если оно делится на три — выводит вместо числа «тыры», если на пять — «пыры», а если и на три и на пять — «тыры-пыры».
Я сделал так только с цифрой 3, и не могу понять как делать дальше.
array = list(range(1,101))
array2 = []

for i in array:
    if i%3 == 0:
        i = "пыры"
        array2.append(i)
    else:
        continue

print(array2)

A: Вариант решения
arr = []
for i in range(1,101):
    if i%15 == 0:
        arr.append("тыры-пыры")
    elif i%3 == 0:
        arr.append("тыры")
    elif i%5 == 0:
        arr.append("пыры")
    else:
        arr.append(i)
print(arr)

A: немного изврата:
arr = [{0: "тыры-пыры", 3: "тыры", 5: "пары", 6: "тыры", 9: "тыры", 10: "пары", 12: "тыры"}.get(i % 15, i) for i in range(1,101)]

A: Да здравствуют однострочники:
arr = ['тыры-пыры' if i%15==0 else 'пыры' if i%5==0 else 'тыры' if i%3==0 else i for i in range(1, 101)]

A: Вот решение без делений и умножений.
возможно оно быстрее (
div3, div5 = 1, 1
for i in range(1,101):

    text3 = "тыры" if div3 == 3 else ""
    text5 = "пыры" if div5 == 5 else ""

    text_answer = "".join([text3,
                           "-" if div3 == 3  and  div5 == 5  else "",
                           text5
                           ])
    print(text_answer if text_answer else i)
    div3 = div3 + 1 if div3 != 3 else 1
    div5 = div5 + 1 if div5 != 5 else 1

Вот сравнение и увы мой способ хуже.... Интересно почему.
наверное из за принта в цикле
228 µs ± 19.7 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
13.1 ms ± 1.5 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)

Конечно, у меня нет результирующего списка значений, но в задаче о нем ни слова.  Если же список таки нужен, то вот:
rez = [i for i in range(1,101)]
div3, div5 = 1, 1
for i in range(1, 101):
text3 = "тыры" if div3 == 3 else ""
text5 = "пыры" if div5 == 5 else ""

text_answer = "".join([text3,
                       "-" if div3 == 3  and  div5 == 5  else "",
                       text5
                       ])
if text_answer:
    rez[i-1] = text_answer

div3 = div3 + 1 if div3 != 3 else 1
div5 = div5 + 1 if div5 != 5 else 1

print(rez)

с результатом
257 µs ± 10.9 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Как не странно, мой вариант медленнее, интересно  -  почему.
Вариант от Zhihar  тоже лучше моего:
244 µs ± 12.4 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)


text:
Q: Powershell Send-MailMessage fails authentication on Azure Pipeline I'm trying to send some emails on a pipeline in Azure Devops with the following Powershell task:
- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
      $username = "$(emailUsername)"
      $password = ConvertTo-SecureString -String "$(emailPassword)" -AsPlainText -Force

      $credentials = [PSCredential]::New($username, $password)

      $sendMailParams = @{
          SMTPServer  = 'smtp.office365.com'
          Port        = 587
          UseSsl      = $false
          Credential  = $credentials
          From        = $username
          To          = '${{ parameters.recipientsAddresses }}'
          Subject     = '${{ parameters.mailSubject }}'
          Body        = '${{ parameters.mailBody }}'
      }

      $encoding = [System.Text.Encoding]::UTF8

      Send-MailMessage @sendMailParams -Encoding $encoding

The PowerShell script works just fine running locally on my machine, yet when I try to run it on my pipeline it fails with the following message:
Send-MailMessage : The SMTP server requires a secure connection or the client was not authenticated. The server
response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [<MAIL_SERVER>.outlook.com]

What am I missing here?

A: There can be different reasons for this:

*

*The From address as emailAddress, which is not a proper email address. For Office 365 the From needs to be a real address on the Office 365 system. You can validate that if you hardcode your email address as the From and your Office 365 password.

*Make sure that $credentials you set are correct.


text:
Q: div styles in html page All,
How to make the div more presentable in the below code.
i.e, on mouseover the div should look like as same as title attribute or even better
And the text on it should also look presentable

move me

Thanks.....

A: How about this:

It looks a bit like the title tool tip (but be aware, that every user can have a different configuration via OS or browser) and it adds a light 3d effect. If you are using CSS3, you can also use gradients, round corners and shadows, which can look nice.

A: How about this:
$(function(){
 $(window).mouseover(function(event){
    $("#div1").css({'color': '#0000ff'});
    $("#div1").css({'font-weight': 'bold'});
    $("#div1").css({'background-color': '#00ff00'});
});
});

A: I think you should switch from "mouseover" to "mousemove", because it's a bit of a smoother effect:
$(window).mousemove(function(event){
    $("#div1").css({'top': event.pageY, 'left': event.pageX});
});

As for the look, here's the Windows tooltip look (if that's what you wanted):

And here's something you might like:


text:
Q: How to solve this error in the name property of composer.json validation? I got this error as i validate my composer.json file:
  [Composer\Json\JsonValidationException]
  "./composer.json" does not match the expected JSON schema:
   - name : Does not match the regex pattern ^[a-z0-9]([_.-]?[a-z0-9]+)*/[a-z0-9](([_.]?|-{0,2})[a-z0-9]+)*$

The name Property looks like this:
"name":"lukas735/united-in-faith",

I also tried out the following alternations:
"lukas735/united-in-faith",
"lukas/united-in-faith",
"lukas735/united.in.faith",
"lukas/united.in.faith",
"lukas735/united_in_faith",
"lukas/united_in_faith",
"lukas/uif",
"lukas735/uif",

None of this worked... The regex proofer said the forward slash is placed wrong... But its composer intern so i can't change anything on that. And anyway. My strings also not got matched if i corrected that in regex proofer.
Is there anyway to let match my united-in-faith String... The name before was just an account name  because a video said this vendor-name can be choosed yourself... But video was from 2016. I found no hints in internet where to find the vendor-name. So i choosed it myself.
I saw some videos and topics about this naming convention, but they all not seemed to giving an answer which solved it.
What did I wrong?
Has anybody a solution for this error?
Here is my Composer.json File:
    {
    "name":"lukas735/united-in-faith",
    "description":"description",
    "keywords": [
        "united-in-faith",
        "united in faith",
        "united_in_faith",
        "dating"
    ],
    "homepage": "https://...",
    "license": "MIT",
    "authors": [
        {
            "name": "...",
            "email": "....",
            "homepage": "...",
            "role": "Developer"
        }
    ],
    "repositories":[
        {
            "type": "package",
            "package": {
                "name": "lukas735/united-in-faith",
                "version": "1.0.0",
                "source": {
                    "url": "https://github.com/...",
                    "type": "git",
                    "reference": "master"
                }
            }
        }
    ],
    "require": {
        "components/jqueryui": "^1.12",
        "united-in-faith": "dev-master"
    },
    "autoload": {
        "psr-4": {
            "lukas735\\": "sites/classes"
        }
    },
    "recommend":{
            "ext-zip":"*"
    },
    "bin":["bin"],
    "config":{
            "vendor-dir":"vendor"
    },
    "scripts": {
        "test": "phpspec run",
        "format": "phpcbf --standard=psr2 src/"
    },
    "extra": {
        "branch-alias": {
                "dev-master": "1.0-dev"
        }
    }
}

A: use command 'composer init' to make a new composer.json file, use old for reference


text:
Q: How to write a test case for a method returning object I have a method for which the return type is object. How do I create a test case for this? How do I mention that the result should be an object?
e.g.:
public Expression getFilter(String expo)
{
    // do something
    return object;
}

A: try Something like this. If the return-type of your function is Object then replace Expression by Object:
//if you are using JUnit4 add in the @Test annotation, JUnit3 works without it.
//@Test
public void testGetFilter(){
    try {
        Expression myReturnedObject = getFilter("testString");
        assertNotNull(myReturnedObject); //check if the object is != null
        //check if the returned object is of class Expression.
        assertTrue(true, myReturnedObject instanceof Expression);
    } catch(Exception e){
        // let the test fail, if your function throws an Exception.
        fail("got Exception, i want an Expression");
     }
}

A: In your example the returntype is Expression? I don't understand the question, could you elaborate?
The function is even unable to return anything other than Expression (or a derived type or null). So "checking the type" would be pointless.
[TestMethod()]
public void FooTest()
{
    MyFoo target = new MyFoo();
    Expression actual = target.getFilter();

    Assert.IsNotNull(actual);  //Checks for null
    Assert.IsInstanceOfType(actual, typeof(Expression)); //Ensures type is Expression
}

I am assuming C# here; you haven't tagged your question nor mentioned the language in your question.


text:
Q: Unable to get intellij option instead just getting maven gradle option only This is my screenshot where you can find that.

A: You can create the project using New Project option:

and add all the needed dependencies/configurations manually as per https://www.jetbrains.com/help/idea/2020.3/javafx.html .
When creating a project with JavaFX project wizard and selecting Maven/Gradle, the IDE will configure everything automatically. E.g. add JavaFX plugin to the pom.xml/build.gradle, download all the needed dependencies, etc... so that you can launch the project out of the box.


text:
Q: How to encode an empty audio track for Azure Media Services v3? I have a site where users can upload videos to be encoded and viewed in azure media player. Some of the videos uploaded do not have audio tracks which azure media player can't play. How can I encode an empty audio track with these videos? I'm using v3 of the REST api.
My current code for transforms is:
private async Task<string> CreateTransformAsync(string transform)
    {
        JObject body = new JObject(
            new JProperty("properties",
                new JObject(
                    new JProperty("description", "Basic Transform using an Adaptive Streaming encoding preset from the libray of built-in Standard Encoder presets"),
                    new JProperty("outputs",
                        new JArray(
                            new JObject(
                                new JProperty("onError", "StopProcessingJob"),
                                new JProperty("relativePriority", "Normal"),
                                new JProperty("preset",
                                    new JObject(
                                        new JProperty("@odata.type", "#Microsoft.Media.BuiltInStandardEncoderPreset"),
                                        new JProperty("presetName", "H264MultipleBitrate720p")
                                    )
                                )
                            )
                        )
                    )
                )
            )
        );
        var jsonBody = new StringContent(body.ToString(), Encoding.UTF8, "application/json");
        HttpResponseMessage responseMsg = await _httpClient.PutAsync($"subscriptions/{_config.Value.SubscriptionId}/resourceGroups/{_config.Value.ResourceGroup}/providers/Microsoft.Media/mediaServices/{_config.Value.MediaAccountName}/transforms/{transform}/?api-version={_config.Value.ApiVersion}", jsonBody);
        string responseContent = await responseMsg.Content.ReadAsStringAsync();

        var response = JObject.Parse(responseContent);

        if (response["error"] == null)
        {
            return response["name"].ToString();
        } else
        {
            throw new Exception(response["error"].ToString());
        }
    }

UPDATE:
After scouring the documentation, I've gotten a little further with this: https://learn.microsoft.com/en-us/azure/media-services/latest/custom-preset-rest-howto#define-a-custom-preset
I now define a custom preset, read it in and send that in the body instead. Problem now is I can't find a similiar option for "condition": "InsertSilenceIfNoAudio" like in v2 of the API. I've opened a github issue about it here: https://github.com/MicrosoftDocs/azure-docs/issues/28133

A: What's your target encoding settings?  Do you need a custom preset?
If not, and you just need a standard adaptive streaming profile preset, you can use the
AdaptiveStreaming preset. It handles the insert silence.

A: It's not finally announced, but as we tested for our project, Azure Media Player got complete support of Video Only content, starting with version 2.3.0 (April 30, 2019).
Officially there is a mention in feature list that the feature is already implemented ("Video Only" feature with comment "Supported in AzureHtml5JS", here) and it's said in Change list of 2.3.0 release that "Added support for video-only assets for DASH" (here), but we personally tested for SMOOTH and HLS as well - no issues, so video-only assets start playing without any issues starting with version 2.3.0.
At the same time the issue is still mentioned in Known Issues: "Assets that are audio or video only will not play back via the AzureHtml5JS tech.", but I guess they just didn't update the docs. Another option, probably they didn't test it completely, but as I say from our internal testing it looks like it completely works.


text:
Q: Events between Marionette.CompositeView and Marionette.ItemView I have two modules itemView.js and ListView.js.
Everything works when I fetch the data.
The problem is about the item view (1) when I change the corresponding model.
a) the ListView.js (2) displays all the object which models have closed value equal to false (3)
b) the action closeTask in (1) changes the value of the model
from closed: false to closed: true
c) when b) occurs nothing change,
 but if I reload the page I get the right results (the model having the closed value equal to true is not displayed).
How should I fix this issue?

(1)
// itemView.js
var itemView = Marionette.ItemView.extend({

    initialize: function () {
        this.model.on('change', this.render, this);
    },

    events: {
        'click #close': 'closeTask'
    },

    template: itemTemplate,

    tagName: 'li',

    closeTask: function () {
        if (!this.model.get('closed')) {
            this.model.save({
                closed: true
            });
        }
    }

});

(2)
// ListView.js
var ListView = Marionette.CompositeView.extend({

    template: listTemplate,

    itemView: itemView

});

(3)
// Collection
myCollection.attributes = [
    {
        id: 1,
        name: 'bar'
        closed: false
    },
    {
        id: 2,
        name: 'bar2'
        closed: false
    },
    ….
];

P.S.:
When I fetch the collection, the server give me just the models which have the closed attribute equal to false.
app.addInitializer(function () {
    myCollection = new MyCollection();
    myCollection.fetch();
});

A: I did not work with Marionette but I have been working with Backbone, my thought is that Marionette is not refreshing the template or something like it.
What happens if you try this?
// itemView.js
var itemView = Marionette.ItemView.extend({

    initialize: function () {
        this.model.on('change', this.render, this);
    },

    onRender : function(){
       //verify your model:
       console.log( this.model.toJSON() );
       if (this.model.get('closed')) {
          this.$el.fadeOut();//bye bye item
       }
    },

    events: {
        'click #close': 'closeTask'
    },

    template: itemTemplate,

    tagName: 'li',

    closeTask: function () {
        if (!this.model.get('closed')) {
            this.model.save({
                closed: true
            });
        }
    }

});


text:
Q: AngularJs used with Play cannot find or instantiate module I am using the Play Framework (2.5.9). On my scala html template, I pull in Angular via WebJars. I next specify the module and controller I want to use for my page. However, when I try to load the page, the relevant variables that should be set to "hi" via AbstractACtrl are not being set. Also, I get the following error in the browser's console:
Error: [$injector:modulerr] Failed to instantiate module abstractA due to:
[$injector:nomod] Module 'abstractA' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

I do not understand why module "abstractA" is not available. I am defining it right there on the view.scala.html page... I am very sure that angular.js is being pulled in, because in Chrome, the Sources shows webjars/angular.js/1.5.9/angular.js. All the console.log and console.error in my code below are just messages I'm outputting to the console for debugging. None are actually printing to the console right now, indicating that execution is never reaching them.
Things I've tried:
1) Load in angular.js directly (without WebJars).
2) Pull in angular-route.js, angular-resource.js, and/or angular-animate.js with / without WebJars.
3) "data-ng-app" - make it either "ng-app" or "x-ng-app".
4) Pass in $scope to the controller and reference all fields via "$scope."... instead of "this."...
5) Make the "var abstractA" at beginning of my JavaScript "var ab" instead.
6) Put the script which pulls in angular in the "head" portion instead of the "body" portion.
7) Remove the "this.originalAs = @aDocs;" line from the controller.
8) Put all javascript in the "head" portion of the page.
Below is my current code. Please let me know why the module "abstractA" is not available.
build.sbt:
libraryDependencies ++= Seq(
    ...
    "org.webjars"             % "angularjs"                % "1.5.9",
    "org.webjars"             % "angular-ui-bootstrap"     % "2.2.0",
    "org.webjars"             % "bootstrap"                % "3.3.7-1",
    "org.webjars"             %% "webjars-play"            % "2.5.0"
)

view.scala.html:
@(aDocs: List[String],
  webJarAssets: controllers.WebJarAssets)

<!DOCTYPE html>

<meta charset='utf-8'/>

  <link rel='stylesheet' href='@routes.WebJarAssets.at(webJarAssets.locate("css/bootstrap.min.css"))' />
  <link rel='stylesheet' type='text/css' href='@routes.Assets.versioned("assets/stylesheets/style.css")' />

  ...

{{originalA}}

{{abstractACtrl.abc}}

{{abc}}

  <button ng-click='abstractACtrl.setUrl()'>Click!</button>

A: I figured out a solution (what an annoying bug!). It wasn't documented anywhere...
I had to change this line:
this.originalAs = @aDocs;

to:
this.originalAs = "@aDocs";

Then, convert it to a list using Javascript split() function for use in the rest of the page.
For some reason, the parsing error there was giving the error statement that the module itself could not be found. Took a bunch of trial-and-error to realize that this was the root cause.


text:
Q: ADF Dataflow - Replace spaces with underscore in column names To remove spaces with underscore I am using replace($$,' ','_') expression in Select transformation
It works for a column "Period Key" and makes it "Period_Key" but for another column "Week in Month Description" it makes it "Week_in Month Description". So it is replacing only first occurrence
Can someone try this? Or how can we write regex for this?

A: I used below function and it worked
regexReplace($$,' ','_')


text:
Q: How to embed ArangoDB in a desktop application I would like to embed a graph database in my application (shipping for windows, linux & MAC). I narrowed the search down to ArangoDB & OrientDB. I was able to get embedded OrientDB to work but I'd still like to try ArangoDB to make an informed decision. Documentation for OrientDB embedded version is pretty clear while I can't find anything for ArangoDB. ArangoDB is written in C++ so I also have to figure out how to make it be portable across platforms and how to install it with my application. The usage of ArangoDB (or OrientDB) should be transparent to the users of our application. Thanks!
Update: I forgot to mention, our application is in C++. We were looking for instructions that can help us build ArangoDB binary with our existing modules. We then can figure out how to load the binaries and talk to them.

A: It's possible to install an instance of ArangoDB with your application installation.
It installs into it's own directory, and its key assets are:

*

*ArangoDB Binaries

*ArangoDB Data files

*ArangoDB Log files

*ArangoDB Foxx Applications (optional)

ArangoDB can run as a service, and it is configured via a file called arangod.conf.
This file centrally controls settings like the ports it runs on, the IP addresses it listens to, the database engine to use, SSL and security settings, and much more.
Taking Windows as an example, you can do a silent installation of ArangoDB, and then use tools like PowerShell or DOS batch files to stop/start the ArangoDB service, copy in an arangod.conf file with your required configuration settings, etc.
It's even possible to generate an SSL certificate and apply it to the ArangoDB instance so that you can have SSL connectivity to the database if required.
Additionally you can utilise the ArangoShell via scripts which allows you to create databases, restore default data from a backup, create ArangoDB users, assign rights.
It sounds like you need to get more comfortable with ArangoDB as a product, and then start to mess around with installing, uninstalling, configuring, and backing up/restoring databases.
I've also evaluated ArangoDB versus OrientDB, and I picked ArangoDB because it runs faster, has many more updates, and their driver packs are well written.
When it comes to embedded databases, you really need a multi-model database, and being able to store standard documents as well as graph data in one database engine, is invaluable.
Additionally, have a really good look at the Foxx MicroService architecture of ArangoDB. It allows you to host business logic behind REST API's and Job Queues running right in the ArangoDB database. This means your application doesn't even need raw table access to the database, rather it can access your data via a REST API and your internal schema is hidden from users, and your business logic stops them doing silly things and wrecking the database.
By having a REST API data layer between your application and the database, it gives you more flexibility on how people consume your data, giving you more options about opening it up in a safe way, knowing your application logic will keep your data safe.
If you chose to use Foxx, there is a cool new tool ArangoDB has released called foxx-cli which lets you script the installation and configuration of Foxx MicroServices in your database. This is a super powerful tool as it's possible to fully install and configure an ArangoDB server, database, and internal settings via installation scripts.
Take time to learn ArangoDB, as with all skills it takes time to really get to know it. I'm still learning something every day and I've only been using it for 2 years :)

A: If you're using NodeJS (which I have to assume as you don't mention what programming language you're using) as your platform you can use Electron (https://electron.atom.io) and use the ArangoJS (http://npmjs.com/package/arangojs) Driver, if an ORM is necessary I'd recommend using (http://npmjs.com/package/caminte) which has built-in support for ArangoDB, although the documentation being to a poor standard, it should be suffice with some programming knowledge.
OFT: Electron lets you create cross platform Desktop applications in pure HTML, JS and CSS. You can also use Cordova if you're targeting the mobile platform.
You could also use Foxx to perform some of your application logic (this is down to your personal preference) or also create an API platform (with for example Restify).
Most of database systems are written in C++ but that does not mean can only access them via C++, additional drivers are provided for the popular languages. If you use a specific language then update the question so we can help further.
You might also want to read this: https://www.arangodb.com/2018/02/nosql-performance-benchmark-2018-mongodb-postgresql-orientdb-neo4j-arangodb/ as to why ArangoDB would be a better choice for you.

Edit
Due to my limited experience in C++ I can only provide some references which I've saved earlier, but I'm sure they'll be of use to you.
For C++ the driver you should be using is:
https://www.arangodb.com/2017/11/introduction-fuerte-arangodb-c-plus-plus-driver/
An example of the usage of the driver:
https://www.arangodb.com/wp-content/uploads/2017/10/C-Example-Source-Code-File.cc
A simple example / tutorial on how to use graphing in ArangoDB:
https://docs.arangodb.com/3.2/Manual/Graphs/
A free course by Arango on Graphing:
https://www.arangodb.com/arangodb-graph-course/
Hope they help!


text:
Q: Trying Retrofit(an android api library),got some issues trying out retrofit , here is my code

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

         var rex = RetrofitClient.getClient("www.xyz.php")

         var pwq= rex?.create(login_sx.class))

the error is in the last line , the error seems to be a (Name Expected)var pwq= rex?.create(login_sx.class))

A: It should be var pwq= rex?.create(login_sx::class.java))


text:
Q: jQuery adding dynamically autosize textarea I'm trying to implement this : https://github.com/jackmoore/autosize/tree/v1
It works as expected when I add a textarea on my html page, but it doesn't work as expected it if I create a textarea dynamically. You can click "new comment" and test it.
Here's my fiddle.
http://jsfiddle.net/hcxgqhae/6/
HTML

<textarea></textarea>

<button type="button" class="btn btn-success new-comment">New comment</button>

Hello this is a test comment.
 on March 5th, 2014
 like
 comment
 share

Hello this is a test comment and this comment is particularly very long and it goes on and on and on.
 on March 5th, 2014

Hello this is a test comment.
 on March 5th, 2014

CSS
.detailBox {
    border: 1px solid #bbb;
}
.titleBox {
    background-color: #fdfdfd;
    padding: 10px;
}
.titleBox label {
    color: #444;
    margin: 0;
    display: inline-block;
}
.commentBox {
    padding: 10px;
}
.commentBox .form-group:first-child, .actionBox .form-group:first-child {
    width: 80%;
}
.commentBox .form-group:nth-child(2), .actionBox .form-group:nth-child(2) {
    width: 18%;
}
.actionBox .form-group * {
    width: 100%;
}
.taskDescription {
    margin-top: 10px 0;
}
.commentList {
    padding: 0;
    list-style: none;
}
.commentList li {
    margin: 0;
    margin-top: 10px;
}
.commentList li > div {
    display: table-cell;
}
.commenterImage {
    width: 30px;
    margin-right: 5px;
    height: 100%;
}
.commenterImage img {
    width: 100%;
    border-radius: 50%;
}
.commentText p {
    margin: 0;
}
.sub-text {
    color: #aaa;
    font-family: verdana;
    font-size: 11px;
}
.actionBox {
    padding: 10px;
}
.commentText p {
    margin-left: 0.2em;
    font-size: 0.9em;
}

jQuery
$(document).ready(function () {
    $('.new-comment').one('click', (function () {
        $('.commentList li:last').after('
 ' +
            '
 ' +
            ' ' +
            '
 ' +
            '
 ' +
            '
<textarea></textarea>
 ' +
            '
 ' +
            '
');
    }));
});

A: you need to autosize the new textarea
$(document).ready(function () {
    $('.new-comment').one('click', (function () {
        var li = $('
 ' +
            '
 ' +
            ' ' +
            '
 ' +
            '
 ' +
            '
<textarea></textarea>
 ' +
            '
 ' +
            '
');

        $('.commentList li:last').after(li);

        // `autosize` the new textarea
        autosize(li.find("textarea"));
    }));
});


text:
Q: Difference between service layer and controller in practice I have read many theories about differences between service layer and controller, and I have some questions about how to realize this in practice. One answer to Service layer and controller: who takes care of what? says:

I try to restrict controllers to doing work related to validating http
  parameters, deciding what service method to call with what parameters,
  what to put in the httpsession or request, what view to redirect or
  forward to, or similar web-related stuff.

and from http://www.bennadel.com/blog/2379-a-better-understanding-of-mvc-model-view-controller-thanks-to-steven-neiland.htm :

Red Flags: My Controller architecture might be going bad if:
The Controller makes too many requests to the Service layer. The
  Controller makes a number of requests to the Service layer that don't
  return data. The Controller makes requests to the Service layer
  without passing in arguments.

At the moment I am developing a web app with Spring MVC, and I have such method for saving changed user's email:
/**
     * <p>If no errors exist, current password is right and new email is unique,
     * updates user's email and redirects to {@link #profile(Principal)}
     */
    @RequestMapping(value = "/saveEmail",method = RequestMethod.POST)
    public ModelAndView saveEmail(
            @Valid @ModelAttribute("changeEmailBean") ChangeEmailBean changeEmailBean,
            BindingResult changeEmailResult,
            Principal user,
            HttpServletRequest request){

        if(changeEmailResult.hasErrors()){
            ModelAndView model = new ModelAndView("/client/editEmail");
            return model;
        }
        final String oldEmail = user.getName();
        Client client = (Client) clientService.getUserByEmail(oldEmail);
        if(!clientService.isPasswordRight(changeEmailBean.getCurrentPassword(),
                                          client.getPassword())){
            ModelAndView model = new ModelAndView("/client/editEmail");
            model.addObject("wrongPassword","Password doesn't match to real");
            return model;
        }
        final String newEmail = changeEmailBean.getNewEmail();
        if(clientService.isEmailChanged(oldEmail, newEmail)){
            if(clientService.isEmailUnique(newEmail)){
                clientService.editUserEmail(oldEmail, newEmail);
                refreshUsername(newEmail);
                ModelAndView profile = new ModelAndView("redirect:/client/profile");
                return profile;
            }else{
                ModelAndView model = new ModelAndView("/client/editEmail");
                model.addObject("email", oldEmail);
                model.addObject("emailExists","Such email is registered in system already");
                return model;
            }
        }
        ModelAndView profile = new ModelAndView("redirect:/client/profile");
        return profile;
    }

You can see that I have a lot of requests to the service layer, and I do redirecting from controller - that is business logic. Please show better version of this method.
And another example. I have this method, which returns user's profile:
/**
     * Returns {@link ModelAndView} client's profile
     * @param user - principal, from whom we get {@code Client}
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/profile", method = RequestMethod.GET)
    public ModelAndView profile(Principal user) throws UnsupportedEncodingException{
        Client clientFromDB = (Client)clientService.getUserByEmail(user.getName());
        ModelAndView model = new ModelAndView("/client/profile");
        model.addObject("client", clientFromDB);
        if(clientFromDB.getAvatar() != null){
            model.addObject("image", convertAvaForRendering(clientFromDB.getAvatar()));
        }
        return model;
    }

method convertAvaForRendering(clientFromDB.getAvatar()) is placed in super class of this controller, it is right placing of this method, or he must be placed in service layer??
Help please, it is really important for me.

A: In both examples, why do you need to cast Client? That's a code smell.
Since the call to the service tier is also the call that establishes the database transaction boundary, making multiple calls means that they are executed in different transactions, and are therefore not necessarily consistent with each other.
That is one of the reasons why multiple calls are discouraged. @ArthurNoseda mentions other good reason in his answer.
In your first case, there should be a single call to the service tier, e.g. something like this:
if (changeEmailResult.hasErrors()) {
    return new ModelAndView("/client/editEmail");
}
try {
    clientService.updateUserEmail(user.getName(),
                                  changeEmailBean.getCurrentPassword(),
                                  changeEmailBean.getNewEmail());
} catch (InvalidPasswordException unused) {
    ModelAndView model = new ModelAndView("/client/editEmail");
    model.addObject("wrongPassword", "Password doesn't match to real");
    return model;
} catch (DuplicateEmailException unused) {
    ModelAndView model = new ModelAndView("/client/editEmail");
    model.addObject("email", oldEmail);
    model.addObject("emailExists", "Such email is registered in system already");
    return model;
}
refreshUsername(newEmail);
return new ModelAndView("redirect:/client/profile");

You could also use return value instead of exceptions.
As you can see, this will delegate the business logic of changing the email to the service tier, while keeping all UI related actions in the controller where they belong.

A: A Spring Controller is generally tied to the Spring API (with classes like Model, ModelAndView...) or the Servlet API (HttpServletRequest, HttpServletResponse...). Methods can return String outcomes that are resolved to the name of a template (JSP...). Controller are most certainly biased toward Web GUIs, with a strong dependence upon Web technology.
Services on the other hand should be designed with business logic in mind and no assumptions about the client. We could remote the service, expose it as Web Service, implement a Web front end, or a Swing client. A Service should not depend upon Spring MVC, Servlet API, and the like. That way, if you need to retarget your application, you could reuse most of the business logic.
As for the note concerning too many calls to the service layer from the controller layer, it mostly is a matter of performance, which IMHO is something different. If each call to the service layer queries a database, you might experience performance issues. It the service layer and the controller layer are not running in the same JVM, you could experience performance issues either. This is another very important aspect of designing your application, but it would indicate that you should façade your services calls to provide coarser-grained operations to the controller layer.