text:
Q: system.formatexception string was not recognized as a valid datetime I get a FormatException with the message "String was not recognized as a valid DateTime." on the following line of code:
SqlCommand scmd1 = new SqlCommand("select count(*) Kount  from chequerequests1 where requestdate between '" + DateTime.ParseExact(txtFromDate.Text, "dd-MMM-yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + " 00:00:00.000' and '" + DateTime.ParseExact(txtToDate.Text, "dd-MMM-yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + " 23:59:59.999' group by chequebookstatus", sc);

*

*DateFormat is "dd/MM/yyyy"

*The current culture is en-GB

*I've tried various variants of DateTimeStyles but to no effect.

Please suggest what is wrong.
Thanks.

A: You have specified the incorrect parsing format: dd-MMM-yyyy.
Your textboxes are in dd-MM-yyyy format.
Change the format, passed to ParseExact, and it should work:
SqlCommand scmd1 = new SqlCommand("select count(*) Kount  from chequerequests1 where requestdate between '" + DateTime.ParseExact(txtFromDate.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + " 00:00:00.000' and '" + DateTime.ParseExact(txtToDate.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + " 23:59:59.999' group by chequebookstatus", sc);

In general, it is a good idea to stop concatinating strings for building SQL query, and start using SQL parameters.
SqlCommand scmd1 = new SqlCommand("select count(*) Kount from chequerequests1 where requestdate between @dateStart and @dateEnd group by chequebookstatus", sc);

DateTime dtStart = DateTime.ParseExact(txtFromDate.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture).StartOfDay();
DateTime dtEnd = DateTime.ParseExact(txtToDate.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture).EndOfDay();

scmd1.Parameters.AddWithValue("dateStart", dtStart);
scmd1.Parameters.AddWithValue("dateEnd", dtEnd);


text:
Q: xsl template not giving correct output to main stylesheets In allTemplate.xsl
<xsl:template match="myRadio">
    <xsl:variable name="radioName"/>
    <input type="radio" value = "F" name="{radioName}"/>
</xsl:template>

In main.xsl
<myRadio>
       <xsl:variable name="radioName" select="Fields/Radio/*" />
</myRadio>

Will this create <input type="radio" etc/> with radioName pointing to the data from Fields/Radio/* on main.xsl in my resulting jsp page after generation?
Error:
Warning: Running an XSLT 1.0 stylesheet with an XSLT 2.0 processor
Warning: at xsl:variable on line 34 of file:/C:/allTemplates.xsl:
  SXWN9001: A variable with no following sibling instructions has no effect
Warning: Running an XSLT 1.0 stylesheet with an XSLT 2.0 processor
Warning: Running an XSLT 1.0 stylesheet with an XSLT 2.0 processor
Error on line 990 of file:/C:/fields.xsl (another random file):
  FORG0001: Failure converting untyped value "" to a number

redpajama_set_name: RedPajamaStackExchange


text:
Q: Should I use Perl/Tk, Tcl::Tk or Tkx for a Perl GUI? I really like Perl/Tk, but have come to the opinion that it's DOA. I think Tcl::Tk and Tkx are better solutions. Assume I drop Perl/Tk. Is the "most supported" route to go with Tcl::Tk (which hasn't been updated since 2007, and whose author seemingly cannot be reached), or Tkx? Are either of these actively used/supported?

A: I have had good result with wxPerl, here is a short article on O'Reilly
Note: I was targeting win32 and this was about 5 years ago.

A: (Disclosure: I am a maintainer of Tcl::pTk and Tkx, and have submitted contributions to Perl/Tk, Tcl/Tk, and Tcl::Tk.)
Update for 2019:
Perl/Tk has had releases in the past few years and development since then, but the maintainer admits to having insufficient time available for major improvements, such as incorporating changes from Tcl/Tk 8.5+. Anyone wanting to use features or improvements in newer Tcl/Tk versions may be interested in instead using one of the Tcl/Tk "wrapper" modules (which provide access to a full separate Tcl/Tk installation from Perl, rather than putting all of Tk in a single Perl module).

*

*If you are working on a new project and like Perl/Tk syntax, you may be fine with Tcl::Tk, a lighter-weight wrapper which uses Perl/Tk-like syntax, while also allowing Tcl/Tk syntax. Tcl::Tk has had some maintenance in the past year.

*However, if you have an existing Perl/Tk program, you may instead want to try Tcl::pTk. It's based on Tcl::Tk, but emphasizes compatibility with Perl/Tk syntax in existing programs. The Tcl::pTk::TkHijack module makes it fairly easy to try out Tcl::pTk by intercepting the use Tk; statements. Tcl::pTk is still a work in progress, but trying it with different programs out there helps find what else needs improvement.

*Or, if you are not familiar with Perl/Tk, have more familiarity with actual Tcl/Tk syntax, or familiar with wrappers for languages (e.g. Tkinter for Python), a better option might be Tkx. As Micheal Carman's answer points out, Tkx hasn't seen much maintenance since 2010, but mainly because it hasn't needed much; as improvements continue to be made to Tcl/Tk, Tkx can usually take advantage of them automatically. The language-agnostic tutorials on TkDocs.com provide examples in Tkx syntax.
I discovered Tcl::pTk last year, and have since become a maintainer for it. I mainly use it in order to use macOS' native aqua UI (instead of XQuartz like Perl/Tk uses), which is what a handful of other active users also report using it for.

A: Under the hood both Tcl::Tk and Tkx use the Tcl module as a bridge to Tcl/Tk. The difference is in the API they present to Perl.
Tkx was developed by ActiveState, who use it in the GUI for their tools. (e.g. PPM) It's actively used, though it's hard to say how widely. It's supported as well, but because it's such a thin layer over Tcl there's not a great deal to support. In a way that's a good thing -- there's little to change or break -- but it does give the impression of abandonware.
Tcl::Tk started as a side project to demonstrate that API compatibility with Perl/Tk was possible. I love the idea of this -- it would be wonderful to only need to change use Tk to use Tcl::Tk and get the benefits of newer versions of Tcl/Tk like tile (theme) support. Unfortunately, it's not there yet. There seems to be some work being done, but not a lot. It could really use more developers.
Personally, I use Tkx. If you're experienced at developing in Perl/Tk the transition isn't too painful, but I think it would be a difficult place to start. The worst part is that you need to refer to the Tcl/Tk documentation in order to use it. That's great if you know Tcl as there are very few surprises introduced by the bridge to Perl, but if you don't it's awkward to translate from an unfamiliar language.


text:
Q: Clarification on mysql deadlock situation Following deadlock is encountered while load testing a application. After going through MySQL documentation and other online resources what I figured out was that
1) Transaction (2) holds exclusive lock for PERMISSION_ID index.
2) Transaction (1) comes and try to acquire insert intention exclusive lock for PERMISSION_ID. But put on to wait since exclusive lock is already with (2)
3) Then transaction (2) also wants to acquire insert intention exclusive lock for PERMISSION_ID which place it behind (1) in waiting queue. Thus deadlock.
What I am not sure about my explanation is assumption in step (2) where request to insert intention exclusive lock for PERMISSION_ID waits for exclusive lock to be released. Is it correct or am I missing something here. Please explain.
*** (1) TRANSACTION:
TRANSACTION 22466201, ACTIVE 0 sec inserting
mysql tables in use 2, locked 2
LOCK WAIT 10 lock struct(s), heap size 1184, 16 row lock(s), undo log entries 2
MySQL thread id 12287, OS thread handle 0x2b4ea1f61700, query id 130397444 10.0.1.222 admin Sending data
INSERT INTO ROLE (PERMISSION_ID, ROLE_NAME, DOMAIN_ID) VALUES (4188, 'everyone', (SELECT DOMAIN_ID FROM DOMAIN WHERE TENANT_ID=1 AND DOMAIN_NAME='INTERNAL'))
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 10787 page no 139 n bits 176 index PERMISSION_ID of table IDENTITY.ROLE trx id 22466201 lock_mode X insert intention waiting
Record lock, heap no 1 PHYSICAL RECORD: n_fields 1; compact format; info bits 0
 0: len 8; hex 73757072656d756d; asc supremum;;
*** (2) TRANSACTION:
TRANSACTION 22466203, ACTIVE 0 sec inserting
mysql tables in use 2, locked 2
8 lock struct(s), heap size 1184, 14 row lock(s), undo log entries 1
MySQL thread id 12279, OS thread handle 0x2b4ea1700700, query id 130397446 10.0.1.222 admin Sending data
INSERT INTO ROLE (PERMISSION_ID, ROLE_NAME, DOMAIN_ID) VALUES (4187, 'anonymous', (SELECT DOMAIN_ID FROM DOMAIN WHERE TENANT_ID=1 AND DOMAIN_NAME='SYSTEM'))
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 10787 page no 139 n bits 176 index PERMISSION_ID of table IDENTITY.ROLE trx id 22466203 lock_mode X
Record lock, heap no 1 PHYSICAL RECORD: n_fields 1; compact format; info bits 0
 0: len 8; hex 73757072656d756d; asc supremum;;
*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 10787 page no 139 n bits 176 index PERMISSION_ID of table IDENTITY.ROLE trx id 22466203 lock_mode X insert intention waiting
Record lock, heap no 1 PHYSICAL RECORD: n_fields 1; compact format; info bits 0
 0: len 8; hex 73757072656d756d; asc supremum;;
*** WE ROLL BACK TRANSACTION (2)

A: Your assumption is correct. Nevertheless, you need to pay attention to what is being locked.
Both transactions are locking

*

*space id 10787

*page no 139

*n bits 176

*index PERMISSION_ID of table IDENTITY.ROLE
The DB Connections 12287 and 12279 ran one INSERT each
Here is what I notice: In each INSERT, you are running SELECT DOMAIN_ID FROM DOMAIN WHERE TENANT_ID=1 AND DOMAIN_NAME='...' to fill in DOMAIN_ID. This would cause additional locks because a query's result is needed to fill DOMAIN_ID while other indexes are made to wait for the materialization of ROLE's primary key. This deadlock lasts a little longer that normal because of this intermittent need to run a SELECT.
SUGGESTION
Instead of doing
INSERT INTO ROLE (PERMISSION_ID, ROLE_NAME, DOMAIN_ID) VALUES (4188, 'everyone',
(SELECT DOMAIN_ID FROM DOMAIN WHERE TENANT_ID=1 AND DOMAIN_NAME='INTERNAL'));

you should retrieve the DOMAIN_ID separately into a variable and then use it in the INSERT
SELECT DOMAIN_ID INTO @domain_id FROM DOMAIN
WHERE TENANT_ID=1 AND DOMAIN_NAME='INTERNAL';
INSERT INTO ROLE (PERMISSION_ID, ROLE_NAME, DOMAIN_ID) VALUES (4188,'everyone',@domain_id);

This might reduce the need to pile up locks


text:
Q: fetch data flutter api I want to get data from API and I tried the link in postman and its working here it is: [ { "Id": "14", "title": "Facebook vs instagram?", }, { "Id": "15", "title": "Facebook vs instagram?", }, { "Id": "16", "title": "Facebook vs instagram?", }, ]
but when I am trying to do a map this error appears : error catch type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List' in type cast.
Here is my code : This error appears in this file and print(recieved) print the same data as postman but the problem in map httpservice.dart:
`
class HttpService {
  final String postsURL =
      "";

  Future<List<Post>> getPosts() async {
    var request = http.MultipartRequest("POST", Uri.parse(postsURL));

    request.headers.addAll(headers);
    List<Post> Posts = [];
    try {
      http.StreamedResponse response = await request.send();

      if (response.statusCode == 200) {
        var response = await http.Response.fromStream(streamedResponse);
final result = jsonDecode(response.body) as List;

        List<Post> posts = result
            .map(
              (dynamic item) => Post.fromJson(item),
            )
            .toList();

        return Posts;
      }
}

`
post_model.dart :
`
class Post {
  final String Id;
  final String title;

  Post({
    required this.Id,
    required this.title,
  });

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
       Id: json['Id'] as String,
      title: json['title'] as String,
    );
  }
}

` post.dart :
class PostsPage extends StatelessWidget {
  final HttpService httpService = HttpService();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Posts"),
      ),
      body: FutureBuilder(
        future: httpService.getPosts(),
        builder: (BuildContext context, AsyncSnapshot<List<Post>> snapshot) {
          if (snapshot.hasData) {
            List<Post> posts = snapshot.data!;
            return ListView(
              children: posts
                  .map(
                    (Post post) => ListTile(
                      title: Text(post.title),
                      subtitle: Text("${post.Id}"),
                    ),
                  )
                  .toList(),
            );
          } else {
            return Center(child: CircularProgressIndicator());
          }
        },
      ),
    );
  }
}

A: The http package gives the data as json in default. You are again trying to decode the decode the response body but the jsonDecode expects string type as parameter.
Simply, all you need to do is remove the jsonDecode
From
final result = jsonDecode(response.body) as List;

to
final result = response.body as Map<String, dynamic>;


text:
Q: user32.dll not found when running mono app on Mac I have created an application on Windows using Visual Studio and compiled it for Mono. But when I run it on a mac I encounter this problem (see image). "user32.dll not found". I thought the MonoFramework accounted for this.
Is this because I am using the MetroFramework UI?
Thanks for any help!
https://i.stack.imgur.com/PMRDH.png

A: This error does originate from MetroFramework (specifically this line). It seems this framework was not designed to work on Mac or rather any operating system other than Windows.
As for your inquiry of Mono's completeness, bear in mind that sometimes framework authors decide to write native code, as opposed to using .NET's BCL, for reasons of performance or lack of supporting APIs for doing a particular thing, to name a few. The case here is that MetroFramework references user32.dll for a host of operations, such as showing a scroll bar, sending Windows messages, etc. – all of which can't be done when dealing with "just" Mono.


text:
Q: AS3: How to access and control embedded sounds in an external swf? I rarely use sounds in AS3/Flash. I am using Flash Pro CS6, but I can't seem to figure out how to access, control (play, stop, etc) sounds embedded in an external SWF loaded into the main SWF.
It's easy to control them when embedded on the main swf. However, on an externally loaded SWR, I get all kinds of errors. For this app, I really need to embed them in the external SWF.
I read several solutions, but none seem to work.
I embed the sound an mp3 file called soundSegment1.mp3 using Flash CS6 import tool and then open the actionscript properties panel on flash to select the class name: SoundSegment1. Then I edit the class code and create a file called SoundSegment1.as and it's saved right next to my document class main.as in the same directory. The code of the SoundSegment1 class looks like this:
package  {

    import flash.media.*;

    public class SoundSegment1 extends Sound
    {

        public function SoundSegment1 ()
        {
            // no code in here
        }

        public function playSound()
        {
            var soundSegment1:Sound = new SoundSegment1();
            var channel:SoundChannel = soundSegment1.play();
        }
    }
}

Then, in my main.as, I have done several attempts to play this sound such as:
var fileLocation:URLRequest = new URLRequest(SWFToLoad);
loader.load(fileLocation);
loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressListener);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeListener);
loader.contentLoaderInfo.addEventListener(Event.INIT, initListener);

function initListener(e:Event):void // I also placed this code on the completeListener and it didn't work
{
    loader.content.soundSegment1.playSound(); // doesn't work.

}

I get:
Line XXX 1061: Call to a possibly undefined method playSound through a reference with static type flash.display:DisplayObject.

or, I also read that I should be able to do something like this anywhere in the Main.as file:
var theClass:Class = Class(loader.content.getDefinitionByName("SoundSegment1"));
var theSound:theClass = new theClass();
theSound.play()  //doesn't work either.

I also tried on the completeListener:
var TheClass:Class = e.target.applicationDomain.getDefinition("SoundSegment1") as Class;
var theSound:TheClass = new TheClass();
theSound.play()  //doesn't work either.

I get:
ReferenceError: Error #1065: Variable SoundSegment1 is not defined.
    at flash.system::ApplicationDomain/getDefinition()

I am stuck and I really need to get this to work. I would be genuinely grateful for your help.
Thank you in advance for any help provided. I really need to get it to work, because I can't simply embed them in the main SWF or load them individually externally one by one.
Thanks again!

A: user SnickelFritz from Kirupa gave me a fabulous answer with much easier code, which can be very powerful when using multiple sounds. This is just great, because you can use only one preloader per SWF, instead of having multiple loader for each file:
code for the main.as file
http://www.kirupa.com/forum/showthread.php?305098-Playing-a-embedded-sound-in-an-external-swf
package
{
    import flash.display.*;
    import flash.media.*;
    import flash.events.*;
    import flash.net.*;

    public class Main extends MovieClip
    {
        var swf:MovieClip;

        public function Main()
        {
            var l:Loader = new Loader();
            l.contentLoaderInfo.addEventListener(Event.COMPLETE, swfLoaded);
            l.load( new URLRequest("child.swf") );
        }

        private function swfLoaded(e:Event):void
        {
            swf = e.target.content as MovieClip;
            addChild(swf);

            swf.playSound();

        }
    }
}

Code for the loaded swf "child.as"
package
{
    import flash.display.*;
    import flash.media.*;
    import flash.events.*;
    import flash.net.*;

    public class Child extends MovieClip
    {
        private var s:Sound1;
        private var sc:SoundChannel;

        public function Child()
        {
            s = new Sound1();
            sc = new SoundChannel();

// All of the following lines are actually optional, if all your graphic  elements are already inside the swf prepared in flash pro

            var g:Graphics = this.graphics;
            g.beginFill(0x666666);
            g.drawRect(0,0,550,400);
            g.endFill();
        }

        public function playSound():void
        {
            sc = s.play();
        }
    }
}

User "kglad.com" on the Adobe Forums also gave me a good answer:
http://forums.adobe.com/message/5681137#5681137


text:
Q: Upgrading from Tastypie 0.9.11 to 0.11 obj_get_list Code that worked in api.py
With Python 2.6, Django 1.4.1, Tastypie 0.9.11 (Running on 2.6.32-48-generic-pae #110-Ubuntu SMP)
class DriveResource(CommonModelResource):
    driver = fields.ForeignKey(DriverResource, 'driver')
    bus = fields.ForeignKey(BusResource, 'bus')
    route = fields.ForeignKey(RouteResource, 'route')

    class Meta(CommonModelResource.Meta):
        queryset = Drive.objects.all()
        allowed_methods = ['get', 'put']
        excludes = ('bus_location',)
        filtering = {
            'updated': ('gt', 'gte', 'lt', 'lte', 'exact'),
            'id': ('exact',),
        }

    def get_object_list(self, request):
        whole_list = super(DriveResource, self).get_object_list(request)
        todays_day_name = datetime.now().strftime('%w')
        filtered_list = whole_list.filter(driver__user=request.user).filter(day=todays_day_name)
        return filtered_list

    def dehydrate_driver(self, bundle):
        return bundle.obj.driver.person_id

    def dehydrate_bus(self, bundle):
        return bundle.obj.bus.number

    def dehydrate_route(self, bundle):
        return bundle.obj.route.id

    def hydrate_bus_location(self, bundle):
        # Guard against the method being called twice
        if not hasattr(bundle, 'geopoint_processed'):
            lon = bundle.data['bus_location'][0] / 1e6
            lat = bundle.data['bus_location'][1] / 1e6
            bundle.data['bus_location'] = Point(lon, lat)
            bundle.geopoint_processed = True
        return bundle

class DriveFullResource(CommonModelResource):
    driver = fields.ForeignKey(DriverResource, 'driver', full=True, blank=True, null=True)
    bus = fields.ForeignKey(BusResource, 'bus', full=True, blank=True, null=True)
    route = fields.ForeignKey(RouteResource, 'route', full=True)

    class Meta(CommonModelResource.Meta):
        queryset = Drive.objects.all()
        resource_name = 'drive'
        allowed_methods = ['get', 'put']
        excludes = ('bus_location',)

    def obj_get_list(self, request=None, **kwargs):
        whole_list = super(DriveFullResource, self).obj_get_list(request, **kwargs)
        todays_day_name = datetime.now().strftime('%w')
        filtered_list = whole_list.filter(driver__user=request.user).filter(day=todays_day_name)
        return filtered_list

    def hydrate_bus_location(self, bundle):
        # Guard against the method being called twice
        if not hasattr(bundle, 'geopoint_processed'):
            lon = bundle.data['bus_location'][0] / 1e6
            lat = bundle.data['bus_location'][1] / 1e6
            bundle.data['bus_location'] = Point(lon, lat)
            bundle.geopoint_processed = True
        return bundle

    def put_detail(self, request, **kwargs):
        deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
        deserialized = self.alter_deserialized_detail_data(request, deserialized)
        bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized), request=request)

        try:
            drive = Drive.objects.get(pk=kwargs['pk'])
            bundle = self.hydrate_bus_location(bundle)
            drive.bus_location = bundle.data['bus_location']
            drive.save()
            return http.HttpNoContent()
        except:
            return http.HttpBadRequest()

Does not work with
Python 2.6, Django 1.5,  Tastypie 0.11 (Running on Centos 5)
Calling server with : https://api.server.com/api/full/drive/?format=json&limit=50&user=12345
I tried changing to:
def obj_get_list(self, bundle, **kwargs):
    request = bundle.request
    whole_list = super(DriveFullResource, self).get_object_list(request)
    todays_day_name = datetime.now().strftime('%w')
    filtered_list = whole_list.filter(driver__user=request.user).filter(day=todays_day_name)
    return filtered_list

and
def obj_get_list(self, bundle, **kwargs):
    request = bundle.request
    whole_list = super(DriveFullResource, self).obj_get_list(bundle, **kwargs)
    todays_day_name = datetime.now().strftime('%w')
    filtered_list = whole_list.filter(driver__user=request.user).filter(day=todays_day_name)
    return filtered_list

Still get error messages of the type below:
{"error_message": "obj_get_list() got multiple values for keyword
argument 'bundle'", "traceback": "Traceback (most recent call
last):\n\n  File
\"/usr/lib/python2.6/site-packages/tastypie/resources.py\", line 195,
in wrapper\n\n  File
\"/usr/lib/python2.6/site-packages/tastypie/resources.py\", line 426,
in dispatch_list\n\n  File
\"/usr/lib/python2.6/site-packages/tastypie/resources.py\", line 458,
in dispatch\n\n  File
\"/usr/lib/python2.6/site-packages/tastypie/resources.py\", line 1266,
in get_list\n\n  File
\"/home/django_projects/project/src/routes/api.py\", line 110, in
obj_get_list\n    request = bundle.request\n\nTypeError:
obj_get_list() got multiple values for keyword argument 'bundle'\n"}

{"error_message": "obj_get_list() got multiple values for keyword
argument 'bundle'", "traceback": "Traceback (most recent call
last):\n\n  File
\"/usr/lib/python2.6/site-packages/tastypie/resources.py\", line 195,
in wrapper\n\n  File
\"/usr/lib/python2.6/site-packages/tastypie/resources.py\", line 426,
in dispatch_list\n\n  File
\"/usr/lib/python2.6/site-packages/tastypie/resources.py\", line 458,
in dispatch\n\n  File
\"/usr/lib/python2.6/site-packages/tastypie/resources.py\", line 1266,
in get_list\n\n  File
\"/home/django_projects/project/src/routes/api.py\", line 114, in
obj_get_list\n    return filtered_list\n\nTypeError: obj_get_list()
got multiple values for keyword argument 'bundle'\n"}

A: I tested the method on Tastypie 0.11 and seems to work ok. But in my opinion you are taking wrong and error prone approach. I prepared solution that will eliminate them.
Problem definition
You didn't defined what is your code supposed to do. Reviewing code I assume you want to have resource that returns object for currently logged user and filtered by day name.
In other words you want to limit access to resource - And this is.. I think you know, authorization.
Why not obj_get_list?
You see that Tastypie obj_get_list is quite Django ORM specific and not documented well. I don't really know how to use it. I wouldn't dare to deal with it.
Solution
Let's define Authorization class for your resource:
from datetime import datetime

from tastypie.authorization import Authorization

class DriverAuthorization(Authorization):
    def read_list(self, object_list, bundle):
        todays_day_name = datetime.now().strftime('%w')
        return object_list.filter(driver__user=bundle.request.user,
                                  day=todays_day_name)

    def read_detail(self, object_list, bundle):
        todays_day_name = datetime.now().strftime('%w')
        return bundle.obj.day == todays_day_name and bundle.obj.driver.user == bundle.request.user

    def create_list(self, object_list, bundle):
        return []

    def create_detail(self, object_list, bundle):
        return False

    def update_list(self, object_list, bundle):
        return []

    def update_detail(self, object_list, bundle):
        object_before_update = object_list.get(pk=bundle.obj.pk)
        return object_before_update.driver.user == bundle.request.user

    def delete_list(self, object_list, bundle):
        return []

    def delete_detail(self, object_list, bundle):
        return False

Now attach authorization to resource:
class DriveResource(CommonModelResource):
    driver = fields.ForeignKey(DriverResource, 'driver')
    bus = fields.ForeignKey(BusResource, 'bus')
    route = fields.ForeignKey(RouteResource, 'route')

    class Meta(CommonModelResource.Meta):
        queryset = Drive.objects.all()
        allowed_methods = ['get', 'put']
        excludes = ('bus_location',)
        authorization = DriverAuthorization()
        filtering = {
            'updated': ('gt', 'gte', 'lt', 'lte', 'exact'),
            'id': ('exact',),
        }

    def dehydrate_driver(self, bundle):
        return bundle.obj.driver.person_id

    def dehydrate_bus(self, bundle):
        return bundle.obj.bus.number

    def dehydrate_route(self, bundle):
        return bundle.obj.route.id

    def hydrate_bus_location(self, bundle):
        # Guard against the method being called twice
        if not hasattr(bundle, 'geopoint_processed'):
            lon = bundle.data['bus_location'][0] / 1e6
            lat = bundle.data['bus_location'][1] / 1e6
            bundle.data['bus_location'] = Point(lon, lat)
            bundle.geopoint_processed = True
        return bundle

Benefits
1. Code now is much more clearer to read
2. You have control on what user can do or cannot do in one place.
3. No obj_get_list means no more problems.


text:
Q: Cómo redondear a entero en kotlin Estoy tratando de redondear un número aleatorio como entero
var top: Int = Math.floor(Math.random() * 4) as Int;

Pero me arroja el siguiente error:

java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer

Tengo Kotlin 1.2, así que no puedo usar el Random de Kotlin
¿Cual es la forma apropiada de obtener ese número entero aleatorio en Kotlin?

A: En realidad el método Math.floor() obtiene un valor tipo double:
public static native double floor(double var);

por lo tanto la conversión a Int se realizaría de esta forma:
//var top: Int = Math.floor(Math.random() * 4) as Int;
var top: Int =  Math.floor(Math.random() * 4).toInt();

Esto crearía un número aleatorio en el rango de 0 a 3.

Usando kotlin 1.3
Puedes establecer el limite mediante el método Random.nextInt(LIMITE), por ejemplo:
val random = Random().nextInt(4);

Usando una versión anterior kotlin 1.3, por ejemplo 1.2
val random  =
       Random().nextInt((limite + 1) - inicio) +  inicio

A: Para un numero al azar entre 0 y 3 usa:
var top: Int=(0..3).shuffled().first()

Esta es una forma en la que no necesitas importar el Random de Java.
Usas un IntRange, "revuelves" los elementos en ese conjunto y obtienes unos de esos elementos.
El usar esta forma también te dará opciones como usar step (paso entre los elementos) por ejemplo, para obtener números pares puedes usar:
(0..3 step 2).shuffled().first()


text:
Q: Aws Aurora cannot connect to Primary instance after replica is promoted I have a Multi-AZ Aurora MySql Cluster. When i first created it, I could connect my local apps to the Cluster Endpoint and interact with it just fine. At some point my Read only instance got promoted and I was no longer able to connect to the cluster endpoint.
If I get on MySql Workbench and enter the Reader endpoint, I can log in to it. From there I can view the tables and rows, but obviously I cant perform inserts/updates/deletes.
If I use the same credentials to try to connect to the Writer endpoint or connect directly to the Cluster endpoint, it times out and says it couldnt connect.
The first time this happened I couldnt find an answer so I just created a new cluster and essentially started over. It worked for a few weeks and then the same thing happened.
My Aurora Instance is in a VPC, but the Security Group is configured for public access via CIDR "0.0.0.0/0". I realize that isnt ideal but I am simply trying to get this to work at the moment. I know the Security Groups and VPN were configured appropriately because I was able to connect to the cluster until today.
Has anyone had this experience before? Have you managed to resolve it? Thanks


text:
Q: How to learn a Bayesian Network (structure+parameters) with the WEKA API? Does anyone know the "proper" procedure to learn a Bayesian Network from data using the WEKA API? I can't find good instructions in the WEKA documentation.
Based on the documentation and what each function is "supposed" to do, I thought this would work:
Instances ins = DataSource.read( filename );
ins.setClassIndex(0);

K2 learner = new K2();

MultiNomialBMAEstimator estimator = new MultiNomialBMAEstimator();
estimator.setUseK2Prior(true);

EditableBayesNet bn = new EditableBayesNet( ins );
bn.initStructure();

learner.buildStructure(bn, ins);
estimator.estimateCPTs(bn);

But it doesn't. I've tried this and other variations and I keep getting ArrayIndexOutOfBoundsException or NullPointerException somewhere inside WEKA code, so what am I missing?

A: It works for me. I tried with the following set of data:
@relation test

@attribute x {0,1}
@attribute y {0,1,2}
@attribute z {0,1}

@data
0,1,0
1,0,1
1,1,1
1,2,1
0,0,0

Let me mention that exceptions are expected when your target attribute is not nominal (e.g. numeric). Bayesian Networks work better when all your attributes are nominal. If you change the target attribute to numeric you'll get a NullPointerException or an ArrayIndexOutOfBoundsException. In particular, this exception is thrown at the line:
EditableBayesNet bn = new EditableBayesNet(ins);

You should first discretize your target class.


text:
Q: How to write excel page header from worksheet formula? Ran into a problem trying to change value of Worksheets.PageSetup.CenterHeader. Now this value can be written/read by passing value with = operator and the following would work nicely as supposed:
Sub Test()
    Call writeHeaderValue(ThisWorkbook.Sheets("Sheet1"), "What what")
End Sub

Sub writeHeaderValue(ByRef mysheet As Worksheet, ByVal writeValue As String)
Set mysheet = ActiveSheet
    Debug.Print mysheet.Parent.Name
    Debug.Print mysheet.Name
    Debug.Print mysheet.PageSetup.CenterHeader

    Application.PrintCommunication = False
    mysheet.PageSetup.CenterHeader = writeValue
    Application.PrintCommunication = True
End Sub

But what causes me headache and can't figure out is that if I call this same writeHeaderValue from a function that I call from a formula in a worksheet, it does show the value and the reference to the worksheet seem to be correct but it fails to change the value. There are no errors from the compiler or any unexpected such, but the value just won't change. Odd thing about this is that the debug.print part clearly shows that I have correct reference and it also shows the current value of that property but it doesn't change so there must be something wrong in the following part:
Function writeValue(ByVal myValue As String)
Application.Volatile
Dim mysheet As Worksheet
Dim r As Range
Set r = Application.Caller
Set mysheet = r.Parent

    Call writeHeaderValue(mysheet, myValue)
writeValue = myValue
End Function

To try this work, you can then use formula for ex.
=writeValue("TEST")

This should change document headers center value to read "TEST" but as you should find out it doesn't. So my question is simple as this - what can be done to make the writeValue function work?
I have gut feeling that it has something to do with using Application.Caller but this is something I want to work so that the reference to sheet is passed based on the cell that the formula is in. Second guess is that there is something happening during the calculation that disables the writing functionality during, but you tell me.
Thanks for all the help!


text:
Q: Data transformation for machine learning I have dataset with SKU IDs and their counts, i need to feed this data into a machine learning algorithm, in a way that SKU IDs become columns and COUNTs are at the intersection of transaction id and SKU ID. Can anyone suggest how to achieve this transformation.
CURRENT DATA
TransID     SKUID      COUNT
1           31         1
1           32         2
1           33         1
2           31         2
2           34         -1

DESIRED DATA
TransID      31      32      33      34
  1          1        2      1       0
  2          2        0      0       -1

A: In R,  we can use either xtabs
xtabs(COUNT~., df1)
#         SKUID
#TransID 31 32 33 34
#     1  1  2  1  0
#     2  2  0  0 -1

Or dcast
library(reshape2)
dcast(df1, TransID~SKUID, value.var="COUNT", fill=0)
#  TransID 31 32 33 34
#1       1  1  2  1  0
#2       2  2  0  0 -1

Or spread
library(tidyr)
spread(df1, SKUID, COUNT, fill=0)

A: In Pandas, you can use pivot:
>>> df.pivot('TransID', 'SKUID').fillna(0)
        COUNT
SKUID      31 32 33 34
TransID
1           1  2  1  0
2           2  0  0 -1

To avoid ambiguity, it is best to explicitly label your variables:
df.pivot(index='TransID', columns='SKUID').fillna(0)

You can also perform a groupby and then unstack SKUID:
>>> df.groupby(['TransID', 'SKUID']).COUNT.sum().unstack('SKUID').fillna(0)
SKUID    31  32  33  34
TransID
1         1   2   1   0
2         2   0   0  -1

A: In GraphLab/SFrame, the relevant commands are unstack and unpack.
import sframe  #or import graphlab
sf = sframe.SFrame({'TransID':[1, 1, 1, 2, 2],
                    'SKUID':[31, 32, 33, 31, 34],
                    'COUNT': [1, 2, 1, 2, -1]})

sf2 = sf.unstack(['SKUID', 'COUNT'], new_column_name='dict_counts')
out = sf2.unpack('dict_counts', column_name_prefix='')

The missing values can be filled by column:
for c in out.column_names():
    out[c] = out[c].fillna(0)

out.print_rows()

+---------+----+----+----+----+
| TransID | 31 | 32 | 33 | 34 |
+---------+----+----+----+----+
|    1    | 1  | 2  | 1  | 0  |
|    2    | 2  | 0  | 0  | -1 |
+---------+----+----+----+----+


text:
Q: In Redux-sagas how to cover lines like variable declaration and URL How to get covered lines like variable declaration
the problem with this var URL declared line or statement or function. and I do not understand how to write a saga test case for the variable declared lines
export function* globalSearchAllAsync(action) {
    var url = "v1/globalSearch/globalSearchTextForAll?pageSize="+action.pageSize+"&recordFromIndex="+action.recordFromIndex;
    if(!checkEmptyOrNull(action.sortBy)){
        url = url + "&SortByProperty="+action.sortBy;
    }
    if(!checkEmptyOrNull(action.sortOrder)){
        url = url + "&sortOrder="+action.sortOrder;
    }
    try{
        const getData = yield NoccSearchServiceAxios.post(url, action.requestObj).then(result => {
            return result;
        });
        yield put(globalSearchAllSuccess(getData.data.response));
    } catch (error) {
        yield put(fetchFailure(error.response.data.errorResponse.errorMessage, action.type))
    }
}

enter code here


text:
Q: memcpy() crashes Cortex M4 I'm developing some software for a STM32F4 controller (Cortex M4).
The other day I was porting my code to a new HW platform, hereby creating a new project in the "System Workbench for STM32" IDE.
When I tried to run the new project, I found memcpy() causing an UsageFault, caused by 32bit-wide Load/Store accessing an uneven address.
I then found out that the old working code had been linked with "-specs=nano" whereas the crashing code was not, so the problem could be fixed easily. I checked the disassembly of memcpy() and found that the Nano library in fact has a very different implementation than the standard (?) libc.
Nevertheless, I'm confused! Why would an implementation of memcpy() not support byte-aligned addresses? That would be a rather trivial bug. There has to be more it?! Anybody knows?

A:
When I tried to run the new project, I found memcpy() causing an UsageFault, caused by 32bit-wide Load/Store accessing an uneven address.

Are you sure it was a 32-bit access and not a 64-bit one (LDRD/STRD instruction)? The former should not crash on a Cortex-M4 at all, unless the MCU is explicitly set up to do so.
All Armv7-M (that includes every Cortex-M but Cortex-M0) support LDR and STR instructions with odd memory addresses. Only the 64-bit variants LDRD/STRD crash on misalignment by default.
Unfortunately FPU loads and stores also crash on -M4F when misaligned. This got me a few times when porting old 8-bit stuff.

Why would an implementation of memcpy() not support byte-aligned addresses?

Modern GCC can use build-ins for memcpy(), especially whith fixed transfer sizes and Pointers to larger types than one byte (say uint32_t* or float*). Nano memcpy() is a minimal implementation that copies slowly byte-for-byte.
You could also try to cast the pointers back to a byte sized type:
uint32_t *pa,*pb;
memcpy((uint8_t*)pa,(uint8_t*)pb, MEMCPY_SIZE);

That should hint the compiler to not use alignmnent sensitive build-ins.


text:
Q: TensorFlow crashes when fitting TensorForestEstimator I am trying to fit at TensorForestEstimator model with numerical floating-point data representing 7 features and 7 labels. That is, the shape of both features and labels is (484876, 7). I set num_classes=7 and num_features=7 in ForestHParamsappropriately. The format of the data is as follows:
f1       f2     f3    f4      f5    f6    f7   l1       l2       l3       l4       l5       l6       l7
39000.0  120.0  65.0  1000.0  25.0  0.69  3.94 39000.0  39959.0  42099.0  46153.0  49969.0  54127.0  55911.0
32000.0  185.0  65.0  1000.0  75.0  0.46  2.19 32000.0  37813.0  43074.0  48528.0  54273.0  60885.0  63810.0
30000.0  185.0  65.0  1000.0  25.0  0.41  1.80 30000.0  32481.0  35409.0  39145.0  42750.0  46678.0  48595.0

When calling fit() Python crashes with the following message:

Python quit unexpectedly while using the _pywrap_tensorflow_internal.so plug-in.

Here is the output when enabling tf.logging.set_verbosity('INFO'):
INFO:tensorflow:training graph for tree: 0
INFO:tensorflow:training graph for tree: 1
...
INFO:tensorflow:training graph for tree: 9998
INFO:tensorflow:training graph for tree: 9999
INFO:tensorflow:Create CheckpointSaverHook.
2017-07-26 10:25:30.908894: F tensorflow/contrib/tensor_forest/kernels/count_extremely_random_stats_op.cc:404]
Check failed: column < num_classes_ (39001 vs. 8)

Process finished with exit code 134 (interrupted by signal 6: SIGABRT)

I'm not sure what this error means, it doesn't really make sense since num_classes=7, not 8 and as the shape of features and labels is (484876, 7), I don't know where the 39001 is coming from.
Here is the code to reproduce:
import numpy as np
import pandas as pd
import os

def get_training_data():
    training_file = "data.txt"
    data = pd.read_csv(training_file, sep='\t')

    X = np.array(data.drop('Result', axis=1), dtype=np.float32)

    y = []
    for e in data.ResultStr:
        y.append(list(np.array(str(e).replace('[', '').replace(']', '').split(','))))

    y = np.array(y, dtype=np.float32)

    features = tf.constant(X)
    labels = tf.constant(y)

    return features, labels

hyperparameters = ForestHParams(
    num_trees=100,
    max_nodes=10000,
    bagging_fraction=1.0,
    num_splits_to_consider=0,
    feature_bagging_fraction=1.0,
    max_fertile_nodes=0,
    split_after_samples=250,
    min_split_samples=5,
    valid_leaf_threshold=1,
    dominate_method='bootstrap',
    dominate_fraction=0.99,
    # All parameters above are default
    num_classes=7,
    num_features=7
)

estimator = TensorForestEstimator(
    params=hyperparameters,
    # All parameters below are default
    device_assigner=None,
    model_dir=None,
    graph_builder_class=RandomForestGraphs,
    config=None,
    weights_name=None,
    keys_name=None,
    feature_engineering_fn=None,
    early_stopping_rounds=100,
    num_trainers=1,
    trainer_id=0,
    report_feature_importances=False,
    local_eval=False
)

estimator.fit(
    input_fn=lambda: get_training_data(),
    max_steps=100,
    monitors=[
        TensorForestLossHook(
            early_stopping_rounds=30
        )
    ]
)

It also doesn't work if I wrap it with SKCompat, the same error occur. What is the cause of this crash?

A: regression=True needs to be specified in the ForestHParams because TensorForestEstimator by default assumes that it is being used to solve a  classification problem, which can only output one value.
There is an implicit num_outputs variable created upon initialization of the estimator and it is set to 1 if regression was not specified. If regression is specified, then num_outputs = num_classes and checkpoints are saved normally.


text:
Q: Call from MDB to SSB is always anonymous in JBoss AS7/EAP6 Got problem with JBoss AS7 / EAP6. In MDB, when I lookup for SSB and call its method, the call is always anonymous, i.e. sessionContext.getCallerPrincipal() returns Principal(anonymous). Always... In AS5 everything was fine.
How can I fix it to make a call with an authenticated user?
My MDB:
@MessageDriven(activationConfig = {
        @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
        @ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/piQueue"),
        @ActivationConfigProperty(propertyName = "dLQMaxResent", propertyValue = "3")
})
@SecurityDomain("mySecurityDomain")
public class PIMessageBean implements MessageListener {
...
    **//subject always anonymous...**
    Subject subject = (Subject) PolicyContext.getContext("javax.security.auth.Subject.container");

    PIManager pim = lookupPIManager();
    pim.getPIs(); **//call is anonymous**
...
}

My queue settings:
<subsystem xmlns="urn:jboss:domain:messaging:1.2">
    <hornetq-server>
    ...
        <jms-destinations>
            <jms-queue name="piQueue">
                <entry name="queue/piQueue"/>
                <entry name="java:jboss/exported/jms/queue/piQueue"/>
            </jms-queue>
        </jms-destinations>
        <security-domain>mySecurityDomain</security-domain>
    </hornetq-server>
</subsystem>

My Security Domain:
<security-domain name="mySecurityDomain" cache-type="default">
    <authentication>
        <login-module code="com.qu.vad.CustomUsernamePasswordLoginModule" flag="required">
        </login-module>
    </authentication>
</security-domain>

A: Solved the problem by doing JAAS login in MDB


text:
Q: Multivalued cookies, not so multivalue? My cookie does seem to create itself and it does store value, but only the last value, so basically it always holds 1 item, and when I try to add another it simply replaces the 1 item.
My code is below, any ideas are appreciated.
    if (Request.Cookies["CartData"] == null)
    {
        HttpCookie NewCookie = new HttpCookie("CartData");
        Response.Cookies.Add(NewCookie);
    }
    /* Process Queries */
        int Qty;
        if (Request.QueryString["Action"] == "AddToCart")
        {
            string ProductID = Request.QueryString["ProductID"];
            string ProductCategory = Request.QueryString["Category"];

            /* Check if Quantity entered is a valid number, if not set to 1 */
            if (!int.TryParse(Request.QueryString["Qty"], out Qty))
            {
                Qty = 1;
            }

            /* Check if the item already exists in Cart */
            if (Request.Cookies["CartData"][ProductID + "_" + ProductCategory] != null)
            {
                int tempQty;
                tempQty = int.Parse(Request.Cookies["CartData"][ProductID + "," + ProductCategory]);
                tempQty += Qty;
                Response.Cookies["CartData"][ProductID + "_" + ProductCategory] = tempQty.ToString();
            }
            else
            {
                Response.Cookies["CartData"][ProductID + "_" + ProductCategory] = Qty.ToString();
            }
            Response.Cookies["CartData"].Expires = DateTime.Now.AddDays(1);

        }

A: In your code when Requesting you use
Request.Cookies["CartData"][ProductID + "," + ProductCategory])

while when writing you use
Response.Cookies["CartData"][ProductID + "_" + ProductCategory]

so you should replace , by _ in the parameter.
Is there any reason not to use Session for this?


text:
Q: Frame buffer not rendering depth into depth texture So, i have this assignment about double pass rendering to compute shadows and I am trying to store the depth value of each of the objects of a scene and rendering them as a texture in another object.
I am using OpenGL, I don't really know where the error could be, but when analyzing a capture with RenderDoc, it says that the FBO (FrameBufferObject) is unused and also interprets what should be my 1st pass, a depth only pass, as a color pass.
/*-This is how I create the FBO and the texture to render the depth-*/

glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);

// Create texture for Depth image (first pass)
glGenTextures(1, &depthTexture);
glBindTexture(GL_TEXTURE_2D, depthTexture);

// Give pixel data to opengl
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, 1024, 1024, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, nullptr);

// WITH PCF for anti-aliasing shadow edges
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);

glGenFramebuffers(1, &FBO);
glBindFramebuffer(GL_FRAMEBUFFER, FBO);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D,
depthTexture, 0);
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);

glBindFramebuffer(GL_FRAMEBUFFER, 0);
/*---------------------------END------------------------------------*/

/*---This is how I render all the objects (1st and second pass)-----*/
glViewport(0, 0, 1024, 1024);

glClearColor(0.3f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

cube.FirstPass(light.getPos());
plane.FirstPass(light.getPos());
cone1.FirstPass(light.getPos());
cone2.FirstPass(light.getPos());

glFlush();
glFinish();

glViewport(0, 0, WIDTH, HEIGHT);
glClearColor(0.3f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

cube.display(&cam, light.getPos());
plane.display(&cam, light.getPos());
viewport.display(&cam, light.getPos());
cone1.display(&cam, light.getPos());
cone2.display(&cam, light.getPos());
/*---------------------------END------------------------------------*/

/*---------This is how I do First Pass---------*/
//Here goes first pass
glBindFramebuffer(GL_FRAMEBUFFER, sceneManager.getFBO());

glClear(GL_DEPTH_BUFFER_BIT);

glUseProgram(DepthPass.shader);

glm::mat4 mtx = glm::perspective(glm::radians(60.0f), 1024.0f / 1024.0f,          5.0f, 40.0f);

DepthPass.setMat("M", mtx * glm::lookAt(glm::vec3(lightPos.x, lightPos.y, lightPos.z), glm::vec3(0.0, 0.0, 0.0), glm::vec3(0.0, 1.0, 0.0)) *
getModelToWorld());

glBindVertexArray(vao);

// Draw
glDrawArrays(GL_TRIANGLES, 0, ModelVertices.size());

glBindFramebuffer(GL_FRAMEBUFFER, 0);
/*---------------------------END------------------------------------*/

/*--This is what I pass to the shader that shows the depth texture--*/
DepthPass.setFloat("near", 5.0f);
DepthPass.setFloat("far", 40.0);

DepthPass.setInt("IsViewport", 1);

glActiveTexture(GL_TEXTURE0);

//GetDepthTexture() returns a handle of the texture created before

glBindTexture(GL_TEXTURE_2D, sceneManager.GetDepthTexture());
std::string textureName = "depthTexture";
DepthPass.setInt(textureName.c_str(), sceneManager.GetDepthTexture());

/*---------------------------END------------------------------------*/


text:
Q: Selenium driver - windowhandle messes up I'm using Selenium WebDriver on Firefox version 48.x.x.  For this to work I need to use GeckoDriver/Marionette driver in order to talk to Firefox driver.  In the older versions of Firefox, Selenium driver is able to get the session ID of a browser window using driver.getWindowHandle() however in the new(?) Gecko/Marionette driver, this function returns a short integer, not a long text string of hexadecimal.  Is this a bug? or the new feature of Gecko/Marionette driver?
Here is where i ran into trouble:
1 - I start Firefox browser using Gecko/Marionette driver
final File file = new File("/Applications/geckodriver");
System.setProperty("webdriver.gecko.driver", file.getAbsolutePath());
driver = new FirefoxDriver();

It works fine.  Then I print out the value of the browser window session ID:
System.out.println("WindowHandle ID = " + driver.getWindowHandle());

It shows some short integers somewhere between 10 to 20 which are incorrect.
Then I print out the browser session and I am able to see the actual session ID (the MAC field between the () ):
Brwowser Session = BrowserSession [driver=FirefoxDriver: Firefox on MAC (**bc4eb9db-608b-5643-8ec9-136b6c54f6a2**), user=Admin, lastPage=null]

Now I think the new Gecko/Marionette messed up the driver.getWindowHandle() function ?  Because of this show-stopper, I am not able to switch the Selenium control from one window to another window or a pop-up.
Question:
Is there anyway that I can get the actual browser window session ID?  Please help.  I really need to get over this huge hurdle.  I've been searching for a solution but found none.
I'm writing in Java.
Thanks a lot folks.

A: Use Selenium 2.53.1 + Firefox (v 48) with the following code
System.setProperty("webdriver.firefox.marionette", file.getAbsolutePath());

or
System.setProperty("webdriver.gecko.driver", file.getAbsolutePath());


text:
Q: How to manually define input split for mapper function in Hadoop I have a text file which I want to parse through map reduce.
File has below mentioned format:
<main node>
<type 1> --data--
<type 2> ---data
.
.
.
<type n> --data
</main node>

<main node>
<type 1> --data--
<type 2> ---data
.
.
.
<type n> --data
</main node>

I would like the map function split according to main node..such that each split has exactly one main node and its data.
all the main node starts with same syntax.
Is it possible to define such input split for Map function?
P.S. this is not xml file..although it looks like one.

A: Looks like your input file is in the XML Format.
In that case you can replace your TextInputFormat class to XMLInputFormat class.
That means instead of mapper getting each line as input, it gets each main_node as input.
Checkout the link below,
https://svn.apache.org/repos/asf/mahout/trunk/integration/src/main/java/org/apache/mahout/text/wikipedia/XmlInputFormat.java
Find a working example at
https://github.com/ajaysadhu/XML_MR_Reader
Hope its helpful.

A: I don't think it is possible, you have to read your whole file as a single split by setting issplittable() to false.

A: Hadoop is pluggable system.
Hadoop does provide standard InputFormat like Text , binary etc.. But if you have custom format file then you need to write your own InputFormat and Implement custom RecorReader to generate input split. If you implement these then you can control where to split data and each Mapper ingest one input spit at a time


text:
Q: rewriting URL seem to be written wrong I just realised that some of my rewritten urls stopped working. I am unaware of why.
Here is my rewrite file
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^forums/([^/]*)/locate/([^/]*)/$ /forums.php?page=$1&tlocate=$2

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^changelogs/([^/]*)/$ /index.php?page=$1

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^forums/$ /forums.php

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/$ /forums.php?page=$1

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^forums/action/([^/]*)/$ /forums.php?page=$1

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^forums/([^/]*)/section/([^/]*)/$ /forums.php?page=$1&sectionid=$2

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^register/([^/]*)/$ /register.php?page=$1

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^account/([^/]*)/$ /account-page.php?page=$1

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^about-us/$ /about.php

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^forums/([^/]*)/topic/([^/]*)/$ /forums.php?page=$1&topic=$2 [L]

ErrorDocument 400   /error.php
ErrorDocument 401   /error.php
ErrorDocument 403   /error.php
ErrorDocument 404   /error.php
ErrorDocument 500   /error.php

If i went to www.localhost/account/
It would just send me to www.localhost/forums/
So i downloaded mozilla to see if my htaccess stopped working. The css didnt work there. I then went to a website to check my code and it complained about the line
RewriteRule ^about-us/$ /about.php

On that line, i tried to rewrite www.localhost/about.php
 into www.localhost/about-us/
without any success. What is it that i'm doing wrong that causes this issue?

A: You can use in your .htaccess:
# skip all files and directories from rewrite rules below
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

RewriteRule ^forums/([^/]*)/locate/([^/]*)/$ /forums.php?page=$1&tlocate=$2 [L]
RewriteRule ^changelogs/([^/]*)/$ /index.php?page=$1 [L]
RewriteRule ^forums/$ /forums.php [L]
RewriteRule ^forums/action/([^/]*)/$ /forums.php?page=$1 [L]
RewriteRule ^forums/([^/]*)/section/([^/]*)/$ /forums.php?page=$1&sectionid=$2 [L]
RewriteRule ^register/([^/]*)/$ /register.php?page=$1 [L]
RewriteRule ^account/([^/]*)/$ /account-page.php?page=$1 [L]
RewriteRule ^about-us/$ /about.php [L]
RewriteRule ^forums/([^/]*)/topic/([^/]*)/$ /forums.php?page=$1&topic=$2 [L]
RewriteRule ^([^/]*)/$ /forums.php?page=$1 [L]

ErrorDocument 400   /error.php
ErrorDocument 401   /error.php
ErrorDocument 403   /error.php
ErrorDocument 404   /error.php
ErrorDocument 500   /error.php

And add this code in your about.php HTML code:
<base href="/">

Because you change the root (for css and others relatives) with your about-us/ link.


text:
Q: symbol(s) not found for architecture armv7 flutter  ld: symbol(s) not found for architecture armv7
    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    ld: warning: dylib (/Users/Shared/store/build/ios/Release-iphoneos/abseil/absl.framework/absl) was built for newer iOS version (11.0) than being linked (10.0)
    ld: warning: dylib (/Users/Shared/store/build/ios/Release-iphoneos/gRPC-C++/grpcpp.framework/grpcpp) was built for newer iOS version (11.0) than being linked (10.0)
    ld: warning: dylib (/Users/Shared/store/build/ios/Release-iphoneos/leveldb-library/leveldb.framework/leveldb) was built for newer iOS version (11.0) than being linked (10.0)
    note: Using new build system
    note: Building targets in parallel
    note: Planning build
    note: Constructing build description

Encountered error while building for device.

[✓] Flutter (Channel stable, 2.0.0, on Mac OS X 10.15.4 19E266
darwin-x64, locale en-IN)
• Flutter version 2.0.0 at /Applications/flutter2.0_midhilaj
• Framework revision 60bd88df91 (4 weeks ago), 2021-03-03 09:13:17 -0800
• Engine revision 40441def69
• Dart version 2.12.0
[!] Android toolchain - develop for Android devices (Android SDK
version 30.0.3)
• Android SDK at /Users/midhilajm/Library/Android/sdk
• Platform android-30, build-tools 30.0.3
• ANDROID_HOME = /Users/midhilajm/Library/Android/sdk
• Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
! Some Android licenses not accepted.  To resolve this, run: flutter doctor --android-licenses
[✓] Xcode - develop for iOS and macOS
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 12.4, Build version 12D4e
• CocoaPods version 1.10.1
[✓] Chrome - develop for the web
• Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
[✓] Android Studio (version 4.1)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin can be installed from:
 https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
 https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
[✓] Android Studio (version 4.1)
• Android Studio at /Applications/Android Studio 2.app/Contents
• Flutter plugin can be installed from:
 https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
 https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
[✓] VS Code (version 1.54.3)
• VS Code at /Applications/Visual Studio Code.app/Contents
• Flutter extension can be installed from:
 https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter
[✓] Connected device (1 available)
• Chrome (web) • chrome • web-javascript • Google Chrome 89.0.4389.90
! Error: Midhilaj's iPhone is not connected. Xcode will continue when Midhilaj's iPhone is connected. (code -13)
! Doctor found issues in 1 category.

A: Run flutter upgrade to upgrade to most recent version of Flutter. After that, flutter clean and build again. This should solve your problem.

A: Only thing which solved me this problem is to clear the pub cache by deleting pubspec.lock file and re running flutter run command.
This mainly happens due to the error in the cached plugin files


text:
Q: Getting User group members using Powershell I got a script Invoke-Command {net localgroup administrators} which only work in server 2012 & not in server 2008R2, getting error as mentioned below, even though "WinRM already is set up to receive requests on this machine."

Connecting to remote server failed with the following error message : The client cannot connect to th
  e destination specified in the request. Verify that the service on the destination is running and is accepting requests
  . Consult the logs and documentation for the WS-Management service running on the destination, most commonly IIS or Win
  RM. If the destination is the WinRM service, run the following command on the destination to analyze and configure the
  WinRM service: "winrm quickconfig". For more information, see the about_Remote_Troubleshooting Help topic.
      + CategoryInfo          : OpenError: (:) [], PSRemotingTransportException
      + FullyQualifiedErrorId : PSSessionStateBroken

Can you pls suggest any other way to get that script working...

A: The Windows RM issue is coming up because you're using Invoke-Command to run a CMD against your AD system/repository. That command may or may not be running with the appropriate privs to query AD for the admin listing.
Try using the Powershell equivalent:
Get-ADGroupMember
https://technet.microsoft.com/en-us/library/ee617193.aspx
You will still need to have the appropriate permissions, but I also suspect Powershell's error message from Get-ADGroupMember will give you much more insight than the one from Invoke-Command.


text:
Q: Looping an ajax function with javascript I have an array that is looping and each one of them needs to go through a ajax/php function. However this doesn't seem to be working. Can you show me a correct way of doing this?
for (var i = 0; i < arr.length; i++) {
    $.ajax({
        type: "POST",
        data: "data=" + arr[i],
        url: "proxy.php",
        success: function(msg){
            $("#test").html(msg+msg);
        }
    });
}

The id "test" needs to contain all the vals gotten from php.

A: .html() replaces the current content with what you pass into it. Instead, you need to add to the content.
$("#test").append(msg,"<br />");


text:
Q: Regex to match all excluding block comments The issue is I want to match all of the text on either side of the comment and exclude the comment itself.
There are plenty of 'comments' related regex posts, but most are in other languages (I am using notepad++ which wikipedia tells me is POSIX ERE, let's not discuss languages or tools), and most are focused on finding the comments, which I have done already.
This will find the encompassing text I desire (this will include the internal block comment in the match):
(^)rule ((.|\n|\r)*?)(^)end

The above finds anything between 'rule' and 'end', inclusive. Fine.
This will find the block comment:
(?:/\*(?:(?:[^*]|\*(?!/))*)\*/)

The above finds anything between /* and */, inclusive. Fine. I am not concerned if there might be one of the */ inside the comment, not an issue in my case.
Now the question is how do I put the block comment into a negative in the middle of the positive rule match above, so that it matches everything between RULE and END except for commented text?
Bonus points if your answer excludes single line // comments as well.

A: Let me start by saying: regex is not made to do this!
But it's not impossible: it can be done with a recursive regex:

*

*Match everything from "rule" to "end" OR to a start of a comment-block which after further matches everything to "end" OR to a start of a comment-block which after further matches everything to "end" OR etc..

of course only capturing the 'everythings'
Which translates to:
^rule((?:.|\r|\n)*?)(?:^end|(?:(?://$|/\*(?:(?:[^*]|\*(?!/))*)\*/)))
                                                                  ^
                                                             put cursor there
                                                              and insert
                           ((?:.|\r|\n)*?)(?:^end|(?:(?://$|/\*(?:(?:[^*]|\*(?!/))*)\*/)))
                                                                or end with
                           (?:\r?\n^end)

then replace with
$1$2$3$4$..
where the number of substitutions should match the number of recursions
to test the limits of Notepad++ I created this fiddle:
http://jsfiddle.net/lovinglobo/wPKjb/
Notepad++ breaks on more than 29 recursions by simply saying "invalid regular expression".

A: If you are able to flip your requirement and instead delete all comments from the source, you could use this pattern to match comments (both block and line):
/(\/\*).*?(\*\/)|(\/\/).*?(\n)/s


text:
Q: Debugging on ART is gruesomely slow, switching to Dalvik not an option I'm not sure whether Tango even works with Dalvik, and switching back to Dalvik from ART seems the most common suggestion for issues with debug performance -  running the point cloud test in debug mode is fundamentally pointless, it runs too slowly for any real work -  what am I missing -  I can't see how GOOG debugged any of the demo apps with what I've encountered  :-(

A: After a certain amount of misery on a Windows platform, this is the solution I've come up with - other factors were also involved, such as getting my hands on the actual image pixels so I can colorize the point cloud and texture the generated surfaces.
1) Use Android Studio for Java, use Visual Studio + VisualGDB (this thing is wonderful!) for C/C++
2) The Visual Studio project rules, i.e. it physically contains all of the files
3) I use cygwin, therefore I can make it so that the Android Studio project is just a giant collection of links to the java bits and ndk output.  I use Android Studio to debug java, have access to nice layout editors, etc.  Its not quite mature yet, and this is a good fit for it.
4) I do all the heavy lifting in C++ in the native part - as things should be if you're chucking around this much data.  I do have lifters for things like images and pointclouds, as java is better suited to phoning these things home as json to webservices
5) I DON'T debug Java and C++ simultaneously.  I'm cool with that.
6) C side debugger performance is awesome!
7) Jury is still out on the Java side,  but since the computationally expensive stuff is out of the way, that's a lot nicer picture.
It was a long strange trip, but if you're on windows, and aware that the key element of this solution costs money, there is at least an opening in the tunnel - I am planning on looking at the nVidia stuff later,  would love to hear if someone beats me to it.


text:
Q: Negative look-ahead assertion in list.files in R I try to list all files in a directory that do not start with "Camera1", but end with ".png". For doing so, I am using a regular expression in list.files in R.
To exclude "Camera1", I tried to use a negative lookahead, but it doesn't work. Where is my mistake? ;)
list.files(pathToDirectory, pattern = "^(?!Camera1).*\\.png")

I get the error: invalid 'pattern' regular expression
Thanks in advance :)

A: Looks like the default engine doesn't like lookarounds, so you need to use Perl.  This works:
dat <- c("Camera1.png", "Camera2.png", "hello.png", "boo")
grep("^(?!Camera1).*\\.png", dat, value=T, perl=T)
# [1] "Camera2.png" "hello.png"

But this doesn't:
grep("^(?!Camera1).*\\.png", dat, value=T)
# invalid regular expression '(?<!Camera1)\.png', reason 'Invalid regexp'

So, to do what you what you want:
grep("(?<!Camera1)\\.png", list.files(), perl=T, value=T)


text:
Q: JQuery traversing table column I have a table as follows;

Column One
Column Two
Column Three
Column Four

Row One

Row Two

Row Three

Row Four

I would like to be able to click on the  with a class of 'click' and then alert me as to how many rows away the  with a class of target is. (in the above example it would return 2).
There may be other  elements in the table with a class of target. I am only interested in the number of rows until the next target in the same row as my 'clicked' td. Any targets above my 'clicked'  or in other columns should be ignored.
If there are no other 'target' 's after the clicked element in the same row, the alert should read 'no other targets'.
I hope this is clear.

A: you could probably find a solution using a combination of parent() and closest(), along with siblings, next, previous, etc. basically using the traversal methods to select "td.target"

A: Do you mean like this?
var targetRowIndex = $('.target')[0].parentNode.rowIndex;

$(".click").bind("click",function(){
   alert( targetRowIndex - this.parentNode.rowIndex );
});

http://jsfiddle.net/BZDyr/3/
You can probably implement the rest of the precise functionality yourself if you realize what's going on in that code.


text:
Q: How do I install Prometheus with Helm so that it's available from the browser? I'm installing Prometheus on GKE with Helm using the standard chart as in
helm install -n prom stable/prometheus --namespace hal
but I need to be able to pull up the Prometheus UI in the browser.  I know that I can do it with port forwarding, as in
kubectl port-forward -n hal svc/prom-prometheus-server 8000:80
but I'm being told "No, just expose it."  Of course, there's already a service so just doing
kubectl expose deploy -n hal prom-prometheus-server
isn't going to work.  I assume there's some value I can set in values.yaml that will give me an external IP, but I can't figure out what it is.
Or am I misunderstanding when they tell me "Just expose it"?

A: It is generally a very bad idea to expose Prometheus itself as it has no authentication mechanism, but you can absolutely set up a LoadBalancer service or Ingress aimed at the HTTP port if you want.
More commonly (and supported by the chart) you'll use Grafana for the public view and only connect to Prom itself via port-forward when needed for debugging.

A: Agree that it's a bad idea to expose prom publicly, but if its a demo it's ok.
Run:
kubectl expose deploy -n hal prom-prometheus-server --type=LoadBalancer

Kubernetes will create a GCP Load Balancer with an external IP.
Hope it helps!


text:
Q: How to pass a 2D array as a parameter in C? The section of function is never entered in the following code
please help me out!
#include<stdio.h>
int findMax(int *a[], int m, int n)//this function is not entering
{
    int i,j,k=0;
    for(i=0;i<m;i++)
      for(j=0;j<n;j++)
        if(k<a[i][j])
           k=a[i][j];
    printf("hi");//this hi is also not printing
                 //this hi is just for testing
    return k;
}

//This function correct it if possible
int main()
{
   int m,n,a[50][50],i,j,k=0;
   printf("Enter the number of rows in the matrix\n");
   scanf("%d",&m);
   printf("Enter the number of columns in the matrix\n");
  scanf("%d",&n);
  printf("Enter the elements in the matrix\n");
  for(i=0;i<m;i++)
    for(j=0;j<n;j++)
    {
      scanf("%d",&a[i][j]);
    }
  printf("The matrix is");
  for(i=0;i<m;i++)
  {
     printf("\n");
     for(j=0;j<n;j++)
       printf("%d ",a[i][j]);
  }
  k=findMax((int **)a,m,n);//statements after this is never running but no
                           //compilation errors
  printf("\nThe maximum element in the matrix is %d",k);
  return 0;
}

please help me out!!
Thanks to you in advance!!

A: int findMax(int *a[], int m, int n)

int *a[] is an array of pointers to int, you want a pointer to an array of 50 int's:
int findMax(int (*a)[50], int m, int n)

or
int findMax(int a[][50], int m, int n)

You don't need the cast, call it using:
k = findMax(a, m, n);

Or you can use a flat array, an example:
#include <stdio.h>

void foo(int *arr, int rows, int cols)
{
    int i, j;

    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++)
            printf("%d ", arr[i * cols + j]);
        printf("\n");
    }
}

#define ROWS 3
#define COLS 3

int main(void)
{
    int arr[ROWS * COLS];
    int i, j;

    for (i = 0; i < ROWS; i++) {
        for (j = 0; j < COLS; j++)
            arr[i * COLS + j] = i * COLS + j;
    }
    foo(arr, ROWS, COLS);
    return 0;
}

If you dont know the sizes of the 2d array beforehand you can use malloc:
#include <stdio.h>
#include <stdlib.h>

void foo(int *arr, int rows, int cols)
{
    int i, j;

    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++)
            printf("%d ", arr[i * cols + j]);
        printf("\n");
    }
}

int main(void)
{
    int i, j, rows, cols;
    int *arr;

    printf("Num of rows:");
    scanf("%d", &rows);
    printf("Num of cols:");
    scanf("%d", &cols);
    arr = malloc(rows * cols);
    if (arr == NULL) {
        perror("malloc");
        exit(EXIT_FAILURE);
    }
    for (i = 0; i < rows; i++) {
        for (j = 0; j < cols; j++)
            arr[i * cols + j] = i * cols + j;
    }
    foo(arr, rows, cols);
    free(arr);
    return 0;
}

A: what you are doing here: int findMax(int *a[], int m, int n) is trying to point at int 50 times, but you want to point at a variabile type int 50 times. therefor you want to decleare the pointer before you decleare the array.
use therefor:
int findMax(int (*a)[], int m, int n)

this should work now without the casting
just turn it into:
k=findmax(a,m,n);

here is a simple tutorial on the subject.

A: #include <stdio.h>
#include <limits.h>

#define MATRIX_SIZE 50

int findMax(int a[MATRIX_SIZE][MATRIX_SIZE], int m, int n){
    //Valid any of the following is
    //int a[MATRIX_SIZE][MATRIX_SIZE]
    //int a[][MATRIX_SIZE]
    //int (*a)[MATRIX_SIZE]
    int i, j, k=INT_MIN;
    for(i=0;i<m;i++)
        for(j=0;j<n;j++)
            if(k<a[i][j])
                k=a[i][j];
    return k;
}

int main(void){
    int m, n, a[MATRIX_SIZE][MATRIX_SIZE], i, j, k=0;

    printf("Enter the number of rows(<=50) in the matrix\n");
    scanf("%d",&m);
    printf("Enter the number of columns(<=50) in the matrix\n");
    scanf("%d",&n);
    if(m < 1 || n < 1 || m > 50 || n > 50){
        printf("invalid input!\n");
        return -1;
    }
    printf("Enter the elements in the matrix\n");
    for(i=0;i<m;i++)
        for(j=0;j<n;j++)
            scanf("%d",&a[i][j]);

    printf("The matrix is");
    for(i=0;i<m;i++){
        printf("\n");
        for(j=0;j<n;j++)
            printf("%d ",a[i][j]);
    }
    k=findMax(a, m, n);
    printf("\nThe maximum element in the matrix is %d\n", k);

    return 0;
}


text:
Q: Strange Concurrence on lines. I got really stuck proving this exercice of my text on geometry. Can anyone provide a solution please?

If the lines $AA'$, $BB'$, $CC'$ concur, then the points of intersection of the lines:
$AB,A'B'$; $BC,B'C'$; $CA,C'A'$; $A'B,BA'$; $B'C,BC'$; $C'A,AC'$ lie by thirds on 4 separated lines

Here's a picture of the initial situation:

I really tried everything on my text and did lots of sketches but failed.
Please, help.


text:
Q: divide sentence string into substrings =< length of longest single word I am a newbie, and have a pile of data strings (sentences). I'm trying to divide each sentence into substrings where each string's length does not exceed the length of longest single word in that sentence, and returning all words in their original sequence with line breaks (Photoshop carriage return, "\r") dividing the substrings, for that sentence. The words in each string are not hyphenated (only full words or groups of words broken at where a space would be*).* Edit: using the maximum characters, up to the longest word's character count... so a line would have 2 or 3 words possibly, up to the length of the longest word.
I've found examples that split and count the array of words, order them by character length, or add line breaks at set characters, all spaces, etc. But none where I know enough to see an easy modification for this outcome. Any help is greatly appreciated.

A: Using replace you can replace all the spaces with \n to get the result.

a = 'This show navigation menu when you scroll up page 0px up (in right-way). But trying to show after 200px (on page scroll-up) means not showing right way want show and hide after 200px when scroll \n up page.'
b = a.replace(/\s{1,}/g,"\n");
alert(b)

A: Try using .split with a regex:
var a = 'This show navigation menu when you scroll up page 0px up (in right-way). But trying to show after 200px (on page scroll-up) means not showing right way want show and hide after 200px when scroll \n up page.'
var outputArray = a.split(/\s+/);
console.log(outputArray);

If you want a more direct way:
var a = 'This show navigation menu when you scroll up page 0px up (in right-way). But trying to show after 200px (on page scroll-up) means not showing right way want show and hide after 200px when scroll \n up page.'

a.match(RegExp('.{0,' + Math.max.apply(0, a.match(/\w+/g).map(function(l) {
    return l.length;
})) + '}', 'g');

ES6:
a.match(RegExp(`.{0,${Math.max(...a.match(/\w+/g).map(l=>l.length))}}`), 'g')


text:
Q: If $n$ is a finite ordinal, either $n=\emptyset$, or there exists a finite ordinal $m$ such that $n=m \cup\{m\}$ I have a difficulty with this statement :
If $n$ is a finite ordinal, either $n=\emptyset$, or there exists a finite ordinal $m$ such that $n=m \cup\{m\}$.
My professor's proof is totally unclear.
I did the following, using the following definitions.
A transitive set is a set a such that $\forall x, y$, if $x \in y$ and $y \in a$, then $x \in a$.
An ordinal is a transitive set which is well-ordered for the relation $\in$.
We define $m=\bigcup n=\bigcup_{z \in n}z$, using the axiom of reunion.
First step : $m$ is transitive : Let $x,y$ such that $x \in y$ and $y \in m$ ;
$y \in m$ implies $\exists z\in n, y\in z$. Since $n$ is transitive, $y\in z$ and $z\in n$ implies $y \in n.$ Then, $x\in y$ and $y \in n$ implies $x \in \bigcup n =m$. Therefore m is transitive.
Then I suppose step 2 would be to show that $m$ is finite, and well-ordered by $\in$, and step 3 would be to finally show the double inclusion $n\subset m \cup\{m\}$ and $m \cup\{m\}\subset n$.
My questions are : how to show that $m$ is finite ? (The rest is ok I think).
Is there a quick way to show that $m$ is well-ordered ? I have a proof the fact that $\in$ is a total order (cf bottom), but the well-ordering seems long to prove.
Last question : my professor seems to say that we can use $\subset$ or $\in$ indifferently for the proofs, is that so, and if so, why ?

Proof for the total ordering : Let $x,y \in m$. $\exists z_x,z_y \in n, x\in z_x, y\in z_y$. Since $n$ is an ordinal, it is totally ordered by $\in$, therefore either $z_x\in z_y$, or $z_y\in z_x$. Without loss of generality, suppose $z_x\in z_y$. Then $x\in z_x$ and $z_x\in z_y$ imply $x\in z_y$ by transitivity of relation $\in$ on $n$. So $x\in z_y$ and $y\in z_y$. By transitivity of $n$, $x\in n$ and $y\in n$. Since $n$ is totally ordered by $\in$, we have $x\in y$ or $y\in x$. Therefore $m$ is totally ordered by $\in$

A: You can note that since $n$ is transitive, $m\in n$ and therefore $m\subseteq n$. Therefore $m$ is a subset of a finite set, so it is finite, and it is a subset of a well-ordered set so it is well-ordered.
Also, note that for ordinals, $\alpha<\beta\iff\alpha\in\beta$, but since those are transitive sets $\alpha\subseteq\beta$, with inclusion being proper if and only if $\alpha<\beta$, so we have that $\alpha\in\beta\iff\alpha\subsetneq\beta$.

A: There are only two ways to build new ordinals: successor or limit.
You start from the base case $\emptyset$.
To be a limit ordinal, you have to have infinitely many ordinals smaller than you, so you are not finite.
It means that if you are finite, either you are $\emptyset$, or you are a successor ordinal of the form $m\cup\{m\}$ (all successor ordinals have this form). Moreover $m$ needs also to be finite, since if $m$ is infinite $n$ is also infinite.


text:
Q: Building"MyApplication" gradle info i am stuck on android studio 2.3.3, it just runs forever without showing any process ahead. Same for new project and importing old ones

A: Wait for at least 30-40 min if the process remain same uninstall studio completely and reinstall studio and then try to create new project, Hope it may help you.


text:
Q: Identify suitable scoring metric for food prediction I am using GridSearchCV to find the best parameter that help me tune XGBoost for a food prediction algorithm.
I am struggling to identify the best scoring metric that would result in the best profit (sales margin minus wastage costs) as this is ultimately what I am looking for. In running the script below and plugging it into the data (I reserved some data for testing only), I noticed that a higher R Square seems to be  better than a lower RMSE in obtaining a higher profit. But I am struggling to find an explanation which will help me guide to the best scoring method.
Here some infos on the situation: It costs me 6 USD to produce the product and 9 USD to sell, so my margin is 3 USD. Therefore my wastage is 6 USD multiplied by (production minus sales quantities), whereas my earnings are sales quantities multiplied by 3. Example: I produce 100, sell 70, waste 30 my earnings are 70*3 - 30*6 = 30 So I have an imbalance between sales and wastage.
Main Question: Which scoring metric puts a higher penalty weight on the over-prediction?
My current code:
My current code:
X = consumption[feature_names]
y = consumption['Meal1']

data_dmatrix = xgb.DMatrix(data=X,label=y)

# Create the parameter grid: gbm_param_grid
gbm_param_grid = {
    'min_child_weight':[1, 2],
    'gamma': [0.05,0.06],
    'reg_alpha':range(1, 2),
    'colsample_bytree': [0.22, 0.23],
    'n_estimators': range(28, 29),
    'max_depth': range(3, 8),
    'reg_alpha':range(1, 2),
    'reg_lambda':range(1, 2),
    'subsample': [0.7,0.8,0.9],
    'learning_rate': [0.1,0.2],

}
fixed_params = {'objective':'reg:squarederror','booster':'gbtree' }

# Instantiate the regressor: gbm
gbm = xgb.XGBRegressor(**fixed_params)

# Perform grid search: grid_mse
grid_mse = GridSearchCV(estimator=gbm, param_grid=gbm_param_grid, scoring="r2", cv=5, verbose=1)

# Fit grid_mse to the data
grid_mse.fit(X,y)

# Print the best parameters and lowest RMSE
print("Best parameters found: ", grid_mse.best_params_)
print("Lowest Score found: ", np.sqrt(np.abs(grid_mse.best_score_)))

A: You apparently have a situation that fits the newsvendor model in the inventory control literature: you produce for each period, face an uncertain demand, sell as much as is demanded or as much product as you have (whatever is lower), and throw away any leftovers.
Let $p$ denote your selling price and $c$ your purchasing or production cost, and assume your demand follows some distribution with CDF $F$. Then the newsvendor model tells you that your optimal stock position, in terms of expected profit, is $F^{-1}\big(\frac{p-c}{p}\big)$. In the situation you sketched above, $p=9$ and $c=6$, so you are interested in
$$F^{-1}\bigg(\frac{9-6}{9}\bigg)=F^{-1}\bigg(\frac{1}{3}\bigg).$$
In prediction or forecasting, this quantity is a quantile forecast and is more commonly denoted by
$$ \hat{q}_{\frac{1}{3}} := F^{-1}\bigg(\frac{1}{3}\bigg).$$
One problem is that your distribution $F$ is almost certainly not the same in the entire forecasting horizon, $F_t$, because of time dynamics like seasonality or promotional efforts, so we need to cope with time effects,
$$ \hat{q}_{\frac{1}{3}}(t) := F_t^{-1}\bigg(\frac{1}{3}\bigg).$$
Now, how do we elicit this particular quantile forecast? It turns out (Gneiting, 2011, "Quantiles as optimal point forecasts", International Journal of Forecasting) that there is a simple loss function which is minimized by the correct quantile forecast, namely
$$ \text{PL}_\alpha(\hat{y},y) := \begin{cases}
\alpha|\hat{y}-y|, & \text{ if }\hat{y}\leq y \\
(1-\alpha)|\hat{y}-y|, & \text{ if }\hat{y}> y.
\end{cases} $$
In your case, $\alpha=\frac{1}{3}$. Note that this is precisely the loss function used in quantile-regression.
One problem is that this function is not everywhere differentiable. However, it can be approximated smoothly to any desired accuracy (Zheng, 2011, "Gradient descent algorithms for quantile regression with smooth approximation", International Journal of Machine Learning and Cybernetics).

Now, a number of caveats apply.

*

*Does a newsvendor model truly describe your data well? Are your products truly as highly perishable as (paper) newspapers? Or can product be sold over multiple periods? If so, you might need to do some more analysis, probably including simulation of quantile forecasts for different quantiles (note the impact of FIFO/LIFO behavior of your customers).

*Does a service level of only 33% really make sense? Depending on your demand distribution, that may mean a lot of empty shelves at the end of the day, and of frustrated customers. (And also of possibly censored demands once your system goes live. If you decide to live with that, you will need to account for the censoring when you retrain your model.) You may need to think about whether the costs of stockouts are adequately captured by the lost sales alone.


text:
Q: What's the story with TRIM support? The situation with TRIM in Ubuntu has me utterly confused. I don't know whether I need to manually run it or not. Sources I've found are disparate and unclear.
I have Ubuntu 10.04 with latest updates (including kernel 2.6.32-26). I have an Intel X-25M drive with latest firmware, and it is formatted as ext4.
So, does TRIM support run automatically? If not, how do I check if I need to run it, and then how do I run it if necessary?

A: The Linux kernel supports TRIM as of version 2.6.33.
So the answer is: Yes, Linux, in it's latest version, supports TRIM out of the box. Ubuntu 10.04 doesn't though.
The question is whether the feature will be back ported to 2.6.32 or 10.04 will get an update to 2.6.33+. (see João Pinto's answer)
Of course your SSD has to support it as well. There are also still some issues with some specific SSDs (I think the Indilinx ones may still be a bit wonky for example). The SSDs firmware has to implement everything properly - but, I understand, some SSDs implement TRIM in a way that isn't really conform with the ATA standard. Or at least in a buggy way.
The first generation X-25M from Intel doesn't support trim "Properly" (or not at all - strictly speaking). The second generation Intel X-25M G2 does. I don't know whether the latest firmware adds proper TRIM, the Intel website keeps mentioning it's "Optimised for Windows 7", which could mean it's bolted on as a software feature in the windows driver, and that the disk doesn't do it on it's own because Intel left their homework on the bus again :-)

A: TRIM support was introduced in Linux 2.6.33 (Ubuntu 10.10), however it is unlikely that Ubuntu 10.04 will ever receive TRIM support. Once acquired, TRIM support must be activated through FSTab.

A: I see the following pieces in the description of 2.6.32-39 update:

*

*sata_mv: fix broken DSM/TRIM support (v2)

*

*LP: #644694

*ext4: make trim/discard optional (and off by default)
I assume this means that it is now supported.

A: According to this bug report TRIM is not supported with the Ubuntu kernel in Ubuntu Lucid (10.04).
All newer versions of Ubuntu come with a kernel which supports TRIM but you will have to manually activate it if you are using the ext4 file system (default).

A: It looks like this went in Ubuntu-2.6.32-9.13 as commit 9f3979ef, back in Dec of 2009, so has been available in lucid since it was released.
You do of course, need to mount with the discard option to enable it.


text:
Q: Why all files of my npm package are installed in node_modules? Here is what I have in node_modules when I install my package:

Even though I am using this files field in package.json:
"files": [
    "./dist"
  ]

Why is that?

A: Maybe you misunderstood what the files field does:
The optional files field is an array of file patterns that describes the entries to be included when your package is installed as a dependency
The files field is used to define files that should be imported alongside your library when another project install your project as a npm package.

A: Thats how module works.if you don't like node_modules folder try Yarn2 .
Same thing.but different module folder name.

A: Thats how npm works. All yours external dependencies will be downloaded to node_modules.
https://medium.com/maxkimambo/how-does-node-module-loading-actually-work-8aa63849f5ae#:~:text=Modules%20are%20the%20building%20block,are%20using%20ES6%20Javascript%20code.&text=included%20in%20your%20app.,can%20have%20their%20own%20package.


text:
Q: CORS 'Access-Control-Allow-Origin' error in preflight when fetching from Chrome Extension to SvelteKit endpoint When making a GET or POST request to a SvelteKit endpoint with an Authorization header, I get the error
Access to fetch at 'http://localhost:8000/api/user' from origin 'chrome-extension://abcdefg' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I have set host_permissions in my manifest (V3), ["https://*/*", "http://localhost:8000/*"].
In addition, my SvelteKit endpoints should be setting headers, possibly incorrectly,
const res = new Response(JSON.stringify({ user }));
res.headers.set(
      "Access-Control-Allow-Origin",
      "chrome-extension://abcdefg"
    );
return res;

Not sure what else to try, as I need to send the Bearer token to my server, which triggers a preflight that seems to be the cause of this CORS error.

A: mode: 'cors' in the client side fetch request fixed the problem. Thanks pulse!


text:
Q: Visual Studio - Clearing or resetting all pinned properties I am using the pinned properties feature of the VS debugger. However, a property that I have pinned causes an "Internal error in the expression evaluator." I can no longer inspect this object to unpin the problematic property or to view other property values. How do I reset this so I can inspect objects of this type again?
Actions taken so far:

*

*Deleted .vs folder from solution root

A: I got the same issue today.  As mentioned above, this answer solved my problem.
Update your ObjectFavorites.json file.  Eg:
C:\Users\<userName>\Documents\Visual Studio 2019\Visualizers\ObjectFavorites.json


text:
Q: Where are Apache Giraph logs (with log4j) located? I am currently experimenting with Apache Giraph using the configuration described in the QuickStart Tutorial :

*

*Ubuntu 12

*Hadoop 0.20

*Giraph Release 1.2

I am running all computation on a single-node local cluster, as described in the QuickStart.
While running the example computations and other custom codes work fine, I am unable to retrieve/locate the logs expected whith log4j logger.
Could you indicate me where these logs are located, either in local system or HDFS ?
Command used to launch Giraph computation :
$HADOOP_HOME/bin/hadoop path/to/giraph/jar org.apache.giraph.GiraphRunner community.RevertedGraphComputation community.JsonLongLongDoubleVertexInputFormat /user/hduser/input/test_graph.txt community.VertexWithLongValueDoubleEdgeTextOutput /user/hduser/output/reverted

Thank you !
Abreviated version of the java code for logging :
//In RevertedGraphComputation class
 private static Logger LOG = Logger.getLogger(RevertedGraphComputation.class);

 //In compute() method
 LOG.info("Vertex "+vertex.getId());


text:
Q: UIDocument saveToURL deletes original file I'm trying to use -[UIDocument saveToURL:(NSURL *)url forSaveOperation:(UIDocumentSaveOperation)saveOperation completionHandler:(void (^ __nullable)(BOOL success))completionHandler] to save a duplicate at a new URL, however the original file -[UIDocument fileURL] is deleted when doing so?

A: I couldn't find any documentation regarding this, but it seems to be intend. ¯\_(ツ)_/¯ Here is the Hopper disassembly of iOS 15.2:

A: Yeah, UIDocument does that. It's a pain.
If you want to save a UIDocument to a new URL without losing the original, you can do it with a function like this:
func saveDocument(_ document: UIDocument, asCopyTo url: URL, completion: @escaping (Bool, Error?) -> Void) {
    let oldUrl = document.fileURL
    document.save(to: url, for: .forOverwriting) { success in
        if success {
            do {
                try FileManager.default.copyItem(at: url, to: oldUrl)
            } catch let error {
                completion(false, error)
            }
        }
        completion(success, nil)
    }
}

This first saves the existing document at its new url, updating the fileURL so that the UIDocument object remains current and doesn't keep on saving over the old file. Once that's done, and assuming it succeeds, we use FileManager to copy the new file's data back to its original location.
It might seem weird to delete and recreate the file at its original location, and I agree that UIDocument is a pretty horrible creation, but this does at least save you from having to reload the document from the file system to maintain the correct location.


text:
Q: How to get function's parameter value without parameter name in swift? func test(_: [Int]) {
  print("xxx")
}

test([1,2,3])

I saw this code is valid in swift, how can I get the value passed into test?

A: To explicitly answer your question:

how can I get the value passed in test?

You can't, in the same way that after
let _ = someFunction()

you have no way to get at the return value of someFunction. That's really the whole point of _ which basically means "I'm ignoring this intentionally".

A: In order to get the parameter value inside the function, you have to specify the parameterName. Swift's function has this kind of structure :
func someFunction(argumentLabel parameterName: Int) {
    // In the function body, parameterName refers to the argument value
    // for that parameter.
}

where argumentLabel is used on the function caller, for example
func eat(byWhom person: String){}

would become
eat(byWhom: "Victor")

in the caller code.
On the other hand, you can get the "Victor" value from the parameterName :
func eat(byWhom person: String){
    print(person) // should print "Victor"
}

A: create function like this
func test(_ value: [Int]) { }
and then you can call it like this.
test([1,2]) without mentioning the parameter name.

A: There's no chance to get functions parameter value w/o its name. That is why it is being used. But you can do this:
func test(_ value: [Int]) {
  print(value)
}

test([1,2,3])


text:
Q: Why decrement is not working properly in C programming? I'm trying to create a pyramid in C, i need to get the next pattern:
    A
   ABA
  ABCBA
 ABCDCDA
ABCDEDCBA

I need to use nested for loops, but the decrementing is not working properly for me, this is my code:
int main(void)

{

    int i, j, k, g;
    char userLatter;
    printf("please enter an uppercase letter:\n");
    scanf("%c", &userLatter);
    int asci = userLatter;

    for (i = 0; i < 5; i++)
    {

        for (j = 4; j > i; j--)
        {
            printf(" ");
        }

        asci = userLatter;
        for (k = 0; k <= i ; k++)
        {
         printf("%c", asci++);
        }

        for (g = 1; g <= i; g++)
        {
            printf("%c", --asci);
        }

        printf("\n");
    }

}

this is the input "a"
and the output im getting is:
    a
   abb
  abccb
 abcddcb
abcdeedcb

Can you please tell me what am I doing wrong?
tnx

A: Add a:
--asci;

between the two for loops.
In the first loop, asci++ performs a postfix increment: the expression is evaluated to asci and then the object is decremented.

A: Cosider that
printf("%c", --asci);//decreases the value and then prints

is different than
printf("%c", asci--);//prints and then decreases the value


text:
Q: Remove git remote in IntelliJ/PyCharm I Git Remotes dialog I see this for my project:

How do I remove the second remote? The minus button is disabled.
This project is a symbolic link to another git project inside the main project's misc/docker/... directory.
The reason I want to remove this project because it complicates the git operations window.

A: preferences > version control> click on remove icon. After that, the remote is going to appear in the "Unregistered roots" section and is not going to be available in the list of remotes to commit/push

A: Try manually removing it through the config file in the .git folder. It should look something like,
[remote "Remote Name"]
    url =
    fetch =


text:
Q: Generate Invoice in PeopleSoft Has anyone here tried running Generate Invoice in PeopleSoft and encountered an error for its process instance? I can't pinpoint what is causing the error since when process monitor shows error - there are no log files to check.
Here are some additional files that may be useful
Server: PSNT
Process Type: COBOL SQL
Process Name: SFPBIPRC
Description: Invoice Batch Process
Does anyone knows how to debug this?
Thanks!


text:
Q: How do I handle errors when using api_auth gem? Currently for a project I am using api_auth gem. I am hitting on an external api in a function by making a signed request. Currently my code looks like this.
access_id = "someKey"
secret_key = "someRandomGeneratedKey"
request = RestClient::Request.new(url: 'serverUrl', method: get, headers:'headers')

@signed_request = ApiAuth.sign!(access_id, secret_key, request)
@signed_request.execute

I am unable to apply any error handling code to that last statement where I execute the request. Any suggestions?

A: You have to use begin rescue block to exception handling.
begin
    #TODO Exception occurring statement
rescue
    #Exception handling code
end

As you should only rescue specific exception, rather than all.
So as your code suggest that you are using rest_client & api-auth gem so from documentation you can get list of exception that this gem raise.
Example - For rest_client below exceptions need to be handled. (probably this is the solution of your problem, just replace last line as given below)
begin
    @signed_request.execute
rescue RestClient::ExceptionWithResponse, URI::InvalidURIError, RestClient::InternalServerError => err
    p err
end

There are few Exceptions also generated by api-auth gem also like
ApiAuth::ApiAuthError, ApiAuth::UnknownHTTPRequest so you need to rescue all this exceptions.
Reference link -
http://www.rubydoc.info/gems/api-auth/1.4.0/
Thanks!