text:
Q: How to copy and rename file to output folder as part of build I believe this is more of an msbuild-related question.
Have a .net core app and I need to conditionally publish a file and based on the build config selected in Visual Studio 2019, the file should be renamed before publishing to the target.
So Im looking at modifying the csproj file (which is nothing but an msbuild file itself)
I dont see a condition option on the copy task
https://learn.microsoft.com/en-us/visualstudio/msbuild/copy-task?view=vs-2019
The goal Im after, is if I have 3 different files
tester-notes.dev.json
tester-notes.debug.json
tester-notes.prod.json
If prod is selected as a build config, I want the file published to be tester-notes.prod.json, but renamed to tester-notes.json

A: Assuming you have three files(build action = None) in Solution Explorer when developing:

You can use something similar to this script to rename and copy to publish folder if you're using FileSystem publish mode:
<ItemGroup Condition="$(Configuration)=='Dev'">
    <FileToRename Include="$(ProjectDir)\tester-notes.dev.json" />
  </ItemGroup>
  <ItemGroup Condition="$(Configuration)=='Debug'">
    <FileToRename Include="$(ProjectDir)\tester-notes.debug.json" />
  </ItemGroup>
  <ItemGroup Condition="$(Configuration)=='Prof'">
    <FileToRename Include="$(ProjectDir)\tester-notes.prof.json" />
  </ItemGroup>

  <Target Name="DoSthAfterPublish1" AfterTargets="Publish" Condition="$(Configuration)=='Dev'">
    <Copy SourceFiles="@(FileToRename)" DestinationFiles="@(FileToRename->Replace('.dev.json','.json'))"/>
    <Move SourceFiles="$(ProjectDir)\tester-notes.json" DestinationFolder="$(PublishDir)" OverwriteReadOnlyFiles="true"/>
  </Target>

  <Target Name="DoSthAfterPublish2" AfterTargets="Publish" Condition="$(Configuration)=='Debug'">
    <Copy SourceFiles="@(FileToRename)" DestinationFiles="@(FileToRename->Replace('.debug.json','.json'))"/>
    <Move SourceFiles="$(ProjectDir)\tester-notes.json" DestinationFolder="$(PublishDir)" OverwriteReadOnlyFiles="true"/>
  </Target>

  <Target Name="DoSthAfterPublish3" AfterTargets="Publish" Condition="$(Configuration)=='Prof'">
    <Copy SourceFiles="@(FileToRename)" DestinationFiles="@(FileToRename->Replace('.prof.json','.json'))"/>
    <Move SourceFiles="$(ProjectDir)\tester-notes.json" DestinationFolder="$(PublishDir)" OverwriteReadOnlyFiles="true"/>
  </Target>

And if you can reset tester-notes.debug.json to tester-notes.Debug.json,, then we may combine the three targets into one by using DestinationFiles="@(FileToRename->Replace('.$(Configuration).json','.json'))". Hope it makes some help :)
In addition:
According to the Intellisense we can find the Copy task supports Condition:


text:
Q: Modeling a database for easy counting / reporting I have an app where user is known (user_id) and he can do several actions (action_id).
Every time he makes an action I need to save the fact that he made it for reports/analytics. I guess it is similar to other analytic solutions and their db design.
Once I have the data, provided with a time window (minutes resolution) I need to count for each user (all or some) the number of times he did actions and which actions he did. (sum all data grouped by action_id).
Some assumptions:

*

*The number of users are ~1000.

*Action types are ~100.

*Actions can happen 24/7.

*The time windows can span from minutes to days and are random.

*A time window can't go back more than 30 days.

I'm considering SQL, NoSQL and RRD to save the data.
I put RRD here because it's easy to implement the insert of the data into statds+graphite. I'm concerned if I take this approach, the querying (although provided by graphite) will not be indexed and will probably have to count all the data whenever I ask for a window/user (no indexing). Another problem is that when querying all the data, all users info will be needed, resulting in reading all the files concurrently which I'm not sure is a good thing.
SQL - Very easy implementation when inserting the data and querying. Easy to index, order and group by. However I'm not sure it's easy if I'm anticipating high traffic. Also, I'm not sure how effective is the count() of sql (haven't used SQL in the last few years) after group by. Can it offer parallel computation?
NoSQL - Is there a solution out there that is the right fit for this type of scenario (perhaps a Map/Reduce algorithm to fast generation of counts in a time window?)
Thanks for helping me model

A: I think the essential approach should be to keep it simple. It will save you frustration and unplanned maintenance. The table design is simple a parent (users) and a child (actions) with a one-to-many foreign key relationship. The data you need will be easy to query.
Lets assume active user actions are 500 users 20 actions 100 per day for 30 days. That's about 30 million rows, a regular day's work for a database.
It sounds like you are most comfortable with a standard SQL relational database. That approach is also widely used, with good community and tool support, and easily maintainable.
So you have a simple design, a feasible architecture, and good comfort level with a SQL relational database. Go with that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to draw equidistant dashes using DashPathEffect At the moment I'm using DashPathEffect with hardcoded intervals to draw a circle as next:
float[] intervals = new float[]{ 3, 18 };
DashPathEffect path = new DashPathEffect(intervals, 0);
paint.setPathEffect(path);
… … … …
canvas.drawCircle(x, y, radius, paint);

But this produces a non-equidistant dash where the circle starts and ends, as shown in the image below:

I can of course adjust it manually, but this would only work for one specific device density, and produce again the same problem in a different display density.
What would the formula to calculate equidistant dashes?

A: You need n dashes plus n gaps to have the same total length as the circumference of the circle. The below code assumes you've correctly determined both the center point and the radius you want to use.
double circumference = 2 * Math.PI * radius;
float dashPlusGapSize = (float) (circumference / NUM_DASHES);
intervals[0] = dashPlusGapSize * DASH_PORTION;
intervals[1] = dashPlusGapSize * GAP_PORTION;

DashPathEffect effect = new DashPathEffect(intervals, 0);
paint.setPathEffect(effect);

canvas.drawCircle(center, center, radius, paint);

For instance, I've used NUM_DASHES = 20, DASH_PORTION = 0.75f, and GAP_PORTION = 0.25f, and I see:

You can use different values for these constants to change how many dashes you chop the cirlce into, or how big the dash/gap are relative to each other (as long as DASH_PORTION + GAP_PORTION adds up to 1).

A: In case you have a different figure you can use this method to measure your custom path length:
    val measure = PathMeasure(path, false)
    val length = measure.getLength()


text:
Q: dateparser in python returns unexpected result import dateparser

to_parse = '20210126231003'
parsed = dateparser.parse(to_parse, date_formats=['%Y%m%d%H%M%s'])

print(to_parse)
print(parsed)

I am expecting it to resolve to Jan 26 2021...
but it instead resolved to some date in 2034.
20210126231003
2034-01-16 03:23:43

I am curious on why this is happening. Is my understanding for the parser's functioning wrong?

A: As mentioned in the comment, the format specifier for second was wrong. it should had been %S.
Closing the question.


text:
Q: Error: Grant type is not set while trying to generate the Token I am working on a python script that generates the access token.
I am working on API calls for the first time.
I am getting the below error:
jsonResponse: {
'error_description': 'Grant type is not set', 'error': 'invalid_request'
}
I tried all the different grant_types but getting the same error.
Could someone help me?
import requests

import json

myToken = 'https://......../internal/access_token'

headers =
   {

                    "Accept": "application/json",
                    'Authorization': 'Bearer {}'.format(myToken),
                   "Content-Type": "application/x-www-form-urlencoded",
                   "Grant_Type":"client_credentials",
                    "scope": 'api-customer',
                    "client_id": '<Clientid>',
                    "client_secret": '<secret>'
  }

response = requests.post(myToken, headers = headers)

jsonResponse = response.json()

print('jsonResponse: ' + str(jsonResponse))

Thanks


text:
Q: vb.net programmatically cancel editig datagridview cell I'm new in vb.net and have a problem with cancel cell edit in data grid view.
I want to have edit property for whole data grid view set on true but on "double click" event I want to run some code and in the end cancel cell editing (blinking cursor).
On VBA to do this in Excel i type cancel = true.
What would be the formula for vb.net?

A: You can use CancelEdit method on CellMouseDoubleClick Event:
Private Sub DataGridView1_CellMouseDoubleClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseDoubleClick

    DataGridView1.CancelEdit()

End Sub


text:
Q: How to do an if statement in a Django template to find if a decimal value is 0 Basically, I want to find out if a decimal field value is 0.00. Then, I want to output a different value in the template. See code below. The code does not work.
variable = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True)

#template
{% for item in table %}
{% if item.variable is 0.00 %}

Total:  Unknown

{% else %}

Total: ${{ item.variable }}

{% endif %}
{% endfor %}

This does not work. It outputs: Total: $0.00.

A: You can check this with if not item.variable for example, since 0.00 has truthiness False. This condition will also check if the value is None (so NULL in the database), which is probably something you should consider as well:
{% for item in table %}
    {% if not item.variable %}

Total:  Unknown

    {% else %}

Total: ${{ item.variable }}

    {% endif %}
{% endfor %}
If you only want to check for zero, you can check it with == 0:
{% for item in table %}
    {% if item.variable == 0 %}

Total:  Unknown

    {% else %}

Total: ${{ item.variable }}

    {% endif %}
{% endfor %}


text:
Q: Mono implementation of Dictionary using .Equals(obj o) instead of .GetHashCode() By searching though msdn c# documentation and stack overflow, I get the clear impression that Dictionary<T,T> is supposed to use GetHashCode() for checking key-uniqueness and to do look-up.

The Dictionary generic class provides a mapping from a set of keys to a set of values. Each addition to the dictionary consists of a value and its associated key. Retrieving a value by using its key is very fast, close to O(1), because the Dictionary class is implemented as a hash table.
  ...
  The speed of retrieval depends on the quality of the hashing algorithm of the type specified for TKey.

I Use mono (in Unity3D), and after getting some weird results in my work, I conducted this experiment:
public class DictionaryTest
{
    public static void TestKeyUniqueness()
    {
    //Test a dictionary of type1
    Dictionary<KeyType1, string> dictionaryType1 = new Dictionary<KeyType1, string>();
    dictionaryType1[new KeyType1(1)] = "Val1";
    if(dictionaryType1.ContainsKey(new KeyType1(1)))
    {
        Debug.Log ("Key in dicType1 was already present"); //This line does NOT print
    }

    //Test a dictionary of type1
    Dictionary<KeyType2, string> dictionaryType2 = new Dictionary<KeyType2, string>();
    dictionaryType2[new KeyType2(1)] = "Val1";
    if(dictionaryType2.ContainsKey(new KeyType2(1)))
    {
        Debug.Log ("Key in dicType2 was already present"); // Only this line prints
    }
  }
}

//This type implements only GetHashCode()
public class KeyType1
{
    private int var1;

    public KeyType1(int v1)
    {
        var1 = v1;
    }

    public override int GetHashCode ()
    {
        return var1;
    }
}

//This type implements both GetHashCode() and Equals(obj), where  Equals uses the hashcode.
public class KeyType2
{
    private int var1;

    public KeyType2(int v1)
    {
        var1 = v1;
    }

    public override int GetHashCode ()
    {
        return var1;
    }

    public override bool Equals (object obj)
    {
        return GetHashCode() == obj.GetHashCode();
    }
}

Only the when using type KeyType2 are the keys considered equal. To me this demonstrates that Dictionary uses Equals(obj) - and not GetHashCode().
Can someone reproduce this, and help me interpret the meaning is? Is it an incorrect implementation in mono? Or have I misunderstood something.

A:
i get the clear impression that Dictionary is supposed to use
  .GetHashCode() for checking key-uniqueness

What made you think that? GetHashCode doesn't return unique values.
And MSDN clearly says:

Dictionary requires an equality implementation to
  determine whether keys are equal. You can specify an implementation of
  the IEqualityComparer generic interface by using a constructor that
  accepts a comparer parameter; if you do not specify an implementation,
  the default generic equality comparer EqualityComparer.Default is
  used. If type TKey implements the System.IEquatable generic
  interface, the default equality comparer uses that implementation.

A: Doing this:
public override bool Equals (object obj)
{
    return GetHashCode() == obj.GetHashCode();
}

is wrong in the general case because you might end up with KeyType2 instances that are equal to StringBuilder, SomeOtherClass, AnythingYouCanImagine and what not instances.
You should totally do it like so:
public override bool Equals (object obj)
{
    if (obj is KeyType2) {
        return (obj as KeyType2).var1 == this.var1;
    } else
        return false;
}

When you are trying to override Equals and inherently GetHashCode you must ensure the following points (given the class MyObject) in this order (you were doing it the other way around):
1) When are 2 instances of MyObject equal ? Say you have:
public class MyObject {
     public string Name { get; set; }
     public string Address { get; set; }
     public int Age { get; set; }

     public DateTime TimeWhenIBroughtThisInstanceFromTheDatabase { get; set; }
}

And you have 1 record in some database that you need to be mapped to an instance of this class.
And you make the convention that the time you read the record from the database will be stored
in the TimeWhenIBroughtThisInstanceFromTheDatabase:
MyObject obj1 = DbHelper.ReadFromDatabase( ...some params...);
// you do that at 14:05 and thusly the TimeWhenIBroughtThisInstanceFromTheDatabase
// will be assigned accordingly

// later.. at 14:07 you read the same record into a different instance of MyClass
MyObject obj2 = DbHelper.ReadFromDatabase( ...some params...);
// (the same)

// At 14:09 you ask yourself if the 2 instances are the same
bool theyAre  = obj1.Equals(obj2)

Do you want the result to be true ? I would say you do.
Therefore the overriding of Equals should like so:
public class MyObject {
    ...
    public override bool Equals(object obj) {
        if (obj is MyObject) {
            var that = obj as MyObject;
            return (this.Name == that.Name) &&
                   (this.Address == that.Address) &&
                   (this.Age == that.Age);
                   // without the syntactically possible but logically challenged:
                   // && (this.TimeWhenIBroughtThisInstanceFromTheDatabase ==
                   //     that.TimeWhenIBroughtThisInstanceFromTheDatabase)
        } else
            return false;
    }
    ...
}

2) ENSURE THAT whenever 2 instances are equal (as indicated by the Equals method you implement)
   their GetHashCode results will be identitcal.
int hash1 = obj1.GetHashCode();
int hash2 = obj2.GetHashCode();
bool theseMustBeAlso = hash1 == hash2;

The easiest way to do that is (in the sample scenario):
   public class MyObject {
    ...
    public override int GetHashCode() {
       int result;
       result = ((this.Name != null) ? this.Name.GetHashCode() : 0) ^
                ((this.Address != null) ? this.Address.GetHashCode() : 0) ^
                this.Age.GetHashCode();
       // without the syntactically possible but logically challenged:
       // ^ this.TimeWhenIBroughtThisInstanceFromTheDatabase.GetHashCode()
    }
    ...
}

Note that:
 - Strings can be null and that .GetHashCode() might fail with NullReferenceException.
 - I used ^ (XOR). You can use whatever you want as long as the golden rule (number 2) is respected.
 - x ^ 0 == x (for whatever x)


text:
Q: How do I set notification in android application at specific time? I have used following code in android application to set up Notification(Alarm) using AlarmManager.
 public void setAlarm() {
          Intent intent = new Intent(MainActivity.this, TimeAlarm.class);
          PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
            intent, PendingIntent.FLAG_UPDATE_CURRENT);

          am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
            (40000), pendingIntent);
         }

Or should I use following code
   Calendar calendar = Calendar.getInstance();

      calendar.set(Calendar.MONTH, 3);
      calendar.set(Calendar.YEAR, 2015);
      calendar.set(Calendar.DAY_OF_MONTH, 21);

      calendar.set(Calendar.HOUR_OF_DAY,11);
      calendar.set(Calendar.MINUTE, 15);
      calendar.set(Calendar.SECOND, 0);
      calendar.set(Calendar.AM_PM,Calendar.AM);

      Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
      pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);

      AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
      alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);

I want to set (notification)alarm at this specific time : 11:15AM on 21-March-2015
Can any one help me to set this?

A: First you need to use Calendar to set your date something like:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, 3);
cal.set(Calendar.YEAR, 2015);
cal.set(Calendar.DAY_OF_MONTH, 15);

cal.set(Calendar.HOUR_OF_DAY, 11);
cal.set(Calendar.MINUTE, 15);

And then in your setAlarm() method you need to set the alarm only once. You don't need to repeat it so:
public void setAlarm() {
     Intent intent = new Intent(MainActivity.this, TimeAlarm.class);
     PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
        intent, PendingIntent.FLAG_UPDATE_CURRENT);

     am.set(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),pendingIntent);
}

A: *

*Use alarm manager with service.

*Service will introduce in manifest file.

*Please follow below tutorial care fully.

A. http://nnish.com/2014/12/16/scheduled-notifications-in-android-using-alarm-manager/
B. http://androidideasblog.blogspot.co.uk/2011/07/alarmmanager-and-notificationmanager.html
C. https://github.com/benbahrenburg/benCoding.AlarmManager
D. http://www.banane.com/2014/05/07/simple-example-of-scheduled-self-clearing-android-notifications/
I hope it will help for you.

A: Run one thread every second and compare your specified time with current time, and if matches set notification.
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm aa");
String dateTimeinSrting = "21-Mar-2015 11:15 am";

try {
    Date dateTime = formatter.parse(dateTimeInString);
} catch (ParseException e) {
    e.printStackTrace();
}

float dateTimeInMillis = dateTime.getTime();

handler = new Handler();

final Runnable r = new Runnable() {
    public void run() {

        Calendar calendar;

        if(Float.compare(dateTimeInMillis, calendar.getTimeInMillis())){
            //Set the notification here
        }

        handler.postDelayed(this, 1000);
    }
};

handler.postDelayed(r, 1000);


text:
Q: How to get multiple column value from database into a list using LINQ query I would like to get FullName, Emailcolumn values using LINQ query in c# to a list and then get these values, but it giving below error;
Cannot implicity convert type Systems.Collections.Generic.List<<anoynymous type: string FullName>>
List <PlayerDetails> details = (from x in conn.Table<PlayerDetails>().Where(x => x.Email == emailTextVal).Select(p => new { p.FullName }) select x).ToList();
  SoccerAvailability soccerAvailability = new SoccerAvailability();
  soccerAvailability.FullName = details[0].FullName;
  soccerAvailability.Email = emailTextVal;

A: why don't you just select the entire PlayerDetail record?
List <PlayerDetails> details = conn.Table<PlayerDetails>().Where(x => x.Email == emailTextVal).ToList();
SoccerAvailability soccerAvailability = new SoccerAvailability();
soccerAvailability.FullName = details[0].FullName;
soccerAvailability.Email = emailTextVal;

alternately, you really only need to select the FullName, since you already know the e-mail value

A: You should not mix up Lambda with C# Expression, i mean you can, but i wouldn't recommend it.
I think this is the query you need:
(from x in conn.Table<PlayerDetails>()
where x.Email == emailTextVal
select new {
  Name = x.FullName,
  Email = x.Email
}).ToList()


text:
Q: no window manager running Kivy Could anyone help me fix this? I have a program with Kivy but it won't start on my computer.
I attach the log file. I have tried to install almost every library in the RPM repos haha...
Running Fedora 27:
Linux v27.lcars-1 4.15.10-300.fc27.x86_64 #1 SMP Thu Mar 15 17:13:04 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

I have tried install SDL2 from source or from package with the same error.
[INFO   ] Logger: Record log in /home/rroman/.kivy/logs/kivy_18-04-23_20.txt
[INFO   ] Kivy: v1.10.1.dev0, git-ae3665c, 20180424
[INFO   ] Python: v2.7.14 (default, Mar 14 2018, 13:36:31)
[GCC 7.3.1 20180303 (Red Hat 7.3.1-5)]
[INFO   ] Factory: 194 symbols loaded
[INFO   ] Image: Providers: img_tex, img_dds, img_sdl2, img_pil, img_gif (img_ffpyplayer ignored)
[INFO   ] OSC: using <multiprocessing> for socket
[INFO   ] Window: Provider: sdl2(['window_egl_rpi'] ignored)
[CRITICAL] Window: Unable to find any valuable Window provider.
egl_rpi - ImportError: cannot import name bcm
  File "/usr/lib64/python2.7/site-packages/kivy/core/__init__.py", line 59, in core_select_lib
    fromlist=[modulename], level=0)
  File "/usr/lib64/python2.7/site-packages/kivy/core/window/window_egl_rpi.py", line 12, in <module>
    from kivy.lib.vidcore_lite import bcm, egl

sdl2 - ImportError: /usr/lib64/python2.7/site-packages/kivy/graphics/cgl_backend/cgl_gl.so: undefined symbol: glGetRenderbufferParameteriv
  File "/usr/lib64/python2.7/site-packages/kivy/core/__init__.py", line 67, in core_select_lib
    cls = cls()
  File "/usr/lib64/python2.7/site-packages/kivy/core/window/window_sdl2.py", line 140, in __init__
    super(WindowSDL, self).__init__()
  File "/usr/lib64/python2.7/site-packages/kivy/core/window/__init__.py", line 960, in __init__
    self.create_window()
  File "/usr/lib64/python2.7/site-packages/kivy/core/window/window_sdl2.py", line 272, in create_window
    self.fullscreen, resizable, state)
  File "kivy/core/window/_window_sdl2.pyx", line 125, in kivy.core.window._window_sdl2._WindowSDL2Storage.setup_window
  File "kivy/graphics/cgl.pyx", line 52, in kivy.graphics.cgl.cgl_get_backend_name
  File "kivy/graphics/cgl.pyx", line 60, in kivy.graphics.cgl.cgl_get_backend_name
  File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "kivy/graphics/cgl_backend/cgl_glew.pyx", line 9, in init kivy.graphics.cgl_backend.cgl_glew

x11 - ImportError: No module named window_x11
  File "/usr/lib64/python2.7/site-packages/kivy/core/__init__.py", line 59, in core_select_lib
    fromlist=[modulename], level=0)

[INFO   ] Text: Provider: sdl2
[WARNING] stderr: Traceback (most recent call last):
[WARNING] stderr:   File "./src/main.py", line 40, in <module>
[WARNING] stderr:     MainApp().run()
[WARNING] stderr:   File "/usr/lib64/python2.7/site-packages/kivy/app.py", line 800, in run
[WARNING] stderr:     root = self.build()
[WARNING] stderr:   File "./src/main.py", line 25, in build
[WARNING] stderr:     Window.clearcolor = settings.whiteColor
[WARNING] stderr: AttributeError: 'NoneType' object has no attribute 'clearcolor'


text:
Q: How can I debug TASM programs using GDB debugger? I am using TURBO Assembler with Dos-Box in a 64-bit system. It is working fine and compiling the programs as usual but whenever I try to use Turbo Debugger, it crashes.
I was thinking if there's any way I can use GDB debugger for debugging purposes.
I'm using 64-bit Linux system.
Apart from that is there any way I can use the Turbo assembler directly with the command line? I am fed up of using Dos-Box continuously and whenever I try to use the assembler directly, it shows me this error:


text:
Q: Answers By Crashlytics - adding custom event I have an app using Crashlytics with Answers. Both are working right, and I am seeing events that are built into the framework being tracked.
I am trying to add a custom event, by using the following line of code in my View Controller:
Answers.logCustomEventWithName("Flight Complete", customAttributes: nil)

My issue is that the compiler doesn't recognize the Answers object. It just tells me "Use of unresolved identifier "Answers"" Which makes sense because I've never declared it.
I am unsure of where or how to create this Answers object, as it is already integrated and working for default events. Does anyone know where I should declare it for use across the app? (AppDelegate?) or what the declaration looks like? They don't show it in the docs.
Thanks
UPDATE: Here's what I've tried adding to AppDelegate but still not recognizing "Answers" object...
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    Fabric.with([Crashlytics.self, Answers.self])

A: Wanted to close this question since it is now answered from the comments:
I failed to call
import Crashlytics

At the top of the view controller like a complete idiot.
Also, I had added
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Fabric.with([Crashlytics.self, Answers.self])

When it is correct as:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Fabric.with([Crashlytics.self])

Answers is included in the Crashlytics call.


text:
Q: Why does Mongoose insert null as the last element of the subdocuments array? I have a Mongoose schema with an array of subdocuments, that looks like this:
const cardsSchema = new mongoose.Schema({
  cards: [
    {
      front: String,
      back: String,
      nameOfSuperset: String,
      nameOfSet: String,
    },
  ],
});

const Cards = mongoose.model("Cards", cardsSchema);

I have created a document from the above model, and I am pushing a couple of objects in the array of subdocuments of this document:
exports.createCards = async (req, res, next) => {

  const userCards = await Cards.findById(req.user.cards);

  for (let i = 0; i < req.body.cards.length; i++) {
    userCards.cards.push(req.body.cards[i]);
  }

  const created = await userCards.save();
  console.log(created);

  res.status(201).json({
    status: "success",
  });
};

When I console.log this saved document, or look at it in MongoDB Compass, there is null in the document at the end of the subdocuments array. I am not pushing any empty objects in this document. The original array, from which I get objects to push (req.body.cards) doesn't have null elements or empty objects. I have console.logged it.
What is this null and how can I get rid of it?

A: replace for loop with forEach
req.body.cards.forEach(item=>{
userCards.cards.push(item)
})


text:
Q: некорректное получение значение переменной session flask javascript Отправляю POST-запрос из шаблона следующим образом:
{% block test_block %}
    console.log('FROM test_block ');
    $.ajax({
        data: {
            'service_name':'{{ session['servicename'] }}',
            'master_name': '{{ session['mastername'] }}'
        },
        url: '{{url_for('main.main_get_allow_dates')}}',
        type: 'POST',
        async: false
    }).done(function(){
        console.log('ajax post done!');
        var a = '{{ session['allow_dates'] | safe }}';
    }).fail(function(){
        console.log('ajax post fail!');
    });

{% endblock %}

На сервере происходит по этому POST-запросу некоторая работа, после которой в session['allow_dates'] записывается словарь.
После этого (по идее) в секции .done(...) AJAX-функции должно в консоль вывестись сообщение ajax post done!, а в переменной a оказаться значение словаря, полученного при работе функции на сервере.
Заполнение этой переменной гарантируется тем, что запрос отправляется синхронный (async: false) (хотя тут я не уверен). Вот что происходит при запуске:
<script>

        $(document).bind('ready',function(){
            console.log('from base ready');

    console.log('FROM test_block ');
    $.ajax({
        data: {
            'service_name':'service_1',
            'master_name': 'dima'
        },
        url: '/main_get_allow_dates',
        type: 'POST',
        async: false
    }).done(function(){
        console.log('ajax post done!');
       var a = '';
    }).fail(function(){
        console.log('ajax post fail!');
    });

        })

        ;

    </script>

Как видно из полученного "выхлопа", переменные service_name и master_name корректно заполняются из переменной session, в консоли действительно появляется ajax post done!, однако в переменной a просто пустая строка, хотя там действительно должен появиться словарь (проверял на стороне сервера по таким же входным данным).
Подскажите, пожалуйста, в чём тут проблема?

A: Вы говорите:

На сервере происходит по этому POST-запросу некоторая работа, после
  которой в session['allow_dates'] записывается словарь.

Но пишете в переменную 'a' значение до запроса, в момент выдачи блока на страницу. Вам переменную 'a' нужно получать из js в методе .success( data ){ let a = data }, а не шаблонизатором:
{% block test_block %}
    console.log('FROM test_block ');
    $.ajax({
        data: {
            'service_name':'{{ session['servicename'] }}',
            'master_name': '{{ session['mastername'] }}'
        },
        url: '{{url_for('main.main_get_allow_dates')}}',
        type: 'POST'
    }).success(function( data ){
        console.log('ajax post done!');
        var a = data;
    }).error(function(){
        console.log('ajax post fail!');
    });

{% endblock %}

И

"Заполнение этой переменной гарантируется тем, что запрос отправляется
  синхронный"

не гарантируется, потому что в момент выдачи шаблонизатором кода страницы, запроса не происходит, потому что браузер запускает запрос позже.


text:
Q: Send email with Siganture via Gmail API, Python I'm trying to send an email via the Gmail API using Python, I want to iclude the signature. I'm able to successfuly get the signature using the following funciotn:
def addSignature(service):
    sigtanture = service.users().settings().sendAs().get(userId=USER, sendAsEmail='example@example.com').execute()
    return sigtanture['signature']

addSignature(SERVICE)

However, at the time of creating the message that I'll send, how do I append the Signature?
def CreateMessage(sender, to, subject, message_text, signature):
    message = MIMEMultipart('alternative')
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject
    message[???] = signature

    raw = base64.urlsafe_b64encode(message.as_bytes())
    raw = raw.decode()
    body = {'raw': raw}
    return body

I'm trying to send the message:
thebody = CreateMessage(USER, 'to@example.com', 'TestSignatureAPI','testing', addSignature(SERVICE))
SendMessage(SERVICE, USER, thebody)

Thank you!

A: Unfortunately there is no built-in feature to append the Gmail signature to your email
Instead, once you retrieve your signature as a text, you can simply append it manually to the end of your message_text before encoding.
See also here.
Assuming you retrieved the signature correctly and based on your code this means:
  def CreateMessage(sender, to, subject, message_text, signature):
    message_text = message_text + "\n" + signature
    message = MIMEMultipart('alternative')
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject

    message.attach(MIMEText(message_text_plain, 'plain'))

    raw = base64.urlsafe_b64encode(message.as_bytes())
    raw = raw.decode()
    body = {'raw': raw}
    return body


text:
Q: I am not getting any error but nothing is getting inserted into my database package application;

import java.time.*;
import java.sql.*;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.DatePicker;
import javafx.scene.control.PasswordField;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;

public class SignUpController {

    private String fname;
    private String lname;
    private String username;
    private String password;
    //private LocalDate dob;
    private String gender;
//  private Date date_of_birth;

    @FXML
    private TextField first_name;

    @FXML
    private TextField last_name;

    @FXML
    private DatePicker date;

    @FXML
    private TextField user;

    @FXML
    private PasswordField pass;

    @FXML
    private RadioButton male_rb;

    @FXML
    private RadioButton female_rb;

    @FXML
    public void submitController(ActionEvent event) throws Exception
    {
        //ZoneId defaultZoneId = ZoneId.systemDefault();

        fname=first_name.getText();
        lname=last_name.getText();
        username=user.getText();
        password=pass.getText();
        //dob = date.getValue();

        if(male_rb.isSelected())
        {
            gender=male_rb.getText();
        }
        else
        {
            gender=female_rb.getText();
        }

        try
        {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
            Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl2","scott","root");
            PreparedStatement stmt=con.prepareStatement("insert into users values(?,?,?,?,?);");
            stmt.setString(1,fname);
            stmt.setString(2,lname);
        //  stmt.setDate(3,date_of_birth);
            stmt.setString(3,gender);
            stmt.setString(4,username);
            stmt.setString(5,password);

            con.close();
        }
        catch(Exception e)
        {
            System.out.println(e);
        }

    }

}

I am using javafx and orcl2 database 10g with jdbc 8 jar file.
The code above is for my signup page where I am getting input from textfields and storing it in local variables.Then I am using this local variables to insert into database. When I am clicking database no error or nothing is printed and no row is getting inserted.
Pls help

A: Prepared statement is never executed. Add code to call execute() method.


text:
Q: Silverlight: ImageTools.ExtendedImage Loading External URL Image NOT Working at all I'm using the ImageTools library (imagetools.codeplex.com) to load an image from external URL.
<Canvas x:Name="LayoutRoot" Background="Blue"
        Width="466" Height="204" >

    <Image Name="theImage" />

    <Button x:Name="btnTest" Canvas.Top="0" Canvas.Left="-200" Click="btnTest_Click"
                Width="100" Height="23"
                Content="Test Button">
    </Button>

</Canvas>

Init:
    public MainPage()
    {
        InitializeComponent();

        Encoders.AddEncoder<PngEncoder>();
        Decoders.AddDecoder<PngDecoder>();
        Encoders.AddEncoder<JpegEncoder>();
        Decoders.AddDecoder<JpegDecoder>();
    }

Then:
    private void btnTest_Click(object sender, RoutedEventArgs e)
    {
        ExtendedImage ei = new ExtendedImage();
        // ei.UriSource = new Uri(@"https://www.google.com/images/srpr/logo3w.png"); // NOT working
        ei.UriSource = new Uri(@"/Images/header.png", UriKind.Relative); // Working

        ei.LoadingCompleted += new EventHandler((ss, ee) =>
        {
            Dispatcher.BeginInvoke(() =>
            {
                theImage.Source = ei.ToBitmap();
            });
        });
    }

I found that loading a local file /Image/header.png is working, but loading an external URL image (https://www.google.com/images/srpr/logo3w.png) is not working at all.
It behaves crazy: once I click the Test Button, the LayoutRoot canvas disappears.
However, according to this discussion: http://imagetools.codeplex.com/discussions/250624
Loading an external URL image should be working.

A: Can it be related with UriType ?
Relative,Absolute,RelativeOrAbsolute
ei.UriSource =
new Uri(@"https://www.google.com/images/srpr/logo3w.png"
,UriKind.RelativeOrAbsolute); // works ?

http://msdn.microsoft.com/en-us/library/system.urikind(v=vs.95).aspx
Hope helps!
EDIT: You need a file like that http://twitter.com/crossdomain.xml otherwise SL throws SecurityException normally.
For crossdomain implementation see
https://stackoverflow.com/a/1325011/413032
http://www.silverlighthack.com/post/2008/11/08/Silverlight-clientaccesspolicyxml-files-for-the-Enterprise-(Part-1-of-2).aspx


text:
Q: How to set different variable in a rails partial based on a condition? I need to be able to pull different values from a database based on a condition that's evaluating the same table from the database, i.e. render one partial for several conditions? For example, in my index view, I have:

- @places.each do |place|
    - if place.level == 1
      = render 'place', one: palce
    - elsif place.level == 2
      = render 'place', two: place
     - else
      = render 'place', none: place

Here is my partial:

%table.table
  %caption
    %h2= place.name
  %thead
  %tbody
    %tr
      %td
        Name:
      %td
        = place.place_name
    %tr
      %td
        Total rooms:
      %td
        = place.places_rooms
    %tr
      %td
        Total places:
      %td
        = place.places_count

What should my index page code partial look like?
Many thanks!

A: What condition are you trying to render differently?
I ask because you are passing place as your local, but you designate one, two, and none as the locals, but they don't exist in your partial.  Without some more information, my only guess is that you  should be doing = render 'place', place: place
EDIT as requirement changed:
-@places.each do |place|
  = render 'place, place: place

partial
%table.table
  %caption
    %h2= place.name
  %thead
  %tbody
    %tr
      %td
        Name:
      %td
        = place.try(:"level_#{place.level}_place") || place.place_name
    %tr
      %td
        Total rooms:
      %td
        = place.places_rooms
    %tr
      %td
        Total places:
      %td
        = place.places_count

So I think that would be the way to do it.  But perhaps this should be a hint to you that your tables may be holding a lot of unnecessary fields.  Perhaps it would be better to create a levels table and then have create a relationship between them.

A: Logic in the view layer is an anti-pattern since it makes the view less readable / less tied to the domain language.
Have you considered wrapping your @places in a decorator object of your own creation? Assuming I understand the problem correctly (disclaimer: not 100% sure I do), here's what I might do:
Assuming that your controller is PlacesController...
# app/controllers/places_controller.rb

class PlacesController < ApplicationController
  def index
    @places = PlaceWithLevels.decorate(places)
  end

  private

  def places
    Place.all
  end
end

Now we define the decorator object, PlaceWithLevels (you can probably come up w/ a better name for this, based on your domain):
# app/models/place_with_levels.rb

class PlaceWithLevels < SimpleDelegator
  def self.decorate(places)
    places.map do |place|
      self.new(place)
    end
  end

  # not sure what to name this since I'm not sure what you're
  # trying to accomplish, but note that this is the method we'll
  # be calling in the partial
  def foo
    case levels
    when 0; 'Text you want to show up when there are 0 levels'
    when 1; 'Text you want to show up when there is 1 level'
    when 2; 'Text you want to show up when there are 2 levels'
  end
end

Then, in the view:
# app/views/places/index.html.haml
= render @places

Notice that we don't need to call @places.each since render will call #to_partial_path on each member of the collection in order to figure out which partial to render.
And finally, in the partial (method calls to places_rooms, etc will work here because of our use of SimpleDelegator, above):
# app/views/places/_place.html.haml
%table.table
  %caption
    %h2= place.name
  %thead
  %tbody
    %tr
      %td
        Name:
      %td
        = place.foo
    %tr
      %td
        Total rooms:
      %td
        = place.places_rooms
    %tr
      %td
        Total places:
      %td
        = place.places_count

Notice that we no longer need special logic here...just call the name method (or whatever the appropriate method should be) on our decorator object, but from the perspective of the view, the view doesn't need to know that it's working with anything other than a place.
This technique is also very useful if you need to render a completely different partial depending on the level attribute — simply define your own to_partial_path method on the decorator object, for example:
def to_partial_path
  case level
  when 0; 'zero_level_place'
  when 1; 'single_level_place'
  when 2; 'two_level_place'
end

Hope this helps!!!!
PS: I would also encourage you to also get rid of the places_ prefixes on places_rooms, places_count, etc... better signal/noise ratio.


text:
Q: How can I get the last two digits of any 3+ digit integer? I'm trying to get the last two digits of an int that is a minimum of 3 digits long. Here is my (rather sloppy) attempt:
char[] number = num.ToString().ToCharArray();
int firstnum;
int secondnum;
string strLastTwoDigits = "";
int intLastTwoDigits;
firstnum = number[number.ToString().Length - 1];
secondnum = number[number.ToString().Length - 2];

strLastTwoDigits = (firstnum.ToString() + secondnum.ToString());
intLastTwoDigits = int.Parse(strLastTwoDigits);

The num variable is the number I'm trying to get the last two digits of. I'm trying to turn them into strings and use the string functions to do it, probably not the way it's done. The logic to check whether it's 3 digits or more isn't included, I don't need help with that, just getting those last two digits.
Any ideas?

A: Do you need those two numbers as a String? Or do you plan to convert them back to a number.
Because if you want to have a number at the end, just use the modulo- operator %.
You can find an example on how to use it here: https://www.dotnetperls.com/modulo
Edit: to state the obvious: last2 = number % 100;

A: Just perform a modulo operation.
var intLastTwoDigits = num % 100;

A: You can use the modulo of that number, it should be something like
int lastTwoDigits = num % 100;

This function will divide num / 100and gives you the rest as integer.

A: If you need the last to digits as int, you could just use modulo:
int lasttwo = num % 100;

the modulo operator (%) will return you the remainder of the division of one integer is by another - in this case your number divided by 100 - the remainder will always be the last two digits

A: If you want to use strings for that, string.Substring method will help you
var numString = num.ToString();
var strLastTwoDigits = numString.Substring(numString.Length - 2, 2);
var intLastTwoDigits = int.Parse(strLastTwoDigits);

Another (and more simpler option) is to use remainder % operator for that
int intLastTwoDigits = num % 100;

You get a remainder of division into 100, because you need the 2 last digits


text:
Q: Proof of unitarity of gauge-invariant S-matrix in Peskin and Schroeder I'm reading chapter 9.4 "Quantization of the electromagnetic field" of Peskin's and Schroeder's book.
When proving the unitarity of the gauge-invariant S-matrix, a trick is used.
$$
SS^\dagger=P_0S_\text{FP}P_0S_\text{FP}^\dagger P_0=P_0S_\text{FP}S_\text{FP}^\dagger P_0
$$
The $S$ on the LHS is a gauge-invariant S-matrix while the $S$ on the RHS is unitary but not gauge-invariant. $P_0$ is a projection onto the subspace of the space of asymptotic states in which all particles are either electrons, positrons, or transverse photons.
In the formula shown above, how is the $P_0$ in the middle removed?

A: "Let $S_{FP}$ be the $S$-matrix between general asymptotic states, computed from the Fadeev-Popov procedure". If I understand it correctly when $S_{FP}$ acts on asymptotic states it produces also asymptotic states. Therefore, the projection in the middle is redundant.


text:
Q: JavaFX PixelWriter low performance I created a simple JavaFX image editor. There are two instances of ImageView (on for the original image and one for the edited one).
A method converts the WritableImage to grayscale.
The problem is, the conversion takes approximately twice the time Swing needs to do the same task. Any idea why?
@FXML
void loadImage(ActionEvent event) {
    FileChooser fileChooser = new FileChooser();
    File file = fileChooser.showOpenDialog(Main.primaryStage);
    if (file != null) {
        Image image = new Image("file:" + file.getAbsolutePath());
        imViewOrig.setImage(image);
        PixelReader pr = imViewOrig.getImage().getPixelReader();
        WritableImage wi = new WritableImage(
            pr,
            (int)imViewOrig.getImage().getWidth(),
            (int)imViewOrig.getImage().getHeight());
        imViewEdit.setImage(wi);
    }
}

@FXML
void greyscale(ActionEvent event) {
    PixelReader pr = imViewOrig.getImage().getPixelReader();
    PixelWriter pw = ((WritableImage)imViewEdit.getImage()).getPixelWriter();
    long beginTime = System.currentTimeMillis();
    for (int x = 0; x < imViewEdit.getImage().getWidth(); x++) {
        for (int y = 0; y < imViewEdit.getImage().getHeight(); y++) {
            Color c = pr.getColor(x, y);
            double avg = (c.getRed() + c.getGreen() + c.getBlue()) / 3.;
            Color grey = new Color(avg, avg, avg, c.getOpacity());
            pw.setColor(x, y, grey);
        }
    }
    System.out.println(System.currentTimeMillis() - beginTime + "ms");
}

Swing code:
public void greyscale() {
    long beginTime = System.currentTimeMillis();
    for (int x = 0; x < image.getWidth(); x++) {
        for (int y = 0; y < image.getHeight(); y++) {
            Color c = new Color(image.getRGB(x, y));
            int avg = (c.getRed() + c.getGreen() + c.getBlue()) / 3;
            Color grey = new Color(avg, avg, avg);
            image.setRGB(x, y, grey.getRGB());
        }
    }
    repaint();
    System.out.println(System.currentTimeMillis() - beginTime + "ms");
}

A: In a quick test, it works of the order of 10 times faster if you just do the int computations, instead of manipulating Color objects. The JavaFX Color class is a substantially richer implementation than the AWT Color class; I guess this comes at a cost of additional overhead.
    int width = (int)image.getWidth();
    int height = (int)image.getHeight();

    int[] pixels = new int[width * height];
    WritablePixelFormat<IntBuffer> pixelFormat = PixelFormat.getIntArgbPreInstance();
    pr.getPixels(0, 0, width, height, pixelFormat, pixels, 0, width);

    int[] newPixels = new int[pixels.length];
    for (int i = 0 ; i < pixels.length; i++) {
        int c = pixels[i];
        int a = c & 0xFF000000 ;
        int r = (c >> 16) & 0xFF ;
        int g = (c >> 8) & 0xFF ;
        int b = c & 0xFF ;
        int gray = (r+g+b) / 3 ;
        newPixels[i] = a | (gray << 16) | (gray << 8) | gray ;
    }

    pw.setPixels(0, 0, width, height, pixelFormat, newPixels, 0, width);

A: ColorAdjust based sample which converts a color image to monochrome by desaturating it when you mouse-over the image.
Given appropriate hardware (which is available to most systems JavaFX runs on), the JavaFX runtime may perform some of the implementation of the color adjustment in hardware, which might lead to a more efficient implementation than manipulating pixels using a PixelWriter.

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.scene.*;
import javafx.scene.effect.*;
import javafx.scene.image.*;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class Shadow extends Application {
    @Override
    public void start(Stage stage) throws Exception {
        Image image = new Image(
                "http://icons.iconarchive.com/icons/designbolts/smurfs-movie/512/smurfette-icon.png"
        );

        ImageView imageView = new ImageView(image);

        ColorAdjust monochrome = new ColorAdjust();
        monochrome.setSaturation(-1.0);

        imageView.effectProperty().bind(
                Bindings
                    .when(imageView.hoverProperty())
                        .then(monochrome)
                        .otherwise((ColorAdjust) null)
        );

        stage.setScene(new Scene(new Group(imageView), Color.AQUA));
        stage.show();
    }

    public static void main(String[] args) {
        Application.launch();
    }
}


text:
Q: Qt SQLite Insert doesn't work —— The table is still empty after do INSERT At first,there is only one table in my database... and all the operations like INSERT, SELECT works well,then I add another table but I didn't change my code of operations on first table...
then when I do INSERT,the first table turn out to be still empty.
here is the table schema:
QString CreateHistoryTable="CREATE TABLE History("
                        "hist_code VARCHAR(50) PRIMARY KEY,"
                        "input_data TEXT NOT NULL,"
                        "output_data TEXT NOT NULL)";

here is the CREATE code:
void CreateHistory(){
    if(!db.isOpen())
        db.open();
    // judge if table 'History' is existed. IMPORTANT.
    bool isTableExist = query.exec(QString("select count(*) from sqlite_master where type='table' and name='History';")                                   );
    if(!isTableExist)
    {
        if (!query.exec(CreateHistoryTable))
            QMessageBox::critical(0, QObject::tr("Create History Table Error"),
                                  query.lastError().text());
        query.finish();
    }
    else
        return;
}

and the table is created properly as I can see in SQLitemanager..
then the INSERT operation function:
QString Insert_History="INSERT INTO History
                     (hist_code,input_data,output_data) "
                    "VALUES (:hist_code,:input_data,:output_data);";

    void InsertHistory(){
        if(!db.isOpen())
            db.open();
        query.prepare(Insert_History);
        InputToString input2str(in_temp);
        OutputToString output2str(out_temp);
        int num=QueryRunTimes();
        QString histcode=QDateTime::currentDateTime().toString("yyyy-MM-dd")+QString::number(num,10);
        query.bindValue(":hist_code",histcode);
        query.bindValue(":input_data",input2str.getAll());
        query.bindValue(":output_data",output2str.getAll());
        if (!query.exec())
                QMessageBox::critical(0, QObject::tr("Insert History Error"),
                                      query.lastError().text());
        query.finish();
    }

after call this function,the table is still empty...but if I do specific INSERT like:
query.exec("INSERT INTO History (hist_code,input_data,output_data) "
                        "VALUES ('1234','aaaaa','bbbbbbb';");

It works well,which really confused me......


text:
Q: SiteWise not consistent in generating metrics for late data First of all, very nice that SiteWise now allows ingestion of data that is up to 7 days old: https://aws.amazon.com/about-aws/whats-new/2020/11/aws-iot-sitewise-now-allows-ingestion-of-data-up-to-7-days-in-past/
And I can confirm that, as long as the late data is less than 7 days old, SiteWise will accept the data. From the SiteWise monitor dashboard, I can see the late sensor data measurements, as well as their transforms, always show up.
However, AWS IoT SiteWise seems not consistent in calculating (or recalculating) related metrics on arrival of late data. In my experiment, sometimes the metrics are generated, while sometimes they are not, as shown in this dashboard:

Any insight? Thank you.
FYI:
Sometimes the metrics do get generated.
Before ingesting late data, notice that there is no data between 13:37:09 and 14:00:00

After ingesting late data, we can see that SiteWise accepts the data and recognises the lateness of the data, the metrics are generated.


text:
Q: I'm using ROS noetic over wsl in Windows 11, but rospy library is not loaded in VS code This is the error I get through the terminal, I wonder if vs code and ros are not integrated vs code because I installed it through windows

A: To work properly with VSCode you need to install the ROS VSCode extension. The wiki also currently has an entry for VSCode support.


text:
Q: Mailchimp cart content block I am creating a website with mailchimp integration using their API. I am using their drag and drop cart block content feature, it seems that the price that is reflected in that block is not the price of the cart but the price of the product.
My first solution is to get the price using a cart merge tag, I have been searching for merge tags but cant find any website that provides me this merge tags.
I would like to use the cart price instead, does anyone knows how can I put the cart price? I've been looking for solution for this problem all day. I hope one of you can help me.
Thank you.
Check this video as well
https://www.youtube.com/watch?v=nTi4nU8ZOj0

A: You can use the merge tag ABANDONED_CART to create custom html for abandoned cart emails.
Example:

    *|ABANDONED_CART:[$total=3]|*

        *|PRODUCT:TITLE|*
        *|PRODUCT:PRICE|*

    *|END:ABANDONED_CART|*

Go to Cart

The $total=3 in the ABANDONED_CART tag changes the number of products that will be shown.
*|CART:URL|* - Generates the url for your cart.

A: This doesn't seem possible. Here's a very recent list of available tags from mailchimp . There's no CART block or CART_PRICE tag.
I contacted mailchimp support with a similar query.
ME:

I'd like to customize the contents of the cart
  block. The test emails/ abandoned carts I have created use the
  checkout_url as the product image link within the template. Is it
  possible to have the cart block product image link url set to that of
  the product or the product link variant?
If that is not possible is there an equivalent PRODUCT_CART tag to
  PRODUCT_RECOMMENDATIONS as documented here
  http://kb.mailchimp.com/merge-tags/all-the-merge-tags-cheat-sheet#Merge-Tags-for-Product-Recommendations
  that I could use to construct my own abandoned cart email, not using the
  predefined cart block drag and drop content block.
In summary:
1) Within the cart block is it possible to have the product images link
  to the products and not the checkout_url?
2) Is there a tag not listed in
  http://kb.mailchimp.com/merge-tags/all-the-merge-tags-cheat-sheet to
  iterate over cart products?

SUPPORT:

There is not a way to change the URL linked to the product image. Additionally, those products must be pulled in using the abandoned cart content blocks, and cannot be populated using a merge tag.
That being said, I do agree these would be great options to have, and I would be happy to pass that feedback along for you. Our developers monitor these suggestions and often use that feedback for future versions of the application. So thank you for giving us your idea, as it may be very useful for a lot of our users in the future.
  Let us know if you have any other questions on this, and have a great rest of your day.


text:
Q: Displaying a custom view in a layout I currently have a class called clientActivity that contains a finger paintig activity that draws onto a canvas, the class has a extension of View Called MyView. I want to make it so that the canvas appears in a relative layout on my xml chat layout.
This is the class ClientActivity
public class ClientActivity extends GraphicsActivity
implements ColorPickerDialog.OnColorChangedListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(new MyView(this));
    mPaint = new Paint();
    mPaint.setAntiAlias(true);
    mPaint.setDither(true);
    mPaint.setColor(Color.BLACK);
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setStrokeJoin(Paint.Join.ROUND);
    mPaint.setStrokeCap(Paint.Cap.ROUND);
    mPaint.setStrokeWidth(20);

    mEmboss = new EmbossMaskFilter(new float[] { 1, 1, 1 },
            0.4f, 6, 3.5f);

    mBlur = new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL);

}

private Paint       mPaint;
private MaskFilter  mEmboss;
private MaskFilter  mBlur;

public void colorChanged(int color) {
    mPaint.setColor(color);
}

public class MyView extends View {

    ClientNetwork net = new ClientNetwork();

    private static final float MINP = 0.25f;
    private static final float MAXP = 0.75f;

    private Bitmap  mBitmap;
    private Canvas  mCanvas;
    private Path    mPath;
    private Paint   mBitmapPaint;

    public MyView(Context c) {
        super(c);

        mPath = new Path();
        mBitmapPaint = new Paint(Paint.DITHER_FLAG);
        Thread fred = new Thread(net);
        fred.start();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(mBitmap);

    }

My chat.xml looks like this.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical" android:weightSum="1">

<RelativeLayout android:id="@+id/relativeLayout3"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_weight="0.83">

<com.DrawTastic.ClientActivity android:id="@+id/MyView1"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="center"/>

</RelativeLayout>

<ListView
android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="152dp" android:layout_weight="0.17">
    </ListView>

    <RelativeLayout
    android:id="@+id/relativeLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true">

        <EditText
        android:layout_width="232dp"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_height="wrap_content"
            android:id="@+id/input">
            </EditText>

        <Button
        android:layout_width="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_marginRight="16dp"
            android:layout_alignParentRight="true"
            android:text="Send"
            android:onClick="sent" android:id="@+id/send"
            android:layout_height="wrap_content">
            </Button>

    </RelativeLayout>

I just need the canvas to appear in the the chat.xml inside one of the layouts so I can lay a listview beneath it.
Any help is greatly appreciated!
Thanks
EDIT: Stack trace.
03-22 15:32:21.310: ERROR/AndroidRuntime(1301): FATAL EXCEPTION: main
03-22 15:32:21.310: ERROR/AndroidRuntime(1301): java.lang.RuntimeException: Unable to     start activity ComponentInfo{com.DrawTastic/com.DrawTastic.GameActivity}:     android.view.InflateException: Binary XML file line #8: Error inflating class     com.DrawTastic.ClientActivity.MyView
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     at         android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     at     android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     at     android.app.ActivityThread.access$1500(ActivityThread.java:117)
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
       03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     at android.os.Looper.loop(Looper.java:123)
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     at android.app.ActivityThread.main(ActivityThread.java:3683)
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     at java.lang.reflect.Method.invokeNative(Native Method)
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     at java.lang.reflect.Method.invoke(Method.java:507)
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     at dalvik.system.NativeStart.main(Native Method)
03-22 15:32:21.310: ERROR/AndroidRuntime(1301): Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class com.DrawTastic.ClientActivity.MyView
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:581)
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:623)
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:626)
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     at android.view.LayoutInflater.inflate(LayoutInflater.java:408)
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:207)
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     at android.app.Activity.setContentView(Activity.java:1657)
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     at com.DrawTastic.GameActivity.onCreate(GameActivity.java:13)
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     ... 11 more
03-22 15:32:21.310: ERROR/AndroidRuntime(1301): Caused by: java.lang.ClassNotFoundException: com.DrawTastic.ClientActivity.MyView in loader     dalvik.system.PathClassLoader[/data/app/com.DrawTastic-2.apk]
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     at android.view.LayoutInflater.createView(LayoutInflater.java:471)
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:570)
03-22 15:32:21.310: ERROR/AndroidRuntime(1301):     ... 21 more

A: you need to declare your Custom view like this in your layout chat.xml :
//Notice that i've added .MyView

<com.DrawTastic.ClientActivity.MyView  android:id="@+id/MyView1"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="center"/>

another thing , you should Override other Consturctors of the View in your MyView class like this :
public MyView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

public MyView(Context context, AttributeSet attrs ) {
    super(context, attrs);
}

EDIT :
about the problem that you got , you should declare your Activity in your Manifest file like this :
<activity android:name=".YourActivity" />

A: You would need <com.DrawTastic.ClientActivity.MyView... since that points to the actual View you want to add


text:
Q: É possível ter um ternário sem o bloco else? Existe a possibilidade de cria um if ternário mais simples, digo sem o código do bloco else? como ficaria?
tipo :
if($total < 10){
 $total_gerente = 10;
}

Pois pelo que sei o ternário tem IF e ELSE. Existe possibilidade de apenas ter o bloco if?

A: Traduzindo o código da pergunta para uma condição ternária:
$total_gerente = (($total < 10)? 10: null);

Recomendado delimitar a condição com parênteses para evitar problemas com erros de sintaxe.
Alternativamente, pode fazer assim, caso não queria setar um valor específico na condição contrária
($total < 10)? $total_gerente = 10: null;

Nota:
Deve estar ciente de que as ações não deve ter mais que uma linha.
Exemplo de código que gera erro
($total < 10)? $total_gerente = 10; $outra_var = 'foo': null;

Quando houver tal necessidade pode usar técnicas com funções anônimas, mas como isso não faz parte da pergunta, me abstenho e aprofundar mais sobre o assunto.

A: Você pode deixar mais simples de algumas formas:
1º
if($total < 10) $total_gerente = 10;

2º
  if($total < 10) :
      $total_gerente = 10;
  endif;

3º
if($total < 10)
    $total_gerente = 10;

Espero ter ajudado.


text:
Q: multiline notification in android different behaviour in different device I am trying to display notification text in multiline.
I am using this code to do so.
    NotificationManager mNotificationManager;
    String msg = "Do you want to share Fantasy Cricket on Twitter/FB/Google+?";

    mNotificationManager = (NotificationManager) this
            .getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            this).setSmallIcon(R.drawable.app_icon)

    .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
            .setContentText(msg).setAutoCancel(true);

    mBuilder.setContentTitle("Change team");
    mNotificationManager.notify(notId, 123, mBuilder.build());

It's displaying differently in two devices.
First device

Second device

In first device it just displays fine text in multiline but in second, it's displaying in one line only removing trailing space.
Why it's having different behavior in both. Am I missing something here? Both device are having kitkat if that makes any difference.
UPDATE
As per @leo's answer it will display in two line when there is only single notification. But I checked TOI app it's always displaying in two lines.
TOI's screenshot

A: Docs say only the top notification is expanded by default. So maybe the other app you are comparing to is using a completely custom notification layout (especially since I don't see a title there)?

A: In case someone falls into it like me, so according to LINK
Users can drag down on a notification in the drawer to reveal the expanded view, which shows additional content and action buttons, if provided. This happens often on Samsung devices though...


text:
Q: how to secure $_GET I'm trying to secure my $_GET inputs everything are working the problem is $_GET['action'] can't pass preg_match() and always resulta in:

"action is not valid"

I don't know why it's happening, the action can have only two values like or hate which both are in lowercase but still can't pass it.
if(isset($_GET['username']) && isset($_GET['action']))
{
    $username = $_GET['username'];
    $action = $_GET['action'];

    $user_filter_a = mysqli_real_escape_string($username);
    $user_filter_b = mysqli_real_escape_string($user_filter_a);
    $user_filter_c = strip_tags($user_filter_b);

    $action_filter_a = mysqli_real_escape_string($action);
    $action_filter_b = mysqli_real_escape_string($action_filter_a);
    $action_filter_c = strip_tags($action_filter_b);
    $action_filter_c_lower = strip_tags($action_filter_b);

    if(preg_match('%^[a-z0-9\.]{4,69}$%',$user_filter_c))
    {
        if(preg_match('%^[a-z]$%',$action_filter_c_lower))
        {
           if($action_filter_c_lower=='like')
           {
               echo 'you have liked this post';
           }elseif(action_filter_c_lower=='hate')
           {
               echo 'you have hated this post';
           }
        }else
        {
            echo 'action is not valid';
        }
    }else
    {
        echo 'username is not valid';
    }

A: When you need to validate that a string is completely comprised of letters, you can use ctype_alpha().
Code: (Demo)
$string = 'asdgadsfg';
if (ctype_alpha($string)) {
    echo "all alphabetical";
} else {
    echo "not entirely alphabetical";
}

Output:
all alphabetical

If you need to check if a submitted value is like, hate, or [something else]; create a "whitelist" array to look up the value.
Code: (Demo)
$string = 'like';
$whitelist = ['like', 'hate'];
if (in_array($string, $whitelist)) {
    echo "valid: $string";
} else {
    echo "invalid: $string";
}

Output:
valid: like

Additional tips:
if(isset($_GET['username']) && isset($_GET['action']))

can be written more simply as:
if (isset($_GET['username'], $_GET['action'])) {

You shouldn't be performing escaping until just before applying the data to the query, this way you don't accidentally mangle your data or confuse yourself.  Honest, I always use prepared statements to build a query with user-submitted data, so I'll recommend that you research that topic.
In your regular expression, you don't need to escape a dot inside of a character class so the character class can look like this: [a-z0-9.]  If you also wish to allow capital letters, you can add i after the end pattern delimiter (%) so that it looks like %^[a-z0-9.]{4,69}$%i  or %^[a-z\d.]{4,69}$%i.
_lower is a strange thing to append to your variable name, because you aren't calling any functions that force the string to lowercase.

A: The total number of actions is limited. It is more secure to not use the user input at all. Instead, use a switch statement with a default action:
$userAction = strtolower($_GET['action']);
switch($userAction) {
    case "like":
        $action = "like";
        break;
    case "hate":
        $action = "hate";
        break;
    default:
        $action = "default-action";
}

Or, you can have the list of valid actions in an array:
$validAction = ["like","hate","other"];
$action = "";
if (in_array($_GET["action"],$validAction)){
    $action = $_GET["action"];
}

Here you have the guarantee that the action is valid.


text:
Q: XeLaTex : Math fonts : different output between Linux and Windows I'm using XeLaTeX to typeset documents containing maths, and using the Libertine font with some packages to get it working in math mode. However, whereas the output is fine on Windows with MikTex, the math font is broken when building in Linux with TeXlive. (see screenshots and MWE below)
\documentclass[12pt,a4paper]{article}

\usepackage[libertine,frenchmath]{newtxmath}
\usepackage{mathspec}
\usepackage{MnSymbol}\undef\mathdollar
\usepackage{libertine}
\begin{document}

These two $N$ N does not look the same on Linux.

\end{document}

Edit : Here is the log of Linux build :https://pastebin.com/raw/H0nrSPV4
And the Windows one : https://pastebin.com/raw/5ejbs5g1

A: You didn't show the log-files but only the terminal output so a lot details are missing. But your texsystem on linux is at least two years older than your miktex system and this quite probably is the reason for the difference.
Beside this: you are loading four package which are trying to change the math setup (newtxmath, mathspec, mnsymbol and through libertine fontspec). That is not a good idea. Better use only the one you really need and load fontspec with the no-math option, e.g.
\documentclass[12pt,a4paper]{article}

\usepackage[libertine,frenchmath]{newtxmath}
\usepackage{MnSymbol}

\usepackage[no-math]{fontspec}
\usepackage{libertine}
\begin{document}

These two $N$ N does not look the same on Linux.

\end{document}


text:
Q: How to load data in the body property using flutter + (bloc) Pattern Hello friends,
I have been learning to use flutter for weeks, I am creating an app that I develop as I learn to program in flutter.
My idea is to be able to follow the Pattern (BLoC). What I want to do now is like being able to load the movie data list into the home.dart file in the body property
I appreciate your help!
home.dart
import 'package:eva_icons_flutter/eva_icons_flutter.dart';
import 'package:flutter/material.dart';
import 'package:skyshowapp/styles/theme.dart' as Style;

class HomeScreen extends StatefulWidget{
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen>{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Style.Colors.mainColor,
      appBar: AppBar(
        backgroundColor: Style.Colors.mainColor,
        centerTitle: true,
        leading: Icon(EvaIcons.menu2Outline , color: Colors.white),
        title: Text("SKYSHOW APP"),
        actions: <Widget>[
          IconButton(icon: Icon(EvaIcons.searchOutline , color: Colors.white,), onPressed: null,)
        ],
      ),
      body: ListView(
        children: <Widget>[

        ],
      ),
    );
  }
}

movie_bloc.dart
import 'package:rxdart/subjects.dart';
import 'package:skyshowapp/model/movie.dart';
import 'package:skyshowapp/repository/repository.dart';

class MovieListBloc{
  final MovieRepository _repository = new MovieRepository();
  final BehaviorSubject<MovieRootClass> _subject = new BehaviorSubject<MovieRootClass>();

  getMovies() async{
    MovieRootClass response = await _repository.getMovies();
    _subject.sink.add(response);
  }

  dispose(){
    _subject.close();
  }

  BehaviorSubject<MovieRootClass> get subject => _subject;
}

final movieBloc = new MovieListBloc();

class MovieRootClass {
  List<Movies> movies;

  MovieRootClass({this.movies});

  MovieRootClass.fromJson(Map<String, dynamic> json) {
    if (json['movies'] != null) {
      movies = new List<Movies>();
      json['movies'].forEach((v) {
        movies.add(new Movies.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.movies != null) {
      data['movies'] = this.movies.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Movies {
  String id;
  String title;
  String sinopsis;
  String poster;
  String rating;
  String quality;
  String year;
  List<Extra> extra;

  Movies(
      {this.id,
      this.title,
      this.sinopsis,
      this.poster,
      this.rating,
      this.quality,
      this.year,
      this.extra});

  Movies.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    title = json['title'];
    sinopsis = json['sinopsis'];
    poster = json['poster'];
    rating = json['rating'];
    quality = json['quality'];
    year = json['year'];
    if (json['extra'] != null) {
      extra = new List<Extra>();
      json['extra'].forEach((v) {
        extra.add(new Extra.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['title'] = this.title;
    data['sinopsis'] = this.sinopsis;
    data['poster'] = this.poster;
    data['rating'] = this.rating;
    data['quality'] = this.quality;
    data['year'] = this.year;
    if (this.extra != null) {
      data['extra'] = this.extra.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

// Extra class .....

A: You can use StreamBuilder widget which takes in a stream, and rebuilds itself when ever new data is added to the stream.
StreamBuilder(
  stream: subject.stream,
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return ListView.builder(
        itemCount: snapshot.data.movies.length,
        itemBuilder: (BuildContext context, int idnex) {
          return ListTile(
            title: Text(snapshot.data.someProperty),
          );
        },
      );
    }
    return const CircularProgressIndicator();
  },
);


text:
Q: How to set docker run arguments on marathon spec I have been using docker to run images along with some options like:
docker run --net host --oom-kill-disable -d -p <port>:<port> image

How do I set values like --oom-kill-disable on marathon?

A: It is required for docker containers in their marathon spec to specify a boolean value for oom-kill-disable flag for executor to run properly.
So the spec would include:
"parameters": [
            { "key": "oom-kill-disable", "value": "true" }
        ]

A: I'm not quite sure if you can pass an empty value in this case, but you could go with something like this:
"container": {
    "type": "DOCKER",
    "docker": {
        "network": "HOST",
        "image": "your/image",
        "parameters": [
            { "key": "oom-kill-disable", "value": "" }
        ]
    }
}

You may read a little bit more here in "Privileged Mode and Arbitrary Docker Options" section.


text:
Q: Textarea at 100% width fills container but div at 100% width expands the parent I'm having an interesting problem that I'm hoping someone can help with. I have a textarea that when set at 100% width, fills the parent div that it's in. HOWEVER, if I replace that with a div, the div blows out the parent divs width to now fit the child's content instead of wrapping.
I've tried various approaches (display:inline-block, display:table, display:table-cell, box-sizing...) I've used span, div, p and table/tr/td.. all result in the following overflow.

I've inspected the source, and all I see is the textarea's width being set to 100% with no other styles affecting it.
Is there's an attribute I'm missing when I'm inspecting?

A: My guess is that you simply need to utilize border box:
*{ box-sizing: border-box; }

A: Basically, your div might have padding also. Now when you add the padding with width: 100%, the child will basically overflow the parent cause of the extra padding.
To include padding within the width try providing your div a box-sizing: border-box;.
You can read more about box-sizing here.

A: Due to the complexity of the application, I'll need to strip it down to the basics and figure it out. I was hoping that there was a structural component of the textarea that I didn't know about.
Thanks,


text:
Q: How to use map and grep in Perl for following data How to display only the chains (such as A, C, E, G) which end with a semicolon ;
Data
COMPND    MOL_ID: 1;
COMPND   2 MOLECULE: JACALIN;
COMPND   3 CHAIN: A, C, E, G;
COMPND   4 SYNONYM: JACKFRUIT
AGGLUTININ;
COMPND   5 MOL_ID: 2;
COMPND   6 MOLECULE: JACALIN;
COMPND   7 CHAIN: B, D, F, H;
COMPND   8 SYNONYM: JACKFRUIT AGGLUTININ

I tried the below code
#!usr/local/bin/perl

open(FILE, "/home/httpd/cgi-bin/r/1JAC.pdb");

while ( $line = <FILE> ) {

    if ( $line =~ /^COMPND/ ) {

        #$line = substr $line,4,21;

        my $line =~ m(/\$:^\w+\$\;/g);
        print $line;
    }
}

A: perl -nle'print $1 if /^COMPND\s+\S*\s*CHAIN:(.+);/' /home/httpd/cgi-bin/r/1JAC.pdb

This is a fairly simple method of "grepping" part of a line to standard output. It will capture everything in the parentheses and print it.

*

*-n uses a while(<>) loop to read data from your file

*-l handles newlines

A: You can use a single regular expression like the following:
while (my $line = <FILE>) {
    if ($line =~ /^COMPND.+?CHAIN:\s*(.*?)\s*;\s*$/) {
        my $chain = $1;
        print "$chain\n";
    }
}

This uses a regular expression to match COMPND, CHAIN and an ending ;. The \s* at the end of the regular expression will match any trailing spaces. It will capture the string between CHAIN: and ; excluding trailing and leading spaces in $1 which is set as the value for the $chain variable.
More information on Perldoc: Perlre - Perl regular expressions.

A: You may like this one-line solution
perl -le 'print for map /CHAIN:\s*([^;]+)/, <>' /home/httpd/cgi-bin/r/1JAC.pdb

output
A, C, E, G
B, D, F, H

A: Using GNU grep with perl regular expressions: find the text between "CHAIN:" and the semicolon
$ grep -oP '(?<=CHAIN: ).*?(?=;)' filename
A, C, E, G
B, D, F, H

A: Try this
use warnings;
use strict;
open my $nis,"<1jac.pdb";
my @ar = grep{ m/^COMPND/g} <$nis>;
my $s = join("",@ar);
my @dav;
my @mp2  = map{split(/,\s|,/, $_)} grep{ s/(COMPND\s+\d+\s+(CHAIN\:\s+)?)|(\n|;)//g} @dav= $s =~m/(COMPND\s+\d+\s+CHAIN\:.+?(?:.|\n)+?\;)/g;
$, = ", ";
print @mp2;

Output
A, C, E, G, B, D, F, H


text:
Q: sbt.bat for windows I'm new to Scala.
I just installed sbt for windows MSI
I have a project with build.sbt
I opened a windows console in the current project folder.
I runned the sbt.bat
I turned @echo on to get the error message.
C:\MasseGuillaume-Scala99-1879ed7>sbt

C:\MasseGuillaume-Scala99-1879ed7>set SBT_HOME=C:\MasseGuillaume-Scala99-1879ed7
\

C:\MasseGuillaume-Scala99-1879ed7>set ERROR_CODE=0

C:\MasseGuillaume-Scala99-1879ed7>rem We use the value of the JAVACMD environmen
t variable if defined

C:\MasseGuillaume-Scala99-1879ed7>set _JAVACMD=

C:\MasseGuillaume-Scala99-1879ed7>if "" == "" (if not "" == "" (if exist "\bin\j
ava.exe" set "_JAVACMD=\bin\java.exe" ) )

C:\MasseGuillaume-Scala99-1879ed7>if "" == "" set _JAVACMD=java

C:\MasseGuillaume-Scala99-1879ed7>rem We use the value of the JAVA_OPTS environm
ent variable if defined

C:\MasseGuillaume-Scala99-1879ed7>set _JAVA_OPTS=

C:\MasseGuillaume-Scala99-1879ed7>if "" == "" set _JAVA_OPTS=-Xmx512M -XX:MaxPer
mSize=256m -XX:ReservedCodeCacheSize=128m -Dsbt.log.format=true

C:\MasseGuillaume-Scala99-1879ed7>"java" -Xmx512M -XX:MaxPermSize=256m -XX:Reser
vedCodeCacheSize=128m -Dsbt.log.format=true  -cp "C:\MasseGuillaume-Scala99-1879
ed7\jansi.jar;C:\MasseGuillaume-Scala99-1879ed7\sbt-launch.jar;C:\MasseGuillaume
-Scala99-1879ed7\classes" SbtJansiLaunch
'"java"' n'est pas reconnu en tant que commande interne
ou externe, un programme exécutable ou un fichier de commandes.

C:\MasseGuillaume-Scala99-1879ed7>if ERRORLEVEL 1 goto error

C:\MasseGuillaume-Scala99-1879ed7>set ERROR_CODE=1

C:\MasseGuillaume-Scala99-1879ed7>exit /B

the error is in this line :
"%_JAVACMD%" %_JAVA_OPTS% %SBT_OPTS% -cp "%SBT_HOME%jansi.jar;%SBT_HOME%sbt-launch.jar;%SBT_HOME%classes" SbtJansiLaunch %*

What should I add to fix it ? The error says that it's Java is not recognized as an internal or an external command or programm.
I just don't get the message error. If I put the sbt.bat and jansi.jar and sbt-launch.jar in the C:\Program Files (x86)\Java\jre6\bin and i run the batch file, it's working.
Any solutions ?

A: I'll admit that I haven't done much French in the thirty-odd years since I left school (other than helping out the kids) but:

'"java"' n'est pas reconnu en tant que commande interne ou externe, un programme exécutable ou un fichier de commandes.

looks suspiciously like:

'"java"' is not recognised as a command internal or external, a program executable or a file of commands.

This is the old favourite 'something' is not recognized as an internal or external command, operable program or batch file that Windows tosses out when it can't find what you're trying to run.
So it sounds like you need to install a Java run-time environment, or modify your path to point to one that's already installed. Since you apparently have a C:\Program Files (x86)\Java\jre6\bin directory, I'd suggest the latter.
Go in to the control panel, select System then Advanced System Settings, choose the Advanced tab, then the Environment Variables button.
Then modify your path to include the JRE bin directory. After saving that, open another cmd window and verify it with path. That's needed to check (and use) the new path since it only affects new sessions, not existing ones.
Note those instructions are for Win 7, it may vary a little on other versions but the concept will be the same.
Alternatively, if you don't want to fiddle with the path in your control panel, you can change it in that batch file with something like:
set path="%path%;C:\Program Files (x86)\Java\jre6\bin"

That way, it will only be in effect when you're running the batch file.


text:
Q: how to implement umano/AndroidSlidingUpPanel lib My App has a map fragment . And on clicking marker , an slide up animation shows from bottom to half of screen . And it slide down on clicking marker again .

I want : Slide up menu should be clickable or drag gable so that it
  can move to top of screen .  to be more clear , i mean either on
  clicking or dragging this slide up menu which is on half of screen ,
  should go to top of screen .

So far i done : On clicking marker, call the slide up animation to half of screen. :
Animation code : slide_up.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <objectAnimator
            android:interpolator="@android:anim/accelerate_decelerate_interpolator"
            android:propertyName="yFraction"
            android:valueType="floatType"
            android:valueFrom="1.0"
            android:valueTo="0.58"
            android:duration="@android:integer/config_mediumAnimTime"/>
    <objectAnimator
            android:interpolator="@android:anim/accelerate_decelerate_interpolator"
            android:propertyName="alpha"
            android:valueType="floatType"
            android:valueFrom="0.58"
            android:valueTo="1.0"
            android:duration="@android:integer/config_mediumAnimTime"/>
</set>

slide_down.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <objectAnimator
            android:interpolator="@android:anim/accelerate_decelerate_interpolator"
            android:propertyName="yFraction"
            android:valueType="floatType"
            android:valueFrom="0.58"
            android:valueTo="1.0"
            android:duration="@android:integer/config_mediumAnimTime"/>
    <objectAnimator
            android:interpolator="@android:anim/accelerate_decelerate_interpolator"
            android:propertyName="alpha"
            android:valueType="floatType"
            android:valueFrom="1"
            android:valueTo="0"
            android:duration="@android:integer/config_mediumAnimTime"/>
</set>

The code in Activity which calling this Animation on Marker click :
 public void toggleList() {
        Fragment f = getFragmentManager().findFragmentByTag(LIST_FRAGMENT_TAG);

        if (f != null) {
            getFragmentManager().popBackStack();
        } else {
            getFragmentManager()
                    .beginTransaction()
                    .setCustomAnimations(R.anim.slide_up,
                            R.anim.slide_down,
                            R.anim.slide_up,
                            R.anim.slide_down)
                    .add(R.id.list_fragment_container, BaseMapSlidingFragment
                                    .instantiate(this, BaseMapSlidingFragment.class.getName()),
                            LIST_FRAGMENT_TAG
                    )
                    .addToBackStack(null).commit();
            googleMap.getUiSettings().setAllGesturesEnabled(false);
            if(animCheck == false){
                animCheck = true;
                }else
            {
                    animCheck= false;
            }

        }}

menu_Sliding.up.xml
<?xml version="1.0" encoding="utf-8"?>

<com.trickyandroid.fragmenttranslate.app.view.SlidingRelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:background="#7c7c7c">

    <ListView
            android:id="@android:id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

</com.trickyandroid.fragmenttranslate.app.view.SlidingRelativeLayout>

Custom_View :
  **package com.trickyandroid.fragmenttranslate.app.view;
    import android.content.Context;
    import android.util.AttributeSet;
    import android.view.ViewTreeObserver;
    import android.widget.RelativeLayout;
    /**
     * Created by paveld on 4/13/14.
     */
    public class SlidingRelativeLayout extends RelativeLayout {
        private float yFraction = 0;
        public SlidingRelativeLayout(Context context) {
            super(context);
        }
        public SlidingRelativeLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
        public SlidingRelativeLayout(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }
        private ViewTreeObserver.OnPreDrawListener preDrawListener = null;
        public void setYFraction(float fraction) {
            this.yFraction = fraction;
            if (getHeight() == 0) {
                if (preDrawListener == null) {
                    preDrawListener = new ViewTreeObserver.OnPreDrawListener() {
                        @Override
                        public boolean onPreDraw() {
                            getViewTreeObserver().removeOnPreDrawListener(preDrawListener);
                            setYFraction(yFraction);
                            return true;
                        }
                    };
                    getViewTreeObserver().addOnPreDrawListener(preDrawListener);
                }
                return;
            }
            float translationY = getHeight() * fraction;
            setTranslationY(translationY);
        }
        public float getYFraction() {
            return this.yFraction;
        }
    }**

Now how to get this menu to top of screen on clicking slide up menu
which is on the half of screen ?

A: I suggest you to use AndroidSlidingUpPanel library, that can be found here. There is no point for you to write the same thing again.
It has what you need and much more. It is easy to use and modify (I am using it in my project).
How to use

*

*Include com.sothree.slidinguppanel.SlidingUpPanelLayout as the root element in your activity layout.

*The layout must have gravity set to either top or bottom.

*Make sure that it has two children. The first child is your main layout. The second child is your layout for the sliding up panel.

*The main layout should have the width and the height set to match_parent.

*The sliding layout should have the width set to match_parent and the height set to either match_parent, wrap_content or the max desireable height.

*By default, the whole panel will act as a drag region and will intercept clicks and drag events. You can restrict the drag area to a specific view by using the setDragView method or umanoDragView attribute.


text:
Q: Convert Cassini-Soldner Projection coordinates from Kenya to UTM I have a list of coordinates from Kenya. The coordinates were recorded in old survey maps using Cassini-Soldner Projection, with Clarke 1858 Datum. The approximate geographic coordinates (WGS84) of the area where the coordinates are apparently located are lat: -1.46 and lon : 36.9.
As an example, one set of the coordinates is (X: 150052.09 ,  Y: 4690.62). My interest is to convert these set of coordinates to UTM projection.

A: You can find details on the transformation from Cassini-Soldner to ARC1960 UTM in this article:
http://cae.uonbi.ac.ke/sites/default/files/cae/cae/Gordon%20Okumu%20Wayumba%20F80-81401-2009.pdf
In Table 4.8, a set of four reference points is given, with an equation to transform from Cassini to UTM:
E= b * n + a * e + ∆E
N= a * n - b * e + ∆N

Where a= Scos (θ),    b= S sin(θ)
N and E are the local UTM coordinates
(n,e) are local Cassini  coordinates

Computed values are given in Table 5.8:
Parameter  Value  Accuracy  Units
S  1.0000169  ±0.000002  -
θ  -0.000886  ±0.000002  rad
∆N  10000167.51  ±0.35  m
∆E  277419.49  ±0.35  m

I get a standard deviation of the four points of 10 meters with those values.
Alternatively, you may use:
E = d * n + f * e + ∆E
N = a * n - b * e + ∆N

with:
a    1.00023
b   -0.00077
∆N  10000201.67
d   -0.00086
f    1.00033
∆E    277420.75

Quality of the reference points is now within 2 meters.
These transformations are valid for the Cassini Soldner projection centered on the 37° meridian, against UTM 37S based on ARC1960 datum (not WGS84!).
For the 39° meridian, transformation parameters are given in table 5.3:
PARAMETER  VALUE
a  1.002248791
b  0.0007371372
∆N  10001507.607
∆E  500339.6901

Again, only valid for transformation to UTM zone 37S. Appendix 11 and 12 of the document have coordinates for both systems, and here the standard deviation is under 1 meter.


text:
Q: How to clear temp files for Apache Storm Is there is any way to clear Storm temp files which is created under c:/windows/temp/ through java Api or some thing else? As the Storm documentation says, at the time of shut-downing the storm cluster, it will clear the temp files (though It has a bug while deleting the temp files see here). But in my application I wont call the shutdown method. The storm service will be in running state throughout the life cycle. For zookeeper, clearing temp files will be like
java -cp zookeeper.jar:log4j.jar:conf org.apache.zookeeper.server.PurgeTxnLog <dataDir> <snapDir> -n <count>
I need similar to that one to delete the storm temp files in a safer manner. Since my temp size exceeds to 2 GB. Any way to achieve this or any solution has been prescribed from Apache Storm regarding to clear temp files?


text:
Q: how to assign value in django I have a problem in subtracting a two values. i just want to be like this
a = b - c
here is my code in my handlers.py
 def create(self, request):
        if not self.has_model():
            return rc.NOT_IMPLEMENTED

        attrs = self.flatten_dict(request.POST)

        if attrs.has_key('data'):
            ext_posted_data = SimplerXMLGenerator(request.POST.get('data'))
            attrs = self.flatten_dict(ext_posted_data)

        prod = Product.objects.get(id=attrs['id'])
        prod_quantity = prod.quantity

        quantity_order = attrs['quantity']

        sumOfQuantity = Booking.objects.filter(date_select=attrs['date_select']).aggregate(Sum('quantity')

        prodAvailable = prod_quantity - sumOfQuantity

        if prodAvailable = 0:
            #select another date
            return rc.NOT_HERE
        if prodAvailable <= quantity_order:
            return prodAvailable
        else :
            total = float(quantity_order) * prod.price
            inst = self.model(
                date_select = attrs['date_select'],
                product_name = prod.name,
                quantity = attrs['quantity'],
                price = prod.price,
                totalcost = total,
                first_name = attrs['first_name'],
                last_name = attrs['last_name'],
                contact = attrs['contact'],
                product = prod
                           )
            inst.save()
            return inst

The problem is in  prodAvailable = prod_quantity - sumOfQuantity
my question is how can i declare it correctly?
thanks in advance  :p
here is my trace back ...
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  89.                     response = middleware_method(request)
File "/usr/local/lib/python2.7/dist-packages/django/middleware/common.py" in process_request
  67.             if (not _is_valid_path(request.path_info, urlconf) and
File "/usr/local/lib/python2.7/dist-packages/django/middleware/common.py" in _is_valid_path
  154.         urlresolvers.resolve(path, urlconf)
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in resolve
  342.     return get_resolver(urlconf).resolve(path)
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in resolve
  252.                     sub_match = pattern.resolve(new_path)
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in resolve
  250.             for pattern in self.url_patterns:
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in _get_url_patterns
  279.         patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in _get_urlconf_module
  274.             self._urlconf_module = import_module(self.urlconf_name)
File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py" in import_module
  35.     __import__(name)
File "/home/agileone/workspace/bookproj/../bookproj/api/urls.py" in <module>
  3. from api.handlers import *

Exception Type: SyntaxError at /api/bookings
Exception Value: invalid syntax (handlers.py, line 94)

furthermore, when i trying to do it in my python shell... it goes like this:
>>> sumOfQuantity = Booking.objects.filter(date_select='2011-11-29').aggregate(Sum('quantity'))
>>> print sumOfQuantity
{'quantity__sum': 2}
>>> prod_quantity = 1
>>> prodAvailable = prod_quantity - sumOfQuantity
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'int' and 'dict'

A: If you really want it to look like a = b - c then you'll have to change your assignment to sumOfQuantity:
sumOfQuantity = Booking.objects.filter(date_select='2011-11-29').aggregate(Sum('quantity'))['quantity__sum']