text:
Q: How to print custom message in try catch - php laravel I need to write to log some data when exception occurred, since it is dynamic data and I need the message I tried with simple code, just to write 'Boom' if exception occurred.
However just the automatic exception data written in logs (as before the try catch).
can someone advise how to print to log in the catch?
I just need to add additional text to the exception, just to be more specific
try {
    $sheet->setCellValue($cell,$innervalue);
} catch(Exception $e) {
    $message = 'Can not set value: '.$innervalue .' in cell ' .$cell .$headerArray[$headerIndex];
    \Log::info('boom');
}

and in the logs nothing displayed

A: php artisan make:Exception SomeAweSomeException

This way you have your own controle of how the exception should look and handle. Also you can use standards wich makes you code look cleaner.
class SomeCustomException extends Exception
{
    // ...

    /**
     * Get the exception's context information.
     *
     * @return array
     */
    public function context()
    {
        return ['order_id' => $this->orderId];
    }
}

use Exception;

class SetDeliverDateToFarAwayException extends Exception
{
    public function __construct()
    {
        parent::__construct(
            'Selecting more than three days into the future is not allowed'
        );
    }
}

and now my method wich creates the error message.
    /**
     * Finalizes the scheduler
     *
     * @return string
     * @throws SetDeliverDateToFarAwayException|Throwable
     */
    public function set(): string
    {
        $today = Carbon::now();
        $deliver = new Carbon();
        $deliver->year($this->year ?? $today->year);
        $deliver->month($this->month ?? $today->month);
        $deliver->day($this->day ?? $today->day);
        $deliver->hour($this->hour ?? $today->hour);
        $deliver->minute($this->minute ?? $today->minute);

        #Mail gun can max schedule mail for 3 days in the future. So we throw an Exception if the date is to big.
        throw_if($deliver->diffInHours($today) > 72, new SetDeliverDateToFarAwayException());
        return Mail::schedule($deliver->toDateTimeString());
    }

A: this what worked for me
try {
                              $sheet->setCellValueExplicit('WELL DONE');
                              }
                              catch (\Exception $e) {
                                $errorMsg = 'the value of:\' '  .$innervalue . '\' in cell ' .  $cell .  ' in header: ' . $headerArray[$headerIndex] . 'problematic'  ;
                                \Log::error($errorMsg);
                                \Log::error($e->getMessage());
                                \Log::error($e->getTraceAsString());
                                throw new Exception($e->getMessage());

                              }

A: To get the exception log message use it like this -
    try {

    } catch(Exception $e) {
        Log::info(json_encode($e->getMessage()));
    }


text:
Q: Replace contents of a column in powerQuery based on another column Mcode= Table.ReplaceValue(#"Renamed Columns2", each if Text.Contains([Rate_Card.Payee],"Financial Services") and [Externalidinvestorlevel] = null then null else [Rate_Card.Payee]

Error Message:
Expression.SyntaxError: Token RightParen expected.

A: I think maybe you want to do this
  Mcode= Table.ReplaceValue(#"Renamed Columns2",
  each [Rate_Card.Payee],
  each if Text.Contains([Rate_Card.Payee],"Financial Services")
  and [Externalidinvestorlevel] = null
  then null else [Rate_Card.Payee]
  ,Replacer.ReplaceValue,{"Rate_Card.Payee"})
  in #"Replaced Value"

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to insert/update data in custom table using Magento 2 using Ajax but 404 error occur on ajax hit? I have created a custom module for admin area in which i have show some data in phtml file.
I have created a custom table in database using installschema.php.
Now i want to save that data in database but on hitting the update button ajax url is hit but the response it gives me 404.
My file path are
My URL is http://127.0.0.1/magento/AdminSample/datasave/index/?isAjax=true
My controller file path is ( app/code/Tym17/AdminSample/Controller/Adminhtml/Datasave/Index.php )
<?php
namespace Tym17\AdminSample\Controller\Adminhtml\Datasave;

use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Config\ScopeConfigInterface; // Needed to retrieve config values

class Index extends \Magento\Backend\App\Action
{
/**
 * @var PageFactory
 */
 protected $resultPageFactory;
/**
 * @var scopeConfig
 * Needed to retrieve config values
 */
protected $scopeConfig;

/**
 * @param Context $context
 * @param PageFactory $resultPageFactory
 */
public function __construct(
    Context $context,
    PageFactory $resultPageFactory,
    ScopeConfigInterface $scopeConfig // Needed to retrieve config values
) {
    parent::__construct($context);
    $this->resultPageFactory = $resultPageFactory;
    $this->scopeConfig = $scopeConfig; // Needed to retrieve config values
}

/**
* Index Action*
* @return void
*/
public function execute()
{
    /*$post = (array) $this->getRequest()->getPost();
    var_dump($post);*/
    die('a');
}
}

My JS file path is ( app/code/Tym17/AdminSample/view/adminhtml/web/js/adminscript.js )
My routes.xml file path ( app/code/Tym17/AdminSample/etc/adminhtml/routes.xml )
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
<router id="admin">
    <route id="AdminSample" frontName="AdminSample">
        <module name="Tym17_AdminSample" before="Magento_Adminhtml" />
    </route>
</router>
</config>

My JS file is ( app/code/Tym17/AdminSample/view/adminhtml/web/js/adminscript.js )
require(["jquery","mage/url"],function($,url) {
$(document).ready(function() {
    console.log('123');
    url.setBaseUrl(BASE_URL);
    var BaseUrl = url.build('');
    jQuery( ".product" ).on( 'click', '.save',function() {
        console.log('click');
        let customurl = "http://127.0.0.1/magento/AdminSample/Datasave/index/";
        let dataid = jQuery(this).parent().parent().find('.dataid').text();
        $.ajax({
            url: customurl,
            type: 'POST',
            dataType: 'json',
            data: {
                dataid:dataid
            },
            complete: function(response) {
                console.log('aaaaa');
            },
        });
    });
});
});

My controller file path ( app/code/Tym17/AdminSample/Controller/Adminhtml/Post/Index.php )
<?php
namespace Tym17\AdminSample\Controller\Adminhtml\Post;

class Index extends \Magento\Backend\App\Action
{
protected $resultPageFactory = false;

public function __construct(
    \Magento\Backend\App\Action\Context $context,
    \Magento\Framework\View\Result\PageFactory $resultPageFactory
)
{
    parent::__construct($context);
    $this->resultPageFactory = $resultPageFactory;
}

public function execute()
{
    echo'controller check'; die('aaahahahah123');
    $resultPage = $this->resultPageFactory->create();
    $resultPage->getConfig()->getTitle()->prepend((__('Posts')));

    return $resultPage;
}
}

if anything else needed i will add that any help is appreciated.

A: Modify files as per below answer & then use the controller url in ajax url.
Step 1- app/code/Tym17/AdminSample/etc/frontend/routes.xml
    <?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="admin">
<route id="adminsample" frontName="adminsample">
            <module name="Tym17_AdminSample"/>
        </route>
        </router>
    </config>

Step 2: Create controller file
File: app/code/Tym17/AdminSample/Controller/Adminhtml/Post/Index.php
   <?php
    namespace Tym17\AdminSample\Controller\Adminhtml\Post;

    class Index extends \Magento\Backend\App\Action
{
    protected $resultPageFactory = false;

    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
    )
    {
        parent::__construct($context);
        $this->resultPageFactory = $resultPageFactory;
    }

    public function execute()
    {
        echo'controller check'; exit;
        $resultPage = $this->resultPageFactory->create();
        $resultPage->getConfig()->getTitle()->prepend((__('Posts')));

        return $resultPage;
    }
}

Step 3 - Check controller
Browse this link  127.0.0.1/magento/adminsample/post/index


text:
Q: is there memory leak if we don't delete memory and the application has exited I write a piece of test code in VS2005 like this:
#include <stdio.h>

class Base {
public:
    Base() {printf("Base +\n");};
    ~Base() {printf("Base -\n");};
    char val[1024 * 1024 * 100];
};

void main()
{
    Base *p = new Base();
    return;
}

build, open a cmd window, then execute this console application.
open windows task manager to watch memory usage status.
I find two things:
1 the destructor is not called;
2 there is no memory leak from the windows task manager result.
is memory deleted by C++ runtime, or is it deleted by OS when the process exit? I just wonder the details about what happens to 100MB meory allocated in contructor after the main() return. If someone can tell me it is appreciated, and thanks.

A: After your program exits, the operating system will reclaim all used memory, whether or not delete has been called on it.
Other resources, like sockets, might take longer to be released by the operating system, but will eventually be reclaimed.

A: It will be up to the operating system.
However, things that you thought would go away when the app goes away tend to stay in memory longer than you thought. At some point, the code in main is moved to some function that gets called once. And then that function gets called multiple times. And then you have a leak. Better coding defensively in the first place than to fix problems later. Maybe years later.

A: Destructor not get called because you are not deleting your class B pointer.
Also after your application exits all the allocated resources get released irrespective whether you released it or not.

A: As with other answer, it's up to the operating system.
Having said this, it's usually well documented what will be clean up upon program termination.
This usually include application's private memory, files, sockets, resource handles, GUI resources, and may exclude resources that is global or shared amount many applications. (e.g. POSIX shared memory will persist until reboot if you do not call shm_unlink).


text:
Q: Remove received push notifications after 5 seconds automatically for my app In my application, My device is getting received Push notifications. If the user will not open received push notification for 5 secs or 10 secs, need to cancel or remove that particular push notification. How can we imlement this in the iOS application
Please Advice.

A: You cannot programmatically remove the visual display of a push notification. If the user has i. e. set your app to display push notifications on the lock screen they will disappear when the user selects them.
If the text message in your notifications is not important you can for example play a custom sound file that's bundled with your app.


text:
Q: BigQuery Convert Columns to RECORD In BigQuery, How can I turn many columns into a RECORD or Array of Key Value pairs
e.g.
Source Table

id
Name
DOB
Sex

1
Fred
01.01.2001
M

Destination Table

Id
Name
Key
Value

1
Fred
DOB
01.01.2001

Sex
M

I've tried a few things but cant get there, is there a nice way of doing it?

A:
I've tried a few things but cant get there, is there a nice way of doing it?

Not sure what exactly was /could be an issue here as it is as simple/straightforward as below
select id, Name,
  [struct<key string, value string>('DOB', DOB),('Sex', Sex)] info
from `project.dataset.table`

with output

Meantime, usually the issue comes when you don't know those columns names in advance and want to have generic approach - in this case you can use below approach where column names DOB and Sex are not being used
select id, Name,
  array(
    select as struct
      split(replace(kv, '"', ''),':')[offset(0)] key,
      split(replace(kv, '"', ''),':')[offset(1)] value,
    from unnest(split(trim(to_json_string((select as struct * except (id, name) from unnest([t]))), '{}'))) kv
  ) info
from `project.dataset.table` t

with exact same result/output

A: Here you go with a solution:-
WITH `proj.dataset.tbl` AS
(SELECT '1' AS id, 'Fred' AS Name, '2020-12-07' AS DOB, 'M' as Sex
)
SELECT id, Name,
        [struct('DOB' as key, cast (DOB as string) as value ),
        struct('Sex' as key, Sex as value)
       ] as key_values

FROM `proj.dataset.tbl`

Output will be as :-


text:
Q: Can you reset Python's sys.path? I've been doing some work with Python, and I believe my sys.path has "lost" entries. Specifically, I can import no libraries whatsoever (it works if I place them in the folder with the program, but placing it within Python's library directory doesn't work).
Presumably, it has forgotten what folders to look in, and I would like to know how to set sys.path back to it's default values.
Edit: Win7, 32-bit. Yes, I've tried reinstalling (and repairing) Python.

A: sys.path is read from the environment variable PYTHONPATH.  Check to see what the environment variable is, and reset it if needed.
Note that a python script could re-define sys.path.


text:
Q: List / Get post redirects In WordPress, when I change the slug of one of the posts, WordPress generally is able to automatically redirect it.
We're using WordPress as a backend for a SPA, and we aren't able to use these redirects.
Is there a way to get a list of all renamed pages with their correct permalink?
At present, I'm trying to look through the posts table to then compare revision guid attributes, but WordPress obviously is already doing something similar, so I'm hoping there is a function that I can use?
Any general pointers in the right direction would be appreciated, should I be looking for revisions, posts a field in the options table...


text:
Q: Htaccess Redirection- I want to redirect to URL when my query string is equal to -this-is-test1 I want to redirect to URL when my query string is equal to -this-is-test1
Redirect /search/product/basecamp?-this-is-test1 https://www.some-example.com/search/product/result-this-is-test1

Note: There is the only value not any key in the query string.

A: Could you please try following, make sure you clear your browser cache after placing these rules into yout .htaccess file.
RewriteEngine On
RewriteCond %{THE_REQUEST}  \s/(search/product)/basecamp\?(-this-is-test1)\s [NC]
RewriteRule ^(.*)$ /%1/result%2? [NE,L,R=301]

A: You cannot match query string in Redirect or RedirectMatch directives.
You may use this rule based on mod_rewrite module:
RewriteEngine On

RewriteCond %{QUERY_STRING} (-this-is-test1) [NC]
RewriteRule ^(search/product)/basecamp/?$ /$1/result%1? [NE,L,R=301,NC]

? at the end of target will strip any query string.
References:

*

*Apache mod_rewrite Introduction

*.htaccess tips and tricks


text:
Q: Cluster points disappear when creating a webmap I have styled the layer to have cluster points rather than individual points. I need to create a webmap (using qgis2web plugin) of the map. Before I styled the layer to have cluster points all my layers showed up fine when producing a webmap. As soon as I changed the style to have cluster points, the preview of my webmap doesn't display the points. Does anyone know the reason why these are disappearing?

A: Try not clustering the points in QGIS, and instead selecting the Cluster option in the qgis2web dialog. At the moment, qgis2web doesn't detect QGIS3 clustering, but there is an open ticket for the issue (https://github.com/tomchadwin/qgis2web/issues/377).


text:
Q: Pattern matching for capturing exponent degrees does not work? I have a function works like this:
f[{m_, n_}] := Assuming[m > 0 && n > 0, Simplify[{n, Sqrt[n m]}]]
finalT = NestList[f, {T3, (T1 T2)^(1/2)}, 25]

Which will return result like this:
finalT[[All, 2]]

I wonder how to capture those exponent degrees in finalT[[All, 2]], like $(T_1 T_2)^\frac{1}{2} \rightarrow \frac{1}{2}$. I have tried
Exponent[finalT[[All, 2]], (T1 T2)]
Cases[finalT[[All, 2]], (T1 T2)^n]

both of them did not work. The first return a list of $0$s and the second returns an empty list. How can I achieve my goal? I am using Mathematica 11.

A: You have to use finalT[[All, 2]] // FullForm to find the correct pattern:
Cases[
  Simplify[finalT[[All, 2]], Assumptions -> {T1 > 0, T2 > 0, T3 > 0}],
  Power[Times[T1, T2], Rational[x_, y_]] -> {x/y}, {0, Infinity}]

(*
    {{1/2}, {1/4}, {3/8}, {5/16}, {11/32}, {21/64}, {43/128}, {85/256}, {171/512},
    {341/1024}, {683/2048}, {1365/4096}, {2731/8192}, {5461/16384}, {10923/32768},
    {21845/65536}, {43691/131072}, {87381/262144}, {174763/524288}, {349525/1048576},
    {699051/2097152}, {1398101/4194304}, {2796203/8388608}, {5592405/16777216},
    {11184811/33554432}, {22369621/67108864}}
*)

A: f[{m_, n_}] := Assuming[m > 0 && n > 0, Simplify[{n, Sqrt[n m]}]]

finalT = NestList[f, {T3, (T1 T2)^(1/2)}, 25]

Below is a look at the FullForm for a subset of FinalT
Map[{FullForm[#[[1]]], FullForm[#[[2]]]} &, finalT[[1 ;; 11]]] // Grid

There are two groups of exponents, one for the product of T1*T2 and another for T3.
We can extract those two groups as follows:
powerList = Module[
  {
   powers
   },
  powers = Cases[finalT, Rational[x_, y_], Infinity];
  {powers[[1 ;; -2 ;; 2]], powers[[2 ;; -2 ;; 2]]}
  ];

This looks like the following for the same subset
Grid@Transpose@{powerList[[1, 1 ;; 11]], powerList[[2, 1 ;; 11]]}


text:
Q: SQL range conditions less than, greater than and between What I would like to accomplish is; query if  'email ocr in' & 'universal production' rows in the "documents created column" field, total the same amount as "email OCR" 'documents_created. If not, pull that batch. finally if the attachment count is less than 7 entries after the email ocr in & universal production files are pulled then return said result

current query below:
use N
SELECT   id,
         type,
         NAME,
         log_time ,
         start_time ,
         documents_created ,
         pages_created,
         processed,
         processed_time

FROM     N_LF_OCR_LOG

WHERE

    -- Log time is current day
    log_time between  CONVERT(date, getdate()) AND CONVERT(datetime,floor(CONVERT(float,getdate()))) + '23:59:00'

    -- Documents created is NULL or non zero
    AND (documents_created IS NULL OR documents_created <> 0)

  or  ( documents_created is null and log_time between  CONVERT(date, getdate()) AND CONVERT(datetime,floor(CONVERT(float,getdate()))) + '23:59:00')

    -- Filter for specific types
    AND type IN ('Email OCR In',
            'Universal Production')

    -- Filter to rows where number of pages and documents created are not equal
    AND documents_created <2 and pages_created >2

ORDER BY log_time
,id asc
,processed_time asc

any idea how to incorporate that? Im a novice. thanks

A: When creating an index, you just specify the columns to be indexed. There is no difference in creating an index for a range query or an exact match. You can add multiple columns to the same index so all columns can benefit from the index, because only one index per table at the time can be selected to support a query.
You could create an index just covering your where-clause:
alter table N_LF_OCR_LOG add index test1(log_time, documents_created, type, pages_created);

Or also add the required columns for the ordering into the index. The ordering of the columns in the index is important and must be the same as for the ordering in the query:
alter table N_LF_OCR_LOG add index test1(log_time, id, processed_time, documents_created, type, pages_created);

Or add a covering index that also contains the returned columns so you do not have to load any values from your tables and can answer to complete query by just using the index. This gives the best response time for the query. But the index takes up more space on the disk.
alter table N_LF_OCR_LOG add index test1(log_time, id,  processed_time, documents_created, type, pages_created, NAME, start_time, processed);

Use the explain keyword infront of your query to see how good your index performs.


text:
Q: How to I pass an object in the RequestBody while testing the API of a Spring Boot Application I am trying to test the API of a Spring Boot application, without using MockMvc or Mockito. I am having trouble setting up the entity for the http post.  It seems easy when the entity is a mere String, but it harder when the request involves a class.
The Controller has this:
@RequestMapping(value = "/dale/search", method = RequestMethod.POST)
public @ResponseBody ResponseEntity<List<DaleSearchReturn>>
 earchDale(@RequestBody MasterBox tlsSearchObj) {

So I somehow need to place a MasterBox object in the request body.  This is what I've tried in my @TEST code:
MasterBox masterBox = new MasterBox ("1", "2", "3", "4", "5", "6", "7") ;

HttpEntity<MasterBox> entity = new HttpEntity<>(masterBox);

HttpUriRequest request = RequestBuilder.create("POST")
    .setUri("http://localhost:8080/dale_service/dale/search")
    .setEntity(entity).build();

// When
HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);

It gives the following error on the .setEntity line...
java.lang.ClassCastException: org.springframework.http.HttpEntity cannot be cast to org.apache.http.HttpEntity
    at TestAPI.givenBox_then200IsReceived(TestAPI.java:48)

My imports are:
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
//import org.hamcrest.Matchers;
import org.junit.Test;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;

import com.ulalaunch.pcplan.models.MasterBox;


text:
Q: Android - Any way to style a button background but leave the rest as it was? Is there any way in Android to style the background gradient of a button without altering the rest of it?
I wanted to make a button that was just like a regular button but with a different gradient.   I made a 3x3 grid of buttons in a table layout.   The first button was like the XML here, the others had no background attribute.
   <Button android:id="@+id/DemoButton"
    android:layout_width="105sp"
    android:layout_height="105sp"
    android:background="@drawable/button1"
    android:onClick="theButtonHandler"
    android:text="Fee">
  </Button>

My style was like this . . .
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:state_pressed="true" >
   <shape>
      <gradient
         android:startColor="#5555AA"
         android:endColor="#000033"
         android:angle="270" />
   </shape>
 </item>
 <item>
   <shape>
      <gradient
         android:startColor="#BBBBDD"
         android:endColor="#BB9988"
         android:angle="270"/>
      <corners android:bottomRightRadius="3dp" android:bottomLeftRadius="3dp"
          android:topLeftRadius="3dp" android:topRightRadius="3dp"/>
    </shape>
  </item>
</selector>

I had to put the corner radii in because the new button had sharp 90 degree corners.     The result looked like this:

. . . It's bigger than the other buttons and I had to code-in rounded corners,even though the only attribute I was changing was the "android:background". How can I just change the background?     Thanks in advance!!

A: If you look on the drawables the Android uses for Buttons, you'll see that there always is an amount of pixels left transparent near the borders of the image. I assume that the image you're using does not have any transparent borders. To make it look equal to Android drawables you should add those borders. You can browse your android-sdk/platforms/<some-platform>/data/res/<some-drawable-folder> folders to see how the images are designed. Hope this helps.

A: You can easily change it to
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:state_pressed="true" >
   <shape>
      <gradient
         android:startColor="#5555AA"
         android:endColor="#000033"
         android:angle="270" />
       <corners
   android:bottomRightRadius="10dp"
   android:bottomLeftRadius="10dp"
   android:topLeftRadius="10dp"
   android:topRightRadius="10dp"/>
   </shape>
 </item>
 <item>
   <shape>
      <gradient
         android:startColor="#BBBBDD"
         android:endColor="#BB9988"
         android:angle="270"/>
       <corners
   android:bottomRightRadius="10dp"
   android:bottomLeftRadius="10dp"
   android:topLeftRadius="10dp"
   android:topRightRadius="10dp"/>
    </shape>
  </item>
</selector>


text:
Q: Asymptotic time complexity of List.fold and foldBack I am trying to understand the time complexity for these two functions. I have tried experimenting with both and here is what I have come up with
List.foldBack (@) [[1];[2];[3];[4]] [] => [1] @ List.foldBack (@) [[2];[3];[4]] []
=> [1] @ ([2] @ List.foldBack (@) [[3];[4]] [])
=> [1] @ ([2] @ ([3] @ List.foldBack (@) [4] []))
=> [1] @ ([2]@([3] @ ([4] @ List.foldBack[])))
=> [1]@([2]@([3]@([4]@([])))
=> [1; 2; 3; 4]

List.fold (@) [] [[1];[2];[3];[4]]
=> List.fold (@) (([],[1])@ [2]) [[3];[4]]
=> List.fold (@)  ((([]@[1])@[2])@[3]) [[4]]
=> List.fold (@)  (((([]@[1])@[2])@[3])@[4]) []
=> (((([]@[1])@[2])@[3])@[4])

Now it seems to me that they are both linear since it takes the same amount of calculations to achieve the same result. Am i correct or is there something that I am missing?

A: If each inner operation is Θ(1), List.fold and List.foldBack is O(n) where n is the length of the list.
However, to estimate asymptotic time complexity, you need to rely on Θ(1) operations. In your example, things are a little more subtle.
Suppose you need to concatenate n lists where each list has m elements. Since @ is O(n) of the length of the left operand, we have complexity of foldBack:
  m + ... + m // n occurences of m
= O(m*n)

and that of fold:
  0 + m + 2*m + ... + (n-1)*m // each time length of left operand increases by m
= m*n*(n-1)/2
= O(m*n^2)

Therefore, with your naive way of using @, foldBack is linear while foldis quadratic to the size of input lists.
It is worth to note that @ is associative (a @ (b @ c) = (a @ b) @ c); therefore, results are the same for fold and foldBack in this case.
In practice, if the inner operator is non-associative, we need to choose the right order by either using fold or foldBack. And List.foldBack in F# is made tail-recursive by transforming lists to arrays; there are some overheads by this operation as well.

A: The List.fold and List.foldBack functions are both T(n) calls to their function argument where n is the length of the list. However, you are passing them the (@) function which is not T(1) but T(m) where m is the length of the first argument list.
In particular, this:
(((([]@[1])@[2])@[3])@[4])

is T(n²) because [1]@[2] is one operation and then [1;2]@[3] is two more operations and then [1;2;3]@[4] is three more operations.

A: In a naive implementation FoldBack is O(n^2) as you need to keep traversing the list.  In F# the compiler actually creates a temporary array and reverses it and then calls Fold, so the time complexity (in terms of O) is O(n) for both, although Fold will be slightly faster by a constant amount


text:
Q: jQuery .before with same id i just want to ask about jQuery. Can jQuery do this:

Hello World!

to this:

Hello World!

A: You mean like this man: working demo Bit dynamic version: http://jsfiddle.net/QSdqM/ or http://jsfiddle.net/GQzFU/
Hope it helps the cause :)
API: http://api.jquery.com/replaceWith/
code
$('h1').replaceWith(function() {

   return '

' + $(this).text() + '
'

});

OR
$('h1').replaceWith('

Hello World!
');

alert($('body').html());

A: var myDiv = $('

').attr('id', 'lorem-ipsum');
$('h1#lorem-ipsum').removeAttr('id').before(myDiv);

A: Try the following:
var txt = $('#lorem-ipsum').text()
$('#lorem-ipsum')
    .after($('
').text(txt))
    .replaceWith('
')

DEMO


text:
Q: maximum line length for regexp.FindAll*? Is there a maximum length defined for text lines fed to the regexp.FindAll*Index() functions in the regexp package? Running the code below only provides the indices of the last 10 occurrences.
Go playground: https://play.golang.org/p/QgOw7TzuV4
package main

import (
    "fmt"
    "regexp"
)

func main() {
    line := `VAL_ Status 31 "31-Not Available" 30 "30-Not Defined" 29 "29-Not Defined" 28 "28-Received Temperature Msg" 27 "27 Temp Main (Sub-system)" 26 "26-Throttle Out of Correlation" 25 "25-Received Throttle Pos Msg" 24 "24-Received Throttle Position" 23 "23-Pedal Throttle Position" 22 "22-Throtttle Main (Sub-System)" 21 "21-Oil Makeup Pump Pressure" 20 "20-Engine/B-Average Speeds" 19 "19-A/D Power Regulator" 18 "18-Received Oil Temperature" 17 "17-Oil Temperature Main (IA)" 16 "16-B-Average Speed" 15 "15-Zero Stroke Position" 14 "14-Throttle Main (RVDT)" 13 "13-Engine Speed" 12 "12-Shift Mode Sel-Critical" 11 "11-Shift Mode Sel-Non Critical" 10 "10-Output Driver" 9 "9-Watchdog Off" 8 "8-Steer Gain Solenoid" 7 "7-Vehicle Driveability ID5" 6 "6-Vehicle Driveability ID4" 5 "5-Vehicle Driveability ID3" 4 "4-Vehicle Driveability ID2" 3 "3-Vehicle Driveability ID1" 2 "2-System Power" 1 "1-ROM" 0 "0-No Failures Detected" ;`
    re := regexp.MustCompile(" [0-9] ")

    fmt.Println(re.FindAllStringIndex(line, -1))
}

Yields:
[[677 680] [696 699] [722 725] [753 756] [784 787] [815 818] [846 849] [877 880] [896 899] [906 909]]
I've tried several of the FindAll*Index funcs and they're all the same.

A: There is no real limit on the number of matches. The reason your regex is not getting more matches is because it needs to be regexp.MustCompile(" [0-9]+ ") to match numbers with more than one digit, surrounded by spaces. Right now it only matches " 0 " through to " 9 ".


text:
Q: Batch file for counting the files with same initial name and moving them Is it possible to do this?
In a folder i have files with same initial names
Example:
Main folder
   -Quest2323231.txt
     Quest2343434.txt
     Quest2343435.txt
     Fund103.txt
    Fund102.txt

I have a config file (abc.config) in which i have name of file on which i need to count and move them . If the count is more than 2 then i need to move them.
In this case for e g I need to find files which have name as 'Quest'
Appreciate you help on this.

A: @echo off
  setlocal enableextensions
  set "number="
  for /f "tokens=1" %%a in (
    'dir /a-d /-c "c:\mainfolder\quest*" 2^>nul^|findstr /b /c:"  "'
  ) do if not defined number set "number=%%a"
  if not defined number set "number=0"

  echo %number%

A: Untested: This expects text in the first line of abc.config which is the file information such as Quest in the example and if there are more than 2 matching files in the source folder then it will echo a move command to move them to the target folder.
Change *%file%* to %file%* in two places if you want to match only the start of the filename.
Remove the echo to actually perform the move commands.
@echo off
set "source=c:\mainfolder"
set "target=d:\target\folder"
set /p "file=" < "abc.config"

for /f %%a in ('dir /b /a-d "%source%\*%file%*" ^|find /i "%file%" 2^>nul^|find /c /v "" ') do set "number=%%a"
if %number% GTR 2 for /f "delims=" %%a in ('dir /b /a-d "%source%\*%file%*" ^|find /i "%file%" ') do (
   echo move "%source%\%%a" "%target%"
)
pause


text:
Q: htaccess redirect from website.com/?u=1&name=john to website.com/1/john Found this, but i want to have to query strings done.
RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} \s/+profile\.php\?u=([^\s&]+) [NC]
RewriteRule ^ /%1? [R=302,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/?$ profile.php?u=$1 [L,QSA]

A: Add a new redirect and rewrite rule for 2 parameters:
RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} \s/+profile\.php\?u=([^\s&]+)&name=([^\s&]+) [NC]
RewriteRule ^ /%1/%2? [R=302,L]

RewriteCond %{THE_REQUEST} \s/+profile\.php\?u=([^\s&]+)\s [NC]
RewriteRule ^ /%1? [R=302,L]

RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

RewriteRule ^([^/]+)/([^/]+)/?$ profile.php?u=$1&name=$2 [L,QSA]

RewriteRule ^([^/]+)/?$ profile.php?u=$1 [L,QSA]


text:
Q: Post thumbnail size for custom field only I'm using advanced custom fields (the plugin), and I have some image upload fields. The images that I'm uploading via this custom field need to have a specific size, but I don't want to create images with this dimensions on every image that is uploaded elsewhere. I just don't want to have hundreds of images being generated that are never going to be used.
Thanks


text:
Q: $\ell^2$ is not locally compact
$\ell^2$ is not locally compact.

How to prove this, I just know the definition of locally compact. I am finding it hard to find any trick. $\ell^2$ is the sequence of all square summable sequences. Any help would be appreciated.
Thanks in advance.

A: "Locally compact" means every point has an open neighborhood whose closure is compact. What does an open neighborhood of $\mathbf 0 =(0,0,0,\ldots)\in\ell^2$ look like? This is a metric space, so every open neighborhood $G$ of $\mathbf 0$ must include some open ball centered at $\mathbf 0.$ Let $r$ be the radius of such an open ball. Then the points $ x_k = \Big( \quad \ldots0,0,0,\underbrace{\quad\dfrac r 2, \quad}_{\large k\text{th component}} 0,0,0, \ldots \quad \Big)$ for $k=1,2,3,\ldots$ are all within the open neighborhood $G$. If the closure of $G$ is compact, then so is every closed subset of the closure of $G$, including $\{x_1,x_2,x_3,\ldots\}.$
Cover the set $\{x_1,x_2,x_3,\ldots\}$ with open balls of radius $r/2,$ one centered at each of $x_1,x_2,x_3,\ldots.$ There can be no finite subcover, because each of the open balls of radius $r/2$ about the points $x_k$ can cover only one of $x_1,x_2,x_3,\ldots$, since the distance between any two of $x_1,x_2,x_3,\ldots$ is $r/\sqrt2 > r/2.$

A: you need to show that closed balls are not compact. For simplicity you can show Unit closed ball is not compact. Take the sequence $\{e_n\}$ then $ \|e_n  - e_m\|^2 = 2$ for all distinct natural numbers $m$ and $n$. Therefore $\{ e_n \}$ does not contain any convergent subsequence.
Note that your claim is even true for any normed space.


text:
Q: Does copying the main file output by native-image is the correct way to make native image in GraalVM? My goal is to create native-image. I intend to create a native image of a "class Main that has 1 dependency of a class on different file". The idea is:

*

*Main.java import class HelloWorld.

What nd did:

*

*I run this

java Main.java // output: Main.class and HelloWorld.class
native-image Main // output: main and main.build_artifacts.txt
cp main /app // copy main to /app folder
./main

It works, but I am not sure whether this is correct. I use Docker for this.
Dockerfile
FROM ghcr.io/graalvm/native-image:java11-21.2
WORKDIR /app
COPY ./src/main/java/ /app
RUN javac Main.java
RUN native-image Main

FROM ghcr.io/graalvm/jdk:java11-21.2
WORKDIR /app
COPY --from=0 /app/main /app/main
CMD ./main


text:
Q: undefined local variable or method ` ' for main:Object Sometimes, the following causes a strange bug:
> nil || 4
NameError: undefined local variable or method ` 4' for main:Object

> nil || []
NameError: undefined local variable or method ` ' for main:Object

What is the reason?

A: I, for one, got a pretty annoying version of this error from a code file that someone else had written. It kept complaining about an undefined space on a line but there was nothing on it. You could place your cursor on the line and it'd only land on the first place a character could go on. Also, no characters(not even space) highlighted on the line after changing editor preferences. Couldn't grep for it either with option-space on a mac.
Finally resolved by reformatting code from the IDE options. It magically introduced extra new lines in the places ruby was complaining about. Just deleted those and voila, no more errors.

A: You are accidentally typing Alt + Space on your Mac, which produces a non-breaking space. Ruby does not consider this as whitespace, but as part of a variable name. It then complains that the variable does not exist.
Some people like to remap Alt + Space to Space in order to prevent this typo.
I personally like to highlight invisible characters in my text editor, so I notice the typo immediately.

A: I had this error when I copied some unsupported quote characters from somewhere.
# does not work
$: << File.join(File.dirname(__FILE__), '..', 'lib')

# works (note '' vs '')
$: << File.join(File.dirname(__FILE__), '..', 'lib')


text:
Q: Haskell Ambiguous type variable in xmonad configuration I have an old xmonad config done by me copying blocks from other configs. I haven't much knowledge in Haskell so I have done my best till the moment. The thing is older compiler didn't complain about the this line in question but now shows an Ambigous type variable error.
I've checked other thread about similar problems but still cant figure how to solve my issue so if anyone could enlight me with any kind of answer I would be enormously thankfull.
The first Ambiguous type variable is shown after this expression:
xmonad $ defaultConfig
  { terminal            = myTerminal
  , workspaces          = myWorkspaces
  , keys                = myKeys
  , modMask             = mymodMask
  , layoutHook          = myLayoutHook
  , manageHook          = manageSpawn <+> myManageHook
  , logHook             = myLogHook dzenLeftBar
  , normalBorderColor   = colorNormalBorder
  , focusedBorderColor  = colorFocusedBorder
  , borderWidth         = 0
  , startupHook  = myStartupHook }

And the error is:
xmonad.hs:86:5: error:
        * Ambiguous type variable `l10` arising from a use of `xmonad`
          prevents the constraint `(LayoutClass
                                      l10 GHC.Word.Word64)` from being solved.
          Probable fix: use a type annotation to specify what `l10` should be.

The second error is thrown by the following expression:
onWorkspaces ["7:media"] mediaLayout $

And the error code is basically the same.
The full config file is this: https://paste.pound-python.org/show/BXD7gxeTXq14c5hQHwyK/
And the errors showed in the compiler are the following:
xmonad.hs:86:5: error:
    * Ambiguous type variable `l10` arising from a use of `xmonad`
      prevents the constraint `(LayoutClass
                                  l10 GHC.Word.Word64)` from being solved.
      Probable fix: use a type annotation to specify what `l10` should be.
      These potential instances exist:
        instance (LayoutClass l a, LayoutClass r a) =>
                 LayoutClass (Choose l r) a
          -- Defined in `XMonad.Layout`
        instance LayoutClass Full a -- Defined in `XMonad.Layout`
        instance LayoutClass l a => LayoutClass (Mirror l) a
          -- Defined in `XMonad.Layout`
        ...plus four others

        ...plus five instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    * In a stmt of a 'do' block:
        xmonad
        $ defaultConfig
            {terminal = myTerminal, workspaces = myWorkspaces, keys = myKeys,
             modMask = mymodMask, layoutHook = myLayoutHook,
             manageHook = manageSpawn <+> myManageHook,
             logHook = myLogHook dzenLeftBar,
             normalBorderColor = colorNormalBorder,
             focusedBorderColor = colorFocusedBorder, borderWidth = 0,
             startupHook = myStartupHook}
      In the expression:
        do { dzenLeftBar <- spawnPipe myXmonadBar;
             dzenStatusBar <- spawnPipe myStatusBar;
             dzenTrayBar <- spawnPipe myTrayBar;
             dzenMpdBar <- spawnPipe myMpdBar;
             .... }
      In an equation for `main`:
          main
            = do { dzenLeftBar <- spawnPipe myXmonadBar;
                   dzenStatusBar <- spawnPipe myStatusBar;
                   dzenTrayBar <- spawnPipe myTrayBar;
                   .... }

xmonad.hs:180:17: error:
    * Ambiguous type variable `l10` arising from a use of `onWorkspaces`
      prevents the constraint `(LayoutClass
                                  l10 Window)` from being solved.
      Relevant bindings include
        myLayoutHook :: XMonad.Layout.PerWorkspace.PerWorkspace
                          (ModifiedLayout
                             AvoidStruts
                             (Choose
                                (ModifiedLayout Spacing ResizableTall)
                                (Choose
                                   (Mirror (ModifiedLayout Spacing ResizableTall))
                                   (Choose
                                      (ModifiedLayout XMonad.Layout.NoBorders.WithBorder Full)
                                      (ModifiedLayout
                                         (XMonad.Layout.Decoration.Decoration
                                            SimpleDecoration
                                            XMonad.Layout.Decoration.DefaultShrinker)
                                         (ModifiedLayout
                                            XMonad.Actions.MouseResize.MouseResize
                                            (ModifiedLayout
                                               XMonad.Layout.WindowArranger.WindowArranger
                                               SimpleFloat)))))))
                          (XMonad.Layout.PerWorkspace.PerWorkspace
                             (ModifiedLayout
                                AvoidStruts
                                (Choose
                                   (ModifiedLayout
                                      XMonad.Layout.NoBorders.WithBorder
                                      (ModifiedLayout Spacing ResizableTall))
                                   (Choose
                                      (Mirror (ModifiedLayout Spacing ResizableTall))
                                      (Choose
                                         (ModifiedLayout XMonad.Layout.NoBorders.WithBorder Full)
                                         (ModifiedLayout
                                            (XMonad.Layout.Decoration.Decoration
                                               SimpleDecoration
                                               XMonad.Layout.Decoration.DefaultShrinker)
                                            (ModifiedLayout
                                               XMonad.Actions.MouseResize.MouseResize
                                               (ModifiedLayout
                                                  XMonad.Layout.WindowArranger.WindowArranger
                                                  SimpleFloat)))))))
                             (XMonad.Layout.PerWorkspace.PerWorkspace
                                (ModifiedLayout
                                   AvoidStruts
                                   (Choose
                                      (ModifiedLayout XMonad.Layout.NoBorders.WithBorder Full)
                                      (Choose
                                         (ModifiedLayout Spacing ResizableTall)
                                         (Choose
                                            (Mirror (ModifiedLayout Spacing ResizableTall))
                                            (ModifiedLayout
                                               (XMonad.Layout.Decoration.Decoration
                                                  SimpleDecoration
                                                  XMonad.Layout.Decoration.DefaultShrinker)
                                               (ModifiedLayout
                                                  XMonad.Actions.MouseResize.MouseResize
                                                  (ModifiedLayout
                                                     XMonad.Layout.WindowArranger.WindowArranger
                                                     SimpleFloat)))))))
                                (XMonad.Layout.PerWorkspace.PerWorkspace
                                   (ModifiedLayout
                                      AvoidStruts
                                      (Choose
                                         (ModifiedLayout
                                            XMonad.Layout.NoBorders.WithBorder
                                            (ModifiedLayout Spacing ResizableTall))
                                         (Choose
                                            (Mirror (ModifiedLayout Spacing ResizableTall))
                                            (Choose
                                               (ModifiedLayout
                                                  XMonad.Layout.NoBorders.WithBorder Full)
                                               (ModifiedLayout
                                                  (XMonad.Layout.Decoration.Decoration
                                                     SimpleDecoration
                                                     XMonad.Layout.Decoration.DefaultShrinker)
                                                  (ModifiedLayout
                                                     XMonad.Actions.MouseResize.MouseResize
                                                     (ModifiedLayout
                                                        XMonad.Layout.WindowArranger.WindowArranger
                                                        SimpleFloat)))))))
                                   (XMonad.Layout.PerWorkspace.PerWorkspace
                                      (ModifiedLayout
                                         AvoidStruts
                                         (ModifiedLayout
                                            XMonad.Layout.NoBorders.WithBorder
                                            (ModifiedLayout
                                               (XMonad.Layout.Decoration.Decoration
                                                  SimpleDecoration
                                                  XMonad.Layout.Decoration.DefaultShrinker)
                                               (ModifiedLayout
                                                  XMonad.Actions.MouseResize.MouseResize
                                                  (ModifiedLayout
                                                     XMonad.Layout.WindowArranger.WindowArranger
                                                     SimpleFloat)))))
                                      (XMonad.Layout.PerWorkspace.PerWorkspace
                                         l10
                                         (XMonad.Layout.PerWorkspace.PerWorkspace
                                            (ModifiedLayout
                                               AvoidStruts
                                               (ModifiedLayout
                                                  AddRoster
                                                  (ModifiedLayout
                                                     (XMonad.Layout.Decoration.Decoration
                                                        SimpleDecoration
                                                        XMonad.Layout.Decoration.DefaultShrinker)
                                                     (ModifiedLayout
                                                        XMonad.Actions.MouseResize.MouseResize
                                                        (ModifiedLayout
                                                           XMonad.Layout.WindowArranger.WindowArranger
                                                           SimpleFloat)))))
                                            (ModifiedLayout
                                               AvoidStruts
                                               (Choose
                                                  (ModifiedLayout
                                                     XMonad.Layout.NoBorders.WithBorder Full)
                                                  (Choose
                                                     (ModifiedLayout Spacing ResizableTall)
                                                     (Choose
                                                        (Mirror
                                                           (ModifiedLayout Spacing ResizableTall))
                                                        (ModifiedLayout
                                                           (XMonad.Layout.Decoration.Decoration
                                                              SimpleDecoration
                                                              XMonad.Layout.Decoration.DefaultShrinker)
                                                           (ModifiedLayout
                                                              XMonad.Actions.MouseResize.MouseResize
                                                              (ModifiedLayout
                                                                 XMonad.Layout.WindowArranger.WindowArranger
                                                                 SimpleFloat)))))))))))))
                          Window
          (bound at xmonad.hs:174:1)
      Probable fix: use a type annotation to specify what `l10` should be.
      These potential instances exist:
        instance (LayoutClass l a, LayoutClass r a) =>
                 LayoutClass (Choose l r) a
          -- Defined in `XMonad.Layout`
        instance LayoutClass Full a -- Defined in `XMonad.Layout`
        instance LayoutClass l a => LayoutClass (Mirror l) a
          -- Defined in `XMonad.Layout`
        ...plus four others
        ...plus five instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    * In the expression: onWorkspaces ["7:media"] mediaLayout
      In the second argument of `($)`, namely
        `onWorkspaces ["7:media"] mediaLayout
         $ onWorkspaces ["8:com"] chatLayout $ simpLayout`
      In the second argument of `($)`, namely
        `onWorkspaces ["5:virt"] vBoxLayout
         $ onWorkspaces ["7:media"] mediaLayout
           $ onWorkspaces ["8:com"] chatLayout $ simpLayout`

xmonad.hs:202:15: error:
    * Couldn't match expected type `ModifiedLayout
                                      AddRoster
                                      (ModifiedLayout
                                         XMonad.Layout.Reflect.Reflect
                                         (ModifiedLayout
                                            AddRoster
                                            (ModifiedLayout
                                               TrackFloating
                                               (ModifiedLayout
                                                  (XMonad.Layout.Decoration.Decoration
                                                     TabbedDecoration
                                                     XMonad.Layout.Decoration.DefaultShrinker)
                                                  XMonad.Layout.Simplest.Simplest))))
                                      Window
                                    -> t`
                  with actual type `ModifiedLayout
                                      XMonad.Layout.NoBorders.WithBorder Full Window`
    * The first argument of ($) takes one argument,
      but its type `ModifiedLayout
                      XMonad.Layout.NoBorders.WithBorder Full Window`
      has none
      In the expression:
        noBorders Full
        $ withIM 0.11 (Role "gimp-toolbox")
          $ reflectHoriz
            $ withIM 0.15 (Role "gimp-dock") (trackFloating simpleTabbed)
      In an equation for `mediaLayout`:
          mediaLayout
            = noBorders Full
              $ withIM 0.11 (Role "gimp-toolbox")
                $ reflectHoriz
                  $ withIM 0.15 (Role "gimp-dock") (trackFloating simpleTabbed)
    * Relevant bindings include
        mediaLayout :: t (bound at xmonad.hs:202:1)

Please check the file for errors.

A: The problem is the mediaLayout definition, you're applying noBorders Full to something but it is a layout! Did you want it to be something like this below?
mediaLayout = noBorders Full |||
       ( withIM 0.11 (Role "gimp-toolbox") $ reflectHoriz
       $ withIM 0.15 (Role "gimp-dock") (trackFloating simpleTabbed)
       )


text:
Q: MySQLdb execute I have searched high and low on this site and many others and have found similar questions, but none of the answers have worked for me (usually just accounting for the tuple). I'm writing a python script to parse html pages and populate a database. I have almost everything working except the populating part...
Here is the code segment that deals with the mySQL database (note: using MySQLdb module in python)
conn = MySQLdb.connect(user="root", passwd="xxxxx",db="nutrients")
cur = conn.cursor()
test = "Canned Corn"
cur.execute("INSERT INTO food (name) VALUES (%s)", (test,))
conn.commit()

I was first testing it with parsed string but that wasn't working. This gives me 2 errors:

*

*Traceback (most recent call last):
  File "C:\Python32\lib\site-packages\MySQLdb\cursors.py", line 171, in execute
    r = self._query(query)
  File "C:\Python32\lib\site-packages\MySQLdb\cursors.py", line 330, in _query
    rowcount = self._do_query(q)
  File "C:\Python32\lib\site-packages\MySQLdb\cursors.py", line 294, in _do_query
    db.query(q)
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax
; check the manual that corresponds to your MySQL server version for the right s
yntax to use near '%s)' at line 1")

*Traceback (most recent call last):
  File "C:\Python32\lib\site-packages\MySQLdb\cursors.py", line 171, in execute
    r = self._query(query)
  File "C:\Python32\lib\site-packages\MySQLdb\cursors.py", line 330, in _query
    rowcount = self._do_query(q)
  File "C:\Python32\lib\site-packages\MySQLdb\cursors.py", line 294, in _do_query
    db.query(q)
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax
; check the manual that corresponds to your MySQL server version for the right s
yntax to use near '%s)' at line 1")
Why does this query not work!?

Update: After nearly pulling my hair out I decided to revert back to 2.7.3 and guess what... everything works now :D Should have know it was an error of that type... Thanks for the help none the less everyone!

A: I just ran across this too. After a lot of digging around, this was found to work (note the change to values):
conn = MySQLdb.connect(user="root", passwd="xxxxx",db="nutrients")
cur = conn.cursor()
test = "Canned Corn"
cur.execute("INSERT INTO food (name) VALUES ({0})", (test,))
conn.commit()

Background info: In the port of MySQLdb to Python 3 posted on an unofficial Python packages site, the execute function in cursors.py was modified to use format() rather than the % operator. Hence why %s remains in the SQL statement rather than being substituted. It looks like these changes were never upstreamed to the official source.

A: I think you don't need any tricky or advanced SQL; you just need to store and retrieve some stuff.  So, I think an ORM might make life a lot easier for you.
I suggest you try using the Autumn ORM:
http://pypi.python.org/pypi/autumn/0.5.1
That is a small and simple ORM, easy to understand and work with.
Another good and popular ORM for Python is SQLAlchemy:
http://www.sqlalchemy.org/

A: You should write your code like this :
 conn = MySQLdb.connect(user="root", passwd="xxxxx",db="nutrients")
 cur = conn.cursor()
 test = "Canned Corn"
 cur.execute("INSERT INTO food (name) VALUES (%s)" % (test,) )
 conn.commit()

If you are new to python and have some programming experience , then follow Dive Into Python book. Its free.


text:
Q: How to fetch Swagger definition from a password-protected remote server in Maven Rather than copy a Swagger definition from another project, I want to fetch the current version direct from Gitlab. I thought that I might be able to link to the server settings in settings.xml but that doesn't seem to work.
How do I pass the server credentials to Maven in order to access the yaml? Or is this not the right way to do it?
<execution>
    <goals>
        <goal>java</goal>
    </goals>
    <id>generate-swagger-attrstore</id>
    <phase>generate-sources</phase>
    <configuration>
        <server>gitlab</server>
        <mainClass>io.swagger.codegen.SwaggerCodegen</mainClass>
        <includePluginDependencies>true</includePluginDependencies>
        <arguments>
            <argument>generate</argument>
            <argument>-l</argument>
            <argument>java</argument>
            <argument>-c</argument>
            <argument>${swagger.dir}/attrstore-codegen-config.json</argument>
            <argument>-i</argument>
            <argument>${swagger.attrstore}</argument>
            <argument>-o</argument>
            <argument>${basedir}</argument>
            <argument>--library</argument>
            <argument>okhttp-gson</argument>
        </arguments>
    </configuration>
</execution>


text:
Q: I can't install any package I want to use render some of the online templates in in vscode. But i am getting this error:
Rc files read:
  NONE
Latexmk: This is Latexmk, John Collins, 20 November 2021, version: 4.76.
Rule 'xelatex': File changes, etc:
   Changed files, or newly in use since previous run(s):
      '/home/osman/Downloads/LaTeXTemplates_developer-cv_v1.0/main.tex'
------------
Run number 1 of rule 'xelatex'
------------
------------
Running 'xelatex -no-pdf -synctex=1 -interaction=nonstopmode -file-line-error -shell-escape -recorder  "/home/osman/Downloads/LaTeXTemplates_developer-cv_v1.0/main.tex"'
------------
Latexmk: applying rule 'xelatex'...
This is XeTeX, Version 3.141592653-2.6-0.999993 (TeX Live 2021/Arch Linux) (preloaded format=xelatex)
 \write18 enabled.
entering extended mode
(/home/osman/Downloads/LaTeXTemplates_developer-cv_v1.0/main.tex
LaTeX2e <2021-11-15> patch level 1
L3 programming layer <2021-11-22> (./developercv.cls
Document Class: developercv 2019/01/28 Developer CV class v1.0
(/usr/share/texmf-dist/tex/latex/extsizes/extarticle.cls
Document Class: extarticle 1996/10/08 v1.0 Non Standard LaTeX document class
(/usr/share/texmf-dist/tex/latex/extsizes/size9.clo) (/usr/share/texmf-dist/tex/latex/base/exscale.sty)) (/usr/share/texmf-dist/tex/latex/hyperref/hyperref.sty (/usr/share/texmf-dist/tex/generic/ltxcmds/ltxcmds.sty) (/usr/share/texmf-dist/tex/generic/iftex/iftex.sty) (/usr/share/texmf-dist/tex/generic/pdftexcmds/pdftexcmds.sty (/usr/share/texmf-dist/tex/generic/infwarerr/infwarerr.sty)) (/usr/share/texmf-dist/tex/latex/graphics/keyval.sty) (/usr/share/texmf-dist/tex/generic/kvsetkeys/kvsetkeys.sty) (/usr/share/texmf-dist/tex/generic/kvdefinekeys/kvdefinekeys.sty) (/usr/share/texmf-dist/tex/generic/pdfescape/pdfescape.sty) (/usr/share/texmf-dist/tex/latex/hycolor/hycolor.sty) (/usr/share/texmf-dist/tex/latex/letltxmacro/letltxmacro.sty) (/usr/share/texmf-dist/tex/latex/auxhook/auxhook.sty) (/usr/share/texmf-dist/tex/latex/kvoptions/kvoptions.sty) (/usr/share/texmf-dist/tex/latex/hyperref/pd1enc.def) (/usr/share/texmf-dist/tex/latex/hyperref/hyperref-langpatches.def) (/usr/share/texmf-dist/tex/generic/intcalc/intcalc.sty) (/usr/share/texmf-dist/tex/generic/etexcmds/etexcmds.sty) (/usr/share/texmf-dist/tex/latex/hyperref/puenc.def) (/usr/share/texmf-dist/tex/latex/url/url.sty) (/usr/share/texmf-dist/tex/generic/bitset/bitset.sty (/usr/share/texmf-dist/tex/generic/bigintcalc/bigintcalc.sty)) (/usr/share/texmf-dist/tex/latex/base/atbegshi-ltx.sty)) (/usr/share/texmf-dist/tex/latex/hyperref/hxetex.def (/usr/share/texmf-dist/tex/generic/stringenc/stringenc.sty) (/usr/share/texmf-dist/tex/latex/rerunfilecheck/rerunfilecheck.sty (/usr/share/texmf-dist/tex/latex/base/atveryend-ltx.sty) (/usr/share/texmf-dist/tex/generic/uniquecounter/uniquecounter.sty)))

! LaTeX Error: File `moresize.sty' not found.

Type X to quit or <RETURN> to proceed,
or enter new name. (Default extension: sty)

Enter file name:
./developercv.cls:44: Emergency stop.
<read *>

l.44 ^^M

No pages of output.
Transcript written on main.log.
Latexmk: Missing input file 'moresize.sty' (or dependence on it) from following:
  '! LaTeX Error: File `moresize.sty' not found.'
Latexmk: Log file says no output from latex
Latexmk: For rule 'xelatex', no output was made
Collected error summary (may duplicate other messages):
  xelatex: Command for 'xelatex' gave return code 1
      Refer to 'main.log' for details
Latexmk: Use the -f option to force complete processing,
 unless error was exceeding maximum runs, or warnings treated as errors.
Latexmk: Examining 'main.log'
=== TeX engine is 'XeTeX'
Latexmk: Errors, so I did not complete making targets

I assumed there are missing packages. But how can i resolve it? I can't install any package, because tlmgr is not installed.
So the question is:
How to install packages via command line or manually?

A: It cannot find package moresize. Please make a directory like mkdir -p ~/.texmf/tex/latex then go to CITAN web site and search for moresize and go to the relevant link returned by its search engine and click on download link, it gives you a zip file containing the source and document files of the package, save it somewhere and unpack it in the directory you have created i.e. ~/.texmf/tex/latex. Run this command cd ~/.texmf/tex/latex && latex moresize.ins it gives you the .sty file. Now to help latexmk find it create a file named .latexmkrc in the folder in which you put your .tex files here main.tex and add this line ensure_path( 'TEXINPUTS', '~/.texmf//' ); to it and save it. It will make the trick.


text:
Q: Swiping between different tabs is smooth but the changing of tabs is very slow I am on android, and testing in my physical device. I am using react-native-scrollable-tab-view. I have two tabs inside ScrollableTabView (Following and Recommended).
<View style={styles.container}>
    <HeaderMain/>
    <ScrollableTabView
        tabBarPosition='overlayBottom'
        tabBarUnderlineColor='#2ec76e'
        tabBarBackgroundColor='white'
        tabBarActiveTextColor='#2ec76e'
        tabBarInactiveTextColor='#99e3b8'
        scrollWithoutAnimation={true}
        tabBarTextStyle={{fontFamily: 'Roboto', fontSize: 15, fontWeight: 'bold'}}>
        <FollowingPostPage tabLabel="Following" />
        <RecommendedPostPage tabLabel="Recommended" />
    </ScrollableTabView>
</View>

Inside the FollowingPostPage I have a ScrollView which has list of posts (each post has a picture and some text)
export default class FollowingPostPage extends Component {
    render() {
        return(
            <ScrollView style={styles.container}>
                <PostCard/>
                <PostCard/>
                ...
                ...
                <PostCard/>
                <View style={styles.toolbar_height}/>
            </ScrollView>
        )
    }
}

Inside the RecommendedPostPage has just a text.
export default class RecommendedPostPage extends Component {
    render() {
        return(
            <View style={{flex:1, backgroundColor: '#ecf0f1'}}>
                <Text>I am from SuggestedPage!</Text>
            </View>
        )
    }
}

The swiping between the tabs is smooth. However, the changing of tabs if very slow.
If I press the Recommended tab, or if I swipe from Following to Recommended, the swiping is smooth, and also the tabs change as soon as the page changes.
However, when I am on Recommended, and press the Following tab or swipe from Recommended to Following, the swiping is very smooth, but the tab change takes a long time, as you can see the GIF from here:
How can I solve this issue? Could you please help me figure it out? Thank you.

A: There's probably something going on when swiping back to "Recommended" that is causing the animation to "drop frames" (Read about it here: React-Native docs). I would first replace your ScrollView with a ListView as this should give you better performance
From React-Native docs

ScrollView works best to present a small amount of things of a limited size. All the elements and views of a ScrollView are rendered, even if they are not currently shown on the screen. If you have a long list of more items that can fit on the screen, you should use a ListView instead.

With the example in the docs its shows strings for rows, but you can use objects too!

ds.cloneWithRows([
    {name: 'John'},
    {name: 'Joel'},
    {name: 'James'}
]);

<ListView
    dataSource={this.state.dataSource}
    renderRow={(rowData) => <Text>{rowData.name}</Text>}
/>

Hopefully this will help!


text:
Q: Understanding call tree view timings in Jprofiler In jprofiler how does the time in CPU views and Databases(jdbc/JPA) in call tree view coorelate with each other? How can i see if the bottleneck is at database calls or in java code

*

*Is the time shown in call tree section of CPU views cumulative time of the whole request and include the time taken by JPA and JDBC calls or is it only of CPU and does not include IO times. Is the total time of request is what i seen in call tree section of CPU views or is it a sum total of call tree timings for database and CPU views

*Question on different lines: I see a significant amount of times taken in java core classes like BigDecimal. Double.value of, Calendar.getInstance. They are a lot of invocations of these methods from my application. Also if I add these classes in my list of ignored classes in filter settings the overall time of my method which calls these classes is reduced. So can I assume that the large time reported in these methods was actually overhead introduced by Jprofiler.

A:
Is the time shown in call tree section of CPU views cumulative time of the
  whole request and include the time taken by JPA and JDBC calls

Only if you set the "Thread status" selector at the top of the CPU views to "All times". By default it's set to "Runnable" and does not include the time a socket waits for a database call to complete.

So can I assume that the large time reported in these methods was actually
  overhead introduced by Jprofiler.

With instrumentation, overhead can get very high in algorithmic code, especially because it reduces the possibility for the hot spot compiler to eliminate method calls. You would either have to adjust your filters to only instrument "high-level" classes or switch to "Sampling" in order to get realistic time measurements.


text:
Q: How to typeset UTF-8 characters without affecting ASCII characters? The context
I'm working on a homework assignment for my Databases courses. I want to typeset the ⨝ character (JOIN operation from relational algebra) but at the same time I would like to have the following behavior when reading the PDF: when selecting and copying the character, it must be copied as it is.
I've done my research and so far I've gotten the following
lualatex main

\documentclass{article}

\usepackage{fontspec}
\usepackage{unicode-math}

\setmathfont{XITS Math}

\begin{document}
$A ⨝ B$
\end{document}

When copying the ⨝ character in all the PDF viewers I've tried (zathura, okular and firefox), the character is copied as it is. I thought I had accomplished my goal. However, a new problem arises.
The problem
The problem is that ASCII characters are not copied as ASCII characters in some PDF viewers. Okular is the only PDF viewer that copy A and B as ASCII characters (see below).
Using Firefox, the line is copied as
firefox --version

Mozilla Firefox 88.0.1

⨝

Using Okular, the line is copied as
okular --version

okular 21.04.0

A⨝B

Using Zathura, the line is copied as
zathura --version

zathura 0.4.7
girara 0.3.5 (runtime: 0.3.5)
(plugin) djvu (0.2.9) (/usr/lib/zathura/libdjvu.so)
(plugin) pdf-mupdf (0.3.6) (/usr/lib/zathura/libpdf-mupdf.so)

 ⨝

The question
Is there any way to create a document that meet the following conditions

*

*Typeset the JOIN character such that when copying it in a PDF viewer, the ⨝ is inserted into the clipboard.

*Typeset the ASCII characters such that when copying them in a PDF viewer, ASCII characters are inserted into the clipboard.

In simpler words: Is there any package that would ensure that: When copying the selected characters from the generated PDF, the characters, that were used to typeset the ones from the PDF, are copied.
Here, the definition of a PDF viewer is any of the following: okular, zathura, built-in firefox PDF viewer. I'm just making clear since I know that there are many bad PDF viewers out there that would have different behaviors in the scenario presented here.
Additional context
Behavior of pdfgrep and pdftotext
pdfgrep and pdftotext also interpret the ASCII characters of the PDF as non-ASCII characters.
pdfgrep '' main.pdf

⨝

      1

pdftotext main.pdf
cat main.txt

⨝

1

Trying every font in my TeXLive distribution
I thought that this problem was caused because of the specified font in \setmathfont. For this reason, I created the following script which generates a PDF for each OTF font in the default TeXLive installation.
\documentclass{article}

\usepackage{fontspec}
\usepackage{unicode-math}

\setmathfont{...}

\begin{document}
foo $A ⨝ B$ bar
\end{document}

found="$(locate "/usr/local/*.otf")"
total="$(echo "$found" | wc -l)"
counter=1

for file in $found
do
  echo "Trying $file ($counter/$total)"
  echo "Trying $file ($counter/$total)" >> lualatex.log
  font=$(basename "$file")
  sed -i "s/\.\.\./$font/g" main.tex
  lualatex -interaction nonstopmode main 2>&1 >> lualatex.log
  exit_code=$?
  sed -i "s/$font/\.\.\./g" main.tex
  rm -f main.aux

  if [ "$exit_code" = 0 ]
  then
    mv main.pdf "$font.pdf"
    pdftotext "$font.pdf"
  fi
  counter=$((counter + 1))
done

The script took more than 30 minutes to finish and this is what I found. Of the 1702 *.otf fonts, the following fonts are the only ones that can typeset the ⨝ character.
grep -l -R --include="*.txt" '⨝' $my__experiments | sort

/home/beep1560/e/Asana-Math.otf.txt
/home/beep1560/e/Erewhon-Math.otf.txt
/home/beep1560/e/GFSNeohellenicMath.otf.txt
/home/beep1560/e/KpMath-Bold.otf.txt
/home/beep1560/e/KpMath-Light.otf.txt
/home/beep1560/e/KpMath-Regular.otf.txt
/home/beep1560/e/KpMath-Sans.otf.txt
/home/beep1560/e/KpMath-Semibold.otf.txt
/home/beep1560/e/NewCMMath-Book.otf.txt
/home/beep1560/e/NewCMMath-Regular.otf.txt
/home/beep1560/e/STIX2Math.otf.txt
/home/beep1560/e/STIX-Regular.otf.txt
/home/beep1560/e/XITSMath-Regular.otf.txt

Apparently, there is no font that typeset ASCII characters as ASCI characters because the following search yields no result
grep -l -R --include="*.txt" 'A.*⨝' $my__experiments | wc -l

0

So, I think that this is enough to think that this can be solved by using another font.

A: You can accomplish what you are searching by specifying the following option: math-style.
\documentclass{article}

\usepackage{fontspec}
\usepackage{unicode-math}

\setmathfont[math-style=upright]{XITS Math}

\begin{document}
$A ⨝ B$ \\
\end{document}

I tested this solution in the same versions of the software that you mentioned (because we are the same person).
I knew this because I searched ASCII in the unicode-math official documentation.  Next time, make sure that you look at the official documentation first (in this scenario, $ texdoc unicode-math) and search for keywords (in this scenario, ASCII).


text:
Q: How to create a button with overlapping Ribbon Shape in CSS? I am trying to create a button like the one shown in the picture. A rectangular box with a tag.

HTML:

POST FREE Ad

Any help would be appreciated.
CSS am using now and how do I create a tag like free given in the picture
.navbar-default {
    background: #fff;
    border-radius: 0 0 5px 5px;
    border: 0;
    padding: 0;
    -webkit-box-shadow: 0 1px 3px 0 rgba(0,0,0,.2);
    -moz-box-shadow: 0 1px 3px 0 rgba(0,0,0,.2);
    box-shadow: 0 1px 3px 0 rgba(0,0,0,.2);
    overflow: hidden;
}
.navbar-default .first a {
    border-radius: 0 0 0 5px;
}
.navbar-default .navbar-brand {
    margin-right: 50px;
    margin-left: 20px;
    width: 175px;
    height: 78px;
    background: url(../images/logo.png) no-repeat 0 50%;
}
.navbar-default .navbar-nav > li {
    margin-left: 0.5px;
}
.navbar-default .navbar-nav > li > a {
    padding: 25px 25px;
    font-size: 13px;
    line-height: 18px;
    color: #999;
}
.navbar-default .navbar-nav > li > a > i {
    display: inline-block;
}
.navbar-default .navbar-nav > li.active > a,
.navbar-default .navbar-nav > li.active:focus > a,
.navbar-default .navbar-nav > li.active:hover > a,
.navbar-default .navbar-nav > li:hover > a,
.navbar-default .navbar-nav > li:focus > a,
.navbar-default .navbar-nav > li.active > a:focus,
.navbar-default .navbar-nav > li.active:focus > a:focus,
.navbar-default .navbar-nav > li.active:hover > a:focus,
.navbar-default .navbar-nav > li:hover > a:focus,
.navbar-default .navbar-nav > li:focus > a:focus {
    background-color: #52b6ec;
    color: #fff;
}

A: jsBin Demo
A quick introduction, what it takes to create a FREE ribbon shape?:

.ribbon{
  display:inline-block;
  height:0;
  border-bottom:20px solid gold;
  border-left:20px solid transparent;
  border-right:20px solid transparent;
}

Now, using a single  element (thanks @Blazemonger for the reminder) let's send that shape to the :after pseudo, adding position, rotation....:

Submit an Ad

[data-ribbon]{
  position:relative;
  display:inline-block;

  padding:20px 26px;
  background:#FF7700;
  text-align:center;
  color:#fff;
  text-decoration: none;
}

[data-ribbon]:after{
  content: attr(data-ribbon);
  position:absolute;
  top: 6px;
  right:-22px;

  height:0;
  border-bottom: 20px solid gold;
  border-left:   20px solid transparent;
  border-right:  20px solid transparent;
  transform: rotate(45deg);
}

A: Here is another idea using linear-gradient to create the shape:

[data-ribbon] {
  position: relative;
  display: inline-block;
  padding: 20px 26px;
  background: #FF7700;
  text-align: center;
  color: #fff;
  text-decoration: none;
}

[data-ribbon]:after {
  content: attr(data-ribbon);
  position: absolute;
  right: 0;
  top: 0;
  display: inline-block;
  padding: 2px 25px;
  background:
    linear-gradient(to top right, gold 49%, transparent 50%) right/20px 100% no-repeat,
    linear-gradient(to top left, gold 49%, transparent 50%) left/20px 100% no-repeat,
    linear-gradient(gold, gold) center/calc(100% - 40px) 100% no-repeat;
  color: #fff;
  transform: rotate(45deg) translate(26%, -60%);
}
Submit an Ad


text:
Q: HTML5, CSS, and JavaScript Game creating I have a game I made with HTML5, CSS, and JavaScript. I have HTML image tags of joystick arrows. I would like users to be able to click my joystick arrow images with the mouse and have it work as if the arrows on the keyboard were pressed. How do I make keyCode 39 fire when the image of the right arrow is clicked? I wrote the code like this but it doesn't work:
var $rt_arrow = $('.rt_arrow')

$rt_arrow.on('click' , function (e) {
    e.keyCode == 39
})

A: You are facing an XY problem.
You don't want to trigger a keyboard event in this case, you just want your mouse event to trigger the same action as your keyboard event.
That is make you code more modular and create functions for each actions, then you can make your handlers call the required function:
onkeydown = e => {
  if(e.key === 'ArrowLeft') goLeft();
  else if(e.key === 'ArrowRight') goRight();
  // ...
};
onclick = e => {
  if(e.target === left_arrow) goLeft();
  else if(e.target === right_arrow) goRight();
  // ...
};

A: I believe this is what you're looking for http://www.port135.com/2017/12/24/how-to-simulate-keyboard-key-press-in-javascript-using-jquery/
I haven't tested this so I'm not 100% sure, though it seems pretty straight-forward.
So instead of:
    e.keyCode == 39

Put:
    jQuery.event.trigger({ type: 'keydown', which: 39 });


text:
Q: Customizing Swagger-UI Layout Swagger-UI docs shows an example of customizing the layout by using getComponent("operations"). This is in the list of components that Swagger-UI uses. This works fine in React. However, it won't work with other components. For example, if wanted to get the "operation" component, how would I include it?
I've tried using getComponent("operation") to no success. I saw that there are default props. Do I need to supply those to the component? If so, how would supply them? In the component Operation.jsx, one of the props is called operation (please see below). My OpenAPI 3.0 file has operationID which did not work.
Here is where I am trying to get the operation component:
    render() {
        const {getComponent} = this.props;
        const Operations = getComponent("operations", true);
        const Operation = getComponent("operation", true);
        return (
            <div>
               //this works (from the example)
               <Operations/>

               //this does not work
               <Operation/>
            </div>
        )

These are the default props:
static defaultProps = {
    operation: null,
    response: null,
    request: null,
    specPath: List(),
    summary: ""
  }

I expected to see getComponent(<any component>) be rendered, but the actual output is:
AppContainer, in SwaggerComponent (at pages/index.js:18)) TypeError: null is not an object (evaluating 'y.toJS')


text:
Q: using windows username password in C# how i can use windows stored username and password in my C# APP. I am looking for method which returns bool state of successful login. means :
bool isCredentialValid = CheckLogin(username, password);

so according to bool value I can show proper message.
Updated
class Program
{
    static void Main(string[] args)
    {
        PrincipalContext pc = new PrincipalContext(ContextType.Machine);
        Console.WriteLine("Enter username : ");
        string user = Console.ReadLine();

        Console.WriteLine("Enter password : ");
        string pass = Console.ReadLine();

        bool isValid = pc.ValidateCredentials(user, pass);

        Console.WriteLine("State : {0}",isValid);

        Console.ReadLine();
    }
}

this code is not working. when i enable Guest account it shows true for every login and when i disable Guest account it does not verifies even existing account. Any help would be appreciated.

A: Have a look at PrincipalContext.ValidateCredentials method. For example,
PrincipalContext pc = new PrincipalContext(ContextType.Domain);
bool isCredentialValid = pc.ValidateCredentials(username, password);

for local accounts, use ContextType.Machine.
Yet another way would be using win32 api LogonUser function

A: Add  using System.Security.Principal;
//for current Username full
 string str = WindowsIdentity.GetCurrent().Name;

Then u can use this username for authentication.
For password it is different.


text:
Q: About JDBC Connection A very simple question but i'm newbie in Java. How can I do the connection with my SQL Server DataBase that are in my network ?
I made the download of the JDBC 4.0, associate the file in my project and I'm trying the follow code, but I don't know how can I do a reference to my database
try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        String connectionUrl = "what i put here ?";
        Connection con = DriverManager.getConnection(connectionUrl, "sa", "testtest");
    } catch (SQLException e) {
        e.printStackTrace();
    }
catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

A: String url = "jdbc:mysql://localhost:3306/";
String db = "yourDB";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "";
    try {
        Class.forName(driver);
        Connection con = DriverManager.getConnection(url + db, user, pass);
        con.setAutoCommit(true);
    } catch (ClassNotFoundException e1) {
                    e1.printStackTrace();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }

A: try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        DriverManager.getConnection("jdbc:sqlserver://url.com;database=dbname;user=username;password=test")
    } catch (SQLException e) {
        e.printStackTrace();
    }
catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

replace the url/username/password. This is the connectionstring for sql server


text:
Q: Determine whether member class is nested or inner? Suppose I have a class that contains come member classes, some of them nested (static) and some inner (non-static):
class Foo {
    static class A {}
    class B {}
    static class C {}
}

I would like to get all the nested member classes of Foo, i.e. A and C, but not B. Is this even possible? I know how to list all the member classes (using Foo.class.getDesclaredClasses()), i see methods such as isLocalClass(), isMemberClass() or isAnonymousClass() on java.lang.Class, but I don't see anything like isNested() or isInner().

A: You can use Modifier#isStatic(int mod) (Return true if the integer argument includes the static modifier, false otherwise.) to know if the inner-class is static or not.
Like this :
public class Demo {
public static void main(String[] args) {
    Class foo = Foo.class;
    Class[] declaredClasses = foo.getDeclaredClasses();
    for (Class class1 : declaredClasses) {
        System.out.println(Modifier.isStatic(class1.getModifiers()));
    }
}
}

class Foo {
    static class A {}
    class B {}
    static class C {}
}

Output :
true
false
true

Note : Class#getModifiers() -

Returns the Java language modifiers for this class or interface,
  encoded in an integer. The modifiers consist of the Java Virtual
  Machine's constants for public, protected, private, final, static,
  abstract and interface; they should be decoded using the methods of
  class Modifier.


text:
Q: Having trouble adding more Texture2D's as Pixel Shader resources in DirectX 11 I'm having a really annoying problem with my application that is a school project. I'm using deferred rendering and I'm trying to add positions from the light's pov as a new g-buffer texture, and the depth buffer texture as a shader resource in the light pass. I handle all of the g-buffer textures in the exact same way.
My problem is that these new shader resources are nowhere to be found on the GPU!
I'm using RenderDoc to debug my application, and there I can see everything being written to these new resources just fine, and the call to bind them as shader resources looks good as well, but I still only have the 4 resources in the light pass that I had before.
My code is an absolute mess, and there's a lot(!) of it. So if you want to see something specific to be able to help me, I can post it.
I'd be really happy if I just got some tips as to how you go about debugging this kind of problem, and even happier if someone knows what the problem is.
Thanks in advance!

A: There are two essential first steps for debugging DirectX applications:

*

*Make sure that for every function that returns an HRESULT that you check it at runtime. If it is safe to ignore the return, it would return void.  When checking the HRESULT don't use == S_OK, but use the FAILED or SUCCEEDED macro instead. A nice option for 'fast fail' errors is to use C++ exception handling via ThrowIfFailed.

*Enable the DirectX Debug Device and look for errors, warnings, and other messages in the debug output window. For details on enabling it, see Anatomy of Direct3D 11 Create Device and Direct3D SDK Debug Layer Tricks.
This may not solve your problem, but can really help avoid some silly mistakes that cost you a lot of time to track down.

If you are new to DirectX development, take a look at the DirectX Tool Kit tutorials

For debugging DirectX 11 applications, the Visual Studio Graphics diagnostics feature in VS 2012 or later is a good option. You likely fit the license requirements to use the VS 2013 or VS 2015 Community edition, and it includes all features including the VSGS. See MSDN.


text:
Q: .htaccess remove extension for a single file Is there a possibility to redirect requests for example.com/test to example.com/test.php for a particular file using .htaccess, leaving all other files/extensions intact?

A: You can try this : RewriteRule ^test$ /test.php [L] place it above your generic redirection written for all site url.
Like for example :
RewriteRule ^test$ /test.php [L] --page wise condition

RewriteRule ^/?$ "http\:\/\/example\.com\/" [R=301,L] -- generic for site

RewriteRule ^(.[^\.]*)$ index.php?$1 [QSA,L] -- generic for site

A: you can use
RewriteEngine On
RewriteRule ^test$ test.php

A: Yes,
All you do is put this right at the beginning of your .htaccess file
RewriteRule ^test test.php [L]

The [L] means it will honor this line and ignore any subsequent lines.
So put all other URL rewrites after this one.


text:
Q: Create the effect of drawing an additional line and legend-item on an existing ggplot2 I am making a presentation and would like to present one line graph (geom_line()) with an appropriate legend. I then want to overlay a new geom_line and add the corresponding legend item. For aesthetic reasons, I want the overlay to not modify the legend location given in the first plot. The effect should be that one is drawing on an existing graph, and adding to its legend.
If I simply using ggplot to first make the first plot and then make a new plot with both lines, the location of the legend changes noticeably.
If I try to make the first plot be the full plot, but setting one of the line sizes to zero, I run into the problem that I can't suppress the legend-item for the size-zero line.
How can I achieve my desired effect with ggplot2?
EDIT:
Here is the code to make the two graphs that I first naively tried.
require(ggplot2)
require(reshape2)

x<-seq(-10,10,length=200)
G <- (1/(sqrt(2*pi))) * exp(-((x)^2)/(2))
G2 <- 2*(1/(pi))*(1/(x^2+1))

df = data.frame(x,G,G2)

ggplot(data = melt(data.frame(x,G),id.vars = 'x'))+
  geom_line(aes(x=x, y=value, color=variable),size=.5)+
  scale_color_manual("Distribution",values=c("orange"),labels=c("Gaussian"))+
  coord_cartesian(ylim = c(0, 1))

ggplot(data = melt(data.frame(x,G,G2),id.vars = 'x'))+
  geom_line(aes(x=x, y=value, color=variable),size=.5)+
  scale_color_manual("Distribution",values=c("orange","blue"),labels=c("Gaussian","2Gaussian"))+
  coord_cartesian(ylim = c(0, 1))

If it's not clear from these pictures that there is a problem, open up the images from these two links and flip from one to another.
http://rpubs.com/jwg/269311
http://rpubs.com/jwg/269312
NOTICE: The problem is even worse than I first described, since not only is the legend moving but the coordinate axis is moving as well.
Presumably this can be fixed by plotting both and then making its legend-item and the line invisible. Is this a possibility?

A: Here's a solution which will keep everything aligned with the bonus of animation.
library(ggplot2)
library(tidyr)
library(gganimate)

p <- df %>%
  gather(var, val, -x) %>%
  ggplot(aes(x, val, frame = var)) +
    geom_line(aes(color = var, group = var, cumulative = TRUE)) +
    coord_cartesian(ylim = c(0, 1))

gganimate(p, "myplot.gif", "gif")

This should generate a file myplot.gif with this result:

A: Not sure if this is what you want, but here goes:
x<-seq(-10,10,length=200)
G <- (1/(sqrt(2*pi))) * exp(-((x)^2)/(2))
G2 <- 2*(1/(pi))*(1/(x^2+1))

df <- data.frame(x,G,G2)
df.plot <- tidyr::gather(df, key = 'variable', value = 'value', -x)

    ggplot(df.plot, aes(x, value, color = variable)) + geom_line() + scale_color_manual(breaks = c("G"), values = c("orange", NA)) +
coord_cartesian(xlim = c(-10, 10), ylim = c(0,1)) + theme(legend.position = c(0,0)) +
theme(legend.position = "right",
legend.justification = "top")

ggplot(df.plot, aes(x, value, color = variable)) + geom_line() + scale_color_manual(breaks = c("G", "G2"), values = c("orange", "blue")) +
coord_cartesian(xlim = c(-10, 10), ylim = c(0,1)) + theme(legend.position = "right",
legend.justification = "top")


text:
Q: Android - Null pointer calling Arraylist with getter/setter. I am attempting to track history of steam URL's played, and the value of getCurrentPosition to offer the user the capability to resume a video where they had left off during that session.  My strategy has been to use two Arraylists to stash the data, compare the URL and stuff the previous position back through the intent extras.
I receive an NPE on a call to my getter.  Here are the important parts:
Getter/Setter class:
public class WatchedGS {

private ArrayList videoURL = new ArrayList();
private ArrayList resumeTime = new ArrayList();

public ArrayList getURL() {
return videoURL;
}

public void setURL(String videoURL) {
    this.videoURL.add(videoURL);
    Log.i("videoURL added: ", videoURL);
}

public ArrayList getresumeTime() {
    return resumeTime;
}

public void setresumeTime(int time) {
    this.resumeTime.add(time);
    Log.i("videoTime added: ", ""+ time);
}
}

Mediaplayer calling set on surface destroy, confirmed working:
    public void surfaceDestroyed(SurfaceHolder holder) {
    watchedGS.setURL(urlString);
    watchedGS.setresumeTime(player.getCurrentPosition());
    player.release();
    player = null;
    finish();
}

MainActivity calling get, causing NPE:
    WatchedGS historyList;

            if (videoHistory){
            int alSize = historyList.getURL().size();
            if (historyList.getURL().contains(url)) {
                Log.i("it's there!", url);
            }

I'm sure I've overlooked something silly, and would appreciate any pointers in what I've missed.  Thank you in advance.

A: WatchedGS historyList;

        if (videoHistory){
        int alSize = historyList.getURL().size();
        if (historyList.getURL().contains(url)) {
            Log.i("it's there!", url);
        }

You're not initializing historyList before calling getURL() on it.


text:
Q: KERNEL_SECURITY_CHECK_FAILURE BSOD Error I have been getting this error on my laptop and I am getting absolutely sick of it now.
I have downloaded many fixes from Microsoft websites but no joy.
If I google it, I get 1000 different possible reasons for this issue, Is there any one stop solution for this issue?
I have updated all of my drivers, Scanned disk for any issues, Scanned Memory for any issues and found nothing.
I get two errors simultaneously KERNEL_SECURITY_CHECK_FAILURE and FIX IRQL_NOT_LESS_OR_EQUAL.
First it would restart the laptop once I get the error, but now it just freezes and I have to power shutdown and start the machine.
Laptop Specs:
Processor: Intel(R) Core(TM) i7-4702 CPU @ 2.20GHz
RAM:       32GB
SSD:       120GB
HHD:       1TB
OS:        Windows 8.1 64 bit

Error Screen Shot


text:
Q: How to enter Text or click outside a JFrame using Java My Goal:
I am trying to make a program which will log me into my zoom classes at the correct time. I have figured out everything except trying to open zoom, enter the ID and passcode correctly, and logging in to the class.

The Problem:
There is no API which I can use to achieve my goal. There is a certain Zoom API, but it is paid, and I am a minor. The only option I think is left is to make java click and enter text anywhere outside a JFrame.
I tried using java.awt.Robot for this, but it can only click on a button inside the JFrame. I tried overlapping the two buttons and keeping the zoom window focused, but Java changes the focus to the JFrame.

If there is any other alternative in Java, or if there is any other external Library or API that may come in use, please suggest me the same.
Thank you in advance.

A: You could use WindowListener,#windowDeactivated or WindowFocusListener#windowLostFocus, but you have to be careful with owned JDialog's (as you have to be with FocusListener anyway)

A:
I tried using java.awt.Robot for this, but it can only click on a button inside the JFrame.

The Robot can be used to generate an OS level event.
If you want the Robot to click out side the frame then you need to move the mouse outside the bounds of the frame.
Simple example:
public static void main(String[] args) throws Exception
{
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    frame.setLocation(25, 25);
    frame.setSize(100, 100);
    frame.setVisible(true);

    Robot robot = new Robot();
    robot.delay(2000);
    robot.mouseMove(15, 15 );
    robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
}

The Robot will click the system menu of the window found at the top/left corner of your desktop. So make sure you have a window maximized.