text:
Q: Is there a way to intercept Undertow RequestTooBigException in spring-ws I have spring boot application that provides some rest api and soap interface using spring-ws.
I'm restricting all post requests to less than 50MB using
server.undertow.max-http-post-size=50MB.
The restriction works but not the error handling.
Tried using a SoapFaultMappingExceptionResolver and mapping RequestTooBigException as an exception inside that. That didn't work because I think this is blocked by undertow and that's before the soapExceptionResolver is triggered.
Tried using a @ExceptionHandler but same result.
Since it's a soap request the accepted type is not json and the default spring exception handler tries to return json with the details of the exception, thus resulting in the following in the logs:
2019-09-17 09:24:11.715  WARN 12564 --- [XNIO-1 task-23] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation]
 2019-09-17 09:24:11.950 ERROR 12564 --- [XNIO-1 task-75] io.undertow.servlet.request              : UT015012: Failed to generate error page /error for original exception: io.undertow.server.RequestTooBigException: UT000020: Connection terminated as request was larger than 52428800. Generating error page resulted in a 406.

Is there a way to either intercept that exception for the WS services, or to make the spring default error handler to return the exception as XML (just for the ws)?

A:
Tried using a @ExceptionHandler but same result.

I suppose that Spring considers that exception as a implementation detail of Undertow during the request processing that it performs and as a consequence it doesn't want to allow it leak above.
In Spring, you have exception handing and exception resolving.
Exception handlers are not always well designed to define a custom exceptions handling whether Spring implementation resolves them for you and apply a specific processing for.   There you look like in this case.
But all is not lost. A clean and possible approach (not tested) is to implement your own exception resolver to prevent Spring to map that Undertow exception into a HttpMediaTypeNotAcceptableException.
Since you use spring-ws, you should implement org.springframework.ws.server.EndpointExceptionResolver or more simply AbstractEndpointExceptionResolver or SimpleSoapExceptionResolver.
Implement resolveExceptionInternal() to perform the logic in case of that exception is thrown :
public class MyEndpointExceptionResolver extends AbstractEndpointExceptionResolver {

    public MyEndpointExceptionResolver(){
       setOrder(0);
    }

    @Override
    protected abstract boolean resolveExceptionInternal(MessageContext messageContext, Object endpoint, Exception ex){
      if (ex instanceof RequestTooBigException){
         // create the response message with the exception
         WebServiceMessage message = ...
         // set it in the MessageContext
         messageContext.setResponse(message);
         return true; // resolved
       }
      return false; // leave the default resolver doing its job
    }
}

Note that you may have multiple active exception revolvers for a same layer/concern. So you have to set the precedence of this one over the default one.
setOrder(0) does that.


text:
Q: visual studio 2010 Symbols aren't loading for debugging I am working on Sharepoint 2010 projects in Visual Studio 2010 and i am trying to attach to the w3wp.exe process.  I attach fine and a few of my assemblies show up in the Modules pane, but the main assembly i want to debug does not.  I have done everything to specifying the place to look for the pdb and even copying the pdb to a folder and pointing VS to look at that folder for the symblos but it still hasn't helped.

*

*i have retracted and deployed

*I have Cleaned all projs in the solution and then REBUILT and deployeed

*I have rebooted

*deleted bin and obj directories, cleaned, rebuilt and deployed

I don't know what else to try.  I have tried things from posts all over the web, anyone have anything else to try.  keep in mind this is a SHarePoint 2010 server with Visual Studio 2010 on it.

A: As Alex implied, it's not always intuitive to figure out when to attach to w3wp.exe, but as a general rule of thumb, if you're not actually watching the content getting rendered (that is, it's not in a web part or an application page), you almost always want to attach to the SharePoint Timer Service (owstimer.exe) instead. This is obviously true with stuff like timer jobs but it's equally the case with workflows and event receivers where you haven't explicitly called them as synchronous.
Alex's links are great for this too. I will add that when in doubt, and you're debugging out of your own dev environment, it's not always the worst thing in the world to attach to both owstimer and your application pool's version of w3wp.

A: in the end, someone over wrote the web.config changes required for the module so the code was never executed.  It never had anything to do with the symbols.  Thanks ULS for showing me the way ;)
Thanks for the responses.....

redpajama_set_name: RedPajamaStackExchange


text:
Q: Undefined Behavior with v-for and custom components First off, please excuse the awful code (we don't have time to fix right now). I know eval is horrible, but for our purposes it was the only thing that worked for us this easily.
This is how we add and remove the rows:
methods: {
    addRow: function() {
        let lastRow = eval(`this.$parent.json${this.path}[this.$parent.json${this.path}.length - 1]`);
        lastRow = Object.assign({}, lastRow);
        eval(`this.$parent.json${this.path}.push(lastRow)`);
        this.$forceUpdate();
    },
    removeRow: function(index) {
        //eval(`this.$parent.json${this.path}.splice(index, 1)`);
        eval(`Vue.delete(this.$parent.json${this.path}, index)`);
        this.$forceUpdate();
    }

https://jsfiddle.net/00e58as4/10/6
To recreate the issue, add a row. Then, change the text on the new row. Try removing the second-to-last row - notice how it doesn't get deleted, but the last one is. However, if you check the json-debug which is a live view of the backend data, you'll see that the proper row gets deleted!
Why does this happen? Why are the UI and the backend not in sync?

A: You should always use a key when iterating with v-for. Try adding one like this.
<div class = "well" v-for = "item, index in items" :key="item">


text:
Q: React, Does render on parent makes children re-render? Log shows that my parent component is rerendering itself.
But the child component's render method is not getting called.
I thought child rerenders with the following logic, and I think I'm wrong about it.
How does react decide which child components gets rerendered when parent rerenders?

*

*Parent's render

*-> child's shouldComponentUpdate gets called

*-> if shouldComponentUpdate return true, child rerenders

Parent render looks like
  render() {

    let { viewConfig } = this.props
    console.log("ViewConfigSettingBase rendering")
    return (
      <div>
        {
          Object.keys(viewConfig.availableSubviewConfigMap).map((sectionName, index) => {
            var subviewConfigData = viewConfig.availableSubviewConfigMap[sectionName]
            return (
              <ViewConfigSettingRow
                key={sectionName}
                viewConfigData={subviewConfigData}
                sectionName={sectionName}
                parentViewConfig={viewConfig}
                />
            )
          })
        }
      </div>
    )
  }

A: React re-renders on a props or state change. If you extended a PureComponent the children will do a check if the props have changed. If yes -> shouldComponendUpdate will return true otherwise false. Maybe this is the case?
Component lifecycle:
https://facebook.github.io/react/docs/react-component.html
Updating

An update can be caused by changes to props or state. These methods are >called when a component is being re-rendered:

componentWillReceiveProps()
shouldComponentUpdate()
componentWillUpdate()
render()
componentDidUpdate()

shouldComponentUpdate()

Use shouldComponentUpdate() to let React know if a component's output is >not affected by the current change in state or props. The default >behavior is to re-render on every state change, and in the vast majority >of cases you should rely on the default behavior.
shouldComponentUpdate() is invoked before rendering when new props or >state are being received. Defaults to true This method is not called for >the initial render or when forceUpdate() is used.
Returning false does not prevent child components from re-rendering when >their state changes.
Currently, if shouldComponentUpdate() returns false, then >componentWillUpdate(), render(), and componentDidUpdate() will not be >invoked. Note that in the future React may treat shouldComponentUpdate() >as a hint rather than a strict directive, and returning false may still result in a re-rendering of the component.
If you determine a specific component is slow after profiling, you may >change it to inherit from React.PureComponent which implements >shouldComponentUpdate() with a shallow prop and state comparison. If you >are confident you want to write it by hand, you may compare this.props >with nextProps and this.state with nextState and return false to tell >React the update can be skipped.

You can find some documentation about the react render process on the following pages:
https://facebook.github.io/react/docs/reconciliation.html
https://facebook.github.io/react/docs/optimizing-performance.html


text:
Q: Why I need to pass this when Im using synchronized block? Why I need to pass "this" when Im using synchronized block? what the purpose of the partemer of the synchronized?

A: Because synchronized needs an object to lock on. this is as convenient as any, or you could say Object lock = new Object() and synchronize on lock.
Alternatively you could mark your methods as synchronized.

A: Java synchronized block construct takes an object in parentheses. "this" is the instance of which method is called on. The object taken in the parentheses by the synchronized construct is called a monitor object. The code is said to be synchronized on the monitor object. A synchronized instance method uses the object it belongs to as monitor object.
Only one thread can execute inside a Java code block synchronized on the same monitor object.

A: The synchronization will be done on the object you specify, meaning if two threads synchronize on the same object, only one can run the code block at one time.
It can be any object, though it will often be this.
This enables you to synchronize on different objects in the same class, for example.

A: syntex is synchronized(objectLock) { }
not necessorily this,
we need to pass an object, to which we want to give exclusive access in case of multiple threads are trying to run the same synchronized block.
in this way, if at any point of time, 2 or more thread trying for access of synchronized block, the object passed ('this' in this case) will have exclusive access of the block, unless the block excution is finished, no one else can access that block.

A: Synchronize uses an object reference to lock on, a monitor object.
Each resource that you want to protect from simultaneous access should have its own monitor object. The easiest way to do this is often to use this.


text:
Q: Azure function trigger go to error when start I'm trying to implement the example of 'Image Resizer' that I find here:
https://github.com/jefking/fl-image-resize
when I start the function it returns me this error
Exception while executing function: Functions.ImageTriggerCSharp01. Microsoft.Azure.WebJobs.Host: Exception binding parameter 'myBlob'. Microsoft.WindowsAzure.Storage: The remote server returned an error: (404) Not Found.
subsequently the function is activated every minute without errors. Then, when I load a file, this error is generated:
Function compilation error
error: Missing a trigger argument named 'myBlob'.
warning: Missing binding argument named 'outputBlob'. Mismatched binding argument names may lead to function indexing errors.
what's wrong?
*********UPGRADE***********
i have this code:
run.csx=
#r "System.Drawing"

using System;
using System.Drawing;
using ImageProcessor;

private static readonly Size size = new Size(EnvAsInt("ImageResize-Width"), EnvAsInt("ImageResize-Height"));

public static void Run(Stream myBlob, Stream outputBlob, string name, TraceWriter log)
{
    log.Info($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes");
    if (myBlob==null){
        log.Info($"C# myBlob is NULL");
    }
    log.Info($"C# ok2");
    if (outputBlob==null){
        log.Info($"C# outputBlob is NULL");
    }
    log.Info($"C# ok3");
    using (var imageFactory = new ImageFactory())
    {
        log.Info($"C# ok31");

        imageFactory
            .Load(myBlob)
            .Resize(size)
            .Save(outputBlob);
    }
    log.Info($"C# ok4");
}

private static int EnvAsInt(string name) => int.Parse(Env(name));
private static string Env(string name) => System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
enter code here

function.json=
{
  "bindings": [
    {
      "type": "blob",
      "name": "outputBlob",
      "path": "photosthumbnails/{name}",
      "connection": "AzureWebJobsStorage",
      "direction": "out"
    },
    {
      "type": "blobTrigger",
      "name": "myBlob",
      "path": "photos/{name}",
      "connection": "AzureWebJobsStorage",
      "direction": "in"
    }
  ],
  "disabled": false
}

i have the error in
imageFactory
            .Load(myBlob)
            .Resize(size)
            .Save(outputBlob);

what can i do?

A: ok. i resolve.
the error is on
private static readonly Size size = new Size(EnvAsInt("ImageResize-Width"), EnvAsInt("ImageResize-Height"));

the two properties, ImageResize-Width and ImageResize-Height, were not included in the 'function' settings.
It's my first Azure function ... ^_^

A: Do verify the parameter names in run.csx and in the function.json file. The parameter names passed in the run.csx file should match with function.json file. Do check them in the reference you provided.


text:
Q: Powershell memory exhaustion using NTFSSecurity module on a deep folder traverse I have been tasked with reporting all of the ACL's on each folder in our Shared drive structure. Added to that, I need to do a look up on the membership of each unique group that gets returned.
Im using the NTFSSecurity module in conjunction with the get-childitem2 cmdlet to get past the 260 character path length limit. The path(s) I am traversing are many hundreds of folders deep and long since pass the 260 character limit.
I have been banging on this for a couple of weeks. My first challenge was crafting my script to do my task all at once, but now im thinking thats my problem... The issue at hand is resources, specifically memory exhaustion. Once the script gets into one of the deep folders, it consumes all RAM and starts swapping to disk, and I eventually run out of disk space.
Here is the script:
$csvfile = 'C:\users\user1\Documents\acl cleanup\dept2_Dir_List.csv'

foreach ($record in Import-Csv $csvFile)
{

$Groups = get-childitem2 -directory -path $record.FullName -recurse | Get-ntfsaccess | where -property accounttype -eq -value group
$groups2 = $Groups | where -property account -notmatch -value '^builtin|^NT AUTHORITY\\|^Creator|^AD\\Domain'
$groups3 = $groups2 | select account -Unique

 $GroupMembers = ForEach ($Group in $Groups3) {
    (Get-ADGroup $Group.account.sid | get-adgroupmember | select Name, @{N="GroupName";e={$Group.Account}}

)}
$groups2 | select FullName,Account,AccessControlType,AccessRights,IsInherited | export-csv "C:\Users\user1\Documents\acl cleanup\Dept2\$($record.name).csv"
$GroupMembers | export-csv "C:\Users\user1\Documents\acl cleanup\Dept2\$($record.name)_GroupMembers.csv"
}

NOTE: The dir list it reads in is the top level folders created from a get-childitem2 -directory | export-csv filename.csv
During the run, it appears to not be flushing memory properly. This is just a guess from observation. At the end of each run through the code, the variables should be getting over-written, I thought, but memory doesn't go down, so it looked to me that since memory didn't go back down, that it wasn't properly releasing it? Like I said, a guess... I have been reading about runspaces but I am confused about how to implement that with this script. Is that the right direction for this?
Thanks in advance for any assistance...!

A: Funny you should post about this as I just finished a modified version of the script that I think works much better. A friend turned me on to 'Function Filters' that seem to work well here. Ill test it on the big directories tomorrow to see how much better the memory management is but so far it looks great.
    #Define the function 'filter' here and call it 'GetAcl'. Process is the keyword that tells the function to deal with each item in the pipeline one at a time
Function GetAcl {

            PROCESS {
            Get-NTFSAccess $_  | where -property accounttype -eq -value group | where -property account -notmatch -value '^builtin|^NT AUTHORITY\\|^Creator|^AD\\Domain'
                    }
                }

#Import the directory top level paths
$Paths = import-csv 'C:\users\rknapp2\Documents\acl cleanup\dept2_Dir_List.csv'

#Process each line from the importcsv one at a time and run GetChilditem against it.
#Notice the second part – I '|' pipe the results of the GetChildItem to the function that because of the type of function it is, handles each item one at a time
#When done, pass results to Exportcsv and send it to a file name based on the path name. This puts each dir into its own file.
 ForEach ($Path in $paths) {
 (Get-ChildItem2 -path $path.FullName -Recurse -directory) | getacl | export-csv "C:\Users\rknapp2\Documents\acl cleanup\TestFilter\$($path.name).csv" }


text:
Q: Azure ML with python - (SSLError(SSLError('The write operation timed out',),),) when doing a table storage entity query Hi I am trying to begin an Azure ML algorithm by executing a python script that queries data from a table storage account. I do it using this:
entities_Azure=table_session.query_entities(table_name=table_name,
                                                filter="PartitionKey eq '" + partitionKey + "'",
                                                select='PartitionKey,RowKey,Timestamp,value',
                                                next_partition_key = next_pk,
                                                next_row_key = next_rk, top=1000)

I pass in the variables needed when calling the function that this bit of code sits in, and I include the function by including a zip file in Azure ML.
I assume the error is due to the query taking too long, or something like that, but it has to take a long time because I might have to query loads of data.... I looked at this SO post Windows Azure Storage Table connection timed out which is a similar issue I think with regard to hitting specified thresholds for these queries, but I don't know how I'd be able to avoid it. The run time of the program is only about 1.5 mins before timing out..
Any ideas as to why this is happening and how I might be able to solve it?
Edit:
As per Peter Pan - MSFT's advice I ran a query that was more specific:
entities_Azure=table_service.query_entities(table_name='#######',select='PartitionKey,RowKey,Timestamp,value', next_partition_key = None, next_row_key = None, top=2)

This returned the following error log:
Error 0085: The following error occurred during script evaluation, please view the output log for more information:
---------- Start of error message from Python interpreter ----------
data:text/plain,Caught exception while executing function: Traceback (most recent call last):

File "C:\server\invokepy.py", line 169, in
batch odfs = mod.azureml_main(*idfs)

File "C:\temp\azuremod.py", line 61, in
azureml_main entities_Azure=table_service.query_entities(table_name='######',select='PartitionKey,RowKey,Timestamp,value', next_partition_key = None, next_row_key = None, top=2)

File "./Script Bundle\azure\storage\table\tableservice.py", line 421, in query_entities
 response = self._perform_request(request)

File "./Script Bundle\azure\storage\storageclient.py", line 171, in _perform_request
 resp = self._filter(request)

File "./Script Bundle\azure\storage\table\tableservice.py", line 664, in _perform_request_worker
 return self._httpclient.perform_request(request)

File "./Script Bundle\azure\storage\_http\httpclient.py", line 181, in perform_request
 self.send_request_body(connection, request.body)

File "./Script Bundle\azure\storage\_http\httpclient.py", line 145, in send_request_body
 connection.send(None)

File "./Script Bundle\azure\storage\_http\requestsclient.py", line 81, in send
 self.response = self.session.request(self.method, self.uri, data=request_body, headers=self.headers, timeout=self.timeout)

File "C:\pyhome\lib\site-packages\requests\sessions.py", line 456, in request
 resp = self.send(prep, **send_kwargs)

File "C:\pyhome\lib\site-packages\requests\sessions.py", line 559, in send
 r = adapter.send(request, **kwargs)

File "C:\pyhome\lib\site-packages\requests\adapters.py", line 382, in send
 raise SSLError(e, request=request)

SSLError: The write operation timed out
---------- End of error message from Python  interpreter
---------- Start time: UTC 11/18/2015 11:39:32 End time: UTC 11/18/2015 11:40:53

Hopefully this brings more insight to the situation!

A: I tried to fill a table storage with data generated by myself and want to reproduce your issue thru doing a query like yours, but failed.
I found table storage query timeout issue for REST API (azure storage sdk for python wrapped REST API). The page (https://msdn.microsoft.com/en-us/library/azure/dd894042.aspx) "Query Timeout and Pagination" for Table Service REST API said:

A query against the Table service may return a maximum of 1,000 items at one time and may execute for a maximum of five seconds. If the result set contains more than 1,000 items, if the query did not complete within five seconds, or if the query crosses the partition boundary, the response includes headers which provide the developer with continuation tokens to use in order to resume the query at the next item in the result set. Continuation token headers may be returned for a Query Tables operation or a Query Entities operation.
Note that the total time allotted to the request for scheduling and processing the query is 30 seconds, including the five seconds for query execution.
It is possible for a query to return no results but to still return a continuation header.

I think the issue was caused by hitting these sepcified thresholds.
Also, I used the module Reader in Data Input and Output and set the data source with Azure Table to read 1000 entites successfully and fast on the Experiment of  Azure ML Studio.

For this scenario, I suggest you can use the specified query filter to query your table storage, such as the following:
entities_Azure=table_session.query_entities(table_name=table_name,
      filter="PartitionKey eq '" + partitionKey + "' and Rowkey eq '" + rowkey + "'",
      select='PartitionKey,RowKey,Timestamp,value',
      next_partition_key = next_pk,
      next_row_key = next_rk, top=1000)

We can use this code to judge the problem is connection issue or thresholds issue.
Any concern, please feel free to let me know.

A: I ran into a very similar problem in Access Azure blog storage from within an Azure ML experiment. I didn't realize they were similar when I first posted. However, it became very clear as the debugging and help continued.
Bottom Line: SSLError with Timeout occurs when azure.storage.* is accessed over HTTPS/SSL. If you change the creation of the 'TableService' to force the use of HTTP (protocol='http') the timeout errors will cease.
table_service = TableService(account_name='myaccount', account_key='mykey',protocol='http')
The full analysis can be found at the StackOverflow post above. However, I saw this and felt I should mention it directly here to help with searching. The fix applies to azure.storage.table, azure.storage.blob, azure.storage.page and azure.storage.queue.
PS. Yes, I know that using HTTP isn't optimal, however, you are running everything here within Azure. And when you leave Azure ML (or Azure App Service) you can switch back to HTTPS.


text:
Q: joda-time-2.2 convert LocalDateTime to java.sql.Timestamp I need a java.sql.Timestamp but when I try to convert from LocalDateTime, it fails because when the input string was converted to LocalDateTime, the letter "T" was added, as in 2013-03-15T00:00:00.000. Any ideas? Or is there a better way to convert a string to a Timestamp? I just wanted to use joda in case the time needs to be manipulated in the future.
Thanks.

A: Why can't you do
LocalDateTime ldt  = LocalDateTime.now();
Timestamp ts = new Timestamp(ldt.toDate().getTime());

A: The best way use Java 8 time API:
  LocalDateTime ldt = timeStamp.toLocalDateTime();
  Timestamp ts = Timestamp.valueOf(dateTime);

For use with JPA put in with your model (https://weblogs.java.net/blog/montanajava/archive/2014/06/17/using-java-8-datetime-classes-jpa):
@Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
    @Override
    public Timestamp convertToDatabaseColumn(LocalDateTime ldt) {
        return Timestamp.valueOf(ldt);
    }

    @Override
    public LocalDateTime convertToEntityAttribute(Timestamp ts) {
        return ts.toLocalDateTime();
    }
}

So now it is relative timezone independent time.
Additionally it is easy do:
  LocalDate ld = ldt.toLocalDate();
  LocalTime lt = ldt.toLocalTime();

Formatting:
 DateTimeFormatter DATE_TME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
 String str = ldt.format(DATE_TME_FORMATTER);
 ldt = LocalDateTime.parse(str, DATE_TME_FORMATTER);


text:
Q: VIm Grep on raspberry pi i want to grep search with vim editor on raspberry pi, Rasbian.
in windows, i usually use findstr and command like this
grep -s xxxx *.c

how do i grep search with vim editor on os Rasbian?

A: *

*If you wanna grep, just without leaving Vim, you can use :!cmd to run grep as an external command: :!grep xxx *.c

*Vim has :grep; it also uses the external grep (or whatever is configured in 'grepprg'), but parses the results and presents them in the quickfix list, which allows you to quickly navigate results inside Vim.

*If you don't have / don't want to use external grep, there's also the :vimgrep variant. You have to use Vim's regular expression syntax, and it'll be slower because files are loaded into Vim.

*Within a buffer, there are many alternatives, like :global or :ilist. With :bufdo, you can run them on all opened buffers.


text:
Q: AppsFlyer SDK integration I have added AppsFlyer SDK in application. Below is the code which i have added in the application:
In Application class:
 AppsFlyerConversionListener conversionDataListener =
                new AppsFlyerConversionListener() {

                    @Override
                    public void onInstallConversionDataLoaded(Map<String, String> conversionData) {

                    }

                    @Override
                    public void onInstallConversionFailure(String errorMessage) {
                        Log.d(AppsFlyerLib.LOG_TAG, "error getting conversion data: " + errorMessage);
                    }

                    @Override
                    public void onAppOpenAttribution(Map<String, String> attributionData) {
                        Log.d(AppsFlyerLib.LOG_TAG, "DEEP LINK WORKING");
                    }

                    @Override
                    public void onAttributionFailure(String errorMessage) {
                        Log.d(AppsFlyerLib.LOG_TAG, "error onAttributionFailure : " + errorMessage);
                    }
                };

AppsFlyerLib.getInstance().startTracking(this, "DEV_KEY");

In manifest :
<receiver android:name="com.appsflyer.SingleInstallBroadcastReceiver" android:exported="true">
      <intent-filter>
           <action android:name="com.android.vending.INSTALL_REFERRER" />
      </intent-filter>
</receiver>

In Activity for track event :
Map<String, Object> eventValue = new HashMap<String, Object>();
                    eventValue.put("login", "member");
AppsFlyerLib.getInstance().trackEvent(getApplicationContext(), "event_login", eventValue);

I am not able to view the event in AppsFlyer dashboard. Also not able to view custom parameters of event.
Any suggestions?
Thank you!

A: Your device is probably not whitelisted. As mentioned here, test devices should be whitelisted via AppsFlyer's app My Device ID by AppsFlyer.


text:
Q: How can I implement 'finding min-spanning tree algorithm' on a complex graph using graph-viz? I need to find minimum spanning trees in a large graph using graph-viz. The number of nodes and edge information will be given in another text-file in 2 columns,"source" and "destination". please help.

A: Graphviz is principally a tool to layout graphs. The algorithms that are included relate to this task. The input for a graph is a graph specification.
What you need is a tool that computes the MST. There are several. The wikipedia article is a good start for references:
http://en.wikipedia.org/wiki/Prim's_algorithm
In python there is
http://pygraphviz.github.io/
In perl, I found
https://gist.github.com/hirotnk/780342
The SO answer here:
Graphviz Dot Algorithm
is also a good reference.
Given the output of an MST tool, you can general a file that is rendered by graphviz.


text:
Q: Code 500 while trying to scrape from website I'm working on scraping from barchart.com using modified code from this stack overflow question:
The header and payload information are from the XHR of the website I was attempting to scrape.
from urllib.parse import unquote

geturl=r'https://www.barchart.com/options/highest-implied-volatility'
apiurl=r'https://www.barchart.com/proxies/core-api/v1/quotes/get'

getheaders={
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'en-US,en;q=0.9',
    'cache-control': 'max-age=0',
    'upgrade-insecure-requests': '1',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36'
    }

getpay={
    'page': 'all'
}

s=requests.Session()
r=s.get(geturl,params=getpay, headers=getheaders)

headersIV = {
    'method': 'GET',
    'scheme': 'https',
    'authority': 'www.barchart.com',
    'Host' : 'www.barchart.com',
    'Accept': 'application/json',
    'Accept-Encoding': 'gzip, deflate, br',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Safari/605.1.15',
    'Accept-Language': 'en-us',
    'Referer': 'https://www.barchart.com/options/highest-implied-volatility',
    'Connection': 'keep-alive',
    'X-XSRF-TOKEN': 'eyJpdiI6Ik8vQTBkcGxZVVF1aG5QeE9TUnk5L3c9PSIsInZhbHVlIjoiMDd6STJyM1FPZEtMMFdLNEcrVjNNWUMva1l3WWxwblMvdEFZMEIzSllzalFySGFoblcyRzgrRmNZa1RMRHdZcTlBVExQTjBQUEhVdTVaNWhMZlJ0ZFM4c3ZaeHMvVmptM2FGQXJobnM1WTl1REx1d3M1eDI2RUc2SEtHY2wzTnUiLCJtYWMiOiIyNGExYjI3N2JkOGRiZGEwYjY4MTQ3OGFiYmYxZGE3ZmJhZmQyMDQwM2NiZTc0YTMzZDFkNjI4ZGIwZmY2YTU0In0=',
    'path': '/proxies/core-api/v1/options/get?fields=symbol%2CbaseSymbol%2CbaseLastPrice%2CbaseSymbolType%2CsymbolType%2CstrikePrice%2CexpirationDate%2CdaysToExpiration%2CbidPrice%2Cmidpoint%2CaskPrice%2ClastPrice%2Cvolume%2CopenInterest%2CvolumeOpenInterestRatio%2Cvolatility%2CtradeTime%2CsymbolCode%2ChasOptions&orderBy=volatility&baseSymbolTypes=stock&between(lastPrice%2C.10%2C)=&between(daysToExpiration%2C15%2C)=&between(tradeTime%2C2021-10-21%2C2021-10-22)=&orderDir=desc&between(volatility%2C60%2C)=&limit=200&between(volume%2C500%2C)=&between(openInterest%2C100%2C)=&in(exchange%2C(AMEX%2CNASDAQ%2CNYSE))=&meta=field.shortName%2Cfield.type%2Cfield.description&hasOptions=true&raw=1',

}

payloadIV={
    'fields': 'symbol,baseSymbol,baseLastPrice,baseSymbolType,symbolType,strikePrice,expirationDate,daysToExpiration,bidPrice,midpoint,askPrice,lastPrice,volume,openInterest,volumeOpenInterestRatio,volatility,tradeTime,symbolCode,hasOptions',
    'orderBy': 'volatility',
    'baseSymbolTypes': 'stock',
    'between(lastPrice,.10,)':'',
    'between(daysToExpiration,15,)':'',
    'between(tradeTime,2021-10-21,2021-10-22)':'',
    'orderDir': 'desc',
    'between(volatility,60,)':'',
    'limit': '200',
    'between(volume,500,)':'',
    'between(openInterest,100,)':'',
    'in(exchange,(AMEX,NASDAQ,NYSE))':'',
    'meta': 'field.shortName,field.type,field.description',
    'hasOptions': 'true',
    'raw': '1'

}

r=s.get(apiurl,params=payloadIV,headers=headersIV)
j=r.json()
print(j)

It returns this error message: {'error': {'message': 'Internal error.', 'code': 500}}
I am pretty new to scraping data using API and XHR data. I think I might be doing many things correctly right now but I don't know where I might be making the mistake.


text:
Q: Result showing two rows to one row I wrote a query to count positive and negative results per day.  My problem is that I am getting two rows per postivie to negative day.

*

*I want one row with a positive and negative column for each day( no multiple days).

SELECT case([MsrSplatPositive]) when '0' then count([MsrSplatPositive]) end as 'Negative'
,case([MsrSplatPositive]) when '1' then count([MsrSplatPositive]) end as 'Positive'
,CONVERT(VARCHAR(10), f.NewsDate, 106) as 'Date'
 FROM [News].[dbo].[Score] s
inner join [News].[dbo].[Feed] f
on f.ScoreId = s.Id
where f.NewsDate between dateadd(day,-30,GETDATE()) and GETDATE()
group by [MsrSplatPositive],CONVERT(VARCHAR(10), f.NewsDate, 106)

A: Remove MsrSplatPositive from the GROUP BY.
That is forcing the positive and negative results into different days.
And then use a SUM(CASE...) instead of CASE(COUNT...)
You have this in the SELECT:
case([MsrSplatPositive]) when '0' then count([MsrSplatPositive]) end as 'Negative'

and instead want this:
sum(CASE WHEN MsrSplatPositive = 0 THEN 1 ELSE 0 END) as 'Negative'

EDIT:
All fixed up should be something like:
SELECT SUM(CASE WHEN MsrSplatPositive = 0 THEN 1 ELSE 0 END) 'Negative'
      ,SUM(MsrSplatPositive 'Positive'
      ,CONVERT(VARCHAR(10), f.NewsDate, 106) as 'Date'
  FROM News.dbo.Score s
       INNER JOIN
       News.dbo.Feed f on f.ScoreId = s.Id
 WHERE f.NewsDate BETWEEN DATEADD(DAY,-30,GETDATE()) and GETDATE()
 GROUP BY f.NewsDate

A: Try this...I haven't run the query but think this should achieve the result. I have modified your original query to return 0 instead of null in the positive and negative column. Then used the modified SQL as a temp table and grouped by the date values.
Select Sum(Temp.Negative), Sum(Temp.Positive), Temp.Date From
(
SELECT case([MsrSplatPositive]) when '0' then count([MsrSplatPositive])
    else 0 end as 'Negative'
,case([MsrSplatPositive]) when '1' then count([MsrSplatPositive]
    else 0) end as 'Positive'
,CONVERT(VARCHAR(10), f.NewsDate, 106) as 'Date'
FROM [News].[dbo].[Score] s
inner join [News].[dbo].[Feed] f
on f.ScoreId = s.Id
where f.NewsDate between dateadd(day,-30,GETDATE()) and GETDATE()
group by [MsrSplatPositive],CONVERT(VARCHAR(10), f.NewsDate, 106)
) Temp
Group By Temp.Date

Hope this helps.


text:
Q: Klein Bottle discrete harmonics? Studying discrete representations of  a function, on a $2$ Dimensional compact surface, brings to the use of spherical harmonics for the 2-sphere, and discrete Fourier transformations for the 2-torus.
But how does it work with the Klein Bottle?
That is, once a function $f$ on a Klein Bottle given, how discrete coefficients $f_{lm}$ are calculated from $f$, and reciprocally  ($f$ from $f_{lm}$  )?

A: Trimok's answer is essentially correct and in fact can be strengthened: the eigenfunctions on the (flat) Klein bottle are exactly
$$e^{i(2n+1)x}\sin(my),\ e^{i(2n)x}\cos(my).$$
This is a consequence of the following theorem, which is not so hard to prove using the fact that Riemannian covers are local isometries:

If $\hat{M}\to M$ is a regular cover of closed Riemannian manifolds with deck group $\pi$ acting by isometries on $\hat{M}$, the eigenfunctions of $M$ are precisely the $\pi$-invariant eigenfunctions of $\hat{M}$.

If we are interested in any (complete) metric at all on the Klein bottle, then I am not sure what one can say. There may be a rigidity theorem that implies eigenvalues are extremized on the flat Klein bottle.

A: I propose a possible answer, while I am not sure at all it is true...
It will correspond, I think, to a flat metric.
For the 2-torus, we have the 2 identifications :
$$x \rightarrow x + 2\pi   \space  \space and \space  \space y \rightarrow y + 2\pi$$
So the torus eigenfunctions are :
$$e^{i(nx+my)}$$
Now, the Klein Bottle could be defined from the 2-torus by the involution :
$$ x \rightarrow x + \pi   \space  \space y \rightarrow - y  $$
So the eigenfunctions of the Klein Bottle should be a subset of the eigenfunctions of the torus, compatible with this involution, so they should be :
$$ e^{i(2n+1)x} \sin (my)   \space   \space , \space \space e^{i(2n)x} \cos (my)$$

A: The 2-sphere and the 2-torus are naturally endowed with an action of some group $G$ ($SO(3)$ in the former case and translations in the latter). Therefore the functions on these manifolds realize a representation of $G$ which can be decomposed into irreducibles. This corresponds to spherical harmonics and Fourier decompositions. It seems to me (though I'm not sure) that there is no natural group action on the Klein bottle, so this appoach wouldn't work.
Alternatively, one can consider these decompositions as being with respect to eigenfunctions of Laplacian, which is itself defined with respect to some riemannian metric (for instance, induced by flat metric of $\mathbb{R}^3$ for the 2-sphere and flat for the 2-torus). So if you have some preferred metric on the Klein bottle (e.g. flat), you can formally write such kind of expansion. However, the eigenbasis of Laplacian ("functions $f_{lm}$") is not known explicitly except probably in the flat case.


text:
Q: How to create 'responsive' lists: creating multiple columns to fit available width? In my old fixed-width world, I could take a variable X # of elements, divide by three and distribute the data across three columns fairly efficiently:

In this new fangled responsive world, the best solution I've come up (so far) is to split data into fixed-size buckets (say 5) and then let the chunked lists float left:

This works great when you have a list that's pretty long, but when you have a small list - there are A LOT of horizontal pixels that can get wasted.  It also works pretty well if one of the elements ends up being SUPER long/wide, and it can effectively push the next group of lists down under it.
I'm currently using Bootstrap3, but open to a pure CSS solution for this.
Is there a great way to do responsive multi-column lists (optimizing for available width on the device)

A: what if you just make 3 responsive columns in a row:
Edit: added media query to make 3 columns 1 column
jsFiddle

Hello

World

!

.outer {
    width: 100%;
}
.inner1 {
    clear: both;
    float: left;
    display:inline-block;
    width: 32%;
}
.inner2 {
    display:inline-block;
    width: 32%;
    margin-left: 2%;

}
.inner3 {
    display:inline-block;
    width: 32%;
    margin-left: 2%;
}

@media only screen and (max-width: 420px) {   /* small mobile sizes */

.inner1, .inner2, .inner3 {
    display:block;
    width:100%;
    }
}

This Fiddle is updated with the media query that makes the 3 columns into 1 column on screen widths <= 420px


text:
Q: How do I get different colored prompt depending on server? I use ssh all the time, but I sometimes forget which server I am on.
Can I using the same .bashrc (/home is NFS shared) have different colored prompt on different servers? Preferably without listing the servers.

A: Something like this:
set_color_prompt() {
    _colorcombos() {
    PERL_HASH_SEED=109 perl -MB -e '
        use B;
        # color combinations that are readable (e.g. no red on red)
        @c =(map { "$_\n0\n" }
             6..7,9..11,13..15,40..51,75..87,113..123,147..159,171..231,249..254),
            (map { "$_\n231\n" }
             1..9,12..13,16..45,52..81,88..116,124..151,153,160..180,
             182..185,187..189,196..214,232..252,255..254);
        for(@ARGV) {
            print @c[hex(B::hash($_)) % $#c];
        }
        ' "$@"
    }
    local col=($(_colorcombos `whoami` `hostname` "`id`"))
    # (bg1,fg1)=user, (bg2,fg2)=host, (bg3,fg3)=path
    PS1='${debian_chroot:+($debian_chroot)}\[\033[48;5;'${col[0]}';38;5;'${col[1]}'m\]\u\[\033[00m\]\[\033[48;5;'${col[2]}';38;5;'${col[3]}'m\]@\h\[\033[00m\]:\[\033[48;5;'${col[4]}';38;5;'${col[5]}'m\]\w\[\033[00m\]\$ '
}

# set a fancy prompt (non-color, unless we know we "want" color)
case "$TERM" in
xterm-color)
    set_color_prompt
    ;;
xterm-256color)
    set_color_prompt
    ;;
*)
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
    ;;
esac

It will set a colored prompt based on whoami, hostname and id, so the color will also be different if you log in as a different user.
whoami, hostname and id are hashed, and based on the hash value a color combination is chosen. The combinations are tested to make sure they are readable.
Change PERL_HASH_SEED=109 to get different colors (e.g. if two important servers happen to give the same value).


text:
Q: Android - JSONException No value for I know that there are several questions posted on here with the same topic and error, but none of them indicate the same problem as mine, so I decided to post my question here, hoping that someone would help me point out the cause.
So I'm trying to implement the login feature in my app and here's the code:
if (tag.equalsIgnoreCase(login_tag)){
                // check for login response
                try {
                    if (json.getString(KEY_SUCCESS) != null) {
                        String res = json.getString(KEY_SUCCESS);
                        if(Integer.parseInt(res) == 1){
                            // user successfully logged in
                            // Store user details in SQLite Database
                            DatabaseHandler db = new DatabaseHandler(mContext);
                            JSONObject json_user = json.getJSONObject("user");

                            // Clear all previous data in database
                            logoutUser(mContext);
                            Toast.makeText(mContext, json.toString(3), Toast.LENGTH_LONG).show();
                            db.addUser(json_user.getString(KEY_EMAIL), json_user.getString(KEY_NAME), json.getString(KEY_UID), json.getString(KEY_AVA), json_user.getString(KEY_BDAY), json_user.getString(KEY_COUNTRY), json_user.getString(KEY_PREF), json_user.getString(KEY_SPEND));

                            // Launch Dashboard Screen
                            Intent dashboard = new Intent(mContext, DashboardActivity.class);

                            // Close all views before launching Dashboard
                            dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            mContext.startActivity(dashboard);

                            // Close Login Screen
                            ((Activity) mContext).finish();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

And this is the JSON response I got when logging in:
{
    "tag": "login",
    "success": 1,
    "error": 0,
    "uid": "5123",
    "user": {
        "email": "abcxyz@gmail.com",
        "name": "abc",
        "avatar": "avatars/img_hzsxda_2013-03-18-11-03-33.jpg",
        "bday": "1991-02-01",
        "country": "Australia",
        "preferences": "none",
        "spending": "none"
    }
}

So apparently there is a value for avatar, but I still got this warning in my logcat:
03-18 12:06:36.972: W/System.err(24574): org.json.JSONException: No value for avatar

Since no value avatar is got, I can't complete addUser, hence login fails.
Please help me find the error and how to solve it. Thank you.

A: You are using the wrong object to get avatar value here json.getString(KEY_AVA). It should be json_user.getString(KEY_AVA).
Also, you can use optString instead of getString which just returns null if value doesn't exist, instead of throwing an exception.


text:
Q: Ruby and Threads - Why isn't my script finishing? I have a script that provisions nodes for a cluster remotely using Thread so I can do all of them at once.
Is there a better way I can do this so I get a return code, a clean exit, and a script that does not seem to run for an inordinate amount of time?
@threads = []

def process_node(apps_to_close, node)
  @threads << Thread.new do
    puts "now processing node #{node}\n"
    ...
  end
end

nodes.each do |node|
  process_node(apps_to_close, node)
end

@threads.each {|thr| thr.join}

A: You can a limit to the amount of time you allow threads to run via join, which returns nil if the thread is still running when the timeout is reached. So you could rewrite this as:
...

results = @threads.collect { |thr| thr.join(1) } # wait 1 second for thread
@threads.each { |t| Thread.kill(t) }
results.any?(&:nil?) ? exit(1) : exit(0)


text:
Q: Why is magnetic field perpendicular to that plane? Magnetic field is perpendicular to the plane containing direction of flow of current in a straight wire and radius vector.What I have been told is that,to explain lorentz force magnetic field was taken perpendicular to the direction of the plane containing radius vector and direction of flow of current.
Now if we talk about physical significance,what I had understood is that the direction of electric field gives the direction of the electrical component of electromagnetic waves but I couldn't relate magnetic field to magnetic component of electromagnetic wave.The magnetic field I mentioned above from starting is perpendicular to the plane but the magnetic field component of electromagnetic wave is not looking so.Can someone explain me?
Or am I opting a wrong idea of electromagnetic wave?

A: I think there is a confusion between the concept of electromagnetic (EM) waves and EM field. Think about this two concept as the analogous of sound waves and air pressure. The first is the radiation, and the second is the medium where the radiation propagates.
Now, consider your system: a conducting wire containing a non-zero current. If the current is constant, there are no EM waves radiating from the wire, but there is only a stationary (constant in time) magnetic field, described by the Biot-Savart law (see Wikipedia).
It is important to understand that in the stationary case, electric and magnetic field are largely independent (if one sticks within a fixed reference frame), and their directions can be perpendicular, parallel, or anything in between. To see this, consider a region of space near a charged object and a magnet. The electrical field of the charge and the magnetic field of the magnet can assume different orientations in each point of the space, depending on the relative positions and orientations of the magnet and of the magnetic field.
EM waves are the excitations of the EM field propagating in space and time. They are typically the consequence of moving charges which are accelerating or changing directions. For example, if the current in the wire is alternating current (variable in time), conducting electrons do not have a constant speed[*] and produce EM radiation.
An EM wave is an oscillating solution of the Maxwell equations. These equations mandate that the magnetic and the electric components of this solutions are perpendicular.
However, since Maxwell equations are linear, any linear superposition of solutions of the Maxwell equations is still a solution. Therefore, one can consider, for example an EM wave superimposed to a stationary electric field. In this case the electric field and the magnetic field are not perpendicular.
[*] Ok, this is an oversimplification, because electrons don't have a constant field even in the case of stationary current (DC), due to scattering with the ion lattice. However this scattering processes are not sufficient to produce a macroscopically observable EM radiation.


text:
Q: Domain logon-dialog when opening "Computer management" When I'm logged in to the domain on the client computer I need to logon to the domain again when I right-click "Computer" and chooses "Manage". No GPO has been set yet, and the user seems to be admin as well.
This problem is only when I logon domain. If I log in with local admin, everything is fine.
Why does it ask for the password again, and how can I prevent that?


text:
Q: Derivative of Gaussian filter in Matlab Is there a derivative of Gaussian filter function in Matlab? Would it be proper to convolve the Gaussian filter with [1 0 -1] to obtain the result?

A: As far as I know there is no built in derivative of Gaussian filter. You can very easily create one for yourself as follow:
For 2D
G1=fspecial('gauss',[round(k*sigma), round(k*sigma)], sigma);
[Gx,Gy] = gradient(G1);
[Gxx,Gxy] = gradient(Gx);
[Gyx,Gyy] = gradient(Gy);

Where k determine the size of it (depends to which extent you want support).
For 1D is the same, but you don't have two gradient directions, just one. Also you would create the gaussian filter in another way and I assume you already have your preferred method.
Here I gave you up to second order, but you can see the pattern here to proceed to further orders.
The convolving filter you posted ( [1 0 -1] ) looks like finite difference. Although yours I believe is conceptually right, the most correct and common way to do it is with [1 -1] or [-1 1], with that 0 in the middle you skip the central sample in approximating the derivative.  This may work as well (but bare in mind that is an approximation that for higher orders diverge from true result), but I usually prefer the method I posted above.

Note: If you are indeed interested in 2D filters, Derivative of Gaussian family has the steerability property, meaning that you can easily create a filter for a Derivative of Gaussian in any direction from the one I gave you up. Supposing the direction you want is defined as
cos(theta), sin(theta)

Then the derivative of Gaussian in that direction is
Gtheta = cos(theta)*Gx + sin(theta)*Gy

If you reapply this recursively you can go to any order you like.

A: Of just use the derivative of a gaussian which is not more difficult then computing the gaussian itself.
G(x,y) = exp(-(x^2+y^2)/(2*s^2))
d/dx G(x, y) = -x/s^2 G(x,y)
d/dy G(x, y) = -y/s^2 G(x,y)

A: function [ y ] = dgaus( x,n )
%DGAUS nth derivative of exp(-x.^2)

odd=0*x;
even=exp(-x.^2);

for order=0:(floor(n/2)-1)
    odd=-4*order*odd-2*x.*even;
    even=-(4*order+2)*even-2*x.*odd;
end
if mod(n,2)==0
    y=even;
else
    y=-2*(n-1)*odd-2*x.*even;
end

end


text:
Q: CLIPS how can I sum up slots of facts Lets say I have the following two deftemplates:
(deftemplate total-crop-yield-quality (slot primary_key) (slot quality))
(deftemplate total-fertilizer-quality (slot primary_key) (slot quality))

and the following deffacts:
   (deffacts tQuality
    (total-crop-yield-quality (primary_key 1) (quality 10))
    (total-crop-yield-quality (primary_key 2) (quality 7))
    (total-crop-yield-quality (primary_key 3) (quality 9))
    (total-crop-yield-quality (primary_key 4) (quality -2)))

   (deffacts fQuality
    (total-fertilizer-quality (primary_key 1) (quality 4))
    (total-fertilizer-quality (primary_key 2) (quality 0))
    (total-fertilizer-quality (primary_key 3) (quality 2))
    (total-fertilizer-quality (primary_key 4) (quality 5)))

How would I sum up the total for all the qualities of both deffacts into a single variable?
(defrule determine-total-quality
  =>
 //code here to add quality to a variable)

A:          CLIPS (6.31 2/3/18)
CLIPS> (deftemplate total-crop-yield-quality (slot primary_key) (slot quality))
CLIPS> (deftemplate total-fertilizer-quality (slot primary_key) (slot quality))
CLIPS>
(deffacts tQuality
   (total-crop-yield-quality (primary_key 1) (quality 10))
   (total-crop-yield-quality (primary_key 2) (quality 7))
   (total-crop-yield-quality (primary_key 3) (quality 9))
   (total-crop-yield-quality (primary_key 4) (quality -2)))
CLIPS>
(deffacts fQuality
   (total-fertilizer-quality (primary_key 1) (quality 4))
   (total-fertilizer-quality (primary_key 2) (quality 0))
   (total-fertilizer-quality (primary_key 3) (quality 2))
   (total-fertilizer-quality (primary_key 4) (quality 5)))
CLIPS>
(defrule determine-total-quality
  =>
  (bind ?sum 0)
  (do-for-all-facts ((?f total-crop-yield-quality)) TRUE
     (bind ?sum (+ ?sum ?f:quality)))
  (printout t "Crop Yield Quality: " ?sum crlf)
  (bind ?sum 0)
  (do-for-all-facts ((?f total-fertilizer-quality)) TRUE
     (bind ?sum (+ ?sum ?f:quality)))
  (printout t "Fertilizer Quality: " ?sum crlf))
CLIPS> (reset)
CLIPS> (run)
Crop Yield Quality: 24
Fertilizer Quality: 11
CLIPS>


text:
Q: Confusing result when using where.not with Rails I've got an orders model with a payment status string field. Ordinarily this field should be populated but sometimes it's nil. I have the following scope
scope :not_pending, -> { where.not(payment_status: 'pending') }

In one of my tests, the payment_status is nil for an order but I still get an empty result for the scope. If I change it to remove the .not, I get an empty result again so I'm a bit confused.
EDIT - Added SQL
"SELECT "orders".* FROM "orders" INNER JOIN "order_compilations" ON "orders"."id" = "order_compilations"."order_id" WHERE "order_compilations"."menu_group_id" = 3724 AND ("orders"."payment_status" != 'pending')"

A: Just add nil along, then it will check both
scope :not_pending, -> { where.not(payment_status: 'pending').or(payment_status: nil) }

which is equivalent to where("payment_status <> 'pending' OR payment_status IS NULL")
UPDATE
changed to include nil

A: This is not because of Rails but because it's how SQL actually works.
!= means something different, but still something. NULL is not something.
You can see this related issue.

A: In SQL, a NULL value in an expression will always evaluate the expression to false. The theory is that a NULL value is unknown, not just an empty value that you could evaluate to 0, or false.
So for example, 1 = NULL is false, but 1 != NULL is false too.
So in your case, I would probably write:
where("payment_status != 'pending' or payment_status is null")


text: Q: Audio on my MacBook stops working while using Ubuntu 20.04 I recently installed Ubuntu 20.04 on my MacBook Pro (macOS Catalina). I run Ubuntu on VirtualBox and every time that I run Ubuntu, the audio on my Mac stops working. It starts working after I close Ubuntu. I am not sure what I can do, it would be great if someone could help me.


text:
Q: Eclipse RCP run application I have a custom editor and implemented my own language similar to Java.
I have implemented my custom runner and want to run the application via the shortcut CTRL+F11. Which command is executed when running via shortcut?


text:
Q: Twisted getpage using proxy I use getpage () to load the pages:
 d = getPage(url)
 d.addCallback(parsePage,url)
 d.addErrback(downloadError,url)

Now you need to download via http proxy. How can I call getpage () to use http proxy?

A: Use twisted.web.client.ProxyAgent instead.  getPage is Twisted's old, not-very-good HTTP client API.  IAgent is the new, better HTTP client API.  Apart from its other advantages, it also has more features than getPage - including support for HTTP proxies.
Here's an example:
from __future__ import print_function

from os import environ

from twisted.internet.task import react
from twisted.internet.endpoints import HostnameEndpoint
from twisted.web.client import ProxyAgent

def main(reactor, proxy_hostname):
    endpoint = HostnameEndpoint(reactor, proxy_hostname, 80)
    agent = ProxyAgent(endpoint)
    return agent.request(b"GET", b"http://google.com/").addCallback(print)

react(main, [environ["HTTP_PROXY"]])


text:
Q: Phonegap App lost images on update, recovering from the camera roll I have an app where users take images and they are saved along with user notes. Per the following link this is what I was using to save the images to the app. The issues is when some users update the app the images are lost.
Phonegap - Retrieve photo from Camera Roll via path
per the bosses instructions the users aren't allowed to browse the gallery for images as they are being used as proof of work performed (small company, 5-12 employees using the app).
is there any way for iphone to relay back to the app the actuall image location on the camera roll like android does? Then I can just save the URI to the database and call it when the form is submitted...
Thanks

A: You need to use

window.resolveLocalFileSystemURI()

to convert the filelocation to a fileentry or else your filepath will contain the App UUID which changes when you update/deploy your app.


text:
Q: How can users enable Background Server GC in a desktop app without changing app.config? I look after a WPF desktop app which many users run on varying hardware. Multiple threads constantly churn through a large volume of data.
Turning on .NET Framework 4.5 Background server garbage collection  has shown significant performance improvements, however this comes at the cost of more memory being used and different CPU usage patterns. This is a potential problem for users with less-powerful machines, so I want to give the users who'd benefit most an opt-in to having server GC enabled instead of forcing it upon everyone.
The only way I've found so far to enable this is in App.Config:
<configuration>
  <runtime>
    <gcServer enabled="true"/>
  </runtime>
</configuration>

However, most users do not have permissions to edit this as the app resides within Program Files and they're not local admins. My ideal scenario would be a friendly-worded option which could restart the app with server GC enabled and remember their choice.
So my question is: Does anyone know of any other way to apply this setting?
I know it's probably wishful thinking - but ideally something dynamic at runtime, or maybe a command-line argument or environment variable which could be set in the context of the process. There are hints of this existing in CoreCLR with the complus_gcServer  env variable.
I've read about global system settings which can enable this on the machine but I don't want to risk impacting any other apps and causing other adverse affects, I only want this to apply to my app.
As a last resort I could deploy two copies of the EXE with different config files and a launcher to choose the correct version to run, this seems extreme though.
Thanks for reading, any ideas welcome!

A: Here is an alternate suggestion. Leave server GC enabled as you have done. Then based on a user defined setting force GC to run if app memory goes above a certain threshold that you determine as the critical level.
Mind you if you follow this path you are effectively stating that you have better knowledge of when garbage collection should run that the CLR does. Most often than not I've found that the CLR does a better job on its own than when we interfere with it.
Code to check memory usage and run GC across either all generations or a specified generation
if (Math.Abs(DateTime.Now.Subtract(MemUsageLastCheckTime).TotalMinutes) > 5d)
{
    long UsedMemory;
    //UsedMemory = GC.GetTotalMemory(false); // Not as reliable
    UsedMemory = System.Diagnostics.Process.GetCurrentProcess().PagedMemorySize64;
    if (UsedMemory > 1073741824) // One GB in bytes 1 X 1024 X 1024 X 1024
    {
        GC.Collect(); // Collect all generations
        //GC.Collect(2,GCCollectionMode.Forced);; Or collect a specific generation and force it to run now
    }
    MemUsageLastCheckTime = DateTime.Now;
}


text:
Q: JavaScript suppress date format warning Whenever I try to reset a date input using JavaScript, like so:
//input_id is an id of a date input
document.getElementById(input_id).value = "0000-00-00";

I get a warning in the console:
The specified value "0000-00-00" does not conform to the required format, "yyyy-MM-dd".

Does anyone know a way to suppress this warning so it won't show? The JS keeps on running smoothly but I want to get rid of these warnings.
If you have another way of resetting a date input (without raising a warning) I will be happy to hear.
Thanks in advance.

A: You're getting the warning because years, months, and days start at 1, not 0. 0 is an invalid value for all of them. But there's a simpler way to reset an input element..
You can just set the value to the empty string which is the initial default value.
var di = document.createElement("input");
di.type = "date";
console.log(di.value); // outputs ""
document.body.appendChild(di);

// change the value if you want

// to reset:
di.value = "";

A: You can assign a empty string value
document.getElementById(input_id).value = "";

A: At the bottom of your Javascript call
console.clear();

This clears all warnings and errors from your console.
You can also replace console.warn with your own code like:
console.warn = function () { };.
NOT recommended because you will not get any warnings to your console this way.


text:
Q: Wordpress ACF Plugin - wp_get_attachment_image function doesn't work with ACF Options Page? I'm trying to get an image asset shown on the front-end using the wp_get_attachment_image WordPress function, but it doesn't seem to work with my options page on ACF.
Here is my code:
<?php

    $image = get_field('logo', 'option');
    $size = 'full'; // (thumbnail, medium, large, full or custom size)

    if( $image ) {

        echo wp_get_attachment_image( $image, $size );

    }

?>

Which looks like this on the back-end:

The picture you see above is an options page in ACF and when I try to query that image into the wp_get_attachment_image function, it doesn't work. However, when I run this code:
<img data-src="<?php the_field('logo', 'option'); ?>" alt="footer logo" class="lazyload" />

which is within an image tag, it works just fine.
I copied and pasted what was shows on the ACF docs located here (Basic Display ID), but it's not showing the image on the front-end.
Anything I'm missing guys?
Thanks a lot!

A: Return value in field should be Image ID. See Screenshot

A: What is the return value type you used? Image Array,  Image URL,  Image ID
And you need to get a field like this:
get_field('logo');  why do you add option?
More info here:
https://www.advancedcustomfields.com/resources/image/

A: wp_get_attachment_image requires the first parameter to be an image ID. In your case, if you are seeing the image using the code <img data-src="<?php the_field('logo', 'option'); ?>" alt="footer logo" class="lazyload" /> then get_field('logo', 'option') is returning the url of the image.. not the ID which is what you need if you are using wp_get_attachment_image.
What you need to do is change the Return Value of your logo field to Image ID.
Then you might have to re upload the image.
And also change this code <img data-src="<?php the_field('logo', 'option'); ?>" alt="footer logo" class="lazyload" /> to <img data-src="<?php echo wp_get_attachment_url(get_field('logo', 'option')); ?>" alt="footer logo" class="lazyload" />

A: ACf plugin returns value as you have set the return type.
If you have sent the return type as Image array then :

$image[0] -> full or $image[0][$full] or $image[$full]   depending on the number of image uploaded.

If you have set return type as Image url:
<img src="<?php $image; ?>">  would do the work.

If you are setting return type as Image Id:

$img2 = wp_get_attachment_image_src(get_post_thumbnail_id($image),
  $full);   echo $img2[0];

I guess above methods will surely help you out.
Thanks


text:
Q: Why does my PDO object return object(PDO)[2] Hi i am working on a basic databse connection class for mysql using PDO, however when i var dump the return result it tells me i has 2 objects: object(PDO)[2]. Should it not be only one ?
Here is my code so far:
class DBConnection
{
    // Settings (DSN)
    protected $driver, $host, $name, $charset;

    // Credentials
    protected $user, $pass;

    // PDO Connection
    protected $connection;

    public function __construct() {
        require_once( 'database.config.php' );

        // Settings (DSN)
        $this->driver   = DB_DRIVER;
        $this->host     = DB_HOST;
        $this->name     = DB_NAME;
        $this->charset  = DB_CHARSET;

        // Credentials
        $this->user     = DB_USER;
        $this->pass     = DB_PASS;

        // Initialise Connection
        var_dump($this->getConnection());
    }

    private function getConnection() {
        // Check if connection is already established
        if ( $this->connection == NULL ) {
            $dsn = "$this->driver:host=$this->host;dbname=$this->name;charset=$this->charset";
            try {
                $this->connection = new PDO($dsn,$this->user, $this->pass);
                $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            } catch ( PDOException $error ) {
                echo 'Connection failed: ' . $error->getMessage();
            }
        }
        return $this->connection;
    }
}

$new = new DBConnection();

Config file:
define('DB_DRIVER', 'mysql');
define('DB_HOST', 'localhost');
define('DB_NAME', 'test');
define('DB_CHARSET', 'utf8');
define('DB_USER', 'root');
define('DB_PASS', '');

A:     private function getConnection() {
    // Check if connection is already established
    if ( $this->connection == NULL ) {
        $dsn = "$this->driver:host=$this->host;dbname=$this->name;charset=$this->charset";
        try {
            $this->connection = new PDO($dsn,$this->user, $this->pass);
            $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            // This line is to remove associate array, then you will get only one object in result set
            $this->conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        } catch ( PDOException $error ) {
            echo 'Connection failed: ' . $error->getMessage();
        }
    }
    return $this->connection;
}


text:
Q: How can i use component located in form1 in other class using c# I create listview in form1 and i need to use it in other class
but if i add load function to the form1 the function works without problem
Form1:
public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Command_Procesures.LoadAll();
    }

And the Command_Procesures:
    public class Command_Procesures

{
    public static void LoadAll()
    {
        List<database> users = database.GetUsers();

        Form1 ff = new Form1();

        ff.listView1.Items.Clear();

        foreach (database u in users)
        {

            ListViewItem item = new ListViewItem(new String[] { u.Id.ToString(), u.Username, u.Password });
            item.Tag = u;

            ff.listView1.Items.Add(item);

        }
    }

}

A: The reason this isn't working is because you're creating a new instance of your form, setting your data to that instance, and then never showing that form.  Instead, you need to set the data on the form instance you already have.
In the simplest case based on the structure you have now you'd pass a reference to it:
public static void LoadAll(ListView listView)
{
    List<database> users = database.GetUsers();

    listView.Items.Clear();

    foreach (database u in users)
    {

        ListViewItem item = new ListViewItem(new String[] { u.Id.ToString(), u.Username, u.Password });
        item.Tag = u;

        listView.Items.Add(item);

    }
}

Then simply supply that reference when calling the method:
Command_Procesures.LoadAll(this.listView1);

It can be argued that this isn't the best practice, though such things are always debatable.  In general you'd want only your UI objects (forms in this case) to access your UI elements.  Other classes would be used to interact with backing data and services and return those to the UI, but only the UI should interact with and depend upon itself.
Basically, by introducing a Windows Forms dependency to your other class, that class can now only be used by Windows Forms projects.  So that class should only be a helper class within your Windows Forms project, if a separate class at all.


text:
Q: Proving the Continuation Passing Style Monad in Coq I'm trying to prove the Monad laws (left and right unit + associativity) for the Continuation Passing Style (CPS) Monad.
I'm using a Type Class based Monad defintion from https://coq.inria.fr/cocorico/AUGER_Monad:
Class Monad (m: Type -> Type): Type :=
  {
    return_ {A}:     A -> m A;
    bind    {A B}:   m A -> (A -> m B) -> m B;

    right_unit {A}:  forall (a: m A), bind a return_ = a;
    left_unit  {A}:  forall (a: A) B (f: A -> m B),
                       bind (return_ a) f = f a;
    associativity {A B C}:
                     forall a (f: A -> m B) (g: B -> m C),
                       bind a (fun x => bind (f x) g) = bind (bind a f) g
}.

Notation "a >>= f" := (bind a f) (at level 50, left associativity).

The CPS type constructor is from Ralf Hinze's Functional Pearl about Compile-time parsing in Haskell
Definition CPS (S:Type) := forall A, (S->A) -> A.

I defined bind and return_ like this
Instance CPSMonad : Monad CPS  :=
  {|
    return_ := fun {A} a {B} => fun (f:A->B) => f a ;
    bind A B := fun (m:CPS A) (k: A -> CPS B)
      =>(fun C => (m _ (fun a => k a _))) : CPS B

  |}.

but I'm stuck with the proof obligations for right_unit and associativity.
- unfold CPS; intros.

gives the obligation for right_unit:
  A : Type
  a : forall A0 : Type, (A -> A0) -> A0
  ============================
   (fun C : Type => a ((A -> C) -> C) (fun (a0 : A) (f : A -> C) => f a0)) = a

Would be very grateful for help!
EDIT:  András Kovács pointed out that eta conversion in the type checker is sufficient, so intros; apply eq_refl., or reflexivity. is enough.
Bur first I had to correct my incorrect definition of bind. (The invisible argument c was on the wrong side of the )...
Instance CPSMonad : Monad CPS  :=
  {|
    return_ S s A f     := f s ;
    bind    A B m k C c := m _ (fun a => k a _ c)
  |}.

A: The solution, as mentioned in a comment by András Kovács on Mar 11 at 12:26, is

Maybe you could try going straight for reflexivity? From Coq 8.5 there's eta conversion for records, so all the laws should be apparent immediately by normalization and eta conversion.

That gives us the following instance:
Instance CPSMonad : Monad CPS  :=
  {|
    return_       S s A f :=     f s ;
    bind          A B m k C c := m _ (fun a => k a _ c) ;
    right_unit    A a :=         eq_refl ;
    left_unit     A a B f :=     eq_refl ;
    associativity A B C a f g := eq_refl
  |}.


text:
Q: MaterialApp Widget's title Property Not Working I am an absolute beginner to Flutter !

Picture# 1 : Reference from tutorial.

Picture# 2 : My implementation.
Virtual Device: Nexus_5X_API_28
Android: 9.0

A: Are you sure you are using the same emulator in both examples?
The title in MaterialApp Widget isn't the title you will see in the Application Bar.

used by the device to identify the app

as documentation says.
So Maybe it is how the device displays 'running applications menu'.

If you want to display the appBar you need to use Scaffold
void main() => runApp(
      MaterialApp(
        title: 'App',
        home: Scaffold(
          appBar: AppBar(
            title: Text('My App'),
          ),
          body: Center(
            child: Text("text"),
          ),
        ),
      ),
    );


text:
Q: How do make columns in a grid "space-evenly" like with flexbox? I have this grid CSS
.grid {
    display: grid;
    grid-column-gap: 50px;
    grid-template-columns: repeat(3, 1fr);
}

which is sitting in a div with width: 500px
but I noticed that the first item in the grid "hugs" the left edge of the div but the far most right item doesn't touch the edge of the div.
In flexbox I could achieve this with (near enough):
.flex {
    display: flex;
    justify-content: space-between;
 }

how do I do this responsively with the grid?
I know I can change the grid-column-gap but that seems flakey

A: Use auto instead of 1fr and the same justify-content will work like with flexbox:

.grid {
  display: grid;
  grid-column-gap: 50px;
  grid-template-columns: repeat(3, auto);
  justify-content:space-between;
}

aaa

bbb

ccc

A: Consider using auto-fit keyword to fit columns into the available row space by expanding them.

.grid-container {
  display: grid;
  grid-column-gap: 10px;
  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
}

.grid-item {
  background-color: blue;
  padding: 30px;
}


text:
Q: lucene.net vs SQL Server In-Memory Tables I have one table while has 10 million records; it has some relational data in another tables as well. I would like to perform more search and few write operations on these tables very frequently.
I am evaluating SQL Server 2014 In-Memory Tables, Full Text Search & Lucene.NET. Apart from this in my web application, I will use odata service to pull the data.
Can you recommend best option for this.
thank you
-nm

A: Regarding performance, every suggestion is unsafe. I would go with Lucene, or Solr which are very easy to setup and manage. Moreover, they are totally fast search oriented. I am sure that SQL Server Full Text Search could be very effective, but I would invest my time on a Lucene based solution.
Hope I helped!


text:
Q: Google Charts custom data-point markers (images) I was wondering if there is a way of defining custom images as data-point.
For a LineGraph there is a pointSize property which sets the size of data points. (Not surprisingly).
This property can also be overridden with the series property in which you can also define a custom color.
Nonetheless, I can't see anything that would allow custom markers.
To make my question absolutely clear:
This is what I am going for: Image with an example
Two ideal solutions

*

*Setting a property to a datapoint with class name and defining a picture for this class name in css. (to me it seems impossible since these are SVG graphics)

*Adding an extra column with data-marker image source.

Although these seem perfect in theory I have no idea how to go about implementing them.
A less perfect solution could be extracting point position from SVG and using JavaScript to dynamically position divs with images (this seems very unelegant and prone to bugs)
Alternatively please recommend a js charting library that would be free and had support for such functionality.
Edit:
In the meantime I found a very good and quite inexpensive (60$ per website license) library that covers this functionality : Highcharts library But the original question is still open.


text:
Q: Creating web app using GeoServer and linking ArcGIS Desktop to it? I have a database (SQL Server) with a table having lat-long information for sites that keep getting updated daily. I want to create a web application to plot the same on map and add other features to it like buffer creation, shortest distance, heatmap etc.
We have the Standard (editor) license level of ArcGIS Desktop and we have made a geodatabase connection in the same.
How can we proceed to create a web map for the above requirement?
We don't have an ArcGIS Server license.
Is there a way we can publish a service on GeoServer from ArcGIS desktop and then use the same in ArcGIS API for JavaScript considering our data will keep changing on a daily basis?

A: You've correctly identified that the missing piece is a server to publish the geodatabase onto the web, from where you can consume it in a JavaScript API.
Here are some potential options:

*

*ArcGIS Server - this is definitely one option, however it may be overkill at this stage.

*ArcGIS Online - Your ArcGIS Desktop Editor license should include an ArcGIS Online license. This is Esri's hosted version of ArcGIS Server, where instead of purchasing the software you pay with credits for various operations. A certain number of credits is included with your Editor license. ArcGIS Online can be used to serve the geodatabase onto the web, allowing you to consume it in a JavaScript API map.

*Portal For ArcGIS - for handling confidential data and keeping it on-premises, you could look at Portal For ArcGIS which is an in-house version of ArcGIS Online.

*GeoServer would be another good option using the methods described by @nmtoken.

A: You can use GeoServer to consume your SQL Server database as a datastore. Then configure GeoServer to provide a WMS &/or WFS, which you can then consume in ArcGIS desktop (or other GIS desktop client, or any web GIS).
For desktop applications there would be no need to any coding.

Is there a way we can publish a service on GeoServer from ArcGIS desktop

No, you would make a direct connection to the SQL Server database using the ArcSDE plugin


text: Q: Camera doesn't work on phone gap build I am new to phone gap and I have built an app that works just fine on phone gap developer. But once I upload the app to phone gap build the camera stops working. I am using Android phone for testing.


text:
Q: How to convert number into character array in java without using any java inbuilt function I am preparing for an interview and I am not able to solve one of the problem.
Below is the problem:

Take number and print it as character one by one without using any inbuilt java conversion function.
  Below is the example lets say you have one numnber 1234 and now write function to take this number as integer and print character array {1,2,3,4}.

It asked to write this function without using any inbuilt java conversion
Please let me if any one knows how to solve it.

A: Hint :

Modulo by 10 gives last digit
Division by 10 of an integer removes its last digit.

A: Iterate through the number digit by digit and use switch-case clauses to decide which character you have to map it to.

A: This is the general idea of the algorithm, modify it to create a char array instead of printing the results:
void printNumber(int n) {
    if (n < 10)
        System.out.println(n);
    else {
        printNumber(n / 10);
        System.out.println(n % 10);
    }
}

I wrote it using a recursive algorithm, because I fancy recursion ... but it's trivial to convert this to an iterative solution.

A: public static void main(String[] args) {
    final int number = 500;
    final int base = 10; // the number system, in your case: decimal
    int tmp = number; // create a temporary variable for processing
    StringBuilder sb = new StringBuilder(); // create a buffer for your textual representation (or calc the length beforehand)
    //
    do {
        int digit = tmp % base; // get the last digit
        sb.append(digit); // attach it to your character buffer
        tmp /= base; // remove the numbers last digit
    } while (tmp != 0); // stop when there is no more character but when the number is 0, you have to execute it once
    sb.reverse(); // now flip the characters because it was written to from behind
    //
    String numText = sb.toString();
    System.out.println(numText);
    //
    char[] chars = numText.toCharArray();
    sb = new StringBuilder("{");
    for (int i = 0; i < chars.length; i++) {
        char c = chars[i];
        sb.append(c);
        if (i != chars.length - 1) {
            sb.append(", ");
        }
    }
    sb.append("}");
    //
    System.out.println(sb.toString());
}

A: If we follow the restrictions completely, this is a rather nice exercise.
Here is my solution:
static char[] getCharArrayFromInt(int value) {
    if (value == 0)
        return new char[]{'0'};
    if (value == Integer.MIN_VALUE)
        return new char[]{'-', '2', '1', '4', '7', '4', '8', '3', '6', '4', '8'};
    int signValue = 0;
    if (value < 0) {
        signValue = 1;
        value *= -1;
    }
    char[] result = new char[signValue + (int) (Math.log10(value) + 1)];
    // to be correct, we need a switch/function here. but for the length, lets reduce it
    if (signValue == 1)
        result[0] = '-';
    for (int i = result.length - 1; i >= 0 + signValue; --i) {
        result[i] = (char) ((value % 10) + '0');
        // to be correct, we need a switch here. but for the length, lets reduce it
        value /= 10;
    }
    return result;
}

It violates the "without using any inbuilt java conversion function" two times, marked in the source. This was only to shorten the program. It is very clear and easy to write a function with a switch for this parts.
The functions should be valid for the complete Integer range.
But honestly, I do not think one could make this solution in 10 min in a job interview. You should start discussing about writing clean code pays off the most and why is it better to avoid such things as shown above.
--tb


text:
Q: I want datareader to read data from a column in database which is varchar and the read result to be stored in string variable I want datareader to read data from a column in database which is varchar and the read result to be stored in string variable but it generates an indexoutofrange exception...Basically I want a validation so that if the user enters a booking time which is already in the database then program should generate an error message. Also an error should be generated if entered value is inside the booked time duration. Like if a booking is there on 12/12/2011 at 4:00 pm and the duration is 2 hours then the program should not allow any booking till 6:00 pm unless a booking is for some other game or for some other courtno (in case of badminton, squash, lawn tennis etc)
I'm trying the following code for this:
Dim str2 As String  ' defines string variable for taking select query
    str2 = "select booking_date, booking_time, booking_duration, poolno, courtno, tableno from Bookings"

    Dim a, b As Date
    Dim c As Date
    Dim d, f, g, l As String

    Dim dur As Integer

    Dim cmd2 As New SqlCommand(str2, con)
    con.Open()

    Dim bookchk As SqlDataReader = cmd2.ExecuteReader
    While bookchk.Read()
        a = bookchk("booking_date")
        b = bookchk("booking_time")
        c = b.ToLongTimeString
        dur = bookchk("booking_duration")

        l = bookchk("game") 'exception is generated here

        If CmboGame.SelectedItem = "Swimming" Then
            If bookchk("poolno") IsNot System.DBNull.Value Then
                d = bookchk("poolno")

            End If

        Else : d = ""

        End If

        If CmboGame.SelectedItem = "Table Tennis" Then
            If bookchk("tableno") IsNot System.DBNull.Value Then
                f = bookchk("tableno")

            End If
        Else : f = ""
        End If
        If CmboGame.SelectedItem IsNot "Table Tennis" And CmboGame.SelectedItem IsNot "Swimming" Then
            If bookchk("courtno") IsNot System.DBNull.Value Then
                g = bookchk("courtno")

            End If
        Else : g = ""
        End If
        If TxtBookDate.Text = a And TxtBookTime.Text = c And TxtPoolNo.Text = d And TxtCrtNo.Text = g And TxtTblNo.Text = f And CmboGame.SelectedItem = l Then
            MessageBox.Show("The date and time you have entered has already been booked" & vbCrLf & "Try Again!", "Bookings Overlapped", MessageBoxButtons.OK, MessageBoxIcon.Stop)
            Exit Sub

        End If

        Dim time, h, i, j, n As DateTime
        n = c.AddHours(dur)
        time = TxtBookTime.Text
        h = time.AddHours(TxtBookDur.Text)
        i = time.ToLongTimeString
        j = h.ToLongTimeString

        If TxtBookDate.Text = a And TxtPoolNo.Text = d And TxtCrtNo.Text = g And TxtTblNo.Text = f And CmboGame.SelectedIndex = l And i > c And i <= n Or j > n Then
            MessageBox.Show("The date and time you have entered has already been booked" & vbCrLf & "Try Again!", "Bookings Overlapped", MessageBoxButtons.OK, MessageBoxIcon.Stop)

            Exit Sub

        End If

    End While
    bookchk.Close()
    con.Close()

A: Your SQL statement:
str2 = "select booking_date, booking_time, booking_duration, poolno, courtno, tableno from Bookings"

You're not selecting a column called "game", so obviously you can't reference this in your datareader. Add the "game" column to the SQL statement, assuming it exists, this problem will disappear. You might have other problems of course.


text:
Q: Python 3.x turtles extremely slow? I've found that python's turtle implementation is amazingly slow. I expected some delay, but not minutes of waiting for a relatively simple fractal (Koch curve with 5 iterations).
Even after setting turtle.speed(0) it is still very slow. Maybe there's a bug since it's not instantaneous like claimed in the docs?
This answer suggested re-implementing turtles by hiding a window. A similar question got no answer. Am I missing something, or is re-implementing the way to go?
Here is my stripped down code (the creation of the l-system is almost instantaneous):
import turtle

def l_system(V, w, P, n):
    current = w

    for i in range(n):
        current = [P[x] if x in P else x for x in list(current)]
        current = ''.join(current)

    return current

def run_turtle(var, start, rules, iters, angle, size, scale):
    terry = turtle.Turtle()
    terry.pensize(1)
    terry.pencolor("blue")
    terry.speed(0)

    dist = size / ((iters + 1) ** scale)
    positions = []
    angles = []

    instructions = l_system(var, start, rules, iters)

    for instr in instructions:
        if instr in ('F', 'G'):
            terry.forward(dist)

        elif instr in ('M', 'N'):
            terry.penup()
            terry.forward(dist)
            terry.pendown()

        elif instr == '[':
            positions.append(terry.pos())
            angles.append(terry.heading())

        elif instr == ']':
            terry.goto(positions.pop())
            terry.setheading(angles.pop())

        elif instr == '+':
            terry.left(angle)

        elif instr == '-':
            terry.right(angle)

    turtle.mainloop()

def right_koch():
    run_turtle(('F',), 'F', {'F':'F+F-F-F+F'}, 5, 90, 500, 3)

right_koch()

A: Here's a quick copy-paste for anyone looking. Credits to @user2357112
Use these methods to greatly speed things up and get right to the end result:
.speed(0)
.delay(0)
.ht()
.tracer(0, 0)

# Code goes here

.update()

A: Turn off the drawing delay:
turtle.delay(0)

and hide the turtle:
terry.ht()

Turning off the drawing delay is the big one. If you don't do that, there's a 10-millisecond pause whenever the turtle moves.

If you want it to go even faster, and you only care about the finished picture, you can turn off screen updates entirely:
turtle.tracer(0, 0)

and call update a single time when your turtle has executed all its commands:
terry.update()

With tracing off and a manual update call, the program finishes near-instantaneously on my machine.

A: This is even faster for copy-pasting:
from turtle import Turtle, speed, delay, tracer, update, done
def initialize():
 speed(0)
 delay(0)
 tracer(0,0)
 turt = Turtle()
 turt.ht()
 return turt
def finish():
 update()
 done()

Everything comes from @user2357112.


text:
Q: Adding a range as list to a dataframe and calculating a second list with a formulat to this list in a dataframe I have been struggling with this for some time now and hope someone will take the time to help me so I can learn something.
I have a data frame and I want to add a range list ("num") to the frame, depending on the int of the column "num".
In the second step, I want to apply a function to the range list here "x" to create "y". So each value in the list "x" will have a corresponding value in the list "y".
The individual steps are not a challenge. But putting the lists in a Frame are. Is this even possible?
Example dataframe:
``` # Example Dataframe
    df = pd.DataFrame(
    {"Foo": ["ba1", "ba2", "ba3"],
    "Foo2": ["ba4", "ba5", "ba6"],
    "num":[1,2,3]}
    )
```

First step: add a range("num"):
For this step the moste promissing try was
``` # best try
df.groupby("foo")["num"].apply(lambda i: [range(0,i) for i in df["num"]])
```

But adding this wont give a list for each line of "num", just for the first one.
``` # First step Dataframe
df = pd.DataFrame(
    {"Foo": ["ba1", "ba2", "ba3"],
     "Foo2": ["ba4", "ba5", "ba6"],
     "num":[[1,2,3]],
      "x":[[1],[1,2],[1,2,3]]}
)
```

The second step is to apply a function to each number in the created range list:
Generating a list of values is easily done with a for loop, but adding the results to a value list "y" faield.
``` # second step Dataframe
df = pd.DataFrame(
{"Foo": ["ba1", "ba2", "ba3"],
"Foo2": ["ba4", "ba5", "ba6"],
"num":[[1,2,3]],
"x":[[1],[1,2],[1,2,3]],
"y":[[2],[2,3],[2,3,4]]}
 )
```

The simplified function here is "x+1"
Thank you for your interest and help. All the best
Martin

A: df = pd.DataFrame(
    {"Foo": ["ba1", "ba2", "ba3"],
     "Foo2": ["ba4", "ba5", "ba6"]})

df['num'] = df.index + 1
df['x'] = df['num'].apply(lambda x: list(range(1, x + 1)))
df['y'] = df['x'].apply(lambda x: [i + 1 for i in x])

gives
   Foo Foo2  num          x          y
0  ba1  ba4    1        [1]        [2]
1  ba2  ba5    2     [1, 2]     [2, 3]
2  ba3  ba6    3  [1, 2, 3]  [2, 3, 4]


text:
Q: Another DialogFragment title color issue I've read some question related to this topic and tried some code examples. My min API level is 11. Some approaches was to get their id based on the layout source code:
dialog layout
I tried to obtain the TextView using simple this code in my DialogFragment:
    int titleTextId = getResources().getIdentifier("android:id/alertTitle", null, null);
    TextView titleText = (TextView)getDialog().findViewById(titleTextId);
    titleText.setTextColor(ContextCompat.getColor(getActivity(), R.color.darkerOrange));
    if(titleText != null){
        Log.d("DEBUG", "FOUNDED");
    }

This is my styles.xml file:
<resources>
<style name="AppTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
    <item name="actionBarStyle">@style/MyActionBar</item>
    <item name="android:alertDialogTheme">@style/DialogTitleText</item>
</style>

<style name="MyActionBar" parent="@style/Widget.AppCompat.ActionBar.Solid">
    <item name="titleTextStyle">@style/TitleBarTextColor</item>
    <item name="background">@color/white</item>
</style>

<style name="TitleBarTextColor" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
    <item name="android:textColor">@color/darkerOrange</item>
</style>

<style name="DialogTitleText" parent="@style/Theme.AppCompat.Light.Dialog">
    <item name="android:windowTitleStyle">@style/DialogTitleStyle</item>
</style>

<style name="DialogTitleStyle" parent="@style/DialogTitleText">
    <item name="android:textColorPrimary">@color/darkOrange</item>
</style>

<style name="SplashScreen" parent="Theme.AppCompat.NoActionBar">
    <item name="android:windowBackground">@drawable/splash_screen</item>
</style>

<style name="TabLayoutTextSize" parent="TextAppearance.Design.Tab">
    <item name="android:textSize">20dp</item>
</style>

My AndroidManifest.xml
<application
    ...
    android:theme="@style/AppTheme">
    ...

These are visited links:
How to style AlertDialogs like a pro
Android - DialogFragment change title text color
Styling custom dialog fragment not working
Android change toolbar title color to white
Even with these approaches I haven't successfully changed title color. And I want 'to preserve min API to 11. Is this related to this min API?

A: Following advice from @Gudin I searched and found the title layout source:
DialogFragment title layout
I appliced the source code to find the view and it works.
Change this line: getResources().getIdentifier("android:id/alertTitle", null, null);
To this: getResources().getIdentifier("title", "id", "android");


text:
Q: "Robot detection failed". Why? I got a "Robot detection failed" error message. What can be the cause?

I did click in the checkbox where I am supposed to click to prove that I am human. I was using the same computer, IP, and browser as usual.


text:
Q: Авторизация на сайте через requests Python3 Прошу помощи в написании куска кода с авторизацией на сайте https://binomo.com средствами requests python3. Знаю что надо найти post запрос отправляемый браузером при авторизации, но вот его то я и не могу найти. Смотрю через средства разработчика в Firefox и Opera. Пока имею следующее:
import requests

data = {'email':'11111@yandex.ru', 'password':'111111'}
login = "1111111@yandex.ru"#логин
pass_ = "1111111"#пароль
Url = "https://binomo.com/ru/account"#ссылка на сайт
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:45.0) Gecko/20100101 Firefox/45.0'}#эмитация живого пользователя
r = requests.get(Url,  headers = headers, data = data)#отправка запроса на сайт
print(r.status_code)

session = requests.Session()
respons = session.get(Url, data=data, headers=headers)
print(respons.status_code)

res = requests.post("https://binomo.com/api/profile?device=web&locale=ru", headers = headers, data = data)
print(res.text)
print(res)

это мой первый опыт в этом направлении, прошу не пинать!))


text:
Q: Using CUDA 11.x but getting error: Unknown CUDA arch (8.6) or GPU not supported I'm setting up a conda environment to use pytorch 1.4.0 (on Ubuntu 20.04.2), but getting the error message:

ValueError: Unknown CUDA arch (8.6) or GPU not supported

I know this has been asked before, but no answer fits my case. This answer suggests that the CUDA version is too old. However, I updated my CUDA version to the most recent, and get the same error message.
nvcc -V says I have CUDA 11 installed, and when I run nvidia-smi I get this info:
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 460.84       Driver Version: 460.84       CUDA Version: 11.2     |
|-------------------------------+----------------------+----------------------+

which, according to the NVIDIA docs, should work be compatible:

Another auxilliary question: What does the "8.6" in CUDA arch (8.6) represent?

A: Specific versions of PyTorch work only with specific versions of CUDA.
If you are using CUDA-11.1, you'll need a fairly recent version of PyTorch. You need to either upgrade your PyTorch, or downgrade your CUDA.

A: It seems you can grab PyTorch v1.4 for CUDA 10.0 from here:
pip install torch==1.4.0+cu100 -f https://download.pytorch.org/whl/torch_stable.html


text:
Q: android use the camera app and private storage I am trying to use the sample code at
https://developer.android.com/training/camera/photobasics.html
to take pictures that WILL NOT show up in gallery or get shared. Google's example missed this part of the demo.
I followed the example: My code is at:
https://github.com/tomha2014/SecureCameraIntent/tree/master
Failed to ensure directory: /storage/sdcard1/Android/data/thackbarth.com.securecameraintent/files/Pictures
I have all the read/write external permissions in the manifest.

A: Make sure folders in this path exist.
thackbarth.com.securecameraintent/files/Pictures

A: YEA! I found it
In the google sample code found at
https://developer.android.com/training/camera/photobasics.html
There is a line of of code that looks like:
    mCurrentPhotoPath = "file:" + image.getAbsolutePath();
That create a file uri, the bitmap decode:
    Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
Wants a path to the file Take off the "file:" and it it works.....
That was a lot of hours wasted, if Google would have just provided that code in the sample linked to that page.
In any case, I am working on a sample that uses that code for Android 6
can be found at:
https://github.com/tomha2014/SecureCameraIntent


text:
Q: How to determine what in my script is blocking my HTML rendering? I have a web application that uses quite a bit of JavaScript.
When the page loads, it's very clear visually that something is blocking the rendering of a particular portion of the web site. This portion is generated by a Tabber Tabify JavaScript library.
How can I determine what's blocking the HTML rendering specifically so that I can modify my code to prevent this blocking?
Can I use Firebug, or some other tool, to walk through my HTML/JavaScript to determine where the HTML rendering is being blocked and if so, how?
UPDATE:
YSlow gives my web-application a score of "A" and Page Speed give a score of 94/100.
UPDATE 2:
The live site is linked below.
http://www.elite.com
What I'm specifically referring too is the actual Tabs themselves being rendering (and NOT the panel content inside the tab panes). It seems strange to me that the Tab headings themselves are taking so long to generate on the first (empty cache) page load.

A: A few possibilities:

*

*Loading scripts in your page will block rendering (the only fix for this is to put them in the head (blocks initial rendering) or at the end just before the </body> or load them after the page is loaded (e.g. onload)

*Whatever the Tabber/Tabify tool is, needs time to process content... see if there is a way to optimize it.
Either way, if you post some code we can likely be of more help
Update:
If I load the page with my cache cleared, I see content rendering on the screen, then hiding (as it becomes hidden tab content)
Changing the non-visible content to display:none; when loading, and then only setting it back to display:block; once the Tabify stuff is done might help (a) speed up the rendering and (b) remove any flash of content that later gets hidden.
The RadComboBox'es you have load inline (which means the scripts block rendering)... if you can delay this until the onload event fires it will speed up rendering.
I would move the Unica Page Tag (tracking) to the end of your page too.
You have 8 external script files - if there is any way you can combine them it would be good.
You don't have gzip turned on for most of those script files
All of your static content (images, css, scripts) don't have an expires header which means they won't get cached, which means pages won't load fast after the first page.


text:
Q: How to remove the 3d effect in the font I don't know why I am getting this 3d effect in words. How can I remove the effect and flatten the words?
The font family is Poppins
   body {font-family: "Poppins";}

A: You can do any formatting with CSS.
a {font-style: normal;}

will make font style as normal

A: There may be a CSS conflict. Try this. Change class & the colors as suitable.
add
text-shadow: none;

.text-class
{
    text-shadow: none;
    background: #333;
    color: #fff;
}