text:
Q: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type Я написал утилиту, которая преобразует массив в объект объектов. Но компилятор TS выдает непонятную ошибку
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. No index signature of type 'string' was found on type '{}'
Вот сам код:
type Map<V> = { [key: string]: V };

export const arrayToObjectByKey = (
  arr: Array<object>,
  keyField: string = 'id',
): Map<object> =>
  Object.assign({}, ...arr.map(item => ({ [item[keyField]]: item })));

Ругается на строке { [item[keyField]]: item }
Как это исправить и вообще почему это происходит?

A: не спрашивайте у меня зечем это автору
не спрашивайте у меня зечем это сообществу
я просто оставлю тут
там песочница
TS
/**
 * в случае понимания объектов и ключей
 * и что станет с объектом если его использовать как ключ:
 * ```
   type $key = any;
   ```
   смотри блок `T2`
 */
type $key = number | string | symbol;
// -,-
interface $item {
    [k: string]: $key;
}
// -,-
type $map<T> = { [k: string]: T }
// -,-
type $arrayToObjectByKey = <T extends $item, K extends keyof T>(
    arr: Array<T>, keyField: K,
) => $map<T>;
// -,-

const arrayToObjectByKey: $arrayToObjectByKey = (listItem, keyItem) =>
    Object
        .assign(
            Object.create(null),
            ...listItem.map(item => (
                {
                    [
                        item[keyItem]
                    ]: item
                }
            ))
        );

JS

const arrayToObjectByKey = (listItem, keyItem) => Object.assign(Object.create(null), ...listItem.map(item => ({
  [item[keyItem]]: item
})));
// -,-
T1: {
  // -,-
  const symboL = Symbol();
  const arr = ['a', 'b'];
  const qq = arrayToObjectByKey(
      [
          { 'id': 'qqq' },
          { 'id': symboL },
          { 'id': 11 },
          { 'id': arr }, // TypeError
      ], 'id');
  // -,-
  // console.dir(qq)
  // -,-
  console.log('qqq' === qq.qqq.id);
  console.log(symboL === qq[symboL].id);
  console.log(11 === qq[11].id);
  arr: {
    console.log(arr === qq[arr].id);
    console.log(arr === qq[['a', 'b']].id);
    console.log(arr === qq['a,b'].id);

  }
};

const arrayToObjectByKey = (listItem, keyItem) => Object.assign(Object.create(null), ...listItem.map(item => ({
  [item[keyItem]]: item
})));
// -,-
T2: {
  // -,-
  const arr = ['a', 'b'];
  const qq = arrayToObjectByKey(
    [{
        'id': arr
      }, // TypeError
    ], 'id');
  // -,-
  // console.dir(qq)
  // -,-
  console.log(arr === qq[arr].id);
  console.log(arr === qq[['a', 'b']].id);
  console.log(arr === qq['a,b'].id);
};


text:
Q: how to improve the performance of the hazelcast queue? all
I met a problem :

i can put 3000 messages into a queue per second on the one-node-hazelcast queue; but can only put 300 message into a queue perseconde on the two-node-hazelcast queue.

how can i improve it?
is there any other solution to improve it?
is rabbitMq faster then hazelcat?
thanks.

A: Doing 300 ops/second is very low. Even 3000 items/second on a queue on a single node cluster is very low. One should easily be doing 100k+ for local setup. On a 4 node cluster on 4 stale dual socket sandy bridge boxes with a crappy 1 GbE one should be able to do in the hundreds of thousands of operations/second.
What are you putting on that queue? Can you explain the content of the items and which serialization technology is used (e.g. Java Serializable). To make sure it isn't your serialization, try putting a Long on the queue and see what kind of performance you get.
A few other questions are

*

*what kind of hardware are you using

*do you have any special map configuration?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google My Business API server to server without Workspace/G-Suite i would like to achieve that the website of my PHP website can fetch business location data (name, address, contact, openings, ...) from the Google APIs, so that i do not have to insert the information twice.
I tried to create a service account and use it to authenticate against the My Business API. It did not work, as Google requires an OAuth2 token for this API.
How can i obtain a Oauth2 token using the service account without having a Google Workspace or G-Suite?

A: You need to actually own or manage a location on Google Business Profile in order to be able to retrieve data for it. So for this you need a Google account.
An alternative for your usecase might be the Places API. In order to use it, you need to create an API key via the Google Cloud console.


text:
Q: Find a bilinear form and a linear form My problem: Let $\Omega$ a smooth, bounded open set of $\mathbb{R}^N$. We want to show the existence of $u \in H_0^1(\Omega)$ solution of
$$
\left\{\begin{array}{l}
V(x) \cdot \nabla_x u-\Delta_x u=f, \quad \text { a.e. in } \Omega, \\
u(x)=0, \text { a.e. in } \partial \Omega,
\end{array}\right.
$$
where $f \in L^2(\Omega)$ and $V: \Omega \rightarrow \mathbb{R}^N$ is a smooth function such that $\operatorname{div} V=\sum_{i=1}^N \partial_i V=0$.
Find $a(\cdot, \cdot)$ a bilinear form, and $L(\cdot)$ a linear form such that the equation above is equivalent to
$$
a(u, v)=L(v),
$$
for any $v \in H_0^1(\Omega)$.
My attempt: I intend to use Lax-Milgram theorem but i don't know how to choose the suitable condition for test function.
Please help me to solve this problem. This is the first time i have approached to this field. If I make any mistake, please let me know.

A: Suppose that $u\in C^2(\Omega) \cap C(\overline \Omega)$ satisfies the PDE in the classical sense. Let $\phi \in C^\infty_0(\Omega)$. Multiplying the PDE by $\phi$ then integrating over $\Omega$ gives $$\int_\Omega \phi V \cdot \nabla u \, dx - \int_\Omega \phi \Delta u\, dx = \int_\Omega f \phi \, dx. $$ Integrating by parts gives $$\int_\Omega \phi \Delta u \, dx = -\int_\Omega \nabla u \cdot\nabla \phi \, dx. $$ This implies that$$ \int_\Omega \phi V \cdot \nabla u \, dx +\int_\Omega \nabla  u \cdot \nabla \phi \, dx = \int_\Omega f \phi \, dx. $$
Hence, if we now have that $u \in H^1_0(\Omega)$, a suitable weak formulation would be $a(u,v) = L(v)$ for all $v\in C^\infty_0(\Omega)$ (by density this then holds for all $v\in H^1_0(\Omega)$) where $$a(u,v)= \int_\Omega v V \cdot \nabla u \, dx +\int_\Omega \nabla  u \cdot \nabla v \, dx  $$ and $$ L(v) =\int_\Omega fv \, dx. $$


text:
Q: Is it possible to add comments to a csproj file? Can you add comments to a .csproj file?  If so, what's the best way to do it?

A: Comments are written as usual in XML files:
<!-- comment -->

How to: Write a Simple MSBuild Project

A: The following works for multi-line comments.
<!--
  comment 1
  comment 2
  ....
-->


text:
Q: Lua 5.1.4 math.random not actually random my problem is when i write math.random(10) it is not actually random it always give me output:
1
6
2
9
and if i have used for example:
local colors = {"ORANG","BLUE","RED","YELLOW","BLACK"}
print(colors[math.random(#colors)])
print(colors[math.random(#colors)])
print(colors[math.random(#colors)])
print(colors[math.random(#colors)])
print(colors[math.random(#colors)])
print(colors[math.random(#colors)])
print(colors[math.random(#colors)])
print(colors[math.random(#colors)])
os.execute 'pause'

The output is always:
ORANGE
RED
ORANGE
BLACK
RED
RED
BLUE BLACK

This is always the output, how could it be random????

A: You're misunderstanding what random does:
It's a pseudorandom number generator. This means that, given a specific seed, it will always give you the exact same sequence of numbers.
Typically, you use a seed from an external source, e.g. use the current time as seed (WARNING: This is cryptologically dangerous!).
Please read up on pseudorandom and how to use Lua's random library.

A: I found the answer, you need to put:
math.randomseed(os.time())
math.random(); math.random(); math.random()

before using math.random()


text:
Q: c#: Вынесение файла ресурсов в отдельный проект решения Есть решение, в нем несколько проектов. Например, проекты: осн. прилож., сервис прилож., библиотека1, библиотека2.
Во всех проектах есть одинаковые картинки, фразы и тому подобное. В итоге получается, что допустим картинка кнопочки "копировать" хранится во всех проектах.
Как вывести ресурсы в отдельный проект и использовать их во всех проектах?
В принципе можно сделать проект, положить туда файлик ресурсов и ссылаться на него,редактируя файлики *.Designer.cs.
Но как-то это не правильно. Опять же больно долго, менять свойство в коде, нежели в свойстве объекта button, Image -> выбор ресурса, нет там того общего ресурса. Как его туда?
VS2012
PS: добавить всем как ссылку во все проекты Resources.resx не работает:(

A: В окне файла Resources.resx. Измените настройку Access Modifier: с Internal на Public. Добавив ссылку на наш проект ресурсов можно будет использовать ресурсы этого проекта.

Еще один вариан использовать ссылки на файлы ресурсов, как предлагается  тут


text:
Q: How to get user feedback (e.g. from AlertDialog) inside AsyncTask/Background-Thread? an Android 4+ app should perform a long running operation. This could be copying a million files from A to B for example. To not block the UI this operation runs in the background using an AsyncTask.
Assume that the operation needs some user feedback in the middle of the process to continue its work, e.g. "File XY already exists. Override, Irgnore or Rename?"
What is the best way to get this feedback from the user? Since the operation is running in a background thread one could not just present an AlertDialog (or something similar) since UI interaction is only possible in the main thread...
So for I came across these solution:

*

*Ask for feeback before background threads starts, e.g. ask how to handle conflicts before starting to copy/move the files in the
background.

*Do not handle conflicts but note them to ask the user
how to handle them after the operation is complete in a new
operation.

*End the background operation on the first conflict, ask the user for feedback and continue a new background operation

I do not like any of these solutions. In the first case the user is asked for feedback even if there will be no conflict at all. The second solutions is not possible if the steps have to be processed in a specific order. The third solution would result in code that is very difficult to read/understand/maintain.
A good solution would be:

*

*Stop the background thread

*Marshal to the UI thread and get feedback from the user

*Resume background thread and use feedback to continue the operation

Using GCD in Objectiv-C/iOS or async/await in C# this is not a big problem. But how can this be done in Android using AsyncTask?

A: Meanwhile I thought, that I found an answer here: Simply run myActivity.runOnUiThread(...) within doInBackground(...) and wait for it. Sounds good, but it does not work. The AsyncTask/background thread does NOT wait for the Runnable to finish:
private void copyFiles() {
    CopyTask copyTask = new CopyTask (this);
    copyTask.execute();
}

private class CopyTask extends CustomAsyncTask<Void, Void, Void> {
    private doCopy;

    @Override
    protected Boolean doInBackground(Void... params) {
        // Custom code, e.g. copy files from A to B and check for conflict
        for (File file : allFiles) {
            doCopy = true;

            if (isConflict(file)) {
                // Stop current thread and ask for user feedback on UI Thread

                Runnable uiRunnable = new Runnable() {
                    public void run() {
                        // Pos 1. --> Execute custom code, e.g. use AlertDialog to ask user if file should be replaced...
                        doCopy = false;

                        synchronized (this) {
                           this.notify();
                        }
                    }
                });

                synchronized(uiRunnable) {
                    // Execute code on UI thread
                    activity.runOnUiThread(uiRunnable);

                    // Wait until runnable finished
                    try {
                        uiRunnable.wait();
                    }
                    catch (InterruptedException e ) {
                        e.printStackTrace();
                    }
                }
            }

            // Pos 2. --> Continue work
            if (doCopy)
               copyFromAToB(File);
        }

        return null;
    }
}

I would expect, that when a conflict is detected the Runnable is executed and and Pos 1 (code inside Runnable to resolve conflict) is executed BEVOR Pos 2 is reached. This is not the case. The Runnable is executed correctly but the AsyncTask does not wait for it to finish. The execution of doInBackground is continued without any interruption. It seems that doInBackground and the Runnable are executed in parallel (not suprising since they are executed on different threads) but why does doInBackground not wait?


text:
Q: scenarios of using oauth2 vs your own token If you are an API developer, when would you go for OAuth2 instead of a simple scheme where you just send some API key in the header (JWT or other)? Is OAuth2 still relevant if you don't need access to third-party APIs?
Thanks.

A: Actually "send some API key in the header (JWT or other)" is what OAuth 2.0 specifies in https://www.rfc-editor.org/rfc/rfc6750#section-2. Let's call that the 2nd leg, which is trivial like your proposal, but standardized.
Obtaining the API key - i.e. the 1st leg - is where the perceived complexity in OAuth 2.0 comes from, using so called grant types. Yet you don't have to use an OAuth 2.0 grant type in your Client to obtain an access token. You're also free to just configure an access_token in your Client like you'd do with a traditional API key. (it still begs the question how you'd generate the access token just like how you'd generate an API key)


text:
Q: AS3 Casting one type to another I have a base class called Room and a subclass called Attic, and another called Basement.
I have a controller class that has an attribute called CurrentLocation which is type Room.  The idea is I want to be able to put Attic or Basement in that property and get it back, then cast that to whatever type it is.
So if on the controller the content is of type Attic, I'm trying to figure out how to explicitly cast it.  I thought I knew but its not working...  Here's what I thought it would be, borrowing from Java:
var myAttic:Attic = (Attic) Controller.CurrentLocation;

This gives me a syntax error:

1086: Syntax error: expecting semicolon before instance.

So how do you cast implicitly?  Or can you?  I could swear I've done this before as as3.

A: Here are your options for casting in ActionScript 3:

*

*Use as.
var myAttic:Attic = Controller.CurrentLocation as Attic; // Assignment.
(Controller.CurrentLocation as Attic).propertyOrMethod(); // In-line use.

This will assign null to myAttic if the cast fails.

*Wrap in Type().
var myAttic:Attic = Attic(Controller.CurrentLocation); // Assignment.
Attic(Controller.CurrentLocation).propertyOrMethod(); // In-line use.

This throws a TypeError if the cast fails.


text:
Q: nodejs domain based routing I have server with single IP address. I have 3 nodejs services. Each service has its own domain. f.e.

*

*a.company.com,

*b.company.com,

*c.company.com

They written by different people so integration into single application problematic.
My aim is to make nodejs routing of different requests to these different services based on hostname mentioned in GET/POST request.
I know that I can use NGINX for such kind of routing but I'm sure it will slowdown whole solution. I still plan to keep speed of 2K Req/s. So I prefer to stay in nice Async world of nodejs.
Any advices?
Thanks

A: If you're using connect, there's the connect.vhost middleware. The repo itself has an example of using connect.vhost for subdomains. The example could be adapted to using different domains just by changing the host names (for example it could be foo.com and bar.com like it is on the example in the first link in this post).
If you want your domains in separate processes, I recommend using node-http-proxy. Or, you could use dnode to divide up some work between processes but still have the one process handle all of the HTTP. It's a good idea to move things that are likely to use up lots of memory or crash in separate processes, so they don't bring the whole server down.

A: I'm using nodejs TCP-proxy to do this. All explanations are in code.
var net = require('net');

// your hosts
var dns = {
  'localhost' : 8000,
  'b.host' : 3000,
  'a.host' : 3001
};

// Create TCP-server
var server = net.createServer( function(soc){ // soc is socket generated by net.Server

  // Incoming request processing
  soc.on('data', function(data){

    // Create new socket
    var client = net.Socket();

    // Get host from HTTP headers
    var re = /[^\n]+(\r\n|\r|\n)host:\w*([^:]+)/i;
    var host = data.toString('utf-8').match(re);

    if (! dns[host])
    {
      soc.end('HTTP/1.1 404 Host not found');
      return;
    }

    // Connect to Node.js application
    client.connect(dns[host]);

    // Pause soc for inner socket connection
    soc.pause();

    client.on('connect', function()
    {
      // Write request to your node.js application
      client.write(data.toString('utf-8'));
    });

    client.on('data', function(cdata)
    {
      // Return socket to live
      soc.resume();

      // Write client data to browser
      soc.write(cdata.toString('utf-8'));
      soc.pipe(soc);
      soc.end();
    });

    client.on('end', function(){
      client.destroy();
    });
  });
}
);

server.on('error', function (err){
  // Error processing i just pass whole object
  console.log(err);
});

server.listen(8088);
console.log('Server is listening %d\n', 8088);

A: Use nginx or node-http-proxy
http://blog.nodejitsu.com/http-proxy-middlewares
http://blog.nodejitsu.com/http-proxy-intro


text:
Q: No column name was specified for column 2 of 't' I have this query, but its not working
select t.ACCOUNT_ID
from
    (select
         a.ACCOUNT_ID, count(a.ACCOUNT_ID)
     from
         EMPLOYER a, EMPLOYER b
     where
         a.main_id = b.main_id
     group by
         a.MAIN_ID, a.account_id
     having
        count(a.account_id) > 1) t

I am trying to find the duplicates and wanted to fetch the only ACCOUNT_ID from
the subquery

A:     select t.ACCOUNT_ID from (select
 a.ACCOUNT_ID,count(a.ACCOUNT_ID) as cnt
from EMPLOYER a,EMPLOYER b
 where a.main_id = b.main_id
 group by a.MAIN_ID,a.account_id
 having count( a.account_id) > 1)t

If you're going to select from a subquery, you should name at least the first instances of each column.
Added as cnt after COUNT(a.account_id)


text:
Q: How cell editing works with extjs store manager? I have this example code from Sencha's website
Ext.onReady(function()
{
    Ext.create('Ext.data.Store', {
        storeId:'simpsonsStore',
        fields:['name', 'email', 'phone'],
        data:{'items':[
            {"name":"Lisa", "email":"lisa@simpsons.com", "phone":"555-111-1224"},
            {"name":"Bart", "email":"bart@simpsons.com", "phone":"555-222-1234"},
            {"name":"Homer", "email":"home@simpsons.com", "phone":"555-222-1244"},
            {"name":"Marge", "email":"marge@simpsons.com", "phone":"555-222-1254"}
        ]},
        proxy: {
            type: 'memory',
            reader: {
                type: 'json',
                root: 'items'
            }
        }
    });

    Ext.create('Ext.grid.Panel', {
        title: 'Simpsons',
        store: Ext.data.StoreManager.lookup('simpsonsStore'),
        columns: [
            {header: 'Name',  dataIndex: 'name', editor: 'textfield'},
            {header: 'Email', dataIndex: 'email', flex:1,
                editor: {
                    xtype: 'textfield',
                    allowBlank: false
                }
            },
            {header: 'Phone', dataIndex: 'phone'}
        ],
        selType: 'cellmodel',
        plugins:
        [{
            ptype: 'cellediting',
            clicksToEdit: 1
        }],
        height: 200,
        width: 400,
        renderTo: 'grid'
    });

});

This ptype: 'cellediting' plugin allows for inline cell editing by just clicking on textfield.
I just cannot find any posts on how and where the changed value gets saved? How can I add a listener to a cell so that after each change I will be able to alert() the new value?
Thanks for any tips...

A: The record values are updated each time the editor is blurred (i.e. lose focus). Ext keeps track of fields in the records that have been modified, until you commit the changes (by syncing the store, for example).
To be notified that a field has been edited, use the edit event of the plugin. As you can see in the doc, you can install a listener for this event directly in the grid (no need to add the listener specifically to the plugin).
Edit
With your code, that would be something like this:
Ext.create('Ext.grid.Panel', {
    title: 'Simpsons',
    store: Ext.data.StoreManager.lookup('simpsonsStore'),
    columns: [
        {header: 'Name',  dataIndex: 'name', editor: 'textfield'},
        {header: 'Email', dataIndex: 'email', flex:1,
            editor: {
                xtype: 'textfield',
                allowBlank: false
            }
        },
        {header: 'Phone', dataIndex: 'phone'}
    ],
    selType: 'cellmodel',
    plugins:
    [{
        ptype: 'cellediting',
        clicksToEdit: 1
    }],
    height: 200,
    width: 400,
    renderTo: 'grid',

    listeners: {
        edit: function(editor, e) {
            var record = e.record;

            alert(Ext.String.format(
                'The field "{0}" or record #{1} has been changed from {2} to {3}',
                e.field, record.get('id'), e.originalValue, e.newValue
            ));

            alert('The following fields of the records are dirty: ' + Ext.Object.getKeys(record.modified).join(', '));
        }
    }
});


text:
Q: Simple php logic So I haven't programmed in a while, but i decided to tackle a small web app to get back in the game. Im having a bit of trouble though, and its kind of annoying because I know the answer is simple. So i'm making a databaseless image gallery, and i'm using Twitter Bootstrap as the front end. I want to display the images that i'm reading from a directory using the classic bootstrap row setup like this:

The problem is that I can only put four images into a row so I cant just do something like:

<?php echo"$img";?>

How can I echo a

every four
<?php echo"$img";?>

I feel like a nested loop may work, but i just cant seem to get it.
Thanks.

A: You need a loop with an index; then you can check if the index is divisible by 4:
if ($i % 4 == 0) {
  ?>

<?php
}

Alternately, you can array_chunk your data, and run a nested loop on the results, outputting the row in the outer loop.

A: For each row
for($i=0; $i<$num_item; $i++) {

Start a new row before the first item and every 4th item following
if($i % 4 == 0) {
  echo '
';
}

End a row after the 4th item and every 4th item following
if($i % 4 == 3) {
  echo '

}

Full code:
for($i=0; $i<$num_item; $i++) {
  if($i % 4 == 0) {
    echo '
';
  }
  // Print the item here
  if($i % 4 == 3) {
    echo '

  }
}

A: When dealing with a lot of html code using the (notice the colon and endif)
    <?php for (index; condition; step) : ?>

HTML STUFF

    <?php endif; ?>

alternative syntax is a bit cleaner than the conventional markup.
I would suggest:

    <?php for($i = 0; $i < $total_pics; $i++): ?>

            <a href="<?php echo $link; ?>"><img class="img-responsive" src="<?php echo $img_link; ?>">

    <?php if ($i % 4 == 3 && $i < $total_pics): ?>

    <?php endif;
    endfor; ?>

This allows the new row only to be put in place if there are more pictures to show and after the fourth one only.
This allows the html code to be indented as you want and clean the php code up a bit in the process. This also allows the initial row to be self closing if there are no pictures to show.


text:
Q: Bot Framework: Read the outgoing message of the Conversation Is there a way to use the Conversation so that the IMessageActivity to be sent to the user is returned to the caller instead of sent back to the user uri?
What I want to accomplish is to handle myself the incoming and outgoing messages, and while I can create an activity to be supplied to the Conversation object I cannot read and use the IMessageActivity reply.
To be more specific I'm wondering if I can substitute
Conversation.SendAsync(IMessageActivity, Func<IDialog<object>>);

With something that will let me handle the reply.
Thank you.

A: The reply should be handled by the dialog passed to the SendAsync method.
In the dialog, you will usually have a method that receives the context and the message sent by the user. For example:
public async virtual Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
{
   var message = await result;
}

In the StartAsync method of the dialog you will have to set this method as the one that will be called once the user sends a message to the bot
public async Task StartAsync(IDialogContext context)
{
    context.Wait(this.MessageReceivedAsync);
}

Then, is up to you to decide what to do after receiving the message.
Do you want to use a PromptDialog, e.g. the Confirm one? You can, just instantiate the dialog, call it and get the result in the ResumeAfter<bool> method.
PromptDialog.Confirm(context, ResumeAfterPrompt, "prompt dialogue", "retry dialog", 3);

private async Task ResumeAfterPrompt(IDialogContext context, IAwaitable<bool> result)
{
    try
    {
        // try get user response
        bool response = await result;

        await context.PostAsync($"You said: {result}");
    }
    catch (TooManyAttemptsException)
    {
        // handle error
    }

   // wait for another message from the user. Could be the same method or a new one following the same signature.
   context.Wait(this.MessageReceivedAsync);
}

Do you want to use a FormFlow? You also, just instantiate the FormDialog and get the result in the ResumeAfter<T> method you define.
It's always the same pattern when working with multi dialogs (Prompts and Forms are dialogs!): call the dialog, get the result in the ResumeAfter method and wait for a new user message.
All this concepts are well explained and also demonstrated in the Multi-Dialogs sample. Go through the readme and the codebase and you will understand what I explained. That sample shows prompts, a FormFlow, custom dialogs, etc. Here there are a few more details.


text:
Q: Swatch Thumbnail in Minibag When selecting a swatch and adding an item to the bag the master product image is shown in the minibag. We would like the image of the selected swatch to be the thumbnail. Is there a script to do this?
Magento 2.1.11

A: It's Magento out of box functionality. You can chagen this from below configuration setting from admin panel
Store => Configurations => Sales => Checkout => Shopping cart => Configurable product image

Select: Product Thumbnail Itself


text:
Q: How to tell if a DATE column in an Oracle table is indexed? We have a 6B row table in a vendor's database that uses Oracle.
We are facing responsiveness issues. Any date queries we add turn our results from returning instantly to time outs after dozens of minutes. There are multiple date fields we might use. The vendor doesn't disclose which fields they have indexed.
Our access to the table is via JDBC making SQL queries.
The vendor does indicate we are accessing materialized tables rather than the views.
How might we determine which fields, particularly date fields, are indexed in the table?

If this question is the same as this SO question then there are several points of clarification needed. The question doesn't appear to be fully answered. That question's answer is that the OP's query should work - but none of the tables listed in their query appear in the the database we are looking. Our vendor system has dozens of databases and thousands of tables in each of the databases. Neither "ALL_IND_COLUMNS or ALL_INDEXES" is in that database.
Here is that question's query:
from all_ind_columns a, all_indexes b

Is this only for particular Oracle Databases? Is it found in a particular admin/meta database?

A: If using Oracle SQL Devloper, right click the table and select Quick DDL > Save to worksheet
If using Toad, browse to the table, right click and select export DDL.
If using SQLPlus, there's a guide here


text:
Q: Differentiation and 3 dimensional Assume that a Mountain is shaped like a function $z=f(x,y)=sin(xy)$. A Hiker begins at the Point $(0,0,0)$ and wants to reach the Point (1,1,sin(1)), but he is not allowed to get over the Slope of $45°$. Can he do it?
A friend of mine asked that it seems very easy question but yet complicated :).
At first i thought it is Just Question to find Angle Between two Vectors with formula $$cos(\alpha)=\frac{v*w}{|v|*|w|}$$ but it doesn't bring anything
Can someone help me with this?
Thanks

A: So you cannot take the path on the surface corresponding to $y=x$ from $x=0$ to $x=1$, because the slope will exceed $1$ near the end of your path. But try a different path:  Follow the $x$-axis from $x=0$ to $x=1$; then follow the surface keeping $x=1$ and letting $y$ go from $0$ to $1$.


text:
Q: Is there a way to give internet only to a virtual machine/virtualized application while not having an internet connection on the host? I'm thinking at this from the privacy perspective, so that we can control the extent of the snoopers intents on our computers, to limit their view to what is online only on the virtual machine running with internet so that the host is completely out of their scope. Is this possible?

A: That's definitely impossible.
Think of it this way:  all resources of the virtual machine come from the physical machine, RAM, Disk, CPU, and Network.
If the physical machines itself doesn't have this resource, there is no way the virtual machines can have this resource.

A: You could, though, this would be tricky - You'd want to passthrough a network device directly to the VM, and the only real way to do this is through passing through a USB wifi, or network adaptor, and having networking completely turned off on the guest. While the USB layer is shared, actual networking is entirely on the guest. You can presumably confirm this with wireshark to be sure
I suppose VT-D and pci passthrough, and some hypervisors may be able to do this as well, but I've never really heard of anyone doing either of these for this reason


text:
Q: PersistentBag exception in Orchard I'm trying to adapt the guide http://docs.orchardproject.net/Documentation/Creating-1-n-and-n-n-relations for creating an N-to-N relation in my Orchard module, but I get an exception "unable to cast NHibernate.Collection.Generic.PersistentGenericBag`1[ArealAds.Models.StreetAreaRecord] to System.Collections.Generic.List`1[ArealAds.Models.StreetAreaRecord]". I don't fully understand what's going on behind the scenes so it's hard for me to debug. What is the likely cause of this error? Where do I start looking?

A: You did not correctly follow the guide. There is an example of an n-n relationship in the document and it works. Without seeing any of your code, it's hard to say what went wrong, but it has to be different from the tutorial somehow. Another example you can look at is the bundle part in this module: https://bitbucket.org/bleroy/nwazet.commerce. it establishes a n-n relationship between content items.

A: You should change the type of the related item collection from List<T> to IList<T> (or more generic IEnumerable<T>), as NHibernate cannot map the property to it's internal item collection (which implements IList<T>).
See similar issue.


text:
Q: Getting aggregate count for nested fields in mongo I have a mongo collection mimicking this java class. A student can be taught a number of subjects across campus.
 class Students {
     String studentName;
     Map<String,List<String>> subjectsByCampus;
}

So a structure will look like this
{
 _id: ObjectId("someId"),
 studentName:'student1',
subjectByCampusName:{
 campus1:['subject1','subject2'],
 campus2: ['subject3']
},
_class: 'fqnOfTheEntity'
}

I want to find the count of subjects offered by each campus or be able to query the count of subjects offered by a specific campus. Is there a way to get it through query?

A: Mentioned in the comments, but the schema here does not appear to be particularly well-suited toward gathering the data requested in the question. For an individual student, this is doable via $size and processing the object (as an array) via $map. For example, if we want your desired out put of campus1:2, campus2:1 for the sample document provided, a pipeline to produce that in a countsByCampus field might look as follows:
[
  {
    "$addFields": {
      "countsByCampus": {
        "$arrayToObject": {
          "$map": {
            "input": {
              "$objectToArray": "$subjectByCampusName"
            },
            "in": {
              "$mergeObjects": [
                "$$this",
                {
                  v: {
                    $size: "$$this.v"
                  }
                }
              ]
            }
          }
        }
      }
    }
  }
]

Playground demonstration here with an output document of:
  {
    "_class": "fqnOfTheEntity",
    "_id": "someId",
    "countsByCampus": {
      "campus1": 2,
      "campus2": 1
    },
    "studentName": "student1",
    "subjectByCampusName": {
      "campus1": [
        "subject1",
        "subject2"
      ],
      "campus2": [
        "subject3"
      ]
    }
  }

Doing that across the entire collection would involve $grouping the results together. This can be done but would be an extremely resource-intensive and likely slow operation.


text:
Q: How to possible make use of .serialize and combine "sets" of inputs into specific groups? Ok, so I'm not sure the best way to even begin to find an answer to this. So the question might seem confusing.
Here's the deal. I would like to make use of an API I've written that is dependent on on multiple "child items" in order to create certain totals.
Thus I want to build a UI where "item input rows" are created dynamically (not hard, done that), BUT I want to be able to ajax those sets of rows, with their inputs in a manner similar too:
{
    item01:
        input1: value,
        input2: value
    item02:
        input1: value,
        input2: value
.....

My first thought, of course was to use [] on the input names to provide for multiple passings of inputs with same name, as each row will have the same inputs. However, this won't provide the POST format I want as each post item will be an array of each input via that inputs name. This means more work making sure everything is associated with the correct item row upon returning results (as there are individual results as well as the total).
So has anyone done anything similar to what I hope to achieve? Any idea how I can group inputs into individual objects within one large POST object before serializing?
Sample HTML

    <fieldset class="fieldset-item ui-corner-all">
        <legend>
Item
</legend>
        <fieldset class="fieldset-item-input ui-corner-all">
            <legend>
Input
</legend>

In 1

In 2

In 3

<input name="in1" type="text" class="text-center ui-widget-content ui-corner-all">

<input name="in2" type="text" class="text-center ui-widget-content ui-corner-all" />

<input name="in3" type="text" class="text-center ui-widget-content ui-corner-all" />

        </fieldset>
        <fieldset class="fieldset-item-output ui-corner-all ui-corner-all">
            <legend>
Output
</legend>

Out 1

Out 2

Out 2

<input name="out1" readonly="readonly" type="text" class="text-center ui-widget-content ui-corner-all">

<input name="out2" readonly="readonly" type="text" class="text-center ui-widget-content ui-corner-all">

<input name="out3" readonly="readonly" type="text" class="text-center ui-widget-content ui-corner-all">

        </fieldset>
    </fieldset>
    <fieldset class="fieldset-item ui-corner-all">
        ...etc...

Fiddle Sample

A: I found a solution I like
I simply go through each row before submission and make a serial array of the inputs in that row, then add them to a data object to be submitted! Works like a charm!
$(document).on('blur change keyup', '#Items .fieldset-item-input input, #Items .fieldset-item-input select', function(e) {
    var submitData = {},
        $input = $(this).closest('.fieldset-item').find('.fieldset-item-input'),
        $output = $(this).closest('.fieldset-item').find('.fieldset-item-output');

    //  here is the key factor that helped!
    //  here i make a serial array of each items inputs
    //  and then add that array to a data object to be
    //  submitted with ajax! WORKS GREAT!
    $('#Items .fieldset-item').each(function(i) {
        submitData[i] = $(this).children('.fieldset-item-input').serializeArray();
    });

    $.ajax({
        data: submitData,
        dataType: 'json',
        type: "POST",
        url: $.myURL('v2', 'quote', 'calc'),
        beforeSend: function (xhr, settings) { /*console.log(settings.data);*/ $output.find('input').val(''); },
        success: function(data, status, xhr) {
            console.log(data);
        }
    });
});


text:
Q: How to implemenst tabs in tabs screen in android I want to implement a tabs in tabs screen as below:

Can you give me an example of this kind of screen?

A: There is a good Android Google webpage @ SlidingTabsBasic and supporting details @ ViewPager class. Few months ago, I had the same answer with more details, hopefully I will find it for you.
I just found a link on SO @ Android - Google Play like tabs. The Tianhai's answer uses the sample project I implemented. The sample project (PagerSlidingTabStrip) on Riccardo's answer may be good too. I can claim that SlidingTabsBasic is a basic tab like GUI project.
In the meantime, is this a good start for you?

A: Try This:
MainActivity
public class MainActivity extends TabActivity {

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Resources ressources = getResources();
    TabHost tabHost = getTabHost();

    // Android tab
    Intent intentAndroid = new Intent().setClass(this, AndroidActivity.class);
    TabSpec tabSpecAndroid = tabHost
            .newTabSpec("Android")
            .setIndicator("", ressources.getDrawable(R.drawable.icon_android_config))
            .setContent(intentAndroid);

    // Apple tab
    Intent intentApple = new Intent().setClass(this, AppleActivity.class);
    TabSpec tabSpecApple = tabHost
            .newTabSpec("Apple")
            .setIndicator("", ressources.getDrawable(R.drawable.icon_apple_config))
            .setContent(intentApple);

    // Windows tab
    Intent intentWindows = new Intent().setClass(this, WindowsActivity.class);
    TabSpec tabSpecWindows = tabHost
            .newTabSpec("Windows")
            .setIndicator("", ressources.getDrawable(R.drawable.icon_windows_config))
            .setContent(intentWindows);

    // Blackberry tab
    Intent intentBerry = new Intent().setClass(this, BlackBerryActivity.class);
    TabSpec tabSpecBerry = tabHost
            .newTabSpec("Berry")
            .setIndicator("", ressources.getDrawable(R.drawable.icon_blackberry_config))
            .setContent(intentBerry);

    // add all tabs
    tabHost.addTab(tabSpecAndroid);
    tabHost.addTab(tabSpecApple);
    tabHost.addTab(tabSpecWindows);
    tabHost.addTab(tabSpecBerry);

    //set Windows tab as default (zero based)
    tabHost.setCurrentTab(2);
}

}

activity_main
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="5dp">
    <TabWidget
        android:id="@android:id/tabs"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="5dp" />
</LinearLayout>

AndroidActivity
public class AndroidActivity extends TabActivity {
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Resources ressources = getResources();
    TabHost tabHost = getTabHost();

    // Android tab
    Intent intentAndroid = new Intent().setClass(this, AppleActivity.class);
    TabHost.TabSpec tabSpecAndroid = tabHost
            .newTabSpec("Android")
            .setIndicator("", ressources.getDrawable(R.drawable.icon_android_config))
            .setContent(intentAndroid);

    // Apple tab
    Intent intentApple = new Intent().setClass(this, AppleActivity.class);
    TabHost.TabSpec tabSpecApple = tabHost
            .newTabSpec("Apple")
            .setIndicator("", ressources.getDrawable(R.drawable.icon_apple_config))
            .setContent(intentApple);

    // Windows tab
    Intent intentWindows = new Intent().setClass(this, WindowsActivity.class);
    TabHost.TabSpec tabSpecWindows = tabHost
            .newTabSpec("Windows")
            .setIndicator("", ressources.getDrawable(R.drawable.icon_windows_config))
            .setContent(intentWindows);

    // Blackberry tab
    Intent intentBerry = new Intent().setClass(this, BlackBerryActivity.class);
    TabHost.TabSpec tabSpecBerry = tabHost
            .newTabSpec("Berry")
            .setIndicator("", ressources.getDrawable(R.drawable.icon_blackberry_config))
            .setContent(intentBerry);

    // add all tabs
    tabHost.addTab(tabSpecAndroid);
    tabHost.addTab(tabSpecApple);
    tabHost.addTab(tabSpecWindows);
    tabHost.addTab(tabSpecBerry);

    //set Windows tab as default (zero based)
    tabHost.setCurrentTab(0);

 }

AppleActivity
public class AppleActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    TextView textview = new TextView(this);
    textview.setText("This is Apple tab");
    setContentView(textview);
}

BlackBerryActivity
public class BlackBerryActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    TextView textview = new TextView(this);
    textview.setText("This is BlackBerry tab");
    setContentView(textview);
}

WindowActivity
public class WindowsActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    TextView textview = new TextView(this);
    textview.setText("This is Windows mobile tab");
    setContentView(textview);
}


text:
Q: Make a sum of sum of lists in Python 2.7? This is my whole code for a work in progress:
 nList = [[[0,0,4287320],[10423234600,0,63248900]],\
[],\
[[132447000,10432900,134820]],\
[[0,0,0],[3002340,4324000,303420],[3003420,40023420,720424],[0,0,102432420]],\
[[132432450,0,0],[10034220,0,36432230], [400432240,40243200,6432260],[4000423, 40243200, 964234240],[12342400,0,132342420]]]

Decoding the list:
nList has multiple traces with trace1 having two points, trace2 having no points, trace3 having 1 point and so one. each point in the trace is made up of three elements [x co-ordinate, y co-ordinate, time.
At the end of this whole code, I need to print the sum(sum(lengthList)), and this formula obviously doesn't work. Problem is, I have also tried print map(sum(sum, lengthList)), print sum(sum(lengthList)) and none of them have worked. It also has to be a function and not just a print as the nList needs to work for multiple lists of a similar nature. Thanks for the help!

A: This should help you from the "float object not iterable" error !
Edit:
Declare the below, above the forloop

lengthList=[]

and in the last else part of the for loop

lengthList.append(sum(float(x) for x in lengths(trace)))

Out side the for loop

print [sum(float(x) for x in lengthList)]

Good Luck!

A: You could use a list comprehension:
sum([sum(x) for x in lengthList])

This would sum the points values in lengthList, and then return the sum of those sums.
Or as @soon pointed out, a generator:
sum(sum(x) for x in lengthList)

Although if you want to use any list methods, you should use the list comprehension.

A: just take a list lengthList = [] and enter element by  extend
you can change simple in your code in last for loop
lengthList = []
for i in range(len(traceList)):
    trace=traceList[i]
    if len(trace)==0:
        print "Trace {0} has no points!".format(i)
    elif len(trace)==1:
        print "Trace {0} consists of a single point.".format(i)
    else:
        #lengthList=lengths(trace)
        lengthList.extend(lengths(trace))

print sum(lengthList)

Output
Trace 1 has no points!
Trace 2 consists of a single point.
22436.5910894

A: I've made two modifications.Change length_list outside the function.
length_list=[]
def lengths(trace):

sum_of_all_lengths=[]
for i in range(0,len(trace)-1):
    length=calculateLength(trace[i][0], trace[i][1], trace[i+1][0], trace[i+1][1])
    length_list.append(length)
return length_list

at the end you can have this
print sum(length_list)

A: If you just want to calculate the total length of all traces, you should firstly calculate the lengths of all traces:
In [9]: lengths_of_all_traces = map(lengths, (trace for trace in traceList if len(trace) > 1))

In [10]: lengths_of_all_traces
Out[10]: [[1000.0], [5000.0, 0.0, 5000.0], [850.0, 5000.0, 0.0, 5586.591089385369]]

As you can see, we skip traces with zero or one points.
The next step is calculating the total length. You could just pass generator expression to sum function:
In [11]: total_length = sum(sum(t) for t in lengths_of_all_traces)

In [12]: total_length
Out[12]: 22436.59108938537

Actually, you could remove the condition if len(trace) > 1, since sum works with empty lists pretty well:
In [13]: lengths_of_all_traces = map(lengths, traceList)

In [14]: lengths_of_all_traces
Out[14]:
[[1000.0],
 [],
 [],
 [5000.0, 0.0, 5000.0],
 [850.0, 5000.0, 0.0, 5586.591089385369]]

In [15]: total_length = sum(sum(t) for t in lengths_of_all_traces)

In [16]: total_length
Out[16]: 22436.59108938537

You could also use imap function (which returns iterator) instead of map (which returns list) for saving memory.


text:
Q: python-docx get tables from paragraph I have .docx file with many paragraphs and tables like:

*

*par1

*

*table1

*table2

*table3

*par2

*

*table1

*table2

2.1 par21

*

*table1

*table2

I need to iterate all objects and make dictionary, maybe in json format like:
   {par1: [table1, table2, table3], par2[table1,table2, {par21: [table1,table2]} ] }

    from docx.api import Document

    filename = 'test.docx'
    document = Document(docx=filename)
    for table in document.tables:
        print table

    for paragraph in document.paragraphs:
        print paragraph.text

How can I relate each paragraph and tables?
Can you suggest something ?

A: from docx import Document
from docx.document import Document as _Document
from docx.oxml.text.paragraph import CT_P
from docx.oxml.table import CT_Tbl
from docx.table import _Cell, Table
from docx.text.paragraph import Paragraph

def iter_block_items(parent):
    """
    Generate a reference to each paragraph and table child within *parent*,
    in document order. Each returned value is an instance of either Table or
    Paragraph. *parent* would most commonly be a reference to a main
    Document object, but also works for a _Cell object, which itself can
    contain paragraphs and tables.
    """
    if isinstance(parent, _Document):
        parent_elm = parent.element.body
    elif isinstance(parent, _Cell):
        parent_elm = parent._tc
    elif isinstance(parent, _Row):
        parent_elm = parent._tr
    else:
        raise ValueError("something's not right")
    for child in parent_elm.iterchildren():
        if isinstance(child, CT_P):
            yield Paragraph(child, parent)
        elif isinstance(child, CT_Tbl):
            yield Table(child, parent)

document = Document('test.docx')
for block in iter_block_items(document):
    #print(block.text if isinstance(block, Paragraph) else '<table>')
    if isinstance(block, Paragraph):
        print(block.text)
    elif isinstance(block, Table):
        for row in block.rows:
            row_data = []
            for cell in row.cells:
                for paragraph in cell.paragraphs:
                    row_data.append(paragraph.text)
            print("\t".join(row_data))

A: Not sure if i am helping but here's my way of doing
def printTables(doc):
    for table in doc.tables:
        for row in table.rows:
            for cell in row.cells:
                for paragraph in cell.paragraphs:
                    print(paragraph.text)
                printTables(cell)

A: This functions returns the paragraphs and tables of a document or part of a document (you can have paragraphs and tables inside tables):
def iter_block_items(parent):
    # https://github.com/python-openxml/python-docx/issues/40
    from docx.document import Document
    from docx.oxml.table import CT_Tbl
    from docx.oxml.text.paragraph import CT_P
    from docx.table import _Cell, Table
    from docx.text.paragraph import Paragraph
    """
    Yield each paragraph and table child within *parent*, in document order.
    Each returned value is an instance of either Table or Paragraph. *parent*
    would most commonly be a reference to a main Document object, but
    also works for a _Cell object, which itself can contain paragraphs and tables.
    """
    if isinstance(parent, Document):
        parent_elm = parent.element.body
    elif isinstance(parent, _Cell):
        parent_elm = parent._tc
    else:
        raise ValueError("something's not right")

    # print('parent_elm: '+str(type(parent_elm)))
    for child in parent_elm.iterchildren():
        if isinstance(child, CT_P):
            yield Paragraph(child, parent)
        elif isinstance(child, CT_Tbl):
            yield Table(child, parent)  # No recursion, return tables as tables
        # table = Table(child, parent)  # Use recursion to return tables as paragraphs
        # for row in table.rows:
        #     for cell in row.cells:
        #         yield from iter_block_items(cell)

Now, to use it, construct your dictionary where it says Do some logic here:
document = Document(filepath)
for iter_block_item in iter_block_items(document): # Iterate over paragraphs and tables
# print('iter_block_item type: '+str(type(iter_block_item)))
        if isinstance(iter_block_item, Paragraph):
                paragraph = iter_block_item  # Do some logic here
            else:
                table = iter_block_item      # Do some logic here

Note: @Elayaraja Dev answer cannot be edited, this answer has the current form of iter_block_items (since docx internals were updated)

A: There is no such method implemented(yet) on the python-docx library but there is a workaround to iterate through all elements of the docx in the order they are presented: https://github.com/python-openxml/python-docx/issues/40
You can try iterating through all these and check if the object is an instance of a table or paragraph and base your logic on that.


text:
Q: why cannot sf object use all data.table methods in R? I am learning sf in R. Since I like data.table very much, I though I could use both. However, it seems that sf object deriving from data.table cannot use methods in data.table any more. Following is an example:
First I generate a very simple data.table and make it to a sf object. So far so good.
> dfr <- data.table(id = c("hwy1", "hwy2"),
+                   cars_per_hour = c(78, 22),
+                   lat = c(1, 2),
+                   lon = c(3, 4))
> my_sf <- st_as_sf(dfr , coords = c("lon", "lat"))

Then I check the structure of the my_sf. It is an sf object, a data.table and a data.frame.
> str(my_sf)
Classes 'sf', 'data.table' and 'data.frame':    2 obs. of  3 variables:
 $ id           : chr  "hwy1" "hwy2"
 $ cars_per_hour: num  78 22
 $ geometry     :sfc_POINT of length 2; first list element:  'XY' num  3 1
 - attr(*, "sf_column")= chr "geometry"
 - attr(*, "agr")= Factor w/ 3 levels "constant","aggregate",..: NA NA
  ..- attr(*, "names")= chr  "id" "cars_per_hour"

Then I tried some arbitary function unique, and it does not work. Actually this my_sf does not work as data.table at all.
> my_sf[, unique(id)]
Error in unique(id) : object 'id' not found

Does anyone know the reason for it? Is it not possible to use data.table for sf?

A: My guess is the function st_as_sf has destroyed .internal.selfref attribute turning back the data.table into data.frame although the class name has been preserved.
> str(dfr)

#Classes 'data.table' and 'data.frame': 2 obs. of  4 variables:
#$ id           : chr  "hwy1" "hwy2"
#$ cars_per_hour: num  78 22
#$ lat          : num  1 2
#$ lon          : num  3 4
#- attr(*, ".internal.selfref")=<externalptr>

setDT(my_sf) might be enough to turn back the data.frame into a data.table


text:
Q: VBA UserForm - Custom count-down timer for minutes working but cannot implement custom seconds I have implemented a count-down timer which is now working for whole minutes entered into a text box by the user (e.g. 05:00), however I am struggling with implementing functionality for the user to enter their own seconds as well.
The userform has a button "Timercustom", when clicked a routine will update every second a text box "TextBox3" in the format 00:00 (e.g.05:00) to countdown from the initial to 00:00.
Could someone with more VBA experience help to make adjustments so that extra seconds that are added are counted down as well? I have tried several hours to do this, but stripped back to the working code below for whole minutes only for clarity.
'Initialisation function
Private Sub UserForm_Initialize()
Dim M As Double, S As Double
M = Int(CDbl(AllowedTime))
S = (CDbl(AllowedTime) - Int(CDbl(AllowedTime))) * 60
 With TextBox1
    .Value = Format(CStr(M), "15") & ":" & Format(CStr(S), "00")
End With

With TextBox2
    .Value = Format(CStr(M), "45") & ":" & Format(CStr(S), "00")
End With

With TextBox3
    .Value = Format(CStr(M), "5") & ":" & Format(CStr(S), "00")
End With
End Sub

'main function to start the timer
Private Sub Timercustom_Click()
Dim t, E, M As Double, S As Double
Dim AllowedTime As Integer
Dim TextStrng As String
Dim Result() As String
Dim tempS As Double
Dim firstRun As Boolean

firstRun = True

TextStrng = TextBox3.Value
Result() = Split(TextStrng, ":")

AllowedTime = Result(0)
t = Timer

Do
    If Timer - t < 0 Then
        Unload UserForm1
        MsgBox "Error encountered - start again"
        Exit Sub
    End If
    E = CDbl(Time) * 24 * 60 * 60 - t 'elapsed time in secs
    M = (CDbl(AllowedTime) - 1) - Int(E / 60)

    'this just avoids a weirdity where the seconds initially goes to 00:0-1, for some reason
    If tempS < 0 Then
    tempS = Result(1)
    End If

    S = tempS

    With TextBox3
        .Value = Format(CStr(M), "00") & ":" & Format(CStr(S), "00")
    End With
    DoEvents
Loop Until (Timer - t) / 60 >= CDbl(AllowedTime) Or UserForm1.Visible = False

End Sub

A: Here is an example of how to do the calculations for the timer and how to format input/output.
You need to validate your user input format and convert it to hh:mm:ss so eg if your user inputs 01:15 which is mm:ss you need to convert it into 00:01:15. This format can then be converted into a real time using TimeValue and with CDbl(TimeValue(UserInput)) * 24 * 60 * 60 you get the amount of seconds of that time.
Note that we need to convert the time into seconds because your Timer is calculating in seconds.
SecondsToRun - (Timer - TimerStart) gives you the amount of seconds that are left on your timer. And with Format$((SecondsToRun - (Timer - TimerStart)) / 24 / 60 / 60, "hh:mm:ss") you can format the seconds as human readable time.
Option Explicit

Public Sub TimerExample()
    Dim UserInput As String
    UserInput = "01:15" 'this is what the user inputs and how long the timer should run

    'validate userinput und ensure hh:mm:ss format
    Select Case Len(UserInput) - Len(Replace$(UserInput, ":", ""))
        Case 2 'input format is hh:mm:ss

        Case 1 'input format is mm:ss
            UserInput = "00:" & UserInput
        Case 0 'input format is ss
            UserInput = "00:00:" & UserInput
        Case Else
            MsgBox "invalid input"
            Exit Sub
    End Select

    'we need to convert the string UserInput into a double and
    'convert it into seconds (Timer uses seconds!)
    Dim SecondsToRun As Long
    SecondsToRun = CDbl(TimeValue(UserInput)) * 24 * 60 * 60

    Dim TimerStart As Double
    TimerStart = Timer 'remember when timer starts

    Do
        Cells(1, 1).Value = Format$((SecondsToRun - (Timer - TimerStart)) / 24 / 60 / 60, "hh:mm:ss")
        'count backwards from 01:15 format as hh:mm:ss and output in cell A1

        DoEvents
    Loop While TimerStart + SecondsToRun > Timer 'run until SecondsToRun are over
End Sub

So this code will start a timer that counts backwards from 01:15 (1 minute, 15 seconds) backwards to 0. The output will be in cell A1 as follows:
00:01:15
00:01:14
00:01:13
00:01:12
00:01:11
00:01:10
00:01:09
00:01:08
and so on.

A: I have worked with the "Peh" solution but used the ontime event.
The result is not predictable depending on the exact start time:

How would you improve this?
1. Timer should not end with positive value 00:01!
2. Timer should not end with negative value! (also displayed as 00:01)

Option Explicit
Dim TimerStart As Double
Dim SecondsToRun As Long
Dim UserInput As String
Dim LatestStartTime As Variant
Dim rowCt As Integer
Dim colCt As Integer

Sub ResetColCount()
    colCt = 0
    Range("A1:Z10").Clear
End Sub

Public Sub TimerExample()
    UserInput = "00:03" 'this is what the user inputs and how long the timer should run
    rowCt = 0
    colCt = colCt + 1

    'validate userinput und ensure hh:mm:ss format
    Select Case Len(UserInput) - Len(Replace$(UserInput, ":", ""))
        Case 2 'input format is hh:mm:ss

        Case 1 'input format is mm:ss
            UserInput = "00:" & UserInput
        Case 0 'input format is ss
            UserInput = "00:00:" & UserInput
        Case Else
            MsgBox "invalid input"
            Exit Sub
    End Select

    'we need to convert the string UserInput into a double and
    'convert it into seconds (Timer uses seconds!)
    SecondsToRun = CDbl(TimeValue(UserInput)) * 24 * 60 * 60

    TimerStart = Timer 'remember when timer starts
    Cells(1 + rowCt, colCt).Value = Format$((SecondsToRun - (Timer - TimerStart)) / 24 / 60 / 60, "hh:mm:ss")
    rowCt = rowCt + 1
    LatestStartTime = Now() + TimeValue(UserInput) + TimeValue("00:00:01")

    Application.OnTime Now() + TimeValue("00:00:01"), "UpdateTime", LatestStartTime

End Sub

Sub UpdateTime()
    Cells(1 + rowCt, colCt).Value = Format$((SecondsToRun - (Timer - TimerStart)) / 24 / 60 / 60, "hh:mm:ss")
    rowCt = rowCt + 1
    If TimerStart + SecondsToRun > Timer Then
        Application.OnTime Now() + TimeValue("00:00:01"), "UpdateTime", LatestStartTime
    End If
End Sub


text:
Q: How to enable cookies I have this assignment to read, write, enable cookies so that the username will be stored in a variable and then written into a cookie. My problem is that it seems like the last part of the code is working. But the first part where the username is suppose to be stored into the variable is not working, and I can see that when I run the code and the first two alert boxes don't show. It is suppose to open with "Hello, I am your pet rock" And after I click iRock for the last time, the image is suppose to change to a happy iRock. But it doesn't happen. I guess because the cookie didn't get read. Any suggestions. Here is the link: http://ciswebs.smc.edu/cis54/tyson_schweidel  /iRockChapter3.htm
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org   /TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>iRock - The Virtual Pet Rock</title>
<link href="donut_stylesheet/donut.css" rel="stylesheet" type="text/css" />

<script type ="text/javascript" >
var userName;

function resizeRock(){
document.getElementById("rockImg").style.height = (document.body.clientHeight - 100) * 0.9;
}

function greetUser(){
userName = readCookie("rock_username");
if(userName)
alert("Hello " + userName + ", I missed you.");
else
alert("Hello, I am your pet rock");
}

function touchRock(){
if(userName)
    alert("I like attention," + userName + ". Thank you.");
}

    userName = prompt("What is your name?", "Enter name here.");
if(userName)
alert("It is good to meet you, " + userName + ".");
writeCookie(irock_username", userName, 1 * 365);

document.getElementById("rockImg").src = "rock_happy.png";
setTimeout("document.getElementById(('rockImg').src = 'images/rock.png';", 5 * 60 * 1000);

</script>
</head>

<body onload="resizeRock(); greetUser(); onResize="resizeRock();">
<img id="rockImg" src="images/rock.png" alt="iRock" style="cursor:pointer"   onClick="touchRock();" />
</body>
</html>

A: Let's break this down.

How to enable cookies

Cookies are enabled by default in pretty much every browser since at least 2000. While you can't rely on someone having cookies enabled - I think it's a safe assumption for a homework assignment. These days, for cookies to not be enabled, a user has to explicitly turn them off.

read, write, enable cookies so that the username will be stored in a variable and then written into a cookie

You have two functions that are undeclared. readCookie and writeCookie are being called, but you haven't declared them anywhere yet. You need something that looks like this:
function readCookie() {
    //Return the value of the cookie
}

function writeCookie(value) {
    //Write the value to the cookie
}

You can learn more about what exactly a cookie is here:
http://www.quirksmode.org/js/cookies.html
As well as how to read and write them.
Additionally, you have a few syntax errors in your HTML and JavaScript. Make sure to review it carefully. Things to look for:

*

*Make sure every curly brace ({}) has a matching opening / closing one.

*Make sure all of the HTML attribute values are enclosed properly in quotes. For example, the onload attribute of your body seems to be missing a quote.

Additional tips:
Don't try and build everything at once. Start off with one simple task, and get that working by itself. For instance, start with just setting / read the cookie and not worry about the rock. Once you get one feature working specifically the way you want it working, add more onto it.

A: you have one line of code in a setTimeout:
setTimeout("document.getElementById(('rockImg').src = 'images/rock.png';", 5 * 60 * 1000);

its syntactically wrong.
setTimeout("document.getElementById('rockImg').src = 'images/rock.png';", 5 * 60 * 1000);

what would be better:
setTimeout(function()
{
    var rockImg = document.getElementById('rockImg');
    if(rockImg != null)
    {
        rockImg.src = 'images/rock.png';
    }
}, 5 * 60 * 1000);

function(){ ... } creates an anonymous function.
It stays as code not text (which means any syntax higlighter will work on it.) and its easy to read.


text:
Q: Menu dinâmico com dropdown Preciso tornar esse menu responsivo, usando dropdown.
A cada categoria adicionada ele gera um item no menu:

        <?php if($secoes) {
              while ($linha=mysql_fetch_array($secoes)) { ?>

<a href="produtos.php?cat=<?=$linha["id"]?>"><?=utf8_encode($linha["nome"])?>

        <?php }
        } ?>

A: Podes fazer isso utilizando o componente dropdown do Bootstrap para adicionar menus dropdown, que são accionados por um toggle (ou seja, abrem e fecham a partir um clique) sem ser preciso escrever uma única linha de JavaScript.
Como no exemplo do código abaixo:
(Tens aqui também um Exemplo Online no jsFiddle com vários itens na lista)

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Marca

                    <?php if($secoes) {
                          while ($linha=mysql_fetch_array($secoes)) { ?>

<a href="produtos.php?cat=<?=$linha["id"]?>"><?=utf8_encode($linha["nome"])?>

                    <?php }
                    } ?>


text:
Q: How to freeze selected weights in keras or tf.keras? I am trying out something where I required to freeze some selected weights. Take this example
from keras.models import Sequential
from keras.layers import Dense,Input

model = Sequential()
model.add(Dense(4, input_shape=(4,),activation='relu'))
model.add(Dense(3,name="hidden",activation='relu'))
model.add(Dense(2,activation='sigmoid'))
model.compile(loss='mse', optimizer='adam')

print(model.layers[1].get_weights()[0])

This will print the input to hidden layer weights.
# Weights input x hidden
# Freeze 2Rx3C and 4Rx2C
# 2Rx3C=0.14362943; 4Rx2C=-0.23868048
array([[-0.05557871,  0.10941017, -0.59108734],
       [ 0.37056673,  0.2968588 ,  0.14362943],
       [-0.05471832, -0.21425706,  0.6455065 ],
       [-0.7883829 , -0.23868048, -0.517396  ]], dtype=float32)

From this weight matrix I want to freeze values in (2nd Row, 3rd Column) and (4th Row, 2nd Column), that is, 0.14362943 and -0.23868048 respectively. I dont want to update these values on backprop. How can I freeze these selected weights?

A: You need to use tf.identity, it is used when you want to explicitly transport tensor between devices.
matrixVariable = tf.Variable(<your matrix>)
matrixVariableSliced = matrixVariable[<sliced matrix>] #take out your required weights
matrixVariable_stop = tf.stop_gradient(tf.identity(matrixVariableSliced))
matrixVariable = tf.concat((matrixVariableSliced, matrixVariable_stop), axis=1)


text:
Q: SQL Server - Must declare the scalar variable I am trying to declare these values and use execute them to get a specific values of an attribute in a table. However everytime I am time trying to set @test and @columnPeriod it gives me the error Must declare the scalar variable "@test" or Must declare the scalar variable "@columnPeriod"
DECLARE @columnPeriod VARCHAR(MAX), @test INT;
SET @test = 2015;
SET @columnPeriod = 'SELECT Period FROM Courses WHERE year = ' + @test + '';

A: You can't combine Strings and INTs
Try
SET @columnPeriod = 'SELECT Period FROM Courses WHERE year = ' + CONVERT(VARCHAR(12),@test) + ' Limit 1';

This will also limit your selection to ensure it is scalar

A: DECLARE @columnPeriod INT, @test varchar(4);
SET @test = '2015';
SET @columnPeriod = SELECT distinct Period FROM Courses WHERE year = ' + @test + '';

Assumptions being:

*

*period only has ONE record with year 2015  if you have more than one but all the same "period" then distinct may be needed.  If you have multiple, you can't do this as the record set returned has more than one row...

*Year is a varchar datatype


text:
Q: Return 2 values from function vb.net What I want is to return 2 values from the database with a function and then store the values in variables so I can work with them. This is my code.
Function Buscar_Registro(ByVal xId As Integer) As String
    Dim a, b As String

    'convertir cadena
    Dim Id As Integer
    Id = xId

    'conexión
    Dim Conexion As OleDbConnection = New OleDbConnection
    Conexion.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Visual\2000Phrases\2000 Phrases.accdb"

    'cadena SQL
    Dim CadenaSQL As String = "SELECT * FROM Data WHERE Id = " & Id

    'Adaptador
    Dim Adaptador As New OleDbDataAdapter(CadenaSQL, Conexion)

    'Data set
    Dim Ds As New DataSet

    'Llenar el Data set
    Conexion.Open()
    Adaptador.Fill(Ds)
    Conexion.Close()

    'Contar registro
    If (Ds.Tables(0).Rows.Count = 0) Then
        Return False
    Else
        a = Ds.Tables(0).Rows(0)("Nombre").ToString()
        b = Ds.Tables(0).Rows(0)("Apellido").ToString()

        Ds.Dispose()
        Return a
        Return b
        Return True
    End If

End Function

Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
    Randomize()
    Dim value As Integer = CInt(Int((20 * Rnd()) + 1))
    TextBox3.Text = Buscar_Registro(value)
    TextBox4.Text =
End Sub

I dont' know how to do it. The function returns only the value of "a"
Thanks

A: Your best option here is to create your own class with the data you need and return that.
Public Class Data
    Public Property Nombre As String
    Public Property Apellido As String
End Class

And then do:
Function Buscar_Registro(ByVal xId As Integer) As Data
....
    If (Ds.Tables(0).Rows.Count = 0) Then
        Return Nothing
    Else
        a = Ds.Tables(0).Rows(0)("Nombre").ToString()
        b = Ds.Tables(0).Rows(0)("Apellido").ToString()

        Ds.Dispose()
        return new Data() With {.Nombre = a, .Apellido = b}
    End If
End Function

As of VB 15 you can use ValueTuple
Function Buscar_Registro(ByVal xId As Integer) As (Nombre As String, Apellido As String)
    ....
        If (Ds.Tables(0).Rows.Count = 0) Then
            Return (Nothing, Nothing)
        Else
            a = Ds.Tables(0).Rows(0)("Nombre").ToString()
            b = Ds.Tables(0).Rows(0)("Apellido").ToString()

            Ds.Dispose()
            Return (a, b)
        End If
    End Function

A: I'm new to .net but wouldn't "ByRef" be the easiest way?
Function Buscar_Registro(ByVal xId As Integer, ByRef a As String, ByRef b As String)

A: To return more values you need to change your function "as object"
Function Buscar_Registro(ByVal xId As Integer) As Object

and then you can put your return values into an object this way:
Return{a, b, true}

You'll get your values this way:
Dim mObj as object = Buscar_Registro(yourInteger)

you'll have:
a in mObj(0)
b in mObj(1)
True in mObj(2)

adapt it to your needs
EDIT (message to those that downvoted):
Creating a class an using a specific Object (the one created) to make a Function able to return multiple elements is surely the best choice.
Anyway, if someone doesn't know that it's possible to use the method that I showed in my answer, he is probably not (yet) able to create a class. So I think it's better give an usable (but not perfect) answer instead of a perfect (but unusable for the one who asked) answer.
This is what I think. Anyone can think differently.


text:
Q: Setting up a basic scala program on a server As an experiment in scala I want to set up a basic website with scala as a server side language. This would not carry out many interactive tasks - it would simply write and distribute HTML in response to HTTP requests.
I don't know much about how the piping of web servers works, but I've written lots of HTML, CSS, JS and PHP and I envisage this working much like the PHP back end in wordpress - the client sends an HTTP request for a page such as example.wordpress.com/2012/06/18/example_blog and the PHP on the server compiles an HTML web page and returns it to the user.
Although I'm open to suggestions, I'd rather not use a full blown framework such as Lift as I'm trying to build from the ground up. I'm only interested in the very basic task of taking an HTTP request as input and outputting an HTTP response.

A: Usually you'd take a Java EE server and implement a Servlet.
Here is one:
package myservlet

import javax.servlet.http._

class Servlet extends HttpServlet {
  /** Servlet's main method. */
  protected def welcome (request: HttpServletRequest, response: HttpServletResponse): Unit = {
    response.getWriter.write ("hi")
  }
  override def doGet (request: HttpServletRequest, response: HttpServletResponse): Unit = welcome (request, response)
  override def doPost (request: HttpServletRequest, response: HttpServletResponse): Unit = welcome (request, response)
}

Then you'd mention it in web.xml as usual:
<servlet><servlet-name>MyServlet</servlet-name>
  <servlet-class>myservlet.Servlet</servlet-class></servlet>
<servlet-mapping><servlet-name>MyServlet</servlet-name>
  <url-pattern>/</url-pattern></servlet-mapping>

Refer to any Java Servlet tutorial for details.

A: You may not want to deal with Java EE and the whole servlet thing, especially if you don't come from the "Java world".
There are some really lightweight HTTP toolkits in Scala like Blueeyes or Play mini but my favorite is definitely Unfiltered
EDIT: A more complete answer on this thread Scala framework for a Rest API Server?


text:
Q: Can we configure what type of failed events should be dead lettered in Azure EventGrid? I have set up a HttpTriggered Azure Function that handles events from EventGrid. We have downstream APIs that we need to call, sometimes these are down or something unexpected happens. I want to store the events that fail. I have setup dead lettering. However, reading the docs, it looks like EventGrid will immediately dead letter events with these responses:
400 Bad Request, 413 Request Entity Too Large, 403 Forbidden, 404 Not Found, 401 Unauthorized
Is there a way to configure event grid to skip dead lettering of these, and only store all other codes? I don't want to clutter my storage account with these types of events, as I suspect I will see lots of 400 and 403 from some of our event sources.
I guess I can make another function that is blob that is blob triggered and deletes the events with the status codes I don't want, if that is possible. Just wondering if this is something that is possible in the setup of the dead lettering configuration in the subscription.

A: The best option here might be to add some structured exception handling within your function to manage those downstream APIs. If you don't want to dead-letter the event delivery, then catch the exception and return a different status code so that another delivery attempt will occur.
A second option could be to choose a different handler, such as a service bus queue. This will give you more control over the dead-letter process as well as accommodate for those long-running processes that may exceed the 30 second response/acknowledgement window that Event Grid expects.


text:
Q: Using group by with left join and IN yields empty result I have two tables: invitees and invitee_information. invitees belong to events (third table event_id is a foreign key in invitees table).
I want to get the total count of invitees per event for which there is no information available yet (no record in the invitee_information table).
When I write the query using only one event_id in the where clause and anti-join pattern (IS NULL for invitee_id column to filter for rows having no information saved) the count is returned as expected for that given event_id:
SELECT COUNT(i.id)
FROM invitees i
LEFT JOIN invitee_information ii
ON ii.invitee_id = i.id
WHERE ii.invitee_id IS NULL AND i.`event_id` = 18571 AND i.`invitation_sent` = 1;

Now in order to optimize the query to get this count data at DB level for multiple event_ids instead of getting this in a loop for each event_id, I used IN and passed multiple event_ids and used GROUP_BY event_id.
Expected result should be (if there is no data saved in invitee_information table for event_id 18569 :
event_id | count(i.id)
18569    |          0

But query result is always empty. My updated query is:
SELECT i.`event_id`, COUNT(i.id)
FROM invitees i
LEFT JOIN invitee_information ii
ON i.id = ii.invitee_id
WHERE ii.invitee_id IS NULL AND i.`event_id` IN(18569,18571) AND i.`invitation_sent` = 1
GROUP BY i.`event_id`;

A: The only way I could imagine this happening is if you have internationalization settings such that , means a decimal point.  You can easily test this using:
SELECT i.`event_id`, COUNT(i.id)
FROM invitees i LEFT JOIN
     invitee_information ii
     ON i.id = ii.invitee_id
WHERE ii.invitee_id IS NULL AND
      (i.`event_id` = 18569 OR i.`event_id` = 18571) AND
      i.`invitation_sent` = 1
GROUP BY i.`event_id`;

If this works, then at least we have identified the problem.  I think a space then works:
SELECT i.`event_id`, COUNT(i.id)
FROM invitees i LEFT JOIN
     invitee_information ii
     ON i.id = ii.invitee_id
WHERE ii.invitee_id IS NULL AND
      i.`event_id` IN (18569, 18571) AND
      i.`invitation_sent` = 1
GROUP BY i.`event_id`;

I should note that you probably want COUNT(ii.invitee_id) in the SELECT rather than COUNT(i.id).  The latter will never return 0.
EDIT:
Perhaps the two events are not in the invitees table.  Assuming you have an events table, then something like this:
SELECT e.event_id, COUNT(i.id)
FROM events e LEFT JOIN
     invitees i
     ON i.event_id = e.event_id AND
        i.invitation_sent = 1 LEFT JOIN
     invitee_information ii
     ON i.id = ii.invitee_id
WHERE ii.invitee_id IS NULL AND
      e.event_id IN (18569, 18571) AND
GROUP BY e.event_id;


text:
Q: How an I get an U.A.C prompt for Administrator rights in Python How can I get the UAC prompt to give my Python code Admin rights? I have tried this but Python 32 Bit or my Terminal just freezes:
    import os
    import sys
    import win32com.shell.shell as shell
    ASADMIN = 'asadmin'

    if sys.argv[-1] != ASADMIN:
         script = os.path.abspath(sys.argv[0])
         params = ' '.join([script] + sys.argv[1:] + [ASADMIN])
         shell.ShellExecuteEx(lbVerb='runas', lpFile=sys.executable, lpParameters=params)
         sys.exit(0)
    with open("somefile.txt", "w") as out:
         print >> out, "i am root"

A: You can make a shortcut somewhere and as the target use: python yourscript.py then under properties and advanced select run as administrator.
When the user executes the shortcut it will ask them to elevate the application.


text:
Q: Hibernate return empty object I have 3 tables: movie, movie_category and category
I create entities class
@Entity
@Table(name = "category")
@Data
public class Category {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(nullable = false, unique = true)
    private Integer categoryId;
    private String name;
}

public class Movie {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(nullable = false, unique = true)
    private Integer movieId;
    ........

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private List<MovieCategory> movieCategories;
}

@Entity
@Table(name="movie_category")
@Data
public class MovieCategory {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(nullable = false, unique = true)
    private Integer movieCategoryId;

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "movieId", referencedColumnName = "movieId")
    private Movie movie;

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "categoryId", referencedColumnName = "categoryId")
    private Category category;

}

One movie has many film_categories. When i use JpaRepository interface and findAll() for Movie entity hiberante return movieCategories as empty array. I using bidirectional perspective. Using unidirectional is possible return Movie with list categories?

A: Do not forget to use mappedBy property on ToMany annotations. In your case is necessary because you are using bidirectional association and every bidirectional association has an owner side and an inverse side.
Before it you may have to define the owning side and inverse side. JPA uses the owning side to decide if an association exists between two entities.
The owning side is the one which defines how the association is mapped (using the JoinColumn, JoinTable, etc. annotations). It doesn't have any mappedBy attribute.
The inverse side uses the mappedBy attribute to map which property the attribute is defined in owning side.

A: Try putting the below code in Movie class
@JoinTable(name = "MovieCategory", joinColumns = @JoinColumn(name = "movieId"), inverseJoinColumns = @JoinColumn(name = "categoryId"))
private List movieCategories;


text:
Q: How to chart a line and a fixed point in the same chart in Looker I want to compare precision-recall curve of my model to current rule based model precision-recall. So I want to have a chart with a line and a fixed point. Data looks like following:

threshold
precision
recall
current precision
current recall

0.01
0.05
0.93
.    0.55
.     0.35.

0.02
0.07
0.87
.    0.55
.     0.35.

0.03
0.09
0.81
.    0.55
.     0.35.

.
.
.
Please note current precision/current recall values are constant for each row.
I want to have a line (or scatter plot) of precision recall and mark the current precision/recall point in the same chart.
Is there a way to do this in Looker?

A: Go to the chart option under the "Series" tab (see pic 1), and for current precision/recall, change the type to scatter. For the remaining dimensions( precision and recall curve), change it to an area or line chart. Also, you can even go to the "Y" tab and drag current recall and precision to the right axis if you want. The final result should be similar to pic 2.


text:
Q: Bim 360 pushpin extension used in forge viewer Is it possible to customize the pushpins icons in forge viewer?
here my sample code which is loading "quality-issues" in the viewer.
 _viewer3D.loadExtension('Autodesk.BIM360.Extension.PushPin', extensionOptions)
.then((pushPinExtension) => {
  PushPinExtensionHandle = pushPinExtension;
  //remove last items collection
  pushPinExtension.removeAllItems();
  pushPinExtension.showAll();

  //get out the data of this pushpin
  var labelData = $('#labelPushpinParam').text();
  var ItemsFromBIM360API = JSON.parse(labelData);
  renderIssues(ItemsFromBIM360API, pushPinExtension);
});

And renderIssue() function will render the pushpins in viewer.
function renderIssues(issues, pushPinExtension) {` issues.forEach(issueData => {
pushPinExtension.createItem({
  type: issueData.type,
  id: issueData.id,
  label: issueData.title,
  status: issueData.type + '-' + issueData.status,
  position: issueData.location,
  objectId: issueData.object_id,
  viewerState: issueData.viewerState
});});`}

How pushpins are looking once rendered
I want to change that pushpin circle into some other icon. How can we do this?


text:
Q: Automatically expire and delete record in SQLite database I'm am fairly new to android and I made an app that creates, modifies and deletes users using SQLite. What I want to do is that after, lets say a week after a user is created, it deletes itself without the administrator having to do it himself.
Is there a way to do this? Thank you for your answers

A: You'll have to store a creationDate with the user then make a service that runs sql command, let's say each night, to see wich users are more than a week old.
I don't think there is a way that the database detects it alone.
Here is a link about AlarmManager it's usefull to run background stuff at set times.

A: So I created two rows in my SQLite DB and made a timestamp with the current date.
The second row was a TEXT and I made the user pick the expiration date using a CalendarView.
To delete the row I used the delete method. Since this method return an int value, I made it launch a Toast to say how many rows where deleted


text:
Q: how we use operators of implementation class with pointers Vec_MD class is implemented with VecMD_Impl.That can't implement operators from implementation class with using pimple pointer
Implemented class is:
class VecMD{
private:
      VecMD_Impl *pimple;
public:
     ///other elements..//
     ///operators//
     double& operator [] (int index){  //works
           return pimple -> operator[](index);
     }
     VecMD& operator +=(const VecMD& Vec){  //errors
           return pimple -> operator += (Vec);
     }};

Implementation class is
class VecMD_Impl{
private:
     double *p_;
     int dim;
public:
     ////other elements....////
     //opearators//
     double& operator[](int index){
          return p_[index];
     }
     VecMD_Impl& operator +=(const VecMD_Impl& Vec){
          for(int i = 0 ; i <= Vec.dim; ++i){
               p_[i] += Vec.p_[i];
          }
          return *this;
     }};

Is it true -> use operators on implementation class?
If is it true how we use them on pimpl idiom?

A: issue fixed with
VecMD& operator += (const VecMD& Vec)
{
     pimple -> operator +=(*Vec.pimple);
     return *this;
}

Implementation class is same.


text:
Q: Within NSDocument subclass, print() is getting a fixme to printDocument() Within a subclass of NSDocument, print() is getting a fixme to printDocument(), is this a bug? My intention is want to print something into the Xcode console.
It won't let me build, it raise as an error. Look at the image below.
I am on Xcode Version 9.0 beta (9M136h)

This is my first time in a situation where print has two distinctively meanings within a context.

A: I had the same issue in Swift 4
I use:
Swift.print(...)

and it gave the expected result


text:
Q: Accessing temp directory in Swift I was trying to access temp directory in Swift. In Objective-C, I could use the following code to do so:
- (NSString *)tempDirectory {

    NSString *tempDirectoryTemplate =
    [NSTemporaryDirectory() stringByAppendingPathComponent:@"XXXXX"];
    const char *tempDirectoryTemplateCString = [tempDirectoryTemplate fileSystemRepresentation];
    char *tempDirectoryNameCString           = (char *)malloc(strlen(tempDirectoryTemplateCString) + 1);
    strcpy(tempDirectoryNameCString, tempDirectoryTemplateCString);
    char *result                             = mkdtemp(tempDirectoryNameCString);
    if (!result) {
        return nil;
    }
    NSString *tempDirectoryPath = [[NSFileManager defaultManager] stringWithFileSystemRepresentation:tempDirectoryNameCString length:strlen(result)];
    free(tempDirectoryNameCString);
    return tempDirectoryPath;
}

However, I'm a bit confuse about the type conversion and casting from Objective-C to Swift, such as  const char * or CMutablePointer<CChar>. Is there any documents that I should look into?
Thanks.

A: Swift 2.1 version:
func createTempDirectory() -> String? {

    let tempDirURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent("XXXXXX")

    do {
        try NSFileManager.defaultManager().createDirectoryAtURL(tempDirURL, withIntermediateDirectories: true, attributes: nil)
    } catch {
        return nil
    }

    return tempDirURL.absoluteString
}

A: Swift 3 and up
I think a good way to do this in swift is with an extension on FileManager. This should create a unique temporary folder and return the URL to you.
extension FileManager{

    func createTemporaryDirectory() throws -> URL {
        let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString)

        try createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
        return url
    }
}

A: Swift 3 version
func createTempDirectory() -> String? {

    guard let tempDirURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("myTempFile.xxx") else {
        return nil
    }

    do {
        try FileManager.default.createDirectory(at: tempDirURL, withIntermediateDirectories: true, attributes: nil)
    } catch {
        return nil
    }

    return tempDirURL.absoluteString
}

A: A direct translation of your Objective-C code to Swift would be:
func tempDirectory()->String! {
    let tempDirectoryTemplate = NSTemporaryDirectory()  + "XXXXX"
    var tempDirectoryTemplateCString = tempDirectoryTemplate.fileSystemRepresentation().copy()
    let result : CString = reinterpretCast(mkdtemp(&tempDirectoryTemplateCString))
    if !result {
        return nil
    }
    let fm = NSFileManager.defaultManager()
    let tempDirectoryPath = fm.stringWithFileSystemRepresentation(result, length: Int(strlen(result)))
    return tempDirectoryPath
}

It uses the same mkdtemp() BSD method as your original code. This method creates
a directory name from the template which is guaranteed not to exist at the time where
the method is called.
Thanks to Nate Cook who figured out that reinterpretCast() can be used to treat the UnsafePointer<CChar> returned  by mkdtemp() as a CString, so that it can be passed to stringWithFileSystemRepresentation(), see Working with C strings in Swift, or: How to convert UnsafePointer<CChar> to CString.

As of Xcode 6 beta 6, the reinterpretCast() is not necessary anymore and the
above code can be simplified to
func tempDirectory()->String! {
    let tempDirectoryTemplate = NSTemporaryDirectory()  + "XXXXX"
    var tempDirectoryTemplateCString = tempDirectoryTemplate.fileSystemRepresentation()
    let result = mkdtemp(&tempDirectoryTemplateCString)
    if result == nil {
        return nil
    }
    let fm = NSFileManager.defaultManager()
    let tempDirectoryPath = fm.stringWithFileSystemRepresentation(result, length: Int(strlen(result)))
    return tempDirectoryPath
}

A: How about something like :
public extension FileManager {
    func createTempDirectory() throws -> String {
        let tempDirectory = (NSTemporaryDirectory() as NSString).appendingPathComponent(UUID().uuidString)
        try FileManager.default.createDirectory(atPath: tempDirectory,
                                                withIntermediateDirectories: true,
                                                attributes: nil)
        return tempDirectory
    }
}

It doesn't answer your question about char* but it's cleaner...
NSFileManager reference here.
Also check out this SO question regarding unique names.

A: According to Apple, use of NSTemporaryDirectory is discouraged:

See the FileManager method url(for:in:appropriateFor:create:) for the
preferred means of finding the correct temporary directory. For more
information about temporary files, see File System Programming Guide.

So instead, you should use FileManager.default.temporaryDirectory
or if you want an unique path:
let extractionPath = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)


text:
Q: More like this for arrays Every document have an array with weights for each element. How I can get the most similar documents arrays. I think that function more_like_this making the same, but with texts.
Need realiztion in by tools of elasticsearch, of course.
["str":int,"str":int,...]


text:
Q: want convert a column of data in a txt file to a row of a csv file using unix shell script want convert a column of data in a txt file to a row of a csv file using unix shell script.
The test present in the txt file as follows.
ApplChk1,
 ApplChk2,
 v_baseLoanAmountTI,
 v_plannedClosingDateField,
 downPaymentTI,
 downPaymentPercentageTI,
 downPaymentCalcTI,
 downPaymentLoanAmountTI,
 v_appraisedValueTI,
 v_purchasePriceTI,
 v_EstimatedPriceTI,
 v_loanPurpose,
 v_loanType,
 v_docTypeCB,
 v_amortizationTypeCB,
 v_Purpose_of_Refinance,
 v_LoanTerm,
 v_lockPeriodCB,
 v_original_Purchase_Price,
 v_improvementCB,
 v_improvementsCostField,
 v_describeImprovements,
 v_originalCostRefi,
 v_subordinateLienTypeCB,
 v_buyDownContributorCB,
 _RespaLoanInformation_DRadioButton7,
 _RespaLoanInformation_DRadioButton8,
 v_subordinateFinancingCreditLineAmount,
 v_buyDownOptionCB,
 v_cashOutPurposeCB,
 v_subordinateFinancingTI,
 v_homeEqPurposeCB,
 v_initialDrawHomeEq,
 v_originalCostHomeEq,
 v_lienPositionCB,
 v_FirstMortgageAmountTI,
 RehabLoan
I want this content in single row of a csv file.
I have used the following code
{ for i in < file.txt ; do echo -n $i ; done; echo; } > out.csv
The above command displaying the above text in single column when i open out.csv in windows environment using microsoft office.
Please help me in converting above data column into row of a csv file
Thanks in Advance

A: Assuming you use Linux/BSD, you can use "tr"
Example:
sharuzzaman.raslan@NL-4168 ~/test1
$ cat data
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

sharuzzaman.raslan@NL-4168 ~/test1
$ cat data | tr '\n' ','
Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,


text:
Q: Rest Interface for MySQL DB with ACL 99% of what REST API's do is serve as a controlled interface between client and DB, and yet I can't for the life of me find any libraries that do just that.
All libraries focus on providing a REST interface to the developer, who then sets up the communication with the database. It seems like a no-brainer to me to create a library that already interfaces with the database, and all the developer needs to do is define some ACL rules and plug in some logic here or there.
So, before I continue and put my thoughts into actions by actually creating this sort of library, may I just ask anyone with knowledge on the subject; has anyone implemented anything like this yet? Will I be re-inventing the wheel?
I'm talking strictly about a PHP based solutions by the way, I have nothing against other languages, PHP is simply my cup of tea. But for that matter, I haven't found any implementations in other languages either.
And in case my explanation doesn't make it very clear, this is essentially what I'd want:
<?php

class post_controller extends controller {

    protected static $config = array(
        'select'        => true,
        'insert'        => true,
        'update'        => true,
        'delete'        => false,

        'fields'            => array(
            'id'        => array(
                'select'    => true,
                'update'    => false
            ),
            'name'      => array(
                'select'    => true,
                'update'    => true
            ),
            'content'   => array(
                'select'    => true,
                'update'    => true
            )
        )
    );

    /**
     * GET, POST, DELETE are implemented already by the parent controller
     * Just overriding PUT to modify the content entry
     */
    function put($data) {
        $data->content = htmlentities($data);
        return parent::put($data);
    }

}

?>

Thanks in advance for anyone giving their input and apologies if this is not a proper Stackoverflow question.
Edit:
To clarify, this type of service would be for specific use-cases, I don't imagine it to be a type of thing that anyone can use for any type of web service.

A: I have built a similar system for SOAP and must say it's very easy to do so. I haven't seen any prebuilt libraries that would help you do it (and I doubt they exist - see next paragraph), but it shouldn't take you more than a few hours to build your own solution (a day max - with testing and documentation writing included).
It is however a whole another question if you really want to do that. REST can be (mis)used for this purpose, but it is meant for manipulating resources. Records in a database only rarely have a one-to-one mapping with resources. If they do in your case (as they did in mine) then feel free to do it, otherwise it would be nicer to provide a proper REST API. Why expose your internal DB structure to the world? YMMV, of course.


text:
Q: Play framework apache reverse proxy This is my first question in SOF.
I am trying to set up reverse proxy using apache for a web server ruing java Play(https://testhost:20443).
I got the following configuration in the httpd.conf and it works for the most of the pages
ProxyPass       /t/  https://testhost:20443/
ProxyPassReverse /t/  https://testhost:20443/

The user see the URL as
"https://localhost/t/xxxx" instead of "https://testhost:20443/xxxx".

But I have the following route define in Play
    # Home page
    GET     /                          controllers.Application.login()
    POST    /session                   controllers.Application.authenticate()
    GET    /session                    controllers.Application.redirect(url="/"

)

When the application goes to "https://testhost/session" it reverse back to "https://localhost/session" instead of "https://localhost/t/session".
Any help , idea is really appreciated. Thx


text:
Q: Cannot find name 'Exclude'. Apollo, Graphql Hi guys I have a problem. I'm trying to include Apollo in my Angular 6 project and when i want to run my application I'm facing an issue. I receive this error.
ERROR in node_modules/apollo-angular/types.d.ts(10,58): error TS2304: Cannot find name 'Exclude'.

In lib from tsconfig.json I have :
 "lib": [
  "esnext.asynciterable",
  "es2017",
  "dom",
]

But I still receive this error. What I can change to be able to run my app?

A: Came across the same issue, but used another approach (hack). apollo-angular seems to be using a type "Exclude" that is not available to Angular 6 in the tsconfig.json options, so adding an "es5"  as following will do the trick:

"lib": [
      "esnext.asynciterable",
      "es5",
      "es2017",
      "dom",
    ]
If that doesn't work, you can declare this type in the  node_modules/apollo-angular/types.d.ts file directly as:
declare type Exclude<T, U> = T extends U ? never : T;
This last option is a hack and will be overwritten by any "npm install" or apollo-angular updates, so use with caution.

A: I faced the same issue and solve it by running the following cmd command:

npm install typescript@2.9.2 --save-exact

A: so I updated typescript version to 2.8.1 and now it work. The thing is now i receive a warning from angular because angular expect to have version < 2.8.0 but it's just a warning and i can hide that.