text:
Q: ScrollBar doesnt work in EditText Hope all of you doing well.
My Problem is:
I have xml code like following:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/activity_left_margin"
        android:layout_marginRight="@dimen/activity_right_margin"
        android:orientation="vertical"
        android:paddingBottom="@dimen/activity_bottom_padding"
        android:paddingTop="@dimen/activity_top_padding" >

        <EditText
            android:id="@+id/custDetailsNameEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/name_cust_all_add"
            android:inputType="textPersonName"
            android:textSize="@dimen/common_fontsize" />

        <EditText
            android:id="@+id/custDetailsDescEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dp"
            android:hint="@string/description_add_all_cust"
            android:inputType="textMultiLine"
            android:lines="5"
            android:minLines="3"
            android:gravity="top|left"
            android:scrollbars="vertical"
            android:scrollbarStyle="insideInset"
            android:overScrollMode="always"
            android:fadeScrollbars="false"
            android:scrollbarAlwaysDrawVerticalTrack="true"
            android:textSize="@dimen/common_fontsize" />
    </LinearLayout>

</ScrollView>

In that i have two EditText in </ScrollView>, Second <EditText/> does not scrolling inner side. Problem is Full View is scrolled while i am scrolling but i want to also scroll vertically in second EditText when user enter more than 5 lines. In that ScrollBar is displaying but not scrolling.
How can i solve this.
Your Help would be appreciated.

A: This code should work.....
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    findViewById(R.id.parentScrollView).setOnTouchListener(parentListener);

    findViewById(R.id.custDetailsDescEditText).setOnTouchListener(childListener);

}

OnTouchListener parentListener = new OnTouchListener() {

    public boolean onTouch(View v, MotionEvent event) {
        findViewById(R.id.custDetailsDescEditText).getParent()
                .requestDisallowInterceptTouchEvent(false);
        return false;
    }
};

OnTouchListener childListener = new View.OnTouchListener() {

    public boolean onTouch(View v, MotionEvent event) {
        v.getParent().requestDisallowInterceptTouchEvent(true);
        return false;
    }
};

A: Try something like this in your code
ScrollView scroller = new ScrollView(this);
EditText et=(EditText)findViewById(R.id.yourEdittext);
scroller.addView(et);


text:
Q: iOS Safari using wrong domain for relative CSS path I'm using Font Awesome from a CDN:
<link rel="stylesheet"
    href="//maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"
>

On desktop browsers, it works all fine. But on iOS Safari browsers (iOS 9), the icons do not render, and are all replaced by a square.
I connected my iPad to a Mac, launched developer tools, and noticed that the iOS browser attempts to download the font files from my own server, instead of the CDN.
For example, the CSS file on the CDN contains the following line:
@font-face{
    src:url('../fonts/fontawesome-webfont.eot?v=4.4.0');

But iOS Safari resolves it to:
GET http://mywebsite.com/fonts/fontawesome-webfont.eot?v=4.4.0

As far as I know, in CSS, relative paths are relative to the location of the CSS file, not to the location of the current page.
Is this a (known?) bug in iOS Safari? Is there a fix?
Any pointer appreciated.

A: Not sure exactly where the problem was, but upgrading to iOS 9.2 and Font Awesome 4.5.0 seems to have fixed the problem for me.
I still had an issue though, as the icons appeared for a second and then disappeared. It turned out this was because of an outdated viewport-units-buggyfill.js script. Upgrading it to 0.5.5 fixed this other problem.

A: Did you try with a http in front of the URL, like this?
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

redpajama_set_name: RedPajamaStackExchange


text:
Q: Gmail image proxy I'm sending out html emails. One of the png images is not showing up. When I click on the proxy link I get a 404 error, but the actual image exists and can be publicly clicked on. This works fine on my dev server too. Any ideas as to what could be causing this?

A: I've heard reports that having the same image in multiple places can be the cause of this error with the Google proxy. Save your image as a different names and it should show. Silly that you'd want to load 2 images instead of one, but I believe that is the only workaround currently.


text:
Q: potential energy of a dipole? The very popular from of potential energy of the dipole is $-P.E$. But in the derivation of it, we have negelected the potential energy of the pair of charges constituting the dipole. will this not affect further treatment when we try to apply this to understand aligning of molecular dipoles in electric field? If yes, then how will the modified potential energy function look like?

A: When we talk of a dipole, we usually assume that its configuration is fixed or the changes to the configuration are negligible.
So the effect of an external field on changing the length between a pair of charges is not considered when we are taking them to be a dipole (usually we consider the charges to be rigidly bound).

A: As mentioned in the answer by @Manishearth the potential energy of the dipole is not considered in simple considerations of the dipole. However, such considerations can't be neglected in the study of wave propagation and specific heat of the substance. You might remember even from the elementary study of specific heats in high school that at high temperatures the vibrations mode become significant. Those are the effects that arise when we consider the energy between the charged particles of dipoles up to harmonic approximation. In the study of waves, this gives rise to the optical modes (https://en.wikipedia.org/wiki/Phonon#Acoustic_and_optical_phonons), when talking about dissimilar particles


text:
Q: CSS list-style: lower-alpha issue Standard lower-alpha produces:
a.
b.
c.
I need something like this:
a)
b)
c)
Any suggestions?

A: Something like this?
Added a bracket using ::before and then fiddled with margins to force it to the right place


text:
Q: How can I get out of all loops after I find my item(link) in table Project table contains project list project has columns (Id, name,  PM, etc. ) when clicking on a project, Project details page opens for the project. the Automation find the project and click on it  but I get this error

OpenQA.Selenium.StaleElementReferenceException: The element reference
  of  is stale; either the element is no longer attached to the DOM,
  it is not in the current frame context, or the document has been
  refreshed

I think after clicking on the project, after going to the Proj detail page, the loop doesn't stop. how can I break; from all the loops after I find my project
I am new to automation I need help
public static void SelectProject()
{
    IWebElement Table = Driver.Instance.FindElement(By.Id("projectsGrid"));
    ReadOnlyCollection<IWebElement> allRows = Table.FindElements(By.TagName("tr"));
    foreach (IWebElement row in allRows)
    {
        ReadOnlyCollection<IWebElement> cells = row.FindElements(By.TagName("td"));
        foreach (IWebElement cell in cells)
        {
            if (cell.Text.Contains("002032"))
            {
                cell.Click();
                break;
            }
        }
    }
}

A: No need for flags, use return instead of break.
return;

A: I personally try to avoid break statements, so I would try and use a while or for with a sentinel value but if you want to use foreach you should include a bool that decides whether you break for each loop.  Once you find what you want then set the bool.  For example:
public static void SelectProject()
{
    IWebElement Table = Driver.Instance.FindElement(By.Id("projectsGrid"));
    ReadOnlyCollection<IWebElement> allRows =
        Table.FindElements(By.TagName("tr"));

    bool loop = true;

    foreach (IWebElement row in allRows)
    {
        ReadOnlyCollection<IWebElement> cells =
            row.FindElements(By.TagName("td"));
        foreach (IWebElement cell in cells)
        {
            if (cell.Text.Contains("002032"))
        {
            cell.Click();
            loop = false;
        }
             if (!loop)
             break;
        }
        if (!loop)
                break;
        }
}

A: You can get rid of 99% of the logic in this function with a good locator.
public void SelectProject()
{
    Driver.Instance.FindElement(By.XPath("[@id='projectsGrid']//td[.='002032']")).Click();
}

The above method with throw an exception if this element doesn't exist. Your current method won't do anything (throw an exception or click an element) if the element doesn't exist. If you want that behavior, use the code below.
public void SelectProject()
{
    IReadOnlyCollection<IWebElement> e = Driver.Instance.FindElements(By.XPath("[@id='projectsGrid']//td[.='002032']"));
    if (e.Any())
    {
        e.ElementAt(0).Click();
    }
}

A: You can use a boolean flag called done. It is initially false and only get's set to true just before breaking from the inner loop. If you break out the inner loop, immediately after that in the outer loop check that done == true. If so, that means you broke out the inner loop, so you should also break out the outer loop.
public static void SelectProject()
{
    // Boolean flag for when we break from inner loop
    bool done = false;

    IWebElement Table = Driver.Instance.FindElement(By.Id("projectsGrid"));
    ReadOnlyCollection<IWebElement> allRows = Table.FindElements(By.TagName("tr"));
    foreach (IWebElement row in allRows)
    {
        ReadOnlyCollection<IWebElement> cells = row.FindElements(By.TagName("td"));
        foreach (IWebElement cell in cells)
        {
            if (cell.Text.Contains("002032"))
            {
                cell.Click();
                done = true;
                break;
            }
        }

        // Check if the inner loop
        // broke, if so also break here
        if (done == true) {
            break;
        }
    }
}


text:
Q: iis8 rewrite web config for https multiple applications Been struggling with this and can't get it to work. Can't find any answers online.
I have tried the web.config in the root (www.example.com) and in the application (www.example.com/APP_SSL)
Basically, I have an iis 8 server with multiple websites.
For one particular website. (say example.com) I want suborders to always redirect to https.  Specifically these sub folders are Applications.
I am also trying to redirect example.com -> www.example.com at the same time.
Here is what I want to accomplish:  (sorry if I am too verbose)
example.com/APP_SSL/... -> httpS://www.example.com/APP_SSL/...
www.example.com/APP_SSL/... -> httpS://www.example.com/APP_SSL/...

BUT for other files and applications just be sure we have the www part.
I can live without this stuff as long as the above works.
example.com ->  http://www.example.com
www.example.com -> http://www.example.com  (yes I know this is always true)
example.com/file.htm  -> http:/www.example.com/file.htm
www.example.com/file.htm  -> http:/www.example.com/file.htm

example.com/APP/ -> http://www.example.com/APP/...
www.example.com/APP/ -> http://www.example.com/APP/...

I have tried this, but it really does not do anything that I want.
<rewrite>
<rules>
<rule name="Redirect to www" stopProcessing="true">
<match url="(.*)" />
<conditions trackAllCaptures="false">
<add input="{HTTP_HOST}" pattern="^example.com/APP_SSL$" />
</conditions>
<action type="Redirect" url="{MapProtocol:{HTTPS}}://www.example.com/APP_SSL/{R:1}" />
</rule>
</rules>
<rewriteMaps>
<rewriteMap name="MapProtocol">
<add key="on" value="https" />
<add key="off" value="http" />
</rewriteMap>
</rewriteMaps>
</rewrite>

Putting this in my /APP_SSL/Web.Config gets me most of what I want with the exception of the example.com -> www.example.com
<rewrite>
<rules>
<rule name="Redirect to HTTPS" stopProcessing="true">
<match url=".*" />
<conditions>
<add input="{HTTPS}" pattern="^OFF$" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/APP_SSL/{R:0}" redirectType="SeeOther" />
</rule>
</rules>
<rewriteMaps>
<rewriteMap name="MapProtocol">
<add key="on" value="https" />
<add key="off" value="http" />
</rewriteMap>
</rewriteMaps>
</rewrite>


text:
Q: aws sagemker does not save model artifacts after training RLEstimator I am training a RLEstimator with COACH toolkit and TENSORFLOW framework.
My code is based on sagemaker docs:
import sagemaker
bucket = sagemaker.Session().default_bucket()
role = sagemaker.get_execution_role()

from sagemaker.rl import RLEstimator, RLToolkit, RLFramework

instance_type = "ml.c5.2xlarge"
estimator = RLEstimator(source_dir='src',
                    entry_point="train-coach.py",
                    dependencies=["common/sagemaker_rl"],
                    toolkit=RLToolkit.COACH,
                    toolkit_version='0.11.1',
                    framework=RLFramework.TENSORFLOW,
                    role=role,
                    instance_count=1,
                    instance_type=instance_type,
                    output_path='s3://{}/'.format(bucket),
                    base_job_name='my-job-name')

estimator.fit()

Training is performed normally, the last lines in the output :
2021-06-15 06:10:02,088 sagemaker-containers INFO     Reporting training SUCCESS
2021-06-15 06:10:20 Uploading - Uploading generated training model
2021-06-15 06:10:20 Completed - Training job completed
Training seconds: 136
Billable seconds: 136

But an attempt of deploying the model causes error:
predictor = estimator.deploy(instance_type='ml.m4.xlarge',
                                initial_instance_count=1)

update_endpoint is a no-op in sagemaker>=2.
See: https://sagemaker.readthedocs.io/en/stable/v2.html for details.
---------------------------------------------------------------------------
ClientError                               Traceback (most recent call last)
<ipython-input-8-3b92cb4c3461> in <module>
      1 # Deploy my estimator to a SageMaker Endpoint and get a MXNetPredictor
      2 predictor = estimator.deploy(instance_type='ml.m4.xlarge',
----> 3                                 initial_instance_count=1)

~/anaconda3/envs/tensorflow2_p36/lib/python3.6/site-packages/sagemaker/estimator.py in deploy(self, initial_instance_count, instance_type, serializer, deserializer, accelerator_type, endpoint_name, use_compiled_model, wait, model_name, kms_key, data_capture_config, tags, **kwargs)
    949             wait=wait,
    950             kms_key=kms_key,
--> 951             data_capture_config=data_capture_config,
    952         )
    953

~/anaconda3/envs/tensorflow2_p36/lib/python3.6/site-packages/sagemaker/tensorflow/model.py in deploy(self, initial_instance_count, instance_type, serializer, deserializer, accelerator_type, endpoint_name, tags, kms_key, wait, data_capture_config, update_endpoint)
    285             wait=wait,
    286             data_capture_config=data_capture_config,
--> 287             update_endpoint=update_endpoint,
    288         )
    289

~/anaconda3/envs/tensorflow2_p36/lib/python3.6/site-packages/sagemaker/model.py in deploy(self, initial_instance_count, instance_type, serializer, deserializer, accelerator_type, endpoint_name, tags, kms_key, wait, data_capture_config, **kwargs)
    761                 self._base_name = "-".join((self._base_name, compiled_model_suffix))
    762
--> 763         self._create_sagemaker_model(instance_type, accelerator_type, tags)
    764         production_variant = sagemaker.production_variant(
    765             self.name, instance_type, initial_instance_count, accelerator_type=accelerator_type

~/anaconda3/envs/tensorflow2_p36/lib/python3.6/site-packages/sagemaker/model.py in _create_sagemaker_model(self, instance_type, accelerator_type, tags)
    329             vpc_config=self.vpc_config,
    330             enable_network_isolation=enable_network_isolation,
--> 331             tags=tags,
    332         )
    333

~/anaconda3/envs/tensorflow2_p36/lib/python3.6/site-packages/sagemaker/session.py in create_model(self, name, role, container_defs, vpc_config, enable_network_isolation, primary_container, tags)
   2554
   2555         try:
-> 2556             self.sagemaker_client.create_model(**create_model_request)
   2557         except ClientError as e:
   2558             error_code = e.response["Error"]["Code"]

~/anaconda3/envs/tensorflow2_p36/lib/python3.6/site-packages/botocore/client.py in _api_call(self, *args, **kwargs)
    384                     "%s() only accepts keyword arguments." % py_operation_name)
    385             # The "self" in this scope is referring to the BaseClient.
--> 386             return self._make_api_call(operation_name, kwargs)
    387
    388         _api_call.__name__ = str(py_operation_name)

~/anaconda3/envs/tensorflow2_p36/lib/python3.6/site-packages/botocore/client.py in _make_api_call(self, operation_name, api_params)
    703             error_code = parsed_response.get("Error", {}).get("Code")
    704             error_class = self.exceptions.from_code(error_code)
--> 705             raise error_class(parsed_response, operation_name)
    706         else:
    707             return parsed_response

ClientError: An error occurred (ValidationException) when calling the CreateModel operation: Could not find model data at s3://<my-bucket>/sagemaker-rl-tensorflow-2021-06-15-06-05-55-347/output/model.tar.gz.

/sagemaker-rl-tensorflow-2021-06-15-06-05-55-347/output/ folder contains intermediate/ folder and output.tar.gz, but no model.tar.gz exists.
Why model artifacts are not saved during training?
How can I deploy my model to sagemeker endpoint?

A: you need your code to save a model in /opt/ml/model.
At the end of training, SageMaker checks this location and uploads its content to S3.

A: You should first check how many episodes that you're actually running. If your training printout doesn't contain any checkpoint logs that send to /opt/ml/model/data...etc... then your _save_tf_model function may not have any files to save. I had a similar issue where I only ran a single episode, and thus there were no checkpoints sending *.onnx files to my checkpoint directory.
Also, check line number 202 in your sagemaker_rl.coach_launcher.py file. In an older version I was using, it was missing the single line:
import tensorflow as tf


text:
Q: Can the behavior of the Firefox FIND be changed or augmented through an add-on? Can the behavior of the Firefox FIND (Ctrl + f) be changed or augmented through an add-on?
If it can not be changed, how can an add-on insert elements into the Find-bar so that it is activated at the same time as FIND with (Ctrl + f)?

A: It absolutely can be changed. You can hijack and edit the find jsm module.
Here's the module:
http://mxr.mozilla.org/mozilla-release/source/toolkit/modules/Finder.jsm#225
I'm not sure exactly how to edit a jsm already inserted though. Maybe unload it than re import it.


text:
Q: How to display a local image (saved on C disk) using Spring? So, I am currently developing a Spring web application that lets you upload an image (valid extensions are: .png, .jpeg, .jpg and .gif) from a form. The image is then saved on a disk and its relative path is stored in a database. I have successfully saved the image to a disk using this code:
@Override
public void saveThumbnail(MultipartFile thumbnailFile) throws Exception {
    String folder = "/bundles/";
    byte[] bytes = thumbnailFile.getBytes();
    Path path = Paths.get(folder + thumbnailFile.getOriginalFilename());
    Files.write(path, bytes);
}

The form looks like that

And here's the code that displays this form
                <form:form method="POST" modelAttribute="eventForm" class="form-signin" enctype="multipart/form-data">
                <spring:bind path="name">
                    Name

                        <form:input type="text" path="name" class="form-control" placeholder="Name"
                                    autofocus="true"></form:input>
                        <form:errors path="name"></form:errors>

                </spring:bind>

                <spring:bind path="price">
                    Price

                        <form:input type="number" path="price" class="form-control"></form:input>
                        <form:errors path="price"></form:errors>

                </spring:bind>

                <spring:bind path="thumbnailFile">
                    Thumbnail image

                        <c:if test="${eventForm.thumbnailUrl != null}">

                        </c:if>
                        <form:input type="file" path="thumbnailFile" class="form-control" name="thumbnailFile"/>
                        <form:errors path="thumbnailFile"></form:errors>

                </spring:bind>

                <spring:bind path="description">
                    Description

                        <form:textarea rows="4" path="description" class="form-control" placeholder="Description"/>
                        <form:errors path="description"></form:errors>

                </spring:bind>

                <button type="submit" class="btn-add-new">Save</button>
            </form:form>

I have already tried to display it like that:

However, my browser seems to block this action in order to prevent any security problems. I did some research and found out that you can let Apache serve files from a directory that it can access. Since I am new to web development, I have no idea how I would implement that even though I looked up a few articles and tutorials.
Thank you in advance.

A: your src should not be the location of the file in your server, the source should be the http link which will serve your resource.
you can either configure apache to map URL to resources from specific directory then mention the mapped URL + file name in src property
or you can create a controller which fetches the resource from the specific location and return it as byte stream and in src property set the link to your controller + file name

A: I have finally managed to display the image. If any one else is trying to do the same, I'd like to list the steps that I took. FYI, I was using Tomcat and MySQL database.

*

*Make sure that your image directory exists on your system and add an image into it.

*Create a new class named FileServlet and apply the following code into it.
@WebServlet("/images/*")
public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException
    {
        String filename = URLDecoder.decode(request.getPathInfo().substring(1), "UTF-8");
        File file = new File("C:\\your\\local\\image\\directory", filename);
        response.setHeader("Content-Type", getServletContext().getMimeType(filename));
        response.setHeader("Content-Length", String.valueOf(file.length()));
        response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
        Files.copy(file.toPath(), response.getOutputStream());
    }
}

*

*Now go to your main class and apply an annotation named @ServletComponentScan. Your main class should now look like that:

@SpringBootApplication
@ServletComponentScan
public class WebApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(WebApplication.class);
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(WebApplication.class, args);
    }

}

*

*In your .jsp file add this line wherever you'd like to display the image:

*

*Rebuild your web application and go to localhost:PORT/images/YOUR_FILE_NAME.EXTENSION
If you have any problems, feel free to comment on this answer and I'll update it if needed.

A: Assuming that you have Apache tomcat server . You will have to update the server.xml file.
add
<Context  docBase="C:\your\physical\path" path="/path/for/http/url" />

inside <Host></Host> tag . Doing so , you can access any file kept inside

"C:\your\physical\path"

from your web application with the help of URL :

"http://yourdomain/path/for/http/url/somefile.someextension"


text:
Q: Why do we need to put BindingResult immediate after ModelAttribute in spring From org.springframework.web.method.annotation.ModelAttributeMethodProcessor
/**
 * Whether to raise a {@link BindException} on validation errors.
 * @param binder the data binder used to perform data binding
 * @param parameter the method argument
 * @return {@code true} if the next method argument is not of type {@link Errors}.
 */
protected boolean isBindExceptionRequired(WebDataBinder binder, MethodParameter parameter) {
    int i = parameter.getParameterIndex();
    Class<?>[] paramTypes = parameter.getMethod().getParameterTypes();
    boolean hasBindingResult = (paramTypes.length > (i + 1) && Errors.class.isAssignableFrom(paramTypes[i + 1]));

    return !hasBindingResult;
}

From the code above we get the idea that while processing handler method argument spring raises Exception if the Error parameter is not immediate after the Model Attribute. Please share your thoughts and ideas.
Thanks in advance.


text:
Q: No route matches [Post] /characters/1/edit I am trying to reach the edit page for my character class, but for some reason it is routing with a POST when it should be a GET. All similar questions have not helped.
Here is my edit function:
def edit
end

Here are my routes:
<%= button_to 'Edit Character', edit_character_path(@character) %>

characters_path GET /characters(.:format)   characters#index
POST    /characters(.:format)   characters#create
new_character_path  GET /characters/new(.:format)   characters#new
edit_character_path GET /characters/:id/edit(.:format)  characters#edit
character_path  GET /characters/:id(.:format)   characters#show
PATCH   /characters/:id(.:format)   characters#update
PUT /characters/:id(.:format)   characters#update
DELETE  /characters/:id(.:format)   characters#destroy

here is my edit link:
<%= button_to 'Edit Character', edit_character_path(@character) %>

A: The problem is that button_to, acccording to documentation, generates a form, and the form method is post
Any reason for which you are ussing button_to ?
Otherwise you can just use a link_to and add a custom class:
<%= link_to 'Edit Character', edit_character_path(@character), class: 'my-custom-class' %>

so you can add the css for your custom class and make it look like a button


text:
Q: cisco openconnect disconnect every 5 minutes Recently I installed Ubuntu (Ubuntu 20.04.5 LTS) and I installed openconnect server I am faced with one problem. When I connect to my server with the cisco any connect app from my iphone or any connect software in windows 10 , my connection is disconnecting every 5 minutes.
Does anyone have a solution to how can I solve this issue?
I installed with below commands :

Build docker image:
docker build -t ocserv https://github.com/iw4p/OpenConnect-Cisco-AnyConnect-VPN-Server-OneKey-ocserv.git

Run docker container:
docker run --name ocserv --privileged -p 443:443 -p 443:443/udp -d ocserv


text:
Q: Object is not abstract and does not implement abstract member public abstract fun error in flutter with kotlin native code I'm trying to call a native kotlin code inside my flutter application .. am doing it this way
flutter side
class NativeLocationServices {
  static const currentLocationChannel = MethodChannel("com.deliveryrunner.driver/getCurrentLocation");

  getCurrentNativeLocation() async {
      // Either the permission was already granted before or the user just granted it.
      final arguments = {"test":"it is working"};
      final  currentLocation = await currentLocationChannel.invokeMethod("currentLocation",arguments);
      print(currentLocation);

    }
  }

kotlin side
package xxxxxx > here are my package name

import android.content.*
import io.flutter.embedding.android.FlutterActivity
import androidx.annotation.NonNull
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import android.content.Intent
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import android.location.Location

class MainActivity : FlutterActivity() {
    private val LOCATION_CHANNEL = "com.deliveryrunner.driver/getCurrentLocation";
    private lateinit var channel: MethodChannel
    private lateinit var fusedLocationClient: FusedLocationProviderClient
    override fun onCreate(savedInstanceState: Bundle) {
        GeneratedPluginRegistrant.registerWith(this)
        MethodChannel(flutterView, CHANNEL).setMethodCallHandler {
                call, result ->
            if (call.method == "currentLocation") {
                val arguments = call.arguments() as Map<String, String>
                val test = arguments["test"]
                fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
                fusedLocationClient.lastLocation
                    .addOnSuccessListener { location: Location? ->
                        // Got last known location. In some rare situations this can be null.
//                        result.success(location)
                        result.success("got the loation")
                    }
            }
        }
    }

but I am getting this error when I try to run the app
e: D:\Flutter\src\flutter\.pub-cache\hosted\pub.dartlang.org\workmanager-0.4.1\android\src\main\kotlin\be\tramckrijte\workmanager\BackgroundWorker.kt: (132, 21): Object is not abstract and does not implement abstract member public abstract fun error(p0: String, p1: String?, p2: Any?): Unit defined in io.flutter.plugin.common.MethodChannel.Result
e: D:\Flutter\src\flutter\.pub-cache\hosted\pub.dartlang.org\workmanager-0.4.1\android\src\main\kotlin\be\tramckrijte\workmanager\BackgroundWorker.kt: (137, 25): 'error' overrides nothing

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':workmanager:compileDebugKotlin'.
> Compilation error. See log for more details

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 14s
Exception: Gradle task assembleDebug failed with exit code 1


text:
Q: Create a new file in Filezilla folder? I can see a "New Folder" menu but no "New File".
Is this impossible or any Filezilla alternative that can do so?

A: I have not seen any FTP client that has this feature - your best bet is simply to create a temp folder somewhere on your machine and have a 0KB file (right click, New > Text File) and rename it to whatever you want. You can then upload this file to wherever you want and it basically will do the same job as a "New File"

A: I use Ubuntu but I guess this will work on windows as well.
In the bottom right of the screen where you see the directory listing, if you right click on any file, there is an option called create new file, which will serve the purpose!


text:
Q: How to append an array to another array, while keeping both arrays seperate from each other in Python I have 2 arrays: A and X. X is an array filled with other arrays. I do not have access to X, so I cannot change it in any way. I need A to be filled with certain arrays from X, but I need to maintain the individual nature of the arrays. The code I have thus far looks like this:
for i in range(len(X)):
    if X[i, split] <= n:
         A = np.append(A, X)

The issue with this is that, while it does successfully get only the values that I need from X into A, it makes every value a part of one large array, rather than retaining the separate arrays. I have attempted to utilize a matrix here, however, I run into an issue where X is recognized as merely a one dimensional array rather than two dimensional such as a matrix would be.
How might I go about getting the arrays from X into A while still keeping them separated into their own individual arrays? Thanks!
It is possible that I am not asking the right question, but my goal with asking this is to get a shape function run on A to return two values, such as (10, 4). Currently X does this, but once I append the arrays into A, I get only one value that appears like (40,), where it has taken all the correct values, but failed to separate them into their separate arrays.
--
The first few lines of X are displayed as such when printed out:
[[5.1 3.5 1.4 0.2]

 [4.9 3.  1.4 0.2]

 [4.7 3.2 1.3 0.2]...

When it is appended into A, it instead becomes this:
[5.1 3.5 1.4 0.2 4.9 3.  1.4 0.2 4.7 3.2 1.3 0.2 ...

A: Does this work as you expect it?
array2d = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

array = [[x for x in arr if (x % 2 == 0)] for arr in array2d]


text:
Q: PDF attachment corrupted After the issue with GmailApp declaratrion has benn resolved, I'm stuck now with a new problem, regarding my pdf attachment which is unreadable.
Prior to this bug, the pdf attachment was working perfectly.
I'm doubting that the var "blobresponse" or "pdfOpts" are the source of the problem, but maybe I'm wrong.
What's going wrong with the script ? Could you please explain me ?
Here is a reproducible example
function emailAsPDF() {

 SpreadsheetApp.flush();
 var ss = SpreadsheetApp.getActiveSpreadsheet();
 ss.setActiveSheet(ss.getSheetByName("Recherche"));
 var sheet = ss.getActiveSheet();
 var gid = sheet.getSheetId();
 var pdfOpts =
    'exportFormat=pdf&format=pdf'+ // export as pdf
    '&size=0' + // paper size letter / You can use A4 or legal
    '&portrait=false' + // orientation portal, use false for landscape
    '&fitw=true' + // fit to page width false, to get the actual size
    '&sheetnames=false&printtitle=true' + // hide optional headers and footers
    '&pagenumbers=true&gridlines=false' + // hide page numbers and gridlines
    '&horizontal_alignment=CENTER&vertical_alignment=CENTER' +
    '&fzr=true' + // do not repeat row headers (frozen rows) on each page
    '&attachment=false' +
    gid;
// '&size=0&fzr=true&portrait=false&fitw=true&gridlines=false&printtitle=true&sheetnames=false&pagenumbers=true&attachment=false&gid='+gid;

 SourceSS = SpreadsheetApp.getActive();
 var SourceSheet = SourceSS.getSheetByName("Recherche");
 var url = 'https://docs.google.com/spreadsheets/d/' + SourceSS.getId().replace(/edit$/, '') + '/export?exportformat=pdf&format=pdf' + pdfOpts;
 //var url = 'https://docs.google.com/spreadsheets/d/'.replace(/edit$/, '') + '/export?exportformat=pdf&format=pdf' + pdfOpts;
 var token = ScriptApp.getOAuthToken();
 //var options = {

//options = {muteHttpExceptions: true};
 //var options = {
  var blobresponse = UrlFetchApp.fetch(url, {
    headers: {
        'Authorization': 'Bearer ' +  token,
      },
      muteHttpExceptions: true}
    );
  //options);
  var CandidateName = ss.getRangeByName("Nom.Candidat").getValue();
  var blob=blobresponse.getBlob().setName(ss.getName() + " - " + CandidateName +".pdf" );
  var emailAddress = Session.getActiveUser().getEmail();
  var signature = Gmail.Users.Settings.SendAs.get("me", emailAddress).signature;
  var mess = "Voulez-vous envoyer votre rapport  à l'adresse : " + emailAddress;
  var ans= Browser.msgBox("Courriel", mess, Browser.Buttons.YES_NO);
  if (ans===Browser.Buttons.NO){return;}
  var mess="Votre rapport a été envoyé à l'adresse : " + emailAddress;
  //var ss=SpreadsheetApp.getActive();
  var sheet = ss.getSheetByName("Recherche");
  var data = ss.getSheetByName("Données");
  const corps = data.getRange("A24:E27").getValues();
  const htmlTemplate = HtmlService.createTemplateFromFile("HtmlSigTemplate");
  htmlTemplate.corps = corps;
  var emailSubject = "Vérifications pré-emploi complétées" +" - "+ CandidateName;
  const htmlForEmail = htmlTemplate.evaluate().getContent() + "--" + "<br>" + signature;
  //console.log(htmlForEmail);
  GmailApp.sendEmail(
    emailAddress,
    emailSubject,
    corps,
    {htmlBody: htmlForEmail,
    attachments:[blob]});
  Browser.msgBox("Courriel", mess, Browser.Buttons.OK);
}

function parentFolder() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var file = DriveApp.getFileById(ss.getId());
  var ParentFolder= file.getParents();
  while ( ParentFolder.hasNext() ) {
    var folder = ParentFolder.next();
    folderID=folder.getId();
     Logger.log(folderID);
  }
  return folderID;
}

A: I found the culprit after a long and painful research. You notice that the last line in the variable pdfOpts was missing a little detail
Old code:
var pdfOpts =
    'exportFormat=pdf&format=pdf'+ // export as pdf
    '&size=0' + // paper size letter / You can use A4 or legal
    '&portrait=false' + // orientation portal, use false for landscape
    '&fitw=true' + // fit to page width false, to get the actual size
    '&sheetnames=false&printtitle=true' + // hide optional headers and footers
    '&pagenumbers=true&gridlines=false' + // hide page numbers and gridlines
    '&horizontal_alignment=CENTER&vertical_alignment=CENTER' +
    '&fzr=true' + // do not repeat row headers (frozen rows) on each page
    '&attachment=false' +
    gid;

New code:
  const pdfOpts = '&top_margin=0.30&bottom_margin=0.30&left_margin=0.25&right_margin=0.25'
    +'&size=LETTER' // paper size letter / You can use A4 or legal
    +'&portrait=false' // orientation portal, use false for landscape
    +'&fitw=true' // fit to page width false, to get the actual size
    +'&sheetnames=false' // hide optional headers
    +'&printtitle=true' //and footers
    +'&pagenumbers=true' // hide page numbers
    +'&gridlines=false' //and gridlines
    +'&horizontal_alignment=CENTER'
    +'&vertical_alignment=CENTER'
    +'&fzr=true' // do not repeat row headers (frozen rows) on each page
    +'&attachment=false'
    +'&gid='+gid;

A: The code has several issues. I suggest you to start to cleaning up your script by removing the redundant statements and adopting better modern JavaScript practices. I.E.
Instead of var use const or let. Old Google Apps Script code used var all the time because const and let were not supported. The current Google Apps Script default runtime does it.
Related

*

*What's the difference between using "let" and "var"?

*v8 JavaScript performance implications of const, let, and var?
Instead of
ss.setActiveSheet(ss.getSheetByName("Recherche"));
 var sheet = ss.getActiveSheet();

use
 const sheet = ss.getSheetByName("Recherche");

Instead of
SourceSS = SpreadsheetApp.getActive();
 var SourceSheet = SourceSS.getSheetByName("Recherche");
 var url = 'https://docs.google.com/spreadsheets/d/' + SourceSS.getId().replace(/edit$/, '') + '/export?exportformat=pdf&format=pdf' + pdfOpts;

use
const url = 'https://docs.google.com/spreadsheets/d/' + ss.getId() + '/export?exportformat=pdf&format=pdf' + pdfOpts;

NOTES:

*

*getId() returns the spreadsheet id, it doesn't includes edit.

*It not necessary to declared new variables for the spreadsheet and sheet to be exported as PDF as the ones that were previously declared have the required objects.

Also you might find helpful to review previous questions related to the use of UrlFetchApp to create a PDF like the following:

*

*Generate PDF of only one sheet of my spreadsheet

*Exporting Google Sheet as PDF with Custom Headers or Footers in Google Apps Script

*Can no longer produce PDF from Google Sheets spreadsheet for some of the users


text:
Q: Remove text when cell size is too small in d3.js In the d3 treemap when a node has a very big value compared to others only the bigger node will be shown and others will not be visible or hidden. In some cases a small cell will be visible but the text margin will be cut off. How to remove the text when the cell is too small or make it responsive in d3 treemap.
My code is in the link https://codesandbox.io/s/d3-treemap-new-n8tix?file=/src/treegraph.js
My code
import React from "react";
import * as d3 from "d3";

class Treegraph extends React.Component {
  state = {
    width: 400,
    height: 400
  };
  createTreeChart = () => {
    var width = 100, // % units for CSS responsiveness
      height = 100,
      snap = snap || 0.0001,
      x = d3
        .scaleLinear()
        .domain([0, width])
        .range([0, width]),
      y = d3
        .scaleLinear()
        .domain([0, height])
        .range([0, height]),
      //blue = d3.hsl(216, 0.92, 0.68),,
      tile = (node, x0, y0, x1, y1) => {
        d3.treemapBinary(node, 0, 0, width, height);
        for (const child of node.children) {
          child.x0 = x0 + (child.x0 / width) * (x1 - x0);
          child.x1 = x0 + (child.x1 / width) * (x1 - x0);
          child.y0 = y0 + (child.y0 / height) * (y1 - y0);
          child.y1 = y0 + (child.y1 / height) * (y1 - y0);
        }
      },
      treemap = d3
        .treemap()
        .size([width, height])
        .tile(tile)
        .paddingInner(0)
        .round(false),
      data = {
        name: "SEGMENTS",
        columnName: "A",
        children: [
          {
            name: "A1 - subsection of a",
            columnName: "A",
            value: 2100,
            children: [
              {
                name: "B1 - subsection of b",
                columnName: "B",
                value: 520,
                children: [
                  {
                    name: "C1  - subsection of C",
                    columnName: "C",
                    value: 85248197
                  }
                ]
              },
              {
                name: "B2 - subsection of b",
                columnName: "B",
                value: 500,
                children: [
                  {
                    name: "C1 - subsection of c",
                    columnName: "C",
                    value: 500
                  }
                ]
              }
            ]
          },
          {
            name: "A2 - subsection of a",
            columnName: "A",
            value: 2000,
            children: [
              {
                name: "B1 - subsection of a",
                columnName: "B",
                value: 1500,
                children: [
                  {
                    name: "C1 - subsection of a",
                    columnName: "C",
                    value: 1248197
                  }
                ]
              },
              {
                name: "B2 - subsection of a",
                columnName: "B",
                value: 500,
                children: [
                  {
                    name: "C1 - subsection of a",
                    columnName: "C",
                    value: 500
                  }
                ]
              }
            ]
          }
        ]
      },
      pathNames = [],
      nodes = d3
        .hierarchy(data)
        .sum(d => {
          return !d.children && d.value;
        })
        .sort((a, b) => !a.children && a.value - !b.children && b.value),
      resizeTimer,
      currentDepth;

    treemap(nodes);

    var chart = d3.select("#chart");
    var cells = chart
      .selectAll(".node")
      .data(nodes.descendants())
      .enter()
      .append("div")
      .attr("class", function(d) {
        // console.log("The d.depth function", d);
        return "node level-" + d.depth;
      })
      .attr("zndex", function(d) {
        // console.log("The d.depth function", d);
        return 110 - d.depth;
      })
      .attr("title", function(d) {
        return d.data.name ? `${d.data.name} (${d.data.value})` : "null";
      });

    cells
      //.style("transform", function(d) { return "translateY(" + chart.node().clientHeight * y(d.y0) / 100 + ")"; })
      .style("left", function(d) {
        //console.log( x(d.x0) + " => " + nearest(x(d.x0), snap) );
        return nearest(x(d.x0), snap) + "%";
      })
      .style("top", function(d) {
        // console.log(y(d.y0) + " => " + nearest(y(d.y0), snap));
        return nearest(y(d.y0), snap) + "%";
      })
      .style("width", function(d) {
        return nearest(x(d.x1) - x(d.x0), snap) + "%";
      })
      .style("height", function(d) {
        // console.log(
        //   y(d.y1) - y(d.y0) + " => " + nearest(y(d.y1) - y(d.y0), snap)
        // );
        return nearest(y(d.y1) - y(d.y0), snap) + "%";
      })
      .style("z-index", function(d) {
        // dynamic zindex for each node levels
        return d.data.name !== "SEGMENTS" && 110 - d.depth;
      })
      //.style("background-image", function(d) { return d.value ? imgUrl + d.value : ""; })
      .style("background-color", function(d) {
        return "orange";
      })
      .on("click", zoom);

    cells
      .append("p")
      .attr("class", "label")
      .text(function(d) {
        return d.data.name ? d.data.name : "null";
      })
      .attr("text-anchor", "middle");
    var parent = d3
      .select(".logo")
      .datum(nodes)
      .on("click", zoom);

    // can't resquarify as we use 100*100% treemap size. Doh!
    d3.select(window).on("resize", function() {
      clearTimeout(resizeTimer);
      resizeTimer = setTimeout(redraw, 250);
    });

    showPath(nodes.ancestors());

    function zoom(d) {
      // http://jsfiddle.net/ramnathv/amszcymq/

      // console.log("clicked: " + d.data.name + ", depth: " + d.depth);

      showPath(d.ancestors());

      currentDepth = d.depth;
      parent.datum(d.parent || nodes);

      x.domain([d.x0, d.x1]);
      y.domain([d.y0, d.y1]);

      var t = d3
        .transition()
        .duration(800)
        .ease(d3.easeCubicOut);

      cells
        .transition(t)
        .style("left", function(d) {
          return nearest(x(d.x0), snap) + "%";
        })
        .style("top", function(d) {
          return nearest(y(d.y0), snap) + "%";
        })
        .style("width", function(d) {
          return nearest(x(d.x1) - x(d.x0), snap) + "%";
        })
        .style("height", function(d) {
          return nearest(y(d.y1) - y(d.y0), snap) + "%";
        });

      cells // hide this depth and above
        .filter(function(d) {
          return d.ancestors();
        })
        .classed("hide", function(d) {
          return d.children ? true : false;
        });

      cells // show this depth + 1 and below
        .filter(function(d) {
          return d.depth > currentDepth;
        })
        .classed("hide", false);

      // if currentDepth == 3 show prev/next buttons
    }

    function redraw() {
      // console.log("window resized");

      treemap(nodes); //?
      //cells
      //    .datum(nodes)
      //    .call(zoom);
    }

    function showPath(p) {
      console.log("THE PATH", p);
      var path = d3
        .select(".breadcrumb")
        .selectAll("a")
        .data(
          p
            .map(function(d) {
              console.log("LOG the MAP FUNC", d);
              return d;
            })
            .reverse()
        );
      var path1 = d3
        .select(".breadcrumb")
        .selectAll("span")
        .data(
          p
            .map(function(d) {
              console.log("LOG the MAP FUNC", d);
              return d;
            })
            .reverse()
        );
      path.exit().remove();
      path1.exit().remove();

      console.log("THE PATHNAMES LOG", pathNames);
      path1
        .enter()
        .append("span")
        .attr("class", "activeNode")
        .html(function(d) {
          console.log("the d in second html", d);
          if (d.data.name !== "SEGMENTS" && d.data.children) {
            return ` <div> ${d.data.name} </div> <p class="right-symbol">></p>`;
          }
          if (!d.data.children) {
            return `<div > ${d.data.name} </div>`;
          }
        });
      path
        .enter()
        .append("a")
        .attr("href", "#")
        .html(function(d) {
          console.log("the d in html", d.data.columnName);
          return d.data.children && `${d.data.children[0].columnName} /`;
        })
        .on("click", zoom);
    }

    function nearest(x, n) {
      return n * Math.round(x / n);
    }
  };
  componentDidMount() {
    this.createTreeChart();
  }
  render() {
    return (
      <React.Fragment>

          {/*

 */}

      </React.Fragment>
    );
  }
}

export default Treegraph;

A: const containerHeight = d3
   .select(".feature")
   .node()
   .getBoundingClientRect().height;

const containerWidth = d3
   .select(".feature")
   .node()
   .getBoundingClientRect().width;

const allLabels = d3.selectAll(".label").nodes();

d3.selectAll(".label").style("display", (d, idx) => {
   const { width, height } = allLabels[idx].getBoundingClientRect();

   const parentWidth = (d.x1 - d.x0) * containerWidth / 100.0;
   const parentHeight = (d.y1 - d.y0) * containerHeight / 100.0;

   if (width > parentWidth || height > parentHeight) return "none";
   return "";
});


text:
Q: How do I match a list with a dict and time related values? I got this in my views.py:
# Get the amount of kilo attached to products
product_data = {}
for product in ProductSpy.objects.all():
    product_data[product.id] = {"product_id": product.product_id, "kilo": product.kilo}

# Get quantity bought of each product
total_qty_bought = self.order_item_model.objects.values("product").annotate(Sum("quantity"))

So in my product_data dump I got this here:
6: {'product_id': 32, 'kilo': Decimal('25.00')},

and in my total_qty_bought dump I got this:
{'product': 32, 'quantity__sum': Decimal('5')},

Now as the product_id match the product, I want it to return 125, as we got 5 times the quantity of 25 kilo.
In my total_qty_bought dump you'd find id's not relevant, so if they dont match any in my product_data dump, I want them ignored.
What is the smartest way to achieve this?
print dump:
product_data:
{4: {'product_id': 30, 'kilo': Decimal('25.00')}, 5: {'product_id': 31, 'kilo': Decimal('25.00')}, 6: {'product_id': 32, 'kilo': Decimal('25.00')}, 7: {'product_id': 33, 'kilo': Decimal('25.00')}, 8: {'product_id': 37, 'kilo': Decimal('15.00')}, 9: {'product_id': 38, 'kilo': Decimal('15.00')}, 10: {'product_id': 39, 'kilo': Decimal('10.00')}, 11: {'product_id': 40, 'kilo': Decimal('10.00')}, 12: {'product_id': 41, 'kilo': Decimal('5.00')}, 13: {'product_id': 42, 'kilo': Decimal('2.50')}, 14: {'product_id': 43, 'kilo': Decimal('5.00')}, 15: {'product_id': 44, 'kilo': Decimal('2.50')}, 17: {'product_id': 50, 'kilo': Decimal('2.50')}, 18: {'product_id': 51, 'kilo': Decimal('5.00')}, 19: {'product_id': 52, 'kilo': Decimal('10.00')}, 20: {'product_id': 53, 'kilo': Decimal('15.00')}, 21: {'product_id': 55, 'kilo': Decimal('15.00')}, 22: {'product_id': 56, 'kilo': Decimal('10.00')}, 23: {'product_id': 57, 'kilo': Decimal('5.00')}, 24: {'product_id': 58, 'kilo': Decimal('2.50')}}

total_qty_bought:
<QuerySet [{'product': 42, 'quantity__sum': Decimal('5')}, {'product': 41, 'quantity__sum': Decimal('3')}, {'product': 51, 'quantity__sum': Decimal('13')}, {'product': 50, 'quantity__sum': Decimal('34')}, {'product': 49, 'quantity__sum': Decimal('1')}, {'product': 40, 'quantity__sum': Decimal('2')}, {'product': 43, 'quantity__sum': Decimal('10')}, {'product': 52, 'quantity__sum': Decimal('12')}, {'product': 32, 'quantity__sum': Decimal('5')}, {'product': 53, 'quantity__sum': Decimal('2')}, {'product': 38, 'quantity__sum': Decimal('1')}, {'product': 55, 'quantity__sum': Decimal('1')}, {'product': 56, 'quantity__sum': Decimal('10')}, {'product': 58, 'quantity__sum': Decimal('60')}, {'product': 44, 'quantity__sum': Decimal('16')}, {'product': 57, 'quantity__sum': Decimal('28')}]>

A:     product_data = {}
    for product in ProductSpy.objects.all():
        product_data[product.product_id] = product.kilo

    # Get quantity bought of each product
    total_qty_bought = self.order_item_model.objects.values("product").annotate(Sum("quantity"))

    our_total = {}
    for qty in total_qty_bought:
        product_id = qty['product']
        quantity = int(qty["quantity__sum"])
        try:
            kilos = quantity * product_data[product_id]
            our_total[product_id] = kilos
            print(f"Product_id: {product_id} - Kilos: {kilos}")
        except KeyError:
            print(f"Product_id {product_id} not found in product_data!")

Here's the solution.


text:
Q: Unable to access existing fields in JSON object, keep getting undefined I have a function in AWS Lambda in which I retrieve an unparsed JSON object, I parse it, and then access its values.
if(data.Payload){

            var parsedData = JSON.parse(data.Payload)
            console.log("PAYLOAD  --> " + parsedData);
            console.log("GROUPNAME --> " + parseData.groupName);
...

When I log to the console the parsedData variable, it seems like the parsing was successful:
PAYLOAD  --> {"groupName":"Hello!","membersCount":1,"searchField":"hello!"}

The issue arises when I try to access the fields in the JSON as I keep getting undefined:
GROUPNAME --> undefined

NOTE:
If I copy and paste the JSON object
{"groupName":"Hello!","membersCount":1,"searchField":"hello!"}

into a variable on the Chrome debugging console
var parsedData = {"groupName":"Hello!","membersCount":1,"searchField":"hello!"}

I am able to access the properties of the object as I am trying to do in the AWS Lambda function.
parsedData.groupName prints "Hello!"

Edit - temporary solution
The parsedData variable contains a String with a JSON, so the JSON object inside the "" I am not quite sure why. The temporary fix was to double parse the variable but that just seems wrong.
if(data.Payload){
            var parsedData = JSON.parse(data.Payload);
            var doubleParsed = JSON.parse(parsedData);
            if(doubleParsed.groupName !== undefined) {
                console.log(doubleParsed.groupName);
            }
          }

A: If that is a copy paste of your code, in your 2nd console.log you are using parseData NOT parsedData missing a D.
EDIT Just adding as answer what I wrote in comments.
It seems parsedData was not being parsed correctly, for some reason JSON.parse is not working, I think some information about data.Payload is needed to know what it exactly returns.
Yet the next code seems to solve it, but I would honestly need further explanation as why it needs to be done twice:
var parsedData = JSON.parse(JSON.parse(data.Payload));


text:
Q: Filling any empty cells with the value above I want to fill in all empty cells using values of above cells
state  name
IL     Mike
       Sam
CA     Kate
       Bill
       Leah

Should be as follows
   state  name
    IL     Mike
    IL     Sam
    CA     Kate
    CA     Bill
    CA     Leah

I tried the following
Sub split()
Dim columnValues  As Range, i As Long

Set columnValues = Selection.Area

Set i = 1
For i = 1 To columnValues.Rows.Count
    If (columnValues(i) = "") Then
    columnValues(i) = columnValues(i - 1)
    End If
Next

End Sub

I get an error when I set i. How can I modify my code

A: Given you asked for VBA, there is a quicker way than looping (the VBA equivalent of what pnuts posed above, with the additional step of removing the formula at the end):
On Error Resume Next
With Selection.SpecialCells(xlCellTypeBlanks)
.FormulaR1C1 = "=R[-1]C"
.Value = .Value
End With

A: It is because i should be defined as i=1. There are although a few other problems with the code. I would change it to something like this:
Sub split()
    Dim columnValues  As Range, i As Long

    Set columnValues = Selection

    For i = 1 To columnValues.Rows.Count
        If columnValues.Cells(i, 1).Value = "" Then
            columnValues.Cells(i, 1).Value = columnValues.Cells(i - 1, 1).Value
        End If
    Next
End Sub

A: For those not requiring VBA for this, select ColumnA, Go To Special..., Blanks and:
Equals (=), Up (▲), Ctrl+Enter
should give the same result.

A:  Sub fill_blanks()
 Dim i As Long
 i = 2 ' i<>1 because your first raw has headings "state " "name"
 'Assume state is in your cell A and name is in your cell B
 Do Until Range("B" & i) = ""
 Range("B" & i).Select
 If ActiveCell.FormulaR1C1 <> "" Then
    Range("A" & i).Select
      If ActiveCell.FormulaR1C1 = "" Then
           Range("A" & i - 1).Copy
           Range("A" & i).PasteSpecial Paste:=xlPasteValues
           Else
           i = i + 1
      End If
    Else
    i = i + 1
  End If
  Loop

End Sub

A: For some cause the method used on post https://stackoverflow.com/a/20439428/2684623 not work for me. When the line .value=.value is executed, I get the error 'not available' (#N/D for local language) in the value of cells. Version of Office is 365.

I dont know the reason however with some modifications runs fine:
Sub TLD_FillinBlanks()

    On Error Resume Next
    With ActiveSheet.UsedRange.Columns(1)
        If .Rows(1) = "" Then .Rows(1).Value = "'"
        .SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "=R[-1]C"
        .Value = .Value
    End With
End Sub

Using loops:
Sub TLD_FillinBlanksLoop()
    Dim rCell As Range

    For Each rCell In ActiveSheet.UsedRange.Columns(1).Cells
        If rCell.Value = "" And rCell.Row > 1 Then
            rCell.FillDown
        End If
    Next

End Sub

I hope that can be useful for somebody. Thanks and regards.

A: Here is the whole module, I pasted the formulas as values at the end.
Sub FillBlanksValueAbove()
Dim sName As String
sName = ActiveSheet.Name
Dim ws As Worksheet
Dim lastRow As Long, lastCol As Long
Dim rng As Range

'Set variable ws Active Sheet name
Set ws = Sheets(sName)

    With ws
    'Get the last row and last column
    lastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    lastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
    'Set the range
    Set rng = .Range(.Cells(1, 1), .Cells(lastRow, lastCol))
    rng.Select
    'Select Blanks
    rng.SpecialCells(xlCellTypeBlanks).Select
    'Fill Blanks with value above
    Selection.FormulaR1C1 = "=R[-1]C"
    'Paste Formulas as Values
    rng.Select
    Selection.Copy
    Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
    xlNone, SkipBlanks:=False, Transpose:=False

    End With
End Sub


text:
Q: How to handle binary data in the browser when using byte range requests to server I'm experimenting with controlled file requests. The browser will use byte-range requests to fetch pieces of large files from the server. This could be a video file or a large data file of some sort. I've been able to set up a simple fetch using the request module to fetch a range of data.
request({
    url: 'http://localhost:8080' + file.path,
    headers: {
        'Range' : 'bytes=0-50'
    }
}, function (err, res, body) {
    console.log('err: ', err);
    console.log('status: ', res.statusCode);
    console.log('body: ', body);
});

And this produces the following output:
err:  null
status:  206
body:  ftypisomisomavc1.��moovlmvhdК{�К{

So, I'm getting the data, however I'm unsure of the best way to handle this binary data and preserve it's integrity. Specifically:

*

*Loading it in as binary data, so I can continue to piece together the chunks and eventually provide a downloadable file to the user.

*Performing some type of checksum or integrity check on the incoming data (assuming I could get an md5 of each chunk, perhaps as a prefetched list).

A: It turns out the issue was due to the fact that I was using the request module, which does not interface with the native browser XMLHttpRequest API, and therefor cannot request binary data. I made a simple little request function which wraps the XMLHttpRequest API and gives me back binary data (blob).
function request (url, _opt, cb) {
    var xhr = new XMLHttpRequest();
    var opt = {
        method: 'GET'
    };
    if (typeof _opt === 'function') {
        cb = _opt;
    } else {
        opt = _opt;
    }
    opt.method = (opt.method) ? opt.method : 'GET';
    xhr.open(opt.method, url, true);
    xhr.responseType = 'blob';

    if (typeof opt.headers === 'object') {
        var keys = Object.keys(opt.headers);
        for (var i = 0, len = keys.length; i < len; i += 1) {
            xhr.setRequestHeader(keys[i], opt.headers[keys[i]]);
        }
    }

    xhr.onload = function (e) {
        if ((this.status >= 200) && (this.status < 299)) {
            // get binary data as a response
            cb(null, this, this.response);
        } else {
            cb('received error code: ' + this.status, this);
        }
    };

    xhr.send();
}

and can use it like this:
request(file.path, {
    headers: {
        'Range' : file.range
    }
}, function (err, res, body) {
    if (err) { throw new Error(err) ; }
    var contentType = res.getResponseHeader ("Content-Type");
    cb(contentType, body);
});


text:
Q: Ubuntu 18.04.3 - when trying to uninstall mongodb says that it doesn't exist, when trying to install says it exists I have been working on this and read a lot of articles. I am trying to get this working on my test server hosted by digital ocean. for some reason, out of seemingly nowhere the my server couldn't connect to Mongodb, so since it's a testing and after exhausting those resources I decided to delete and reinstall, However, whenever trying to remove mongodb it says that it doesn't exist: after running $ sudo apt-get purge mongodb mongodb-server mongodb-server-core mongodb-clients
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package 'mongodb' is not installed, so not removed
Package 'mongodb-clients' is not installed, so not removed
You might want to run 'apt --fix-broken install' to correct these.
The following packages have unmet dependencies:
 mongodb-org : Depends: mongodb-org-server but it is not going to be installed
               Depends: mongodb-org-mongos but it is not going to be installed
               Depends: mongodb-org-tools but it is not going to be installed
E: Unmet dependencies. Try 'apt --fix-broken install' with no packages (or specify a solution).

so it says that it doesn't exist so after $ sudo apt-get install mongodb-org I get:
Reading package lists... Done
Building dependency tree
Reading state information... Done
mongodb-org is already the newest version (3.6.17).
You might want to run 'apt --fix-broken install' to correct these.
The following packages have unmet dependencies:
 mongodb-org : Depends: mongodb-org-server but it is not going to be installed
               Depends: mongodb-org-mongos but it is not going to be installed
               Depends: mongodb-org-tools but it is not going to be installed
E: Unmet dependencies. Try 'apt --fix-broken install' with no packages (or specify a solution).

I tried in both cases to do the apt --fix-broken install but to no avail.
when typing $ mongo I get
MongoDB shell version v3.6.17
connecting to: mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb
2020-03-31T18:26:22.472+0000 W NETWORK  [thread1] Failed to connect to 127.0.0.1:27017, in(checking socket for error after poll), reason: Connection refused
2020-03-31T18:26:22.472+0000 E QUERY    [thread1] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed :
connect@src/mongo/shell/mongo.js:263:13
@(connect):1:6
exception: connect failed

I read about unmasking, enabling, or any type of mongodb interactivity I get:
2020-03-31T18:26:22.472+0000: command not found
-bash: connect@src/mongo/shell/mongo.js:263:13: No such file or directory
@(connect):1:6: command not found
exception:: command not found
-bash: root@ubuntu-s-1vcpu-1gb-fra1-01:/home/name#: No such file or directory

I am performing all the same actions that previously did to access the db.... no clue WHAT happened.... thank you guys.

A: It seems that you've messed up your repositories by adding additional mongodb-org repository.
Try to comment out it's source in /etc/apt/sources.list.d/mongodb-org-4.2.list or similar file.
Then do sudo apt update && sudo apt install -f
Then try again: sudo apt install mongodb and so on.


text:
Q: event to check if the contents of iframe are completely loaded in Ext JS I want to perform few operations after the loading of iframe is completed.
I have tried by adding the afterrender event listener, but after render event fires when the window is opened not when the content is fully loaded.
new window.Ext.create('Ext.window.Window', {
            title: 'Popup',
            height: 630,
            width: 1050,
            modal: true,
            layout: 'fit',
            closeAction: 'close',
            items: [
                {
                    xtype: "component",
                    autoEl: {
                        tag: "iframe",
                        frameborder: 0,
                        src: "http://www.yahoo.com"

                    },
                    id: "frametoShow"
                }
            ]
        });

Is there any event which fires when the content of the frame is fully loaded ?
I'd also go with jQuery solution as well.
Any help would be appreciated.

A: Yes, you will need to add afterrender listener but also get the element on load like this:
items: [
    {
        xtype: "component",
        autoEl: {
            tag: "iframe",
            frameborder: 0,
            src: "http://www.yahoo.com"

        },
        listeners: {
            afterrender: function () {
                console.log('rendered');

                this.getEl().on('load', function () {
                    console.log('loaded');
                });
            }
        },
        id: "frametoShow"
    }
]


text:
Q: reversed expression in bsearch block not working ary = [1, 4, 6, 9]
(0...ary.size).bsearch { |i|
  ary[i] - 1
}                                   # => nil

1 - ary[i]                          # => 0

When the code is written in a form ary[i] - 1 which doesn't work as expected.
What I am trying to do is to find the index of the number 1 in the array.
But 1 - ary[i] can return the number's index correctly. Why doesn't ary[i] - 1 work?

A: Array#bsearch is meant to perform binary search to find an element that meets certain criteria. As per documentation, if you return numeric values from the block, the find-any mode type of search is used.
The search starts at center of the sorted array - and if block returns negative value, it continues search in first half, and if block returns positive value, it continues the search in second half of the array.
In your case when you use ary[i] - 1, the value returned by block is always positive and search continues recursively on second half of the array - and never finds the value 1.
Here is the code with some debug statements:
ary = [1, 4, 6, 9]
p (0...ary.size).bsearch { |i|
  puts "Elem: #{ary[i]} Index: #{i}"
  ary[i] - 1
}

Output:
Elem: 4 Index: 1
Elem: 6 Index: 2
Elem: 9 Index: 3
nil
[Finished in 0.4s]

A: Array#bsearch returns an element of the array, not the index of a matching element.
You might want to use Array#index instead.

A: If you want to find the index of the element instead of the element itself, you need to use Array#bsearch_index. Note: this method was introduced in Ruby 2.3, which at the time of this writing has not been released yet (it will be released on Christmas 2015).
The feature request for Array#bsearch_index contains a comment by Yusuke Endoh showing how to implement Array#bsearch_index (and in fact Array#bsearch as well) based on Range#bsearch:
class Array
  def bsearch_index(&blk)
    return enum_for(__method__) unless blk
    (0...size).bsearch {|i| yield self[i] }
  end
end

When either running Ruby 2.3 or using the above monkey patch, you can then do:
ary.bsearch_index(&1.method(:-))

in order to find the index of the 1 element in your array.
The reason why it doesn't work with
ary.bsearch_index {|el | el - 1 }

is simple: the block violates the contract of bsearch_index (and also bsearch since they are the same). The block needs to return a positive number for indices left of the one you are searching for, a negative number for indices right of the one you are searching for, and 0 for indices within the range you are searching for. Your block does the opposite.


text:
Q: can't access backend while frontend works perfect Before 2 days there was a automatic update for wordpress, which I for my website.
When the update was over, I tried to access backend but I always get this message:
Fatal error: Call to undefined function wp_is_mobile() in /home/*******/public_html/wp-login.php on line 67

Can you give me any idea what to do, how to fix this. Thanks

A: /!\ Before change I suggest, please make a full backup (code + database) of your Wordpress.

*

*Deactivate all plugins.

If it does not help try next

*

*Re-upload all files and folders (except the wp-content folder) from a fresh download of WordPress.

A: You're not the first one to get this error. Similar problems have been reported here and on Wordpress.org
And the answer from the Wordpress.org link is:

Try:
  - switching to the Twenty Eleven theme by renaming your current theme's folder inside wp-content/themes and adding "-old" to the end
  of the folder name using FTP or whatever file management application
  your host provides.

*

*resetting the plugins folder by FTP or phpMyAdmin.

*re-uploading all files & folders - except the wp-content folder - from a fresh download of WordPress.

*running the upgrade manually via wp-admin/upgrade.php

A: It probably means that the automatic update process wasn't successful (even though, WordPress might have showed you a different message).
As Maxim already mentioned, I'd recommend to re-install WordPress manually.


text:
Q: Enable full screen using seesaw? How can I make my seesaw program full screen when F11 is pressed? (not just maximized)
I currently have this:
(defn toggle-full-screen [e]
  (-> (to-root e)
    magic!)

(def full-screen-action  (action  :name "Full Screen" :tip "Full Screen"
                                  :mnemonic \f        :key (keystroke "F11")
                                  :handler toggle-full-screen))
(def view-menu (menu  :text "View"
                      :mnemonic \v
                      :items [full-screen-action]))

(def top-menubar (menubar :items [view-menu]))
[...]

toggle-full-screen runs when F11 is pressed however I can't figure out how to make the frame fullscreen.

A: Caveat scriptor, I haven't tried this in seesaw but I think this is mostly about directly leveraging what is available in swing.
The following suggests what can be done with the swing API:
http://weblogs.java.net/blog/mkarg/archive/2010/01/03/fullscreen-mode-cool
Also:
http://docs.oracle.com/javase/tutorial/extra/fullscreen/index.html
At least part of the trick is to call setUndecorated on the frame.
I haven't investigated how you get at the necessary swing objects within seesaw yet.


text:
Q: How to "wrap" rows and column indicies around? I want to be able to "wrap" around the matrix when it reaches the end of the matrix, row, and column-wise.
My current code reads a matrix from a file and finds all the '.' into a list of row coordinates and column coordinates.
I want to check the neighboring indices to see if they are 'O'.
for x in range(0, len(row_dead)):
    if (content_matrix[row_dead[x] - 1][column_dead[x]]) == 'O':  # above
        count += 1
    if (content_matrix[row_dead[x] + 1][column_dead[x]]) == 'O':  # below
        count += 1
    if (content_matrix[row_dead[x]][column_dead[x] + 1]) == 'O':  # right
        count += 1
    if (content_matrix[row_dead[x]][column_dead[x] - 1]) == 'O':  # left
        count += 1
    if (content_matrix[row_dead[x] - 1][column_dead[x] + 1]) == 'O':  # up_right
        count += 1
    if (content_matrix[row_dead[x] - 1][column_dead[x] - 1]) == 'O':  # up_left
        count += 1
    if (content_matrix[row_dead[x] + 1][column_dead[x] + 1]) == 'O':  # bot_right
        count += 1
    if (content_matrix[row_dead[x] + 1][column_dead[x] - 1]) == 'O':  # bot_left
        count += 1

The code I have works fine when the '.' is not bordering the perimeter of the matrix. However, if there is a '.' on the perimeter of the matrix, I get an index out of range error.
I do have a solution in my head and it's to hard code every indices along the parameter to "wrap" around to certain indices, but I feel like that way is too primitive and I feel like there's a way to properly wrap around the indices mathematically.

A: Use the modulus operator to wrap your subscript around either end.  I'll use shorter variable names: given a 2D structure grid with indices row and col:
grid[ (col+1) % len(grid) ]
       [ (row-1) % len(grid[0]) ]

This assumes that len(grid[0]) gives you the column quantity (row length) for any column -- otherwise, you'd have to specify the same index you used for the col.
For instance, give a 5x5 grid, 4+1 % 5 will return 0; 0-1 % 5 will return 4.
Does that get you going?

A: Use try/except statements
There should be smarter and more pythonic ways to do this but this should work:
for x in range(0, len(row_dead)):
    xx = row_dead[x]
    yy = column_dead[x]
    for ox, oy in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]:
        try:
            count += content_matrix[xx+ox][yy+oy] == 'O'  # Ugly but works
        except IndexError:
            pass


text:
Q: displaying images on crystalreport This is my code,i want display images that stored in sql to crystal reports,please someone help me :)
private void button2_Click(object sender, EventArgs e)
                {
                    string connectionstring = null;
                    SqlConnection conn;
                    connectionstring="Server=AJITHBABU\\SQLEXPRESS;Initial Catalog=temprorary;User ID=sa;Password=2604";
                        conn=new SqlConnection(connectionstring);
                        byte[] img = null;
                        FileStream fs = new FileStream(imgloc, FileMode.Open, FileAccess.Read);
                        BinaryReader br = new BinaryReader(fs);
                        img = br.ReadBytes((int)fs.Length);
                        k = "INSERT INTO temprorary4(id,img)values('" + textBox1.Text + "',@img)";
                        conn.Open();
                        cmd = new SqlCommand(k, conn);
                    cmd.Parameters.Add(new SqlParameter("@img",img));
                    int x=cmd.ExecuteNonQuery();
                    conn.Close();
                    MessageBox.Show(x.ToString() +"record(s) saved");

                }


text:
Q: xml values are not inserting into the table Here is my code:
ALTER PROCEDURE sp_Insertxmldata
    @xml xml
AS
BEGIN
    declare @hdoc as int

    EXEC sp_xml_preparedocument @hdoc output,@xml

    Insert into tbllogin([user_name],mobile,[Password])
    select [USER_NAME],mobile,[password]
    FROM openxml(@hdoc, '/NewDataSet/table', 2)
    with
    (
        [user_name] varchar(50)'@username',
        mobile varchar(50) '@mobile',
        [password] varchar(15) '@password'
    )

    EXEC sp_xml_removedocument @hdoc

END
GO

The xml is:
<NewDataSet>
  <Table1>
    <user_name></user_name>
    <password></password>
    <mobile></mobile>
  </Table1>
</NewDataSet>

A: As you are using the XML datatype, you must be using SQL Server 2005 or above. Therefore you can use the methods of the XML datatype (eg .nodes, .value, .query) to read the XML. For such a small piece of XML performance is likely to be the same or better than OPENXML, eg
DECLARE @xml XML

SET @xml = '<NewDataSet>
  <Table1>
    <user_name></user_name>
    <password></password>
    <mobile></mobile>
  </Table1>
</NewDataSet>'

--INSERT INTO ...
SELECT
    t.c.value('(user_name/text())[1]', 'VARCHAR(50)' ),
    t.c.value('(mobile/text())[1]', 'VARCHAR(50)' ),
    t.c.value('(password/text())[1]', 'VARCHAR(15)' )
FROM @xml.nodes('NewDataSet/Table1') t(c)

Remember when dealing with XML, things are generally case-sensitive, so I'm using 'Table1' rather than 'table' as per your original post.


text:
Q: Storing a timestamp with a custom timezone I have to store an "event time" that could be in any timezone. By default rails stores these in the DB as UTC and strips off our custom timezone. When we read the attribute back it is converted to our application's timezone - we lose the original timezone information.
We're working around this by storing the timestamp (as UTC) and an offset (an integer number of seconds) which is fine, but I'd really love to be able to store this as just one column and have rails use that rather than converting to UTC on write and to the application's timezone on read.
Is having rails store the timestamp in non-UTC just for this one field just not possible?


text:
Q: Is it possible to use matlab tables in mex code? I would like to manipulate a matlab table (http://se.mathworks.com/help/matlab/tables.html) inside mex code. Is that possible?
For example to manipulate an array in mex code one would call:
mxArray * matlabArray = prhs[0] ;// if matlabArray was the first argument to the mex function;

Can one do something like
mxTable * matlabTable  = prhs[0] ; //mxTable does not actually exist... but I would like it to:)

and pass a table as the first argument?

A: prhs is an array of mxArray pointers, so your first line of code is correct.
Use mxIsClass (https://www.mathworks.com/help/matlab/apiref/mxisclass.html) to determine if the input array is of type table:
if (mxIsClass(prhs[0],"table") { ... }

To access properties of the table, use the mxGetProperty (https://www.mathworks.com/help/matlab/apiref/mxgetproperty.html) function:
mxArray* data = mxGetProperty(prhs[0],0,"ColumnName");

This is equivalent to the MATLAB command table.ColumnName. data should then by a normal double matrix. Unfortunately, this syntax creates a copy of the data. There are no documented ways of accessing data inside of (non-standard) objects without making copies. For undocumented ways, see: http://www.advanpix.com/2013/07/19/undocumented-mex-api/

A: It is currently not possible to access a Matlab table in a mex function based upon the following:

*

*You can do a Ctrl+F on the Matlab C/C++, Fortran and Python API Reference for table and come up with only references to tables in the text. I would take this as evidence that there is no mxTable type provided.

*The table type in Matlab is implemented as a Matlab class. You can actually see all of the source code for tables by simply typing edit table in the command window. This is not true for numeric arrays or cell arrays.
This doesn't appear to be an omission in mex support though since the main advantage of tables is that they organize data well. If you have computational requirements that would push you towards writing a mex function, you'll probably be working with numeric arrays in Matlab already.


text:
Q: Problems with SaveAsync task in DynamoDB for C# I'm trying to save my administrator class object to DynamoDB using Context.SaveAsync method:
// Save admin to DynamoDB.
context.SaveAsync(admin,(result)=>{
  if (result.Exception == null)
  {
    Console.WriteLine("admin saved");
  }
});

but it keeps bothering me with following error:
cannot convert `lambda expression' to non-delegate type `system.threading.cancellationtoken'

How do I handle this issue ?. I'm using Xamarin Studio for OS X

A: According to the documentation, DynamoDBContext.SaveAsync takes a type T, and a CancellationToken. It does not take any form of delegate type, at all.
What you want is to do is:
public async Task SaveAsync<T>(T entity, CancellationToken ct)
{
     await context.SaveAsync<T>(entity, ct);
     Console.WriteLine("entity saved");
}


text:
Q: Number of unique CIELab colors in an image I have an image represented in the CIELab color space. How can I return the number of unique CIELab colors the image contains?
Thanks.

A: You can use unique(...,'rows'):
n = size(unique(reshape(img, [], 3)),1);


text:
Q: Counting steps and O-notation How many steps do these two methods each have and how do I count them when I'm going for the worst case in both methods? I have read tons of articles on how to calculate the O-notation (smallest O-Notation amount in this case), but have no idea how it works. I get what the programms do but can someone help me with counting its steps and calculating the O-Notation in the worst case?
static int methode1(int[] arr) {
    int min = 100;
    int minidx = 0;
    for(int i = 0; i<arr.length; i++) {
        if(arr[i]<min) {
            minidx = i;
        }
    }
    return minidx;
}

static int methode2(int n) {
    int count = 2;
    for(int i = 1; i<=n; i++) {
        for(int j=n; j>i; j--) {
            count++;
        }
    }
    return count;
}

A: *

*Method 1

if I denote the length of the array (the number of elements in it) with n,
this loop will do n iterations. At every iteration an "if" is executed and sometimes an assignment. In any case there'll be an addition to get to the next item in the table. So we have something like 2-3 operations per element. The complexity is O(n). (Which means that there exists a natural number p, such that the number of operations is smaller than p * n, for all n. In our case, something like p = 5 would definitely work).
edit: To clarify the idea a little more: this is like in every iteration there's exactly 1 complex operation that consumes at most p time units.
O(n) means that the algorithm will execute at most n of these complex operations. Hence, the running time of the algorithm only depends on n.

*Method 2

In this case you have one loop counting from 1 to n. These are n operations. For each of this steps you have another loop counting from n to 1, which are also n operations. Within the second loop there's only an increment operation.
So we have n * n increment operations within the inner loop, n * n decrement operations to do the inner loop, and another n increment operations to do the outer loop. This makes a complexity of O(n^2).

A: First of all there are no worst cases to consider for both of your methods, since there are no conditional exit in both of them.
Next, first one, while you seeking for them minimal element in the array (which most likely not ordered) you have to literally consider checking each one of the elements to find the minimal one, hence complexity will be O(n).
Regarding second one, you have two nested loops, for first iteration of the outer loop you are doing n iteration within inner, for second you are doing n - 1, and etc... E.g.
n, n - 1, n - 2, ..., 1
which turns to be arithmetic series and sums up to n*(n+1)/2, in in big-O notation is O(n^2).

A: It would be methode1 - O(arr.length), methode2 - O(n^2).
You have for loops inside the methods. You can count (calculate) the number of times the code inside the loops executes. In the second case there's a loop nested inside another loop. In cases like that, the number of executions equals the number of executions in the first loop, times the number of executions in the second loop.


text:
Q: Cloning tr to add new item and replacing a select box I Had a code where i had to clone the respected tr and create the new one, but the tr has the column which has a select and that selection has one value which when chosen converts the select box into the textbox and then whe i click add item, it adds another text text, i knowwhy it is hapening, because i am just cloning it.
how can i fix it, i am bit confused
here is my code

<input type="text">

              Item(s)

                <select name="get_Items" id="get_Items" class="selectItemsList" data-rule-required="true" data-msg-required="Choose Item">
                  <option></option>
                </select>

                <select name="getSelection" class="form-control getSelectedprice">
                    <optgroup label="Class Price">

                        <option value="160.0000">$160.00</option>

                    </optgroup>

                    <optgroup label="Custom Price">
                        <option value="0">$0</option>
                        <option value="-2">My Price</option>
                        <option value="-1">Custom Price</option>
                    </optgroup>
                </select>

                <input type="text" name="getSelection" value="" class="form-control">

Add Item

    $('.createNewItemTag').click(function(){
        var obj = $(this).parents('tr').first();
        var clonedObj = $(obj[0].outerHTML);
        clonedObj.find(".select2-container").remove();
        clonedObj.find('.createNewItemTag').remove();
        clonedObj.find('td').last().append("Remove");
        clonedObj.find(".removeItem").click(function(){
            $(this).parents('tr').first().remove();
        });
        obj.before(clonedObj);
        initSelect2ForNextItem(clonedObj.find(".selectItemsList").first());
    });

    $(document).on('change','.getSelectedprice',function() {
        if ($('.getSelectedprice option:selected').text() == "Custom Price"){
            $('.moveboxleft').hide();
            $('.moveboxleftinput').show();
        }else {
            $('.moveboxleft').show();
            $('.moveboxleftinput').hide();
        }
    });

A: Your HTML is invalid. For example, you haven't closed the first div in your first td tag:

            Item(s)

Try correcting your HTML and re-evaluate your code, then resubmit if you are still having problems.

A: You do have some improperly nested HTML that should be fixed.
But as for the cloning. My advice is to never clone an item after it has been instrumented with any event handlers or other plugins (like Select2). The way to avoid that is to do the following:

*

*Clone the row right away at page load (before registering event handlers and instrumenting).

*Whenever you need a new row, clone the original clone. That way you still have the original clone to re-clone over and over.

*Use event delegation as much as possible to register event handlers.

*If you need to instrument any of the elements on a newly added row, do it after you have inserted it into the page.

In your case, you could have this:
var $table = $('table');

var $CLONED_ROW = $table.find('tbody>tr:first').clone();
$CLONED_ROW.find('.createNewItemTag').replaceWith(
    'Remove');

$table.on('click', '.createNewItemTag', function(e) {
    e.preventDefault();
    var $row = $(this).closest('tr'),
        $newRow = $CLONED_ROW.clone();
    $newRow.insertBefore($row);
    //initSelect2ForNextItem($newRow.find('.selectItemsList'));
});

$table.on('click', '.removeItem', function(e) {
    e.preventDefault();
    $(this).closest('tr').remove();
});

$table.on('change', '.getSelectedprice', function() {
    var $select = $(this),
        $row = $select.closest('tr');
    if ($select.val() == '-1') {
        $row.find('.moveboxleft').hide();
        $row.find('.moveboxleftinput').show();
    } else {
        $row.find('.moveboxleft').show();
        $row.find('.moveboxleftinput').hide();
    }
});

//initSelect2ForNextItem($table.find('.selectItemsList'));

Notice the placement of the calls to initSelect2ForNextItem().
jsfiddle
A few more things:

*

*You can use .closest(), instead of .parents().first().

*When you hide/show the text input, you need to limit it to the current row.

*It is better to use the value of a select element, rather than the text.


text:
Q: .Net Core MVC notyf (notification) pop-up I want to show notyf message just using c#. I cant see notification message because of return view(). How can I show?
My codes like that.
        try
        {
            if (entity == null)
            {
                notyf.Warning("Entity null");
                return View();
            }

            categoryService.Insert(entity);
            notyf.Success("WellDone.");

            return RedirectToAction("ListCategory");
        }
        catch (Exception ex)
        {
            notyf.Error("serviceError" + ex.Message, 12);
            return View();
        }

A: You can read the readme in this link. I follow the steps and it works for me.
ToastNotification - Elegant Notifications For ASP.NET Core Applications
My test sample code:


text:
Q: Hichcharts- hidden series does not show again after updating plots twice I have done something like:

*

*Have a check box to change the plot's data

*when the check box is checked/unchecked, update the series data array by calling series[i].update() accordingly.

But I have a problem that when a series is hidden by the user and try to check the checkbox and then uncheck, followed by reshow the series, the series does not show again.
Please note that If I only check the box once, no problem occurs, there will be problem only when we check the box more than once after we hide the series.
I have reproduce the problem HERE (JSFiddle)
The code to update the plot is :
if (chart) {
    for (var i = 0; i < chart.series.length; i++) {
        //chart.series[i].setVisible(true, true); // Note that if I add this code, then no problem
        chart.series[i].update({
            data: dataArray[i]
        });
    }
}

A: The problem is that you base on Highcharts generated points. When series is hidden, then points don't exist and you set empty data for a series. In other words it looks like this: chart.series[i].setData( [] );.
I suggest to use separate arrays for data and use those for your calculations. General idea: http://jsfiddle.net/pGuEv/37/ (I know, it works a bit different, but shows how should be written)
var origData = [
    [11, 22, 33, 44, 55, 66, 77, 88],
    [10, 20, 30, 40, 50, 60, 70, 80]
];
$('#container').highcharts({
    series: [{
        data: origData[0].slice()
    }, {
        data: origData[1].slice()
    }]
});

And later:
        for (var i = 0; i < origData.length; i++) {        // original data
            var onePlotData = [];
            var sum = 0; //前面点的合计值s
            for (var j = 0; j < origData[i].length; j++) { // original data
                var value = origData[i][j];                // original data
                var point = {
                    //x: value.x,
                    y: state ? value + sum : value - sum,
                    //total: value.total
                }
                sum = point.y;
                onePlotData.push(point);
            }
            dataArray.push(onePlotData);
        }


text:
Q: Riak is creating siblings of expired keys in bitcask bucket types I have a Riak server using multi backend storage with the following configuration:
...
storage_backend = multi
multi_backend.bitcask_mult.storage_backend = bitcask
multi_backend.bitcask_mult.bitcask.expiry = 10s
...

I have checked that the following sequence of steps works correctly.

*

*Put a new value with key key-1.

*Get the value with key key-1 returns the expected value.

*Wait 15 seconds.

*Try to get the value with key-1. This returns nothing, as the key has expired.

So far so good.
However, if now I put the value with the same key again...

*Put a new value with key key-1

*Get the value with key-1 returns two siblings!

I have waited for hours between steps #4 and #5 (just in case the expiration had to be flushed or something like that), with no luck.
I can address this situation handling the siblings, which is something that I do anyway for some other buckets I work with, but I wasn't expecting to have to deal with "expired siblings"!
I have read something about automatic expiration and Riak Search but I don't think this is the case.
Am I doing something wrong? Am I missing something?
Thanks.

A: Void, expiration is working but you are running into a problem I will call "Expiration <> Delete". When an object expires in Bitcask a tombstone is created by Bitcask and the backend returns not_found to any requests for that object BUT the object isn't deleted. The object gets "deleted" when the oldest object in the Bitcask data file expires and the whole file is expired. At that point a new file is created.
Until a new file is created in Bitcask the object actually still exists even though Bitcask is returning not_found. When you write to "deleted" key the Bitcask the last-modified time is getting updated essentially resurrecting it.
To test this theory you can actually stop Riak and restart it. Restarting Riak will cause Bitcask to create a new data file and will keep you from getting siblings.
Long story short you still need to deal with siblings in this case.


text:
Q: What statistics can be used for correlating gene expression on a specific organ with its function My hypothesis is that a gene whose function is related to an organ will have higher gene expression in that organ compared to other organs.
An example of my hypothesis:
From a published literature, it is evident that gene x is function in liver lipid metabolism. So, as per my hypothesis, the expression of gene x would be higher in liver compared to other tissues or organs as,
genes       Kidney  Brain   Heart   Liver   Pancreas    Cornea
gene a      3.09    3.27    4.29    3.4       4.97       3.91
gene x      4.38    4.49    3.4     12.84     4.87       6.21
gene k      4.77    4.34    3.68    4.64      4.90       5.95
gene m      6.27    5.82    4.84    7.41      6.57       6.13
.
.
gene 20000  5.21   3.70     8.21    8.01      7.11       4.87

I have checked a few genes with reported organ related function and its level of gene expression in all organs. Most of the gene expression pattern justified my hypothesis.
What I have is
1) Normalized gene expression micro-array data for 20000 genes from 15 different organs as similar to the example above
2) A set of 35 genes for which function is identified in specific organs (based on literature published data).
I would like to know how can I apply statistics to test my hypothesis?

A: Unfortunately the most common test here is the dirty fold-change cutoffs.
gene x      4.38    4.49    3.4     12.84     4.87       6.21

For this gene, your Liver has 12.84 and your second largest is 6.21. Your log2 ratio will be log2(12.84/6.21).
Compare this cutoff with your preferred thresholds, very common in bioinformatics.


text:
Q: Find a Link in PHP String and convert it into a Hyperlink? Find a Link in PHP String and convert it into a Hyperlink so it becomes Clickable and opens in New Tab.
PHP Code / String:
<?php echo $post_details['description']; ?>

Test Link:
http://www.test.com

A: use this library. it automatically detect link from the string and make it clickable. you don't need to create a link just add a string having a link. this library will detect it automatically.
http://soapbox.github.io/jQuery-linkify/

A: Use this example to solve your problem
<?php

function makeClickableLink($text) {
    $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '\\1', $text);
    $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '\\1\\2', $text);
    $text = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})', '\\1', $text);
    return $text;
}

// Usage

// Email address example
$text = "you@example.com";
echo makeClickableLink($text);

// URL example
$text = "http://www.example.com";
echo makeClickableLink($text);

// FTP URL example
$text = "ftp://ftp.example.com";
echo makeClickableLink($text);

?>


text:
Q: Weird session_start() error (key cannot be empty) for a specific client I can't reproduce One specific user has been experiencing difficulties logging in to my site. He's getting the following error: session_start(): Key cannot be empty.
I have no idea what this error means, and haven't been able to identify why this happens only for a specific user. My session saving is handled through memcache.
What does the error mean? What can cause it only in a very specific case?

A: This can often mean you're outputting something before the session_start, which shouldn't happen.
It could be a third party extension interfering with your page loading, I'd recommend the usual steps of use an incognito / private session, to see if problem persists. If not, it's a problem with his setup.
EDIT: However, this appears to be an existing bug...


text:
Q: Decoding video directly into a texture in separate thread Is it possible to decode video using ffmpeg capabilities directly into texture asynchroniously? I need to output the video onto a geometry.
There is mpv video player, which can output video directly into framebuffer and uses other close to metal features, but is there minimalistic example, which suitable for embedded devices (OpenGL ES 2.0 or 3.0)?
It would be nice if texture won't leave GPU memory during whole the frame time.

A: I currently use sws_scale to trim the edges off mpegts streams frames as some frames will have 16 or even 32 extra pixels at the edge used when decoding. This isn't necessary for most uses. Instead I use it to copy direct into my own buffers.
ff->scale_context = sws_getContext(wid, hgt, ff->vid_ctx->pix_fmt,  // usually YUV420
                               wid, hgt, AV_PIX_FMT_YUV420P,        // trim edges and copy
                               SWS_FAST_BILINEAR, NULL, NULL, NULL);

// setup my buffer to copy the frame into

uint8_t *data[] = { vframe->yframe, vframe->uframe, vframe->vframe };
int linesize[4] = { vid_ctx->width, vid_ctx->width / 2, vid_ctx->width / 2, 0 };

int ret = sws_scale(scale_context,
          (const uint8_t **)frame->data, frame->linesize,
          0, vid_ctx->height,
          data, linesize);

You will need to adjust if the frames are in another format.
The GPU shader for openGL ES used which saves on a lot of overhead:
// YUV shader (converts YUV planes to RGB on the fly)

static char vertexYUV[] = "attribute vec4 qt_Vertex; \
attribute vec2 qt_InUVCoords; \
varying vec2 qt_TexCoord0; \
 \
void main(void) \
{ \
    gl_Position = qt_Vertex; \
    gl_Position.z = 0.0;\
    qt_TexCoord0 = qt_InUVCoords; \
} \
";

static char fragmentYUV[] = "precision mediump float; \
uniform sampler2D qt_TextureY; \
uniform sampler2D qt_TextureU; \
uniform sampler2D qt_TextureV; \
varying vec2 qt_TexCoord0; \
void main(void) \
{ \
    float y = texture2D(qt_TextureY, qt_TexCoord0).r; \
    float u = texture2D(qt_TextureU, qt_TexCoord0).r - 0.5; \
    float v = texture2D(qt_TextureV, qt_TexCoord0).r - 0.5; \
    gl_FragColor = vec4( y + 1.403 * v, \
                         y - 0.344 * u - 0.714 * v, \
                         y + 1.770 * u, 1.0); \
}";

If using NV12 format instead of YUV420 then the UV frames are interleaved and you just fetch the values using either "r, g" or "x, y" which ever swizzle you use.
Each YUV frame from your buffer is uploaded to "qt_TextureY, U and V".
As mentioned in the comments, FFMpegs build will automatically use HW decoding.
Also, to shave on CPU overhead I separate all decoding streams into their own threads.
Good luck. Anything else, just ask.