text:
Q: MIPS: Accessing all indexes of an array and printing it out I am trying to take in some user input that takes in a length of an array, and the user is able to assign the numbers for every index of that array, and then print it out. The Java code I basically want to do is:
Scanner sc = new Scanner(System.in);
    int N = sc.nextInt();
    int[] array = new int[N];
    for (int i=0; i<N; i++) {
      array[i] = sc.nextInt();
    }

A: The index needs to be scaled to make a byte offset, which can then be used together  with the base address of the array.  Why?  Because each integer takes 4 bytes, and in memory, each of those 4 bytes has its own address.  The next integer in the array (e.g. at i+1) starts at an address that is numerically 4 higher than the last one (e.g. at i).  So, we scale indexes by the size of the array element to make a byte offset to access an indexed element of the array.
There's no point to copy $v0 into $s1, it will store into memory just fine from $v0.
You've changed the loop from a for-loop in Java to a do-while in assembly, which means that if the user inputs a count of 0 it will work in the Java version, but break in the assembly version, in that it will still ask for at least one input.  The Java version will follow this pattern:
int i = 0;
while ( i < N ) {
    <for-loop-body>
    i++;
}

So, loop-test, loop-body, increment, loop-test, loop-body, increment...
By the syscalls, looks like you're using MARS or QtSpim, and neither of these uses a branch delay slot by default.  I guess you are selecting the option for that?
The approach of putting the increment in the branch delay slot will also loop one more time than you're expecting: in the Java version, the increment will happen before the loop exit test, but in the assembly version, after.
It's a very good approach that you started with pseudo code — that often offers considerable clarity that is hard to have writing in assembly from scratch without an algorithm.  But you should try to follow your pseudo code more literally, rather than making arbitrary changes in taking it to assembly code.


text:
Q: Issue uninstalling machine-wide ProvisionedAppX package Our company has a UWP application, DentalDial that is packaged as a .msix. This package is installed for all users with the ProvisionedAppPackage powershell commands.
Command used for install:
Add-AppxProvisionedPackage -Online -PackagePath "C:\some\path\DentalDialInstaller_3.0.7.0\DentalDialInstaller_3.0.7.0_x86.msixbundle" -SkipLicense

This seemingly works fine, the app package is installed for all users, without problem.
As seen from the output of
Get-AppPackage -AllUsers

The issues arise when trying to uninstall the package for all users. Following guides form here https://www.advancedinstaller.com/per-machine-msix.html I have tried all possible path combinations I could think off, with most of the commands seeming to execute successfully but change nothing
Remove-AppPackage -Package "DentalDialInstaller_3.0.7.0_x86__sxsx6zjqc160p" -AllUsers
Remove-AppPackage -Package "DentalDialInstaller_3.0.7.0_x64__sxsx6zjqc160p" -AllUsers
Remove-AppPackage -Package "DentalDialInstaller_3.0.7.0_neutral__sxsx6zjqc160p" -AllUsers
Remove-AppPackage -AllUsers -package "DentalDialInstaller.DentalDial_3.0.7.0_x86__sxsx6zjqc160p"
Remove-AppPackage -AllUsers -package "DentalDialInstaller_3.0.7.0.DentalDial_3.0.7.0_x86__sxsx6zjqc160p"

Any ideas as to how to properly uninstall this app packages for all users would be greatly appreciated, Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Read the instrument data from printer port directly with computer I could not find the step by step guide of some kind to accomplish what I am planning to do. I have two devices that I want to connect to PC (windows). Right now, both devices write their output through the printers attached to them. My goal is intercept the data sent to the printer and read the output through computer and remove the printer completely from both devices. On one of the device, the OEM seems to have used just some pins  and removed others.
Can you please advise  in a step-by-step manner the instructions I need to follow to transmit the data directly to the computer?
I have attached the images of the cable that is now going to printer.
I have some programming experience but this is the first time I am playing with serial and parallel port communication.

A: Forget trying to read data from the parallel port. You can do it, but it's not built in to the PC.
Instead, look at the serial port.
ETA - Sorry, but I was unclear. First, of course, new machines generally don't have a parallel port. Problem is, new machines don't have serial ports, either. Drat. You can get USB adapters for both. What I meant was that basic (not BASIC, although it applies) operation of serial ports is intrinsically bidirectional, so you can read data from a serial port without getting into advanced features. This is not, in general, true of parallel ports, although bidirectional data transfers have been available for a long time. It's just not as easily implemented with standard commands the way serial data is.
You'll notice that only 8 pins are used. That is a bog-standard pin use, and is very common. Now look at the back of your PC, and you should find a serial port connector, which has 9 pins. You can get a standard "DB25 to DB9 serial port adapter" which will allow you to connect to this 9-pin connector using a standard serial cable. Note also that, for many applications you only need 3 wires to do this. Google RS232. Actually, you can probably get away with 2 wires, since most printers don't talk back to the device that is commanding it.
Now that you've made physical connection, it's time for software. What language do you program in? Read the manual, dude. If it's C or BASIC, there are built-in commands that will let you do this very simply. Note, though, that you may well have to fiddle around (perhaps with an oscilloscope) to determine the bit rate and configure your PC serial port to the correct speed and other parameters. (If you just want to jump in, try 9600 baud, 1 stop, no start, no parity.) Again, read up on RS232 and serial communications.


text:
Q: determine if file is complete I am trying to write a video ruby transformer script (using ffmpeg) that depends on mov files being ftped to a server.
The problem I've run into is that when a large file is uploaded by a user, the watch script (using rb-inotify) attempts to execute (and run the transcoder) before the mov is completely uploaded.
I'm a complete noob. But I'm trying to discover if there is a way for me to be able to ensure my watch script doesn't run until the file(s) is/are completely uploaded.
My watch script is here:
watch_me = INotify::Notifier.new
watch_me.watch("/directory_to_my/videos", :close_write) do |directories|
  load '/directory_to_my/videos/.transcoder.rb'
end
watch_me.run

Thank you for any help you can provide.

A: Just relying on inotify(7) to tell you when a file has been updated isn't a great fit for telling when an upload is 'complete' -- an FTP session might time out and be re-started, for example, allowing a user to upload a file in chunks over several days as connectivity is cheap or reliable or available. inotify(7) only ever sees file open, close, rename, and access, but never the higher-level event "I'm done modifying this file", as the user would understand it.
There are two mechanisms I can think of: one is to have uploads go initially into one directory and ask the user to move the file into another directory when the upload is complete. The other creates some file meta-data on the client and uses that to "know" when the upload is complete.
Move completed files manually
If your users upload into the directory ftp/incoming/temporary/, they can upload the file in as many connections is required. Once the file is "complete", they can rename the file (rename ftp/incoming/temporary/hello.mov ftp/incoming/complete/hello.mov) and your rb-inotify interface looks for file renames in the ftp/incoming/complete/ directory, and starts the ffmpeg(1) command.
Generate metadata
For a transfer to be "complete", you're really looking for two things:

*

*The file is the same size on both systems.

*The file is identical on both systems.

Since "identical" is otherwise difficult to check, most people content themselves with checking if the contents of the file, when run through a cryptographic hash function such as MD5 or SHA-1 (or better, SHA-224, SHA-256, SHA-384, or SHA-512) functions. MD5 is quite fine if you're guarding against incomplete transmission but if you intend on using the output of the function for other means, using a stronger function would be wise.
MD5 is really tempting though, since tools to create and validate MD5 hashes are very widespread: md5sum(1) on most Linux systems, md5(1) on most BSD systems (including OS X).
$ md5sum /etc/passwd
c271aa0e11f560af419557ef49a27ac8  /etc/passwd
$ md5sum /etc/passwd > /tmp/sums
$ md5sum -c /tmp/sums
/etc/passwd: OK

The md5sum -c command asks the md5sum(1) program to check the file of hashes and filenames for correctness. It looks a little silly when used on just a single file, but when you've got dozens or hundreds of files, it's nice to let the software do the checking for you. For example: http://releases.mozilla.org/pub/mozilla.org/firefox/releases/3.0.19-real-real/MD5SUMS -- Mozilla has published such files with 860 entries -- checking them by hand would get tiring.
Because checking hashes can take a long time (five minutes on my system to check a high-definition hour-long video that wasn't recently used), it'd be a good idea to only check the hashes when the filesizes match. Modify your upload tool to send along some metadata about how long the file is and what its cryptographic hash is. When your rb-inotify script sees file close requests, check the file size, and if the sizes match, check the cryptographic hash. If the hashes match, then start your ffmpeg(1) command.

A: It seems easier to upload the file to a temporal directory on the server and move it to the location your script is watching once the transfer is completed.


text:
Q: Navigation Item in XIB file is not visible I'm in XCode 7.2.1 and I am trying to make a view that is reusable and should have some custom elements in the navigation bar.
If I would add a view to my storyboard, connect it via a segue to the navigation controller and make sure there is a "Navigation Item" in the view, I could see the navigation bar and edit my items in it.
If I manually add a Navigation Item to a XIB however I can't see anything. Even if I switch in the simulated metrics settings Top Bar to something else than Inferred or None.
I don't want to use the storyboard, if possible. Is there a descent way to make the navigation item visible and edit it?
Thanks in advance.

A: I don't think you link your View Controller correctly with Navigation Controller. When you link it, you should choose with root View Controller. If you link it correctly, you don't have to add NavigationItem manually.
By the way, you shouldn't do the customization for Navigation bar directly in xib. All you can do is only to set the Title, Prompt and Back Button text.
Do it in code! I think you won't have different styles for navigation bar in different views, right? That would be too silly.


text:
Q: Reuse a ClearCase view I would like to reload a view (which was created previously) instead of creating a whole new one.
Two scenarios:
1 - Hard drive crashes and the local view isn't there anymore.
2 - A new laptop is set up with ClearCase.
In either (or both) of these cases, can a view be restored on your local drive?  Or does the view have to be removed and then create a new one?  I would rather not have STREAM_2_int and STREAM_3_int if I can get away from that.
(Side question:  If someone has a desktop and a laptop, can they use the same view on each, or is it only one for each computer?)

A: Yes, for a snapshot view, provided the ClearCase view storage (the .vws directory) isn't on the same workstation than the view itself.
The only file needed to make a directory a root directory of a (previously created) snapshot view is the hidden file view.dat.
See the IBM technote "Regenerate the view.dat file"
And the perl script (packaged within any ClearCase installation) used to restore that view.dat file is <ClearCase>\etc\utils\regen_view_dot_dat.pl -tag <view-tag-id> <view root directory path>.
Example:
C:\source>ccperl c:\Rational\ClearCase\etc\utils\regen_view_dot_dat.pl -tag aSnapViewName .
rgy_view_uuid: "d17190d381de4ce89757d5465eb41f2c".
creating ".\view.dat".

C:\source>type view.dat
ws_oid:00000000000000000000000000000000 view_uuid:d17190d381de4ce89757d5465eb41f2c

Again, that can only work if the view storage \\shared\path\to\aSnapViewName.vws is in a shared path accessible from the workstation or from the new laptop.


text:
Q: Rocket chat enable ssl in apache I have installed rocket chat on docker - on Debian 9 OS.
I am unable to enable https for the same.
I can access it using fqdn - http://chat.xyz.com:3003
I have generated ssl certificates using certbot.
I am using below configuration in apache:
https://docs.rocket.chat/installation/manual-installation/configuring-ssl-reverse-proxy
    ServerAdmin it@xyz.com
    ServerName chat.xyz.com

    LogLevel info
    ErrorLog /var/log/chat.xyz.com_error.log
    TransferLog /var/log/chat.xyz.com_access.log

    SSLEngine On
    SSLCertificateFile /etc/ssl/certs/cloud-no.com.crt
    SSLCertificateKeyFile /etc/ssl/private/cloud-no.com.key

    <Location />
        Require all granted
    </Location>

    RewriteEngine On
    RewriteCond %{HTTP:Upgrade} =websocket [NC]
    RewriteRule /(.*)           ws://localhost:3003/$1 [P,L]
    RewriteCond %{HTTP:Upgrade} !=websocket [NC]
    RewriteRule /(.*)           http://localhost:3003/$1 [P,L]

    ProxyPassReverse /          http://localhost:3003/
</VirtualHost>```

I have also enabled necessary modules in apache - proxy_http, proxy_wstunnel, etc
I have referred and tried many sites/guides before posting here.
Please help me.


text:
Q: input type=number in BB10 with decimal point on virtual keyboard doen't working I was unable to find the solution to this problem:
I use one  in a webworks app. It's supose that this input will accept integers and float numbers.
The problem is: When I insert some data, for example 3.1415 the device removes the dot and inserts 31415.
I'm not using the input types inside a form so the "novalidate" option isn't possible.
I tried a lot of stuff to fix the problem. Any Idea?
Possible solutions(tricks):
- Use type = text and force the keyboard layout to be the numeric one.
- Disable the validation to this input (and no others).
Do you know how to do that? Do you know other solutions?
Regards. Pablo.

A: This is a know bug in Blackberry 10.
There are posts about it in their support forum, here is a link to one of them.
The only real way around it is to use a standard text input and validate the content yourself until this bug is fixed.

A: I just tested this on an internal build (10.2.1.x) and it is working prefect for me although I'm unable to track down a specific OS build number where the fix was implemented.


text:
Q: Build Python scripts and call methods from C# Is there any way to make this scenario work?
There is a Python script. It is built into a DLL by running this script with IronPython:
import clr
clr.CompileModules("CompiledScript.dll", "script.py")

The goal is to call this DLL's methods from C# code. .NET Reflector shows there is one class in the DLL - DLRCashedCode and the methods we are interested in are private static methods of this class.
For example, there is a function in the script:
def scriptMethod(self, text):
...

Its representation in the DLL is:
private static object scriptMethod(Closure closure1, PythonFunction $function, object self, object text)
{
...
}

Closure and PythonFunction are IronPython classes (from Microsoft.Scripting.dll and IronPython.dll).
So far so good. Is it possible this method to be called by C# code? The idea of using reflection like
Type t = typeof(DLRCachedCode);

string methodName = "scriptMethod";
MethodInfo method = t.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Static);

object[] parameters = new object[] { "param1", "param2" };  // the "params problem"
method.Invoke(null, parameters);

seems harder because of setting the method's parameters. If they are (any how) initialized correctly, could we expect the method to work smoothly?
Is there a better way to call this methods from C#? For various different reasons we prefer to have the script built as a .NET assembly and not to call the script itself.

A: Sort of. You cannot access the Python methods directly from C# code. Unless you are playing with C# 4.0 and the dynamic keyword or you are very, very special ;).  However, you can compile an IronPython class to a DLL and then use IronPython hosting in C# to access the methods (this is for IronPython 2.6 and .NET 2.0).
Create a C# program like this:
using System;
using System.IO;
using System.Reflection;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
// we get access to Action and Func on .Net 2.0 through Microsoft.Scripting.Utils
using Microsoft.Scripting.Utils;

namespace TestCallIronPython
{
    class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            ScriptEngine pyEngine = Python.CreateEngine();

            Assembly myclass = Assembly.LoadFile(Path.GetFullPath("MyClass.dll"));
            pyEngine.Runtime.LoadAssembly(myclass);
            ScriptScope pyScope = pyEngine.Runtime.ImportModule("MyClass");

            // Get the Python Class
            object MyClass = pyEngine.Operations.Invoke(pyScope.GetVariable("MyClass"));

            // Invoke a method of the class
            pyEngine.Operations.InvokeMember(MyClass, "somemethod", new object[0]);

            // create a callable function to 'somemethod'
            Action SomeMethod2 = pyEngine.Operations.GetMember<Action>(MyClass, "somemethod");
            SomeMethod2();

            // create a callable function to 'isodd'
            Func<int, bool> IsOdd = pyEngine.Operations.GetMember<Func<int, bool>>(MyClass, "isodd");
            Console.WriteLine(IsOdd(1).ToString());
            Console.WriteLine(IsOdd(2).ToString());

            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
    }
}

Make a trivial Python class like this:
class MyClass:
    def __init__(self):
        print "I'm in a compiled class (I hope)"

    def somemethod(self):
        print "in some method"

    def isodd(self, n):
        return 1 == n % 2

Compile it (I use SharpDevelop) but the clr.CompileModules method should also work.  Then shove the compiled MyClass.dll into the directory where the compiled C# program lives and run it.  You should get this as the result:
Hello World!
I'm in a compiled class (I hope)
in some method
in some method
True
False
Press any key to continue . . .

This incorporates Jeff's more direct solution that eliminates having to create and compile a small Python 'stub' and also shows how you can create C# function calls that access the methods in the Python class.

A: The clr.CompileModules is purely a load-time optimization - it doesn't make the scripts directly available to a static languge like C#. You'll need to host the IronPython runtime, and then you can load the DLL into the runtime and use IronPython's hosting interfaces to access it.


text:
Q: Dependent combobox in yii framework not working Hi I am using following code to make dependent combobox :
In view :
<?php
    echo $form->dropDownListControlGroup($model, 'DDCode',
            CHtml::listData(dds_designations::model()->findAll
                    (array(
                        'select'=>'DDCode, DDName',
                         'distinct'=>true,
                    )) , 'DDCode', 'DOName')

            , array('ajax' => array(
            'type' => 'POST', //request type
            'url' => CController::createUrl
                    ('OrequestsController/createi')
            ,
            'update' => '#' . CHtml::activeId
                    ($model, 'Designation'),
            'data' => array
                ('DDCode' => 'js:this.value'),
        ))
    );
    ?>

// Designation which need be dependent on above combobox values

  <?php $this->widget('ext.select2.ESelect2',array(

'model'=>$model,
  'attribute'=>'Designation',
  'data'=>CHtml::listData(Orequests::model()->getdesignations($_GET['r']), 'designation', 'designation',
    'htmlOptions'=>array(
    'style'=>'width:50%')
)); ?>

In Controller creati action :
 public function actioncreatei()

                 {

               echo "<option value=''>Select Value</option>";
               if (isset($_POST['DDCode']))
           {
                 $ddcode = $_POST['DDCode'];

               if ($datalst = Orequests::model()->getdesignations($ddcode) )
               {

                  foreach($datalst as $datar)
                {
                  echo
                    CHtml::tag('optgroup', array('label'=>$datar['designation']),
                    CHTML::tag('option', array('value'=>$datar['designation']),
                    CHtml::encode($datar['designation']),true));

           }}}}

The Controller action is not being performed .I have debugged it too after selection in combobox of DDCode, the controller action event don't get triggered at all.Permission has also been granted in accessrules function of controller.Not sure what mistake i m doing i have tested all remedies.
Any Idea what mistake i am doing in code ?


text:
Q: Should I use a single cloud function, or multiple, when handling multiple webhooks from Woocommerce with Firebase Functions? (Webhooks Best Practices) I have webhooks being sent to firebase functions for when Products, Customers, Orders, and Subscriptions are created, updated, restored, and deleted on my WooCommerce site. I am using one destination URL for all of the webhooks (16 - CRUD for Orders, Products, Customers, Subscriptions) and then they are parsed and handled in Firebase functions.
Is this single destination URL a best practice, or should I be creating a new destination URL for every webhook or even every webhook category?
I could see creating a separate one for orders vs products but creating 4 separated ones for product-update, product-create, product-restore, product-delete seems like overkill.

A: You have the ability to go with creating an express app in NodeJS for example, and for your https trigger.onRequest method, pass in your express app, and let the functions handle it from there. It keeps your code cleaner, easier to maintain. For now you are using the web-hooks you mentioned, but if in the future, modifying your express app, would be easier than creating a new cloud function.
You probably have read these docs, but just in case, leaving them here.
In the end, billing would be the same, because you are charged per invocation. Using an app would be cleaner.


text:
Q: Is it possible to get an output from a hidden adaptive card in an action set? I have an adaptive card going to a user in Teams. The card includes a list of values for a user to review and Submit if they're good. If a value needs to be changed, there's an Edit button. The Edit button will Action.ShowCard. A portion of that code is below.
    {
        "type": "ActionSet",
        "actions": [
            {
                "type": "Action.ShowCard",
                "title": "Edit Information ✏",
                "card": {
                    "type": "AdaptiveCard",
                    "body": [
                        {

It seems I'm not getting an output from this adaptive card in Power Automate (screenshot included). I need the output of this card to fill in the values of the following action to Update an item in SPO. The value I'm currently using is @{body('Post_adaptive_card_and_wait_for_a_response_3')?['data']?['client']}.
Is it possible to extract data out of the embedded adaptive card?
Post Adaptive Card And Wait For Response - OUTPUT
I initially posted in the Power Automate Community here where you can find more screenshots.


text:
Q: Servicestack Authentication IsAuthenticated always false Hi am trying to use OAuth authentication provided by servicestack
plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[]     {
new BasicAuthProvider(), new LinkedInOAuth2Provider(new AppSettings()),
new GoogleOAuth2Provider(new AppSettings()) }));

        //Use Redis Repo
        var userRepository = new RedisAuthRepository(redisClientsManager);
        container.Register<IUserAuthRepository>(userRepository);
        //Register Users with redis
        Plugins.Add(new RegistrationFeature());

After Successful authentication by Google/LinkedIn the redis AuthRepo contains this,  We can see that isAuthenticated is False even after Successful authentication.

Could anyone let me know more about OAuth, Because there are many Secrets of it when comes to Mobile.
Eg: What Redirect Uri should i give in LinkedIn Console..! if i use OAuth for Mobiles ..? And how can i refresh session on each App StartUp.

A: Your screenshot does not show an authenticated User Session, which would have IsAuthenticated = true and include OAuth details returned by each OAuth provider in ProviderOAuthAccess collection.
ServiceStack OAuth Live Demos
See the httpbenchmarks.servicestack.net for an example of a working Live Demo that uses Google and LinkedIn OAuth2. The HttpBenchmarks Github Repo includes a step-by-step Guide explaining how to Configure OAuth in ServiceStack, including an example of a App Settings configuration and how to configure Glimpse for inspecting DotNetOpenAuth errors.
The mvc.servicestack.net Live Demo is another example that contains a working configuration using a number of Auth Providers.
Use AppHost AppSettings
When registering the OAuth Provider you should use the AppHost's AppSettings instead of injecting a new AppSettings() that way all Auth Providers will use the same configured AppSettings for your AppHost, e.g:
Plugins.Add(new AuthFeature(() => new AuthUserSession(),
    new IAuthProvider[] {
        new BasicAuthProvider(),
        new LinkedInOAuth2Provider(base.AppSettings),
        new GoogleOAuth2Provider(base.AppSettings)
    }));


text:
Q: IE 11 css SVG fill alternative? I'm currently working on a site which determines the colour of an svg icon by the css element fill, I've had a look on caniuse and I've noticed that it cannot be done on IE, is there a fallback css element I can use instead of this? Or will I have to go through and manually change the colour of the svg's myself for this browser.
Cheers!


text:
Q: Icinga2 check_load plugin thresholds I've recently installed Icinga2 on a bunch of Ubuntu LXC containers. I have a master node where you can log into icingaweb to check status.
However the load thresholds seem low and I cannot see how our even where you can adjust the parameters. May I ask for someone to point me in the right direction? Is this done on the master or the remote nodes? What's the file and where does it sit in the file structure?
I installed Icinga2 on Ubuntu 16.04 server from the Icinga2 PPA

A: Create a service definition for load in master:
apply Service "load" {
    import "generic-service"
    check_command = "load"
    vars.load_wload1 = 5
    vars.load_wload5 = 4
    vars.load_wload15 = 3
    vars.load_cload1 = 10
    vars.load_cload5 = 6
    vars.load_cload15 = 4
    command_endpoint = host.address
    assign where host.name == "monitored client"
}

More info here


text:
Q: python+ keras Error: Error when checking target: expected dense_2 to have 3 dimensions I have DNA data as input to Keras, DNA data is an one-hot encoded array it such that each DNA sequence is 4 channels (one for each type of nucleotide). The one-hot matrix is in matlab and has the dimension: (4,400,100)  100 samples.
first matlab has dimensions row* cloumn * slice (4, 400, 100)
but I change dimensions to get  (100, 4, 400) like python format
    import scipy.io
    x = scipy.io.loadmat('x.mat')
    x2 = x['x']
    x2 = np.ascontiguousarray(x2.T)
    x2 = np.ascontiguousarray(x2.swapaxes(1, 2))
    X_train =x2
    y = scipy.io.loadmat('y.mat')
    y2 = y['y']
    Y_train = np_utils.to_categorical(y2, 2)

Now the X_train shape is: (100, 4, 400)
Y_train shape is (100, 2)
2)
And my model is Conv1D looks like this:
model = Sequential()
model.add(Conv1D(32, 3, activation='relu', input_shape=(4, 400)))
model.add(MaxPooling1D(2))
model.add(Dropout(0.5))

model.add(Dense(128, activation='relu'))

model.add(Dense(1, activation='sigmoid'))

model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

model.fit(X_train, Y_train, batch_size=16, epochs=10)

Error massage
Traceback (most recent call last): in <module>
    model.fit(X_train, Y_train, batch_size=16, epochs=5)

in _standardize_user_data
    exception_prefix='target')
  in _standardize_input_data
    str(array.shape))
ValueError: Error when checking target: expected dense_2 to have 3 dimensions, but got array with shape (100, 2)

A: Try this version:
import numpy as np
from keras.models import Sequential
from keras.layers import Conv1D, MaxPooling1D, Dropout, Dense, Flatten

# This generates some test sample for me to check your code
X_train = np.random.rand(100, 4, 400)
Y_train = np.random.rand(100, 2)

model = Sequential()

model.add(Conv1D(32, 3, activation='relu', input_shape=(4, 400)))
model.add(MaxPooling1D(2))
model.add(Dropout(0.5))
model.add(Flatten()) # <- You need a flatten here
model.add(Dense(128, activation='relu'))
model.add(Dense(2, activation='sigmoid')) # <- the last dense must have output 2

model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

model.fit(X_train, Y_train, batch_size=16, epochs=10)

*

*I added a Flatten layer after the Dropout (remember to import it)

*Since the output is (2,), you need to have the second Dense layer to be Dense(2)
If you change your output to have dimensions (1,), then put again in a Dense(1), but also change the loss from categorical_crossentropy to binary_crossentropy


text:
Q: What is the way of making "Http.post" call in elm I have used the http post in elm in following manner but it is not working and on server side I am getting the empty body.
Can anybody tell me what is wrong with this code.this is the code of my command module
module SignupForm.Commands exposing (..)

import Http exposing(..)
import Json.Decode as Decode exposing (field)
import SignupForm.Models exposing (..)
import SignupForm.Messages exposing (..)
import Json.Encode as Encode
import Debug exposing (log)

memberDecoder : Decode.Decoder UserDetails
memberDecoder =
    Decode.map4 UserDetails
        (field "fname" Decode.string)
        (field "lname" Decode.string)
        (field "email" Decode.string)
        (field "password" Decode.string)

saveUrl : String
saveUrl =
   "http://localhost:4000/userSignup"

saveRequest : UserDetails -> Http.Request UserDetails
saveRequest d =
    Http.request

        { body = memberEncoded d |> Http.jsonBody
        , expect = Http.expectJson memberDecoder
        , headers = defaultRequestHeaders
        , method = "POST"
        , timeout = Nothing
        , url = saveUrl
        , withCredentials = False
        }

defaultRequestHeaders : List Header
defaultRequestHeaders =
    [ Http.header "Content-Type"  "application/x-www-form-urlencoded"
    ]

fetchAll : UserDetails -> Cmd Msg
fetchAll data =
    saveRequest data
        |> Http.send OnSignUp

memberEncoded : UserDetails -> Encode.Value
memberEncoded data =
    let
        list =
            [ ( "fname", Encode.string data.fname )
            , ( "lname", Encode.string data.lname )
            , ( "email", Encode.string data.email )
            , ( "password", Encode.string data.password )
            ]
    in
        list
            |> Encode.object

A: You are posting json, but declaring that you are sending formdata.
Try removing:
defaultRequestHeaders : List Header
defaultRequestHeaders =
    [ Http.header "Content-Type"  "application/x-www-form-urlencoded"
    ]

(Note that expectJson will add Http.header "Content-Type"  "application/json" automatically for you


text:
Q: In "algorithmic" environment, how can I place a comment before a statement? In the algorithmic environment, I can use the \Comment macro to put a comment after a statement. But when I try to put it before the first statement in an algorithm, I get an error. Is there a way to put a comment before a statement? e.g.:

// The following line initializes the variable x.
Let x = 0

A: Comments in pseudocode are typically set on the right, but you can use \Statex to set a blank (unnumbered) \State and then insert whatever you like as a comment:

\documentclass{article}

\usepackage{algorithm,algpseudocode}

\begin{document}

\begin{algorithm}
  \caption{Euclid's algorithm}
  \begin{algorithmic}[1]
    \Function{Euclid}{\null}\Comment{The gcd of $a$ and $b$}
      \Statex \textit{// The following line initializes the variable $r$}
      \State $r \gets a \bmod b$
      \While{$r \neq 0$}\Comment{We have the answer if $r$ is 0}
        \State $a \gets b$
        \State $b \gets r$
        \State $r \gets a \bmod b$
      \EndWhile
      \State \textbf{return} $b$\Comment{The gcd is $b$}
    \EndFunction
  \end{algorithmic}
\end{algorithm}

\end{document}


text:
Q: Show list in descending order I have this program that does not throw error, but the viewl procedure only shows the first item in the list. How do I for the viewl procedure that printing but in the reverse order to what does the procedure viewr?
#include <stdio.h>
#include <conio.h>
#include <windows.h>
#include <stdlib.h>

struct list
{
    int info;
    struct list *nxt,*prv;
}*HEAD=NULL,*AUX=NULL,*P=NULL,*F=NULL,*QD=NULL,*FD=NULL;

main function (ok)
int main()
{
    void insertr(void);
    void extractr(void);
    void viewr(void);
    void viewl(void);
    void deleten();
    void deletep();
    char opc;
    do
    {
        system("cls");
        printf("___________________________________________________\n");
        printf("_______¡¡¡DOUBLE-LINKED CIRCULAR LIST MENU!!!______\n");
        printf("___________________________________________________\n");
        printf("_________________SELECT AN OPTION__________________\n");
        printf("___________________________________________________\n");
        printf("___________________________________________________\n");
        printf("__________1) INSERT________________________________\n");
        printf("__________2) VIEW ASCENDING________________________\n");
        printf("__________3) VIEW DESCENDING_______________________\n");
        printf("__________4) ENTERING AND ELIMINATE NEXT___________\n");
        printf("__________5) ENTERING AND ELIMINATE PREVIOUS_______\n");
        printf("__________6) EXIT__________________________________\n");
        printf("___________________________________________________\n");
        opc=getch();
        switch(opc)
        {
        case '1':
            insertr();
            break;
        case '2':
            viewr();
            break;
        case '3':
            viewl();
            break;
        case '4':
            deleten();
            break;
        case '5':
            deletep();
            break;
        }
    }
    while(opc!='6');
    getch();
    return 0;
}

insert right process
void insertr(void)
{
    P=HEAD;/* very first execution of this method P=NULL */
    AUX=(struct list *)malloc(sizeof(struct list));
    system("cls");
    printf("ENTER AN ENTIRE NUMBER: ");
    scanf("%d",&AUX->info);
    AUX->nxt=HEAD;
    AUX->prv=HEAD;
    F=AUX;
    if(HEAD==NULL)
    {
        HEAD=AUX;
        P = AUX;/*first execution of this method P is no longer NULL but P is pointing to AUX */
    }
    else
    {
        while (P->nxt!=HEAD)
        {
            P=P->nxt;
        }
    }
    P->nxt=AUX;
    AUX->prv=P;
    HEAD->prv=AUX;
}

void deleten()
{
    int x;
    system("cls");
    printf("ENTER A NUMBER TO ELIMINATE THE FOLLOWING: ");
    scanf("%d",&x);

    FD=HEAD;
    QD=HEAD;
    while(FD->info!=x&&FD->nxt!=HEAD)
    {
        FD=FD->nxt;
    }
    QD=FD->nxt;

    if(FD->nxt==HEAD&&FD->info!=x)
    {
        printf("\nENTERED NUMBER IS NOT LISTED");
    }
    else
    {
        if(FD->info==x)
        {
            FD->nxt=QD->nxt;
            (QD->nxt)->prv=FD;
            printf("\nDELETED %d",QD->info);
            free(QD);
        }
    }
    getch();
}

deletea process (ok)
void deletep()
{
    int x;
    system("cls");
    printf("ENTER A NUMBER TO REMOVE THE PREVIOUS ");
    scanf("%d",&x);

    FD=HEAD;
    QD=HEAD;
    while (FD->info!=x&&FD->nxt!=HEAD)
    {
        FD=FD->nxt;
    }
    QD=FD->prv;
    if(FD->nxt==HEAD&&FD->info!=x)
    {
        printf("\nENTERED NUMBER IS NOT LISTED");
    }
    else
    {
        if(FD->info==x)
        {
            FD->prv=QD->prv;
            (QD->prv)->nxt=FD;
            printf("\nDELETED %d",QD->info);
            free(QD);
        }
    }
    getch();
}

viewr process (ok):
void viewr(void)
{
    system("cls");
    if(HEAD==NULL)
    {
        printf("EMPTY LIST");
        getchar();
        return;
    }
    AUX=HEAD;
    printf("LIST:\n\n");
    while(AUX->nxt!=HEAD)
    {
        printf("-> %d\n",AUX->info);
        AUX=AUX->nxt;
    }
    if(AUX->nxt==HEAD)
    {
        printf("-> %d\n",AUX->info);
    }
    getch();
}

this function fails:
void viewl(void)
{
    system("cls");
    if(HEAD==NULL)
    {
        printf("EMPTY LIST");
        getchar();
        return;
    }
    AUX=F;
    printf("LIST:\n\n");
    do
    {
        printf("-> %d\n",AUX->info);
        AUX=AUX->prv;
    }
    while(AUX->nxt!=HEAD);
    getch();
}

A: in your code:
do
{
    printf("-> %d\n",AUX->info);
    AUX=AUX->prv;
}
while(AUX->nxt!=HEAD);

It can be happening something like this.

As you are going to the previous node and checking if next is head, next will be head if you built your list to be double-linked and circular.
try like this:
do
{
    AUX=AUX->prv;
    printf("-> %d\n",AUX->info);
}
while(AUX!=HEAD);

and you should avoid using all variables as global.

A: The code had several logical errors, other variables, etc. Here it is working without problems
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<windows.h>

//THIS IS TO CREATE THE LIST

struct list{
    int info;
    struct list *nxt,*prv;
}*HEAD=NULL,*AUX=NULL,*P=NULL,*FD=NULL,*QD=NULL,*Fd=NULL,*Qd=NULL;

int main(){
    void insertr(void);
    void viewr(void);
    void viewl(void);
    void deleten();
    void deletep();
    char opt;
    do{
        system("cls");

        printf("___________________________________________________\n");
        printf("_______¡¡¡DOUBLE-LINKED CIRCULAR LIST MENU!!!______\n");
        printf("___________________________________________________\n");
        printf("_________________SELECT AN OPTION__________________\n");
        printf("___________________________________________________\n");
        printf("___________________________________________________\n");
        printf("__________1) INSERT________________________________\n");
        printf("__________2) VIEW ASCENDING________________________\n");
        printf("__________3) VIEW DESCENDING_______________________\n");
        printf("__________4) ENTERING AND ELIMINATE NEXT___________\n");
        printf("__________5) ENTERING AND ELIMINATE PREVIOUS_______\n");
        printf("__________6) EXIT__________________________________\n");
        printf("___________________________________________________\n");
        opt=getch();
        switch(opt)  {
        case '1':
            insertr();
            break;
        case '2':
            viewr();
            break;
        case '3':
            viewl();
            break;
        case '4':
            deleten();
            break;
            case'5':
                deletep();
                break;
        }
    }while(opt!='6');
    return 0;
}

void insertr(void){
    P=HEAD; /* very first execution of this method P=NULL */
    AUX=(struct list *)malloc(sizeof(struct list));
    system("cls");
    printf("ENTER AN ENTIRE NUMBER: ");
    scanf("%d",&AUX->info);
    AUX->nxt=HEAD;
    AUX->prv=HEAD; // The pointer to the previous node is null (HEAD is null)
    if(HEAD==NULL){ //I ask if HEAD is equal to Null
        HEAD=AUX;
        P=AUX; /* The first execution of this method P is no longer NULL but P is pointing to AUX */
    }else{ //THIS YES
        while(P->nxt!=HEAD){
            P=P->nxt;
        }
    }
    P->nxt=AUX; // The next pointer of P takes the value of AUX
    AUX->prv=P;
    HEAD->prv=AUX;
}

void deleten(){
    int x;
    system("cls");
    printf("ENTER A NUMBER TO ELIMINATE THE FOLLOWING: ");
    scanf("%d",&x);
    FD=HEAD;
    QD=HEAD;
    while(FD->info!=x&&FD->nxt!=HEAD){ // if what I am going to eliminate is different from the number that was entered and if there is another
        FD=FD->nxt; //step to the next node
    }
    QD=FD->nxt;
    if(FD->nxt==HEAD&&FD->info==x){
        printf("\nIT IS THE HEADBOARD! CAN NOT BE ELIMINATED");
    }else
       if(FD->nxt==HEAD&&FD->info!=x){
        printf("\nTHE NUMBER ENTERED IS NOT IN THE LIST");
    }else{
           FD->nxt=QD->nxt;
           (QD->nxt)->prv=FD;
           printf("\nDELETED %d",QD->info);
           free(QD); //free space in memory occupied by QD
       }
       getch();
}

void deletep()
{
    int xd;
    system("cls");
    printf("IENTER A NUMBER TO REMOVE THE PREVIOUS: ");
    scanf("%d",&xd);

    Fd=HEAD;
    Qd=HEAD;
    while(Fd->info!=xd){
        Fd=Fd->prv;
    } Qd=Fd->prv;

    if(Fd==HEAD){
        printf("\nIT'S THE HEAD! CAN NOT BE ELIMINATED");
    }else{
        if(Qd==HEAD){
            HEAD=HEAD->nxt;
            Fd->prv=Qd->prv;
            (Fd->prv)->nxt=Fd;
            printf("\nDELETED %d",Qd->info);
        }else{
            Fd->prv=Qd->prv;
            (Qd->prv)->nxt=Fd;
            printf("\nDELETED %d",Qd->info);
        }
        free(Qd);
    }
    getch();
}

void viewr(void)
{
    system("cls");
    if(HEAD==NULL){
        printf("LISTA VACIA");
        getchar();
        return;
    }
    AUX=HEAD;
    printf("LISTA:\n\n");
    while(AUX->nxt!=HEAD){
        printf("->%d\n",AUX->info);
        AUX=AUX->nxt;
    }
    if(AUX->nxt==HEAD){
        printf("->%d\n",AUX->info);
    }
    getch();
}

void viewl(void){
    system("cls");
    if(HEAD==NULL){
        printf("EMPTY LIST");
        getchar();
        return;
    } AUX=HEAD->prv;
    printf("LIST:\n\n");
    do{
        printf("->%d\n",AUX->info);
        AUX=AUX->prv;
    }while(AUX->nxt!=HEAD);
    getch();
}


text:
Q: Launch arguments (NSDoubleLocalizedStrings, NSShowNonLocalizedStrings) don't work I'm trying to use the launch arguments such as NSDoubleLocalizedStrings and NSShowNonLocalizedStrings to test localization in my Objective-C project. For some reason I couldn't get neither of them to work. I tried to set both arguments on launch and options in scheme settings:

Also I've checked NSUserDefaults keys and they both are YES. But the arguments still don't work.
To make sure it's not an XCode bug I've created absolutely new single-view project on Objective-C and Swift with one label on the view. Both projects had empty Localizable.strings files and the code in these projects was the following:
@interface ViewController ()
@property (nonatomic, strong) IBOutlet UILabel *label;
@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.label.text = NSLocalizedString(@"Some text", nil);
}
@end

and
class ViewController: UIViewController {
    @IBOutlet var label: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        label.text = NSLocalizedString("Some text", comment: "")
    }
}

The result looked like this:

So here are the questions:
1) What could be the reasons launch arguments don't work in my Objective-C project?
2) Why NSDoubleLocalizedStrings argument doesn't work in Swift?

A: Spending couple days on investigation and deleting gradually all the files and frameworks from my Objective-C project I figured out that the reason was in AFNetworking library. The issue is described here. If you want to use AFNetworking in your project and debug the localization issues you can add such lines to application: didFinishLaunchingWithOptions:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:YES forKey:@"NSDoubleLocalizedStrings"];
[defaults setBool:YES forKey:@"NSShowNonLocalizedStrings"];
[defaults synchronize];

On second launch of the app you'll see those launch arguments working.
The answer for the second question about why NSDoubleLocalizedStrings argument doesn't work in Swift is that it's probably a bug in XCode. It might be connected with macros which are not supported in Swift, and NSLocalizedString is actually a macro. Therefore I've created a bug on radar.


text:
Q: (Softlayer API) How can I get NAS/FTP storage list for an account? I've tried getNasNetworkStorage(), getNetworkStorge() etc. But I couldn't find storages named IBMN87XXXX although I actually have 3 NAS/FTP.
    Account.Service service = Account.service(client);
    service.withMask().nasNetworkStorage();
    service.withMask().nasNetworkStorage().billingItem();
    service.withMask().nasNetworkStorage().billingItem().orderItem();
    service.withMask().nasNetworkStorage().billingItem().orderItemId();

    Account account = service.getObject();

    List<Storage> storages = account.getNasNetworkStorage();

A: The getNasNetworkStorage method must return the NAS/FAT storages, also you can try the getNetworkStorage method which will return all the storages in your account. In case you are not able to see the storage, even using the getNetworkStorage method, this is likely because the API account you are using does not have permissions to list the object storages and I recomend you to check your permissions with the account administrator.


text:
Q: How to add background music to a video file on a specific video second? In node-fluent-ffmpeg I have a 12sec long audio.mp3 file
and video.mp4 is 60sec long.
I need to insert audio.mp3 on the 40th second of the video.
How to do it with node-fluent-ffmpeg?

A: I live in Ukraine and I do not know English well, that's how I realized it.
These are asynchronous methods that can be added to the class, I think you will understand the essence
// just variables
let cutesAudio = await this.cutAudio(audio, time, tempAudio);
let videoDuration = await this.getMediaDuration(video);
let mergeVideoAudio = await this.margeFiles(cutesAudio, video, tempVideo);
let cutMergeVideo = await this.cuteVideo(mergeVideoAudio, videoDuration, resultVideo);

 // cut audio from a specific time and get temp.mp3
 async cutAudio (audio, time, outputMp3) {
   return new Promise((resolve, reject) => {
      ffmpeg()
      .input(audio)
      .setStartTime(time)
      .output(outputMp3)
      .format('mp3')
      .on('end', () => {
          resolve(outputMp3);
      }).on('error', (_err) => {
        reject(_err);
      }).run();
   });
 }

 // get the video duration
 async getMediaDuration (file) {
   return new Promise((resolve, reject) => {
      ffmpeg.ffprobe(file, (_err, metadata) => {
        if (_err === null) {
          resolve(metadata.format.duration);
        } else {
          reject(_err);
        }
      });
   });
 }

 // connect the cut off temp.mp3 and the video and get temp.mp4
 async margeFiles (audio, video, outputVideo) {
   return new Promise((resolve, reject) => {
      ffmpeg()
      .videoCodec('libx264')
      .format('mp4')
      .outputFormat('mp4')
      .input(audio)
      .input(video)
      .output(outputVideo)
      .on('end', () => {
          resolve(outputVideo);
      }).on('error', (_err) => {
          reject(_err);
      }).run();
   });
 }

 // we cut off the video we make it old length as the music can be longer.
 async cuteVideo (video, time, result) {
   return new Promise((resolve, reject) => {
      ffmpeg()
      .input(video)
      .setDuration(time)
      .format('mp4')
      .output(result)
      .on('end', () => {
          resolve(result);
      }).on('error', (_err) => {
        reject(_err);
      }).run();
   });
 }


text:
Q: Why can't Doxygen resolve most of the methods in my call graph? Take a look at this call graph. Now look at the source of that function and all the calls to methods of InboundLedger, through the shared_ptr<InboundLedger> named inbound. Notice how the call graph mentions none of those methods. Notice how the source doesn't cross-reference hyperlink any of those methods (unlike the methods of app_, for example).
If we look at a method of InboundLedger, we can see that Doxygen can resolve and hyperlink other methods of InboundLedger that it calls (tryDB(), isDone(), done()), so the problem isn't just a general "Doxygen can't resolve InboundLedger".
This is the source tree that was used to build that documentation. This is the Doxyfile in that tree. I used Doxygen 1.8.18, built from source, commit b4b47b3919650d7350acc9fe59becaee4a3d5ff5. I had started my journey on 1.8.13, the version packaged for Ubuntu Eoan.
I have enabled BUILTIN_STL_SUPPORT, so Doxygen should be able to see through std::shared_ptr. In fact, I have tried to build a minimum reproducible example with this same Doxyfile and failed; three files with InboundLedger, InboundLedgers, and InboundLedgersImp was able to resolve the call graph as I expected, with the help of BUILTIN_STL_SUPPORT.
I have tried changing various settings, but they af nothing:

*

*Upped DOT_GRAPH_MAX_NODES to 200

*Set every EXTRACT_* setting to YES

*Unset TAGFILES

*Set CLANG_ASSISTED_PARSING to YES


text:
Q: Mysql : daemon doesn't start Few hours ago, Mysql shuts down on my production server. I've tried to restart it with 'service mysqld restart' as usual (I'm on a centos), but:

MySQL Daemon failed to start.

In my log file, I have :
151125 10:53:10 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
151125 10:53:10  InnoDB: Initializing buffer pool, size = 8.0M
151125 10:53:10  InnoDB: Completed initialization of buffer pool
151125 10:53:10  InnoDB: Started; log sequence number 0 6283559
01:53:10 UTC - mysqld got signal 11 ;
This could be because you hit a bug. It is also possible that this binary
or one of the libraries it was linked against is corrupt, improperly built,
or misconfigured. This error can also be caused by malfunctioning hardware.
We will try our best to scrape up some info that will hopefully help
diagnose the problem, but since we have already crashed,
something is definitely wrong and this may fail.

key_buffer_size=8384512
read_buffer_size=131072
max_used_connections=0
max_threads=151
thread_count=0
connection_count=0
It is possible that mysqld could use up to
key_buffer_size + (read_buffer_size + sort_buffer_size)*max_threads = 338336 K  bytes of memory
Hope that's ok; if not, decrease some variables in the equation.

Thread pointer: 0x0
Attempting backtrace. You can use the following information to find out
where mysqld died. If you see no messages after this, something went
terribly wrong...
stack_bottom = 0 thread_stack 0x40000
/usr/libexec/mysqld(my_print_stacktrace+0x29) [0x8509b9]
/usr/libexec/mysqld(handle_fatal_signal+0x483) [0x6a3ef3]
/lib64/libpthread.so.0() [0x3e59e0f790]
The manual page at http://dev.mysql.com/doc/mysql/en/crashing.html contains
information that should help you find out what is causing the crash.
151125 10:53:10 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended

I am losing potential clients every second, so I will appreciate your help, thank you

EDIT
Problem solved ! My partition was full :
# df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1        15G   15G  0M  100% /

I've deleted some useless backups/logs files and restart mysql.
Thank you


text:
Q: CSS: How to NOT display on hover I have
.table_header:nth-of-type(5) {display: none;}

However, when I hover over .table_header on the page the "nth-of-type(5)" shows up. What do I need to do so that it doesn't even if I hover.
Thanks in advance.

A: Demo Fiddle
Why not use :not?
.table_header:nth-of-type(5):not(:hover) {display: none;}

From MDN

The negation CSS pseudo-class, :not(X), is a functional notation
  taking a simple selector X as an argument. It matches an element that
  is not represented by the argument. X must not contain another
  negation selector, or any pseudo-elements.
The specificity of the :not pseudo-class is the specificity of its
  argument. The :not pseudo-class does not add to the selector
  specificity, unlike other pseudo-classes.

A: you missed the :hover :)
.table_header:nth-of-type(5):hover {display: none;}


text:
Q: Make Google Assistant listen for 1 minute I want to make the Assistant leave the microphone open for the user to dictate for up to 1 minute maximum. I somehow want to make it close the microphone only if there previously were 10 seconds of silence.
At the moment the mic closes if the user has stopped speaking at any moment.
I'm not sure if there is any way to change the way the microphone opens for input and closes after input.
Should I use the Dialogflow API or what should I look towards to solve my problem?
Thanks!

A: No, changing the open mic period is not possible
You cannot directly change the amount of time that the microphone stays open in a conversation with Google Assistant. Google automatically closes the conversation as soon as no input is heard from a person.
Responding when the user is silent
What you can do is create an event in Dialogflow that triggers on the actions on google no_input event. With this event you can start a response once the assistant doesn't hear any input, some example responses could be:

*

*Hey, are you still there?

*Hmm, I didn't hear you, could you repeat that?

*etc.


text:
Q: How can I apply cpu and memory limit to "Web Content"? I tried to put memory limit on programs, by using their desktop shortcuts in order to apply the same limit for their child process too.
I found that "Web Content" is a separate process in what is web content and it uses high memory not only in my computer.
I am using for instance for Firefox and child processes in Firefox's .desktop shortcut having an execution line:
Exec=sh -c "ulimit -m 131072;nice -u username 19; cpulimit -l 25 -- ../firefox/firefox/firefox"

Although sometimes, Firefox uses a little bit higher than 25(i.e 26,27) but it seemed that it worked. Also GeckoMain is limited in terms of cpu.
However, I noticed that process named "Web Content" continues to use much higher CPU when Firefox is open. How can I apply cpu and memory limit to "Web Content"?

A: "Web Content" is a subprocess of FireFox.  If you run pgrep -a "Web Content" it will list all of these processes.  The penultimate field will be the process ID of the parent FireFox, for example:
4940 /usr/lib64/firefox/firefox -contentproc -childID 1 -isForBrowser -prefsLen 38 -prefMapSize 289537 -jsInit 285716 -parentBuildID 20220214091044 -appdir /usr/lib64/firefox/browser 4376 tab

where 4376 is the parent ID.


text:
Q: Tuning mysql's query cache I'm looking into tuning the query cache on mysql on my VPS [a 360MB setup]. When I started, it was set at 32MB, and I was getting a non-trivial amount of qcache_lowmem_prunes. I added a cronjob to run FLUSH QUERY CACHE periodically, which helped, but not enough. I've been enlarging it gradually, but even at 80MB [I temporarily took some memory away from php-cgi], I still see lowmem prunes.
OTOH, I only have about a 50% hit ratio [i.e., Qcache_hits is about half of Qcache_hits+Com_select]. I strongly suspect that many of my queries are one time queries, and therefore should not be cached. I'd like to identify them, and mark them with SQL_NO_CACHE.
Any suggestions for an easy way to do this?
It's also possible that some of my queries are not cached since the tables have changed, although I don't think, based on a rough mental model, that this is the case. At least, the results should be consistant for most queries; I'm using InnoDB, so my understanding is that a random UPDATE does not necessarily invalidate all SELECTs. Is this correct?

A: I don't understand why you want to flush the cache.  It takes care of itself, and there's no performance benefit (that I've seen) to periodically flushing it.  50% cache hit ratio is actually pretty amazing.
Any update to any row in the table invalidates all queries that used that table.  That means any queries that join to it are purged.  It doesn't matter if the results are affected or not.
I suggest using a caching solution like memcached instead, where you have more fine grained control of what's being cached and how the data is expired.
If you're seeing performance problems, you might be better off dropping the memory associated to the query cache and bumping up your innodb_buffer_pool and innodb_additional_mem_pool_size.
http://dev.mysql.com/doc/refman/5.0/en/innodb-configuration.html
Also, you should take a look at mysql tuner: https://launchpad.net/mysqltuner/

A: You may create MySQL trigger to analyze on the fly incomming requests and rewrite it with the query_cache var.
This will consume more CPU, but avoid to look at the source of the software.
http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html


text:
Q: AttributeError: 'CorrectorSubwordBert' object has no attribute 'from_huggingface' in Neuspell Upon loading hugging face distilbert-base-case for BertChecker to implement autocorrect on custom vocabulary in NeuSpell using,
checker = BertChecker(device="cuda")
checker.from_huggingface(bert_pretrained_name_or_path="distilbert-base-cased", vocab=vocab),
as in docs, it throws an error
AttributeError: 'CorrectorSubwordBert' object has no attribute 'from_huggingface' in Neuspell.
Any suggestions on how to train a autocorrect in NeuSpell on custom vocabulary?


text:
Q: How to prevent Multi-Value field showing duplicates in Access 365 2016 Im using Microsoft Access 365 2016.
I have created a multi-value field in a table so that i can choose multiple values from a list of check box options (similar to the drop down menu in a field table).
When I click the drop down arrow It shows all the values from the lookup table and displays duplicate options like this:
Null,
Yes,
Yes,
No,
NuLL,
Null,
No
How can I get it to display only unique options like this:
Null,
Yes,
No
Thank you

A: Make Unique Values=Yes on property sheet of your .

When you selecting values from other table as Multiselect Combobox Row Source then build a query from table and make Unique Values to Yes.


text:
Q: Programatically unchecking items in a dialog on Android I am displaying a list with checkboxes in a dialog. The list looks something like-
Item 1

Item 2

All

with a checkbox beside each item. Now the requirements is-
If Item 1 or Item 2 or both are already checked, and All is selected, Item 1 & 2 should be unchecked.
To accomplish this, I implemented DialogInterface.OnMultiChoiceClickListener 's onClick listener.
public void onClick(DialogInterface dialog, int which, boolean isChecked)
{
  if(which == 2 && isChecked)
  {
    ((AlertDialog)dialog).getListView().setItemChecked(0, false);
    ((AlertDialog)dialog).getListView().setItemChecked(1, false);
  }
}

But this does not work. I even tried invalidating the listview by calling Invalidate() & InvalidateViews(), but no success.
Any help will be really appreciated.
Thanks,
Akshay

A: If I understand correctly, the checkboxes are in a list. There's been a question with the opposite situation: trying to uncheck all boxes. The solution seems to be to call
adapter.notifyDataSetChanged()

Here is the link to that question: Uncheck all checkboxes in a custom ListView
EDIT: Okay, I'll try again :-) Found another question about it: android: Refresh ListView using ListAdapter and SimpleCursorAdapter Hope this helps! :-)


text:
Q: to get to the column name or column count in result set of query?
*

*SQL:
select a.a, a.b, b.c from a, b where a.a=b.a;

*SQL:
select '*' from table;

*SQL:
select '*' from table1, table2 where table1.a=table2.a;

*SQL:
select '*' from table1 left join table2 on table1.a=table2.a;

Case 1 is knew the column name in result set of sql (OK).
Case 2 is possible find column name (use to pragma table_info (table);) (OK).
But case 3, 4 is how to get to the column name of column count in result set?

A: You can traverse the returned Cursor like this:
 for (int i = 0; i < cursor.getColumnCount(); i++) {
      Log.d("tag", cursor.getColumnName(i) + " -> " + cursor.getType(i));
 }

Note that the cursor.getType() will be one of the following:
static final int FIELD_TYPE_NULL = 0;
static final int FIELD_TYPE_INTEGER = 1;
static final int FIELD_TYPE_FLOAT = 2;
static final int FIELD_TYPE_STRING = 3;
static final int FIELD_TYPE_BLOB = 4;

A: A query returns a Cursor and you can get cursor column names with e.g. getColumnName().


text:
Q: Is there a way to enable container recycling when grouping in a ListBox? I have a ListBox that can contain hundreds of items. I've added the following attributes to the listbox and performance is great, even if I group / ungroup (using x as ListCollectionView)

<ListBox ItemsSource="{Binding x}"
        VirtualizingStackPanel.IsVirtualizing="True"
        VirtualizingStackPanel.VirtualizationMode="Recycling"/>

However, if I set the ListBox.GroupStyle to anything, even the most simple thing possible, it takes a few seconds to switch from grouped -> ungrouped.
<ListBox.GroupStyle>
    <GroupStyle>
        <GroupStyle.ContainerStyle>
            <Style TargetType="GroupItem">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate>
                            <ItemsPresenter/>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </GroupStyle.ContainerStyle>
    </GroupStyle>
</ListBox.GroupStyle>

I think the reason for this is that WPF is throwing away the cache of containers (enabled by recycling mode in the VirtualizingStackPanel) when I switch to ungrouped and is having to rebuild them from scratch.
Is there a way to improve the performance here? Can anyone suggest something I could try or perhaps a resource I could check out?

A: Check this post, maybe it will be helpful
WPF: Data Virtualization
Also I found similar question on stackoverflow: WPF ListView Virtualization Grouping
and another one (even with answer) WPF Data virtualizing ListView


text:
Q: Using String as Variable Name (C++) Assume I have Variable called "Volume", for example. I now have a file with Settings in it. Every Settings looks like this: ":
I now go through this file from top to bottom, and I want the program to store the Setting in a Variable with an equal Name.
e.G. if there is "Volume: 76", I want the program to write "76" into the Variable "Volume". How can I make the program to get the right Variable just by the string? Is this even possible?
There is no code yet, since I haven't started working on it yet. I was making thoughts about it.

A: You can't use variables directly, since the name must be existent at compile time, but reading a file is runtime.
You can use std::map though. Each settings will be a key, and the value will be read in.
std::map<std::string, std::string> settings;
settings["volume"] = "76";

But, the values ("76" in this case) will be strings as well. You can not use differing types directly.
I think, its possible with type erasure, but thats really advanced (and iam not fluent with it!).


text:
Q: Nonexistence of map taking boundary to torus to wedge of circles homeomorphically Specifically, the question says to consider the torus $T$ as a square with the usual identifications, with two opposite boundary edges labelled $a$ and the other two edges labelled $b$, and consider the wedge of two circles $S$ having two oriented loops labelled $\alpha$ and $\beta$. I have to show that there is no continuous map $T\to S$ which takes $a$ to $\alpha$ and $b$ to $\beta$ homeomorphically.
I should be able to tackle this with homology somehow, I figure by something like assuming there is such a map and showing that the homology groups don't agree, but I'm not seeing how to start going about it. The problem also tells me that it can also be solved with the fundamental group, but I'm even a little more lost as to how to attack that way. A nudge in the right direction would be much appreciated.

A: Well, the fundamental group of a torus is free abelian, the fundamental group of a wedge of circles is free. A continuous map induces a homomorphism on fundamental groups, and you know that YOUR map sends the generators of $\mathbb{Z} \times \mathbb{Z}$ to the generators of $F_2.$ But now consider the element $aba^{-1} b^{-1}$ it is identity in the abelian group, but its image is not the identity in the free group. Pretty goofy for a homomorphism.


text:
Q: Webfont Not Working in Chrome and Firefox So, I'm trying to import the StateFace font into a web app I'm working on. I'm using the following css:
@font-face {
  font-family: 'StateFace Regular';
  src: url('../fonts/StateFace-Regular-webfont.eot');
  src: url('../fonts/StateFace-Regular-webfont.eot?#iefix') format('embedded-opentype'), url('../fonts/StateFace-Regular-webfont.woff') format('woff'), url('../fonts/StateFace-Regular-webfont.ttf') format('truetype'), url('../fonts/StateFace-Regular-webfont.svg#statefaceregular') format('svg');
}
.state {
  font-family: 'StateFace Regular';
  position: relative;
  top: 1px;
  display: inline-block;
  font-style: normal;
  font-weight: normal;
  line-height: 1;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
.state.state-ak:before {
  content: 'A';
}
.state.state-al:before {
  content: 'B';
}
.state.state-ar:before {
  content: 'C';
}
.state.state-az:before {
  content: 'D';
}
.state.state-ca:before {
  content: 'E';
}
.state.state-co:before {
  content: 'F';
}
.state.state-ct:before {
  content: 'G';
}
.state.state-de:before {
  content: 'H';
}
.state.state-fl:before {
  content: 'I';
}
.state.state-ga:before {
  content: 'J';
}
.state.state-hi:before {
  content: 'K';
}
.state.state-ia:before {
  content: 'L';
}
.state.state-il:before {
  content: 'N';
}
.state.state-ks:before {
  content: 'P';
}
.state.state-ky:before {
  content: 'Q';
}
.state.state-la:before {
  content: 'R';
}
.state.state-ma:before {
  content: 'S';
}
.state.state-me:before {
  content: 'U';
}
.state.state-mi:before {
  content: 'V';
}
.state.state-mn:before {
  content: 'W';
}
.state.state-mo:before {
  content: 'X';
}
.state.state-ms:before {
  content: 'Y';
}
.state.state-mt:before {
  content: 'Z';
}
.state.state-nc:before {
  content: 'a';
}
.state.state-nd:before {
  content: 'b';
}
.state.state-ne:before {
  content: 'c';
}
.state.state-nh:before {
  content: 'd';
}
.state.state-nj:before {
  content: 'e';
}
.state.state-nm:before {
  content: 'f';
}
.state.state-nv:before {
  content: 'g';
}
.state.state-ny:before {
  content: 'h';
}
.state.state-oh:before {
  content: 'i';
}
.state.state-ok:before {
  content: 'j';
}
.state.state-or:before {
  content: 'k';
}
.state.state-pa:before {
  content: 'l';
}
.state.state-ri:before {
  content: 'm';
}
.state.state-sc:before {
  content: 'n';
}
.state.state-sd:before {
  content: 'o';
}
.state.state-tn:before {
  content: 'p';
}
.state.state-tx:before {
  content: 'q';
}
.state.state-ut:before {
  content: 'r';
}
.state.state-va:before {
  content: 's';
}
.state.state-vt:before {
  content: 't';
}
.state.state-wa:before {
  content: 'u';
}
.state.state-wi:before {
  content: 'v';
}
.state.state-wv:before {
  content: 'w';
}
.state.state-wy:before {
  content: 'x';
}

It works fine in IE (9-11), but not in Firefox or Chrome. I've looked, and both browsers are pulling in the font file with 200 (or 304) responses with a content length > 0, but the content is not displaying in the font. The Glyphicons font that comes with Bootstrap is working fine, however, and the StateFace font works on other pages, so it must be something specific to my implementation. Does anything stand out as being off?
Edit: The css files are in ~/Content, and the font files are in ~/fonts

A: You're missing the woff source call in your CSS. You must add the woff source to get chrome support. Read this answer on StackOverFlow. I reccommend using Font Squirrel Web Font Generator. Just upload your font and it generates all the CSS you need for cross browser capabilities.
Update:
Another problem that it could be is that Bootstrap less could be overriding your styles because your CSS selector is not specific enough.
Update 2:
Just downloaded the font from font squirrel and it seems that it doesn't work in firefox or chrome for me either.

A: So I found the font on fontsquirrel which is where I assume you downloaded it.
Fontsquirrel's own demo file doesn't work for me in Chrome, and their TTF format doesn't work in windows:

I would try to find a mirror for the file somewhere else and use that, or maybe its just straight up broken and you might have to find another option.


text:
Q: How to mix python mysql.connector and newspaper libraries? I'm currently making a program which searches through the BBC News website and adds each headline to a MySQL database using the mysql.connector and newspaper libraries. I've written the following code but nothing happens when I run it, I was wondering what I'm doing wrong? Apologies if it's just a simple mistake :)
import mysql.connector
import newspaper

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="",
  database="headlines"
)

search = newspaper.build('https://www.bbc.co.uk/news')
for article in search.articles:
    mycursor = mydb.cursor()

    sql = "insert into headlines (headline) values (%s)", (article.title)

    mycursor.execute(sql)

    mydb.commit()

    print(mycursor.rowcount, "headlines inserted.")

A: Currently, you are neither interpolating your article.title to SQL string with modulo operator nor enclosing string literals with quotes. Also, do note: the string modulo formatting is an old, non-recommended version for string formatting, de-emphasized but not officially deprecated.
sql = "insert into headlines (headline) values (%s)", (article.title)

In fact, sql returns as a tuple which is not the expected first argument in cur.execute()
print(type(sql))
# <class 'tuple'>

Possibly, you meant to parameterize your query as MySQL's placeholder, %s, is similar to string modulo placeholder. Doing so properly, you avoid any string interpolation or quote enclosures:
# INITIALIZE CURSOR OUTSIDE LOOP
mycursor = mydb.cursor()

# PREPARED STATEMENT (SCALAR STRING)
sql = "insert into headlines (headline) values (%s)"

search = newspaper.build('https://www.bbc.co.uk/news')

for article in search.articles:
    # BIND PARAM AS ONE-ITEM TUPLE
    mycursor.execute(sql, (article.title,))
    mydb.commit()

    # print(mycursor.rowcount, "headlines inserted.")   -- rowcount IS N/A FOR ACTION QUERIES


text:
Q: How to get linux console $COLUMNS and $ROWS from PHP cli? I'm currently creating a new neat CLI library for PHP, and i'd like to figure out the width/height of the console it's running in.
I've tried many things like digging through $_ENV, exec("echo $COLUMNS"), etc, but no result, while if i type echo $COLUMNS or $ROWS in bash commandline, it neatly displays the value.
What do i need to do to access this value from PHP?
I'm using .sh scripts like this:
#!/usr/bin/php -q
<?php

require_once('lib.commandline.php');

class HelloWorld extends CommandLineApp {

  public function main($args) {

       echo('O, Hai.');

    }

}

Update
Final solution:
public function getScreenSize() {
      preg_match_all("/rows.([0-9]+);.columns.([0-9]+);/", strtolower(exec('stty -a |grep columns')), $output);
      if(sizeof($output) == 3) {
        $this->settings['screen']['width'] = $output[1][0];
        $this->settings['screen']['height'] = $output[2][0];
      }
    }

A: Use the PHP ncurses_getmaxyx function.
ncurses_getmaxyx (STDSCR, $Height, $Width)

PREVIOUSLY:
http://php.net/manual/en/function.getenv.php
$cols = getenv('COLUMNS');
$rows = getenv('ROWS');

The "proper" way is probably to call the TIOCGSIZE ioctl to get the kernel's idea of the window size, or call the command stty -a and parse the results for rows and columns

A: Another shell option that requires no parsing is tput:
$this->settings['screen']['width'] = exec('tput cols')
$this->settings['screen']['height'] = exec('tput lines')

A: $COLUMNS and $LINES is probably not being exported to your program. You can run export LINES COLUMNS before running your app, or you can get this information directly:
$fp=popen("resize", "r");
$b=stream_get_contents($fp);
preg_match("/COLUMNS=([0-9]+)/", $b, $matches);$columns = $matches[1];
preg_match("/LINES=([0-9]+)/", $b, $matches);$rows = $matches[1];
pclose($fp);

A: I dunno, why one should ever need grep to parse stty output: it does have a separate option to report "the number of rows and columns according to the kernel".
One-liner, no error handling:
list($rows, $cols) = explode(' ', exec('stty size'));

One-liner, assume both rows/cols to be 0 in case of problems and suppress any error output:
list($rows, $cols) = explode(' ', @exec('stty size 2>/dev/null') ?: '0 0');

A: Maybe this link might be the answer, you could use the ANSI Escape codes to do that, by using the echo using the specific Escape code sequence, in particular the 'Query Device', which I found another link here that explains in detail. Perhaps using that might enable you to get the columns and rows of the screen...

A: For the record, it is my function (PHP 7.2 and higher):
It works in Windows and Linux. In case of errors, it returns 80.
In the case of some wacky or too small value, it returns the minimum value (80)
ps: "mode con" does return the number of lines but it is based on the buffer than on the screen size.
ps2: Oddly but if I run it as a website, it returns 120 (Windows Host).
   function calculateColSize($min=80) {
       try {
            if (PHP_OS_FAMILY === 'Windows') {
                $a1 = shell_exec('mode con');
                /*
                 * Estado para dispositivo CON:
                 * ----------------------------
                 * Líneas:              9001
                 * Columnas:            85
                 * Ritmo del teclado:   31
                 * Retardo del teclado: 1
                 * Página de códigos:    65001
                 */
                $arr = explode("\n", $a1);
                $col = trim(explode(':', $arr[4])[1]);

            } else {
                $col = exec('tput cols');
                /*
                 * 184
                 */
            }
        } catch (Exception $ex) {
            $col = 80;
        }
    }

A: Environment variables can be found in the $_ENV super global variable.
echo $_ENV['ROWS'];

for instance.


text:
Q: Deleting trigger auto-deleted my script project When I deleted my only trigger (set to run daily) it took all of my script code with it!
When I now go into Tools/Script Editor it shows a blank project (not the saved code I've been working on for a month!)
Restoring previous versions of the spreadsheet doesn't work and I am using the account that I created it in.
I don't know where Sheets automatically stores the .gs files (they don't show on my Drive) but I'm hoping it still exists on their servers and it's just the link to it from the spreadsheet got broken and can be restored.
Please help as I do not want to start from scratch again

A: Here is a script that I use for backing up my files as both separate files and one  big JSON file. It won't help you fix your current problem but you can use to avoid it in the future and unlike backing up the entire spreadsheet and creating another unnecessary project, they get saved as ascii text files.
function saveScriptBackupsDialog() {
  SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('backupscripts1'), 'Script Files Backup Dialog');
}

function scriptFilesBackup(obj) {
  console.log(JSON.stringify(obj));
  const scriptId = obj.script.trim();
  const folderId = obj.folder.trim();
  const saveJson = obj.saveJson;
  const saveFiles = obj.saveFiles;
  const fA = obj.selected;

  if (scriptId && folderId) {
    const base = "https://script.googleapis.com/v1/projects/"
    const url1 = base + scriptId + "/content";
    const url2 = base + scriptId;
    const options = { "method": "get", "muteHttpExceptions": true, "headers": { "Authorization": "Bearer " + ScriptApp.getOAuthToken() } };
    const res1 = UrlFetchApp.fetch(url1, options);
    const data1 = JSON.parse(res1.getContentText());
    const files = data1.files;
    const folder = DriveApp.getFolderById(folderId);

    const res2 = UrlFetchApp.fetch(url2, options);
    const data2 = JSON.parse(res2.getContentText());
    let dts = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "yyyyMMdd-HH:mm:ss");
    let subFolderName = Utilities.formatString('%s-%s', data2.title, dts);
    let subFolder = folder.createFolder(subFolderName);
    if (saveFiles) {
      files.forEach(file => {
        if (file.source && file.name) {
          let ext = (file.type == "HTML") ? ".html" : ".gs";
          if (~fA.indexOf(file.name)) {
            subFolder.createFile(file.name + ext, file.source, MimeType.PLAIN_TEXT)
          }
        }
      });
    }
    if (saveJson) {
      subFolder.createFile(subFolderName + '_JSON', res1, MimeType.PLAIN_TEXT)
    }
  }
  return { "message": "Process Complete" };
}

The html for the dialog:
<!DOCTYPE html>

    <base target="_top">

    <form>
        <input type="text" id="scr" name="script" size="60" placeholder="Enter Apps Script Id" onchange="getFileNames();" />

<input type="text" id="fldr" name="folder" size="60" placeholder="Enter Backup Folder Id" />

<input type="button" value="0" onClick="unCheckAll();" size="15" id="btn3" />
    <input type="button" value="1" onClick="checkAll();"size="15" id="btn4"/>

<input type="checkbox" id="files" name="saveFiles" checked />Save Files

<input type="checkbox" id="json" name="saveJson" checked />Save JSON

<input type="button" value="Submit" onClick="backupFiles();" />
    </form>

If you want the restore just ask.  I haven't used it that much I usually the file that I need and paste past it in.


text:
Q: Why does Magento's translations fail after an unsuccessful payment transaction? we are using magento with onestepcheckout module in our shopping system. But when the payment process fails and when we get an error about payment, not all but some translations fails on the checkout page.
Has anybody face this problem before. I will be very happy if there is an solution.
P.S. I can solve the situation by hard-coding the translations. But I dont want to use this method.
Thank you

A: When a module developer creates a module, it's up to them to make sure that each and every phrase that could be translated is marked for translation. In Magento this means

*

*Strings in template files are passed through the ->__ method

*Labels, parameters, and other strings in XML fiels are marked with translate attribute
As an individual developer, if you're not developing applications/modules intended for translation it's easy to fall into the habit of not doing the above.  Also, the areas of Magento's XML configuration system that can (vs. can't) be translated aren't well documented.  It's easy to miss a string or two, and localization (along with everything else) is almost never tested.
All of which is a long way of saying, contact your vendor and file a bug.  If you want to play capitalism, since you've already hard-coded the translations, fix the core problem yourself and offer to sell the solution back to the onepage people.


text:
Q: Code First Enable Migration I receive this error:
Additional information: The model backing the 'ApplicationDbContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).
Go to that link, and click on the tutorial section for Enabling Migrations which has a link on how to do this. Where do you think this link goes? BACK TO THE SAME PAGE. The documentation is consistently horrendous.
It seems like it should be a checkbox somewhere, or a line of code that I need to add, but I don't know where to find it.
Healy in Tampa

A: The documentation on the Microsoft site isn't very clear. I first came across an issue where I needed to enable migrations when working on an ASP.NET application which relied on the Entity Framework.
The error thrown was the same:

Additional information: The model backing the 'ApplicationDbContext' context has changed since the database was created. Consider using
  Code First Migrations to update the database
  (http://go.microsoft.com/fwlink/?LinkId=238269).

This was a result of me adding a new property to one of my models. When I looked at the controller, it did not update to reflect the new property. If I navigated to http://localhost:59108/Controller I received that message within the Visual Studio 2015 debugger.
To enable migrations, which will update your database when you add a new property to my model and controller, do the following:
Navigate to the Package Manager Console in Visual Studio. (View -> Other Windows -> Package Manager Console). Enter this text:

*

*Enable-Migrations

When it asks for a name enter the name of a new table you'd like to use -- it can be anything.
(UPDATE, from @DrewJordan: it asks for a name when you do add-migration, and it's nothing (inherently) to do with a new table; it's a new migration, and it helps to give descriptive names to your migrations. Like 'AddFooToBar' for adding a Foo property to table Bar.)

*Add-Migration

*Update-Database

*Rebuild your project

*Deploy


text:
Q: Esconder h2 si no hay nada en input tipo search Gracias por la ayuda de antemano.
Tengo un buscador con php que me mustra los resultados desde la base de datos y un h2 donde me dise(Resultados de busqueda para:'el texto que ingrese en el buscador')
pero cuando no pongo nada en el buscador que es un input tipo search con un boton con el name="enviar" me sigue apareciendo el mismo h2.
Anteriormente hice un scrip para que no me lo mostrara mientras no se accionara de esta forma:
<?php
session_start();

function esconderv3(){
    if(!isset($_GET['enviar'])){
        echo "esconder";
    }
}

function esconderv4(){
    if(isset($_GET['enviar'])){
        echo "esconder";
    }
}

?>
Y el html
<h2 class="<?php esconderv3(); ?>">Resultados de búsqueda para:
<h2 class="<?php esconderv3(); ?>"><?php echo $búsqueda ?>

Ahora como podria hacer para que al no ingresar nada en mi buscador se deje de mostrar ese h2??

A: Simplemente así:
<?php
session_start();

if(isset($_GET['enviar']))
    echo '
Resultados de búsqueda para:
'
        .'
'.$busqueda.'
';

O, con un style="display:none", si es que prefieres ocultarlo desde CSS.


text:
Q: REST resource call from JavaScript I have a web app which has JS code as follows (uses Backbone.JS for the model);
var StudentDemographic = BaseModel.extend({
        idAttribute: 'studentId',
        url: 'api/list/student/demographic',
        urlRoot: 'api/list/student/demographic',
        defaults: {
                gender: null,
                age: null,
                dob: null,
        }
});

Now, there is a call to Java (REST resource) , which I am unable to understand like how it is called exactly. The Java code (REST resource) looks like;
@Path("/list")
public class StudentListResource extends BaseResource {

@GET
@Path("/student/demographic")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
@Override
public StudentDemographic getStudentDemographic(@QueryParam("StudentId") String StudentId) {
}

}

My question is how exactly is the mapping there between the JS call to api/list/student/demographic and the corresponding Java method. Is that handled by Java library internally or do I need to look up some configuration in my project? (I am into front-end dev, so not very clear with this backend integration).
Also I am keen to understand the lines in Java code @GET, @PUT, @Override, etc (like what do they mean).

A: Looks like REST application.
The mapping is done by your web application container (Java EE/Spring/...), exact configuration might vary.
The basic mapping definition is done by @Path annotations(here the class StudentListResource handles request going to /list and concrete method getStudentDemographic then handles "relative URL" /student/demographic, thus together /list/student/demographic. This URL is the relative to your web application, that I assume is called "api" (or at least is mapped to /api/**)
@GET annotation just says that it handles only HTTP GET request, similarly @PUT, @POST etc
@Consumes and @Produces specifies that the input and output is expected to be JSON, which is then mapped to Java objects, the input to the method is taken from query (@QueryParam)
@Override is just java language annotation indicating that this method is overridden from super class, but do not have special meaning for mapping.


text:
Q: Page Transformation animation using nineoldandroid doesn't render on api level 10 I have following code for page transformation in  View Pager. It works well on api level 11 or above but not showing animation on api level 10 or below. Note that code uses NineOldAndroid lib to do all animations.
import android.support.v4.view.ViewPager;
import android.view.View;
import com.nineoldandroids.view.ViewHelper;

public class ZoomOutPageTransformer implements ViewPager.PageTransformer {
    private static float MIN_SCALE = 0.85f;
    private static float MIN_ALPHA = 0.5f;

    public void transformPage(View view, float position) {
        int pageWidth = view.getWidth();
        int pageHeight = view.getHeight();

        if (position < -1) { // [-Infinity,-1)
            // This page is way off-screen to the left.
            ViewHelper.setAlpha(view, 0);

        } else if (position <= 1) { // [-1,1]
            // Modify the default slide transition to shrink the page as well
            float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
            float vertMargin = pageHeight * (1 - scaleFactor) / 2;
            float horzMargin = pageWidth * (1 - scaleFactor) / 2;
            if (position < 0) {
                ViewHelper.setTranslationX(view, (horzMargin - vertMargin / 2));
            } else {
                ViewHelper.setTranslationX(view, -horzMargin + vertMargin / 2);
            }

            // Scale the page down (between MIN_SCALE and 1)
            ViewHelper.setScaleX(view, scaleFactor);
            ViewHelper.setScaleY(view, scaleFactor);

            // Fade the page relative to its size.
            ViewHelper.setAlpha(view, MIN_ALPHA +
                    (scaleFactor - MIN_SCALE) /
                            (1 - MIN_SCALE) * (1 - MIN_ALPHA));

        } else { // (1,+Infinity]
            // This page is way off-screen to the right.
            ViewHelper.setAlpha(view, 0);
        }
    }

}