text:
Q: Django staticfiles and CSS and javaScript I'm using django 1.3 for production and want to use static file's in my CSS and javaScript but it doesn't work , I don't have any problem in my HTML ! how must solve this problem ? I didn't find any solution in django doc .
I use this code for adding static files to my CSS :
{% load static %}
{% get_static_prefix as STATIC_PREFIX %}
#main {
     background-image: url("{{ STATIC_PREFIX }}img.png");
}

I'm using this template tag {% load static %} {% get_static_prefix as STATIC_PREFIX %} in my html and it works fine but I dunno why it doesn't work in CSS !!!

A: Your CSS files aren't rendered by the Django templating engine, they are just served by your web server, so you can't use the Django template language.
If you really wanted to (and this is an exceptionally bad idea) you could serve you CSS files through Django by creating URLs and views that render the CSS files, allowing you to make use of the template language.

A: The documentation for static CSS and image files is here: Current Django Documentation and Django Documentation 1.3.
In your settings.py you'll want to set
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    '/full/page/to/static/',
)

Then you can store your images and css files under that '/full/page/to/static/' directory.
In your template you would use your css and images like this:
<link rel="stylesheet" type="text/css" href="/static/styles.css">

In addition to that you can add a directory structure under the "/static/" directory and it will reflect in URL.
For example
/full/path/to/static/img
/full/path/to/static/css

Would resolve to:
    <link rel="stylesheet" type="text/css" href="/static/css/styles.css">


text:
Q: Read timed out after 30,000 ms I am stackoverflow user.
I asked there a question EGIT saying Read timed out after 30,000 ms
One of the kind user there tried helping me but we couldnt resolve it.
so he suggested me to take my question to superuser as all solutions there couldnt solve my prob and he suspected its internet or proxy or firewall issue.
I am new here, and really dont know how to move stackoverflow question to superuser.
so had to make this new post...
kindly excuse me and please help me in resolving the issue.
details of question are:
Im trying to clone a remote repo over http in my local dest.
im using egit on eclipse luna.
but im always getting error read timed out after 30,000ms.
i know http is correct protocol for it, my username passsword is correct but still this problem occuring multiple times.
pls see screenshot in stackoverflow question for more clear idea. (im not allowed to post images here as I dont have enough reputation on Super User.
UPDDATE: 11-5-2014
When i saw eclipse error log at location .metadata/log
I saw following error message..... i think it says same.... but still adding here in case if it can help solving this problem....
error message is
!ENTRY org.eclipse.egit.ui 4 0 2014-11-05 19:09:13.827
!MESSAGE Read timed out after 30,000 ms
!STACK 0

org.eclipse.jgit.api.errors.TransportException: Read timed out after 30,000 ms
    at org.eclipse.jgit.api.FetchCommand.call(FetchCommand.java:139)
    at org.eclipse.jgit.api.CloneCommand.fetch(CloneCommand.java:178)
    at org.eclipse.jgit.api.CloneCommand.call(CloneCommand.java:125)
    at org.eclipse.egit.core.op.CloneOperation.run(CloneOperation.java:156)
    at

org.eclipse.egit.ui.internal.clone.AbstractGitCloneWizard.executeCloneOperation(AbstractGitCloneWizard.java:433)
    at org.eclipse.egit.ui.internal.clone.AbstractGitCloneWizard.access$2(AbstractGitCloneWizard.java:426)
    at org.eclipse.egit.ui.internal.clone.AbstractGitCloneWizard$6.run(AbstractGitCloneWizard.java:405)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)

Caused by: org.eclipse.jgit.errors.TransportException: Read timed out after 30,000 ms
    at org.eclipse.jgit.transport.BasePackFetchConnection.doFetch(BasePackFetchConnection.java:370)
    at org.eclipse.jgit.transport.TransportHttp$SmartHttpFetchConnection.doFetch(TransportHttp.java:780)
    at org.eclipse.jgit.transport.BasePackFetchConnection.fetch(BasePackFetchConnection.java:301)
    at org.eclipse.jgit.transport.BasePackFetchConnection.fetch(BasePackFetchConnection.java:291)
    at org.eclipse.jgit.transport.FetchProcess.fetchObjects(FetchProcess.java:247)
    at org.eclipse.jgit.transport.FetchProcess.executeImp(FetchProcess.java:160)
    at org.eclipse.jgit.transport.FetchProcess.execute(FetchProcess.java:122)
    at org.eclipse.jgit.transport.Transport.fetch(Transport.java:1111)
    at org.eclipse.jgit.api.FetchCommand.call(FetchCommand.java:130)
    ... 7 more
Caused by: java.io.InterruptedIOException: Read timed out after 30,000 ms
    at org.eclipse.jgit.util.io.TimeoutInputStream.readTimedOut(TimeoutInputStream.java:141)
    at org.eclipse.jgit.util.io.TimeoutInputStream.read(TimeoutInputStream.java:114)
    at org.eclipse.jgit.util.IO.readFully(IO.java:246)
    at org.eclipse.jgit.transport.PacketLineIn.readLength(PacketLineIn.java:186)
    at org.eclipse.jgit.transport.PacketLineIn.readString(PacketLineIn.java:138)
    at org.eclipse.jgit.transport.PacketLineIn.readACK(PacketLineIn.java:102)
    at org.eclipse.jgit.transport.BasePackFetchConnection.negotiate(BasePackFetchConnection.java:655)
    at org.eclipse.jgit.transport.BasePackFetchConnection.doFetch(BasePackFetchConnection.java:356)
    ... 15 more

can anybody help me to resolve this prob?
thanks in advance !!
thanks.

A: I have a headache about GitHub.

*

*there is a setting:window-->preference-->team-->git
change "Remote connection timeout"'s value to 180.

this doesn't do work, but it may work sometime for my network is in a great wall.

*find Git-->Configuration,there are "User Setting","System Setting" and "Repository Setting". Check "User Setting" and "System Setting" files are exist.

*my problem is "User setting"(H:\myeclipse_git.gitconfig) exists but "System setting"(j:\Program Files\Git\etc\gitconfig) do not. So I create .gitconfig in directory ect and copy U's(H:\myeclipse_git.gitconfig) content to it, save change and it works!

Now I've cloned the remote git project.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to read attributes of tag under another tag in xml I want to read value of suppose subTag1's name and id, currently I am able to read attributes of TAG1 but not able to read attributes of subTag1. i am using the following code:
  <TAG1>
<name ='tag1',id='ad'>
<subTAG1>
<name ='abc',id='123'>
<name ='asdfbc',id='143'>
</subTag1>
</TAG1>

    $.ajax({
                    type: "GET",
                    url: dataset,// url from where I am reading xml
                    dataType: "xml",
                    async: false,
                    crossDomain: true,
                    headers: {
                    },
                    success: function (xml) {

                              $(xml).find('TAG1').each(function () {
                                  var dsid = $(this).attr('id');
                                  var dsname = $(this).attr('name');
                              console.log("Dataset id ="+dsid);
                                  console.log("Dataset name ="+dsname);

                        });

A: Your XML is not valid:

*

*Any attribute shall have a name (the equal is not accepted like that)

*There are no comas between attributes

*Name of opening/closing tags shall match (and it is case-sensitive)

*All tags must be closed, either like  or like

So the resolved xml should be like:
<TAG1>
    <name value='tag1' id='ad'/>
    <subTAG1>
        <name value='abc' id='123'/>
        <name value='asdfbc' id='143'/>
    </subTAG1>
</TAG1>

In your JavaScript+JQuery code, the TAG1 element has no attribute, you should look for a "name" tag to get attributes:
success:
    function (xml) {
        $(xml).find('name').each(
            function () {
               var dsid = $(this).attr('id');
               var dsname = $(this).attr('name');
               console.log("Dataset id ="+dsid);
               console.log("Dataset name ="+dsname);
            });
    }


text:
Q: How to convert HashMap to Closure for Titan filter I am using Gremlin 2.5.0 / Groovy 2.3.7.
I have a hashMap that contains key-value pairs of the parameters/values for which I want to filter.  For example, I have
[param1:val1, param2:val2:, param3:val]

The type of query that I want to make is:
g.V.filter{it.param1=='val1' && it.param2=='val2' && it.param3=='val3'}

Is there a straightforward Gremlin/Groovy way of using the hashMap to make the query?

A: You should avoid use of filter in Gremlin when possible, especially with Titan and on large scale graphs.  Use of filter will prevent Titan from making proper use of indices.  You should prefer use of has when possible.
I would attempt to build a pipeline with your Map:
gremlin> g = TinkerGraphFactory.createTinkerGraph()
==>tinkergraph[vertices:6 edges:6]
gremlin> params = [name:'josh',age:32]
==>name=josh
==>age=32
gremlin> pipeline = g.V();null
==>null
gremlin> params.each{k,v->pipeline=pipeline.has(k,v)}
==>name=josh
==>age=32
gremlin> pipeline
==>v[4]

A: I don't know what's acceptable in the filter closure, but this might work.
def params = [param1:'val1', param2:'val2':, param3:'val3']
g.V.filter{
    params.every {key, value ->
        it[key] == value
    }
}


text:
Q: How to activate layout tab in chrome I'm looking for Layout tab for chrome dev tools. I was looking everywhere and can't find it. If it's extension or just in settings...watch img for better idea what I mean

A: There is no such feature in Google Chrome Devtools as of June, 2019.


text:
Q: Component of an Open Set: Polygonal Arcs So I'm reading my Complex Analysis book, and I'm a little confused.
Specifically, I'm puzzled by why it is that we need an open disk that does not intersect any of the line segments of the polygonal arc except those with $z$ as one of its end points. Additionally, couldn't there be other paths through $U$ that intersect some point in this disk that shares no other points besides $z_0$ in common with the first path?
Given that $U$ is an open set, it is straightforward enough that there exists an $r$ that does not intersect any of these line segments.

A: Apparently, a polygonal arc is not allowed to have self-intersections. So, to be able to say

the polygonal arc in $U$ formed when the segment from $z$ to $w$ is appended to $A$,

we have to know that this segment from $z$ to $w$ does not cross line segments already in $A$. This is the reason for the choice of $U$.

couldn't there be other paths

Sure there are. Not every step of proof is dictated by necessity; there are choices to be made. The author needed some polygonal arc going to $w$, and
this was the construction  of such an arc they chose to present.


text:
Q: SQL: Select all observations within a series of date ranges? I have an OLAP structured sql server database. My fact table is sales.
I have 2 dimensions and 1 fact table. The dimensions are as follows:
Product (ProductID, ProductName, ProductDescription, ListPrice)
Promotion (ProductID, Discount, StartDate, EndDate)

And the Fact table:
Sales (SalesID, CustomerID, ProductID, Date, ProductReturned)

Note, the Promotion dimension does not have a unique identifier of its own. I believe that the four element tuple is ~composite primary key.
First, I'd like to create a primary key called PromotionID, storing it in this dimension. Next, I'd like to iterate through each of the observations in the sales fact table, if the date of an observation falls within the range StartDate -> EndDate in the Promotion dimension, I want to assign a foreign key attribute as the PromotionID. Lastly, I want to select all observations from the sales fact table where the FK PromotionID is not NULL.
Two questions:

*

*How do I accomplish this affect?

*Are the above steps the easiest way to reach this goal - or is there a simpler way?


text:
Q: The colors of the PopupMenuItems and Cards are wrong after Flutter upgrade The colors of PopupMenuItems and Cards must match the background of the PopupMenu and Cards color. Before the update the colors were wrong and to fix it I used ElevationOverlay.applySurfaceTint but now this doesn't work. I tried everything I know.

AppBar Code:
appBar: AppBar(
        automaticallyImplyLeading: false,
        elevation: 4,
        surfaceTintColor: Theme.of(context).colorScheme.surfaceTint,
        backgroundColor: Theme.of(context).colorScheme.surface,
        title: const Text('Asistente'),
        centerTitle: true,
        actions: [
          PopupMenuButton(
              position: PopupMenuPosition.under,
              // color: ElevationOverlay.applySurfaceTint(
              //     Theme.of(context).colorScheme.surface,
              //     Theme.of(context).colorScheme.surfaceTint,
              //     2),
              elevation: 2,
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(4)),
              constraints: const BoxConstraints(
                minWidth: 112,
                maxWidth: 280,
              ),
              iconSize: 30,
              icon: CircleAvatar(
                backgroundImage: NetworkImage(user.photoURL!),
              ),
              // icon: const Icon(Icons.account_circle_outlined),
              itemBuilder: (BuildContext context) => [
                    PopupMenuItem(
                      child: ListTile(
                        iconColor:
                            Theme.of(context).colorScheme.onSurfaceVariant,
                        leading: const Icon(Icons.settings),
                        onTap: (() {
                          Navigator.pop(context);
                          openDialog(context);
                        }),
                        title: Text(
                          'Configuración',
                          style: Theme.of(context)
                              .textTheme
                              .labelLarge
                              ?.copyWith(
                                  color:
                                      Theme.of(context).colorScheme.onSurface),
                        ),
                      ),
                    ),
                    PopupMenuItem(
                      child: ListTile(
                        iconColor:
                            Theme.of(context).colorScheme.onSurfaceVariant,
                        leading: const Icon(Icons.account_circle),
                        onTap: (() {
                          Navigator.pop(context);
                          infoDialog(context);
                        }),
                        title: Text(
                          'Información',
                          style: Theme.of(context)
                              .textTheme
                              .labelLarge
                              ?.copyWith(
                                  color:
                                      Theme.of(context).colorScheme.onSurface),
                        ),
                      ),
                    ),
                    PopupMenuItem(
                      child: ListTile(
                        iconColor:
                            Theme.of(context).colorScheme.onSurfaceVariant,
                        leading: const Icon(Icons.logout_outlined),
                        onTap: (() {
                          final provider = Provider.of<GoogleSignInProvider>(
                              context,
                              listen: false);
                          provider.logout();
                          Navigator.pop(context);
                        }),
                        title: Text(
                          'Cerrar Sesión',
                          style: Theme.of(context)
                              .textTheme
                              .labelLarge
                              ?.copyWith(
                                  color:
                                      Theme.of(context).colorScheme.onSurface),
                        ),
                      ),
                    ),
                  ])
        ],
      ),

For theming I'm using Material 3 with color scheme
Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => GoogleSignInProvider(),
      child: Consumer<ThemeProvider>(builder: (context, provider, child) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          title: 'Tesis',
          theme: ThemeData(
            useMaterial3: true,
            colorScheme: lightColorScheme,
          ),
          darkTheme: ThemeData(
            useMaterial3: true,
            colorScheme: darkColorScheme,
          ),
          themeMode: provider.themeMode,
          initialRoute: '/',
          routes: {
            '/': (context) => const Start(),
            '/second': (context) => const Home(),
          },
        );
      }),
    );
  }

Color Scheme
const lightColorScheme = ColorScheme(
  brightness: Brightness.light,
  surfaceTint: Color(0xFF6750A4),
  onErrorContainer: Color(0xFF410E0B),
  onError: Color(0xFFFFFFFF),
  errorContainer: Color(0xFFF9DEDC),
  onTertiaryContainer: Color(0xFF31111D),
  onTertiary: Color(0xFFFFFFFF),
  tertiaryContainer: Color(0xFFFFD8E4),
  tertiary: Color(0xFF7D5260),
  shadow: Color(0xFF000000),
  error: Color(0xFFB3261E),
  outline: Color(0xFF79747E),
  onBackground: Color(0xFF1C1B1F),
  background: Color(0xFFFFFBFE),
  onInverseSurface: Color(0xFFF4EFF4),
  inverseSurface: Color(0xFF313033),
  onSurfaceVariant: Color(0xFF49454F),
  onSurface: Color(0xFF1C1B1F),
  surfaceVariant: Color(0xFFE7E0EC),
  surface: Color(0xFFFFFBFE),
  onSecondaryContainer: Color(0xFF1D192B),
  onSecondary: Color(0xFFFFFFFF),
  secondaryContainer: Color(0xFFE8DEF8),
  secondary: Color(0xFF625B71),
  inversePrimary: Color(0xFFD0BCFF),
  onPrimaryContainer: Color(0xFF21005D),
  onPrimary: Color(0xFFFFFFFF),
  primaryContainer: Color(0xFFEADDFF),
  primary: Color(0xFF6750A4),
);

const darkColorScheme = ColorScheme(
  brightness: Brightness.dark,
  surfaceTint: Color(0xFFD0BCFF),
  onErrorContainer: Color(0xFFF2B8B5),
  onError: Color(0xFF601410),
  errorContainer: Color(0xFF8C1D18),
  onTertiaryContainer: Color(0xFFFFD8E4),
  onTertiary: Color(0xFF492532),
  tertiaryContainer: Color(0xFF633B48),
  tertiary: Color(0xFFEFB8C8),
  shadow: Color(0xFF000000),
  error: Color(0xFFF2B8B5),
  outline: Color(0xFF938F99),
  onBackground: Color(0xFFE6E1E5),
  background: Color(0xFF1C1B1F),
  onInverseSurface: Color(0xFF313033),
  inverseSurface: Color(0xFFE6E1E5),
  onSurfaceVariant: Color(0xFFCAC4D0),
  onSurface: Color(0xFFE6E1E5),
  surfaceVariant: Color(0xFF49454F),
  surface: Color(0xFF1C1B1F),
  onSecondaryContainer: Color(0xFFE8DEF8),
  onSecondary: Color(0xFF332D41),
  secondaryContainer: Color(0xFF4A4458),
  secondary: Color(0xFFCCC2DC),
  inversePrimary: Color(0xFF6750A4),
  onPrimaryContainer: Color(0xFFEADDFF),
  onPrimary: Color(0xFF381E72),
  primaryContainer: Color(0xFF4F378B),
  primary: Color(0xFFD0BCFF),
);

A: The problem was a compatibility conflict between the new versions and the ListTile on the Cards and PopupMenu. The solution was to remove the ListTile.
The new PopupMenu:
actions: <Widget>[
          PopupMenuButton<Item>(
            position: PopupMenuPosition.under,
            initialValue: selectedMenu,
            onSelected: (Item item) {
              setState(() {
                selectedMenu = item;
                if (selectedMenu == Item.itemOne) {
                  infoDialog(context);
                } else if (selectedMenu == Item.itemTwo) {
                  openDialog(context);
                } else if (selectedMenu == Item.itemThree) {
                  final provider =
                      Provider.of<GoogleSignInProvider>(context, listen: false);
                  provider.logout();
                }
              });
            },
            itemBuilder: (context) => [
              PopupMenuItem<Item>(
                value: Item.itemOne,
                child: Row(
                  children: const [
                    Padding(
                      padding: EdgeInsets.only(right: 12),
                      child: Icon(Icons.account_circle),
                    ),
                    Text(
                      'Información',
                    ),
                  ],
                ),
              ),
              PopupMenuItem<Item>(
                value: Item.itemTwo,
                child: Row(
                  children: const [
                    Padding(
                      padding: EdgeInsets.only(right: 12),
                      child: Icon(Icons.settings),
                    ),
                    Text('Configuración'),
                  ],
                ),
              ),
              PopupMenuItem<Item>(
                value: Item.itemThree,
                child: Row(
                  children: const [
                    Padding(
                      padding: EdgeInsets.only(right: 12),
                      child: Icon(Icons.logout_outlined),
                    ),
                    Text('Cerrar Sesión'),
                  ],
                ),
              ),
            ],
            child: CircleAvatar(
              backgroundImage: NetworkImage(user.photoURL!),
            ),
          )
        ],

The new Cards:
Card(
      clipBehavior: Clip.antiAlias,
      child: SizedBox(
        width: 300,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Image(
              image: NetworkImage(widget.products.imageUrl),
              fit: BoxFit.cover,
            ),
            Padding(
              padding: const EdgeInsets.fromLTRB(8, 8, 0, 0),
              child: Text(
                widget.products.name,
                style: Theme.of(context).textTheme.titleMedium,
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(left: 8),
              child: Text('Precio: ${widget.products.price}\$'),
            ),
            Container(
              margin: const EdgeInsets.only(left: 8),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text('Cantidad: '),
                  Padding(
                    padding: const EdgeInsets.only(left: 8),
                    child: QuantityMenu(
                      quantityFuction: quantityFunction,
                    ),
                  ),
                ],
              ),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Padding(
                  padding: const EdgeInsets.fromLTRB(0, 0, 8, 8),
                  child: ElevatedButton(
                    style: ButtonStyle(
                      foregroundColor: MaterialStateProperty.all<Color>(
                        const Color(0xFFFFFFFF),
                      ),
                      backgroundColor: MaterialStateProperty.all<Color>(
                        const Color(0xFF6750A4),
                      ),
                    ),
                    onPressed: () => showDialog(
                      context: context,
                      barrierDismissible: false,
                      builder: (BuildContext context) => AlertDialog(
                        title: SizedBox(
                          width: 240,
                          height: 260,
                          child: QrImage(
                            data: data,
                            backgroundColor: Colors.white,
                          ),
                        ),
                        content: Text('ID del producto: $data'),
                        actions: <Widget>[
                          TextButton(
                              onPressed: () {
                                Navigator.pop(context);
                              },
                              child: const Text('Cerrar')),
                        ],
                      ),
                    ),
                    child: const Text(
                      'Mostrar QR',
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(0, 0, 8, 8),
                  child: ElevatedButton(
                    style: ButtonStyle(
                      foregroundColor: MaterialStateProperty.all<Color>(
                        const Color(0xFFFFFFFF),
                      ),
                      backgroundColor: MaterialStateProperty.all<Color>(
                        const Color(0xFF6750A4),
                      ),
                    ),
                    onPressed: () => showDialog(
                      context: context,
                      barrierDismissible: false,
                      builder: (BuildContext context) => AlertDialog(
                        title: Text(
                          '¿Desea eliminar el producto ${widget.products.name} de la base de datos?',
                          textAlign: TextAlign.center,
                        ),
                        actions: <Widget>[
                          TextButton(
                              onPressed: () {
                                Navigator.pop(context);
                              },
                              child: const Text('Cancelar')),
                          TextButton(
                              onPressed: () {
                                final docProducts = FirebaseFirestore.instance
                                    .collection('products')
                                    .doc(widget.products.id);

                                docProducts.delete();
                                Navigator.pop(context);
                              },
                              child: const Text('Eliminar')),
                        ],
                      ),
                    ),
                    child: const Text(
                      'Eliminar',
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(0, 0, 8, 8),
                  child: ElevatedButton(
                    style: ButtonStyle(
                      foregroundColor: MaterialStateProperty.all<Color>(
                        const Color(0xFFFFFFFF),
                      ),
                      backgroundColor: MaterialStateProperty.all<Color>(
                        const Color(0xFF6750A4),
                      ),
                    ),
                    onPressed: () => showDialog(
                      context: context,
                      barrierDismissible: false,
                      builder: (BuildContext context) => AlertDialog(
                        content: Text(
                          '¿Desea añadir $quantity ${widget.products.name}(s) a la lista de compras? \n \n'
                          'Atencion!: Si este producto ya se encuentra en el carrito añadirlo de nuevo reemplazará el anterior',
                          textAlign: TextAlign.center,
                        ),
                        actions: <Widget>[
                          TextButton(
                              onPressed: () {
                                Navigator.pop(context);
                              },
                              child: const Text('Cancelar')),
                          TextButton(
                              onPressed: () {
                                double total = widget.products.price *
                                    double.parse(quantity);
                                addToList(
                                        id: widget.products.id,
                                        total: total,
                                        name: widget.products.name,
                                        price: widget.products.price,
                                        imgUrl: widget.products.imageUrl,
                                        quantity: quantity)
                                    .then((value) => Navigator.pop(context));
                              },
                              child: const Text('Añadir')),
                        ],
                      ),
                    ),
                    child: const Text(
                      'Añadir al Carro',
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );


text:
Q: Ruby Kernel::system, negation pattern in shell command not working as expected The following bash command removes all hidden files from a directory called foo (excludes . and ..):

rm -rf foo/.[^.]*

I would expect that passing this same command to Ruby's Kernel::system should do the same thing:

system("rm -rf foo/.[^.]*")

However, the above Ruby code returns false and produces this:

rm: cannot remove `..' directory `foo/..'

If I try it this way:

system("rm", "-rf", "foo/.[^.]*")

Then it returns true, but does not delete anything.

If I do away with the -f flag:

system("rm", "-r", "foo/.[^.]*")

Then it returns false and produces this:

rm: cannot remove `foo/.[^.]*': No such file or directory

I'm wondering if perhaps the system call is evaluating the negation pattern [^.] as literal characters or something. I'm not sure what the problem is.
Any insight or suggestions would be much appreciated. Thanks!

A: The system command passes a single string argument to /bin/sh for processing (not /bin/bash). I can't find a definitive citation, but it appears that [^.] would be two
literal characters, ^ and ., in sh. Try [!.] instead.
In your second and third examples, the arguments to "system" are passed directly to exec, and not processed by the shell, so the patterns (not regexes, by the way) are not expanded. In the second, the -f lets it ignore the fact that there is no file "foo/.[^.]*" to remove; in the third, the error is not suppressed.


text:
Q: Hiding/Unhiding Inner Layouts in Android I need to have the capacity to hide/unhide (in the sense of View.GONE) an entire linear layout row in an Activity.  Is this the best approach to just to get a reference to the inner layout that is part of a greater relative layout and set visibility on that inner layout to gone?  Also should I maintain a reference to the layout so I can just do innerLayout.setVisibility(View.GONE).  If so what type of reference should it be ? final or is it better to just do a find each time I want to hide/unhide.  Somehow keeping a direct reference to a layout does not seem quite right.  On the other hand, I don't want to set each item in the layout to be gone or put a findBy to locate it each time I hide/unhide.
Perhaps add/remove layout is better form? but then I would need to add to the right place in the View hierarchy, putting this logic in code is also not a good idea.

A: Is yur linear layout set in XML or made programmatically?
if its done in XML:
note that if any views use this view as a reference in the layout such as android:layout_below="@+id/this" then that won't be a very good idea.
You can use something like this, it will hide all of the child views and itself, not hide but completely gone (No space taken up by it)
Use this as a reference either in the class if you want to use it in multiple methods or in the method which you are using it
View layout;

Then in onCreate call this
layout = findViewById(R.id.linearLayout);

then to make it dissapear:
layout.setVisibility(View.GONE);

or
layout.setVisibility(8);

and to get it back
layout.setVisibility(View.VISIBLE);

or
layout.setVisibility(0);


text:
Q: How to create and execute procedures in MySQL workbench I created a Spatial table Points using SQL Editor in MySQL workbench. To fill this table,
the following is the code I am using.
CREATE PROCEDURE fill_points(
IN size INT(10)
)
BEGIN
DECLARE i DOUBLE(10,1) DEFAULT size;

DECLARE lon FLOAT(7,4);
DECLARE lat FLOAT(6,4);
DECLARE position VARCHAR(100);

-- Deleting all.
DELETE FROM Points;

WHILE i > 0 DO
SET lon = RAND() * 360 - 180;
SET lat = RAND() * 180 - 90;

SET position = CONCAT( 'POINT(', lon, ' ', lat, ')' );

INSERT INTO Points(name, location) VALUES ( CONCAT('name_', i), GeomFromText(position) );

SET i = i - 1;
END WHILE;
END

when I executed it, it shows the error

Error Code: 1064. You have an error in your SQL syntax; check the
  manual that corresponds to your               MySQL server version for
  the right syntax to use near 'END' at line 1

Executing the statement
CALL fill_points(1000);
shows the same error
I even don't know whether the way I proceed is correct or not.
Can anybody help me...

A: Have you ended the entire query? Try setting a delimiter, and use it after the END so the server knows you finished the command.
delimiter //
CREATE PROCEDURE fill_points(
IN size INT(10)
)
BEGIN
DECLARE i DOUBLE(10,1) DEFAULT size;

DECLARE lon FLOAT(7,4);
DECLARE lat FLOAT(6,4);
DECLARE position VARCHAR(100);

-- Deleting all.
DELETE FROM Points;

WHILE i > 0 DO
SET lon = RAND() * 360 - 180;
SET lat = RAND() * 180 - 90;

SET position = CONCAT( 'POINT(', lon, ' ', lat, ')' );

INSERT INTO Points(name, location) VALUES ( CONCAT('name_', i), GeomFromText(position) );

SET i = i - 1;
END WHILE;
END //
delimiter ;

Also, by the by
While DELETE FROM TABLE does remove all data from the table, TRUNCATE table does so faster. Unless you have good reasons to use DELETE (they exist), TRUNCATE might be what you want.


text:
Q: I wanna study on iOS App and Game development but I don't have any Mac device I know little bit C Programming and Java. I want to start hard study on Objective-C and all other stuff that needed for Apple App and Game development, But I don't have any MacBook or iMac where I can learn them with xCode. I have just a iPhone 5.
Can anyone please let me know, how can I process on my Windows/Ubuntu computer?
Thank you,
John

A: Working on PC always have some difficulties, my advise is go and buy a mid price level Mac mini. Probably you can connect your monitory with it.
http://store.apple.com/us/buy-mac/mac-mini
Here is the Video tutorial for your first time :
http://channel9.msdn.com/Series/Visual-Studio-Tools-for-Apache-Cordova/Creating-your-first-Hello-World-app-with-Tools-for-Apache-Cordova

A: If you are a newer developer, it will be easier and a more efficient use of your time to learn Apple's new language, Swift. I don't believe the rumors that Apple is planning to phase objective-C out any time soon, but I know from experience that it is much easier to go from Java to Swift than to objective-C, especially considering that objective-C has little benefit over swift in programming for iOS.
You can download the Swifty app on your phone today for free to start learning swift.


text:
Q: date range in drupal-6 view arguments? I have a view which loads certain goods elements on the view based upon start date and end date, what i need is a date range. Unfortunately in drupal arguments there is no range and filtering option.
I'm using only one table in mysql, which receive from and two date and returns specific items.
I tried this code, but it's not working. Is there any date-range filter which does the job or should I write my own filter?
function abc_display_screen() {
  $viewName = 'abc';
  $arg = '2008-01-04--2014-02-04';
  $viewsHtml .= views_embed_view($viewName, 'default', $arg);
  return $viewsHtml;
}

A: Could you not use two filters instead?
Filter by dates below x and above y ?

A: I think the date module may do this for you. It has some views integration and I belive that this is something it does. However the versions you are using may cause some integration headaches at the moment.


text:
Q: Jsf NullPointerException ManagedBean when accessing other bean or property After searching for hours I finally found what caused a nullpointerexception. It's the use of the property Survey in my QuestionController.create(). When I comment out the line getSurvey().. the page works just fine. All other functionality works fine as well. Only the QuestionController.create() doesn't work. I know my injected managedProperty works as the surveyname (questionController.survey.surveyName) displays correctly on the page.
Does anyone know why my QuestionController turns Null when trying to use the create() function?
javax.faces.el.EvaluationException: java.lang.NullPointerException
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:724)
Caused by: java.lang.NullPointerException
at com.survey.jsfController.QuestionController.create(QuestionController.java:69)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at javax.el.ELUtil.invokeMethod(ELUtil.java:326)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:536)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256)
at com.sun.el.parser.AstValue.invoke(AstValue.java:269)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 35 more

My Managed bean QuestionController
@SessionScoped
@ManagedBean(name = "questionController")
public class QuestionController extends Controller  implements Serializable {

private QuestionService questionService;
private QuestionTypeService questionTypeService;

public QuestionController() {
    setQuestionService(ApplicationController.getQuestionService());
    setQuestionTypeService(ApplicationController.getQuestionTypeService());
    question = new Question();
}

@PostConstruct
private void init(){
    setSurvey(getSessionController().getSurvey());
}

private static final long serialVersionUID = 1L;

private Question question;

private Survey survey;

private String surveyId;

@ManagedProperty("#{sessionController}")
private SessionController sessionController;

public Question getQuestion() {
    return question;
}

public void setQuestion(Question question) {
    this.question = question;
}

public List<Question> getQuestions() {
        return getQuestionService().retrieveAll();
}

public List<QuestionType> getQuestionTypes() {
        return getQuestionTypeService().retrieveAll();
}

public void create() {
    //TODO: link survey with this question
    getSurvey().getQuestions().add(getQuestion());
    //surveyService.update(survey);
    questionService.create(getQuestion());
    FacesContext.getCurrentInstance().addMessage("questionCreation", new FacesMessage("Question has been created succesfully!"));
}

public String update() {
    questionService.update(question);
    FacesContext.getCurrentInstance().addMessage("questionCreation", new FacesMessage("Question has been updated succesfully!"));
    return "overview";
}

public String delete() throws RemoteException {
    getQuestionService().delete(question);
    FacesContext.getCurrentInstance().addMessage("questionDeletion",
            new FacesMessage("Question has been deleted succesfully!"));
    return "overview";
}

public String show(Question question){
    if (question != null) setQuestion(question);
    return "detail";
}

public String update(Question question){
    if (question != null) setQuestion(question);
    return "update";
}

public String delete(Question question){
    if (question != null) setQuestion(question);
    return "delete";
}

public void setSurveyId(String survey) {
    this.surveyId = survey;
}

public String getSurveyId() {
    return this.surveyId;
}

@Override
public void clear(){
    setQuestion(null);
    FacesContext.getCurrentInstance().addMessage("formClearing", new FacesMessage("Form cleared!!", "The answer creation has been submitted successfully"));
}

public SessionController getSessionController() {
    return sessionController;
}

public void setSessionController(SessionController sessionController) {
    this.sessionController = sessionController;
}

public Survey getSurvey() {
    return survey;
}

public void setSurvey(Survey survey) {
    this.survey = survey;
}

public QuestionService getQuestionService() {
    return questionService;
}

public void setQuestionService(QuestionService questionService) {
    this.questionService = questionService;
}

public QuestionTypeService getQuestionTypeService() {
    return questionTypeService;
}

public void setQuestionTypeService(QuestionTypeService questionTypeService) {
    this.questionTypeService = questionTypeService;
}

}

My managed bean SessionController
@SessionScoped
@ManagedBean(name = "sessionController")
public class SessionController extends Controller{

private Survey survey;

private String emailAddress;

private String password;

public String getEmailAddress() {
    return emailAddress;
}

public void setEmailAddress(String emailAddress) {
    this.emailAddress = emailAddress;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public String login() {

    return "about";
}

public String logout() {
    FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
    return "login";
}

public Survey getSurvey() {
    return survey;
}

public void setSurvey(Survey survey) {
    this.survey = survey;
}

The questionCreate.xhtml

Step 1: Created survey: #{questionController.surveyId}

            Step 2: Create questions

Step 3: Create benchmark

Step 4: Create graph per question

            <f:facet name="header">Create question for survey #{questionController.survey.surveyName} </f:facet>

            <h:outputText value="#{msg['question']}" for="question" />
            <h:inputText id="question"
                value="#{questionController.question.question}"></h:inputText>

            <h:outputText value="#{msg['selectType']}" for="questionType" />

                <f:selectItem itemLabel="select questionType" itemValue=""/>

                <f:selectItems value="#{questionController.questionTypes}" var="q"
                    itemLabel="#{q.typeName}" />

            <f:facet name="footer">
                <h:panelGroup>
                    <h:commandButton value="#{msg['createButton']}"
                        action="#{questionController.create()}"/>
                    <h:commandButton value="Clear"
                        action="#{questionController.clear()}" immediate="true">
                        <f:resetValues render="form form:question" />
                    </h:commandButton>
                </h:panelGroup>
            </f:facet>

        <h:messages style="color:red" />

        <ui:include src="listRetrieveComponent.xhtml"></ui:include>

    </ui:define>

Thanks for having a look!

A: You are setting Survey in @PostConstruct
@PostConstruct
private void init(){
    setSurvey(getSessionController().getSurvey());
    //But Survey survey; is null of SessionController
    //getSessionController().getSurvey() is giving you null
}

BUT Survey survey; Of SessionController is null you have to initialized it so you have to first instantiate Survey in constructor or make sure it's not null before using it.
public class SessionController extends Controller{
   private Survey survey;//Not Initialized
   private String emailAddress;
   private String password;
   ...

EDIT After Comment:
Okay than I think getSurvey().getQuestions() is returning null that's what causes NPE.

A: Maybe the questions list of the survey haven't been initialized. so before you had a question you should check if survey.getQuestions() is null and if it is you initialize it.


text:
Q: Split 1st column values to search two other columns and return single value I'm attempting to take a CONCATENATEd value in a column (A), SPLIT that value in two and VLOOKUP two columns in another sheet (same file).  The issue I'm running into is if there are not two values to SPLIT in the CONCATENATEd cells, I get an error.  I can flip my formula to search for two values or one (two values JOINed with : or a single value), but not both.
This is the latest iteration of my formula that's only showing half of the desired results.
=ArrayFormula(VLOOKUP(IF(FIND(":",A3:A),SPLIT(A3:A,":"),A3:A),{materialsData!C2:C,materialsData!D2:D,materialsData!E2:H},4,))

Here is an example sheet of what I'm trying to do.

A: try:
=ARRAYFORMULA(IFNA(VLOOKUP(A3:A, {IF(materialsData!D2:D<>"",
 materialsData!C2:C&":"&materialsData!D2:D, materialsData!C2:C), materialsData!F2:F}, 2, 0)))


text:
Q: Deleting Rows in VBA if it satisfies some criteria Please find the related workbook attached below:
https://www.dropbox.com/s/zlwz12sigx5w6le/deleting%20rows.xlsm
So there are 3 columns, column A is dates, column B is values related to a bank and column C is "exitflag". Essentially what I want to do is the following:
If the number is 1 under "exitflag", then I want to delete the entire row, eg, in row 2, "exitflag" takes on a value of 1, so I want the entire row deleted such that both the date and the value related to the bank is also deleted. By delete I mean I want the row removed so that the next row "shifts" up so that no empty row appears. Also note that there is also the number 1 under column B, eg, row 201, I do not want to delete those, I only want the rows deleted where exitflag has a value of 1.
I have written the following code but for some reason I don't think it works (or if it does work, I have to keep running it over and over, it doesn't do what I want in one go):
Sub DeleteRows()

    For Each R In Selection.Rows

        For Each c In R.Cells(1, 3)
            If c.Value = 1 Then
                R.Delete
            End If
        Next

    Next

End Sub

Also preferably I would like the code to be a "selection." code rather than specifying a range as I would like to reuse the code on other datasets but with different number of rows.
Much appreciated for any assistance!

A: It's quite common mistake made also by good programmers. When deleting you should start with the last position and count backwards. If not, you will remove one element of the collection changing the order of other elements within collection. As a result you (rather) won't delete all required collection items.
Without looking into your sheet this could be a solution (not tested):
Sub DeleteRows()

    Dim i as Long
    For i= Selection.Rows.Count To 1 Step -1

        For Each c In Selection.Rows(i).Cells(1, 3)
            If c.Value = 1 Then
                c.EntireRow.Delete Shift:=xlUp
                Exit For  'can be important
            End If
        Next

    Next

End Sub

A: Try this.
Sub DeleteRows()
    Dim flag As Range, exitFlags As Range

    Set exitFlags = Selection //NOTE: just select the ExitFlags column

        For Each flag In exitFlags
            If flag = 1 Then
                flag.EntireRow.Delete Shift:=xlUp
            End If
        Next
End Sub


text:
Q: Remove an array from an array list I have an array list, like this one: http://pastebin.com/UKrrVyUs
I need to remove the array4 because his category is the same of the array1
I was thinking to use unset but he remove the array leaving the position empty, how i can remove the array4 generating a new array list like:
Array( [0] => Array () [1] => Array () [2] => Array () [3] => Array ()  [4] => Array () )

where the array[4] is the previously Array[5] ?


text:
Q: Type class instances for type synonyms are disallowed I tried to implement a show function for a custom type called Token. I have tried the following code:
type Token =
    { identifier :: String
    , value :: String
    }

instance showToken :: Show Token where
    show t = "(Token " <> t.identifier <> ", " <> t.value <> ")"

I get the following error however:
Type class instances for type synonyms are disallowed.

The error provides a link, but it does not provide any helpful information. What does it mean and how can it be fixed?

A: Use newtype to give Token a distinct type from the record. Otherwise, you're simply defining a type alias.
import Prelude

newtype Token = Token
  { identifier :: String
  , value :: String
  }

instance showToken :: Show Token where
  show (Token t) = "(Token " <> t.identifier <> ", " <> t.value <> ")"


text:
Q: Lifetime of references in closures I need a closure to refer to parts of an object in its enclosing environment. The object is created within the environment and is scoped to it, but once created it could be safely moved to the closure.
The use case is a function that does some preparatory work and returns a closure that will do the rest of the work. The reason for this design are execution constraints: the first part of the work involves allocation, and the remainder must do no allocation. Here is a minimal example:
fn stage_action() -> Box<Fn() -> ()> {
    // split a freshly allocated string into pieces
    let string = String::from("a:b:c");
    let substrings = vec![&string[0..1], &string[2..3], &string[4..5]];

    // the returned closure refers to the subtrings vector of
    // slices without any further allocation or modification
    Box::new(move || {
        for sub in substrings.iter() {
            println!("{}", sub);
        }
    })
}

fn main() {
    let action = stage_action();
    // ...executed some time later:
    action();
}

This fails to compile, correctly stating that &string[0..1] and others must not outlive string. But if string were moved into the closure, there would be no problem. Is there a way to force that to happen, or another approach that would allow the closure to refer to parts of an object created just outside of it?
I've also tried creating a struct with the same functionality to make the move fully explicit, but that doesn't compile either. Again, compilation fails with the error that &later[0..1] and others only live until the end of function, but "borrowed value must be valid for the static lifetime".
Even completely avoiding a Box doesn't appear to help - the compiler complains that the object doesn't live long enough.

A: There's nothing specific to closures here; it's the equivalent of:
fn main() {
    let string = String::from("a:b:c");
    let substrings = vec![&string[0..1], &string[2..3], &string[4..5]];
    let string = string;
}

You are attempting to move the String while there are outstanding borrows. In my example here, it's to another variable; in your example it's to the closure's environment. Either way, you are still moving it.
Additionally, you are trying to move the substrings into the same closure environment as the owning string. That's makes the entire problem equivalent to Why can't I store a value and a reference to that value in the same struct?:
struct Environment<'a> {
    string: String,
    substrings: Vec<&'a str>,
}

fn thing<'a>() -> Environment<'a> {
    let string = String::from("a:b:c");
    let substrings = vec![&string[0..1], &string[2..3], &string[4..5]];
    Environment {
        string: string,
        substrings: substrings,
    }
}

The object is created within the environment and is scoped to it

I'd disagree; string and substrings are created outside of the closure's environment and moved into it. It's that move that's tripping you up.

once created it could be safely moved to the closure.

In this case that's true, but only because you, the programmer, can guarantee that the address of the string data inside the String will remain constant. You know this for two reasons:

*

*String is internally implemented with a heap allocation, so moving the String doesn't move the string data.

*The String will never be mutated, which could cause the string to reallocate, invalidating any references.

The easiest solution for your example is to simply convert the slices to Strings and let the closure own them completely. This may even be a net benefit if that means you can free a large string in favor of a few smaller strings.
Otherwise, you meet the criteria laid out under "There is a special case where the lifetime tracking is overzealous" in Why can't I store a value and a reference to that value in the same struct?, so you can use crates like:
owning_ref
use owning_ref::RcRef; // 0.4.1
use std::rc::Rc;

fn stage_action() -> impl Fn() {
    let string = RcRef::new(Rc::new(String::from("a:b:c")));

    let substrings = vec![
        string.clone().map(|s| &s[0..1]),
        string.clone().map(|s| &s[2..3]),
        string.clone().map(|s| &s[4..5]),
    ];

    move || {
        for sub in &substrings {
            println!("{}", &**sub);
        }
    }
}

fn main() {
    let action = stage_action();
    action();
}

ouroboros
use ouroboros::self_referencing; // 0.2.3

fn stage_action() -> impl Fn() {
    #[self_referencing]
    struct Thing {
        string: String,
        #[borrows(string)]
        substrings: Vec<&'this str>,
    }

    let thing = ThingBuilder {
        string: String::from("a:b:c"),
        substrings_builder: |s| vec![&s[0..1], &s[2..3], &s[4..5]],
    }
    .build();

    move || {
        thing.with_substrings(|substrings| {
            for sub in substrings {
                println!("{}", sub);
            }
        })
    }
}

fn main() {
    let action = stage_action();
    action();
}

Note that I'm no expert user of either of these crates, so these examples may not be the best use of it.


text:
Q: Chrome floped image background stuck issue I am having a weird problem with Chrome.
If I flop an image using -webkit-transform, show another div on top it and then hide the div, part of the image is showed in background as some sort of ghost image.
Here is the fiddle
http://jsfiddle.net/fahadnabbasi/d4erm/
The problem is only in chrome.
I am using Mac OS X and latest version of chrome for mac.
Please please held me as I am out of options here

A: if you remove  -webkit-transform: matrix(1, 0, 0, -1, 0, 0); the issue no longer appears
try instead
-webkit-transform: rotateX(180deg);
-webkit-transform-origin: 50% 28%;

example fiddle : http://jsfiddle.net/JHFQV/


text:
Q: Compute $\iint_ S \text{F}.\vec n\; \text{d}S$, with and without using Divergence theorem Given a vector field $$\text{F}=(xz^2)\vec i+(x^2y-z^3)\vec j+(2xy+y^2z)\vec k$$

*

*How to describe $\Sigma_1$ in cylindrical coordinates?

*How to generally find $\vec n$?

And $S$ is the sphere half sphere $z= \sqrt {4-x^2-y^2}$ and $z=0$, then compute $$\iint_ S \text{F}\cdot\vec  n\; \text{d}S$$

From Divergence theorem I know that the double integral is indeed:
$$\begin{align}
\iiint_V \nabla \cdot \text{F} \;\text{d} V &= \iiint_V x^2+y^2+z^2 \;\text{d} V\\[1ex]
&= \int_{0}^{2 \pi}\int_{0}^{2}\int_{0}^{\sqrt {4- \rho^2
}}(\rho^2+z^2)\rho \;\text{d}z\text{d}\rho\text{d}\theta\\[1ex]
&=\frac{64\pi}{5}\end{align}$$
If I was going to compute $\iint_ S \text{F}\cdot\vec  n\; \text{d}S$ directly without using Divergence theorem, then how I could proceed?

The surface $S$ can be written as $$S= \Sigma_1 \cup \Sigma_2$$
Where $$\Sigma_1= \left\{(\rho \cos\theta,\rho  \sin\theta
,z):  0\le \theta  \le
 2\pi , 0 \le z  \le \sqrt{4-\rho^2} \right\}$$
$$\Sigma_2= \left\{(2 \cos\theta,2 \sin\theta,0): 0\le \theta \le  2\pi \right\}$$
And $$\vec n_1=\frac{\partial \Sigma_1}{\partial \theta}×  \frac{\partial \Sigma_1}{\partial z}=\langle \rho\cos\theta,\rho\sin\theta,0 \rangle $$
So:$$\iint_ {\Sigma_1} \text{F}\cdot\vec  n_1\; \text{d}S$$$$=\int_{0}^{2 \pi}\int_{0}^{\sqrt{4-\rho^2} } z^{2}r^{2}\cos^{2}\theta+\left(r^{2}\cos^{2}\theta\sin\theta-z^{3}\right)r\sin\theta\;\text{d}z\text{d}\theta\tag{I} $$
And $$\vec n_2=\frac{\partial \Sigma_2}{\partial \theta}\times  \frac{\partial \Sigma_2}{\partial z}=\langle 0,0,0 \rangle $$
So:$$\iint_ {\Sigma_2} \text{F}\cdot\vec  n_2\; \text{d}S=0 \tag{II}$$
Now we need to add $(\text{I})$ and $(\text{II})$
$$\iint_ S \text{F}\cdot\vec  n\; \text{d}S=\iint_ {\Sigma_1} \text{F}\cdot\vec  n_1\; \text{d}S+\iint_ {\Sigma_2} \text{F}\cdot\vec  n_2\; \text{d}S$$
However I doubt if $\Sigma_1$ describes the half sphere correctly.

A: First, let's work on $\Sigma_1$, we consider the parametrization,
$$x=r\cos \theta, y=r\sin \theta, z=\sqrt{4-r^2}$$
$$\begin{bmatrix} \cos \theta \\ \sin \theta \\ \frac{-r}{\sqrt{4-r^2}}\end{bmatrix}  \times \begin{bmatrix} -r\sin \theta \\ r \cos \theta \\ 0 \end{bmatrix}=\begin{bmatrix} \frac{r^2\cos \theta}{\sqrt{4-r^2}} \\ \frac{r^2 \sin \theta}{\sqrt{4-r^2}}\\ r\end{bmatrix}$$
$$F(r, \theta) =\begin{bmatrix} r(4-r^2)\cos \theta \\ r^3\cos^2 \theta \sin \theta - (4-r^2)^\frac32\\ 2r^2\sin \theta \cos \theta + r^2 \sin ^2 \theta\sqrt{4-r^2}\end{bmatrix}$$
\begin{align}
&\int \int_{\Sigma_1} F \cdot \vec{n}_1 dS\\
&=\int_0^2 r^3\sqrt{4-r^2}\, dr \int_0^{2\pi}\cos^2 \theta \, d\theta + \int_0^2 \frac{r^5}{\sqrt{4-r^2}}\, dr \int_0^{2\pi}\sin^2 \theta \cos^2 \theta \, d\theta + \int_0^2r^3 \sqrt{4-r^2}\, dr \int_0^{2\pi} \sin^2 \theta \, d\theta \\
&= 2\pi \int_0^{2}r^3\sqrt{4-r^2}\, dr + \frac{\pi}4 \int_0^2 \frac{r^5}{\sqrt{4-r^2}}\, dr\\
&= 2\pi \left(\frac{64}{15} \right) + \frac{\pi}{4} \left( \frac{256}{15}\right)\\
&=3\pi \left(\frac{64}{15} \right)\\
&= \frac{64\pi}{5}
\end{align}
Now, let's work on $\Sigma_2$,
$$x=r\cos \theta, y=r\sin \theta, z=0$$
$$ \begin{bmatrix} -r\sin \theta \\ r\cos\theta \\ 0\end{bmatrix} \times \begin{bmatrix} \cos \theta \\ \sin \theta \\ 0\end{bmatrix}=\begin{bmatrix} 0 \\ 0 \\ -r\end{bmatrix}$$
\begin{align}
&\int\int_{\Sigma_2} F \cdot \vec{n}_2 dS\\
&= \int_0^2-r^3 \, dr \int_0^{2\pi} \sin \theta \cos \theta\, d\theta
\\&=0
\end{align}


text:
Q: Example of exception in ArrayList? I am using ArrayList and I want an example of Exception in case if multiple threads try to access the same list without synchronization ? I done this in single threaded application in which if we remove an element from list while iteration it throws ConcurrentModificationExceptoin but I want to achieve the same in multi threaded environment. If anyone could give me an example of that would be highly appreciated ?
package com.test2;

public class ThreadTest extends Thread {

    List list = new ArrayList<String>();

    @Override
    public void run() {

        list.add("1");
        list.add("2");
        list.add("3");
        list.add("4");
        list.add("5");
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        list.add("6");
        list.add("7");
        list.add("8");

        Iterator<String> it = list.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }

    }

    public static void main(String[] args) {

        Thread th1 = new ThreadTest();
        Thread th2 = new ThreadTest();
        Thread th3 = new ThreadTest();
        th1.start();
        th2.start();
        th3.start();
        try {
            th1.join();
            th2.join();
            th3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}

A: Quick answer:
public class Main {

    public static void main(String[] args) throws InterruptedException
    {
        final ArrayList<String> list = new ArrayList<String>();
        list.add("Item 1");
        list.add("Item 2");
        list.add("Item 3");
        list.add("Item 4");

        Thread thread = new Thread(new Runnable()
        {
            @Override
            public void run ()
            {
                for (String s : list)
                {
                    System.out.println(s);
                    try
                    {
                        Thread.sleep(1000);
                    }
                    catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread.start();

        Thread.sleep(2000);
        list.remove(0);
    }
}

Output:
Item 1
Item 2
Exception in thread "Thread-0" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
    at java.util.ArrayList$Itr.next(ArrayList.java:831)
    at com.akefirad.tests.Main$1.run(Main.java:34)
    at java.lang.Thread.run(Thread.java:745)

Note:
As @Braj and @DaoWen said you are using different instances. Either use their suggestions or pass the list variable in the constructor of your class (ThreadTest).

A: You're accessing a separate list instance in each of your threads. Since each list is only accessed by one thread, you can't get a concurrency error.
List list = new ArrayList<String>();

That declares an instance field. Therefore, each call to new ThreadTest() creates a new list. In order to make all the ThreadTest instances use the same list, try making the field static (i.e. a class field):
static List list = new ArrayList<String>();

As for how an error can happen, take a look at the code for ArrayList's add method:
 public boolean add(E e) {
     ensureCapacityInternal(size + 1);  // Increments modCount!!
     elementData[size++] = e;
     return true;
 }

If two threads call add at the same time, they could process the elementData[size++] = e statement at the same time. The size field is not declared volatile; therefore, the two threads could end up writing to the same index in the elementData array.
Even if size were declared volatile, the size++ operation is not atomic. See How to model a situation, when i++ is corrupted by simultaneously executing threads? for an example of how an operation like size++ can fail in a multithreaded environment.
Finally, if you don't understand what volatile and atomic mean in the Java context, you really need to read up on concurrent programming in Java before you write any multithreaded code. It will be a worthwhile investment as you'll save yourself a lot of headaches by understanding these concepts.

A: If I understand your question, yes change this
List list = new ArrayList<String>();

by using Collections.synchronizedList(List) to something like (and don't use raw types),
List<String> list = Collections.synchronizedList(new ArrayList<String>());

From the javadoc,

Returns a synchronized (thread-safe) list backed by the specified list. In order to guarantee serial access, it is critical that all access to the backing list is accomplished through the returned list.
It is imperative that the user manually synchronize on the returned list when iterating over it:
List list = Collections.synchronizedList(new ArrayList());
...
synchronized (list) {
  Iterator i = list.iterator(); // Must be in synchronized block
  while (i.hasNext())
    foo(i.next());
  }
}

A:
it throws ConcurrentModificationExceptoin but I want to achieve the same in multi threaded environment
I am asking how to get an exception in multithreaded environment - From comment

Since you are creating separate copy of List for each thread hence there is no chance to get this exception.
Just make the List as shared resource then you will encounter this exception:
sample code:
public class Main{

    public static void main(String[] args){

        // shared by all the threads.
        final List<String> list = new ArrayList<String>();

        class ThreadTest extends Thread {

            @Override
            public void run() {

                list.add("1");
                list.add("2");
                list.add("3");
                list.add("4");
                list.add("5");
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                list.add("6");
                list.add("7");
                list.add("8");

                Iterator<String> it = list.iterator();
                while (it.hasNext()) {
                    System.out.println(it.next());
                }

            }
        }

        Thread th1 = new ThreadTest();
        Thread th2 = new ThreadTest();
        Thread th3 = new ThreadTest();
        th1.start();
        th2.start();
        th3.start();
        try {
            th1.join();
            th2.join();
            th3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Output:
Exception in thread "Thread-2" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
    at java.util.ArrayList$Itr.next(Unknown Source)
    at com.test.TestDemo$1ThreadTest.run(TestDemo.java:390)


text:
Q: free(ptr) crashes sometimes, pointer is always valid I am trying to create some streams of bytes, dynamically allocated, and perform a copy of them in some other place. My code is this (earlier i didn`t type from a pc :) ):
    void construct_cypherstreams(uint8_t * stream, int key_length, int stream_length, uint8_t ** encr_streams, int * bytes_in_stream) {
        // chyperstream = the stream formed of every ith byte
        uint8_t * cypherstream;
        int length;
        length = stream_length / key_length + 1;
        // each byte of the key can have values
        // between 0 and 256
        int i = 0;
        int num_added = 0;
        for (int k = 0; k < key_length; k++) {
            printf("\n%s %d\n", "iteration", k);
            i = k; num_added = 0;
            cypherstream = (uint8_t *)malloc(length * sizeof (char));
            if (cypherstream == NULL) {
                printf("%s\n", "could not allocate");
                exit(1);
            }
            else {
                printf("%s\n", "succesfully allocated");
            }
            while (i < stream_length) {
                // construct cypherstream
                cypherstream[num_added] = stream[i];
                num_added++;
                i += key_length;
            }
            printf("\n%s\n", "created cypherstream:");
            for (int m = 0; m < num_added; m++) {
                printf("%X", cypherstream[m]);
            }
            printf("\n");
            printf("%s\n", "making deep copy...");
            encr_streams[k] = (uint8_t *)malloc(num_added * sizeof(char));
            // perform deep copy of characters
            for (int n = 0; n < num_added; n++) {
                encr_streams[k][n] = cypherstream[n];
            }
            printf("%s\n", "done making deep copy");
            free(cypherstream);
            printf("%s\n", "succesfully freed");
            printf("%s %d\n", "position:", k);
            printf("%s %d\n", "num_added:", num_added);
            bytes_in_stream[k] = num_added;
            printf("%s\n", "iteration ended");
        }
    }

And I call it like this:
    uint8_t ** encr_streams;
    int  * bytes_in_stream;
    encr_streams = (uint8_t **)malloc(key_length * sizeof **encr_streams);
    bytes_in_stream = (int *)malloc(key_length * sizeof *bytes_in_stream);
    construct_cypherstreams(stream, key_length, stream_length, encr_streams, bytes_in_stream);

Now my program sometimes runs, sometimes crashes.
I am stuck here for the moment and I could really use some help.
Compiler: msvc
Thanks

A: This is a case of heap corruption as you are trying to overwrite some dynamically allocated memory.

A: encr_streams = (uint8_t **)malloc(key_length * sizeof **encr_streams);

just looks wrong. I think it should be
encr_streams = malloc(key_length * sizeof *encr_streams);

because you seem to intend to allocate an array of pointers to uint8_t. Then you probably also have to initialize the elements of that array by something.

A: If you program on Linux, run your code under the valgrind memory debugger:

*

*http://valgrind.org/docs/manual/quick-start.html
For Windows... you may want to try MS AppVerifier though I haven't used it for years and forgot almost everything about it :-(

*

*How to use Microsoft Application Verifier


text:
Q: How to automatically convert dots on paper maps to vector points? I have several paper maps with dots that I need to convert to vector points.  I was hoping to get some suggestions on how to accomplish this without recreating each and every point by hand.  I know the basic workflow will look something like this:

*

*Scan paper maps.

*Use QGIS Georeferencer plugin to georeference maps.

*Run some kind of analysis to identify dots and convert to vector
points.

I'm fine on 1-2, but a little stuck on 3.  I've provided a sample crop of one of the maps below.

A: You can clean up the scan in Gimp first and make processing a lot easier: Use the 'select by colour' tool and select the map background, adjusting the threshold to give a nice clean selection. Invert the selection, so the lines and points are now selected.

Now 'shrink' the selection down Select > Shrink... by enough pixels so that just you points remain, 'grow' the selection a tiny bit and fill the selection with a solid colour. This stage may take a bit of playing around with shrink and grow values. Undo and try again if needed.

Georeference the raster image as before and then vectorise it Raster > Conversion > Polygonize, filter the polygons to show those with value 0 (black) and create polygon centroids from them.

There may be smarter or more accurate ways to do this, but it really does only take a minute using this method.

A: I guess the third step would be(among others) use high/low pass filters to eliminate the lines.Then Rasterize the resultant image to get points digitized automatically.


text:
Q: Регулярные выражения в MySQL Такой вопрос, насколько эффективно использование регулярок в запросах к БД
Например, у меня есть база, в которой 2000 статей. Необходимо сделать выборку статей, в тексте которых есть фраза, удовлетворяющая некой регулярке. Сделать это можно:

*

*Считать все статьи, а дальше,
        средствами php например, отобрать
        необходимые

*Использовать
        регулярку в запросе к БД (то есть,
        использование LIKE, RLIKE и тд)

Собственно, как лучше поступать и в каких случаях?
A: Лучше на уровне БД выполнять всё что можно, особенно отсеивание и выборку данных.
Причины на это очень простые:

*

*У MySQL данные организованы специально для поиска, т.е. однако в случае с регулярками это не столь существенно

*MySQL читает данные сразу из памяти.

*PHP работает заметно медленнее MySQL, написанного на С++

*Передача данных из MySQL в PHP происходит через сетевые интерфейсы, затем обрабатывается адаптером PHP чтобы из формата MySQL преобразовать в PHP формат.

A: Я бы не рекомендовал использовать регулярки в MySQL при большом объеме данных, они будут сильно нагружать сервер и тормозить, лучше продумать полнотекстовый поиск по словам (MATCH AGAINST) или использовать LIKE с индексом, но как было сказано выше, ни в коем случае, не делать фильтр средствами PHP.


text:
Q: Protection from accidentally misnaming object attributes in Python? A friend was "burned" when starting to learn Python, and now sees the language as perhaps fatally flawed.
He was using a library and changed the value of an object's attribute (the class being in the library), but he used the wrong abbreviation for the attribute name.  It took him "forever" to figure out what was wrong.  His objection to Python is thus that it allows one to accidentally add attributes to an object.
Unit tests don't provide a solution to this.  One doesn't write unit tests against an API being used.  One may have a mock for the class, but the mock could have the same typo or incorrect assumption about the attribute name.
It's possible to use __setattr__() to guard against this, but (as far as I know), no one does.
The only thing I've been able to tell my friend is that after several years of writing Python code full-time,  I don't recall ever being burned by this.  What else can I tell him?

A: There are code analyzers like pylint that will warn you if you add a attribute outside of __init__. PyDev has nice support for it. Such errors are very easy to find with a debugger too.

A: If the possibility to make mistakes is enough for him to consider a language "fatally flawed", I don't think you can convince him otherwise. The more you can do with a language, the more you can do wrong with the language. It's a caveat of flexibility—but that's true for any language.

A: You can use the __slots__ class attribute to limit the attributes that instances have. Attempting to set an attribute that's not expliticly listed will raise an AttributeError. There are some complications that arise with subclassing. See the Python data model reference for details.

A: A tool like pylint or pychecker may be able to detect this.

A: "changed the value of an object's attribute"  Can lead to problems.  This is pretty well known.  You know it, now, also.  That doesn't indict the language.  It simply says that you've learned an important lesson in dynamic language programming.

*

*Unit testing absolutely discovers this.  You are not forced to mock all library classes.  Some folks say it's only a unit test when it's tested in complete isolation. This is silly.  You have to trust the library modules -- it's a feature of your architecture.  Rather than mock them, just use them.   (It is important to write mocks for your own newly-developed libraries.  It's also important to mock libraries that make expensive API calls.)
In most cases, you can (and should) test your classes with the real library modules.  This will find the misspelled attribute name.

*Also, now that you know that attributes are dynamic, it's really easy to verify that the attribute exists.  How?
Use interactive Python to explore the classes before writing too much code.
Remember, Python is not Java and it's not C.  You can execute Python interactively and determine immediately if you've spelled something wrong.  Writing a lot of code without doing any interactive confirmation is -- simply -- the wrong way to use Python.
A little interactive exploration will find misspelled attribute names.

*Finally -- for your own classes -- you can wrap updatable attributes as properties.  This makes it easier to debug any misspelled attribute names.  Again, you know to check for this.  You can use interactive development to confirm the attribute names.
Fussing around with __setattr__ creates problems.  In some cases, we actually need to add attributes to an object.  Why?  It's simpler than creating a whole subclass for one special case where we have to maintain more state information.

Other things you can say:
I was burned by a C program that absolutely could not be made to work because of ______.  [Insert any known C-language problem you want here.  No array bounds checking, for example]  Does that make C fatally flawed?
I was burned by a DBA who changed a column name and all the SQL broke.  It's painful to unit test all of it.  Does that make the relational database fatally flawed?
I was burned by a sys admin who changed a directory's permissions and my application broke.  It was nearly impossible to find.  Does that make the OS fatally flawed?
I was burned by a COBOL program where someone changed the copybook, forgot to recompile the program, and we couldn't debug it because the source looked perfect.  COBOL, however, actually is fatally flawed, so this isn't a good example.

A: He's effectively ruling out an entire class of programming languages -- dynamically-typed languages -- because of one hard lesson learned. He can use only statically-typed languages if he wishes and still have a very productive career as a programmer, but he is certainly going to have deep frustrations with them as well. Will he then conclude that they are fatally-flawed?

A: I think your friend has misplaced his frustration in the language. His real problem is lack of debugging techniques. teach him how to break down a program into small pieces to examine the output. like a manual unit test, this way any inconsistency is found and any assumptions are proven or discarded.

A: I had a similar bad experience with Python when I first started ... took me 3 months to get over it. Having a tool which warns would be nice back then ...


text:
Q: Include background image using react-material-ui-carousel I am trying to use a background image in a carousel component, but when I refer to the image as a component, I could not run the development because one character error blocks.
I would like to use some background images with the products I want to expose.
export default function Management() {

  var items = [
    {
      name: "Produto #1",
      description: "Oculos esportivo"
    },
    {
      name: "Produto #2",
      description: "Jaqueta Jeans"
    },
    {
      name: "Produto #3",
      description: "Presente para o dia das crianças"
    }
  ]

  return (
    <Layout>
      <Carousel
        autoPlay={"false"}
        animation={"fade"}
      >
        {
          items.map((item, i) => <Item key={i} item={item} />)
        }
      </Carousel >

managing products

    </Layout>
  )
  function Item(props) {
    return (
      <Paper>
        <FormControlLabel
          control={<Checkbox icon={<FavoriteBorder />} checkedIcon={<Favorite />} name="checkedH" />}
          label="Meu Favorito"
        />
        <Box borderRadius={16} {...defaultProps} >

{props.item.name}

{props.item.description}

        </Box>
      </Paper>
    )
  }
}

A: This is a Banner I found that works as I wanted when I posted it.
import React from 'react'
import { Carousel } from 'react-responsive-carousel';
import "react-responsive-carousel/lib/styles/carousel.min.css";
//import './Banner.css';

export default function Banner() {
  return (
    <Carousel
      autoPlay
      infiniteLoop
      showThumbs={false}>

Legend 4

Legend 5

Legend 4

      </Carousel>
  )
}


text:
Q: Is there any way to prevent chrome's password manager to save the password only for a specific web page? I am trying to figure out whether it is possible for Chrome or any web browser to not to ask for saving password only for a specific web page?
(for example only if I log into Oracle BI or Oracle 12c admin page, I do not want a scenerio where user can save it later and may be exploited)

A: I did this for not storing password in browser.
<input type="text" name="password" autocomplete="off" readonly
onfocus="this.removeAttribute('readonly');" >

you can do same for username or email that you are using with passwords.


text:
Q: How do I get the first day of the previous year through yesterday one year ago? For example, I'm current hard-coding it like this
  "ACCOUNT1"."account_opendate" >= '01/01/2021' and
  "ACCOUNT1"."account_opendate" <= '05/08/2021'

I would like to instead use a dateadd like in SQL, but I keep getting an error.
I tried something like this and got an error:
  "ACCOUNT1"."account_opendate" >=  DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) - 1, 0)

I'd also like to have another query where I get the first day of the current month one year ago, so...
  "ACCOUNT1"."account_opendate" >= '05/01/2021'

Any ideas?

A: There are two questions here.  Let's tackle the first one.
The reason you are likely having issues with the dates is that Drill doesn't automatically recognize text as dates.  Drill is schema free (sort of) and so trying to compare strings that way, won't work.
In any event, the way to convert a string field to a date is with the CAST() function.   Thus, you could do something like:
WHERE CAST(`ACCOUNT1`.`account_opendate` AS DATE) >= CAST('01/01/2021' AS DATE) AND
CAST(`ACCOUNT1`.`account_opendate` AS DATE) <= CAST('05/08/2021' AS DATE)

Take a look at the Drill date time function documentation for more info about Drill's date/time functions. Drill does have DATEADD and many others.
One more thing.  Drill uses backticks rather than double quotes for identifiers.
For the second part, I'm not sure exactly how to do that, but I'd think you could construct a date by extracting the current month, then subtracting one year. You might also be able to do it with the NEARESTDATE function.


text:
Q: How to prove that an existence statement cannot be constructive Given the well known spaces of sequences:
 $$
l_\infty =\{(x_n), n\in \mathbb{N}, x_n \in \mathbb{R} : \sup_n |x_n|<\infty\}
$$
$$
l_1= \{(x_n), n\in \mathbb{N}, x_n \in \mathbb{R} : \sum_n |x_n|<\infty\}
$$
we can prove, by Hahn-Banach theorem, that $l_1\subsetneqq( l_\infty)^*$, where $( l_\infty)^*$ is the dual space of $ l_\infty$. But it seems that it's impossible to show explicitly an element of $( l_\infty)^*/l_1$.
Here I found that "it is impossible for an explicit example to be constructed", but there is not a proof of this statement.
I found the same statement also here, but again without proof.
I tried to find a proof but it's too hard for me. Someone can give me a sketch of the proof, or indicate an accessible source where I can find such proof?
I'm interested to this question because it's connected with that Do we really need reals?, being an example of a non constructive existence theorem with an explicit proof of the fact that a constructive approach is impossible. Some one know other similar results?

A: The answer is given in both your sources, in the second one more explicitly. Shelah showed that, assuming ZF is consistent, ZF cannot prove that $(\ell^\infty)^\ast \neq \ell^1$. In particular, some non-constructive methods are needed to separate $(\ell^\infty)^\ast$ from $\ell^1$. Shelah's result is even stronger: even ZF+DC cannot prove that $(\ell^\infty)^\ast \neq \ell^1$ (Dependent Choice is a weak form of AC).
Here ZF is Zermelo–Fraenkel, the usual constructive set of axioms used for set theory. The non-constructive Axiom of Choice is also usually assumed, and it implies in particular the Hahn–Banach theorem, which in turn shows that $(\ell^\infty)^\ast \neq \ell^1$. Without AC, however, the Hahn–Banach theorem cannot be proved, as Shelah's result shows. Shelah proved his result by constructing a model of ZF+DC in which $(\ell^\infty)^\ast = \ell^1$. The exact paper of Shelah is probably referenced in Schechter's book Handbook of Analysis and its Foundations, but it might prove to be too technical for you (or me).


text:
Q: Create custom keyboard within app not external How am I able to create a keyboard that is already enabled in the app, or is it just buttons put next to each other to make it seem like a keyboard. Like the image below
http://i.imgur.com/qIoxR0a.png

A: you can use to the UIButton element or UIView with TouchBegan. But don't keyboard extension because different controller.

A: You can use ETCustomKeyboard which is mostly like same as you need.
And the output of that is show into below image:

You can modify this as per your need.
And HERE is one more same like that.
Hope this will help.

A: Create the keyboard as an ordinary UIView, and make it the inputView for your text field.  There is more information in Apple's Custom Views for Data Input page.


text:
Q: Determining the mass of a rolling cart If I have a cart that has a force sensor on it and then I have the available supplies: Motion sensor, computer to read the motion and force sensors, weights and weight holder, wood blocks (tilt the track) and also some springs, then how could I go about getting the mass of the cart without a scale or spring scale?
The computer outputs a graph of the position, velocity, acceleration, and the force.
I'm guessing there are multiple ways to go about determining the mass of the cart, but I'm not sure what all of them could be, so I'll write about my idea, but it would be nice if someone can help confirm I'm doing it correctly and if they have any other ideas.
My first idea is to tilt the track (with the wood blocks) and then start recording the data of $x(t)\;v(t)\;a(t)\;\;and\;\; F(t)(not \;useful\;here)$ so that I'm collecting data that I can then get values from. So, start with the track tilted and the cart being held at zero velocity and then release it. I think that it doesn't matter if I let the cart come to rest or if I stop recording data while it is still rolling (shouldn't make a difference in my calculations). Then I can use these equations to find acceleration: $$v_f^2=v_i^2+2a(x_f-x_i)\;\;\;or\;\;\;x_f^2=x_i^2+v_it+{1\over2}at^2$$
I can only use the second if I keep track of time. So, at this point, I may be able to use Newton's second law $F=ma$ but I'm not sure what to do with the force if I want to solve for m. I'm stuck at this point for this idea.
For my second idea, I can just pull on the force sensor hook and measure the force and acceleration but I'm not sure what to do with friction here. If I ignore friction (I would like to be able to justify doing that) then it should be simple to calculate the mass. I could also use the spring here, but that just complicates everything at this step.
If anyone can answer my above questions I would be very grateful, sorry for them being so easy I just can't get a hang of physics for some reason, it doesn't come naturally to me. Thank you!

A: Do your second experiment, where you apply a known force on flat ground, measure the acceleration, and apply $F=ma$. If you're worried about friction, measure it by bringing the cart to a known velocity and observing it decelerate. If the friction forces end up being much smaller than the force you applied in your first measurement, then don't worry about it. If not, then you'll have to characterize the friction more carefully and disentangle them.


text:
Q: How to count the number of incoming calls a specific number has in callLog.calls? ANDROID QUERY CALL LOGS I have a phonestatelistener which retrieves the incoming call number
what i want to do is to have that certain number queried and checked in the callLog content provider and get the number of incoming calls that specific number has made on a specific date
and with that, i want to check also if that number has the most incoming calls for the specific time given, if yes, only his calls will ring, otherwise, no ring will be heard
the app actually considers the person with the most incoming calls as a frequent caller,
if he qualifies, then he will be considered an important contact and his calls will ring
my problem is, how do i do it in a query?? heeelpp!!

A: You can use the code as
   Uri urlcall = Uri.parse("content://call_log/calls/");
   Cursor receivec = null;
   receivec = HomeErasor.this.getContentResolver().query(urlcall,
                null, "TYPE='" + CallLog.Calls.INCOMING_TYPE + "'", null,
                null);

   if (c.moveToFirst()) {
        do {

//here you will get all information like number and date compare same number with different date and that date should be as you want.( CALLLOG.CALL.DATE return time+date ) by comparing this you will get how many times that number called you.
            String num =c.getString(c.getColumnIndex(CallLog.Calls._ID));
            String queryString = "_ID=" + num;
            // Log.v("_ID", queryString);
            // use value
        } while (c.moveToNext());
    }


text:
Q: How to determine the Average and Worst Case Space Complexity of Bucket Sort Can someone tell how the average and worst case SPACE complexity of Bucket sort is found?

A: Well first off we need to understand how bucket sort works:

*

*Create an empty array

*Loop through the original array and put each object in a bucket

*Sort each of the non-empty buckets

*Check the buckets in order and then put all objects back into the original array.

This makes bucket sort a great algorithm for big lists that need to be sorted. The average time complexity is O(n+k) where n is the number of your buckets. The worst time complexity is Θ(n^2). The reason for that is because bucket sort is useful when input is uniformly distributed over a range since whenever there are keys that are close to each other they are probably going to end up in the same bucket otherwise we would need a bucket for each key in the original array.
The worst case space complexity is O(nk).
Space complexity is a measure of the amount of working storage an algorithm needs. That means how much memory, in the worst case, is needed at any point in the algorithm. As with time complexity, we're mostly concerned with how the space needs grow, in big-Oh terms, as the size N of the input problem grows.
I hope that helped!


text:
Q: c++ system command I have written a sample c++ program...here i am using system command to call python program with an argument...
system("python /home/rpms/a3/dsp/noise_rem_python.py /home/rpms/a3/dsp/files/p1f%d.txt",tid);

/home/rpms/a3/dsp/noise_rem_python.py is a program name

/home/rpms/a3/dsp/files/p1f%d.txt is a parameter for this program.
but I am getting error as:

"/usr/include/stdlib.h: In function 'void* writefile(void*)':
  /usr/include/stdlib.h:712: error: too many arguments to function 'int system(const char*)'
  writefile.cpp:29: error: at this point in file"

A: You can also do it this way:
char command[200];    // 200 is just an example value that can hold the whole string
sprintf(command, "python /home/rpms/a3/dsp/noise_rem_python.py /home/rpms/a3/dsp/files/p1f%d.txt", tid);
system(command);

if you want to do it in the same style.

A: Say this:
#include <string>

system(("python /home/rpms/a3/dsp/noise_rem_python.py /home/rpms/a3/dsp/files/p1f" + std::to_string(tid) + ".txt").c_str());

A: look at the end of the arguments you are passing in to the function
... ,tid);
if you are trying to format a string? Do it before you use it as an argument.


text:
Q: Centering an image with css not working I just started taking a web design class about 4 weeks ago and I'm extremely interested in it. If anyone can help a newbie like me, I'd be very grateful.
I'm not quite sure on what the problem is here. The code worked on a separate file of mine, but when
I tried to start a new project it just wouldn't work anymore. :/
Here is my HTML:
<!DOCTYPE html>

<title>Good Boy</title>
<link rel="stylesheet" type="text/css" href="goodboyslove.css">
<link rel="shortcut icon" href="images/GBFavicon.ico">

Here is my CSS:
<!DOCTYPE css>

.center {
display: block;
margin-left: auto;
margin-right: auto; }

#gblogo{position:relative;top:32px;}

A: doctype is a document type declaration which is not valid in a CSS document. Removing that will solve the issue. CSS falls under a MIME type which you are declaring with the  type="text/css" of your link tag.
Here is a introduction article regarding HTML and includes a section of the use of doctype

A: Try This! (I do not guarantee)
Your HTML file:
<!DOCTYPE html>

<title>Good Boy</title>
<link rel="stylesheet" type="text/css" href="goodboyslove.css">
<link rel="shortcut icon" href="images/GBFavicon.ico">

Your CSS file:
.center {
display: block;
margin-left: auto;
margin-right: auto;
position: relative;
}


text:
Q: How to transform one object to another in Objective-C? I am working on a small game which is pretty much finished. The thing is it didn't have any menus or game over acreens and the like. Everything used to be in a single class Game which had all the logic and rendering. To make the menus possible I created a State class and now there is a StateGame, StateMenu, ... The problem is that I don't know how to switch one state to the other. Currently the State class has a method switchTo: (State*)new state. In the method I put:
[self release];
self = newState;

This produces a segfault and I changed it to:
State *old = self;
self = newState;
AUTORELEASE (old)

This simply doesn't work.
Sorry for the formatting but I'm typing this on a phone, anyways, any help would be greatly appreciated

A: Well, you probably don't want to "change the object to another"... (Not recommended by the way, self = ... bad idea :[ )
What you'll want is a new Class called, ie GameManager. it will have a property that can be Game, a Menu or a GameOver instance. It will work as a state machine (perform action on state changes) and will display, according to the state, a Game, a Menu or a GameOver screen.