text:
Q: how to add scrollbar to all the bootstrap div in html? I am using bootstrap classes for my view page. But I want to add a scrollbar to my div. It's not adding.

Expected Result:-
I want a scroll bar which will be having my last div. As col-md-12 will contain 6 div but the 7th div should be hidden.
Current Result:-
7th div is coming in the second line. No scrollbar is getting added.

A: if you are using Bootstrap 4, change this
Change Class Name col-md-12 row to d-flex

https://jsfiddle.net/lalji1051/zkvu9o5r/5/

A: Create a CSS file and include it at the top of the HTML file, and in the CSS file write the following code:
body > div {
    overflow-X: scroll;
}


text:
Q: How to solve: console.error: "redux-persist failed to create sync storage. falling back to "noop" storage I'm trying to setup redux-persist in a react native app.
However I'm hitting this error:

console.error: "redux-persist failed to create sync storage. falling
  back to "noop" storage

I've tried to change the storage from storage to AsyncStorage in "src/redux/index.js", but it's still hitting the same error:
import AsyncStorage from '@react-native-community/async-storage';

const config = {
  key: "root",
  storage: AsyncStorage // Attempted to fix it (but failed)
  // storage // old code
};

Here's the other codes:
In App.js:
import React, { Component } from "react";
import { Provider } from "react-redux";
import { persistStore } from "redux-persist";
import { PersistGate } from "redux-persist/es/integration/react";
import store from "@store/configureStore";
import Router from "./src/Router";

export default class ReduxWrapper extends Component {
  render() {
    const persistor = persistStore(store);
    return (
      <Provider store={store}>
        <PersistGate persistor={persistor}>
          <Router />
        </PersistGate>
      </Provider>
    );
  }
}

In configureStore.js:
import { applyMiddleware, compose, createStore } from "redux";
import thunk from "redux-thunk";
import reducers from "@redux";

const middleware = [
  thunk,
  // more middleware
];

const configureStore = () => {
  let store = null;
  store = compose(applyMiddleware(...middleware))(createStore)(reducers);
  return store;
};

export default configureStore();

In /src/redux/index.js
import { persistCombineReducers } from "redux-persist";
import storage from "redux-persist/es/storage";

import { reducer as NetInfoReducer } from "./NetInfoRedux";
import { reducer as UserRedux } from "./UserRedux";

const config = {
  key: "root",
  storage,
};

export default persistCombineReducers(config, {
  netInfo: NetInfoReducer,
  user: UserRedux,
}

In Router.js
import React from "react";
import NetInfo from "@react-native-community/netinfo/lib/commonjs";
import { Config, AppConfig, Device, Styles, Theme, withTheme } from "@common";
import { AppIntro } from "@components";
import { connect } from "react-redux";

class Router extends React.PureComponent {
  constructor(props){
    super(props)
    this.state = {
      loading: true,
    };
  }

  componentWillMount() {
    NetInfo.getConnectionInfo().then((connectionInfo) => {
      this.props.updateConnectionStatus(connectionInfo.type != "none");
      this.setState({ loading: false });
    });
  }

  render() {
    return <AppIntro />;
  }
}

export default withTheme(
    connect(
    //   mapStateToProps,
    //   mapDispatchToProps
    )(Router)
);

Update:
Managed to solve the error base on mychar suggestion: github.com/rt2zz/redux-persist/issues/1080:
1) npm install --save @react-native-community/async-storage
2) on iOS, remember to perform "pod install" in iOS folder
3) Change storage to AsyncStorage
old code => import storage from 'redux-persist/lib/storage';
new code => import AsyncStorage from '@react-native-community/async-storage';

old code =>
const persistConfig = {
//...
storage,
}

new code =>
const persistConfig = {
//...
storage: AsyncStorage,
}

However, still getting this warning:

A: I solve it by removing :
import storage from 'redux-persist/lib/storage'

and replacing it with:
import { AsyncStorage } from 'react-native'

Don't forget this :
const rootPersistConfig = {
    key: 'root',
    storage: AsyncStorage
}

A: I faced the same issue, even though I replaced storage with AsyncStorage.
I solved the issue by removing the import line of the original storage
import storage from "redux-persist/es/storage"; //remove this

A: Before redux-persist v6.0.0 you were using storage like this:
import storage from 'redux-persist/lib/storage';

What this uses in background is AsyncStorage that was in react-native core.
Since react-native has deprecated AsyncStorage and will remove it from react-native core then the new version of redux-persist has stopped using it and it seems a good decision.
You can do the same now but instead import AsyncStorage from community version.
import AsyncStorage from '@react-native-community/async-storage';

And then use in in your config:
const persistConfig = {
  storage: AsyncStorage,
  //other configurations
};

Downgrading to redux-persist v5 is not a stable solution since it uses AsyncStorage from core react-native and react-native will remove it completely in the upcoming versions.
Also I read in comments that you don't like AsyncStorage, well as I explained redux-persist has been using it as a storage so the only difference now is that you should get it from community version and not from react-native core

A: My error was solved by downgrading redux-persis version to "5.10.0".

A: Comment out / exclude this line from your imports  import storage from 'redux-persist/lib/storage'
ensure that only async storage is imported
import AsyncStorage from '@react-native-community/async-storage';

A: First of all import AsyncStorage using below line
import AsyncStorage from '@react-native-community/async-storage';

Secondly the persistConfig should be assigned AsyncStorage like below and if you supplied storage object then comment it out
const persistConfig = {
    // storage,
    storage: AsyncStorage,
}

Lastly the below line importing storage or any other storage should not exist in your file
// import storage from 'redux-persist/lib/storage'  COMMENT THIS OUT

This is how I solved mine problem.

A: For Expo SDK version >=33 Workflow, the plugin
@react-native-community/async-storage doesn't work.
It worked for me.
import { AsyncStorage } from 'react-native';`
.
.
.
const persistConfig = {
  key: 'root',
  storage: AsyncStorage
}

reference: https://docs.expo.io/versions/latest/react-native/asyncstorage/

A: In redux-persist v6, you try changing as follows:
Old config V5 =>
import storage from 'redux-persist/lib/storage';
const persistConfig = {
   //...
   storage,
}

New config v6 =>
First add: yarn add @react-native-async-storage/async-storage
import AsyncStorage from '@react-native-async-storage/async-storage';
const persistConfig = {
  //...
  storage: AsyncStorage,
}

A: comment out //import storage from "redux-persist/lib/storage";
and import from  import AsyncStorage from '@react-native-community/async-storage';

A: Downgrade redux-persist to 5.10.0

redpajama_set_name: RedPajamaStackExchange


text:
Q: Boot from usb take forever Recently I made the stupid mistake of erasing MacBook Pro (2012) HDD without immediately installing OS X. And now it can't even boot or get to recovery utilities.
So I decided to make a bootable OS X El Capitan usb installer. I could select it as boot drive and it go to screen with Apple logo and a progress bar. However the progress bar takes very long to build up (more than an hour) and you could hear the HDD spinning really hard. Finally the progress bar is filled but nothing happen for an hour now. Please let me know how to fix this problem.
Thanks!

A: OP here, it was actually pretty simple to fix. I just hard reset it and try again. Had to hard reset twice before the setup succeed.
I don't know why but my guess is that El Capitan is quite newer than my laptop so it takes a few tries to iron out all the conflicts.


text:
Q: T-SQL Replacing If Else (Case When) with lookup table *edit
As pointed out my question provided the neccessary details. So I will try to be precise.
The bloated If Else structure is used in a crystal report. The result is a csv export. This is the way it works now. :) The design decission was to rework this and generate dynamic SQL. So that these bloated If Else structures will become part of a SQL query.
Right now I've implemented a modell to be able to create T-SQL dynamically. I've come up with a table that holds the column definitions for the Select part of the query, a table that holds the join conditions and a table that holds the where conditions. In a stored procedure all the information is gathered and a T-SQl query is the result.
SELECT Column Definition Table:
ColumnName  T-SQL                           OrderID IncludeInSelectList InterfaceID_ID
Monat       SUBSTRING(CP.TCOEP_PERIO, 2,2)  1       1                   1
Jahr        CP.TCOEP_GJAHR                  2       1                   1

The problem is that in the table with the column definition the column that will store the SQL definition (e.g. Substring(ColA, 2,3)) has the max length restriction of 4000 characters.
The more I'm trying to explain it, the more I'm getting the feeling that trying to get everything into one giant query isn't a good idea at all. I have to speak to my superior I guess. ;)
*edit
I'm having troubles replacing a bloated If Else structure. Here is an example:
If ColA startswith 'ABC' then 'Ext' else
If ColB startswith 'DBC' then 'Int' else
If ColC startswith ('CCC', 'DDD','EEE', ..) then 'N/A'

.... and so on.
I know I can rewrite this into a Case When structure. The problem is that this needs to be stored in a table where the max length is nvarchar(4000). I tried to solve this with a lookup table looking like this:
lookupColumnName | lookupValue | lookupResultName | lookupResult
I was trying to write my query in a more "generic" way like:

SELECT
   (SELECT lookupResult from lookupTable where lookupColumn = 'ColA')
FROM
SourceTable

Here is my first try to implement the order of the origanel If Else structure:

CASE WHEN
    CASE WHEN
        CASE WHEN
        (
        SELECT TOP 1 lookupResult FROM ##lookupDefinition where lookupColumnName = 'BKTXT' AND BKPF_BKTXT like lookupValue order by len(lookupValue) DESC
        ) IS NULL THEN (
        SELECT TOP 1 lookupResult FROM ##lookupDefinition where lookupColumnName = 'XBLNR' AND BKPF_XBLNR like lookupValue order by len(lookupValue) DESC
        ) ELSE (
        SELECT TOP 1 lookupResult FROM ##lookupDefinition where lookupColumnName = 'BKTXT' AND BKPF_BKTXT like lookupValue order by len(lookupValue) DESC
        ) END
        <> 'LEER' THEN
        CASE WHEN
        (
        SELECT TOP 1 lookupResult FROM ##lookupDefinition where lookupColumnName = 'BKTXT' AND BKPF_BKTXT like lookupValue order by len(lookupValue) DESC
        ) IS NULL THEN (
        SELECT TOP 1 lookupResult FROM ##lookupDefinition where lookupColumnName = 'XBLNR' AND BKPF_XBLNR like lookupValue order by len(lookupValue) DESC
        ) ELSE (
        SELECT TOP 1 lookupResult FROM ##lookupDefinition where lookupColumnName = 'BKTXT' AND BKPF_BKTXT like lookupValue order by len(lookupValue) DESC
        ) END
        ELSE
        (
        SELECT TOP 1 lookupResult FROM ##lookupDefinition where lookupColumnName = 'SGTXT' AND COEP_SGTXT like lookupValue order by len(lookupValue) DESC
        )
    END IS NULL THEN 'App'
    ELSE
    CASE WHEN
        CASE WHEN
        (
        SELECT TOP 1 lookupResult FROM ##lookupDefinition where lookupColumnName = 'BKTXT' AND BKPF_BKTXT like lookupValue order by len(lookupValue) DESC
        ) IS NULL THEN (
        SELECT TOP 1 lookupResult FROM ##lookupDefinition where lookupColumnName = 'XBLNR' AND BKPF_XBLNR like lookupValue order by len(lookupValue) DESC
        ) ELSE (
        SELECT TOP 1 lookupResult FROM ##lookupDefinition where lookupColumnName = 'BKTXT' AND BKPF_BKTXT like lookupValue order by len(lookupValue) DESC
        ) END
        <> 'LEER' THEN
        CASE WHEN
        (
        SELECT TOP 1 lookupResult FROM ##lookupDefinition where lookupColumnName = 'BKTXT' AND BKPF_BKTXT like lookupValue order by len(lookupValue) DESC
        ) IS NULL THEN (
        SELECT TOP 1 lookupResult FROM ##lookupDefinition where lookupColumnName = 'XBLNR' AND BKPF_XBLNR like lookupValue order by len(lookupValue) DESC
        ) ELSE (
        SELECT TOP 1 lookupResult FROM ##lookupDefinition where lookupColumnName = 'BKTXT' AND BKPF_BKTXT like lookupValue order by len(lookupValue) DESC
        ) END
        ELSE
        (
        SELECT TOP 1 lookupResult FROM ##lookupDefinition where lookupColumnName = 'SGTXT' AND COEP_SGTXT like lookupValue order by len(lookupValue) DESC
        )
    END
END

But this approach could also result in a string containing more than 4000 characters.
Right now I'm stuck. Is there a better way?

A: It is pretty difficult to follow your exact logic, since it is pretty complicated and not helped by the fact that no columns have table aliases so I don't know what column belongs to what table.
I have however given it a go. Since you are reusing the same correlated subquery multiple times, it would probably be beneficial to move these to an APPLY so that the result can be reused. I then just tried to pick apart your logic replacing the statements like:
CASE WHEN <expression1> IS NULL THEN <expression2> ELSE <expression1> END

With
ISNULL(<expression1>, <expression2>)

Giving a final query of:
SELECT  CASE WHEN ISNULL(BKTXT.LookupResult, XBLNR.LookupResult) <> 'LEER' THEN
            ISNULL(BKTXT.LookupResult, XBLNR.LookupResult)
        ELSE
            ISNULL(SGTXT.LookupResult, 'App')
        END
FROM    SourceTable
        CROSS APPLY
        (   SELECT TOP 1 lookupResult
            FROM ##lookupDefinition
            WHERE lookupColumnName = 'BKTXT'
            AND COEP_SGTXT LIKE lookupValue
            ORDER BY LEN(lookupValue) DESC
        ) AS BKTXT
        CROSS APPLY
        (   SELECT TOP 1 lookupResult
            FROM ##lookupDefinition
            WHERE lookupColumnName = 'XBLNR'
            AND COEP_SGTXT LIKE lookupValue
            ORDER BY LEN(lookupValue) DESC
        ) AS XBLNR
        CROSS APPLY
        (   SELECT TOP 1 lookupResult
            FROM ##lookupDefinition
            WHERE lookupColumnName = 'SGTXT'
            AND COEP_SGTXT LIKE lookupValue
            ORDER BY LEN(lookupValue) DESC
        ) AS SGTXT;

A: Your attempt to use a "more generic" way, pushed me to this idea:
CREATE FUNCTION dbo.GetLookUp(@LookupColumnName AS VARCHAR(100))
RETURNS VARCHAR(100)
AS
BEGIN
    DECLARE @RetVal VARCHAR(100)='#missing value!!!';
    SELECT lookupResult from lookupTable where lookupColumn = @LookupColumnName;
    RETURN @RetVal;
END

Your
SELECT
   (SELECT lookupResult from lookupTable where lookupColumn = 'ColA')
FROM
SourceTable

Is transfered to
SELECT dbo.GetLookUp('ColA')
FROM
SourceTable

That would mean you save a lot of characters.
But I must admit that the whole concept is not clear to me and there is quite some smell of to much complexity. Maybe you want to give details about your table structures, some sample data and expected output.
I'm quite sure, that there is some better approach...


text:
Q: Spring parallel processing inside a transaction I have lots of micro services that perform database custom logic on pretty big data volumes. Every instance of these microservices use the following query: select * from ENTITY_TABLE for update skip locked to organize parallel work on this data and prevent data sets intersections.
The thing is that on each entity fecthed (batch size is around 100) I need to perform 3 more db requests and this takes pretty much time and not effective in general.
What I'd like to do is to organize parallel processing of each entity inside one big transaction. The main problem is that spring doesn't allow this. My code is something like this:
public class Manager {
    private final Fetcher fetcher;
    private final Processor processor;
    private TransactionTemplate transactionTemplate;

    public void doWork(int batchSize) {
        transactionTemplate.executeWithoutResult(status -> {
            List<MyEntity> entities = fetcher.fetch(batchSize);
            List<CompletableFuture<Boolean>> resultList = new ArrayList<>();
            for(MyEntity me : entities) {
                resultList.add(processor.process(entity));
            }
            CompletableFuture.allOf(resultList.toArray(new CompletableFuture[0])).join();
        });
    }
}

public class Fetcher {
    private JdbcTemplate jdbcTemplate;

    public List<MyEntity> fetch(int batchSize) {
        jdbcTemplate.setFetchSize(batchSize);
        jdbcTemplate.setMaxRows(batchSize);
        return jdbcTemplate.query("select * from ENTITY_TABLE for update skip locked", new BeanPropertyRowMapper<>(MyEntity.class);
    }
}

public class Processor() {
    @Async // <- this messes up transaction and makes it impossible to perform this work in parallel fashion inside transaction opened in the Manager class
    public void CompletableFuture<Boolean> process(MyEntity me) {
        boolean exists = repository.existsRelatedEntity(me.getId());
        if (!exists) {
            repository.createRelatedEntity(new RelatedEntity(/*..*/));
        } else {
            repository.updateRelatedEntity(me);
        }
        repository.markProcessed(me);
    }
}

And the question is: Do I have any options here to make this possible to parallel work on te process function? Do I have some possibility to point jdbcTemplate on the transaction it should use for its opertions?
Any help is greatly appreciated.
Disclaimer: I know that I can mark all of the selected entities with help of additional update query and then process them one by one in separate transactions but I would like to see if I have any options here cause I simplified the code and in reality it is much more complex and would require a big rework in case of logic changes.

A: If Fetcher and Processor are in the same service it should work in the same transaction after adding @Transactional(isolation = Isolation.READ_UNCOMMITTED) annotation on public void doWork(int batchSize);
I tested this with spring repository instead of JdbcTemplate and it seems to be working.
If you have any errors, please add it to your post


text:
Q: How to use PhpStorm autocomplete from class inside container array Yesterday I started using an container array which contains my classes. Now I have the Problem, that I can't use autocomplete for the Classes Functions.
Here's a small example of what my container looks like:
$container[PDO::class] = function () use ($container) {
    return new PDO('mysql:host=' . $container['database_host'] . ';dbname' . $container['database_name'], $container['database_user'], $container['database_pass']);
};

$container[\Envms\FluentPDO\Query::class] = function () use ($container) {
    return new \Envms\FluentPDO\Query($container[PDO::class]());
};

$container[\Twig\Loader\FilesystemLoader::class] = function () use ($container) {
    return new \Twig\Loader\FilesystemLoader($container['template_dir']);
};

$container[\Twig\Environment::class] = function () use ($container) {
    return new \Twig\Environment(new $container[\Twig\Loader\FilesystemLoader::class]());
};

return $container;

Is there a way to use autocomplete for the functions inside classes which are created within the $container array?


text:
Q: AJAX readystatechange listener for IE7+8 (function (send) {

     XMLHttpRequest.prototype.send = function () {

         this.addEventListener('readystatechange', function() {

             console.log('readyState changed');

         }, false);

         send.apply(this, arguments);
     };

})(XMLHttpRequest.prototype.send);

This works, but it seems to be affecting other frameworks (like jQuery). When I use the code above, my jQuery ajax calls doen't complete (IE7 + IE8).
Is there any way to give the event a new alias so that it doesn't cause any conflicts (I'm just assuming that this is the problem)?
And I can't use this.onreadystatechange, since jQuery is overwriting it (see Fiddle).
As soon as I bind the event listener, the code seems to fail silently so I can't use the console to debug.
Fiddle
Compare in ie8 vs ie9 mode and notice that the console is empty in ie8
The reason why I need this is that I want a global ajax handler for another framework (GWT). I use jQuery just for testing it now.
Edit: Looks like only ie9 supports addEventListener. However, attachEvent doesn't seem to exist on the XHR object in ie7-8.

A: We have had similar issue with jquery failing on IE8. I assume that you are making a cross domain request. Jquery does ajax through the XMLHttpRequest , but IE8 has replaced XMLHttpRequest object with XDomainRequest and jquery folks do not support it.So for IE8 , you will have to modify the code to use XDomainRequest with jquery.
see the links
Using jquery ajax for IE8


text:
Q: What's the right statistic for iOS Memory footprint. Live Bytes? Real Memory? Other? I'm definitely confused on this point.
I have an iPad application that shows 'Live Bytes' usage of 6-12mb in the object allocation instrument. If I pull up the memory monitor or activity monitor, the 'Real Memory' Column consistently climbs to around 80-90mb after some serious usage.
So do I have a normal memory footprint or a high one?
This answer and this answer claim you should watch 'Live Bytes' as the 'Real Memory' column shows memory blocks that have been released, but the OS hasn't yet reclaimed it.
On the other hand, this answer claims you need to pay attention to that memory monitor, as the 'Live Bytes' doesn't include things like interface elements.
What is the deal with iOS memory footprint!? :)

A: Those are simply two different metrics for measuring memory use. Which one is the "right" one depends on what question you're trying to answer.
In a nutshell, the difference between "live bytes" and "real memory" is the difference between the amount of memory currently used for stuff that your app has created and the total amount of physical memory currently attributed to your app. There are at least two reasons that those are different:

*

*code: Your app's code has to be loaded into memory, of course, and the virtual memory system surely attributes that to your app even though it's not memory that your app allocated.

*memory pools: Most allocators work by maintaining one or more pools of memory from which they can carve off pieces for individual objects or allocated memory blocks. Most implementations of malloc work that way, and I expect that the object allocator does too. These pools aren't automatically resized downward when an object is deallocated -- the memory is just marked 'free' in the pool, but the whole pool will still be attributed to your app.
There may be other ways that memory is attributed to your app without being directly allocated by your code, too.
So, what are you trying to learn about your application? If you're trying to figure out why your app crashed due to low memory, look at both "live bytes" (to see what your app is using now) and "real memory" (to see how much memory the VM system says your app is using). If you're trying to improve your app's memory performance, looking at "live bytes" or "live objects" is more likely to help, since that's the memory that you can do something about.

A: Seeing as how I wrote the last answer you linked to, I'll have to stand by that. If you want a total, accurate count of the current memory usage for your application, use the Memory Monitor instrument.
For reasons that I describe in this answer, Allocations hides the memory sizes of certain elements, meaning that its memory usage totals are significantly lower than your application's in-memory size. Many people find this out the hard way when they try to get their application functional on older iOS devices. On the older hardware, you had a hard memory ceiling of ~30 MB, where if you exceeded that your application was hard-killed.
Many developers (myself included) saw that we only had ~1-2 MB of live bytes in Allocations and thought we were good, until our applications started receiving memory warnings and early terminations. If you looked at Memory Monitor, you could see the true in-memory size of these applications being >20 MB, and you could see the applications being terminated the instant they crossed the 30 MB barrier in Memory Monitor.
Therefore, if you want an accurate assessment of your total application memory usage, use Memory Monitor. Allocations is great to find out the specific objects that are in memory, particularly when you use the heap shots to find things that might be accumulating (as leaks, retain cycles, or for other reasons). Just don't trust it when determining your application's actual size in memory.

A: 'Live bytes' means memory allocated by your code (for example by malloc), so you have access to this memory. 'Real memory' shows physical amount of memory used by your app. This include also OpenGL textures, (possibly) sounds from Open AL...
Live bytes is useful to check when you allocate and release memory in your code. Real memory is good indicator for memory optimization efficiency. And it's overhead causes 'low memory' warnings.


text:
Q: Is it compulsory to make a folder before creating react app why cannot create react app directly in a directory before going in a particular folder
D:\>create-react-app ananya

Creating a new React app in D:\ananya.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts...

npm ERR! Unexpected end of JSON input while parsing near '...e"},"devDependencies"'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\sethi\AppData\Roaming\npm-cache\_logs\2019-08-24T05_53_19_688Z-debug.log

Aborting installation.
  npm install --save --save-exact --loglevel error react react-dom react-scripts has failed.

Deleting generated file... package.json
Deleting ananya/ from D:\
Done.

D:\>

A: You can also try
npx create-react-app ananya

This will create the project folder ananya and have the project files in it.
OR
npx create-react-app .

This will create the project in the current folder.
Note: The current folder must be empty. Project name will be the folder name. So you have to properly name your folder before executing.

A: You can create directly in your D:\ directory. Error is nothing to do with the folder.
You just need to clear your npm cache and try again. Run the below command in your cmd.
npm cache clean --force

You can also clean the cache by deleting all the content in this folder manually : `

C:\Users\YOUR_USER_NAME\AppData\Roaming\npm-cache

`


text:
Q: How to Get Outgoing call duration with Twilio Client API in Android? I have developed Twilio SDK in my Android application. For outgoing and incoming it is worked well. But when i try to set the timer for call duration, i am unable to get the notification from the other device. Is there any method to find out the other device(Which was notified after picking the call)?
Please help me on this.
Thanks,

A: I'm not sure if you still need help with this or not, or I get exactly your issue.
What I'm doing is keeping the timestamp of when the call was started (incoming/outgoing) in any of the clients. Then in my activity/fragment, since I have my own callbacks for the Twilio events, as soon as I know there's a call going on, I use Chronometer which is like a TextView that automatically sets things as soon as you set a base time and start it.

*

*get timestamp of when that call started

*Chronometer.setBase(timestamp);

*Chonometer.start();

So it shows the duration. Remember to have your own Twilio manager class to hold that value for you so if you leave your activity and come back, the duration will be displayed correctly.
Good luck


text:
Q: Inclusion Exclusion with 4 sets: How many integers between 1 and 100 are divisible by 2 or 3 or 5 or 7? How many numbers between 1 and 100 are divisible by 2 or 3 or 5 or 7?
The solution I had gives a different answer from what was provided, so I was wandering if anyone could tell me what mistake I made?
Let A be the set of those divisible by 2, B the set of those divisible by 3, C the set of those divisible by 5 and D the set of those divisible by 7.
Singles:
$|A| = 50$, $|B| = 33$, $|C| = 20$, $|D| = 14$
Doubles:
$|A \cap B|=16$, $|A \cap C|=10$,
$|A \cap D|=7$, $|B \cap C|=6$,
$|B \cap D|=4$, $|C \cap D|=2$
Triples:
$|A \cap B \cap C|=3$, $|A \cap B \cap D|=2$
$|A \cap C \cap D|=1$, $|B \cap C \cap D|=0$
Quadruples:
$|A \cap B \cap C \cap D|=0$
Inclusion Exclusion:
$|A \cup B \cup C \cup D| = $ Sum of Singles $-$ Sum of Doubles $+$ Sum of Triples $-$ Sum of Quadruples
$
|A\cup B\cup C\cup D|=|A|+|B|+|C|+|D|\\
-(|A\cap B|+|A\cap C|+|A\cap D|+|B\cap C|+|B\cap D|+|C\cap D|)\\
+(|A\cap B\cap C|+|A\cap B\cap D|+|A\cap C\cap D|+|B\cap C\cap D|)\\
-|A\cap B\cap C\cap D|\\
$
$|A \cup B \cup C \cup D| = 50 + 33 + 20 + 14 - 16 - 10 - 7- 6 - 4 - 2 + 3 + 2 + 1$
$|A \cup B \cup C \cup D| = 114 - 45 + 6$
$|A \cup B \cup C \cup D| = 75$
The answer given to us was 78, but I can't tell whether it's a mistake or if I've made a mistake somewhere here.

A: $$50+33+20+14=11\color{red}{7}.$$


text:
Q: Python Tkinter: Referencing a slider value in multiple threads results in error I created a custom tkinter widget class which has (among other things) a slider. The below methods run_control_thread and control_loop are methods within said class. They run a thread that sends a command to a motor when a button (also a "child" of my widget class) is pressed. This works fine when only one widget is controlling a motor, but if there are multiple widgets controlling (different) motors, an error pops up when trying to run self.slider.get(), seen in the run_control_thread method. Instead of getting the value of the slider, it gets an exception. I'm quite new to Python, Tkinter, and Stack Overflow, so any help would be appreciated!
    def run_control_thread(self):
        global HTTP, command
        print("running")
        def run_thread():
            global HTTP, command
            current_device = CANDeviceDict[self.current_chosen]
            while(self.control_loop_enabled == True):
                demand = self.slider.get()
                HTTP.send_command(command.control(current_device.model, current_device.id, demand, False, False,
                                  self.control_mode_value(), 0, 0, False, False))
                time.sleep(0.028)
        control_thread = threading.Thread(target=run_thread)
        control_thread.start()

    def control_loop(self):
        global HTTP, selected_device, command
        if HTTP != None and command != None and selected_device != None:
            if (self.control_loop_enabled):
                self.control_loop_enabled = False
                self.enable_control.config(text="Enable Control")
                self.slider.set(0)
            else:
                self.control_loop_enabled = True
                self.enable_control.config(text="Disable Control")
            self.run_control_thread()

The errors:
>Exception in thread Thread-4"
Traceback (most recent call last):
    File "C:\...\Python\Python38-32\lib\tkinter\__init__.py", line 3457, in get
    return self.tk.getint(value)
    _tkinter.TclError: expected integer but got "expected integer but got "0.00""
    <class 'tkinter.Scale'>

>During handling of the above exception, another exception occurred:
Traceback (most recent call last):
    File "C:\...\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
    File "C:\...\Python\Python38-32\lib\threading.py", line 870, in run
    demand = self.slider.get()
    File "C:\...\Python\Python38-32\lib\tkinter\__init__.py", line 3460, in get
    return self.tk.getdouble(value)
    <class 'tkinter.Scale'>
    _tkinter.TclError: expected floating-point number but got "expected integer but got "0.00""


text:
Q: How to capture the result of DOS Commands in C++ I am creating a windows application that must capture results of several DOS Commands without the command prompt opening and save them into a string. I am using the borland libraries.
system("dir") therefore is not good. The result of each command needs to be written to a string variable so I can write it to a log and a separate file.
I have an XML file where they are defined.
The thing i'm struggling on the most is actually capturing the output into a string variable. I have heard of _popen but having problems trying to use it.

A: I think what you really want is freopen() that allows you to redirect the usual streams to a file (either temporary or the separate file you mentioned), and when the process closes, read the file into your log.
I assume the 'result' is the output from the command, and not its return value.


text:
Q: How to align two divs of same height and third div in next line I need to display an image(left-side) in one column and display a button(on Right side column) and description in second column(on right side column). i got the result as expected, but in mobile view, i need to display the button  on left bottom and on the right side, the image should be place. The description column should come in the next line.

Button

Description Text Comes here

In mobile view the button and the image should be aligned towards bottom. as shown in the picture.

A: If I understand well, you need to re-order your elements on mobile devices? I suggest you use flexbox for it:
.row {
    display: flex;
    flex-direction: row;
}
.image-block {
    order: 2;
}
.button-block {
    order: 1;
}
.text-block {
    order: 3;
    flex-basis: 100%;
}

with flex-basis: 100%, you force the element 100% width.
Is this the solution you are looking for?


text: Q: Error while installing Google App Engine SDK in eclipse 3.7 I am trying to install the Google App Engine SDK in eclipse 3.7(Indigo) and i keep gettin the following error which is shown in the picture. I am using Windows 7. Could anyone direct me as to what to do to get over with this.


text:
Q: How to disable Safari Network Caches for specific URLs only? I am aware that in Safari you are able to disable all network cache by going to Web Inspector (Command + Control + i), network tab, and then check the disable caches button. That's nice but it would be even more nice if I could specify for what URLs the network cache should be disabled.
That way I would not have to toggle the network cache between each development session. Instead I'd be able to disable the network cache for all local.* , https://www.myurl.com or something like that.
Does anyone know of any way to achieve this in a simple way?


text:
Q: Implementing functions in another class I am having trouble with this function I created: enter(linearLayout, llp). I created it in my class Game but am trying to implement it in my class MyTouchListener.
And as you can see below, I made class MyTouchListener extend class Game so it can get the functions of that class, including enter(linearLayout, llp)
Currently the enter(linearLayout, llp) is in the onFling method in class MyTouchListener but it does not work. My app crashes when I fling across the screen.
Can someone please tell me what is wrong here and offer a solution?
class MyTouchListener:
public class MyTouchListener extends Game implements OnTouchListener{

    protected static final String TAG = "MyTouchListener";
    protected static final boolean D = true;

    public interface MyListener{
        public void onTouch();
    }

    private MyListener mListener;
    private GestureDetector mGestureDetector;

    private class MyClickListener extends SimpleOnGestureListener{

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            if (D){
                enter(linearLayout, llp); //ERROR HERE
                Log.d(TAG, "2 - onFling event");

            }
            return true;
        }
    }

    public MyTouchListener(Context context, MyListener listener){
        mGestureDetector = new GestureDetector(context, new MyClickListener());
        mListener = listener;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (D){
            Log.d(TAG, "2 - onTouch event");
        }
        mListener.onTouch();
        mGestureDetector.onTouchEvent(event);
        return false;
    }
}

class Game:
public class Game extends Activity   {

    protected static LinearLayout linearLayout;
    protected static LinearLayout.LayoutParams llp;

    public void enter(String[] w, LinearLayout ll, LinearLayout.LayoutParams params){

    ...//code
    ...//code
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.game_activity);

        mListener = new MyListener() {

            @Override
            public void onTouch() {
                if (D){
                    Log.d(TAG, "2 - onTouch event");
                }
            }
        };

        for(Button b:button_list){
            b.setOnTouchListener(new MyTouchListener(getApplicationContext(), mListener));
        }

        linearLayout = (LinearLayout) findViewById(R.id.ll_bttn_words);

        llp = new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);

        llp.gravity = Gravity.TOP;

    }

Here is the error log. This occurs once I fling across the screen:
12-14 20:09:28.342: D/MyTouchListener(18212): 2 - onTouch event
12-14 20:09:28.342: D/MyTouchListener(18212): 2 - onTouch event
12-14 20:09:28.342: E/InputEventReceiver(18212): Exception dispatching input event.
12-14 20:09:28.342: E/MessageQueue-JNI(18212):  at android.view.GestureDetector.onTouchEvent(GestureDetector.java:1405)
12-14 20:09:28.342: E/MessageQueue-JNI(18212):  at android.view.View.dispatchTouchEvent(View.java:7456)
12-14 20:09:28.342: E/MessageQueue-JNI(18212):  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2270)
12-14 20:09:28.342: E/MessageQueue-JNI(18212):  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2010)
12-14 20:09:28.342: E/MessageQueue-JNI(18212):  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2270)
12-14 20:09:28.342: E/MessageQueue-JNI(18212):  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2010)
12-14 20:09:28.342: E/MessageQueue-JNI(18212):  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2270)
12-14 20:09:28.342: E/MessageQueue-JNI(18212):  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2010)
12-14 20:09:28.342: E/MessageQueue-JNI(18212):  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2270)
12-14 20:09:28.342: E/MessageQueue-JNI(18212):  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2010)
12-14 20:09:28.342: E/MessageQueue-JNI(18212):  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2270)
12-14 20:09:28.342: E/MessageQueue-JNI(18212):  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2010)
12-14 20:09:28.342: E/MessageQueue-JNI(18212):  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2270)
12-14 20:09:28.342: E/MessageQueue-JNI(18212):  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2010)
12-14 20:09:28.342: E/MessageQueue-JNI(18212):  at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2186)
12-14 20:09:28.342: E/MessageQueue-JNI(18212):  at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1516)
12-14 20:09:28.342: E/MessageQueue-JNI(18212):  at android.app.Activity.dispatchTouchEvent(Activity.java:2466)
12-14 20:09:28.342: E/MessageQueue-JNI(18212):  at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2134)
12-14 20:09:28.342: E/MessageQueue-JNI(18212):  at android.view.View.dispatchPointerEvent(View.java:7641)
12-14 20:09:28.342: E/MessageQueue-JNI(18212):  at android.view.ViewRootImpl.deliverPointerEvent(ViewRootImpl.java:3676)
12-14 20:09:28.342: E/MessageQueue-JNI(18212):  at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:3607)
12-14 20:09:28.342: E/MessageQueue-JNI(18212):  at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:4802)
12-14 20:09:28.342: E/MessageQueue-JNI(18212):  at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:4781)
12-14 20:09:28.342: E/MessageQueue-JNI(18212):  at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:4873)
12-14 20:09:28.342: E/MessageQueue-JNI(18212):  at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
12-14 20:09:28.352: E/AndroidRuntime(18212):    at android.view.GestureDetector.onTouchEvent(GestureDetector.java:1405)
12-14 20:09:28.352: E/AndroidRuntime(18212):    at android.view.View.dispatchTouchEvent(View.java:7456)
12-14 20:09:28.352: E/AndroidRuntime(18212):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2270)
12-14 20:09:28.352: E/AndroidRuntime(18212):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2010)
12-14 20:09:28.352: E/AndroidRuntime(18212):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2270)
12-14 20:09:28.352: E/AndroidRuntime(18212):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2010)
12-14 20:09:28.352: E/AndroidRuntime(18212):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2270)
12-14 20:09:28.352: E/AndroidRuntime(18212):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2010)
12-14 20:09:28.352: E/AndroidRuntime(18212):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2270)
12-14 20:09:28.352: E/AndroidRuntime(18212):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2010)
12-14 20:09:28.352: E/AndroidRuntime(18212):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2270)
12-14 20:09:28.352: E/AndroidRuntime(18212):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2010)
12-14 20:09:28.352: E/AndroidRuntime(18212):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2270)
12-14 20:09:28.352: E/AndroidRuntime(18212):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2010)
12-14 20:09:28.352: E/AndroidRuntime(18212):    at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2186)
12-14 20:09:28.352: E/AndroidRuntime(18212):    at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1516)
12-14 20:09:28.352: E/AndroidRuntime(18212):    at android.app.Activity.dispatchTouchEvent(Activity.java:2466)
12-14 20:09:28.352: E/AndroidRuntime(18212):    at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2134)
12-14 20:09:28.352: E/AndroidRuntime(18212):    at android.view.View.dispatchPointerEvent(View.java:7641)
12-14 20:09:28.352: E/AndroidRuntime(18212):    at android.view.ViewRootImpl.deliverPointerEvent(ViewRootImpl.java:3676)
12-14 20:09:28.352: E/AndroidRuntime(18212):    at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:3607)
12-14 20:09:28.352: E/AndroidRuntime(18212):    at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:4802)
12-14 20:09:28.352: E/AndroidRuntime(18212):    at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:4781)
12-14 20:09:28.352: E/AndroidRuntime(18212):    at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:4873)
12-14 20:09:28.352: E/AndroidRuntime(18212):    at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)

I tried tons of things including creating constructors for my Game class and apply it to my other class but that didn't work. So I thought the best strategy would be to make class MyTouchListener extend class Game and make the global variables static.


text:
Q: Minecraft Villager for Farming Potatoes A villager has been kidnapped and brought far from his village, and has been placed into a farm. I hope for him  to break and replant potatoes, but he does not break the crops or plant any.
Does the farm need to be inside a village? It is a few hundred blocks away from the nearest one.


text:
Q: unable to load android socket classes java.lang.NoSuchMethodException: com.android.org.conscrypt.OpenSSLSocketImpl.setUseSessionTickets [boolean] Hi everyone I am facing a problem with my retrofit code on an api call, I am posting the stack trace below please have a look at it:
    Accessing hidden method Lcom/android/org/conscrypt/OpenSSLSocketImpl;->setUseSessionTickets(Z)V (greylist-max-q,core-platform-api, reflection, denied)
2021-09-25 19:02:08.588 30949-30949/W/OkHttp: unable to load android socket classes
2021-09-25 19:02:08.588 30949-30949/W/OkHttp: java.lang.NoSuchMethodException: com.android.org.conscrypt.OpenSSLSocketImpl.setUseSessionTickets [boolean]
2021-09-25 19:02:08.588 30949-30949/W/OkHttp:     at java.lang.Class.getMethod(Class.java:2072)
2021-09-25 19:02:08.588 30949-30949/W/OkHttp:     at java.lang.Class.getDeclaredMethod(Class.java:2050)
2021-09-25 19:02:08.588 30949-30949/W/OkHttp:     at okhttp3.internal.platform.android.AndroidSocketAdapter.<init>(AndroidSocketAdapter.kt:34)
2021-09-25 19:02:08.588 30949-30949/W/OkHttp:     at okhttp3.internal.platform.android.StandardAndroidSocketAdapter.<init>(StandardAndroidSocketAdapter.kt:31)
2021-09-25 19:02:08.588 30949-30949/W/OkHttp:     at okhttp3.internal.platform.android.StandardAndroidSocketAdapter$Companion.buildIfSupported(StandardAndroidSocketAdapter.kt:57)
2021-09-25 19:02:08.588 30949-30949/W/OkHttp:     at okhttp3.internal.platform.android.StandardAndroidSocketAdapter$Companion.buildIfSupported$default(StandardAndroidSocketAdapter.kt:50)
2021-09-25 19:02:08.588 30949-30949/W/OkHttp:     at okhttp3.internal.platform.AndroidPlatform.<init>(AndroidPlatform.kt:44)
2021-09-25 19:02:08.588 30949-30949/W/OkHttp:     at okhttp3.internal.platform.AndroidPlatform$Companion.buildIfSupported(AndroidPlatform.kt:239)
2021-09-25 19:02:08.588 30949-30949/W/OkHttp:     at okhttp3.internal.platform.Platform$Companion.findPlatform(Platform.kt:211)
2021-09-25 19:02:08.588 30949-30949/W/OkHttp:     at okhttp3.internal.platform.Platform$Companion.access$findPlatform(Platform.kt:179)
2021-09-25 19:02:08.588 30949-30949/W/OkHttp:     at okhttp3.internal.platform.Platform.<clinit>(Platform.kt:180)
2021-09-25 19:02:08.588 30949-30949/W/OkHttp:     at okhttp3.OkHttpClient.<init>(OkHttpClient.kt:219)
2021-09-25 19:02:08.588 30949-30949/W/OkHttp:     at okhttp3.OkHttpClient$Builder.build(OkHttpClient.kt:955)
2021-09-25 19:02:08.588 30949-30949/W/OkHttp:     at .ui.retroPack.RetrofitClient.getClient(RetrofitClient.java:35)
2021-09-25 19:02:08.588 30949-30949/W/OkHttp:     at .ui.retroPack.RetrofitClient.getAPIService(RetrofitClient.java:52)
2021-09-25 19:02:08.588 30949-30949/

This java.lang.NoSuchMethodException: only occurs when the connection is being established for the first time with the server, although api is still getting success response and everything works fine in debug build and when I hit the api again it does not shows the same exception message in the android studio logcat.
I am facing problem with the app in production, I get the same exception message in production as well and api is being called and i can see the response as well but in production screen in not moving to next screen as it should. Is this issue because of java.lang.NoSuchMethodException this exception or there is some other problem with my app in production. If anybody have any possible solution or suggestion please share. It will be of great help for me, Thanks.

A: I hit a similar error on API 30 and com.squareup.okhttp3:okhttp:4.2.2.
The problem was that OkHttp uses refection to access some parts of the core Android SDK. So OkHttp is strongly coupled to API version.
In my case upgrading to com.squareup.okhttp3:okhttp:4.9.3 fixed the issue but the required version will depend on your target SDK.
More info here:
https://github.com/amplitude/Amplitude-Android/issues/309


text: Q: How to uniquely identify SIM I want to uniquely identify Sim, but if I am using TelephonyManager getLine1Number() it always return null, if I am using TelephonyManager getDeviceId() it is returned even without sim. So the question is that how can I uniquely identify SIM?


text:
Q: Minimum of function of x and y any ideas how to find minimum of the following function:
$f(x,y)=a-b\frac{x}{y}-c\frac{y}{x}+\frac{d}{x}+\frac{e}{y}-\frac{g}{xy}$.
Assume that $a,b,c,d,e,g>0$. We can also assume that $x,y \ge 1$.
Any advise will be appreciated.

A: In the region $x,y \ge 1$ we have them each nonzero, so that the partials $f_x,f_y$ may be multiplied by products using $x,y.$ We have
$$x^2yf_x=-bx^2+cy^2-dy+g,\\ xy^2f_y=bx^2-cy^2-ex+g.$$
Both of these must be zero at any critical point, so that on adding them we see any critical point lies on the line $L:ex+dy=2g.$ Trying to solve this for say $y$ and put it back into either one of the partials and get the possible $x$ values is an awful mess.
However since in your problem we have the boundaries $y=1,x \ge 1$ and $x=1,y\ge 1$ there is hope of solving the minimum, at least in a specific case. See if the line $L$ contains any points in the interior. If it does, parametrize $L$ there and get a one variable function after plugging into $f(x,y)$ and find the min on that part (one variable calc). In any case one must also parametrize the two horizontal and vertical parts of the boundary, and again by one variable calculus find the minimums of those. Of course the overall minimum is the smallest of these three (or two) subresults.
Important Edit: I went too quickly and tried to apply the usual critical point and check the boundary method to this problem. The issue is that it doesn't apply here, since the domain in question is not a compact subset of $\mathbb{R}^2.$ That is, one has to check what happens as $x,y \to \infty$ in this example, if looking for min (or max).
In this example one can see there is actually no minimum by defining $t=x/y$ so that $x=ty$ and the objective function becomes
$$a-bt-\frac{c}{t}+\frac{d}{ty}+\frac{e}{y}-\frac{g}{ty^2}. \tag{*}$$
Now one can certainly in the region $x,y\ge 1$ make both $t,y$ approach $+\infty$ since all that implies is that $x=ty \to \infty$ also. But then all terms of $(*)$ other than the first two approach zero, while $a-bt \to -\infty.$ Thus in fact the function $f(x,y)$ has no minimum in the given region $x,y \ge 1.$ There may well be a maximum, I didn't check that since not asked in the question. Actually $f(x,y)$ is bounded above by $a+d+e$ given positivity of the coefficients and $x,y\ge 1.$ Then the max or sup must exist.


text:
Q: How can I make a class in C# that I can initialize just like a string? I want to be able to initialize a class just like I initialize a string:
string str = "hello";
MyClass class = "hello";

I really don't know what exactly string str = "hello"; does. I assume "hello" gets translated by the compiler into new System.String("hello"); but I'm not sure. Maybe is just not possible or maybe I'm missing something very elemental; if that's the case excuse my ignorance :). What I'm trying to make is a class that works just like a string but stores the string in a file automatically.
Ok, here's my code after reading you answers:
class StringOnFile
{
    private static string Extension = ".htm";
    private string _FullPath;
    public bool Preserve = false;

    public string FullPath
    {
        get
        {
            return _FullPath;
        }
    }

    public static implicit operator StringOnFile(string value)
    {
        StringOnFile This = new StringOnFile();
        int path = 0;

        do{
            path++;
            This._FullPath = Path.GetFullPath(path.ToString() + Extension);
        }
        while(File.Exists(This._FullPath));

        using (StreamWriter sw = File.CreateText(This._FullPath))
        {
            sw.Write(value);
        }

        return This;
    }

    public static implicit operator string(StringOnFile stringOnFile)
    {
        using (StreamReader sr = File.OpenText(stringOnFile._FullPath))
        {
            return sr.ReadToEnd();
        }
    }

    ~StringOnFile()
    {
        if(!Preserve) File.Delete(FullPath);
    }
}

What do you think?

A: Try the following
class MyClass {
    public static implicit operator MyClass(string value) {
        // Custom logic here
        return new MyClass();
    }
}

void Example() {
  MyClass v1 = "data";
}

This will get the end result you are looking for.  However I would advise against this approach.  There are several pitfalls with implicit conversions that you will eventually run into.  Much better to just have a constructor which takes the string

A: Well, you can create an implicit conversion from string to your type... but I would personally rarely do so. One example of a class that does is XNamespace from LINQ to XML. Does your class really just have a string member? If so, maybe it's suitable. Or maybe it only has a string and some other fields which can usually be defaulted... but in most cases, I wouldn't expect a conversion from string to be appropriate.
To put it another way: should your users really think of your class in exactly the same way as a string? Is it effectively a wrapper around a string? If you could give us more details, we could give more advice.
And no, the compiler doesn't translate "hello" into new System.String("hello") - that would just cause a recursive problem, of course, as well as breaking interning. IL has direct support for string constants, which the C# compiler uses.

A: You need to implement implicity conversion from string http://msdn.microsoft.com/en-us/library/z5z9kes2(VS.71).aspx


text:
Q: Performance of arcpy.Exists() in SQL Server enterprise gdb environment While iterating on a list containing table names,
I used arcpy.Exists() to check if a table/featureclass exists.
This action is very time consuming.
I've ended up using a database approach select count(*) from 'tablename'
and checked the query result to check if a table exists, which works very fast.
I even tried using a readonly user/administrative user for arcpy.Exists(), still received the same performance problem.
My questions:
1. Does anyone knows why arcpy.Exists() is so slow vs SQL server (it is much faster in SDE)?
2. Any other ideas for workarounds? my list contains 400  names, I'd rather use arcpy on creating multiple db queries.

A: One of the interesting quirks of many SQL client APIs is the lack of a "table exists" function.  Many implementations of an "exists" are really a low-level "describe", which returns a "does not exist" error if the table doesn't exist, and populates metadata if it does.  The side effect of this is that an "exists" test is often quite slow, because if it succeeds, then it has to clean up something that cost effort to create.
The function in ArcPy which tests for table existence (arcpy.Exists()) has the overhead of verifying the connection string, then describing the table and cleaning up. By comparison, the arcpy.ListFeatureClasses() function has connection overhead, and then requests the list of tables, and then needs to either consult the geodatabase metadata or describe each table in turn to see if it has a geometry column, and potentially needs to describe it anyway, to see if anything has changed, or if unsupported columns are present, so this isn't an intrinsically fast process either.
So then the issue is which is faster, compiling a list of valid tables or describing all the tables up front, then sifting through the result for potential matches (the answer for which could vary by database implementation, number of tables, and number of columns).
There is another mechanism, which is to execute an RDBMS-dependent query against the system catalog via the arcpy.ArcSDESQLExecute() function, and assume that the table is valid if the database reports that it exists.
Now, I don't have a MS SQL Server instance handy (new laptop, no need), but I can perform some timing tests with PostgreSQL. The experiment I propose is as follows:

*

*Create 65 random-named tables in the form 'tableNN' with six columns, one of which is an identity (ID) column, and another geometry.

*Measure the performance of using arcpy.Exists on tables 00 through 99 (tracking the timing for both existing and non-existing tables)

*Measure the performance of using arcpy.ListFeatureClasses to retrieve all tables as the owner, then test against this list to determine existance

*Measure the performance of using arcpy.ArcSDESQLExecute to retrieve a table list, then test existance with this list as well

*Repeat the above with tables of just two columns, and tables with forty columns

And the results for six, two, and forty columns are:
       Tot (all) = 6.1800
      Mean (all) = 0.0618
      Mean (exi) = 0.0920
      Mean (dne) = 0.0057
    List elapsed = 3.4900
      List total = 3.4900 (65 found)
     SQL elapsed = 0.0200
       SQL total = 0.0200 (65 found)
----------
       Tot (all) = 5.6300
      Mean (all) = 0.0563
      Mean (exi) = 0.0832
      Mean (dne) = 0.0063
    List elapsed = 2.6800
      List total = 2.6800 (65 found)
     SQL elapsed = 0.0100
       SQL total = 0.0100 (65 found)
----------
       Tot (all) = 6.5800
      Mean (all) = 0.0658
      Mean (exi) = 0.0986
      Mean (dne) = 0.0049
    List elapsed = 3.3600
      List total = 3.3600 (65 found)
     SQL elapsed = 0.0100
       SQL total = 0.0100 (65 found)

So it seems as if, anecdotally, my above assertions are borne out:

*

*The Exists cascade takes 5.63-6.58 seconds

*Testing for non-existent tables is significantly (order of magnitude)
faster than existing ones

*Wider tables take longer to test than skinnier ones

*Using ListFeatureClasses takes 2.68-3.49 seconds (roughly half of Exists)

*Using the information_schema query in PostgreSQL takes 10-20 milliseconds
Also somewhat interesting: Converting the list to a dictionary and then searching the dictionary 100 times took no measureable time (Windows box, so sub-millisecond)
Now obviously, you'd need to tweak the actual SQL for SQL Server, but I'll provide the Python here for reference*:
import math
import os
import random
from datetime import datetime

print("Importing arcpy...")
import arcpy

# -----------------------------------
def findTables(names,schema,fmt,count):
    found = []
    d = {}
    for name in names:
        parts = name.split('.')
        d[parts[2]] = name
    for i in range(count):
        table = fmt.format(i)
        if (table in d):
            found.append(table)
    return found
# -----------------------------------

verbose=False
keep=65
fudge=keep-12
total=100
schema=""
geomcol="geom"
tableFmt="xxtmp_table{:02d}"
random.seed(42)

dropStatement   = "DROP TABLE IF EXISTS {:s}{:s}"

createStatement6 = """CREATE TABLE {:s}{:s} (
  objectid        serial          NOT NULL,
  col1            smallint            NULL,
  col2            integer             NULL,
  col3            real                NULL,
  col4            varchar(20)         NULL,
  {:<12s}    geometry            NULL,
  CONSTRAINT {:s}_pkey PRIMARY KEY (objectid),
  CONSTRAINT enforce_srid_{:s} CHECK (st_srid({:s}) = 4326)
)
WITH (
  OIDS=FALSE
)"""

createStatement2 = """CREATE TABLE {:s}{:s} (
  objectid        serial          NOT NULL,
  {:<12s}    geometry            NULL,
  CONSTRAINT {:s}_pkey PRIMARY KEY (objectid),
  CONSTRAINT enforce_srid_{:s} CHECK (st_srid({:s}) = 4326)
)
WITH (
  OIDS=FALSE
)"""

createStatement40 = """CREATE TABLE {:s}{:s} (
  objectid        serial          NOT NULL,
  col1            smallint            NULL,
  col2            integer             NULL,
  col3            real                NULL,
  col4            varchar(20)         NULL,
  col5            varchar(20)         NULL,
  col6            smallint            NULL,
  col7            integer             NULL,
  col8            real                NULL,
  col9            varchar(20)         NULL,
  col10           varchar(20)         NULL,
  col11           smallint            NULL,
  col12           integer             NULL,
  col13           real                NULL,
  col14           varchar(20)         NULL,
  col15           varchar(20)         NULL,
  col16           smallint            NULL,
  col17           integer             NULL,
  col18           real                NULL,
  col19           varchar(20)         NULL,
  col20           varchar(20)         NULL,
  col21           smallint            NULL,
  col22           integer             NULL,
  col23           real                NULL,
  col24           varchar(20)         NULL,
  col25           varchar(20)         NULL,
  col26           smallint            NULL,
  col27           integer             NULL,
  col28           real                NULL,
  col29           varchar(20)         NULL,
  col30           varchar(20)         NULL,
  col31           smallint            NULL,
  col32           integer             NULL,
  col33           real                NULL,
  col34           varchar(20)         NULL,
  col35           varchar(20)         NULL,
  col36           smallint            NULL,
  col37           integer             NULL,
  col38           real                NULL,
  {:<12s}    geometry            NULL,
  CONSTRAINT {:s}_pkey PRIMARY KEY (objectid),
  CONSTRAINT enforce_srid_{:s} CHECK (st_srid({:s}) = 4326)
)
WITH (
  OIDS=FALSE
)"""

listStatement="""SELECT (table_catalog ||'.' || table_schema || '.' || table_name)::varchar(100) as name
FROM    information_schema.tables
WHERE   table_type = 'BASE TABLE'
  AND   table_schema NOT IN ('pg_catalog', 'information_schema')"""

conn = os.path.join(os.getcwd(),"bench.sde")
cursor = arcpy.ArcSDESQLExecute(conn)

for createStatement in [createStatement6, createStatement2, createStatement40]:
    count = 0
    print '----------'
    # .. (re)Create tables
    start = datetime.datetime.now()
    created=[]
    for i in range(total):
        if (math.floor(random.random() * 100) < fudge or (total - i) < (total - keep)):
            table = tableFmt.format(i)

            sql = dropStatement.format(schema,table)
            if (verbose): print("{:s};".format(sql))
            cursor.execute(sql)

            sql = createStatement.format(schema,table,geomcol,table,geomcol,geomcol)
            if (verbose): print("{:s};\n".format(sql))
            cursor.execute(sql)

            created.append(table)
            count += 1
            if (count >= keep): break

    elapsed = (datetime.datetime.now() - start).total_seconds()
    #print("{:>16s} = {:.4f} secs".format("Prep",elapsed))

    # .. Measure Exists

    allSum = 0.0
    exiSum = 0.0
    dneSum = 0.0
    for i in range(total):
        table = tableFmt.format(i)
        start = datetime.datetime.now()
        doesExist = arcpy.Exists(os.path.join(conn,"{:s}{:s}".format(schema,table)))
        elapsed = (datetime.datetime.now() - start).total_seconds()
        allSum += elapsed
        if (doesExist):
            exiSum += elapsed
        else:
            dneSum += elapsed
        if (verbose): print("{:s} ({:s})".format(table,"Y" if doesExist else "N"))

    print("{:>16s} = {:.4f}".format("Tot (all)",allSum))
    print("{:>16s} = {:.4f}".format("Mean (all)",allSum / float(total)))
    print("{:>16s} = {:.4f}".format("Mean (exi)",exiSum / float(keep)))
    print("{:>16s} = {:.4f}".format("Mean (dne)",dneSum / float(total-keep)))

    # .. Measure ListFC

    arcpy.env.workspace = conn
    start = datetime.datetime.now()
    allTables = arcpy.ListFeatureClasses()
    elapsed = (datetime.datetime.now() - start).total_seconds()

    print("{:>16s} = {:.4f}".format("List elapsed",elapsed))
    start = datetime.datetime.now()
    found = findTables(allTables,schema,tableFmt,total)
    elapsed += (datetime.datetime.now() - start).total_seconds()
    print("{:>16s} = {:.4f} ({:d} found)".format("List total",elapsed,len(found)))

    # .. Measure SQL

    start = datetime.datetime.now()
    sql = listStatement
    allTables = [row[0] for row in cursor.execute(sql)]
    elapsed = (datetime.datetime.now() - start).total_seconds()

    print("{:>16s} = {:.4f}".format("SQL elapsed",elapsed))
    start = datetime.datetime.now()
    found = findTables(allTables,schema,tableFmt,total)
    elapsed += (datetime.datetime.now() - start).total_seconds()
    print("{:>16s} = {:.4f} ({:d} found)".format("SQL total",elapsed,len(found)))

    # .. Cleanup

    start = datetime.datetime.now()
    for table in created:
        sql = dropStatement.format(schema,table)
        if (verbose): print("{:s};".format(sql))
        cursor.execute(sql)
    elapsed = (datetime.datetime.now() - start).total_seconds()
    #print("{:>16s} = {:.4f} secs".format("Cleanup",elapsed))

cursor = None

#EOF

*Note: hack job; took way longer than I wanted to make, so it's as-is.

Follow-up:  I used this technique in an application against a PostgreSQL database and ran into an issue with failure to detect views and materialized views.  Adding view support was as simple as changing the SQL that compiles the list to UNION ALL a query to information_schema.views:
  SELECT (table_schema || '.' || table_name)::varchar(255) as name
  FROM  information_schema.tables
  WHERE table_type = 'BASE TABLE'
    AND table_schema NOT IN ('pg_catalog', 'information_schema')
UNION ALL
  SELECT (table_schema || '.' || table_name)::varchar(255) as name
  FROM  information_schema.views
  WHERE table_schema NOT IN ('pg_catalog', 'information_schema')

But for PostgreSQL, at least, materialized views are not published through information_schema (because MATERIALIZED VIEW is an extension), so for them I needed to append a PG-specific catalog query:
UNION ALL
  SELECT (schemaname || '.' || matviewname)::varchar(255) as name
  FROM  pg_matviews


text:
Q: Transition between posts not refund to the list of all posts i use React-admin. And I should add on the page "Edit", for example, products, two buttons.
That on clicking the corresponding button it was possible to pass to the next or previous products not refund to the list of all products. Is it possible in react-admin?
Example

A: You can create your own actions component


text:
Q: Can someone explain this formula for determining collinear points Trying to understand some code I am looking at. If you have three latlong points, p1 p2 and p3.
You want to determine if they are on a line.
You work out:
X.Lat = p1.Lat - p2.Lat
X.Long = p1.Long - p2.Long
Y.Lat = p3.Lat - p2.Lat
Y.Long = p3.Long - p2.Long
Then you do some crazyness
Cosang = ( X.Lat * Y.Lat + x.Long * y.Long ) / ( Sqrt( x.Lat^2 + x.Long^2 ) * Sqrt ( Y.Lat^2 + y.Long^2 ) )
If Abs(Cosang) > 0.997 they are collinear?
How does that work?

A: I transcript your formulas into readable form (longitude et latitude are resp. $x$ and $y$ coordinates).
The first groupe makes $(X_2,Y_2)$ a new origin :
$X=X_1-X_2 \ $ and $ \ Y=Y_1-Y_2$,
$X'=X_3-X_2 \ $ and $ \ Y'=Y_3-Y_2.$
Then the big formula reads
$$XX'+YY'=\cos \alpha \sqrt{X^2+Y^2} \sqrt{X'^2+Y'^2}$$
which links the two ways of expressing a dot product.
The test, more or less, means $\cos(\alpha)=+1$ or $-1$:
In the case $+1$, the points are aligned in the order $A_2,A_1,A_3$ or $A_2,A_3,A_1.$
In the case $-1$, the points are aligned in the order $A_1,A_2,A_3$.
Taking $abs(cos(\alpha))>0.997$ groups the two cases, including cases where the alignment is only approximate.


text:
Q: How to stop chrome from reading text selected? Chrome reads aloud the text selected by accident, the sudden voice frightening me. Can we turn off this feature? Badly needed on Both mobile and desktop platform.

A: https://www.google.com/preferences
Please change "Spoken Answers"


text:
Q: JPQL inner join I am trying to convert mysql code into JPQL. I have two tables. The first table is named Product. It has the following fields: id and code. The second table is called Descriptor which has 3 fields: id ( from product table), code ( from product table) and Description which is a field specific to the Descriptor table. I want to join the tables so for each unique combination of product id and product code I want the description added on.
    The Sql is as follows ( this is correct):
    Select Product.id, Product.code, Descriptor.DESCRIPTION
    from Product Inner join Descriptor where
    Product.id = Descriptor.id and
    Product.code = Descriptor.code

(The error is in here)
The JPQL I am trying is as follows which results in a "path" error
select p from Product p INNER JOIN Descriptor d where
p.id = d.id and p.code = d.code;

All advice very welcome thanks

A: Read the documentation about HQL. Joins, in HQL, are done using associations between entities:
select p from Product p
inner join p.descriptor d
where p.code = d.code;

(assuming there is a OneToOne association between Product and Descriptor, using their respective IDs).


text:
Q: How do I prevent multiple results when condition is null for a LINQ query? Assuming the following two SQL tables.
db.Fruits
ID  Name
F1  Apple
F2  Orange
F3  Melon

db.Attributes
ID  Fruits_ID   AttributeType   AttributeValue
A1  F1          Color           Red
A2  F3          Size            Large
A3  F2          Size            Small
A4  F1          Size            Small
A6  F3          Color           Brown

How do I use a LINQ query to search for the fruit I want with multiple nullable conditions WITHOUT multiplying the results due to a JOIN? For example, the following query produces multiple results if condition is null.
var q = from f in db.Fruits
        join a in db.Attributes
        on f.ID equals a.Fruits_ID
        where string.IsNullOrEmpty(condition) || fa.AttributeValue.Contains(conditon)
        select FruitResult
        {
            // ...
        }

In any case, I have also looked into INTO but that's not working for me.
var q = from f in db.Fruits
        join a in db.Attributes
        on f.ID equals a.Fruits_ID
        into FruitsAttributes

        from fa in FruitsAttributes
        where string.IsNullOrEmpty(condition) || fa.AttributeValue.Contains(conditon)
        select FruitResult
        {
            // ...
        }

The above still returns multiple/joined results when condition is null or empty.
TL;DR: How do I use a one-to-many .Contains check in my query such that, if the conditions are null, returns individual "unjoined" rows?

A: You can try this query:
var q = from f in db.Fruits
                join a in db.Attributes
                on f.Id equals a.FruitId
                into g
                select new FruitResult
                {
                    Id = f.Id,
                    Name = f.Name,
                    Attribute = condition != null ? g.FirstOrDefault(a => a.AttributeValue.Contains(condition)) : null
                };

You can easily extend retrievieng Attribute value in the select, I don't know what you need, so I left it as it is.

A: I'm guessing you're expecting an empty set if condition is null since it won't match any attributes? The easiest way would be to just handle that case separately.
IEnumerable<FruitResult> q;
if (!string.IsNullOrEmpty(condition))
{
    q = from f in db.Fruits
        join a in db.Attributes
        on f.ID equals a.Fruits_ID
        where fa.AttributeValue.Contains(conditon)
        select FruitResult
        {
            // ...
        }
}
else
{
    q = Enumberable.Empty<FruitResult>();
}

A: Finally arrived at an answer. It's actually very simple, just had to create a filter and skip the join.
var qFilter = from a in db.Attributes
              where a.AttributeValue.Contains(condition)
              select a.Fruits_ID

var q = from f in db.Fruits
        where string.IsNullOrEmpty(condition) || qFilter.Contains(f.ID)
        select FruitResult
        {
            // ...
        }


text:
Q: How to detect a click on a list element? I have this html code:

bateau

braguette

bateau

Then I have a javascript file:
document.addEventListener( 'click', mouseEventsListener);

function mouseEventsListener ( event ) {

    switch( event.target ) {

        case ***HOW_TO_DETECT_CLICK_ON_THE_LI_ELEMENTS***:

            myFunction( parameter );

        break;

    default:

        break;

    }

}

How can I execute myFunction from within the switch/case statement when the user clicks on a "li" element?

A: Check this code and as mention in above comment you can add more check as per your need

document.addEventListener( 'click', mouseEventsListener);

function mouseEventsListener ( event ) {

    switch( event.target.tagName ) {

        case 'LI':
            alert('Clicked LI')
            //myFunction( parameter );

        break;

    default:

        break;

    }

}

bateau

braguette

bateau

A: To track click on every element, you need to add event listener in a loop

    let list = document.querySelectorAll( '#wordListDiv ul li' );
    for ( var i = 0; i < list.length; i++ ) {
        list[i].addEventListener( 'click', (e) => {
            console.log( e.target.id );
        })
    }

bateau

braguette

bateau

A: If you absolutely need the case syntax, use this:

[...document.getElementsByTagName("li")].forEach(function(el) {
  console.log(el)
  el.addEventListener('click', mouseEventsListener);
})

function mouseEventsListener(evt) {
  var index = whichChild(event.target)
  switch (index) {
    case 0:
      myFunction("1");
      break;
    case 1:
      myFunction("2");
      break;
    case 2:
      myFunction("3");
      break;
    default:
      break;
  }
}

function myFunction(parameter) {
  console.log(parameter)
}

function whichChild(elem) {
  var i = 0;
  while (elem.previousElementSibling != undefined) {
    ++i;
    elem = elem.previousElementSibling;
  };
  return i;
}

bateau

braguette

bateau

Otherwise, I would recommend looking at the other solutions.


text:
Q: Открытие страницы в новой вкладке Пытаюсь написать дополнение для Firefox, которое будет открывать группу вкладок.
При использовании window.open('url'), открывается новое окно. Как это обойти?
Между тем, если я вызываю window.open('url') в обычном скрипте, то страница открывается в новой вкладке. Это довольно странно. Может быть, есть способ явно указать браузеру на то, что открываться страница должна именно в новой вкладке?

A: Если вы используете Add-on SDK для написания дополнения, то как верно замечено в комментах, это делается с помощью модуля tabs:
var tabs = require("sdk/tabs");
tabs.open("http://www.example.com");

В обычном расширении (без SDK), обычно используется:
gBrowser.addTab(url)

Больше подробностей на странице по ссылке и тут: https://developer.mozilla.org/en/docs/Working_with_windows_in_chrome_code


text:
Q: jquery datepicker, show the preceeding months I would like the datepicker on my page to show both the current month and the preceding three months on click.
I have tried setting numberOfMonths:-3  with no success. I have also set  showOtherMonths: true. I realize that number of months must be set at 2 or greater. Is there a workaround?

A: Here's the code:
$(function() {
$("input.datepicker").datepicker({
  dateFormat: 'MM d, yy',

  defaultDate: "-2MM",
  numberOfMonths: 3,
showOtherMonths: true
});


text:
Q: iOS app cache...bug or feature? This happens after I update my iPad to iOS 12. When I remove an app from my device, it seems that the app isn't removed immediately.
More precisely, when I redownload the app from App Store, usually the progress indicator will be slow enough for me to see the download progress. I do have a fast Wi-Fi access, so I can download things in e.g. 40Mbps (so 5MBps), and I expect to finish downloading a 50MB-app in around 12-15 seconds (some extra time for installation). However, when I redownload an app shortly after I removed it from the home screen (it was removed, at least not appearing at Settings -> General -> iPad Storage), the app reappears almost immediately. There is no "Loading..." or "Waiting" label showing in the home screen. Instead, a greyed-out icon appears after I redownload the app from App Store, and then it changes to a normal bright one shortly.
Just for curiosity: is this a bug or a feature?


text:
Q: I have two pictureBoxes in other sizes how can i make that when i click on one pictureBox it will draw a point on the smaller pictureBox? This is my code but its not working not drawing points at all on pictureBox2.
public partial class Form1 : Form
    {
        private int counter;
        private int pb1mouse_x;
        private int pb1mouse_y;
        private int pbsize_x;
        private int pbsize_y;

        public Form1()
        {
            InitializeComponent();

            pbsize_x = pictureBox2.Width / pictureBox1.Width;
            pbsize_y = pictureBox2.Height / pictureBox1.Height;
            label4.Visible = false;
            label5.Visible = false;
            label6.Visible = false;
            counter = 0;
            pictureBox1.Load(@"d:\radar000075.png");

        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            label4.Visible = true;
            label4.Text = String.Format("X: {0}; Y: {1}", e.X, e.Y);
        }

        private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                label5.Visible = true;
                label5.Text = String.Format("X: {0}; Y: {1}", e.X, e.Y);
                counter += 1;
                label6.Visible = true;
                label6.Text = counter.ToString();
                pb1mouse_x = e.X;
                pb1mouse_y = e.Y;
                pb1mouse_x = pb1mouse_x * pbsize_x;
                pb1mouse_y = pb1mouse_y * pbsize_y;
                pictureBox2.Invalidate();
            }
        }

        private void pictureBox2_Paint(object sender, PaintEventArgs e)
        {
            Pen p = new Pen(Color.Red);
            var g = e.Graphics;
            g.Clear(pictureBox1.BackColor);
            g.DrawEllipse(p, new Rectangle(pb1mouse_x, pb1mouse_y, 10, 10));
        }
    }

A: You should be able to simply multiply by factors, i.e. smallBox.Width/largeBox.Width and smallBox.Height/largeBox.Height.  Multiply the coordinates for the larger box by those factors and it will give you coordinates for the smaller box.
Edit:
This is what my code looks like:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace PBoxes
{
    public partial class Form1 : Form
    {
        private float xFactor, yFactor;
        List<PointF> points = new List<PointF>();

        public Form1()
        {
            InitializeComponent();
            xFactor = (float)pictureBox2.Width / pictureBox1.Width;
            yFactor = (float)pictureBox2.Height / pictureBox1.Height;
        }

        private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
        {
            points.Add(new PointF(e.X * xFactor, e.Y * yFactor));
            pictureBox2.Invalidate();
        }

        private void pictureBox2_Paint(object sender, PaintEventArgs e)
        {
            foreach (PointF pt in points)
            {
                e.Graphics.FillEllipse(Brushes.Red, pt.X, pt.Y, 3f, 3f);
            }
        }

        private void pictureBox_SizeChanged(object sender, EventArgs e)
        {
            xFactor = (float)pictureBox2.Width / pictureBox1.Width;
            yFactor = (float)pictureBox2.Height / pictureBox1.Height;
        }
    }
}


text:
Q: How to sort lists of objects using java I have 2 lists which are holding the same objects but unordered and I want to sort them first before comparing them in order to check whether they are equals.
One item of each list looks like that:
first list:
AuditRow{dateStr='2019-04-15 11:16', userStr='admin', entityStr='Users'}

second list:
AuditRow{dateStr='2019-04-15 10:28', userStr='admin', entityStr='Users'}

I tried to use Comparator for this issue but with no success
I must say that both of the list got more than 10 items.
I want to achieve the goal of sorting up my lists by their date time (mostly relying on hour since the date is the same for all the items).
This is what I tried:
    Override
    public int compareTo(AuditRow auditRow) {
        int compareage = Integer.parseInt(((AuditRow)auditRow).dateStr.replace(" ",""));
        return Integer.parseInt(this.dateStr.replace(" ",""))-compareage;
    }

But this did not do the trick

A: if you want to sort them by the dateStr:
list.sort((obj1,obj2) ->{SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm");
return sdf.parse(obj1.getDate()).compareTo(sdf.parse(obj2.getDate());}

I assumed the dateStr is a string, so I included the conversion here, if they already are dates, then simply do (obj1,obj2) -> obj1.getDate().compareTo(obj2.getDate())
EDIT: as @RobertKock pointed out, you don't even need to convert the string to a date, you can straight up compare it without any conversion.

A: I don't know what you tried with comparator.
Have you tried using like this:
First you create a comparator, by the field you want to use in your case date time.
Comparator<AuditRow> compareByDate = (AuditRow a1, AuditRow a2) -> a1.getDateStr().compareTo(a2.getDateStr());

Then you use the above created comparator as param in sort:
Collections.sort(auditRowList, compareByDate);

A: Using comparator:
List(AuditRow) myList;
Collections.sort(myList, new Comparator<AuditRow>{
    public int compare(AuditRow ar1, AuditRow ar2) {
        return ar1.getDateStr().compareTo(ar2.getDateStr());
    }
});

Same as above, but using lambda expressions (Java 8+):
List(AuditRow) myList;
Collections.sort(myList, (ar1, ar2) ->
        ar1.getDateStr().compareTo(ar2.getDateStr()});

If your comparator is created from comparing properties then you can use:
List(AuditRow) myList;
myList.sort(myList,
        Comparator.comparing(AuditRow::getDateStr)
            .thenComparing(AuditRow::userStr));


text:
Q: Strange and very low results in Ljung-Box test I have been reading some posts about the Ljung-Box test and I am applying it to some of my databases. However, I am not really understanding the outputs, I think I am doing something wrong. I have a time series data every 5 minutes and I want to check if it is White Noise. The data has 800 rows and it is the following (mostly all 1):
[1  1  1  1  1  1  1  1  1  1  1  1  1  5  4  4  1  1  1  1  1  1  1  2
  1 10  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1
  2  2  4  1  3  1  1  1  1  1  2  1  1  1  1  1  1  1  2  3  2  1  1  2
  1  1  1  2  2  2  1  1  1  1  1  1  1  1  1  2  1  3  1  1  1  1  1  1
  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  7 11  7  1  1  1  1  1...1]

I am also plotting the ACF of statsmodels with 40 lags. The outputs of the function acf are:
[ 1.          0.40168385  0.17665485 -0.00746597  0.00272706 -0.02031781
  0.00265903  0.01285206  0.01281804  0.00511375  0.066442    0.0459539
  0.07660102 -0.02058992 -0.01688757 -0.00580984  0.00271113 -0.0024364
 -0.00247042 -0.00506119 -0.02043578 -0.00768598  0.01784761  0.05872178
  0.04875562  0.08707303  0.01299028  0.06153473 -0.0100886  -0.01523614
 -0.02038367 -0.0127474  -0.01278142  0.00763866  0.0101614   0.06381938
  0.06634212  0.08420544  0.01258211  0.01510486  0.00740056]

thus I can see that they are very close to 0 starting from lag 3, what gives me the idea of it being white noise. However, when I run the Ljung-Box test of statsmodels, it returns me the following data:
       lb_stat     lb_pvalue     bp_stat     bp_pvalue
1   144.570070  2.666584e-33  144.085478  3.403318e-33
2   172.562972  3.376189e-38  171.953272  4.579536e-38
3   172.613028  3.471591e-37  172.003048  4.701366e-37
4   172.619714  2.865290e-36  172.009689  3.873593e-36
5   172.991262  1.677989e-35  172.378331  2.267774e-35
6   172.997633  1.040093e-34  172.384645  1.403245e-34
7   173.146633  5.446860e-34  172.532147  7.341165e-34
8   173.295013  2.628478e-33  172.678869  3.539256e-33
9   173.318656  1.255253e-32  172.702221  1.687471e-32
10  177.314414  8.455177e-33  176.644405  1.164428e-32
           ...           ...         ...           ...
31  202.825613  3.860873e-27  201.502716  6.810909e-27
32  202.977258  9.384704e-27  201.648600  1.654383e-26
33  203.031484  2.341230e-26  201.700706  4.117698e-26
34  203.127555  5.651189e-26  201.792912  9.923617e-26
35  206.921511  2.839503e-26  205.430023  5.319358e-26
36  211.026126  1.249621e-26  209.360364  2.515537e-26
37  217.646477  1.909240e-27  215.692230  4.339157e-27
38  217.794461  4.405961e-27  215.833601  9.997658e-27
39  218.007986  9.768113e-27  216.037345  2.215969e-26
40  218.059303  2.287945e-26  216.086253  5.172516e-26

Since the pvalues are so low, I reject the null hypothesis, what gives the result of it not being white noise while the ACF plot was indicating the opposite. Am I interpreting it correctly?
Thank you very much!!

A:
I can see that they are very close to 0 starting from lag 3, what gives me the idea of it being white noise

White noise should have close to zero autocorrelations for all (nonzero) lags, not only from the third lag on. Perhaps your time series is better approximated by an MA(2) process of the form
$$
x_t=\mu_t+\varepsilon_t+\theta_1\varepsilon_{t-1}+\theta_2\varepsilon_{t-2}
$$
with $\varepsilon_t$ being white noise. For such a process, you would see nonzero autocorrelation at lags 1 and 2 and zero autocorrelation beyond that. MA(2) is of course not white noise, and the Ljung-Box test is likely picking that up.


text:
Q: object_getInstanceVariable works for float, int, bool, but not for double? I've got object_getInstanceVariable to work as here however it seems to only work for floats, bools and ints not doubles. I do suspect I'm doing something wrong but I've been going in circles with this.
float myFloatValue;
float someFloat = 2.123f;
object_getInstanceVariable(self, "someFloat", (void*)&myFloatValue);

works, and myFloatValue = 2.123
but when I try
double myDoubleValue;
double someDouble = 2.123f;
object_getInstanceVariable(self, "someDouble", (void*)&myDoubleValue);

I get myDoubleValue = 0. If I try to set myDoubleValue before the function eg. double myDoubleValue = 1.2f, the value is unchanged when I read it after the object_getInstanceVariable call. Setting myIntValue to some other value before the getinstancevar function above returns 2 as it should, ie. it has been changed.
then I tried
Ivar tmpIvar = object_getInstanceVariable(self, "someDouble", (void*)&myDoubleValue);

If I do ivar_getName(tmpIvar) I get "someDouble", but myDoubuleValue = 0 still!  Then I try ivar_getTypeEncoding(tmpIvar) and I get "d" as it should be.
So to summarize, if typeEncoding = float, it works, if it is a double, the result is not set but it correctly reads the variable and the return value (Ivar) is also correct.
I must be doing something basic wrong that I cant see so I'd appreciate if someone could point it out.

A: object_getInstanceVariable is a confused little function. It is documented that the last parameter is a void ** parameter—that is, you pass the address of a void * variable and get a pointer to the instance variable—but it is implemented as if it was a void * parameter—that is, you pass the address of the variable that you want to hold a copy of the instance variable. The problem is that the implementation ignores the size of the instance variable and just does a pointer copy. So anything that's the same size as a pointer will work perfectly. If you're running on a 32-bit architecture, only the high 32 bits will be copied. (You should witness the same behavior with a long long instance variable as well.)
The solution is to use the primary API, key-value coding, using -valueForKey:.
The other solution: If you wanted to write a fixed version, say as a category for NSObject, it would look something like this:
@implementation NSObject (InstanceVariableForKey)

- (void *)instanceVariableForKey:(NSString *)aKey {
    if (aKey) {
        Ivar ivar = object_getInstanceVariable(self, [aKey UTF8String], NULL);
        if (ivar) {
            return (void *)((char *)self + ivar_getOffset(ivar));
        }
    }
    return NULL;
}

@end

Then your code would look like this:
double myDoubleValue = *(double *)[self instanceVariableForKey:@"someDouble"];

A: What about using valueForKey:?
NSNumber * value = [self valueForKey:[NSString stringWithUTF8String:ivar_getName(tmpIvar)]];
NSLog(@"Double value: %f", [value doubleValue];

Note: this requires you to have a "someFloat" method.  If you want to use setValue:forKey:, you'll also need the "setSomeFloat:" method.  This is easily implemented by declaring the ivar as an @property and synthesizing it.


text:
Q: How do I check if a name is among a list of names in python? I am writing Oregon trail game and this is the code I have that is causing issues, I don't know why it is having issues. What I want to do is if they enter a name that contains a word that is in a list it will set the variable easter_mode to 1 if they don't then it will set easter_mode to 0. The words that need to be in the list are: (Sturtz, sturtz, Nate, nate)
Thank you
#asking name
player_name = input('What is your name:')
while len(player_name) >= 0:
  if len(player_name) > 1:
    print("Weclome" + str(player_name))
    print('Which mode do you want to play?')
    mode_choice = input('(easy) More modes comming soon:')
    break
  if len(player_name) == 1:
    player_name_choice = input(str(player_name)+"? Are you kidding me? Only one letter? You might regreat it (Y/N):")
    if player_name_choice == "y" or player_name_choice == "Y":
      print("Ok Your Choice!!...")
      mode_choice = 'easter'
      break
    if player_name_choice == "n" or player_name_choice == "N":
      player_name = input('What is your name:')
  else:
    print("You do not type anything, try again")
    player_name = input('What is your name:')

#Check Easter Egg Names
easter_names = ["nate sturtz", "Nate Sturtz", "Nate", "nate", "Sturtz", "sturtz"]
if player_name in easter_names:
    easter_mode = 1
else:
    easter_mode = 0
#easter eggs for name

if easter_mode == 1:
  year_set = 2005
  mode_choice = 'easter'
else:
  year_set = input('Enter a year whatever you like:')
  if year_set.isdigit():
    return_num = 0
  else:
    return_num = 1
  while return_num == 1:
    print('Error,please try again!')
    year_set = input('Enter a year whatever you like:')
    if year_set.isdigit():
      return_num = 0
    else:
      return_num = 1
  year_set = int(year_set)

When I run the full file I get
Traceback (most recent call last):
  File "Oregon.py", line 64, in <module>
    player_name = input('What is your name:')
  File "<string>", line 1, in <module>
NameError: name 'nate' is not defined

You can view the full code on Github
https://raw.githubusercontent.com/nsturtz/Oregon-Trail/master/Oregon.py

A: You'll get this error in Python 2. In Python 2, input() uses the exact value as your enter it.
In your example, you're typing nate and not 'nate'. The former value is a variable name (which is undefined in your code, hence the NameError), whereas the latter is a string.
In Python 3, input() behaves as you assume, and passes a string to your code.
If you are sure that you want to use Python 2, you can replace input() with raw_input() and it will interpret your input as a string rather than a variable name.

A: Under Python 2, you can use raw_input instead of input to prevent Python from interpreting the user input as Python code.
However, since Python 2 is deprecated, I strongly recommend against using it1. Use Python 3 instead, where input works as expected.

1 Except of course to maintain legacy products. But that doesn't seem relevant here.


text:
Q: Lightning Components | dynamic field Error I'm trying to build a dynamic Lightning Component using Design Resources.
The user should choose 1 object and 3 fields and the component will show the records of that object and the 3 fields.
Problem is:
I'm writing my fields with variables but the component give me this error:

Unfortunately, there was a problem. Please try again. If the problem continues, get in touch with your administrator with the error ID shown here and any other related details. This page has an error. You might just need to refresh it. rerender threw an error in 'markup://aura:iteration' [Assertion Failed!: Unable to get value for key 'art.text__c'. No value provider was found for 'art'. : false] Failing descriptor: {markup://aura:iteration}

The only way to make this component work normally it's to put the fields manually, let's say the user will choose the object "Contact" and the fields Name, Birthdate and email, if i put the fields like this:
{!art.Name}
{!art.Birthdate}
{!art.Email}
It works! But if i put the exact same thing but by variable...here comes the error!
My question is: Why the component is accepting

{!art.Birthdate}

but it's not acepting the variable that brings the exact same thing ?
PS: The "{!v.componentname}" it's for user to choose the name of the component, and that it's working fine by variable.
My component:
<aura:component controller="ArticlesClass" implements="flexipage:availableForAllPageTypes" access="global">
<aura:attribute name="Articles" type="string"/>
<aura:attribute name="componentname" type="String"/>
<aura:attribute name="object" type="String"/>
<aura:attribute name="titlename" type="String"/>
<aura:attribute name="textname" type="String"/>
<aura:attribute name="imgname" type="String"/>
<aura:attribute name="title" type="String"/>
<aura:attribute name="text" type="String"/>
<aura:attribute name="img" type="String"/>
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />

<aura:handler event="aura:waiting" action="{!c.showSpinner}"/>
<aura:handler event="aura:doneWaiting" action="{!c.hideSpinner}"/>

{!v.componentname}

<input id="search" class="search" type="search" onkeyup="{!c.searchKey}" />

                <ui:spinner aura:id="spinner"/>
                <aura:iteration items="{!v.Articles}" var="art">

                       {!v.img}

{!v.title}

{!v.text}

                </aura:iteration>

    </aura:component>

My Controller:
     doInit : function(component, event, helper) {
     console.log("doInit");
    helper.Init(component, event);
    },

My Design Resource:
<design:component label="Article List">
<design:attribute name="componentname" label="Choose the name of the component" description="It will appear in the blue header"/>
<design:attribute name="object" label="Enter the name of the object"/>
<design:attribute name="titlename" label="Enter the name of the title field"/>
<design:attribute name="textname" label="Enter the name of the text field" description="Should be a summary of the article"/>
<design:attribute name="imgname" label="Enter the name of the image field" />
</design:component>

My Apex Class
public with sharing class ArticlesClass {
@AuraEnabled
public static list<Sobject> getArticles(string obj, string titlefield, string textfield, string imgfield) {
    try{
        string query = 'SELECT '+titlefield+', '+textfield+', '+imgfield+' FROM '+obj+'';
        list<Sobject> ArticlesReturn = database.query(query);
        return ArticlesReturn;
    }catch(Exception e){
        return null;
    }
}
}

My helper:
    Init: function(component) {
    var action = component.get("c.getArticles");
    var action2 = component.get("c.findArticles");
    action.setParams({
    obj: component.get("v.object"),
    titlefield: component.get("v.titlename"),
    textfield: component.get("v.textname"),
    imgfield: component.get("v.imgname")
    });
    action.setCallback(this, function(a) {
    component.set("v.Articles", a.getReturnValue());
    });
    $A.enqueueAction(action);
    var b = component.get("v.titlename");
    var c = component.get("v.textname");
    var d = component.get("v.imgname");
    component.set("v.title", "{!art." + b + "}");
    component.set('v.text', "{!art." + c + "}");
    component.set('v.img', "{!art." + d + "}");
}