text:
Q: swift multipart post with 2 or more base64encoded image in json param fails Well, the request holds many params and one of them is a json string.
The problem: if the json param has more than 1 image in it (as shown below), the server side received post simply does NOT have it (the json param is not there in the post). Nevertheles, the rest of the params in the post are there in good shape (not shown in this example).
json parameter debugged:
THIS WORKS:
[{"title":"A","image":""},
{"title":"B","image":"HERE BASE64ENCODED IMAGE"}]

THIS WORKS TOO:
[{"title":"A","image":""},[{"title":"B","image":""},
{"title":"C","image":"HERE BASE64ENCODED IMAGE"}]

And these are the json params content that will be ignored in the server received post (each post has only one json param):
DONT WORK:
[{"title":"A","image":""},
{"title":"B","image":"HERE BASE64ENCODED IMAGE"},
{"title":"C","image":"HERE BASE64ENCODED IMAGE"}]

DONT WORK ALSO:
[{"title":"A","image":"HERE BASE64ENCODED IMAGE"},
{"title":"B","image":"HERE BASE64ENCODED IMAGE"}]

Every image is at most 900kb.(in my debug they maked in total 1.3MB)
EDIT: here the request:
let url:NSURL = NSURL(string: url)!
var request = URLRequest(url: url as URL)
request.httpMethod = "POST"
request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringCacheData
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

My doubts are focused in the multipart-form body, here the code i am dealing with so far:
var body = Data()
for (key, value) in parameters {
    body.append("--\(boundary)\r\n")
    body.append("Content-Disposition: form-data; name=\"\(key)\"")
    if key == "json" {
        body.append("\r\n")
        body.append("Content-Type: text/json")
    }
    body.append("\r\n\r\n")
    body.append("\(value)\r\n")
}
body.append("--\(boundary)--\r\n")
return body

EDIT 2: (following Dale's comment) This didnt fix it also.
    body.append("--\(boundary)")
    body.append("\r\n")
    body.append("Content-Disposition: form-data; name=\"params\"\r\n")
    body.append("Content-Type: multipart/mixed; boundary=\(boundary2)")
    body.append("\r\n\r\n")

    for (key, value) in parameters {
        body.append("--\(boundary2)")
        body.append("\r\n")
        body.append("Content-Disposition: form-data; name=\"\(key)\"")
        body.append("\r\n\r\n")
        body.append("\(value)\r\n")
    }

    body.append("--\(boundary2)--\r\n")
    body.append("--\(boundary)--\r\n")

EDIT 3: How the json param is constructed (@OOPer):
let image = UIImage(contentsOfFile: self.getPath() // String extension
let data = UIImageJPEGRepresentation(image, 0.4)
let strBase64 = data.base64EncodedString()
var post1 = [String:Any]
post1["title"] = "AA"
post1["image"] = "\(strBase64)"

let aPosts = [[String: Any]]()
aPosts.append(post1)
aPosts.append(post2)... etc

// later on
let data = try JSONSerialization.data(withJSONObject: aPosts)
let jsonParam = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
let param["json"] = jsonParam

let parameters = [String : String]()
parameters.update(other: param)

thx


text:
Q: How to order results by closest match to query? I have a field where I'm using Jquery TokenInput to autocomplete a Product. To find the products I'm doing:
def token
   @products = Product.order(:name)
   respond_to do |format|
     format.html
     format.json { render json: @products.where("name ILIKE ?", "%#{params[:q]}%").limit(10).order('name DESC') }
   end
end

If I have a product named Rice and do a search on the field, typing in "r", "ri",  and "ric", I want the closest result to be the one that matches the query. Instead though, if I have over 10 different types of Rices in the database, the results will be "out of order" with Rice being placed around 6th or 9th place out of 10 founded rices. To me, Rice should come first and than Rice Ball or Cake but instead I get something like:
Brown Rice # First result in Tokeninput
Rice Cake
Yellow Rice
Long Grain Rice
Rice Ball
Chinese Rice
Super Rice
Rice
New Rice
The Super Rice Game

Even if I type in "Rice" exactly I get something similar to the above. I want it to be the 1st choice if r, ri, ric or rice is typed in but my results don't believe in order, they only want chaos. How would this be done?

A: You may add the following method to your Product model:
def self.good_search(criteria)
  regexp = /#{criteria}/i; # case-insensitive regexp based on your string

  result = order(:name).where("name ILIKE ?", "%#{criteria}%").limit(10)
  result.sort{|x, y| (x =~ regexp) <=> (y =~ regexp) }
end

Here I use the match operator (=~) which returns position where regexp matched. The earlier the "rice" met the closer to the top of result array string'll be.
This method might not be good for big arrays, but for 10 elements it's okay.
And here's your controller:
def token
  respond_to do |format|
    format.html
    format.json { render json: Product.good_search(params[:q]) }
  end
end

Good luck!

A: Full Text Search
We've done something like this - you're looking for full text search
We've done something similar to what you're seeking at http://firststopcosmeticshop.co.uk -- the way we've done it is like this:
#config/routes.rb
match 'search(/:search)', :to => 'products#search', :as => :search, via: [:get, :post]

#app/controllers/products_controller.rb
def search
    @products = Product.search(params[:search])
    respond_to do |format|
        format.js   { render :partial => "elements/livesearch", :locals => {:search => @products, :query => params[:search]} }
        format.html { render :index }
    end
end

#app/models/product.rb
def self.search(search)
 basic_search(name: search, description: search).take(5) #-> uses textacular gem
end

This uses the textactular gem for PGSQL, but hopefully gives you some idea as to how to load perform the search

Code
For you, I would recommend performing your search like this:
def token
   @products = Product.where(name: "%#{params[:q]}%").order(name: :desc)
   respond_to do |format|
     format.html
     format.json { render json: @products.to_json }
   end
end

Although this won't answer your question directly, I hope it will give you some information on efficiency etc

A: I solved my search with this query and I think that you can use it as well and would make your search results much better. Given a query string as input I used the following sql:
select items.*
from items
where lower(items.name) like 'query%' or items.name like '% query%'
order by case when lower(items.name) like 'query%' then 1 else 2 end,
items.name ASC

this will return all the items which have at least one work matching the result ordered with the ones which starts the match first.
In Rails this would be something like:
Item.where("lower(items.name) like '#{downcase_query}%' or
            lower(items.name) like '% #{downcase_query}%'").
     order("case when lower(items.name) like '#{downcase_query}%' then 1 else 2 end,
            items.name ASC")

A: In general, the key in ruby to sort something is by using either .sort or .sort_by
For instance, an example is this:
%w{ banana apple pear fig }.sort_by {|word| word.length} # => ["fig", "pear", "apple", "banana"]
Now in your example, you need to specify which criterium you wish to use.
Given that you want to return Rice first, and then Rice Ball, I would suggest to add a sorting method that preferrentially returns Rice first, then works on the remaining results.

redpajama_set_name: RedPajamaStackExchange


text:
Q: auto generate CRUD view in angular 5 Is there any framework could help to generate CRUD crud view files form table in DB using MVC project but the front-end is angular?
Sorry. I had googling for some hours . But still cant find the solution.
All I found is manual creating the controllers/Models/Views(Angular files (services-components-models)
Nothing ease these steps and generate the view.
Thanks

A: I never tried out ng-momentum but you should give it a try as there is a crud part (but you need to create the project with it).

A: It is always not the best practice to generate CRUD views from a relational schema, unless you just want to build a toy app for demo purpose.
However, there is a way to simplify the building of CRUD apps. Please check the project: Json-on-relations


text:
Q: Minimal instalation CentOS USB modem LTE internet doesn't work I am using a Huawei USB stick. Unfortunately I cannot connect to the Internet. It's a problem somewhere in DHCP, I guess, but I don't know.
Could somebody help me?

A: Looks like NetworkManager is trying to operate the LTE modem like a generic wired NIC, and trying to request an IP address by DhCP immediately.
But a LTE modem needs a bit more preparation than that: it may need to be told to connect to a particular network, and maybe fed a PIN number to unlock the (U)SIM card, if applicable. All these things can be handled by ModemManager, that works as an add-on to NetworkManager.
You don't seem to have ModemManager installed: it covers various 3G/LTE modems and the various vendor-specific control protocols they use. Install it, then use mmcli -L to verify the modem is detected. The detection and initialization of the modem can take a moment or two.


text:
Q: Adding new attribute and using it in a rails form I've added a new column to my Supplier model of 'source' and 'source_other'. The form I've set up for new suppliers, however, isn't correctly taking this attribute and adding it to the model
The migration looks like:
class AddNewColumnToOwner < ActiveRecord::Migration
  def change
     add_column :owners, :source, :string
     add_column :owners, :source_other, :string
  end
end

And I know the migration has worked because I can see in my rails console that owners do have source and source_other listed as attributes.
Then, I've added it to the new owner form views/owners/new.html.haml:
.field{style: 'padding-bottom:0px;' }
        = f.input :source, as: :select, collection: HOW_HEAR, label: 'How did you hear about us?', allow_blank: false
      .field#other_source_field
        = f.input :source_other, input_html: { class: 'text_field' }, label: 'If other please let us know where you heard about us'

However, when I fill out the form to add a new owner and select one of the source options, it's not storing this in the table. I know this because when I check Owner.last in my rails console, I can see that source is 'nil', even though I selected an option for source in the form dropdown options.
I must be missing something but I'm not sure where I'm going wrong...?

A: You must have forgotten to permit those additional fields' params in your controller.


text:
Q: react router hosting with sub folders issues I am using react router with my application and everything works fine locally. Below is my code. The issue is when I host it online it is in a my-application subdirectory:

https://www.example.com/my-application

This is breaking the code and it is not functioning as it should.
can anyone advise how to fix this issue? If there is anything unclear please feel free to ask. I have tried countless approaches but cannot get it to work. One answer can be seen here.
the issue I am getting is that with the current code it navigates to https://www.example.com/test as opposed to https://www.example.com/my-application/test. I thought if I hardcoded in the url it would work but this also breaks the application.
The code below is slightly whittled down to remove superfluous code.
import React, { Component } from 'react';
import styled from 'styled-components'
import { Route, Switch } from 'react-router-dom'

const Home = ({ avatarUrl }) => {
  return (

         <Route exact path="/" component={Overview}/>
         <Route path="/test" component={Test}/>

  );
};

class App extends Component {

  render() {

    return (

        <Switch>
          <Route path="/example" component={Example}/>
          <Route path="/" render={()=><Home
            avatarUrl={ avatarUrl }
          />}/>

        </Switch>

    )
  }
}

export default App

A: Apply config changes pacakage.json add homepage page as your folder name

A: To solve this I just did two things:

*

*Added "hostname": "https://www.example.com/my-application" at the top of package.json.

*Added basename="my-application" to the BrowserRouter e.g. <BrowserRouter basename="my-application">
Note: I created the project using create-react-app. I am using react version 18 and react-router version 6.


text:
Q: VBA code to fetch data from Mysql DB in Mac Excel 2011 I was using ADODB code in Windows to fetch data from Mysql Database and it was working fine. However, I can not seem to get my Excel workbook (using ADODB) to work with Excel Mac 2011.  After a lot of googling, I found an ODBC connector from Actual tech and I was able to fetch  three rows using Microsoft Query. But I want this to be done using VBA code but have been unable to do so. Has anyone gotten this to work? If yes, can you please provide me with a sample code. Thanks in Advance !!
P.S: I know there is a similar existing question but the link provided in the answer is no longer working. hence, I have asked a new question
Also, If anyone needs the link to do it through Microsoft Query, here is the link:
http://www.agentjim.com/MVP/Excel/2011Relational7Queries.html
Here is the code I use in Windows:
  Sub getMysqlDBdata()

  Dim Cn As Object
  Dim sqlQa as string
  dim temparray1 as variant

  Source = "MySQL"

  mysql_driver = "MySQL ODBC 5.2 ANSI Driver"

  sqlQa = "select * from test.TestTable;"

  Set Cn = CreateObject("ADODB.Connection")
  Set rs = CreateObject("ADODB.Recordset")
  Cn.Open "Driver={" & "MySQL ODBC 5.2 ANSI Driver" & "};Server=" & "127.0.01" & ";Database= test;UID=" & "root" & ";PWD=" & "12345"

  rs.Open sqlQa, Cn, adOpenStatic
  temparray1 = rs.GetRows()
  rs.Close

  Set rs = Nothing

  End Sub

A: After a lot of googling I came across this sample code provided by Bryan Duchesne in MSDN:
Sub TestSqlConnection()
Dim sqlstring As String
Dim connstring As String
Dim sLogin As String
sLogon = "Uid=myUserID;Pwd=myPassowrkd;"
sqlstring = "select * from zitemloc"
connstring = "ODBC;DSN=myDSN;" & sLogon
ActiveSheet.Range("B1:t2000").Clear

Dim qt As QueryTable
For Each qt In ActiveSheet.QueryTables
    qt.Delete
Next qt
With ActiveSheet.QueryTables.Add(Connection:=connstring, Destination:=Range("B1"),   Sql:=sqlstring)
    .BackgroundQuery = False
    .Refresh
End With

Set qt = ActiveSheet.QueryTables(1)
Dim rowCount As Integer
rowCount = UBound(qt.ResultRange.Value)

Dim ix, iy As Integer
Dim data As Variant
Dim colCount As Integer
colCount = qt.ResultRange.Columns.Count

For ix = 1 To rowCount
    If Not IsArray(data) Then
            ReDim data(rowCount - 1, colCount - 1)
    End If
    For iy = 1 To qt.ResultRange.Columns.Count
        data(ix - 1, iy - 1) = qt.ResultRange.Value2(ix, iy)

    Next
Next
End Sub


text:
Q: How can I extract image tag from a string using jQuery? I have string like this:
var p = ' Online free quiz';

I need to extract this:

How might I achieve this?

A: Try this regex:
<[^>]+>

and a sample code:
match = inputString.match(/<[^>]+>/);
if (match != null) {
    matchedText = match[0];
} else {
    // Match attempt failed
}

explanation:

[abc] Character groups match any single character inside the group, this will match a single a, b or c.
[^abc] When the first symbol inside a character group is ^, it is negated. This will match any character except a, b or c.

A: On this specific string, you can do this :
var extracted = p.match(/<[^>]+>/)[0]

But in more general cases, regular expressions fast appear as very limited to handle HTML.

A: I always use jQuery to do that. It's simple.
var str = ' Online free quiz';
var imgs = $("
" +str +"
").find("img");


text:
Q: Cannot add local jar files in maven project I'm trying to repackage log4j so I can use it with Android. In order to do so, I have to use openbeans library and replace each java.beans with com.googlecode.openbeans.
Obviously this is not sufficient, since before repacking the through maven log4j I've to include openbeans-1.0.jar in the project.
So I've found this method.
I've installed openbeans through the following command:
mvn install:install-file -Dfile=/home/luca/openbeans-1.0.jar -DgroupId=com.googlecode -DartifactId=openbeans -Dversion=1.0 -Dpackaging=jar -DgeneratePom=true

I've checked that the correct execution of the command checking if the .jar exists in the following path (and it does):
~/.m2/repository/com/googlecode/openbeans/1.0/openbeans-1.0.jar
Then I edited the pom.xml file adding:
<dependency>
  <groupId>com.googlecode</groupId>
  <artifactId>openbeans</artifactId>
  <version>1.0</version>
</dependency>

But if I try mvn package then this error is returned:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-antrun-plugin:1.2:run (rmdir_tests_output) on project log4j: Execution rmdir_tests_output of goal org.apache.maven.plugins:maven-antrun-plugin:1.2:run failed: Plugin org.apache.maven.plugins:maven-antrun-plugin:1.2 or one of its dependencies could not be resolved: Failure to find com.googlecode:openbeans:jar:1.0 in http://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced -> [Help 1]

Like the install-file didn't worked.
I've tried also with this method, using the following code (obviously I copied the .jar in the project root dir):
<dependency>
  <groupId>com.googlecode</groupId>
  <artifactId>openbeans</artifactId>
  <version>1.0</version>
  <scope>system</scope>
  <systemPath>${project.basedir}/openbeans-1.0.jar</systemPath>
</dependency>

And here the error returned is:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.1:compile (default-compile) on project log4j: Compilation failure
[ERROR] /home/luca/apache-log4j-1.2.17/src/main/java/org/apache/log4j/config/PropertyGetter.java:[31,21] error: package com.googlecode does not exist

What is wrong in what I'm doing?

A: Even if I still don't understand why, I found out that executing:
mvn install:install-file -Dfile=/home/luca/openbeans-1.0.jar -DgroupId=com.googlecode.openbeans -DartifactId=openbeans -Dversion=1.0 -Dpackaging=jar -DgeneratePom=true

And using in pom:
<dependency>
  <groupId>com.googlecode.openbeans</groupId>
  <artifactId>openbeans</artifactId>
  <version>1.0</version>
</dependency>

The code is compiled without error. But as I said, still wondering why.


text:
Q: open dialog dynamically from href I am trying to open a dialog from an anchor tag.
my html is:

    <title>show dynamic dialog box in jquery</title>
    <link href="style/jquery-ui.css" rel="stylesheet" type="text/css"/>

<input id="Button1" type="button" value="Save" /> // this works!
// this is the line I want to use

my_script.js is:
$(document).ready(function(){
$(function() {
        $("input:button").click(function() {
            var NewDialog;
            var _id = $(this).attr('id');
            if (_id === "Button1") {
                NewDialog = $('
\
                Pitch is the relationship between a note and it\'s fundamental requency.
');
            }
            NewDialog.dialog({
                resizable: false,
                modal: true,
                show: 'clip',
                buttons: {
                    "Close": function() {
                        $(this).dialog("close");
                    }
                }
            });
        });
    });
});

my question is: how can I do this using the anchor tag as in the commented out line:
Open
This has been driving me nuts for three days and I have searched many times for an answer. Any help would be appreciated

A: You could just use something like:
$("#Button1").click(function (event) {
    event.preventDefault();

    NewDialog = $('
\
        Pitch is the relationship between a note and it\'s fundamental requency.
');
    }
    NewDialog.dialog({
        resizable: false,
        modal: true,
        show: 'clip',
        buttons: {
            "Close": function() {
                $(this).dialog("close");
            }
        }
    });
});


text:
Q: Tomcat Remote Debugging (jpda) i want to enable Tomcat Remote Debugging on a special port for connecting my source and debug applications but before it i want to understand:
can we change the source code on tomcat(webapps) by JPDA port ?


text:
Q: pymongo gridfs mongodb authentication fails I am using gridfs to store and get files from my MongoDB database
fs = gridfs.GridFS(MongoClient('mongodb://username:password@XX.XX.XX.XXX:27017/').mydb)

and to get a file I am using
file = fs.get_last_version(file_name).read()

On this line I get Authentication Failed exception.
Traceback (most recent call last):
  File "C:\Python36\lib\site-packages\flask\app.py", line 1997, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Python36\lib\site-packages\flask\app.py", line 1985, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Python36\lib\site-packages\flask\app.py", line 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Python36\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "C:\Python36\lib\site-packages\flask\app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Python36\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Python36\lib\site-packages\flask\app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Python36\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "C:\Python36\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Python36\lib\site-packages\flask\app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "D:\git\EEG\ABM\BLabPythonService\app.py", line 1039, in start_processing
    sys.stderr.flush()
  File "D:\git\EEG\ABM\BLabPythonService\process_studies.py", line 271, in start_processing
    overlay_artifacts(study)
  File "D:\git\EEG\ABM\BLabPythonService\process_studies.py", line 49, in overlay_artifacts
    edf_file = fs.get_last_version(file_name).read()
  File "C:\Python36\lib\site-packages\gridfs\__init__.py", line 200, in get_last_version
    return self.get_version(filename=filename, **kwargs)
  File "C:\Python36\lib\site-packages\gridfs\__init__.py", line 184, in get_version
    grid_file = next(cursor)
  File "C:\Python36\lib\site-packages\pymongo\cursor.py", line 1132, in next
    if len(self.__data) or self._refresh():
  File "C:\Python36\lib\site-packages\pymongo\cursor.py", line 1055, in _refresh
    self.__collation))
  File "C:\Python36\lib\site-packages\pymongo\cursor.py", line 892, in __send_message
    **kwargs)
  File "C:\Python36\lib\site-packages\pymongo\mongo_client.py", line 950, in _send_message_with_response
    exhaust)
  File "C:\Python36\lib\site-packages\pymongo\mongo_client.py", line 961, in _reset_on_error
    return func(*args, **kwargs)
  File "C:\Python36\lib\site-packages\pymongo\server.py", line 99, in send_message_with_response
    with self.get_socket(all_credentials, exhaust) as sock_info:
  File "C:\Python36\lib\contextlib.py", line 81, in __enter__
    return next(self.gen)
  File "C:\Python36\lib\site-packages\pymongo\server.py", line 168, in get_socket
    with self.pool.get_socket(all_credentials, checkout) as sock_info:
  File "C:\Python36\lib\contextlib.py", line 81, in __enter__
    return next(self.gen)
  File "C:\Python36\lib\site-packages\pymongo\pool.py", line 852, in get_socket
    sock_info.check_auth(all_credentials)
  File "C:\Python36\lib\site-packages\pymongo\pool.py", line 570, in check_auth
    auth.authenticate(credentials, self)
  File "C:\Python36\lib\site-packages\pymongo\auth.py", line 486, in authenticate
    auth_func(credentials, sock_info)
  File "C:\Python36\lib\site-packages\pymongo\auth.py", line 466, in _authenticate_default
    return _authenticate_scram_sha1(credentials, sock_info)
  File "C:\Python36\lib\site-packages\pymongo\auth.py", line 237, in _authenticate_scram_sha1
    res = sock_info.command(source, cmd)
  File "C:\Python36\lib\site-packages\pymongo\pool.py", line 477, in command
    collation=collation)
  File "C:\Python36\lib\site-packages\pymongo\network.py", line 116, in command
    parse_write_concern_error=parse_write_concern_error)
  File "C:\Python36\lib\site-packages\pymongo\helpers.py", line 210, in _check_command_response
    raise OperationFailure(msg % errmsg, code, response)
pymongo.errors.OperationFailure: Authentication failed.

Everything worked fine when my mongo database didnt have authentication.
Other use of database is working fine. I have this python service that is connecting to database using flask_pymogno and a c# application that is also connecting to database using c#, and all connections are with the same credentials.

A: Solved it. The problem was actually in my password witch contained '+' character. It is a reserved URI character. Fixed it by replacing '+' with '%2B' and it now works.
Reference:
https://en.wikipedia.org/wiki/Percent-encoding


text:
Q: "invalid email address" parse I'm trying to create a sign up with parse, and I'm pretty sure I did it right. However, whenever I put in values in the text fields and press the button nothing happens and I just get an error in the console saying:
2015-09-27 19:30:45.203 ParseStarterProject-Swift[42538:6770189][Error]: invalid email address (Code: 125, Version: 1.8.5)
Optional("invalid email address")

//register in to app
@IBAction func register(sender: UIButton) {

    let user = PFUser()
    user.username = username.text
    user.password = username.text
    user.email = username.text

    user.signUpInBackgroundWithBlock { (success, error) -> Void in
        if let error = error {
            let errorString = error.userInfo["error"] as? String
            print("\(errorString)")
        }else{
            print("success")
        }
    }

}

A: that might be leading you to invalid credentials
user.password = username.text

A: I had the same challenge, only to realize that I created two outlets from my user text field: one for username, and another for email.
Once I corrected this error (by selecting one text field for username, and the text field for email), it worked just fine.


text:
Q: The page number position changing within the same document? The position of the page number is changing within the same chapter. Specifically, the first page is shown correctly (on the bottom of the page), but the rest of that chapter is shown on the bottom top right.
I want the page number to be shown on the right bottom for the entire text!
MVE
\documentclass[12pt,a4paper]{report}
\usepackage[pdftex]{graphicx}
\usepackage{url}
\usepackage[english]{babel}
\usepackage{amsmath}
\usepackage{amssymb}
\setlength{\parindent}{0.5cm}
\usepackage{float}
\usepackage{footnote}
\usepackage[english]{babel}
\usepackage{blindtext}
\usepackage[bookmarks, colorlinks=true, pdfborder={0 0 0}, pdftitle={Internship report}, pdfauthor={Kristjan Qarri}, pdfsubject={Internship report}, pdfkeywords={<keywords here>}]{hyperref}
\usepackage[pagestyles]{titlesec}
\titleformat{\chapter}[display]{\normalfont\bfseries}{}{0pt}{\Huge}
\newpagestyle{mystyle}
{\sethead[\thepage][][\chaptertitle]{}{}{\thepage}}
\pagestyle{mystyle}
%%%%%%%%%%%%%
% add references in the TOC
\usepackage[nottoc,numbib]{tocbibind}
%%%%%%%%%%%
% acronyms
\usepackage[acronym,nomain,nonumberlist]{glossaries}
\makeglossaries

\newacronym{iso}{ISO}{international organization for standardization}
\newacronym{la}{LA}{Los Angeles}
\newacronym{un}{UN}{United Nations}
% end of file

\include{sections/Introduction}

\begin{document}
\tableofcontents

\chapter{Chapter 1}
\blindtext
\blindtext
\blindtext
\section{Section 1}
\blindtext
\blindtext
\blindtext

\chapter{Chapter 2}
\blindtext
\section{Section 1}
\blindtext
\blindtext
\blindtext
\end{document}

Link to the project file

A: The solution is shown in the code
\documentclass[12pt,a4paper]{report}
\usepackage[pdftex]{graphicx}
\usepackage{url}
\usepackage[english]{babel}
\usepackage{amsmath}
\usepackage{amssymb}
\setlength{\parindent}{0.5cm}
\usepackage{float}
\usepackage{footnote}
\usepackage[english]{babel}
\usepackage{blindtext}
\usepackage[bookmarks, colorlinks=true, pdfborder={0 0 0}, pdftitle={Internship report}, pdfauthor={Kristjan Qarri}, pdfsubject={Internship report}, pdfkeywords={<keywords here>}]{hyperref}
\usepackage[pagestyles]{titlesec}
\titleformat{\chapter}[display]{\normalfont\bfseries}{}{0pt}{\Huge}
%% Change from here
%\newpagestyle{mystyle}{\sethead[\thepage][][\chaptertitle]{}{}{\thepage}}
%\pagestyle{mystyle}
%%%%%%%%%%%%%
% add references in the TOC
\usepackage[nottoc,numbib]{tocbibind}
%%%%%%%%%%%
% acronyms
\usepackage[acronym,nomain,nonumberlist]{glossaries}
\makeglossaries

\newacronym{iso}{ISO}{international organization for standardization}
\newacronym{la}{LA}{Los Angeles}
\newacronym{un}{UN}{United Nations}
% end of file
% Kristjan Qarri
\usepackage{array}
\usepackage{makecell}
\usepackage{multirow}

\begin{document}
\tableofcontents

\chapter{Chapter 1}
\blindtext
\blindtext
\blindtext
\section{Section 1}
\blindtext
\blindtext
\blindtext

\chapter{Chapter 2}
\blindtext
\section{Section 1}
\blindtext
\blindtext
\blindtext
\end{document}


text:
Q: Supermicro IPMI and Windows Share I am trying to do a Windows Share for a Supermicro IPMI. I go to "Virtual Media" and then "CD-ROM image". I need to enter:

*

*Share to host:

*Path to Image:

*User:

*Password:

I know to enter my Windows 2008 server IP in share to Host, and I entered the Administrator username and password. However, when I enter the path image as C:\Users\Administrator\Desktop\OperatingSystems\CentOS-5.7-x86_64-netinstall.iso I get this

error: The image path is invalid or contain /:*?"<>|

A: I'm not familiar with IPMI, so take this as you wish, but you should probably use an UNC path instead of a drive letter. After all, it's talking about a Windows share.
Try to create a network share on your server, with a path of C:\Users\Administrator\Desktop\OperatingSystems\, and name it OperatingSystems, for example.
Then, use the UNC path in IPMI, though I'm not sure in what format the parameters are expected.

A: On my SMT-based IPMI 2.0, which is a rather old generation, a ISO-image won't mount no matter what. I had success via Java-console, which also allows mounting images.

A: The error reported by the web interface is misleading - what it really wants is to have the Path to image: entry beginning with a backslash (\) so it would look like \sharename\filename.iso. The host name (or IP address) in the Share host field has to be entered without backslashes though.
The share has to be an SMB share, but at least the BMC thingy is using NTLMv2 authentication, so it works with current Windows servers out of the box (i.e. without modifying security settings or installing additional software) and presumably should also work with Samba as well.


text:
Q: Convert RadialGradient to Drawable? (CSS RadialGradient to Android) I am attempting to convert CSS radial-gradient to Android and have found that I have needed RadialGradient because the CSS has multiple colors and stops. An example of the CSS is below.
background-image: radial-gradient(circle at 24% 50%, #ffffff, #c0e3e0 20%, #a4c4d7 61%, #000000);

I tried to use
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>

<gradient
    android:centerX="36%"
    android:centerY="50%"
    android:endColor="#000000"
    android:gradientRadius="300"
    android:startColor="#ffffff"
    android:type="radial"
    />
 </shape>

but you cannot include all of the colors and no stops.
I went for RadialGradient
 RadialGradient radialGradient = new RadialGradient(0.25f, 0.45f, 140.f, new int[]{
            ContextCompat.getColor(context, R.color.background_gradient_start_color),
            ContextCompat.getColor(context, R.color.background_gradient_second_color),
            ContextCompat.getColor(context, R.color.background_gradient_third_color),
            ContextCompat.getColor(context, R.color.background_gradient_end_color)}, new float[]{1.0f, 0.2f, .61f, 1.0f},
            Shader.TileMode.CLAMP);

but I cannot set the RadialGradient as the background of my RelativeLayout since it is not android.graphics.Drawable or don't know how. Can someone provide a solution?

A: You can use layer-list, like this:
<?xml version="1.0" encoding="utf-8"?>
<layer-list>
    <item>
        <shape xmlns:android="http://schemas.android.com/apk/res/android"
            android:shape="rectangle">
            <gradient
                android:centerX="36%"
                android:centerY="50%"
                android:endColor="#33c0e3e0"
                android:gradientRadius="300"
                android:startColor="#ffffff"
                android:type="radial"
                />
        </shape>
    </item>
    <item>
        <shape xmlns:android="http://schemas.android.com/apk/res/android"
            android:shape="rectangle">
            <gradient
                android:centerX="36%"
                android:centerY="50%"
                android:endColor="#000000"
                android:centerColor="@color/colorAccent"
                android:gradientRadius="600"
                android:startColor="#9ca4c4d7"
                android:type="radial"
                />
        </shape>
    </item>
</layer-list>


text:
Q: Using Beanshell sampler return value in JMeter while condition
I am trying to use the return value from beanshell sampler, later in the while condition ${__javaScript(${homeState}<6)}.
When i run and check logs, ${homeState} is not getting replaced with the beanshell sampler homeState integer value.
Can any one suggest what's wrong going on?
however, when i check the response of beanshell sampler in view results tree, it is returing integer as expected.

A: return keyword in Beanshell defines Beanshell sampler response data. If you need to store the value into a JMeter Variable you should replace the line return homeState with the following expression:
vars.put("homeState", String.valueOf(homeState));

vars is a shorthand to JMeterVariables class instance, it provides read/write access to the JMeter Variables in scope.
See How to Use BeanShell: JMeter's Favorite Built-in Component article for comprehensive information on using Beanshell scripting in JMeter tests


text:
Q: Getting an address and creating a static google map in php Hi I have an address which has each line separated by tags e.g. span or p's I have used jQuery to strip out the tags (my idea is to get the address in a entire row) and then use google maps static version to link the address to the correct map, when I copy the google maps code and the address and paste that into google maps its fine and works as it should (ie it brings up the right map) but I need to take it one step further and show it as a image, If I wrap the code in a image tag like:
<img src='<?php function to bring address ?>' alt='' />

and then I go to preview it, It shows the tags I previously stripped out in jquery when I view the source of a image.
Can anyone shed any light on this?
thanks

A: Take a look at this: http://imagine-it.org/google/staticmap/encodemymap.php and
http://static-maps-generator.appspot.com/


text:
Q: 3 way Vlookup or Index unable to get working I am trying to look up two columns to see if a team is present in the other columns.  In this case if J2:J9 exists in N2:N9 and R2:R9.
Thus far I have tried using a simple Vlookup formula like below:
=VLOOKUP(J4,N$2:O$40000,R$2:S$40000,1,0)

Though I believe vlookup is limited to one column only unfortunately.
I have also tried:
=INDEX(N$2:O$40000,MATCH(J4,R$2:S$40000,1),0)

Though this does not give me what I am wanting.  Is what I am asking possible or are you able to only see if the Team NZ in this case is present in N:O but seeing if it exists in N:O and R:S and giving it a N/A not possible?  What am I doing wrong here.
Thanks
UPDATE: Ideally I want if it is present to display the Team name in the column otherwise display a #N/A similar to what Column M does except it checks if it is present in all the columns

A: If you just need to check if the team in 'Back' group is present in both the other groups, you need not include columns 'O' and 'S' in your lookup.
Here's a solution that uses COUNTIFS:
=COUNTIFS(M:M,J2,R:R,J2)

It'll return 1 if the team is present in both the other columns, and 0 if it's not present in either of them.
And if you prefer having a message, then you can wrap the above COUNTIFS function with CHOOSE:
=CHOOSE(COUNTIFS(M:M,J2,R:R,J2)+1, "Not present in both", "Present in both")

Here's the result:
╔═══╦════════════╦═════════════════════╦════════╦═══╦═══╦═══════╦═══╦═══╦═══╦═══╦════════╗
║   ║     H      ║          I          ║   J    ║ K ║ L ║   M   ║ N ║ O ║ P ║ Q ║   R    ║
╠═══╬════════════╬═════════════════════╬════════╬═══╬═══╬═══════╬═══╬═══╬═══╬═══╬════════╣
║ 1 ║ Solution 1 ║     Solution 2      ║ Back   ║   ║   ║ Draw  ║   ║   ║   ║   ║ Lay    ║
║---║------------║---------------------║--------║---║---║-------║---║---║---║---║--------║
║ 2 ║     1      ║ Present in both     ║ Melb   ║   ║   ║ Melb  ║   ║   ║   ║   ║ Melb   ║
║ 3 ║     0      ║ Not present in both ║ Aus    ║   ║   ║ Aus   ║   ║   ║   ║   ║ Paysan ║
║ 4 ║     1      ║ Present in both     ║ Nz     ║   ║   ║ Int   ║   ║   ║   ║   ║ Circi  ║
║ 5 ║     1      ║ Present in both     ║ Syd    ║   ║   ║ Syd   ║   ║   ║   ║   ║ Syd    ║
║ 6 ║     0      ║ Not present in both ║ Circ   ║   ║   ║ Circ  ║   ║   ║   ║   ║ Nz     ║
║ 7 ║     0      ║ Not present in both ║ Oeste  ║   ║   ║ Oeste ║   ║   ║   ║   ║ Gois   ║
║ 8 ║     0      ║ Not present in both ║ Gois   ║   ║   ║ Gois  ║   ║   ║   ║   ║ Parana ║
║ 9 ║     0      ║ Not present in both ║ Parana ║   ║   ║ Nz    ║   ║   ║   ║   ║ Nz     ║
╚═══╩════════════╩═════════════════════╩════════╩═══╩═══╩═══════╩═══╩═══╩═══╩═══╩════════╝

A: A little unclear if you are just searching column after column to find first match to J in specified columns if exists and retrieve the adjacent value. I so, you could try nesting VLOOKUPs with IFERROR.
For example:
=IFERROR(VLOOKUP($J4,N:O,2,FALSE),VLOOKUP($J4,Q:R,2,FALSE))

You can nest further VLOOKUPs if there are additional columns to search.
If not found you will get #N/A returned.

A: And yet another solution to get a TRUE or FALSE answer:
=IFNA(MATCH(J4,$N$2:$N$40000,0)+MATCH(J4,$R$2:$R$40000,0),0)>0

A: You can use this formula as shown in the pic:

=IF(ISNUMBER(MATCH(J2,$N$2:$N$9,0)+MATCH(J2,$R$2:$R$9,0)),"Present","Not Present")


text:
Q: Android - view does not keep height I'm trying to add a custom view to a linearlayout, but the view does not keep it's height. The height is 48dp so it's fixed but after I do addView() it change to wrap_content :
LinearLayout cmsList = (LinearLayout) mView.findViewById(R.id.ll_cms_sections);

View group = getActivity().getLayoutInflater().inflate(R.layout.item_cms_group, null);

cmsList.addView(group);

The group :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="@color/clear_orange">

<com.dekibae.android.popinthecity.presentation.ui.widgets.FontText
    android:id="@+id/tv_cms"
    style="@style/TitleOrangexNormal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginEnd="@dimen/margin_normal"
    android:layout_marginStart="@dimen/margin_normal"
    android:layout_toLeftOf="@+id/indicator"
    android:gravity="center"
    android:paddingTop="4dp"
    android:text="TEST SECTION"
    app:font="@string/plaak" />

<ImageView
    android:id="@+id/indicator"
    android:layout_width="24dp"
    android:layout_height="24dp"
    android:layout_alignParentEnd="true"
    android:layout_centerVertical="true"
    android:layout_marginEnd="@dimen/margin_normal"
    android:scaleType="centerInside"
    android:src="@drawable/dropdown_arrow" />

</RelativeLayout>

The cmsList
<LinearLayout
            android:id="@+id/ll_cms_sections"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

I even tried to force it :
group.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 48));

A: Picking up on @Abtin Gramian's comment the constructor used takes as a dimension pixels, and not dp (density independent pixels)
From the android documentation

android.view.ViewGroup.LayoutParams public LayoutParams(int width,
                      int height)
Creates a new set of layout parameters with the specified width and height.
Parameters:
width - either WRAP_CONTENT, FILL_PARENT or a fixed size in pixels
height - either
  WRAP_CONTENT, FILL_PARENT or a fixed size in pixels

So through the use of
public static float applyDimension (int unit, float value, DisplayMetrics metrics)
we can make a conversion from a dimension in one type of metrics like TypedValue.COMPLEX_UNIT_DIP to another, in this case one adequate for the current display.
group.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 48, context.getResources().getDisplayMetrics())));


text:
Q: Pass props to React container component I'm new to React. I'm displaying a list of songs and I want to allow the user to add songs to their favourites. I'm using Redux to store the favourited songs. My PlayList component looks like:
import AddSong from '../containers/AddSong'

class Playlist extends Component {

    render(){
        return (

Playlists

              {this.state.items.map(item =>

                    {item.track.name} by {item.track.artists[0].name}

                    <AddSong title={item.track.name} />

              )}

        );

    }
    ...
}

So I passing the song name to AddSong with <AddSong title={item.track.name} />
And AddSong looks like:
import React from 'react'
import { connect } from 'react-redux'
import { addSong } from '../actions'

let AddSong = ({ dispatch }) => {
  let input

  console.log('this is ', this);

  return (

      <form
        onSubmit={e => {
          e.preventDefault()
          // GET SONG FROM PROPS AND DISPATCH
          //dispatch(addSong(input.value))

        }}
      >
        <input
          ref={node => {
            input = node
          }}
        />
        <button type="submit">
          Add Song
        </button>
      </form>

  )
}
AddSong = connect()(AddSong)

export default AddSong

However, this is an object with the property:
{
   a: Connect(props, context)
}

How do I get the song title in AddSong?
EDIT
So this is what I have now, Im passing the song title to AddSong here:
<AddSong song={item.track.name} title={item.track.name} />

I'm passing the song title in as song and title to show what happens.
In AddSong, I have:
const mapStateToProps = (state) => {

    const {song:song} = state; // or whatever the reducer called
    return {song};
};

const mapDispatchToProps = (dispatch) => ({

    addSong: (value) => dispatch(addSong(value)),
});

export default connect(mapStateToProps, mapDispatchToProps)(AddSong);

And at the top of AddSong I'm doing:
let AddSong = ({ dispatch, ...props }) => {
  let input

  console.log('props is ', props);

The console outputs:
props is  Object {song: undefined, title: "Young Blood"}

I've changed the button to:
<button onClick={(value)=>props.addSong(value)}>
  Add Song
</button>

When I click, this gives the error:
Failed prop type: Invalid prop `songs[0].text` of type `object` supplied to `SongList`, expected `string

A: Try to use this function
const mapStateToProps = function(store) {
  return {
    data: store.data
  };
  }

AddSong = connect(mapStateToProps)(AddSong)

A: I assume you have the reducer and you want to access the state via props, if this the case you can mapStateToProps e.g.

const mapStateToProps = (state) => {

    const {song:song} = state; // or whatever the reducer called
    return {song};

};

const mapDispatchToProps = (dispatch) => ({
    addSong: (value) => dispatch(addSong(value)),
});

export default connect(mapStateToProps, mapDispatchToProps)(AddSong);

then you can just write this.props.song.


text:
Q: Принцип работы LinkExtractor в Scrapy Всем привет!
Нужно спарсить сайт с помощью Scrapy. Почитал документацию, посмотрел несколько роликов, но что-то я запутался с LinkExtractor в Scrapy.
Вот смотрите, один из примеров, на котором обучался:
class SpiderSpider(CrawlSpider):

    name = 'prodpar'
    allowed_domains = ['sipwhiskey.com']
    start_urls = ['https://sipwhiskey.com/']

    rules = [Rule(LinkExtractor(allow='japanese'),
                  callback='parse_filter', follow=True), ]

    def parse_filter(self, response):
        item = Product()
        item['product_url'] = response.url
        yield item

Получилось около 230 ссылок, вот пример ответов:
   https://sipwhiskey.com/collections/japanese-whisky/nikka,,
   https://sipwhiskey.com/collections/japanese-whisky/mars-iwai-japanese-whisky,,
   https://sipwhiskey.com/collections/japanese-whisky?page=3,,

Scrapy выдал все ссылки на сайте, где упоминается слово "japanese".
Верно ли я понимаю, что LinkExtractor ищет по всему сайту, начиная с start_urls, т.е. перебирает все ссылки на сайте, где присутствует слово "japanese" и выдает мне их?
Если это так, то не могу сделать подобное на сайте, который мне нужен.
class SpiderSpider(CrawlSpider):
name = 'sbermega'
allowed_domains = ['sbermegamarket.ru']
start_urls = ['https://sbermegamarket.ru/catalog/']

rules = [Rule(LinkExtractor(allow='kingxbar'),
              callback = 'parse_prod', follow = True),]

def parse_prod(self, response):
    item = SberMegaItem()
    item['product_url'] = response.url
    yield item

Мне нужно взять все ссылки с сайта, где упоминается бренд Kingxbar. Т.е. я тоже самое (наверно) указываю стартовый url, указываю в LinkExtractor по какому слову искать. Но реальном примере паук проходит и ничего не выдает. А ссылок на сайте с данным словом много, например, вот такие:
     https://sbermegamarket.ru/catalog/chehly-dlya-sotovogo-telefona/brand-kingxbar/
     https://sbermegamarket.ru/catalog/details/chehol-kingxbar-epoxy-series-colorful-dlya-iphone-13-pro-600005916434/

Может кто-нибудь помочь объяснить принцип работы LinkExtractor? Т.е. если я укажу start_urls = ['https://sbermegamarket.ru/catalog/'] и ключевое слово "kingxbar" и follow = True, означает ли, что паук начиная с этой страницы посмотрит ВСЕ ссылки на сайте, которые начинаются с  sbermegamarket.ru/catalog (например, https://sbermegamarket.ru/catalog/chehly-dlya-sotovogo-telefona/brand-**kingxbar** или https://sbermegamarket.ru/catalog/chehly-dlya-sotovogo-telefona/brand-**apple**).
Если это так, то почему паук не скрапит во втором примере. А если это не так, то как работает LinkExtractor в первом примере?
Вот ответ паука во втором примере:

2022-04-21 10:00:03 [scrapy.utils.log] INFO: Scrapy 2.6.1 started
(bot: sbermega) 2022-04-21 10:00:03 [scrapy.utils.log] INFO: Versions:
lxml 4.8.0.0, libxml2 2.9.12, cssselect 1.1.0, parsel 1.6.0, w3lib
1.22.0, Twisted 22.4.0, Python 3.9.7 (tags/v3.9.7:1016ef3, Aug  30 2021, 20:19:38) [MSC v.1929 64 bit (AMD64)], pyOpenSSL 22.0.0 (OpenSSL
1.1.1n  15 Mar 2022), cryptography 36.0.2, Platform Windows-10-10.0.19044-SP0 2022-04-21 10:00:03 [scrapy.crawler] INFO:
Overridden settings: {'BOT_NAME': 'sbermega',  'DOWNLOAD_DELAY': 0.5,
'FEED_EXPORT_ENCODING': 'utf-8',  'FEED_EXPORT_FIELDS':
['product_url', 'code', 'price', 'shop', 'name'],  'NEWSPIDER_MODULE':
'sbermega.spiders',  'ROBOTSTXT_OBEY': True,  'SPIDER_MODULES':
['sbermega.spiders']} 2022-04-21 10:00:03 [scrapy.utils.log] DEBUG:
Using reactor: twisted.internet.selectreactor.SelectReactor 2022-04-21
10:00:03 [scrapy.extensions.telnet] INFO: Telnet Password:
e2f3495172556346 2022-04-21 10:00:03 [py.warnings] WARNING:
c:\users\purchase\pycharmprojects\sbermegamerket\venv\lib\site-packages\scrapy\extensions\feedexport.py:289:
ScrapyDeprecationWarning: The FE ED_URI and FEED_FORMAT settings
have been deprecated in favor of the FEEDS setting. Please see the
FEEDS setting docs for more details   exporter = cls(crawler)
2022-04-21 10:00:03 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
'scrapy.extensions.telnet.TelnetConsole',
'scrapy.extensions.feedexport.FeedExporter',
'scrapy.extensions.logstats.LogStats'] 2022-04-21 10:00:03
[scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware',
'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
'scrapy.downloadermiddlewares.retry.RetryMiddleware',
'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware',
'scrapy.downloadermiddlewares.stats.DownloaderStats'] 2022-04-21
10:00:03 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
'scrapy.spidermiddlewares.referer.RefererMiddleware',
'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
'scrapy.spidermiddlewares.depth.DepthMiddleware'] 2022-04-21 10:00:03
[scrapy.middleware] INFO: Enabled item pipelines: [] 2022-04-21
10:00:03 [scrapy.core.engine] INFO: Spider opened 2022-04-21 10:00:03
[scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min),
scraped 0 items (at 0 items/min) 2022-04-21 10:00:03
[scrapy.extensions.telnet] INFO: Telnet console listening on
127.0.0.1:6023 2022-04-21 10:00:04 [filelock] DEBUG: Attempting to acquire lock 2231374258336 on
c:\users\purchase\pycharmprojects\sbermegamerket\venv\lib\site-packages\tldextract.suffix_cache/public
suffix.org-tlds\de84b5ca2167d4c83e38fb162f2e8738.tldextract.json.lock
2022-04-21 10:00:04 [filelock] DEBUG: Lock 2231374258336 acquired on
c:\users\purchase\pycharmprojects\sbermegamerket\venv\lib\site-packages\tldextract.suffix_cache/publicsuffix.org-tl
ds\de84b5ca2167d4c83e38fb162f2e8738.tldextract.json.lock 2022-04-21
10:00:04 [filelock] DEBUG: Attempting to release lock 2231374258336 on
c:\users\purchase\pycharmprojects\sbermegamerket\venv\lib\site-packages\tldextract.suffix_cache/public
suffix.org-tlds\de84b5ca2167d4c83e38fb162f2e8738.tldextract.json.lock
2022-04-21 10:00:04 [filelock] DEBUG: Lock 2231374258336 released on
c:\users\purchase\pycharmprojects\sbermegamerket\venv\lib\site-packages\tldextract.suffix_cache/publicsuffix.org-tl
ds\de84b5ca2167d4c83e38fb162f2e8738.tldextract.json.lock 2022-04-21
10:00:04 [scrapy.core.engine] DEBUG: Crawled (200) <GET
https://sbermegamarket.ru/robots.txt> (referer: None) 2022-04-21
10:00:05 [scrapy.core.engine] DEBUG: Crawled (200) <GET
https://sbermegamarket.ru/catalog/> (referer: None) 2022-04-21
10:00:05 [scrapy.core.engine] INFO: Closing spider (finished)
2022-04-21 10:00:05 [scrapy.statscollectors] INFO: Dumping Scrapy
stats: {'downloader/request_bytes': 553,  'downloader/request_count':
2,  'downloader/request_method_count/GET': 2,
'downloader/response_bytes': 242207,  'downloader/response_count': 2,
'downloader/response_status_count/200': 2,  'elapsed_time_seconds':
2.02061,  'finish_reason': 'finished',  'finish_time': datetime.datetime(2022, 4, 21, 7, 0, 5, 922735),
'httpcompression/response_bytes': 1125518,
'httpcompression/response_count': 2,  'log_count/DEBUG': 7,
'log_count/INFO': 10,  'log_count/WARNING': 1,
'response_received_count': 2,  'robotstxt/request_count': 1,
'robotstxt/response_count': 1,  'robotstxt/response_status_count/200':
1,  'scheduler/dequeued': 1,  'scheduler/dequeued/memory': 1,
'scheduler/enqueued': 1,  'scheduler/enqueued/memory': 1,
'start_time': datetime.datetime(2022, 4, 21, 7, 0, 3, 902125)}
2022-04-21 10:00:05 [scrapy.core.engine] INFO: Spider closed
(finished)

Добавляю спустя время.
Попробовал в start_url записать одну из страниц каталога данного бренда:
      https://sbermegamarket.ru/catalog/details/chehol-kingxbar-epoxy-series-colorful-dlya-iphone-13-pro-600005916434/

все ок, спарсил все страницы с сайта (их там около 180). Вот сейчас совсем запутался. Не пойму, как он работает - что в итоге нужно указывать start_url и по какому принципу он проходит страницы.
Всем откликнувшимся - спасибо!


text:
Q: Android Java: I need to save a bitmap alongwith name,mobile no.s to the contact list Android: Java
I'm able to save name,mobile no.s to my Contact List.

*

*however, i'm Unable to save logo/bitmap to the (new item in the) Contact List.

Could you send me a snippet of code to save the bitmap/logo, too, to the Contact List?
Thanks,
Kumar

A: ContentValues values = new ContentValues();
values.put(People.NAME, "Serkan Ozel");
Uri uri = getContentResolver().insert(People.CONTENT_URI, values);

Bitmap photo = myImage.getBitmap();
if (photo != null) {
  ByteArrayOutputStream stream = new ByteArrayOutputStream();
  photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);
  People.setPhotoData(getContentResolver(), uri, stream.toByteArray
());

}


text:
Q: how i can publish without destination url? I don't have a link in the "Associations" section.
How can I publish a project without him?
IIS

VS 2022

is it possible?

A: The Destination URL setting isn't required. When Visual Studio finishes deploying the application, it automatically opens your default browser to this URL. If you don't want the browser to open automatically after deployment, leave this box blank.


text:
Q: Keeping current JSF pagination state when going to another page and coming back to the page that contains the paginator I'm using the Tomahawk t:dataScroller for pagination. It is working really well. There is only one issue that I'll try to explain:
Page A contains the t:dataTable, which is paginated with the t:dataScroller. There are links in the dataTable that can redirect me to another page, say page B. When I go back from B to A, the state of the pagination is restarted.
What I mean is that, if, in Page A, I'm at the 5th page, and then move to page B, when I go back to A, I'll be at the 1st page on A.
Does anyone have gone through this? Does anybody have any idea?

A: You can take control of 'first' property of the datatable. What you need to this,

*

*Declare a public/protected variable in your session bean,
@ManagedBean
@SessionScoped
public class DataTableController implements java.io.Serializable {
   protected int first;
        // getters and setters...

*Bind it with the 'first' property of datatable
<p:dataTable id="results-table" var="result"
      ...
      first="#{dataTableController.first}"

*While navigating between the pages, store the 'first' record value using something like this,
public void onPageChange(PageEvent event) {
      this.setFirst(((DataTable) event.getSource()).getFirst());
   }
For more details, follow the link.
http://forum.primefaces.org/viewtopic.php?f=3&t=25399#p80324
BTW Thanks for the comments


text:
Q: Construct a data structure with special requirements in python Requirements:

*

*There is a variable, for example, related_to_dict = 10

*Construct a key value pair data, for example, special_dict = {0 :
ref_related_to_dict}

*When the variable of related_to_dict changed, the value of
special_dict[0] also changed to the value of related_to_dict
accordingly.

*When the value_of special_dict[0], e.g. ref_related_to_dict changed, the
value of related_to_dict also changed to the value of
special_dict[0] accordingly.

Is there a way to achieve this task?

A: You need to wrap the value in some sort of container.
class Ref:
   def __init__(self, v):
        self.val = v

And then:
related_to_dict = Ref(10)
special_dict = {0: related_to_dict}

Then it works as desired:
related_to_dict.val = 40
print(special_dict[0].val) # 40


text:
Q: Converting 0xFF to RGB value I have a snippet of code I am using for a Java application, I am trying to replace the hex value of 0xFF which equals blue to a different color preferably represented by an RGB value, is this possible?
void trailBlurEffect(int blendAmount, PGraphics buffer) {
   for (int i = 0, y = 0; y < buffer.height; y++) {
     for (int x = 0; x < buffer.width; x++, i++) {
       buffer.pixels[i] = 0xff000000 | (( buffer.pixels[i]  & 0xFF) * blendAmount) >> 8;
     }
   }
   nodeBuffer.updatePixels();
}

edit:
I am trying to write a different color however I am unable to get a result that works, for example by replacing 0xFF(blue) with the hex equivalent of red which is = 0xFF0000 my canvas draws nothing. My code is coming from this example: openprocessing.org/sketch/52388

A: It's pretty unclear on what you're trying to accomplish.  RGB colors are given as three different numbers: A Red, Green, and a Blue value.  Each value can range from 0 - 255.  0xFF isn't an RGB value, it's a value representing one of the colors.  To get a full RGB color, you would have to use something like 0xFF0000.  So no, you can't magically turn 0xFF into Blue, you have to know the values of the other colors as well.  You could take in three values, and then formulate the color from there, IE take in a rValue, gValue, and bValue, then stick 'em all together to get the classic RGB format of 0xRRGGBB.
Hope this helps!

A: I don'y know binary math, but i think this is what is being done in
  buffer.pixels[i]  & 0xFF

0xFF is a mask to be applied to buffer.pixels[i]. So this is not the way you will get the color you need. You can try calling fill(wantedColor) just before ellipse() in draw(), but as author said in the page you pointed, for the trail he only used the blue channel i think the trail will still be blue.


text:
Q: What is the official documentation of Scala? I see two links whenever searching up official documentation for Scala:
This: https://www.scala-lang.org/
And this link: https://www.scala-lang.org/api/2.13.3/
What is the difference between the two? Which one is the official documentation for the language, or is there some other link?

A: docs.scala-lang.org gives links to main sources of documentation, for example,

*

*Scala Language Specification (SLS)

*Scala Library API
The source code of SLS is at https://github.com/scala/scala/tree/2.13.x/spec which can be useful for searching for a particular symbol in SLS via IDE (because browsers make it hard). SLS is the authoritative reference on Scala. contributors.scala-lang.org and scala/contributors is where in-depth discussion on design of Scala happen.
For a more approachable user guide from the designer of Scala consider Programming in Scala which is authored by Martin Odersky et al.


text:
Q: Recycleview under NestedScrollview in android I put my RecyclerView under NestedScrollView. If RecyclerView data is small then it's working fine but if data is more than 10,000, Android OS default pop come and ask for wait or close the application. If I remove my NestedRecyclerView then it's working fine. My question is what is the better way to put the layout in ScrollView
This is my layout
    <LinearLayout
    android:id="@+id/totstock_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:visibility="visible">

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:scrollbars="vertical"
        android:nestedScrollingEnabled="true"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <LinearLayout
                android:id="@+id/totstockrelativeLayout1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/totstockSelectBox"
                    android:layout_width="0dp"
                    android:layout_height="40dp"
                    android:layout_alignParentLeft="true"
                    android:layout_centerVertical="true"
                    android:layout_gravity="center"
                    android:layout_marginLeft="10dp"
                    android:layout_weight="1"
                    android:gravity="start|center"
                    android:maxLines="1"
                    android:minLines="1"
                    android:minWidth="100dp"
                    android:padding="5dp"
                    android:text="Warehouse"
                    android:textSize="14sp"
                    android:textStyle="bold" />

                <AutoCompleteTextView
                    android:id="@+id/totstockwarehouse"
                    android:layout_width="0dp"
                    android:layout_height="40dp"
                    android:layout_alignParentRight="true"
                    android:layout_centerVertical="true"
                    android:layout_marginLeft="8dp"
                    android:layout_marginRight="8dp"
                    android:layout_marginTop="5dp"
                    android:layout_weight="3"
                    android:background="@drawable/round_text"
                    android:gravity="center|left"
                    android:paddingLeft="8dp"
                    android:paddingRight="8dp"
                    android:textColor="@color/primaryText"
                    android:textSize="16sp" />

            </LinearLayout>

            <LinearLayout
                android:id="@+id/totstockrelativeLayout2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/totstockSelectBox1"
                    android:layout_width="0dp"
                    android:layout_height="40dp"
                    android:layout_alignParentLeft="true"
                    android:layout_centerVertical="true"
                    android:layout_gravity="center"
                    android:layout_marginLeft="10dp"
                    android:layout_weight="1"
                    android:gravity="start|center"
                    android:maxLines="1"
                    android:minLines="1"
                    android:minWidth="100dp"
                    android:padding="5dp"
                    android:text="Customer"
                    android:textSize="14sp"
                    android:textStyle="bold" />

                <AutoCompleteTextView
                    android:id="@+id/totstockcustomer"
                    android:layout_width="0dp"
                    android:layout_height="40dp"
                    android:layout_alignParentRight="true"
                    android:layout_centerVertical="true"
                    android:layout_marginLeft="8dp"
                    android:layout_marginRight="8dp"
                    android:layout_marginTop="5dp"
                    android:layout_weight="3"
                    android:background="@drawable/round_text"
                    android:gravity="center|left"
                    android:paddingLeft="8dp"
                    android:paddingRight="8dp"
                    android:textColor="@color/primaryText"
                    android:textSize="16sp" />

            </LinearLayout>

            <LinearLayout
                android:id="@+id/totrelativeLayout3"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/totSelectBox2"
                    android:layout_width="0dp"
                    android:layout_height="40dp"
                    android:layout_alignParentLeft="true"
                    android:layout_centerVertical="true"
                    android:layout_gravity="center"
                    android:layout_marginLeft="10dp"
                    android:layout_weight="1"
                    android:gravity="start|center"
                    android:maxLines="1"
                    android:minLines="1"
                    android:minWidth="100dp"
                    android:padding="5dp"
                    android:text="Item Name"
                    android:textSize="14sp"
                    android:textStyle="bold" />

                <AutoCompleteTextView
                    android:id="@+id/totitemautotext"
                    android:layout_width="0dp"
                    android:layout_height="40dp"
                    android:layout_alignParentRight="true"
                    android:layout_centerVertical="true"
                    android:layout_marginLeft="8dp"
                    android:layout_marginRight="8dp"
                    android:layout_marginTop="5dp"
                    android:layout_weight="3"
                    android:background="@drawable/round_text"
                    android:gravity="center|left"
                    android:paddingLeft="8dp"
                    android:paddingRight="8dp"
                    android:textColor="@color/primaryText"
                    android:textSize="16sp" />

            </LinearLayout>

            <android.support.v7.widget.AppCompatButton
                android:id="@+id/totstocksearch_wms"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:background="@color/mdtp_light_gray"
                android:padding="4dp"
                android:text="Search"
                android:textColor="@color/white"
                android:textSize="16sp" />

        </LinearLayout>
    </android.support.v4.widget.NestedScrollView>

    <HorizontalScrollView
        android:id="@+id/datahorizontal2tot"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scrollbars="none">

        <LinearLayout
            android:id="@+id/datahorizontal1tot"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <LinearLayout
                android:id="@+id/datahorizontaltot"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/totstockitemsku"
                    android:layout_width="150dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:text="Item SKU"
                    android:textColor="@color/black"
                    android:textSize="15sp" />

                <TextView
                    android:id="@+id/totstockstockitemname"
                    android:layout_width="150dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:text="Item Name"
                    android:textColor="@color/black"
                    android:textSize="15sp" />

                <TextView
                    android:id="@+id/totstockbrandname"
                    android:layout_width="100dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:text="Brand Name"
                    android:textColor="@color/black"
                    android:textSize="15sp" />

                <TextView
                    android:id="@+id/totstockgrdname"
                    android:layout_width="100dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:text="Grade Name"
                    android:textColor="@color/black"
                    android:textSize="15sp" />

                <TextView
                    android:id="@+id/totstockgrnqty"
                    android:layout_width="110dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:text="GRN Quantity"
                    android:textColor="@color/black"
                    android:textSize="15sp"
                    android:visibility="visible" />

                <TextView
                    android:id="@+id/totstockpickqty"
                    android:layout_width="140dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:text="Pick List Quantity"
                    android:textColor="@color/black"
                    android:textSize="15sp" />

                <TextView
                    android:id="@+id/totstockavailqty"
                    android:layout_width="150dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:text="Available Quantity"
                    android:textColor="@color/black"
                    android:textSize="15sp" />

                <TextView
                    android:id="@+id/totstockputawayqty"
                    android:layout_width="140dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:text="Put Away Quantity"
                    android:textColor="@color/black"
                    android:textSize="15sp" />

                <TextView
                    android:id="@+id/totstockorderqty"
                    android:layout_width="140dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:text="Order Quantity"
                    android:textColor="@color/black"
                    android:textSize="15sp" />

                <TextView
                    android:id="@+id/totstockdamage"
                    android:layout_width="140dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:text="Damage"
                    android:textColor="@color/black"
                    android:textSize="15sp" />

                <TextView
                    android:id="@+id/totstockdispatchhqty"
                    android:layout_width="140dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:text="Dispatch Quantity"
                    android:textColor="@color/black"
                    android:textSize="15sp" />

            </LinearLayout>

            <View
                android:id="@+id/viewline1"
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="@android:color/darker_gray" />

            <android.support.v7.widget.RecyclerView
                android:id="@+id/totstockwmsrecyclerview"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:visibility="gone"
                app:layout_behavior="@string/appbar_scrolling_view_behavior">

            </android.support.v7.widget.RecyclerView>

        </LinearLayout>
    </HorizontalScrollView>

    <TextView
        android:id="@+id/totstocknorecord"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:text="No Record Found"
        android:textColor="@android:color/black"
        android:textSize="24sp"
        android:visibility="visible" />

</LinearLayout>

A: you shouldn't use scrolling views as parent and child
instead you should use recyclerview with multiple rows like this:
http://arjunu.com/2015/10/android-recyclerview-with-different-cardviews/


text:
Q: Why do favicons get refreshed so rarily? I know how to force refresh a favicon on a website.
But I would really like to know the reason why it is common with all browsers to refresh favicons in such huge time intervals. After all, images get refreshed much more often.
I'm not looking for a solution, I would just like to know the why.

A: Because many servers are configured to tell the browsers to cache (save) files like favicons to reduce the number of requests for files that rarely change.


text:
Q: BOM not expected in CF but sent by IIS/SharePoint I'm trying to consume a SharePoint webservice from ColdFusion via cfinvoke ('cause I don't want to deal with (read: parse) the SOAP response itself).
The SOAP response includes a byte-order-mark character (BOM), which produces the following exception in CF:
"Cannot perform web service invocation GetList.
The fault returned when invoking the web service operation is:
'AxisFault
faultCode: {http://www.w3.org/2003/05/soap-envelope}Server.userException
faultSubcode:
faultString: org.xml.sax.SAXParseException: Content is not allowed in prolog."

The standard for UTF-8 encoding optionally includes the BOM character (http://unicode.org/faq/utf_bom.html#29). Microsoft almost universally includes the BOM character with UTF-8 encoded streams . From what I can tell there's no way to change that in IIS. The XML parser that JRun (ColdFusion) uses by default doesn't handle the BOM character for UTF-8 encoded XML streams. So, it appears that the way to fix this is to change the XML parser used by JRun (http://www.bpurcell.org/blog/index.cfm?mode=entry&entry=942).
Adobe says that it doesn't handle the BOM character (see comments from anoynomous and halL on May 2nd and 5th).
http://livedocs.adobe.com/coldfusion/8/htmldocs/Tags_g-h_09.html#comments

A: I'm going to say that the answer to your question (is it possible?) is no. I don't know that definitively, but the poster who commented just above halL (in the comments on this page) gave a work-around for the problem -- so I assume it is possible to deal with when parsing manually.
You say that you're using CFInvoke because you don't want to deal with the soap response yourself. It looks like you don't have any choice.

A: As Adam Tuttle said already, the workaround is on the page that you linked to
<!--- Remove BOM from the start of the string, if it exists --->
<cfif Left(responseText, 1) EQ chr(65279)>
<cfset responseText = mid(xmlText, 2, len(responseText))>
</cfif>

A: It sounds like ColdFusion is using Apache Axis under the covers.
This doesn't apply exactly to your solution, but I've had to deal with this issue once before when consuming a .NET web service with Apache Axis/Java. The only solution I was able to find (since the owner of the web service was unwilling to change anything on his end) was to write a Handler class that Axis would plug into the pipeline which would delete the BOM from the message if it existed.
So perhaps it's possible to configure Axis through ColdFusion? If so you can add additional Handlers to the message handling flow.


text:
Q: Fields that lend themselves to variational principles? In physics, we often describe the dynamic properties of fields using variational principles like defining an action or a Lagrangian. A field however is simply some function of space $\phi(x)$ so I wonder what kind of properties the dynamics must follow to lend itself to description by an action principle?
For example, can all dynamics that are continuous be described by some specific action?
Just want to get an idea of the restrictions.

A: Since you have tagged it as classical field theory, I am assuming you are asking what properties $\phi(x)$ must have to admit equations of motion which may be derived from an action principle.
The property $\phi(x)$ must have to be amenable by an action principle is that it must satisfy equations of motion which are Euler-Lagrange equations for some action.
Unfortunately, I do not know of any papers on what properties $\phi(x)$ must have, but there is a classical theorem on what properties the equations must have, in classical mechanics. If one has $u : [0,T] \to \mathbb R^n$ which is differentiable, and satisfying $\ddot u = f^i(u, \dot u)$, we require that for the existence of Lagrangian, the existence of a non-singular symmetric matrix $M_{ij}(u,\dot u)$ satisfying:

*

*$$(M \Phi) = (M\Phi)^T$$

*$$\forall_{i,j}\quad \dot M_{ij} = \frac12 \frac{\partial f^k}{\partial \dot u^i} M_{kj} + \frac12 \frac{\partial f^k}{\partial \dot u^j} M_{ki} $$

*$$\forall_{i,j,k} \quad \frac{\partial M_{ij}}{\partial \dot u^k} = \frac{\partial M_{ik}}{\partial \dot u^j}$$
where $\Phi^i_j = \frac12 \partial_t \partial_{\dot u^j} f^i - \partial_{u^j}f^i - \frac14 (\partial_{\dot u^k} f^i)(\partial_{\dot u^j} f^k)$. These are the Helmholtz conditions.  I do not know of a generalisation to field theory, but this work has been expanded on in papers such as here, here and the citations of this paper. Another way to view these conditions is as those for $0+1$-dimensional field theory.


text:
Q: illegal state exception on clicking a button here the next button is a method called upon clicking a button.When i click on the button it gives me an illegal state exception.
code:
 public class Shapes extends Activity {

    int i=3;
    ShapeView shape;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shapes);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.shapes, menu);
        return true;
    }
    public void next(View view)
    {
        i++;
        shape=(ShapeView)findViewById(R.id.shape_view);
        shape.nextshape(i);
    }

     }

here nextshape(i) is a method defined in a custom view class.And the following is the message in logcat
Logcat :
     08-19 12:09:15.348: E/AndroidRuntime(812): FATAL EXCEPTION: main
     08-19 12:09:15.348: E/AndroidRuntime(812): java.lang.IllegalStateException: Could not       execute method of the activity
     08-19 12:09:15.348: E/AndroidRuntime(812):     at     android.view.View$1.onClick(View.java:2072)
     08-19 12:09:15.348: E/AndroidRuntime(812):     at android.view.View.performClick(View.java:2408)
     08-19 12:09:15.348: E/AndroidRuntime(812):     at android.view.View$PerformClick.run(View.java:8816)
     08-19 12:09:15.348: E/AndroidRuntime(812):     at android.os.Handler.handleCallback(Handler.java:587)
     08-19 12:09:15.348: E/AndroidRuntime(812):     at android.os.Handler.dispatchMessage(Handler.java:92)
     08-19 12:09:15.348: E/AndroidRuntime(812):     at android.os.Looper.loop(Looper.java:123)
     08-19 12:09:15.348: E/AndroidRuntime(812):     at android.app.ActivityThread.main(ActivityThread.java:4627)
     08-19 12:09:15.348: E/AndroidRuntime(812):     at java.lang.reflect.Method.invokeNative(Native Method)
     08-19 12:09:15.348: E/AndroidRuntime(812):     at java.lang.reflect.Method.invoke(Method.java:521)
     08-19 12:09:15.348: E/AndroidRuntime(812):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
     08-19 12:09:15.348: E/AndroidRuntime(812):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
     08-19 12:09:15.348: E/AndroidRuntime(812):     at dalvik.system.NativeStart.main(Native Method)
     08-19 12:09:15.348: E/AndroidRuntime(812): Caused by: java.lang.reflect.InvocationTargetException
     08-19 12:09:15.348: E/AndroidRuntime(812):     at org.example.m_pustika.Shapes.next(Shapes.java:29)
     08-19 12:09:15.348: E/AndroidRuntime(812):     at java.lang.reflect.Method.invokeNative(Native Method)
     08-19 12:09:15.348: E/AndroidRuntime(812):     at java.lang.reflect.Method.invoke(Method.java:521)
     08-19 12:09:15.348: E/AndroidRuntime(812):     at android.view.View$1.onClick(View.java:2067)
     08-19 12:09:15.348: E/AndroidRuntime(812):     ... 11 more
     08-19 12:09:15.348: E/AndroidRuntime(812): Caused by: java.lang.NullPointerException

xmlfile:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".Shapes" >

    <org.example.m_pustika.ShapeView
        android:id="@+id/shape_view"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/next_button" />

    <Button
        android:id="@+id/next_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="@string/next_button"
        android:onClick="next" />

     </RelativeLayout>

CustomView:
   public class ShapeView extends View {

Paint cPaint;
Random r=new Random();
int n=3;
public ShapeView(Context context,AttributeSet attrs) {
    super(context);
    // TODO Auto-generated constructor stub
    cPaint = new Paint();
    cPaint.setColor(Color.BLACK);

}
public void nextshape(int n)
{
    this.n=n;
}

public void onDraw(Canvas canvas)
{
    Log.d("n","n= " +n);
    for(int i=1;i<=n;i++)
    {
        int x=r.nextInt(canvas.getWidth()-50);
        int y=r.nextInt(canvas.getHeight()-200);
        canvas.drawCircle(x, y, 10, cPaint);
    }
}

}

A: I guess you are shape object is null
You probably want to do
          ShapeView shape = new ShapeView(Shapes.this);

to initalize and then call shapenext
Add appropriate constructors also
Edit:
As a side note to refresh or update view call invalidate() on your view or call postInvalidate() from a thread (non ui thread).

A: I think you called the method next() before running the onCreate() method.
Try this instead of you current next() method:
public void next(View view)
{
    setContentView(R.layout.activity_shapes);
    shape=(ShapeView)findViewById(R.id.shape_view);
    shape.nextshape(i);
}

A: Try this once. remove shape=(ShapeView)findViewById(R.id.shape_view); from next()
  @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_shapes);
            shape=(ShapeView)findViewById(R.id.shape_view);

        }

or please make a call of next() in onCreate()


text:
Q: The sound of cutting board I have been searching for a word (verb/adjective) to describe the sound of a knife cutting on a wooden board for a while fruitlessly. What I ended up writing is "intermittent cutting board thumps" which, in my opinion, is pretty rubbish. The word "thud" also doesn't apply as I'm trying to describe a sound that is not dull; the sound a knife makes against a cutting board is pretty sharp and quick.
Any suggestions? Thanks!


text:
Q: Como listar el primer registro por grupo en MYSQL Tengo una consulta que me trae el estado de la asistencia del alumno por cada asistencia tomada en la clase. (No se si me deje entender ,les dejo un ejemplo):
SELECT
aac.codAlumno,CONCAT(a.apePaterno,' ',a.apeMaterno,', ',a.nombres) as nombres, aac.estado, aac.codClase
FROM asistencia_alumno_clase aac
INNER JOIN clases c ON aac.codClase = c.id
INNER JOIN oeraae_estandar.alumnos a ON aac.codAlumno = a.codAlumno_fk
WHERE c.periodo = '20201'
AND c.codHorario = '19464'
AND aac.codAlumno != '08115218'
ORDER BY nombres asc, c.id asc, aac.estado desc;

En la clase 1 se tomo 3 asistencias
En la clase 7 se tomo 3 asistencias
En la clase 10 se tomo 2 asistencias
 codigo       Nombre               estado   codClase
35482522I   CASAS ZAPATA, CARLOS      1         1
35482522I   CASAS ZAPATA, CARLOS      0         1
35482522I   CASAS ZAPATA, CARLOS      0         1
35482522I   CASAS ZAPATA, CARLOS      0         7
35482522I   CASAS ZAPATA, CARLOS      0         7
35482522I   CASAS ZAPATA, CARLOS      0         7
35482522I   CASAS ZAPATA, CARLOS      1         10
35482522I   CASAS ZAPATA, CARLOS      0         10

Pero lo que necesito que me liste es esto (El primer resultado por clase)
 codigo       Nombre               estado   codClase
35482522I   CASAS ZAPATA, CARLOS      1         1
35482522I   CASAS ZAPATA, CARLOS      0         7
35482522I   CASAS ZAPATA, CARLOS      1         10

A: Dado que utilizas mySQL 8 o superior, puedes valerte de

*

*CTE para hacer la consulta legible

*Funciones de ventana, por ejemplo rank() o row_number() para particionar y numerar las filas del resultado y finalmente quedarte solamente con la primera fila de cada partición.

Por ejemplo:
with
Base as (
SELECT   aac.codAlumno
       , CONCAT(a.apePaterno,' ',a.apeMaterno,', ',a.nombres) as nombres
       , aac.estado
       , aac.codClase
       , row_number() over (partition by aac.codAlumno, aac.codClase order by aae.estado desc) NumeroFilaAlumno
  FROM asistencia_alumno_clase aac
       INNER JOIN clases c ON aac.codClase = c.id
       INNER JOIN oeraae_estandar.alumnos a ON aac.codAlumno = a.codAlumno_fk
 WHERE c.periodo = '20201'
   AND c.codHorario = '19464'
   AND aac.codAlumno != '08115218'
ORDER BY nombres asc, c.id asc, aac.estado desc
)
select   CodAlumno
       , nombres
       , estado
       , codClase
  from Base
 where NumeroFilaAlumno = 1
 order by Nombres, CodClase


text:
Q: How to find the output power of antenna including distance? I have a PCB and antenna (1) attached to it at the output. Now I would like to measure the output power of the antenna (1) using antenna (2) which is at a distance of D.
I have the readings of the received power from antenna 2, distance, gain, antenna factor,  and the frequency.
Can anyone explain how to calculate the output power at the antenna 1 using above mentioned parameters?

A: The Friis transmission path-loss equation in decibels is this: -
$$\color{red}{\boxed{\text{Path loss (dB) = 32.45 + } 20log_{10}(f) + 20log_{10}(d)}}$$
Where \$f\$ is in MHz and \$d\$ is in kilometres.
So, if you take readings at various distances (2 might be enough) you should be able to factor out all the unknowns and get your answer. Clearly you should know the frequency in MHz so that part of the equation turns into a constant.
If you can gather this data but can't get an answer, report back.

A: I hate to be the Cassandra here, but what you're trying to do is fraught with sources of error.

*

*To start off, you need to know accurately the performance of your receive antenna, gain as function of receive angle, in both azimuth and elevation, at your frequency of interest.  You might be able to simplify this part of the problem by constraining the transmit and receive antennas to be in the same plane, in which case you would only need to know the receive antenna pattern along a single azimuth cut through the antenna pattern.

Calibrated antennas that provide this type of information are available commercially (such as standard gain horns) but they are not cheap.

*Next, you need to make sure that you are only measuring the direct path from the transmit to the receive antenna.  Any reflections from objects alongside of or behind your transmit and receive antennas will corrupt you measurements.  This where RF absorber comes in.  This is judiciously placed around (but not in front of) your transmit and receive antennas to absorb and attenuate any RF energy that's not in the direct path between the antennas.

*You need to make sure there are no other sources of RF energy that could corrupt your measurement.  Even a cell phone could create an error.

*Along with #3, you need to make sure that your receiver properly filters and/or bandwidth limits the incoming frequency so that just the energy from the transmit antenna is being processed.
More as I think of them...
Added some cartoons
Here's en example illustrating the first problem.  These two cases are going to measure significantly different amounts of power at Ant 2. They can be normalized, but only if you know the radiation pattern of both antennas.

This cartoon shows how reflections (multipath) can impact the measured power level.


text:
Q: VB script + replcae word in txt code , that find in the txt file the line that start with the : THIS_LOCATION
and replace the OFF_LINE with NEW
if InStr(strText  , 'THIS_LOCATION' )  then
strNewText = Replace(strText, "OFF_LINE", "NEW")
End if
the VB script failed on the line :
if InStr(strText  , 'THIS_LOCATION' )
what wrong?
THX
yael

A: You need double quotes:
If InStr(strText, "THIS_LOCATION") Then


text:
Q: Worklight Analytics Operational Console empty I'm trying to use Worklight Analytics features for App. I have separated servers for analytics and worklight console.
I have tried the configuring of analytics in 3 way:

*

*in worklight.properties:
wl.analytics.logs.forward=true
wl.analytics.url=http://[host]:[port]/analytics/data

*in initOptions.js:
{
   analytics: {enable: true, url: 'http://[host]:[port]/analytics/data'}
}

*in server's config:
<jndi name="[context]/wl.analytics.url" value="http://[host]:[port]/analytics/data" />
<jndi name="[context]/wl.analytics.logs.forward" value="true" />

Operational Analytics page has not data.

A: Actually problem is related to queues. If you want to have results right away also consider adding this, as jndi properties in worklight server config (in case of Liberty):
<jndiEntry jndiName="wl.analytics.queues" value='"1"'/>
<jndiEntry jndiName="wl.analytics.queue.size" value='"0"'/>

A: This answer is based on that the Windows 7 MFP 6.3 server is installed on top the default WAS Libery Core.
After you setting up the analytic ear file, you also need to forwarding the Data to the analytic Console.  Furthermore, you have to add in the user name and password for the ear because the analytic ear file has security on.  Without the username and password (which is the one for the WAS that you setup in the Configuration Tools), with just the first 3 lines, you will still see no data.
One other very important point, notice that there is a mfp/ in the jndiName.  Yours might name differently, as that's the dummy project that we created in the Configuration Tools to represent the runtime.  You could have called it anything else.  Replace "mfp/" here with whatever you call your runtime. That's the same contextRoot that you would have used in the app settings to find the MFP server.
Setup the analytic console to forward the data

*

*The worklight.analytics.url property needs to be set such that the mfp server knows where to send the data to

*The analytics EAR file was enabled with security, specify the username and passwords so the
mfp server could send data to the analytics console

Add the following lines in the server.xml as follow.  Save the file and Restart the MFP standalone server to take effect.
<jndiEntry jndiName="mfp/wl.analytics.queue.size" value="1"/>
<jndiEntry jndiName="mfp/wl.analytics.url" value="http://localhost:9080/worklight-analytics-service/data"/>
<jndiEntry jndiName="mfp/wl.analytics.console.url" value="http://localhost:9080/worklight-analytics/console"/>
<jndiEntry jndiName="mfp/wl.analytics.username" value="demo"/>
<jndiEntry jndiName="mfp/wl.analytics.password" value="demo"/>

A: Worklight queues the data before sending it. You may have analytics data waiting to be sent but the queue has not yet filled. Try setting the following property:
wl.analytics.queue.size=1


text:
Q: Generating progress bar based on variable value I'm making a very simple text-based pet game, and I need a way for the pet's "food meter" to increase. The user can open a menu where they can select "FEED" by writing it out, and this needs to add 1 bar to the food meter.
I have every version of the food meter set up as separate variables, like this:
statfull = "[▇▇▇▇▇▇▇▇▇▇]"
stat9 = "[▇▇▇▇▇▇▇▇▇_]"
stat8 = "[▇▇▇▇▇▇▇▇__]"
stat7 = "[▇▇▇▇▇▇▇___]"
stat6 = "[▇▇▇▇▇▇____]"
stat5 = "[▇▇▇▇▇_____]"
stat4 = "[▇▇▇▇______]"
stat3 = "[▇▇▇_______]"
stat2 = "[▇▇________]"
stat1 = "[▇_________]"
statempty = "[__________]"

If the food bar's variable currently prints stat7, how can I make it go up a level (in this case change to stat8) when the user inputs the word "FEED"?
By which I mean:
currentFStat = stat7
print("Your food bar is at " + currentFStat)

Which would look like
Your food bar is at [▇▇▇▇▇▇▇___]
I want the player to be able to input "FEED" when prompted, and then have the program change the value of currentFStat to stat8 so that when it
print("Your food bar is at " + currentFStat)

the output would now be
Your food bar is at [▇▇▇▇▇▇▇▇__]
The only way I can think of doing it is having an if statement for every possible state it could be at, and if it's that state, changing to the next, but that seems way too tedious and I'm sure there's an easier way I'm missing...

A: How about instead representing the food level of your pet with an integer variable:
foodlevel = 5 # for example

If user FEEDs your pet, increment foodlevel. Decrement otherwise.
Use foodlevel to create your health meter on the go:
>>> '▇' * foodlevel + '_' * (10 - foodlevel)
'▇▇▇▇▇_____'

I've assumed that 10 is "full", while 0 is "empty". You can modify this design as needed.


text:
Q: How can I avoid Guice boiler-plate code How do I avoid guice boiler plate?
With Spring, I usually use @AutoWired and thats it, no createInjector, no injectMemebers(this). Is there a way to avoid those while using giuce? Is there some global settings that I can do so I'll automatically have all things injected in app and test classes?
public class AccountDaoTest {
    @Before
    public void setup() {
        Injector injector;
        injector = Guice.createInjector();// I don't want this boiler-plate
        injector.injectMembers(this);
    }

    @Inject
    AccountDAO accountDao ;

    @Test
    public void persist(){
        Account ac =  new Account();
        ac.setName("AccountName");
        ac.setAccountType(AccountType.Hospital);
        accountDao.createAccount(ac);

    }
}

A: I guess you are looking for something like the SpringJunitRunner for guice: https://github.com/caarlos0/guice-junit-test-runner
@RunWith(GuiceTestRunner.class)
@GuiceModules(MyModule.class)
public class MyTest {
   @Inject
   private Something something;

   @Test
   public void testItWorks() throws Exception {
      Assert.assertThat(something.doSomething(), CoreMatchers.notNullValue());
   }
}

A: As Jan suggested, you can cope with manual Injector construction using test runner. For removing the need of having single-use modules with test bindings there's new 'Bound Fields' feature starting from Guice 4 (see the wiki page)
Not sure both things can work together out of the box, but it definitely worth trying.


text:
Q: Separating delimited input into variables using >> operator I am a beginner in C++ and I'm trying to experiment with delimited input. I use the following code to get some delimited data and then to separate it out.
#include <iostream>
#include <string>

int main()
{
    int n1,n2,n3; char data,c;
    while (std::cin >> data >> c >> n1 >> c >> n2 >> c >> n3 && c == ','){
        std::cout << "Entered loop" << "\n";
        std::cout << "Value:" << data << "\n";
        std::cout << "Value:" << n1 << "\n";
        std::cout << "Value:" << n2 << "\n";
        std::cout << "Value:" << n3 << "\n";
        std::cout << std::endl;
        }
}

Input here is something like: A,1,2,3
But if I replace the char data with std::string data like so:
#include <iostream>
#include <string>

int main()
{
    int n1,n2,n3; std::string data; char c;
    while (std::cin >> data >> c >> n1 >> c >> n2 >> c >> n3 && c == ','){
        std::cout << "Entered loop" << "\n";
        std::cout << "Value:" << data << "\n";
        std::cout << "Value:" << n1 << "\n";
        std::cout << "Value:" << n2 << "\n";
        std::cout << "Value:" << n3 << "\n";
        std::cout << std::endl;
        }
}

With input like : ABCD,1,2,3
There is no output which coupled with the debugging "Entered loop" output means that the while loop condition is never fulfilled.
What's going wrong here when I replace char with a string.

A: A char is a single character, one symbol; no less, no more.
A std::string may hold zero or more characters.
When operator>> uses a char variable, it reads only one single character.
When operator>> uses a std::string variable, it first ignores white space characters, then reads characters until a white space character is read.
Edit 1: std::getline and std::string
When reading in text data, prefer to use std::getline with std::string and specify a terminating character.
For example:
std::getline(cin, data, ',');

The above will read from std::cin until a ',' is read, placing everything except the ',' into the data variable.


text:
Q: In Wordpress, can you get the post ID from a comment ID In Wordpress, given the ID of a comment is it possible to get the ID of the post that the comment is attached to?
For example, comment with ID 1642 is attached to post with ID 172
Thanks

A: You could use get_comment() https://codex.wordpress.org/Function_Reference/get_comment  Make sure to read the parameters for the function in the above link.  You must pass a variable containing an integer with this function.
<?php
    $my_id = 7;
    $comment_id_7 = get_comment( $my_id );
    $comment_post_id = $comment_id_7->comment_post_ID ;
?>