text:
Q: HTTP Request in FOR loop is not executing I have a script that is meant to execute a number of HTTP requests and then store the data retrieved:
var ParseXbrl = require('parse-xbrl')
var request = require('request');
var tickers = ['AAPL','F','TSLA','GOOG','MSFT'];

var json = "";
var XML = "";
var Data = [];

for(z in tickers){
request
.get('https://www.valuespreadsheet.com/iedgar/results.php?stock=' + tickers[z] + '&output=json')
.on('response', function(response) {
   response.on('data', function(chunk){
       json += chunk;
   });
   response.on('end',function(){
       json = JSON.parse(json);

       request
           .get(json.filings[2].instanceUrl)
           .on('response', function(response) {
               response.on('data', function(chunk){
                   XML  += chunk;
               });
               response.on('end',function() {
                   ParseXbrl.parseStr(XML).then(function(parsedDoc) {
                     console.log(parsedDoc);
                    var x = 0;
                       for(i in parsedDoc){
                            Data[tickers[z]][x]=parsedDoc[i];
                            x++
                            console.log(Data);
                       }
                   });
               });
               });
             });
   });
 }

The above script returns the following error code:
undefined:1
[object Object]{
 ^

SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
    at IncomingMessage.<anonymous> (Test.js:18:24)
    at emitNone (events.js:110:20)
    at IncomingMessage.emit (events.js:207:7)
    at endReadableNT (_stream_readable.js:1047:12)
    at _combinedTickCallback (internal/process/next_tick.js:102:11)
    at process._tickCallback (internal/process/next_tick.js:161:9)
[Finished in 0.871s]

However when I change the array tickers such that it contains only one value e.g. tickers = ['AAPL'] the code works (what ticker I use is irrelevant).
I did some testing and noticed that when I added console.log(z); to my code it logged both 0 and 1 before it attempted to retrieve any data. This leads me to suspect that my code is looping through for(z in tickers) before it executes a request

A: The JSON string you are building is going to be invalid after the first request. If the API is returning an object, you are going to end up with:
"{ response1: 'foo'}{ response2: 'bar}{ etc }"

Which JSON.parse will error on, since it is not a single object (and that's what JSON.parse expects). If it's an array you have a similar problem:
"[responseArray1][responseArray2]"

Again, that will not parse because JSON.parse expects a single object. Brett is correct in his comment, you need to move where your json variable is defined:
.on('response', function(response) {
   var json = "";
   response.on('data', function(chunk){
       json += chunk;
   });

That way you won't be concatenating multiple request responses.
The same also applies for XML = '';


text:
Q: "SELECT DISTINCT field_name from table" Django using raw sql How can I run SELECT DISTINCT field_name from table; SQL query in Django as raw sql ?

When I try to use Table.objects.raw("""SELECT DISTINCT field_name from table"""), I got an exception as

InvalidQuery: Raw query must include the primary key

A: If you don't need the model instances (which are useless if you want a single field), you can as well just use a plain db-api cursor:
from django.db import connection
cursor = connection.cursor()
cursor.execute("select distinct field from table")
for row in cursor:
    print(row[0])

But for your example use case you don't need SQL at all - the orm has values and values_list querysets and a distinct() modifier too:
queryset = YourModel.objects.values_list("field", flat=True).order_by("field").distinct()
print(str(queryset.query))
# > 'SELECT DISTINCT `table`.`field` FROM `table` ORDER BY `table`.`title` ASC'
for title in queryset:
    print(title)

NB :
1/ since we want  single field, I use the flat=True argument to avoid getting a list of tuples
2/ I explicitely set the ordering on the field else the default ordering eventually defined in the model's meta could force the ordering field to be part of te generated query too.

A: Looks like you have to use some workaround
select field_name, max(id)
from table_name
group by field_name;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Should I implement father interface in the child? If I'm writing a class that inherits from another, which implement an interface, should I implement this interface in the child?
class FatherClass implements MyInterface
{
    ...
}

public class ChildClass extends FatherClass { // Should I implement MyInterface here?
    ...
}

A: *

*Implemented interfaces in Parent class are just inherited

*so there's no need to copy and paste "implements SomeInterface" on the children classes. It's not necessary, smarter.

*Having both the child and the parent implement the same Interface has no additional effect.

*It is equivalent to having the parent only implement that interface.


text:
Q: how to create a dataset for multi-output regression with sliding window approach I want to build normal DNN model, I have huge data with X_train= 8000000x7 and y_train=8000000x2.
How to create a dataset with sliding window of 100 data points to feed the neural network.
If I use a customized dataset using following code, I have a problem of allocation due to large dataset.
def data_set(x_data, y_data, num_steps=160):
    X, y = list(), list()
    # Loop of the entire data set
    for i in range(x_data.shape[0]):
        # compute a new (sliding window) index
        end_ix = i + num_steps
        # if index is larger than the size of the dataset, we stop
        if end_ix >= x_data.shape[0]:
            break
        # Get a sequence of data for x
        seq_X = x_data[i:end_ix]
        # Get only the last element of the sequency for y
        seq_y = y_data[end_ix]
        # Append the list with sequencies
        X.append(seq_X)
        y.append(seq_y)
    # Make final arrays
    x_array = np.array(X)
    y_array = np.array(y)
    return x_array, y_array

So, in order to avoid this is there any dataset generator I can use with sliding window for feeding into DNN.
Thanks in advance

A: You can use dataset.window method to achieve that.
dataset = tf.data.Dataset.from_tensor_slices((X_train, y_train))
stride = 1
dataset = dataset.window(batch_size, shift=batch_size-stride, drop_remainder=True)


text:
Q: Why does it take longer to toggle graphics after a selection is made from a combo box? I have a WPF app that draws a compass. There is a large ring with tick marks and labels. I have a checkbox that toggles the compass graphics on and off. When I first start up the app, the compass turns on and off instantly.
Meanwhile, I have a combo box that grabs some data from a local database and uses that to render some overlay graphics. After using this combo box, the compass graphics no longer toggle quickly. In fact, the UI completely freezes for about 4 seconds whenever I click the checkbox.
I attempted to profile my app using Window Performance Profiling Tool for WPF. When I activated the checkbox, not only did my app freeze, so did the profiler. The graphs "catched up" afterward, but this tells me something must be seriously wrong.
I've managed to nail down that the problem graphics are the tick marks (not the numeric labels). If I eliminate them, the freezing problem stops. If I cut them down from 360 to, say, 36, the app still freezes, but for less time. Again, no matter how many tick marks I have, they toggle instantly when the app first starts.
My question is, How do I figure out why the toggle for my compass graphics goes from instant to horribly slow? I've tried extensive profiling and debugging, and I just can't come up with any reason why setting the Visibility on some tick marks should ever cause the app to freeze.
Edit
Okay, I've stripped everything out of my app to just the bare essentials, zipped it up, and uploaded it to Sendspace. Here is the link (it's about 143K):
http://www.sendspace.com/file/n1u3yg
[Note: don't accidentally click the banner ad, the real download link is much smaller and lower on the page.]
Two requests:

*

*Do you experience the problem on your machine? Try opening Compass.exe (in bin\Release) and clicking the check box rapidly. The compass tick marks should turn on and off with no delay. Then, select an item from the combo box and try rapidly clicking the check box again. On my machine, it's very laggy, and after I stop rapid-fire clicking, it takes a few seconds for the graphics to catch up.

*If you do experience the lag, do you see anything in the code that could be causing this odd behavior? The combo box is not connected to anything, so why should selecting an item from it affect the future performance of other graphics on the window?

A: Although ANTS didn't indicate a particular performance 'hotspot', I think that your technique is slightly flawed as it seems that every tick has a ViewModel that is responsible for handling an individual tick, and you are individually binding those ticks to the view. You end up creating 720 view models for these ticks that fire the a similar event each time the entire compass is shown or hidden. You also create a new LineGeometry every time this field is accessed.
The recommended approach for WPF in a custom drawn situation like this is to use a DrawingVisual and embrace the retained mode aspect of WPF's rendering system. There are several googleable resources that talk about this technique, but the gist is to declare a compass class inherits from FrameworkElement, and some smaller classes that inherit from DrawingVisual and use that to render the compass. With this technique, you can still have a ViewModel drive the compass behavior, but you wouldn't have individual viewmodels for each part of the compass. I'd be inclined to decompose the compass into parts such as bezel, arrow, sight, etc... but your problem may require a different approach.
class Compass : FrameworkElement
{
    private readonly List<ICompassPart> _children = new List<ICompassPart>();

    public void AddVisualChild(ICompassPart currentObject)
    {
        _children.Add(currentObject);
        AddVisualChild((Visual)currentObject);
    }

    override protected int VisualChildrenCount { get { return _children.Count; } }

    override protected Visual GetVisualChild(int index)
    {
        if (index < 0 || index >= _children.Count) throw new ArgumentOutOfRangeException();

        return _children[index] as Visual;
    }

    override protected void OnRender(DrawingContext dc)
    {
        //The control automatically renders its children based on their RenderContext.
        //There's really nothing to do here.
        dc.DrawRectangle(Background, null, new Rect(RenderSize));
    }
}

class Bezel : DrawingVisual
{
   private bool _visible;

   public bool Visible {
   {
     get { return _visible; }
     set
     {
        _visible = value;
        Update();
     }
   }

   private void Update()
   {
       var dc = this.RenderOpen().DrawingContext;
       dc.DrawLine(/*blah*/);
       dc.Close();
   }
}


text:
Q: Opening another tab using selenium with send_keys won't work when a tab is manually opened, The problem :
Simply start a .py with: driver = webdriver.Chrome() Open another tab manualy and use :
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)

It won't switch tabs.
If you open the tab using :
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + "t")

The problem isn't there, but won't fix my issue. I need to open tabs manualy and switch later using selenium.
Using the command tab send_key works fine when using firefox.
Any suggestions?
Example 1:
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()

# Open 2 extra tabs
driver.get("http://www.google.com")
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + "t")
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + "t")

# Switch tabs
time.sleep(2)
print "Press TAB"
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)
time.sleep(2)
print "Press TAB"
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)
time.sleep(2)
print "Press TAB"
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)

Example 2:
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.get("http://www.google.com")

raw_input("Open 2 tabs manually")

# Switch_to_window won't help
#firstpage = driver.window_handles[0]
#driver.switch_to_window(firstpage)

time.sleep(2)
print "Press TAB"
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)
time.sleep(2)
print "Press TAB"
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)
time.sleep(2)
print "Press TAB"
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)

Example 1 Works. In example 2 the send_keys is ignored.
Update:
If you switch to the handle you want to focus use:
driver.execute_script('alert("Focus window")')
driver.switch_to.alert.accept()


text:
Q: Can I restart the USB stack on Windows 7? I am developing a USB 3.0 audio device. However, the current state of the firmware is so buggy, that often Windows crashes or stops enumerating new devices, stops detecting disconnected devices, etc.
Is there a way to restart the USB 3.0 hub? Or the whole USB bus?


text:
Q: If my RxJava 2 call returns a Single or Maybe, do I still need to use CompositeDisposable? Suppose I have
Disposable disposable = signOutUser()
            .subscribe((Response<ResponseBody> response) -> {
                if (response.isSuccessful()) {
                    Intent intent = new Intent(view.getContext(), SignInUserActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
                    view.getContext().startActivity(intent);
                    ((FragmentActivity) view.getContext()).finish();
                }
            }, (Throwable ex) -> {
                Log.e(TAG, "signOutUser: " + ex.getMessage());
            });

where signOutUser() returns Single<Response<ResponseBody>>. When signOutUser() is successful, there is an Intent and the current activity is finished(). Otherwise, it fails, possibly due to network error, so there is no intent and the user stays on current activity.
Since this isn't something to observe (it's a one time event, success or fail), and IF the user successfully logs out, then onDestroy will be called which calls compositeDisposable.clear() which clears all the disposables. So then I'm adding a Disposable and immediately that Disposable is being disposed or cleared.
My question is, do I event need to use Composite Disposable? Do I immediately call disposable.dispose() after subscribe? Do I set anything to null? Do I not use Single?

A:
Do I event need to use Composite Disposable?

Yes, you should always use composite disposable (or normal Disposable), and unsubscribe from it when the time comes (onDestroy/onStop whathere you need). The reason for it is that the network call may be finished after you have closed activity, which will result in memory leaks or even crashes (because context will be null).

Do I immediately call disposable.dispose() after subscribe?

No, because this would result in the call to never return a result. If you dispose immediately after calling subscribe, you will never get a response from it. Read about what happens after you dispose an observable.

Do I set anything to null?

No need to. If your single has finished, you don't have to do anything about it. And there won't be any problems that it is still in CompositeDisposable (even if you call dispose on it). Actually, after the Single is finished, RxJava will dispose the observable itself to safe some memory.

Do I not use Single?

Yes, this is perfect situation to use it. You want to perform a single request, no need to use Observable.

A: Yes, you should use a disposable. Consider the case when the response is received from your API call, but the context is gone for whatever reason. Then, all your code where you are getting the context and calling methods on it would cause an NPE. Disposing properly of this Single would help you avoid this crash.


text:
Q: Swift 3 - Limit TextField to alphanumeric (with whitespace and hypens) Want to limit Textfield input to only A-Z,a-z,0-9, " " and -. Currently have:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
    {
        if self.isNumericTextInput{
            let allowedCharacters = CharacterSet.decimalDigits
            let characterSet = CharacterSet(charactersIn: string)
            if allowedCharacters.isSuperset(of: characterSet) && returnFlag{
                return true
            } else{
                return false
            }

        } else{
            // Allow only alphanumerics, whitespace and hyphens
        }
        return
    }

A: Though it's late to answer, but it might be useful to someone.
Swift 3:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    /// 1. replacementString is NOT empty means we are entering text or pasting text: perform the logic
    /// 2. replacementString is empty means we are deleting text: return true
    if string.characters.count > 0 {
        var allowedCharacters = CharacterSet.alphanumerics
        allowedCharacters.insert(charactersIn: " -") // "white space & hyphen"

       let unwantedStr = string.trimmingCharacters(in: allowedCharacters)
       return unwantedStr.characters.count == 0
    }

    return true
}

Note: This will work for pasting strings into the text field as well. Pasted string will not be displayed in text field if it contains any unwanted characters.

A: Try this:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let characterSet = CharacterSet(charactersIn: string)

    let allowedCharacters = (self.isNumericTextInput
        ? CharacterSet.decimalDigits
        : CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 -"))

    return allowedCharacters.isSuperset(of: characterSet) && returnFlag
}


text:
Q: What determines whether runtime_error is_nothrow_copy_constructible? I have an implementation of an exception class that inherits from std::runtime_error:
class custom_error : public std::runtime_error {
public:
  explicit custom_error(const std::string &arg)
      : std::runtime_error(arg){};

  ~custom_error() noexcept override = default;
};

This implementation is, as far as possible, identical to the libstdc++ implementation of other subclasses of std::runtime_error.
When running clang-tidy over this code (in some circumstances - see below), the following warning is emitted:
warning: thrown exception type is not nothrow copy constructible [cert-err60-cpp]

The relevant information about this check is available here.
I believe I understand the information on that page.
In particular, I believe the relevant information is that a std::runtime_error, and subclasses thereof, should have the trait is_nothrow_copy_constructible.
I have trouble reconciling the following.
Scenario 1:
The following code on compiler explorer demonstrates that the class is_nothrow_copy_constructible when compiled with gcc 5.x and newer, but not when compiled with gcc 4.x.
Scenario 2:
On my laptop, running Ubuntu 18.04, the same class also is_nothrow_copy_constructible when compiled with gcc 5, gcc 7, clang 3.8, clang 5 and clang 6, all when linked against libstdc++.so.6.0.25.
Scenario 3:
On travis-ci running an instance of Ubuntu 14.04, I cannot find a single configuration in which the same class is_nothrow_copy_constructible.
This includes using gcc 5, gcc 6, gcc 7, clang 4 and clang 5, linked against libstdc++.so.6.0.25.
Here is a specific travis build log demonstrating the test failure, which uses gcc 5, linked against libstdc++.so.6.0.25.
 (custom_error is renamed simply Exception.)
The question:
Can someone explain to me what could be determining whether the class is_nothrow_copy_constructible?
To me, the above demonstrates that the answer can differ when the:

*

*implementation

*compiler, and

*standard library version

are identical.


text:
Q: Django how to compare correctly against django.utils.timezone.localtime and PostgreSQL time with time zone? I have a legacy PostgreSQL table with time with time zone column.
in models.py I have the filed set to models.TimeField
I want to compare accessed Django.utils.timezone.localtime() with db_field_time_with_time_zone
I have tried below:
# let's say now=20:00 and db_field_time_with_time_zone=16:00
now = timezone.localtime()
data = timezone.datetime.combine(timezone.localdate(), db_field_time_with_time_zone)
self.assertTrue(now > data) # I get False...

In the raw PostgreSQL column it's stored as 16:00:00+09:00
but when I retrieve data using python manage.py shell it returns 16:00:00+00:00 and I also think this is the cause of this problem.
In my settings.py
TIME_ZONE = 'Asia/Tokyo'
USE_TZ = True


text:
Q: MySQL adds broken comment script after each line Every time I try to create a table using MySQL Workbench 6.3 CE it adds "broken" comments at the end of the script.
Example:
I am trying to create a table called "user". This is what the table should look like:

However when I click the apply button, the script generates incorrectly:
CREATE TABLE `user` (
  `userid` INT NOT NULL AUTO_INCREMENT COMMENT '',
  `record_status` INT NOT NULL DEFAULT 1 COMMENT '',
  `createdby` VARCHAR(75) NOT NULL COMMENT '',
  `createddate` DATETIME NOT NULL COMMENT '',
  `updatedby` VARCHAR(75) NULL COMMENT '',
  `updateddate` DATETIME NULL COMMENT '',
  `username` INT NOT NULL COMMENT '',
  `password` VARCHAR(75) NULL COMMENT '',
  `firstname` VARCHAR(75) NULL COMMENT '',
  `lastname` VARCHAR(75) NULL COMMENT '',
  `email` VARCHAR(75) NULL COMMENT '',
  `facebook_userid` VARCHAR(75) NULL COMMENT '',
  `email_verified` VARCHAR(75) NULL COMMENT '',
  PRIMARY KEY (`userid`, `username`)  COMMENT '');

The comment in this line should not be there, so the code should be:
PRIMARY KEY (`userid`, `username`));

and the code executes when I paste it into an editor and remove this comment. However I create massive databases daily. (Each with +- 15 tables). I can't keep doing this for each table as it is time consuming.
How can I disable this feature that adds the comments to the script?
I don't need them in my databases

A: This is a bug on MySQL Workbench >=6.3.* reported in these cases #76578 and HERE.
This is what ALTER TABLE do:

*

*It adds a COMMENT '' on every line of the SQL Script to apply:

I recommended you to downgrade your MySQL Workbench to 6.2.* until they fix this.
Tested in Ubuntu LTS 14.04 and MySQL Workbench 6.3.4.0.

A: Remove all occurence of COMMENT ''. Feel free to leave a comment under this bug. We're working on it to fix it, so stay tuned for upcoming release.

A: Downgrade to 6.2; 6.3 has the bug you describe.


text:
Q: How to open a view using a button So I have a tabbed application, and I'm really new to xCode. I created a first view.

So I need help with code for the Quotes button to help lead me to the tab bar controller. Thanks

A: It looks like you have a programmatic ("custom") segue in the view controller. This probably isn't what you want.
In Interface Builder, select that segue and in the Attributes Inspector, change the kind of segue to "Show (e.g. Push)".

A: First of all, it looks like you're using a custom segue and it looks like you don't actually need it in your situation.
There is a simple solution by changing the segue Kind to Show (e.g. push). This will simply show the connected view controller on top of your first viewcontroller.
This won't allow you to navigate back to the first view controller. If you want to do so, click on the first view controller in your storyboard and go to Editor > Embed in > Navigation controller.
This will automatically add a navigation controller which will manage the default navigation for you.

A: let storyboard = UIStoryboard(name: "StoryboardName", bundle: nil)
let tb = storyboard.instantiateViewControllerWithIdentifier("Storyboard ID") as! UITabBarController
self.presentViewController(tb, animated: true, completion: nil)

To return from TabBarController
self.dismissViewControllerAnimated(true, completion: nil)

A: click on button press and hold control and drag it to another view controller some actions will pop than select the first option show and you are ready to go.


text:
Q: How my web crawler(python, Scrapy, Scrapy-splash) can crawl faster? Develop Environment:

*

*CentOS7

*pip 18.1

*Docker version 18.09.3, build 774a1f4

*anaconda Command line client (version 1.7.2)

*Python3.7

*Scrapy 1.6.0

*scrapy-splash

*MongoDB(db version v4.0.6)

*PyCharm

Server Specs:

*

*CPU ->
processor: 22,
vendor_id: GenuineIntel,
cpu family: 6,
model: 45,
model name: Intel(R) Xeon(R) CPU E5-2430 0 @ 2.20GHz

*RAM -> Mem: 31960

*64 bit

Hello.
I'm a php developer, and this is my first python project. I'm trying to use python because I heard that python has many benefits for web crawling.
I'm crawling one dynamic web site, and I need to crawl around 3,500 pages in every 5-15 seconds. For now, mine is too slow. It is crawl only 200 pages per minute.
My source is like this:
main.py
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
from spiders.bot1 import Bot1Spider
from spiders.bot2 import Bot2Spider
from spiders.bot3 import Bot3Spider
from spiders.bot4 import Bot4Spider
from pprint import pprint

process = CrawlerProcess(get_project_settings())
process.crawl(Oddsbot1Spider)
process.crawl(Oddsbot2Spider)
process.crawl(Oddsbot3Spider)
process.crawl(Oddsbot4Spider)
process.start()

bot1.py
import scrapy
import datetime
import math

from scrapy_splash import SplashRequest
from pymongo import MongoClient
from pprint import pprint

class Bot1Spider(scrapy.Spider):
    name = 'bot1'
    client = MongoClient('localhost', 27017)
    db = client.db

    def start_requests(self):
        count = int(self.db.games.find().count())
        num = math.floor(count*0.25)
        start_urls = self.db.games.find().limit(num-1)

        for url in start_urls:
            full_url = domain + list(url.values())[5]
            yield SplashRequest(full_url, self.parse, args={'wait': 0.1}, meta={'oid': list(url.values())[0]})

    def parse(self, response):
        pass

settings.py
BOT_NAME = 'crawler'

SPIDER_MODULES = ['crawler.spiders']
NEWSPIDER_MODULE = 'crawler.spiders'

# Scrapy Configuration

SPLASH_URL = 'http://localhost:8050'

DOWNLOADER_MIDDLEWARES = {
    'scrapy_splash.SplashCookiesMiddleware': 723,
    'scrapy_splash.SplashMiddleware': 725,
    'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810,
}

SPIDER_MIDDLEWARES = {
    'scrapy_splash.SplashDeduplicateArgsMiddleware': 100,
}

DUPEFILTER_CLASS = 'scrapy_splash.SplashAwareDupeFilter'

# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'my-project-name (www.my.domain)'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

# Configure maximum concurrent requests performed by Scrapy (default: 16)
CONCURRENT_REQUESTS = 64

# Configure a delay for requests for the same website (default: 0)
# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
CONCURRENT_REQUESTS_PER_DOMAIN = 16

When execute these code, I'm using this command: python main.py
After seeing my code, please help me. I'll happily listen any saying.
1.How my spider can faster? I've tried to use threading, but it's seem not working right.
2.What is the best performance line up for web crawling?
3.Is that possible to crawl 3500 dynamic pages in every 5-15 seconds?
Thank you.


text:
Q: Format field for 3 numerical digits with optional letter I have a very large list of assets all with room numbers.  All room number are 3 digits.  Room number on the bottom floor begin with leading zeros (001, 002, etc).  However, some rooms have letters after them (020A, 020B).
How can I format my field in Microsoft Access to display leading zeros but also accept that some rooms have a letter after the 3 digits?

A: A text formatted field will display any entered data as a string literal, i.e. no matter what combination of numbers and letters you enter it will keep those data as typed.  So 001 and 020A would both be accepted.


text:
Q: Prove that 9 divides $7\cdot5^{2n}+2^{4n+1}$ We have to prove that the following statement is true for all non zero natural numbers:
$$9|7\cdot5^{2n}+2^{4n+1}$$

A: with congruence:
$7\cdot5^{2n}+2^{4n+1}\equiv$
$(-2)\cdot(-4)^{2n} + 2^{4n}\cdot 2\equiv $
$-2\cdot 16^n + 16^n \cdot 2 \equiv 0\pmod 9$.
Oh... I didn't actually expect it to end so soon.
....
By induction:
You can't go wrong with induction.
$7*5^2 + 2^5 = 7*25+ 32= 207=9*23$.
Okay... that was the  base case.
If $7*5^{2k} + 2^{4k+1}$ is divisible by $9$ then
$7*5^{2(k+1)} + 2^{4(k+1)+1}=$
$7*5^{2k}\times 25 + 2^{4k+1}\times 16=$
$7*5^{2k}\times (16+9) + 2^{4k+1}\times 16=$
$16(7*5^{2k} + 2^{4k+1}) + 9(7*5^{2k})$.
And $9$ divides $7*5^{2k} + 2^{4k+1}$ and $9$ divides $9(7*5^{2k})$ so $9$ divides the sum which is $7*5^{2(k+1)} + 2^{4(k+1)+1}$
So that's our induction step.

A: $$=7(5^{2n}-2^{4n})+9\cdot2^{4n}$$
Now for integer $n,$ $$5^{2n}-2^{4n}=(5^2)^n-(2^4)^n=25^n-16^n$$
Use Why is $a^n - b^n$ divisible by $a-b$?

A: Hint:
Modulo $9$, $5\equiv-4$, so $7\cdot5^{2n}+2^{4n+1}\equiv 7\cdot4^{2n}+2\cdot4^{2n}$.


text:
Q: Integrating PHPSpellCheck into YUI RTE I have everything set up to integrate PHPSpellCheck (http://www.phpspellcheck.com) to the YUI Rich Text Editor - I have the button made, I have the spell check program in and working - I'm missing one thing - the function phpspellcheck calls.  To integrate the spell check to YUI, I am using this call:
this.toolbar.on('splchkClick', function(o) {?????, myEditor, true);

but I can't figure out what to put in place of the ???? - a function or an action - I know, but pouring through the phpspellcheck files, I can't figure out where I find out what is happening when I click it's spell check button.  Here's the integration code for phpspellcheck:
require ("/var/www/html/evoHTDOCS/phpspellcheck/include.php");
$mySpell = new SpellCheckButton();
$mySpell->InstallationPath = "/phpspellcheck/";
$mySpell->Fields = "EDITORS";
echo $mySpell->SpellImageButton();

the source files for the includes of phpspellcheck (there are only two really, include.php and include.js and you can grab them at that website above) seem simple enough, but I don't know how to read jscript and I think that's where it's doing the magic.  Does anyone have any hints on what I might replace ????? with?  Thanks.

A: this.toolbar.on('splchkClick', doPhpSpell , myEditor, true);

function  doPhpSpell(){
PHPLiveSpell_0.CheckInWindow()
}

You may want to look at the PHPSpellCheck Javascript API:
http://www.phpspellcheck.com/Javascript-AJAX-Spell-Check-API


text:
Q: I need to implement a c++ function pointer to member function overload arma::Mat<double> (*Sum)(arma::Mat<double>, int) = arma::sum; // The function pointer to arma::sum
arma::Mat<double> mat = Sum(A, 1);      //A is of type arma::Mat<double>
std::cout<<mat;

produces the error :
error: no matches converting function 'sum' to type 'class arma::Mat<double> (*)(class arma::Mat<double>, int)'
arma::Mat<double> (*Sum)(arma::Mat<double>, int) = &arma::sum;

I'm unable to understand this as
arma::Mat<T> mat;
mat = arma::sum(this->data, 1);
std::cout<<mat;

produces the desired result when the template T is of type double.Please help me out,thanks!!
The prototype for arma::sum in Armadillo documentation is given as:
sum( M )

sum( M, dim ) //dim = 0, 1 for rowise or columnwise sum

A: Just because the result can be assigned to a variable of a certain type, that doesn't mean that, that is the signature of the method.
A function can return a type which can be converted or assigned to a variable of another type.
In this case, to solve the problem - the original function has to be checked for it's signature (in the header files).
Then it will be possible to create the correct signature, expecially if there are overloads of the function.
For example, a signature from the Armadillo project:
template<typename T1>
arma_warn_unused
arma_inline
const Op<T1, op_sum>
sum
  (
  const T1& X,
  const uword dim = 0,
  const typename enable_if< is_arma_type<T1>::value       == true  >::result* junk1 = 0,
  const typename enable_if< resolves_to_vector<T1>::value == false >::result* junk2 = 0
  )
  // ignore the implemenation ...

As can be seen this function returns an Op type which is a template class. The function has 2 usefull for the user parameters and 2 metaprogramming parameters, used by the implementation.
If you call this function with the type arma::Mat<double> then the signature of this chosen function is:
const Op<arma::Mat<double>, op_sum> (*sum_func)(const arma::Mat<double>, const uword, const void*, const void*)

As I can see in the header file, 11 definitions for sum function are provided. Then also metaprogramming is used to improve the performance of the implementation, which also increases the amount of combinations of parameters for this function, which means even more definitions.
So the type of this function is actually quite compilcated. And because of the metaprogramming it is not necassarily the one which is used, when it is called.

To help with the deduction of the return type decltype can be used.
class Test
{
public:
    int sum (int i){return 1;}
    float sum (float i){return 2.0;}
};

int main()
{
    Test t;

    decltype(t.sum(0)) (Test::* sum_ptr)(int) = &Test::sum;
    return (t.*sum_ptr)(0);
}

A: I keep a helper function around just for this kind of cases, whare you want to resolve an overload without caring about the return type:
template <class... Params, class R>
auto ovl(R(*f)(Params...)) {
    return f;
}

Your initialization then becomes:
auto Sum = ovl<arma::Mat<double>, int>(arma::sum);


text:
Q: Python command not found en Windows 10 con el substima de linux Bueno, resulta que tengo instalado Python en Windows 10 y recientemente instale el bash en ubuntu que esta disponible ahora en estas nuevas versiones, pero cuando realizo el típico python para correrlo este me da el mensaje de error al no encontrarlo.
¿Debería desinstalar el que ya tengo en Windows 10(incluso la variable de entorno) y volver a instalarlo desde el subsistema de linux o no creará conflicto alguno tener ambos instalados?
Espero alguien pueda ayudarme con esto.
Gracias de antemano!.

A: En teoría Python ya está instalado en el subsistema Bash de Ubuntu en Windows, al menos este documento así lo especifica, creo que viene con la versión 2.7x y no encontré documentación para instalar alguna otra. Lo que seguramente te este faltando es el comando pip que puedes instalarlo con sudo apt-get install python-pip. con respecto a la versión "Windows" de Python, te comento que son entornos totalmente distintos, aislados e independientes.


text:
Q: How to handle with GridView distance between images? I want to create app like on galaxy 4s to send to a group contacts.
the group contact names show in a gridView. the problem is when i add new names the distance between them is by column .i what the distance will be more flexible for different length of names like in the example :

my code:
Main.xml
    <GridView
        android:id="@+id/gridNames"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="bottom|center"
        android:layout_weight="1"
        android:gravity="right"
        android:numColumns="auto_fit" >

    </GridView>

row_grid.xml
<TextView
    android:id="@+id/grid_rowName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/round_shape"
    android:padding="3dp"
    android:text="Anna 123"
    android:textSize="17dp"
    android:textStyle="bold" />

Thanks!


text:
Q: creating existing users on AWS when they don't have a group It seems when chef creates a user with the id of "foobar" it also creates a group with the id of "foobar".  AWS doesn't do that.
So, when I run my create users script via Opsworks it blows up on the first user that already exists because the group doesn't.
I thought there was a way to say create the user but not the group, but I can't find it.
What's the best way to solve this problem?  Can I:

*

*Tell chef to not create the user's group?

*Tell chef to create it if the user exists but the group doesn't?

*Write a script that finds the existing users and creates groups for them?

*Something else?

A: This is actually based on the operating system. Under the hood, Chef is just shelling out to useradd or adduser, etc. Each OS implements this differently.

A: The problem I was having was due to my Chef script and Opsworks ssh_users scripts trying to create the same users.  Opsworks won.  As it turns out there is no reason to have a script to create users that opsworks will create for you.


text:
Q: How to switch to other view controller programmatically in Swift 4? I need to switch page(other view controller) using a button.
I have two controllers (viewController to HomeViewController)
I have a button created in viewController:
let acceptButton: UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("Accept", for: .normal)
    button.setTitleColor(.blue, for: .normal)
    button.translatesAutoresizingMaskIntoConstraints = false
    button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18)
    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
    //button.sendAction(Selector(buttonAction), to: HomeViewController(), for: .touchUpInside)

    return button

}()

and I have set a function and used a print statement to test the function:
 @objc func buttonAction(sender: UIButton){
 print("button pressed")
}

I executed the program and when I press the button it prints out "button pressed"
Then I added the following into the function:
  let HomeViewController = ViewController(nibName: ViewController, bundle: nil)
  self.presentViewController(HomeViewController, animated: true, completion: nil)

As a result, it does not switch to other viewController(HomeViewController).
Any idea on how should I make it works? Thank you

A: Switch to another viewController programmatically in Swift 4  -
Navigation process
first, you need to embed your view with Navigation Controller like -

For Navigation programmatically you can use below code -

*

*But this code work with if you working with StoryBoard in your project.
First, you need to set view identifier in storyBoard

Push with StoryBoard
let homeView = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
self.navigationController?.pushViewController(homeView, animated: true)

Present with StoryBoard
let homeView = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
present(homeView, animated: true, completion: nil)

Push with XIB
let homeView = HomeViewController(nibName: "HomeViewController", bundle: nil)
self.navigationController?.pushViewController(homeView, animated: true)

Present with XIB
let homeView = HomeViewController(nibName: "HomeViewController", bundle: nil)
present(homeView, animated: true, completion: nil)

For avoiding any crashes you can also try this code -
guard let homeView = HomeViewController(nibName: "HomeViewController", bundle: nil) else {
   print("Controller not available")
   return
}
self.navigationController?.pushViewController(homeView, animated: true)

A: There are couple of ways to switch to another ViewController.

*

*Navigation

*Present
If you have created the controllers in storyboard then you have to first get the instance of storyboard in case of multiple storyboards.
In case of multiple storyboard you need to mention the name of the storyboard.
let sampleStoryBoard : UIStoryboard = UIStoryboard(name: "UserBoard", bundle:nil)

Then get the instance of the view controller you wish to switch.
* Make sure you set the correct Identifier in ViewController.
let homeView  = sampleStoryBoard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController

if you wish to present the view controller:
self.present(homeView, animated: true, completion: nil)

if you wish to push the view controller:
self.navigationController?.pushViewController(homeView, animated: true)

if you want to Switch to another Controller which you created as Xib
let homeView = HomeViewController(nibName: "HomeViewController", bundle: nil)

If you want to push:
self.navigationController?.pushViewController(homeView, animated: true)

Present the Controller:
present(homeView, animated: true, completion: nil)

Other ways to Switch between Controllers.
Wiring up the Segues
Ctrl+Drag from the "View Controller" button, to somewhere in the second View Controller(HomeViewController).  It can be anywhere in the main box of the second view controller.  When you release, it will show you a box like the one below.

in this you don't need any code to switch, it will switch on click of a button.
or you can CTLR + Drag from View controller to other controller to create segue and write below code on click of button action and switch to another view controller.
performSegue(withIdentifier: "mySegueID", sender: nil)
make sure you set the correct identifier of segue.
Details of different segues
Show — When the View Controllers are in a UINavigationController, this pushes the next View Controller onto the navigation stack.  This allows the user to click the back button to return to the previous screen through the back button on the top left of the Navigation Bar.
Present modally — This presents the next view controller in a modal fashion over the current View Controller.  This one doesn't need to be part of a UINavigationController or a UISplitViewController.  It just shows the destination View Controller in front of the previous one.  This is usually used when the user has to either Finish or Cancel .
Custom — Exactly what it sounds like.  You can make your own segue style and transitions and use it here.

A: you can switch to a Controller in two ways

*

*Present and Dismiss

*Navigation Controller

-> First Method is simple
just need to write two lines as :
In case Controller in Another storyboard file
let newStoryBoard : UIStoryboard = UIStoryboard(name: "UserBoard", bundle:nil)
let VC = newStoryBoard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
self.present(VC, animated: true, completion: nil)

Or if in same storyboard
let VC = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
self.present(VC, animated: true, completion: nil)

-> Second using navigation Controller
Just make use of a navigation controller and then push or pop controllers in navigation stack
let VC = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
self.navigationController?.pushViewController(VC, animated: true)

In your case You are providing bundle as Nil which is wrong
let HomeViewController = ViewController(nibName: ViewController, bundle: nil)

///Need to Provide Bundle detail
let HomeViewController = ViewController(nibName: ViewController, bundle: Bundle.main)

A: let HomeViewController = ViewController(nibName: "ViewController", bundle: Bundle.main)
self.presentViewController(HomeViewController, animated: true, completion: nil)


text:
Q: Python не принимает данные из переменной Делаю отправку BNB из одного кошелька на другой
sign_txn = web3.eth.account.signTransaction(token_tx, private_key=private_key)

вот на этом моменте выбивает ошибка
    return binascii.unhexlify(ascii_hex)
binascii.Error: Non-hexadecimal digit found

НО если я ввожу его как бы без переменной
sign_txn = web3.eth.account.signTransaction(token_tx, private_key='...')

то все хорошо, как мне быть?
Пробовал через f''

A: Нашел ответ, переменная бралась из списка и в конце был знак переноса строки (\n).
Убрал его с помощью line.rstrip('\n').


text:
Q: Get view from Widget reference In Eclipse, can I get the View ID given a reference to one of its widgets? I don't want to enumerate all views and traverse their hierarchies.

A: Use Control.getParent() API to go up the widget hierarchy starting with your widget. At some point, you will find the view part. Then you can get the info you need. I'd do this in the debugger first to make it easier to identify the class that the view part will have in the controls tree. It should be pretty obvious when you see it.

A: Ended up using SWTbot and some manual bookkeeping for the purpose.


text:
Q: How do I make an array keep going? I want to make an array keep on going as opposed to stopping on the last object, if I have sorted its elements how do I make it keep going ?
window.onload=nextcity;

var c = new Array();
c[0] = {cName:"Dresden"};
c[1] = {cName:"Belin"};
c[2] = {cName:"Frankfurt"};
c[3] = {cName:"Koln"};
c[4] = {cName:"Dusseldorf"};
c[5] = {cName:"Leipzig"};

c.sort();

var Citynum = 0;

function nextcity () {
  document.getElementById('cityoptions').innerHTML=c[Citynum].cName;
  Citynum ++;
}

To explain better, when a button is clicked I want the writing to change to a city name i.e. it would look something like this
< DRESDEN >
and when the arrow is clicked it will show a different name I don't want it to stop I want it to keep going.

A: You could reset the Citynum counter to 0 once it reaches the size of c, making the list repeat:
function nextcity () {
  document.getElementById('cityoptions').innerHTML=c[Citynum].cName;
  Citynum ++;
  if (Citynum >= c.length)
    Citynum = 0;
}

A: You could do this:
for (i = 0; i < c.length; i++) {
    document.getElementById('cityoptions').innerHTML=c[i].cName;
}


text:
Q: How do I only return TRUE for full word matches in my doctest? I've got a doctest to return TRUE if a species name starts with quercus but it also returns TRUE if the given species name contains a typo (e.g. quercuss). How do I make sure that TRUE is returned not only if it starts with that species name and matches the full word only?
def is_an_oak(name):
    """ Returns True if name is starts with 'quercus'"""
    return name.lower().startswith('quercus')

I tried leaving a space after the word but it omitted the results when using the function further into my script:
def is_an_oak(name):
    """ Returns True if name is starts with 'quercus'"""
    return name.lower().startswith('quercus ')

A: This should do the trick:
def is_an_oak(name):
    """ Returns True if first word in name is 'quercus'"""
    return name.split()[0].lower() == 'quercus'

Edit considering OPs comment:
What I've added is splitting the string by spaces (.split()) then taking the first word ([0]) and doing the comparison on it.

A: For getting the word;
import re

def is_an_oak(name):
    """ Returns Name if name is 'quercus'"""
    return re.match("^[qQ]uercus*",name).string

For getting TRUE/FALSE
 import re

 def is_an_oak(name):
     """ Returns True if name is 'quercus'"""
     if re.match("^[qQ]uercus*",name):
         return True
     else:
         return False


text: Q: How to cosume Bundling and Minification in .NET on html page I have an angular app with .NET backend. I am on stage where I need to deploy my app on production but before I do, I would like to use the bundling feature in .NET to minify my js,css files.To use bundling feature is not an issue but the problem is I only have index.html page which contain all js and css files references. I need to know what syntax would I need to use to put the bundle on my html page? Is it possible? I know on Razor view or Web Form it's simple to be done but what about If I only have index.html and would like to leverage this feature?


text:
Q: Unformatted Seagate SATA 3.5" internal hard disk external enclosure to recover data I used to have a desktop which was running on a 160GB internal hard drive. I moved cities, so I ditched the desktop and took out just my internal to the new place. The disk has Ubuntu 12.04 installed as the OS.
It's a Seagate SATA 3.5" internal drive and it has a lot of important data which I would like to recover now. So, I bought an external enclosure (Rocketfish) and even though on Windows, I can see it on Device Manager, the drive doesn't show up. I can't see it at all on my Laptop (which runs Ubuntu 14.04). Rocketfish suggests that I format and repartition the drive to be able to use it, but that's not what I want to do. I want to be able to access the data in the internal disk.
Since I don't want to format it, I'm looking for options which will help me access the data as it is. Should I be looking for more external enclosure options or adapters which will help me do this? Or will all of them require me to format the disk? What else is possible?
The hard drive is in perfect working condition. I used it just a few weeks back when it was on my desktop.

A: It's possible that your enclosure for your hard drive isn't passing information about the hard drive correctly.
You didn't indicate what product your enclosure was, but I think it was this Rocketfish™ - 3.5" Serial ATA Hard Drive Enclosure:

In the product description, the enclosure offers two additional USB ports, a memory card reader, and a kind of button that magically takes backups.  These aren't standard USB mass storage device features, which means that you might need additional drivers to support this enclosure.  (Most proprietary drivers are written for Windows, unfortunately, which doesn't help your Linux-formatted drive.)

Troubleshooting
Determining how the USB device is recognized
We can determine definitively whether Linux can work with this enclosure.

*

*Unplug your enclosure's USB cable.

*Since you are on Ubuntu, run this command to get a live stream of kernel messages: sudo tail -f /var/log/syslog

*Plug in your USB enclosure.

*Look for "kernel" messages with "usb" following on the same line.

Example output:
deltik@workstation [~]# sudo tail -f /var/log/syslog
Jun  9 03:38:19 workstation kernel: [16197.624834] usb 1-4: new high-speed USB device number 13 using xhci_hcd
Jun  9 03:38:19 workstation kernel: [16197.753643] usb 1-4: New USB device found, idVendor=0000, idProduct=0000
Jun  9 03:38:19 workstation kernel: [16197.753647] usb 1-4: New USB device strings: Mfr=1, Product=2, SerialNumber=3
Jun  9 03:38:19 workstation kernel: [16197.753649] usb 1-4: Product: NA
Jun  9 03:38:19 workstation kernel: [16197.753651] usb 1-4: Manufacturer: NA
Jun  9 03:38:19 workstation kernel: [16197.753653] usb 1-4: SerialNumber: 20030775011600033F73
Jun  9 03:38:19 workstation kernel: [16197.754266] usb-storage 1-4:1.0: USB Mass Storage device detected
Jun  9 03:38:19 workstation kernel: [16197.754488] scsi host3: usb-storage 1-4:1.0
Jun  9 03:38:19 workstation mtp-probe: checking bus 1, device 13: "/sys/devices/pci0000:00/0000:00:14.0/usb1/1-4"
Jun  9 03:38:19 workstation mtp-probe: bus: 1, device: 13 was not an MTP device
Jun  9 03:38:20 workstation kernel: [16198.755022] scsi 3:0:0:0: Direct-Access     NA       NA               1.26 PQ: 0 ANSI: 5
Jun  9 03:38:20 workstation kernel: [16198.755445] sd 3:0:0:0: Attached scsi generic sg2 type 0
Jun  9 03:38:20 workstation kernel: [16198.756638] sd 3:0:0:0: [sdc] 31266816 512-byte logical blocks: (16.0 GB/14.9 GiB)
Jun  9 03:38:20 workstation kernel: [16198.757620] sd 3:0:0:0: [sdc] Write Protect is off
Jun  9 03:38:20 workstation kernel: [16198.757622] sd 3:0:0:0: [sdc] Mode Sense: 43 00 00 00
Jun  9 03:38:20 workstation kernel: [16198.757855] sd 3:0:0:0: [sdc] Write cache: disabled, read cache: enabled, doesn't support DPO or FUA
Jun  9 03:38:20 workstation kernel: [16198.766125]  sdc: sdc1 sdc2
Jun  9 03:38:20 workstation kernel: [16198.768140] sd 3:0:0:0: [sdc] Attached SCSI removable disk

The above output shows that a "USB Mass Storage device" was detected, meaning that the device could be used as a flash drive, almost exactly like an internal hard drive.
If your output doesn't look like the above, then most likely, you won't be able to interface with the enclosure.
Here's a different example showing a device being recognized as a keyboard:
deltik@workstation [~]# sudo tail -f /var/log/syslog
Jun  9 03:33:45 workstation kernel: [15922.756034] usb 1-4: new low-speed USB device number 11 using xhci_hcd
Jun  9 03:33:45 workstation kernel: [15922.944965] usb 1-4: New USB device found, idVendor=1050, idProduct=0010
Jun  9 03:33:45 workstation kernel: [15922.944972] usb 1-4: New USB device strings: Mfr=1, Product=2, SerialNumber=0
Jun  9 03:33:45 workstation kernel: [15922.944975] usb 1-4: Product: Yubico Yubikey II
Jun  9 03:33:45 workstation kernel: [15922.944978] usb 1-4: Manufacturer: Yubico
Jun  9 03:33:45 workstation kernel: [15922.945174] usb 1-4: ep 0x81 - rounding interval to 64 microframes, ep desc says 80 microframes
Jun  9 03:33:45 workstation kernel: [15922.948270] input: Yubico Yubico Yubikey II as /devices/pci0000:00/0000:00:14.0/usb1/1-4/1-4:1.0/0003:1050:0010.0006/input/input26
Jun  9 03:33:45 workstation kernel: [15923.004567] hid-generic 0003:1050:0010.0006: input,hidraw3: USB HID v1.11 Keyboard [Yubico Yubico Yubikey II] on usb-0000:00:14.0-4/input0
Jun  9 03:33:45 workstation mtp-probe: checking bus 1, device 11: "/sys/devices/pci0000:00/0000:00:14.0/usb1/1-4"
Jun  9 03:33:45 workstation mtp-probe: bus: 1, device: 11 was not an MTP device

Determining if the USB device can be used for block storage
If the kernel log shows that you can use the Rocketfish enclosure as a storage device, then follow these steps:

*

*Unplug the USB cable from the enclosure.

*Run this command: cat /proc/partitions

*Plug in the USB cable again.

*Run this command again: cat /proc/partitions
If the USB device was recognized as block storage, then you will see at least one new line added to the output from cat /proc/partitions.
If not, then unfortunately, the kernel doesn't support your Rocketfish device, and my only recommendation for you left would be to get a new, simpler enclosure that doesn't have any extra fancy features.
If the enclosure is recognized as a block device...
There might be some hope, but I wouldn't recommend trying to interface with the drive through the Rocketfish enclosure because the enclosure is returning data about the hard drive in an unusual way that could lead to data corruption if you try to use it.


text:
Q: Powershell - rename file using Date Taken attribute I have a stack load of images and videos on my Samsung phone. I copied these images to a USB then onto my PC.
I want to use Powershell to rename these files based on their Date Taken attribute.
Format required = yyyy-MM-dd HH.mm.ss ddd
I have been using a Powershell script (see below) that does this beautifully using the Date Modified attribute, but the copy above somehow changed the Date Modified value on me (WTH!), so I can't use that now (as its not accurate).
Get-ChildItem | Rename-Item -NewName {$_.LastWriteTime.ToString("yyyy-MM-dd HH.mm.ss ddd") + ($_.Extension)}

In summary - is there a way to change the file name based on the Date Taken file attribute?  Suggestions I have seen online require use of the .NET System.Drawing.dll and convoluted code (I'm sure it works, but damn its ugly).
GG

A: Please checkout  Set-PhotographNameAsDateTimeTaken Powershell module. It extract date and time from the picture and change name of the picture to it.

It allows to use -Recurse -Replace and -Verbose parameter. By default it will create reuslt folder at the same level as your working dir.
If you need change the format of the target names the code can be found here.

A: I 'glued' together a bunch of other answers to make a bulk script.  Credit to those, but Chrome crashed and I lost those other webpages on Stack.  This works on photo files only and will rename all files to YYYYMMDD_HHMMSS.jpg format.
Here it is:
$nocomment = [reflection.assembly]::LoadWithPartialName("System.Drawing")
get-childitem *.jpg | foreach {
    $pic = New-Object System.Drawing.Bitmap($_.Name)
    $bitearr = $pic.GetPropertyItem(36867).Value
    $string = [System.Text.Encoding]::ASCII.GetString($bitearr)
    $date = [datetime]::ParseExact($string,"yyyy:MM:dd HH:mm:ss`0",$Null)
    [string] $newfilename = get-date $date -format yyyyMd_HHmmss
    $newfilename += ".jpg"
    $pic.Dispose()
    rename-item $_ $newfilename -Force
    $newfilename
}

A: In order to avoid this error:
New-Object : Cannot find type [System.Drawing.Bitmap]: verify that the assembly containing this type is
loaded.
...

Make sure the required assembly is loaded before executing the code above:
add-type -AssemblyName System.Drawing


text:
Q: How to specify a range without limiting to numbers This is the code that gets the restaurant reviews. I am collecting reviews.
The range is specified and imported. But there is a problem. Each store has a different number of reviews. Store with little reviews should go to next store soon.
I am suffering from too large a scope. But it can not reduce the scope. This is because some shops have reviews in this range.
How can I work effectively?
I saw find all?(element) searching this code. But I do not know if I've mistakenly applied my code.
#python3
import sys
from bs4 import BeautifulSoup
import urllib.request
import requests
from urllib.parse import quote
import time
import os
import xlwt
import random

import re

FISRT_URL = "https://www.yelp.com/search?
find_desc=Korean+Food&find_loc=Seattle,+WA&start="
LAST_URL = "&cflt=korean"
def get_link(URL, doc_name):
    global jisu_i
    global num
    global page
    for jisu_i in range(1):
        current_page_num = 20 + jisu_i*10
        position = URL.index('t=')
        URL_with_page_num = URL[: position+2] + str(current_page_num) \
                            + URL[position+2 :]
    print(URL_with_page_num)
    importurl = URL_with_page_num
    r = requests.get(importurl)
    soup = BeautifulSoup(r.content.decode('euc-kr','replace'), "lxml")
    time.sleep(random.randint(10, 15))

    for title in soup.find_all('h3')[page+2:21]:

        page = page + 1
        title_link = title.select('a')
        for jisu_m in range(130):
            print(page)
            last_URL = title_link[0]['href']
            print(last_URL)

            first_URL = "https://www.yelp.com"
            global article_URL
            article_URL = first_URL + last_URL
            time.sleep(random.randint(15, 30))

            jisuurl = article_URL
            for k in range(99):  #
                jisu_page_num = 0 + k * 20  #
                position = jisuurl.index('?')
                URL_with_page_num = jisuurl[: position + 1] + str("start=") + str(jisu_page_num)

                jisu_with_page_num = URL_with_page_num
                print(jisu_with_page_num)

                jisu_importurl = jisu_with_page_num
                get_text(URL, jisu_importurl, doc_name)
                time.sleep(random.randint(40,180))

A: Yelp has a very well documented API here: https://www.yelp.com/developers/documentation/v3
This is the only reliable way of interacting with the site programatically.


text:
Q: Can't get basic example from react-navigation to work correctly I'm trying to get a basic AppContainer to work in react-navigation but am having some trouble.
This example here works perfectly fine on snack.expo.io and even works fine when I run it on my device off of snack. However, when I copy paste the exact code into VSCode and push it to my device, it errors out with:
Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

Check the render method of `NavigationContainer`.

The code is the exact same, yet errors out on my Android device. Am I missing a dependency or something?
Thanks!
EDIT:
package.json file:
{
  "main": "node_modules/expo/AppEntry.js",
  "private": true,
  "dependencies": {
    "es6-promise": "^4.2.5",
    "expo": "^25.0.0",
    "isomorphic-fetch": "^2.2.1",
    "react": "^16.7.0",
    "react-native": "https://github.com/expo/react-native/archive/sdk-25.0.0.tar.gz",
    "react-navigation": "^3.0.9"
  }
}


text:
Q: Application closes all the activities when click on home key? Hi Everyone im developing one android application in which there are 7 screens.
when i debug my application it works fine and when i click on home button at 4 screen and again i start my app it starts from same screen/4screen where the app goes into background,but when i create app.apk file for my users and when they use that app and press home key  suppose at 4 screen and he/she restart the  app starts from starting screen that is login screen/1 screen .
Can any buddy tell me whats the problem in it and what can i do to sortout this problem.
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.dblist);
    setTitle("Databases");

    try {
        jsonObj = new JSONObject(getIntent().getStringExtra("key"));
        nameArray = jsonObj.names();
        valArray = jsonObj.getJSONArray("DbList");
    } catch (JSONException e1) {

        e1.printStackTrace();
    }

    ArrayAdapter<String> dbName = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1);

    for (Integer i = 0; i < valArray.length(); i++) {

        try {
            String obj = valArray.getJSONObject(i)
                    .getString("DataBaseName").toString();
            dbName.add(obj);
        } catch (JSONException e) {

        }

    }
    setListAdapter(dbName);
}

@Override
protected void onResume() {

    super.onResume();

    // versionUpdate();

    Logout lo = new Logout();
    lo.Check();
    processThreadLogoutTime();

}

final Handler handler = new Handler() {

    @Override
    public void handleMessage(Message msg) {

        super.handleMessage(msg);

        int compareTime = 1;

        if (diff >= compareTime) {

            Intent intent = new Intent(ShowDbList.this, LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);

        }

    }

};

protected void processThreadLogoutTime() {

    new Thread() {

        public void run() {

            cw = new ConnectToWebService();
            getMethod gm = getMethod.GetApplicationDetails;
            String result = cw.getUrl("", gm);
            String urlLogoutTime = result.replaceAll(" ", "%20");
            cw.LogoutTime(urlLogoutTime);
            Logout logout = new Logout();

            diff = logout.LogoutFun();

            handler.sendEmptyMessage(0);

        }

    }.start();

}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {

    String item = (String) getListAdapter().getItem(position);
    Entities.DataBaseName = item;
    try {
        String webAdmin = valArray.getJSONObject(position)
                .getString("WebAdmin").toString();
        Integer uId = Integer.parseInt(valArray.getJSONObject(position)
                .getString("UserID"));
        Entities.webAdmin = webAdmin;
        Entities.userId = uId;
    } catch (JSONException e) {
        // TODO Auto-generated catch block

    }
    Intent intent = new Intent(v.getContext(), Menu.class);
    startActivity(intent);

}

A: Kazekage Gaara is right: Your application gets killed. If you insist on starting the application from where it where last, even if it has been closed, you need to handle this. Make a persistent save of the state whenever onStop is called and make sure that the user is sent to the correct place in onCreate/onStart.


text:
Q: How to handle dynamic JSON data with GWT Autobeans? Currently I have a class setup to be processed as an autobean:
public interface Asset extends Hit {
    String getGuid();
    String getHitType();
    Map<String,Serializable> getMetadata();
}

I tried using Object instead of Serializable:
Map<String,Object>  getMetadata()

but this seems to blow up when trying to access data (because it's not 'reified').
The Metadata map may contain other maps, strings, ints, etc.  How do I retrieve data from an inner map of that metadata object?
Currently, if I call asset.getMetadata().get("title"); this returns a SerializableAutoBean and performing toString() or String.valueOf(obj) on that object returns the in memory object information and not the actually string value.
Can an AutoBean object be this dynamic, or do you specifically have to define every field?

A: AutoBeans aren't "dynamic" in the Java generics or RTTI sense.
In GWT, all types have to be known at compile time for anything which is auto-generated (which includes AutoBeans). This places restrictions on your designs which don't allow you to take full advantage of Java's language features (specifically, generics and other RTTI features). So, AutoBeans are not dynamic in the RTTI or Java generic sense. However, AutoBeans are simply a low-level way of wrapping your data, and you still have access to the data by using Splittables!
As stated in the previous comments, you can use Splittables for the parts of your JSON object whose type is not known at serialization/decode time. Sure, it would be nice to have everything happen at once, but nothing is stopping you from performing some post-processing on your data objects to get them into your desired state.
A really good way for someone to "Grok" what is going on with AutoBeans (and anything else which is autogenerated) is to look at the resulting generated code. The default location for maven is: ${project.build.directory}/.generated.
If you look in there after you've compiled, you should find the code which the GWT compiler produces for your AutoBeans.


text:
Q: How to separate (x,y) to new coulmns x and y in R? A dataset (CSV) file has a column latitudes and longitudes as (33, -118), (34, -119), (36, -120) etc. There are a million rows.
How can I seperate them, for instance how can I create two new columns with lat and long separate values. I know how to map using ggmap given lat and long in separate columns.
Thank you for your help

A: One more attempt:
library(tidyverse)

df <- data.frame(col = c('(33, -118)', '(34, -119)', '(36, -120)'))

df %>%
  mutate(col =col %>% str_sub(2,-2)) %>%  # remove ( and )
  separate(col, c('lat', 'lon'), convert=T) # separate

  lat lon
1  33 118
2  34 119
3  36 120

A: In data.table:
library(data.table)
setDT(myData)
myData[ , c('lat', 'lon') := tstrsplit(
  gsub('[()]', '', lat_lon_col),
  split = ', ',
  fixed = TRUE, type.convert = TRUE
)]

A: You could extract the numbers from the column and create two new columns.
df[c('lat', 'lon')] <- stringr::str_extract_all(df$col, "-?\\d+", simplify = TRUE)
df

#         col lat  lon
#1 (33, -118)  33 -118
#2 (34, -119)  34 -119
#3 (36, -120)  36 -120

data
df <- data.frame(col = c('(33, -118)', '(34, -119)', '(36, -120)'))


text:
Q: Instalé Android Studio pero sale "Error:Failed to complete Gradle execution" Luego de instalar Android Studio, muestra:

Error:Failed to complete Gradle execution.
Cause: Process 'command '/usr/local/android-studio/jre/bin/java''
  finished with non-zero
  exit value 126

Instalé nuevamente el jdk 1.8.101 y jre pero sigue saliendo el mismo error.

A:
Error:Failed to complete Gradle execution.
Cause: Process 'command '/usr/local/android-studio/jre/bin/java''
  finished with non-zero exit value
  126

Asegura instalar la versión de java y Android Studio adecuada para tu sistema operativo.
Si tu sistema operativo es de 64bits o 32 bits, asegura instalar la version correspondiente.

A: Aunque esta respuesta llega tarde, por si a alguien le sigue siendo de ayuda, puede que al descomprimir android-studio fallen los permisos de ejecucion de varios programas necesarios para android-studio. Prueba a ejecutar lo siguiente desde la carpeta donde tienes instalado android studio:
for f in `find . -name bin`; do chmod +x $f/*; done

En tu caso, al estar en /usr/local puede ejecutar directamente desde cualquier sitio:
for f in `find /usr/local/android-studio -name bin`; do sudo chmod +x $f/*; done


text:
Q: MYSQL Select tables starting with "x" I have a bunch of tables in my "stats" database.
tcl20151w1d1
tcl20151w1d2
tcl20151w2d1
tcl20151w2d2
tcl20151w3d1
tcl20151w3d2
tcl20151w4d1
eu20151w1d1
eu20151w1d2
eu20151w2d1
eu20151w2d2
eu20151w3d1
eu20151w3d2
eu20151w4d1
..

How can i select all tables that starts with "tcl" in "stats" database. Is it possible? Do I have to union them manually?

A: You can query information_schema.tables table to get a list of tables where the table name start with tcl.
You can use the list to dynamically create a union query in a stored procedure using string concatenation and prepared statements.
If those tables are all myisam tables with the same structure, you may consider creating a merge table on them:

The MERGE storage engine, also known as the MRG_MyISAM engine, is a
  collection of identical MyISAM tables that can be used as one.
  "Identical" means that all tables have identical column and index
  information.


text:
Q: getting data from DFs to put into a main DF I am trying to get data from a list of dfs into one df.
I am using the following code
main_df =  pd.DataFrame(columns=data.columns[-len_data+1:], index = is_refs)
for index, dict in enumerate(dict_lists):
    df = pd.DataFrame(dict_lists[index])
    df = df.reindex(is_refs)
    main_df = main_df.append(df[df.columns])

The problem is that it returns the following DF. Clearly I don't want repeated items in the index and just want the financial data to fit into my rows. Any idea how to do this?

A: df_col = df[df.columns]
print(df_col)
main_df = main_df.join(df_col)


text:
Q: Convert int to DateTime I need to convert int to DateTime
var a = reader.ValueOrDefault<DateTime>(beginWorkHour);
//........................................................

    internal static T ValueOrDefault<T>(this IDataReader reader, int ordinal) {
                if (reader.IsDBNull(ordinal))
                    return default(T);

                return (T) reader.GetValue(ordinal);
            }

This code throws an error "Specified cast is not valid".
reader.GetValue(ordinal) returns 12.

A: An int is an int; you still need to fetch it like that, and to be honest it isn't exactly clear how exactly you mean, but at a guess it sounds like you want:
DateTime time =
    DateTime.Today.AddHours(reader.ValueOrDefault<int>(beginWorkHour));

A: At the light of your new comment, maybe that's what you're after:
var hours = TimeSpan.FromHours(reader.ValueOrDefault<int>(beginWorkHour));

A: So if it returns an int, why are you trying to read it as a DateTime? I would have thought you'd want something like:
int hour = reader.ValueOrDefault<int>(beginWorkHour);
DateTime time = new DateTime(2000, 1, 1, hour, 0, 0);

or something similar. (I'm just guessing, given the variable name.)
How do you want the integer to be converted to a date and time?


text:
Q: Overlay loading indicator before data and charts are loaded Is there a possibility to activate loading indicator (overlay) before date and charts are loaded? There is no info on this in documentation and also no event possibilities like oninit or oncomplete.
Google also doesn't give any useful solutions. Thx

A: The options.animation lets you define how animation looks and how long it takes. Especially the onProgress and onComplete animation callbacks may be useful in your case.
Please have a look at the following code sample: https://www.chartjs.org/samples/latest/advanced/progress-bar.html


text:
Q: Want to make Boss RC-505 mobile with batteries, do I need a choke? My Boss RC-505 Loopstation is a greaat bit of kit, but I'd like to make it more mobile (already done the 12v battery -> inverter -> 240 boss adapter -> loopstation) but it seems a little OTT when the input on the boss is only 9v @0.5A, never mind the form factor!
On the stock Boss power adapter they've fitted (near the connector to the boss) a dual coil choke - I assume to cut out interference from AC -> DC conversion from messing with the audio mixed with the loopstation - but do I need the choke if I'm planning to power with battery?
Also, any tips on battery or issues I might face would be appreciated :)

A: The ferrite beads aren't designed to block low frequency AC hum, but rather to reduce the amount of RFI from the device that is radiated back to the mains (e.g. from switching regulators) or noise pickup from it, and to stop the cable acting as a giant antenna.
For a battery application, you won't have those issues anyway, so in all likelihood the ferrite bead is not required.


text:
Q: Magento 2 Product Filter By Category & Multiple Product Attributes I'm currently building a custom product filter via Ajax. I've got the basics working but now I'm trying to filter via category and a specific product attribute.
Here is my code
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');

$categoryData = $this->getRequest()->getParam('whoisitfor');

// Get category selected.
if(isset($categoryData)) {
    $categoryData = $this->expandFormValues($categoryData);
    $categories = [$categoryData];//category ids array
    $collection->addCategoriesFilter(['in' => $categories]);
}

This get's the products for the specific categories that are selected on the frontend, this works fine.
Now when I try and filter it by a specific product attribute it still just returns all the products from the category above not the specific products with the attribute filtered on.
Here is the code:
$collection->addAttributeToFilter('user_experience_level', array('eq' => 3003));

Full code looks like this:
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');

$categoryData = $this->getRequest()->getParam('whoisitfor');

// Get category selected.
if(isset($categoryData)) {
    $categoryData = $this->expandFormValues($categoryData);
    $categories = [$categoryData];//category ids array
    $collection->addCategoriesFilter(['in' => $categories]);
}

$collection->addAttributeToFilter('user_experience_level', array('eq' => 3003));

If anyone can help me with this, it'd be great.
Thanks.

A: you can try this code.
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');

$categoryData = $this->getRequest()->getParam('whoisitfor');

// Get category selected.
if(isset($categoryData)) {
$categoryData = $this->expandFormValues($categoryData);
$categories = [$categoryData];//category ids array
$collection->addCategoriesFilter(['in' => $categories]);

}

$collection->addFieldToFilter('user_experience_level', array('eq' => 3003));


text:
Q: Is Eclipse's $SWITCH_TABLE$ thread-safe? It appears when Eclipse compiles an enum whose values are used in a switch statement, it adds the following to the enum class file:

*

*synthetic field: private static int[] $SWITCH_TABLE$mypackage$MyEnum;

*synthetic method: static int[] $SWITCH_TABLE$mypackage$MyEnum()
Lazily initializes $SWITCH_TABLE$mypackage$MyEnum field with respective enum ordinal values.

And at every place where a switch on the enum values occurs it calls $SWITCH_TABLE$mypackage$MyEnum()[e.ordinal()].
Source code:
package mypackage;

public enum MyEnum {
    FIRST;

    public int get() {
        switch (this) {
            case FIRST:
                return 2;
            default:
                return -1;
        }
    }
}

Decompiled code:
package mypackage;

public enum MyEnum {
   FIRST;

   // $FF: synthetic field
   private static int[] $SWITCH_TABLE$mypackage$MyEnum;

   public int get() {
      switch($SWITCH_TABLE$mypackage$MyEnum()[this.ordinal()]) {
      case 1:
         return 2;
      default:
         return -1;
      }
   }

   // $FF: synthetic method
   static int[] $SWITCH_TABLE$mypackage$MyEnum() {
      int[] var10000 = $SWITCH_TABLE$mypackage$MyEnum;
      if (var10000 != null) {
         return var10000;
      } else {
         int[] var0 = new int[values().length];

         try {
            var0[FIRST.ordinal()] = 1;
         } catch (NoSuchFieldError var1) {
         }

         $SWITCH_TABLE$mypackage$MyEnum = var0;
         return var0;
      }
   }
}

However, as you can see here neither the field $SWITCH_TABLE$mypackage$MyEnum is volatile nor $SWITCH_TABLE$mypackage$MyEnum() is performing any sychronization.
The question is now: Is this actually thread-safe? If I understand the Java Memory Model correctly, there is no guarantee that if one thread initializes the switch table (through a call to get()), a second thread sees an up to date switch table value. Instead it might see a stale value which does not have the correct elements.
Followup question: Since there are no happens-before  relations, would a JVM also be allowed to reorder the assignment to the $SWITCH_TABLE$ in front of the element changes? If this was possible there could be race conditions where one thread sees the array while the other thread is still modifying the elements.

A: I run some tests with jcstress on Windows 7/OpenJDK 13. The local variables are important!
This code should mimic posted code, running 3 threads, multiple times:
// concurrency stress test
@JCStressTest

// expected outcome (III_Result::toString)
@Outcome(id = "1, 1, 1", expect = Expect.ACCEPTABLE, desc = "Correctly initialized.")
@Outcome(id = ".+, .+, .+", expect = Expect.FORBIDDEN, desc = "Some Thread did see a not initialized array")

// test data
@State
public class EnumInitOK {

    int[] array;

    int[] switchTable() {
        int[] v1 = array;
        if (v1 != null) {
            return v1;
        } else {
            int[] v2 = new int[1];
            v2[0] = 1;
            array = v2;
            return v2;
        }
    }

    // each called only by one particular Thread, once per State instance
    @Actor public void test1(III_Result r) {
        r.r1 = switchTable()[0];
    }

    @Actor public void test2(III_Result r) {
        r.r2 = switchTable()[0];
    }

    @Actor public void test3(III_Result r) {
        r.r3 = switchTable()[0];
    }
}

Results from all runs with different settings, not one initialization error (almost 400M tests):

Java Concurrency Stress Tests
---------------------------------------------------------------------------------
Rev: null, built by cfh with 12.0.2 at null

Probing what VM modes are available:
 (failures are non-fatal, but may miss some interesting cases)

----- [OK] [-Xint]
----- [OK] [-XX:TieredStopAtLevel=1]
----- [OK] []
----- [OK] [-XX:+UnlockDiagnosticVMOptions, -XX:+StressLCM, -XX:+StressGCM]
----- [OK] [-XX:-TieredCompilation]
----- [OK] [-XX:-TieredCompilation, -XX:+UnlockDiagnosticVMOptions, -XX:+StressLCM, -XX:+StressGCM]

Initializing and probing the target VM:
 (all failures are non-fatal, but may affect testing accuracy)

----- [OK] Unlocking diagnostic VM options
Burning up to figure out the exact CPU count....... done!

----- [OK] Trimming down the default VM heap size to 1/4-th of max RAM
----- [OK] Trimming down the number of compiler threads
----- [OK] Trimming down the number of parallel GC threads
----- [OK] Trimming down the number of concurrent GC threads
----- [OK] Trimming down the number of G1 concurrent refinement GC threads
----- [OK] Testing @Contended works on all results and infra objects
----- [OK] Unlocking Whitebox API for online de-optimization
----- [OK] Testing allocation profiling
----- [OK] Trying Thread.onSpinWait

  Hardware threads in use/available: 4/4, using Thread.onSpinWait()
  Test preset mode: "default"
  Writing the test results to "jcstress-results-2019-10-22-23-32-40.bin.gz"
  Parsing results to "results/"
  Running each test matching "cfh.jcstress.EnumInitOK" for 1 forks, 5 iterations, 1000 ms each
  Each JVM would execute at most 5 tests in the row.
  Solo stride size will be autobalanced within [10, 10000] elements, but taking no more than 100 Mb.

... [output deleted] ...

RUN COMPLETE.

RUN RESULTS:
------------------------------------------------------------------------------------------------------------------------

*** INTERESTING tests
  Some interesting behaviors observed. This is for the plain curiosity.

  0 matching test results.

*** FAILED tests
  Strong asserts were violated. Correct implementations should have no assert failures here.

  0 matching test results.

*** ERROR tests
  Tests break for some reason, other than failing the assert. Correct implementations should have none.

  0 matching test results.

*** All remaining tests
  Tests that do not fall into any of the previous categories.

  6 matching test results.
      [OK] cfh.jcstress.EnumInitOK
    (JVM args: [-XX:+UnlockDiagnosticVMOptions, -XX:+StressLCM, -XX:+StressGCM])
  Observed state   Occurrences   Expectation  Interpretation
      .+, .+, .+             0     FORBIDDEN  Some Thread did see a not initialized array
         1, 1, 1    76.194.931    ACCEPTABLE  Correctly initialized.

      [OK] cfh.jcstress.EnumInitOK
    (JVM args: [-XX:-TieredCompilation, -XX:+UnlockDiagnosticVMOptions, -XX:+StressLCM, -XX:+StressGCM])
  Observed state   Occurrences   Expectation  Interpretation
      .+, .+, .+             0     FORBIDDEN  Some Thread did see a not initialized array
         1, 1, 1    76.756.011    ACCEPTABLE  Correctly initialized.

      [OK] cfh.jcstress.EnumInitOK
    (JVM args: [-XX:-TieredCompilation])
  Observed state   Occurrences   Expectation  Interpretation
      .+, .+, .+             0     FORBIDDEN  Some Thread did see a not initialized array
         1, 1, 1    78.453.381    ACCEPTABLE  Correctly initialized.

      [OK] cfh.jcstress.EnumInitOK
    (JVM args: [-XX:TieredStopAtLevel=1])
  Observed state   Occurrences   Expectation  Interpretation
      .+, .+, .+             0     FORBIDDEN  Some Thread did see a not initialized array
         1, 1, 1    73.608.821    ACCEPTABLE  Correctly initialized.

      [OK] cfh.jcstress.EnumInitOK
    (JVM args: [-Xint])
  Observed state   Occurrences   Expectation  Interpretation
      .+, .+, .+             0     FORBIDDEN  Some Thread did see a not initialized array
         1, 1, 1     8.740.641    ACCEPTABLE  Correctly initialized.

      [OK] cfh.jcstress.EnumInitOK
    (JVM args: [])
  Observed state   Occurrences   Expectation  Interpretation
      .+, .+, .+             0     FORBIDDEN  Some Thread did see a not initialized array
         1, 1, 1    86.069.111    ACCEPTABLE  Correctly initialized.

------------------------------------------------------------------------------------------------------------------------

To cross-check, I tried the same code accessing the array directly, without using the local variables, in the switchTable method:
//concurrency stress test
@JCStressTest

//expected outcome (III_Result::toString)
@Outcome(id = "1, 1, 1", expect = Expect.ACCEPTABLE, desc = "Correctly initialized.")
@Outcome(id = ".+, .+, .+", expect = Expect.FORBIDDEN, desc = "Some Thread did see a not initialized array")

//test data
@State
public class EnumInitErr {

    int[] array;

    int[] switchTable() {
        if (array != null) {
            return array;
        } else {
            array = new int[1];
            array[0] = 1;
            return array;
        }
    }

    // each called only by one particular Thread, once per State instance
    @Actor public void test1(III_Result r) {
        r.r1 = switchTable()[0];
    }

    @Actor public void test2(III_Result r) {
        r.r2 = switchTable()[0];
    }

    @Actor public void test3(III_Result r) {
        r.r3 = switchTable()[0];
    }
}

This time we got some results with uninitialized arrays:

... [output deleted] ...

RUN COMPLETE.

RUN RESULTS:
------------------------------------------------------------------------------------------------------------------------

*** INTERESTING tests
  Some interesting behaviors observed. This is for the plain curiosity.

  0 matching test results.

*** FAILED tests
  Strong asserts were violated. Correct implementations should have no assert failures here.

  6 matching test results.
  [FAILED] cfh.jcstress.EnumInitErr
    (JVM args: [-XX:+UnlockDiagnosticVMOptions, -XX:+StressLCM, -XX:+StressGCM])
  Observed state   Occurrences   Expectation  Interpretation
         0, 0, 1           565     FORBIDDEN  Some Thread did see a not initialized array
         0, 1, 0         1.089     FORBIDDEN  Some Thread did see a not initialized array
         0, 1, 1         2.835     FORBIDDEN  Some Thread did see a not initialized array
         1, 0, 0           792     FORBIDDEN  Some Thread did see a not initialized array
         1, 0, 1         3.272     FORBIDDEN  Some Thread did see a not initialized array
         1, 1, 0         2.394     FORBIDDEN  Some Thread did see a not initialized array
         1, 1, 1    70.441.694    ACCEPTABLE  Correctly initialized.

  [FAILED] cfh.jcstress.EnumInitErr
    (JVM args: [-XX:-TieredCompilation, -XX:+UnlockDiagnosticVMOptions, -XX:+StressLCM, -XX:+StressGCM])
  Observed state   Occurrences   Expectation  Interpretation
         0, 0, 1           481     FORBIDDEN  Some Thread did see a not initialized array
         0, 1, 0           604     FORBIDDEN  Some Thread did see a not initialized array
         0, 1, 1         2.373     FORBIDDEN  Some Thread did see a not initialized array
         1, 0, 0           901     FORBIDDEN  Some Thread did see a not initialized array
         1, 0, 1         2.908     FORBIDDEN  Some Thread did see a not initialized array
         1, 1, 0         3.310     FORBIDDEN  Some Thread did see a not initialized array
         1, 1, 1    69.456.024    ACCEPTABLE  Correctly initialized.

  [FAILED] cfh.jcstress.EnumInitErr
    (JVM args: [-XX:-TieredCompilation])
  Observed state   Occurrences   Expectation  Interpretation
         0, 0, 1         1.332     FORBIDDEN  Some Thread did see a not initialized array
         0, 1, 0           948     FORBIDDEN  Some Thread did see a not initialized array
         0, 1, 1         4.212     FORBIDDEN  Some Thread did see a not initialized array
         1, 0, 0         1.071     FORBIDDEN  Some Thread did see a not initialized array
         1, 0, 1         5.216     FORBIDDEN  Some Thread did see a not initialized array
         1, 1, 0         5.052     FORBIDDEN  Some Thread did see a not initialized array
         1, 1, 1    64.580.410    ACCEPTABLE  Correctly initialized.

  [FAILED] cfh.jcstress.EnumInitErr
    (JVM args: [-XX:TieredStopAtLevel=1])
  Observed state   Occurrences   Expectation  Interpretation
         0, 0, 1         8.766     FORBIDDEN  Some Thread did see a not initialized array
         0, 1, 0        11.470     FORBIDDEN  Some Thread did see a not initialized array
         0, 1, 1        21.761     FORBIDDEN  Some Thread did see a not initialized array
         1, 0, 0        11.280     FORBIDDEN  Some Thread did see a not initialized array
         1, 0, 1        28.461     FORBIDDEN  Some Thread did see a not initialized array
         1, 1, 0        27.634     FORBIDDEN  Some Thread did see a not initialized array
         1, 1, 1    71.079.569    ACCEPTABLE  Correctly initialized.

  [FAILED] cfh.jcstress.EnumInitErr
    (JVM args: [-Xint])
  Observed state   Occurrences   Expectation  Interpretation
         0, 0, 1            77     FORBIDDEN  Some Thread did see a not initialized array
         0, 1, 0           117     FORBIDDEN  Some Thread did see a not initialized array
         0, 1, 1         2.417     FORBIDDEN  Some Thread did see a not initialized array
         1, 0, 0            83     FORBIDDEN  Some Thread did see a not initialized array
         1, 0, 1         2.291     FORBIDDEN  Some Thread did see a not initialized array
         1, 1, 0         1.789     FORBIDDEN  Some Thread did see a not initialized array
         1, 1, 1     5.674.177    ACCEPTABLE  Correctly initialized.

  [FAILED] cfh.jcstress.EnumInitErr
    (JVM args: [])
  Observed state   Occurrences   Expectation  Interpretation
         0, 0, 1           785     FORBIDDEN  Some Thread did see a not initialized array
         0, 1, 0           804     FORBIDDEN  Some Thread did see a not initialized array
         0, 1, 1         2.717     FORBIDDEN  Some Thread did see a not initialized array
         1, 0, 0         1.250     FORBIDDEN  Some Thread did see a not initialized array
         1, 0, 1         4.041     FORBIDDEN  Some Thread did see a not initialized array
         1, 1, 0         5.500     FORBIDDEN  Some Thread did see a not initialized array
         1, 1, 1    63.510.464    ACCEPTABLE  Correctly initialized.

*** ERROR tests
  Tests break for some reason, other than failing the assert. Correct implementations should have none.

  0 matching test results.

*** All remaining tests
  Tests that do not fall into any of the previous categories.

  0 matching test results.

------------------------------------------------------------------------------------------------------------------------

first time using jcstress, sorry for any errors


text:
Q: When pressing the any Button on Asp.net form Default Button is also pressed I have an ASP.net form  with buttons on it.
When I try to press any button, the button which is set as default is also pressed.
And this only happens when I use Firefox browser. Does not happen on Internet Explorer.
How can I solve this problem?

A: Ok this issues is solved by removing the lable tags from above and down to the buttons.

Thanks all in contributing my answer.

The World is Gold if U r Bold.


text:
Q: React navigation - Render Custom Header Inside the Screen View Using React Navigation, I would like to pass a custom header component using header option in navigationOptions.
The problem is that the header is rendered outside of the screens view. In my case I want it to be part of the screen's ScrollView, and scroll up along with the screen (not stay sticky on the top).
I've tried setting header to null in navigationOptions, and manually put the header component inside the screen's ScrollView, but this way I can't access the headerProps that are passed to the header component when using the header option. The headerProps are necessary to access things like the previous scene etc.
Any solution for this?

A: You can do like this:

*

*Hide header from react-navigation and add your header in the screen component, inside ScrollView:

const SignedOut = createStackNavigator({
  SignIn: {
    screen: SignIn,
      navigationOptions: {
        header: () => null,
      },
    },
});

SignIn screen:

class SignIn extends React.Component<Props, State> {
  render() {
    return (
      <ScrollView style={styles.container}>
       <! -- add header for screen and content -->
      </ScrollView>
    )
  }
}
export default SignIn;

In this way you can render a custom header component inside your ScrollView.


text:
Q: laravel, filtering many to many relations with different filter I'm building a website with laravel.
I use these models:

*

*Post

*Countrytag

*Citytag

*Categorytag

A post can have many countrytags, citytags or categorytags and vice versa.
I would like to search posts by tags.
I use this function:
    public function blogsearchresults(Request $request)
        {
            $attributes=request()->validate([

                'countrytag_id'=>'required_without_all:citytag_id,categorytag_id',
                'citytag_id'=>'required_without_all:countrytag_id,categorytag_id',
                'categorytag_id'=>'required_without_all:countrytag_id,citytag_id'
            ]);
            $posts=Post::all();
            if($request->has('countrytag_id')) {
                $countryid=$attributes['countrytag_id'];
                $posts =$posts->whereHas('countrytags', function ($query) use ($countryid){
                $query->wherein('countrytag_id', $countryid);
                });
            }
            if($request->has('citytag_id')) {
                $cityid=$attributes['citytag_id'];
                $posts=$posts->whereHas('citytags', function ($query2) use ($cityid){
                $query2->wherein('citytag_id', $cityid);
                });
            }
            if($request->has('categorytag_id')) {
                $categoryid=$attributes['categorytag_id'];
                $posts=$posts->whereHas('categorytags', function ($query3) use ($categoryid){
                $query3->wherein('categorytag_id', $categoryid);
                });
            }
            $posts=$posts->paginate();

            return view('pages.blog.blogsearchresults', compact('posts'));

        }

But I get this error:
Method Illuminate\Database\Eloquent\Collection::whereHas does not exist.

Could you please help me in solving this issue?
Thank you

A: the method all() returns a collection, you can't use query builder methods on it. (also when you query build, you dont need to assign the value $posts over and over)
public function blogsearchresults(Request $request)
    {
        $attributes = request()->validate([

            'countrytag_id'=>'required_without_all:citytag_id,categorytag_id',
            'citytag_id'=>'required_without_all:countrytag_id,categorytag_id',
            'categorytag_id'=>'required_without_all:countrytag_id,citytag_id'
        ]);
        $postQuery = Post::query();
        if($request->has('countrytag_id')) {
            $countryid = $attributes['countrytag_id'];
            $postQuery->whereHas('countrytags', function ($query) use ($countryid){
            $query->wherein('countrytag_id', $countryid);
            });
        }
        if($request->has('citytag_id')) {
            $cityid = $attributes['citytag_id'];
            $postQuery->whereHas('citytags', function ($query2) use ($cityid){
            $query2->wherein('citytag_id', $cityid);
            });
        }
        if($request->has('categorytag_id')) {
            $categoryid = $attributes['categorytag_id'];
            $postQuery->whereHas('categorytags', function ($query3) use ($categoryid){
            $query3->wherein('categorytag_id', $categoryid);
            });
        }
        $posts = $postQuery->paginate();

        return view('pages.blog.blogsearchresults', compact('posts'));

    }


text:
Q: Excel2010 VBA: Get all comments of row is there any chance getting all comments of a single row as an array?
So, all I wanna have is a handy way to display all comments in a message box like this:
Dim cmt As Comment
For Each cmt In ActiveSheet.Comments
    MsgBox cmt.Text, vbOKOnly
Next cmt

But I cannot find any hint how to do about a single row. :(
THX :)

A: You are very, very close...
If you want to display all comments in separate MsgBox(es) (here in the code below- for row no. 6) you can do it in this way:
Sub test()
Dim cmt As Comment
For Each cmt In ActiveSheet.Comments
    'check row in this way...- using if statement-:
    If cmt.Parent.Row = 6 Then
        MsgBox cmt.Text, vbOKOnly
    End If
Next cmt
End Sub


text:
Q: Tranpose Rows to Columns while keeping part of dataframe in tact I am trying to move some of my rows and make the them columns, but keep a large portion of the dataframe the same.
My Dataframe looks something like this:
ID  Thing      Level1 Level2  Time OAttribute IsTrue Score Value
1   bicycle    value  value  9:30  whatever    yes   1     type1
2   non-cycle  value  value  1:30  whatever    no    2     type2
3   bicycle    value  value  2:30  whatever    yes
4   bicycle    value  value  3:30  whatever    no    4     type3

And I want something like this:
ID  Thing Level1 Level2  Time OAttribute      IsTrue  Type1  Type2 Type 3
1   bicycle    value  value  9:30  whatever     yes   1
2   non-cycle  value  value  1:30  whatever     no            2
3   bicycle    value  value  2:30  whatever      yes
4   bicycle    value  value  3:30  whatever     no                   4

A: Something like this?
In [112]: df
Out[112]:
   ID      Thing Level1 Level2  Time OAttribute IsTrue  Score  Value
0   1    bicycle  value  value  9:30   whatever    yes      1  type1
1   2  non-cycle  value  value  1:30   whatever     no      2  type2
2   3    bicycle  value  value  2:30   whatever    yes    NaN    NaN
3   4    bicycle  value  value  3:30   whatever     no      4  type3

In [113]: dg = pd.DataFrame(columns=df['Value'].dropna().unique())

In [114]: for i in range(len(df)):
     ...:     key = df.loc[i]['Value']
     ...:     value = df.loc[i]['Score']
     ...:     if key is not pd.np.nan:
     ...:         dg.loc[i, key] = value
     ...:

In [115]: dg
Out[115]:
Value type1 type2 type3
0         1   NaN   NaN
1       NaN     2   NaN
3       NaN   NaN     4

In [116]: df.join(dg).drop('Value', 1).fillna('')
Out[116]:
   ID      Thing Level1 Level2  Time OAttribute IsTrue Score type1 type2 type3
0   1    bicycle  value  value  9:30   whatever    yes     1     1
1   2  non-cycle  value  value  1:30   whatever     no     2           2
2   3    bicycle  value  value  2:30   whatever    yes
3   4    bicycle  value  value  3:30   whatever     no     4                 4

A: Option 1
Use merge
df_ = df[['ID', 'Value']].dropna().set_index('Value', append=True).ID.unstack()

df.drop('Value', 1).merge(df_, right_index=True, left_index=True, how='left').fillna('')

Option 2
Use pd.concat
df_ = df[['ID', 'Value']].dropna().set_index('Value', append=True).ID.unstack()

pd.concat([df, df_], axis=1).drop('Value', 1).fillna('')


text:
Q: iPhone accelerometer in web applications I want my website to change its layout according to the device positon. The site has 2 layout types: vertical(height > width) ang horizontal(width > height).
do you see any solution?
upd: I don't see any complexity in changing the site layout. I want to know is there any event to handle.
p.s. will iphone's browser change its orientation if i rotate the device 90 degree?
Dave, tnx for emendation.

A: There is a javascript event called onorientationchange sent when the orientation changes and also there is a property called orientation on the window object that tells what the current orientation is.
See the documentation for more info and sample.