text:
Q: How can I change the order life cycle in Magento? I'm new to magento and as far as I can see, the order states are labeled as "pending", "processing" and "completed". When customer checks out, then the state becomes "pending", and either invoicing or shipping makes the state "processing", and when both are done, state becomes "completed". Please correct me if I am wrong.
So, I'd like to introduce new states but not statuses, I did manage to introduce new statuses when it is in one of the states above, or I could change the labels of the existing states but I want to learn how magento manages the states and how to modify it/add new states. I can modify the core code if required.
So, my question is how do I introduce new states (not statuses) or how do I change/modify the order life-cycle?
I can investigate the source if you tell me which parts of the code is managing the order life-cycle. Any help or clue is appreciated.
PS: I'm using v1.5.1.0 right now.

A: So in your config.xml you would have something like ...
<config>
    <global>
        <sales>
            <order>
                <states>
                    <my_state translate="label">
                        <label>My State</label>
                        <statuses>
                            <pending default="1"/>
                        </statuses>
                        <visible_on_front/>
                    </my_state>
                </states>
            </order>
        </sales>
    </global>
</config>

Then whenever you want the state to change you could override the core or add an observer to change the state (please don't edit the core directly!) with something like (assuming $order is a valid order already loaded and ready to go) ....
$order->setState("my_state");
$order->save();

which will do the default status for the state. if you want to set a status put that in the second parameter so ..
$order->setState("my_state","complete");
$order->save();

HTH


text:
Q: data is not reloading after being saved I'm storing data using API, it saves successfully, but it's not reloading in the datagrid. I have manually refresh the entire page to view the data. I tried to put the storing variable in a function, then call that function, but it's not rendering I guess. kindly help me. Thank you in advance
here's the code
const ContactDataGrid = ({ rows, columns }) => {
 const [platform, setPlatform] = useState([]);
 const [searchText, setSearchText] = useState('');
 const [Rows, setRows] = useState([]);
 const [open, setOpen] = useState(false);
 const [formInputData, setformInputData] = useState(
   {
     name: '',
     details: '',
   }
 );

 const handleOpen = () => setOpen(true);
 const handleClose = () => setOpen(false);

 const handleChange = (evnt) => {
   setOpen(true)
   const newInput = (data) => ({
     ...data,
     [evnt.target.name]: evnt.target.value
   });
   setformInputData(newInput);
 }

 const showData = () => setRows(rows);

 useEffect(() => {
   setPlatform(rows);
   showData();
 }, [rows]);
 console.log()

 const handleSubmit = (evnt) => {
   evnt.preventDefault();
   const formData = new FormData();    //formdata object
   formData.append('nickname', formInputData.nickname);   //append the values with key, value pair
   formData.append('target', formInputData.target);
   const config = {
     headers: { 'content-type': 'multipart/form-data' }
   }
   axios.post('http://localhost:8006/api/v2/save/beneficiary', formData, config)
     .then(response => {
       if (response.data.success === true) {
         showData()
         alert(response.data.message)
       }
     })
     .catch(error => {
       alert(error.message);
     });
   setformInputData({ nickname: "", target: "" });
   setOpen(false);
 }

 function escapeRegExp(value) {
   return value.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
 }
 const requestSearch = (searchValue) => {
   const searchRegex = new RegExp(escapeRegExp(searchValue), 'i');
   const filteredRows = platform.filter((row) => {
     return Object.keys(row).some((field) => {
       return searchRegex.test(row[field]?.toString() || '');
     });
   });
   setRows(filteredRows);
 };

A: I think when you request success the variable rows don't change so show data load the old data. You can trigger when post data you request fetch data again and change datagrid.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Site working in FF not in IE, Built with iframes I have a site, that i built through iframes, but i cant seem to use it with IE.
For safety resons i cannot give access to it, but ill explain wehat the problem is.
First of all i was forced to do it through iframes due to the webserver didnt support .net.
Heres how it looks:
http://ipdg.se/order.htm
So far so good, an iframe working good. But when i try to log in the problem starts.
If FF it goes smoothly, but in ie, it doesnt happen anything(Would normally be redirect to the same page but with session variables and showing other content) i dont know what causes this. but either IE cannot do response.redirects, or there is a problems with the iframe.. or both.
It works in alla major browsers except for internet explorer!

A: Some time back there was a problem like this... the iframe tag was
<Iframe src="order.php" width="450" height="650"></Iframe>

The solution was to change the src from order.php to order.html... That may not be possible in your case, but it appeared that there was an IE security setting that prohibited the dynamic page from loading.

A: As a previous poster said. the problem is with IE and its security check, therefore. Using server.transfer got it working.
response.redirect doesnt redirect directly to the page, it communicates with the client browser before the redirect. therefore the browser has a chance to stop the request(Lame IE).
but server.transfer doesnt do that and goes around the problem.


text:
Q: Tensorflow: import init_ops and random_ops I would like to create a custom initializer based on the code of tf.truncated_normal_initializer.
However, when I try to import init_ops and random_ops. I get the error:
AttributeError: 'module' object has no attribute 'ops'
to reproduce:
import tensorflow.python.ops.random_ops as random_ops

A: Oops, quite trivial. Issue solved with
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import init_ops


text:
Q: Update value in view which is changed inside a loop by a service My component uses a service which (triggered by the component) manipulates thousands of objects in a loop. As is good practice, I want to include a progress indication for this operation. At the moment, I haven't managed to feed the progress back to the user interface as the loop is running.
Simplified app on StackBlitz
While the progress is updated in real time in the console (in my app, weirdly enough not on the StackBlitz...) I can't get the progress to update in the view.
What is the proper view to do this? I have tried ChangeDetectorRef, running certain things in an NgZone and subscribing from the template directly using the async pipe, all without any success so far.

A: If you check the console you will see first nothing is printed out until the synchronous tasks are done and suddenly the browser console prints out all the asyncronous values of your console.log at once.
In my understanding
As you are processing a synchronous function, even if the progress value is asynchronously emitted, still the browser engine process the synchronous tasks first and then the asynchronous tasks.
But if you turn your function into a complete async function like using setTimeout and then call your function recursively while you are increasing the progress value each time the function is called, angular will have time to update the view and display the progress value.
doLoading() {

    if (this._internalProgress >= 100) return;

    setTimeout(() => {
      this.sleep(Math.random() * 300);
      this._internalProgress += Math.random() * 10;

      if (this._internalProgress > 100) {
        this._internalProgress = 100;
      }

      this.doLoading();
    }, 100);
  }

You can adjust the timeout value 100 to set the delay time between each chunk execution of you function.
And then in your template just read the _internalProgress value from the service directly, or whatever way you prefer.
<p>{{ loader._internalProgress }}</p>

Checkout my Stackblitz example


text:
Q: How to specify the number of CPU a container will use? I am on working on Windows Server 2019 and trying to run a docker container of CentOS on it. I am running the following:
PS C:\Windows\system32> docker run -dit --name=testing23 --cpu-shares=12    raycentos:1.0
6a3ffb86c1d9509a9d80f0de54fc6acf5731ca645ee74e6aabe41d7153b3af70
PS C:\Windows\system32> docker exec -it 6a3ffb86c1d9509a9d80f0de54fc6acf5731ca645ee74e6aabe41d7153b3af70 bash
(app-root) bash-4.2# nproc
2

It still specifies only 2, and not 32. How can we assign more CPUs to the container?

A: refer to this topic for more details https://docs.docker.com/config/containers/resource_constraints/#cpu
you have to add the values with proper flags
try :
    --cpus=<value> for maximum CPU resources a container can use
    --cpuset-cpus = 12

A: By default, all can be used, or you can limit it per container using the --cpuset-cpus parameter.
docker run --cpuset-cpus="0-2" myapplication:latest

That would restrict the container to 3 CPU's (0, 1, and 2). See the docker run docs for more details.
The chosen way to limit CPU usage of containers is with a fractional limit on CPUs:
docker run --cpus 2.5 myapplication:latest


text:
Q: using command line arguments to include/exclude text sections I have a main document defined of which I need to extract different versions. For example, in:
\section*{5\\animalia}
\vspace{\oneline}
\includegraphics[page={33}, trim=1cm 0 0 0]{\pdfsource}
\includepdf[page={34-37}]{\pdfsource}

the last line would be compiled only if I would run pdflatex with the argument AA.
There should be around 20 different versions to prepare, so it would be great if I could compile all these in a batch, instead of preparing 20 different files. There are no common elements to select, so the lines from AA will all be different ones from AB or AJ.
I had a look at \newcommand and \xparse, but I think I didn't find exactly what I needed. Any suggestions?
One other detail: the argument would also be passed to a text line at the start, namely:
\subsection*{ARGUMENT}

would print as AA. I think that is easy to do, but I couldn't also find a concrete example.

A: If you compile the following with
pdflatex "\newcommand{\version}{KK}\input{filename.tex}"

you can test for the value of \version:
\documentclass{article}

\usepackage{ifthen}

\ifdefined\version
\else
\def\version{AK}
\fi

\begin{document}

\section{\version}

\ifthenelse{ \equal{\version}{KK} }{
    KK version
}{
    other version
}

\end{document}


text:
Q: best way to convert flow to live data I am implementing search from Unsplash api and data will be updated on the basis of search
GalleryViewModel.kt
@HiltViewModel
class GalleryViewModel @Inject constructor(
    private val fetchPhotoUseCase:FetchPhotoUseCase,
    @Assisted state: SavedStateHandle
) :ViewModel(){

    companion object{
        private const val CURRENT_QUERY = "current_query" // key
        private const val DEFAULT_QUERY = "cats"
    }

    private val currentQuery = state.getLiveData(CURRENT_QUERY, DEFAULT_QUERY)

    val photos = currentQuery.switchMap { queryString ->
        liveData {
            fetchPhotoUseCase.execute(queryString).collect {
                emit(it)
            }
        }
    }

   fun searchPhotos(query: String) {
    currentQuery.value = query
   }
}

FetchPhotoUseCase.kt
class FetchPhotoUseCase @Inject constructor(
    private val repository: UnSplashRepository
) : UseCaseWithParams<String,Flow<PagingData<UnsplashPhoto>>>(){
    override suspend fun buildUseCase(params: String): Flow<PagingData<UnsplashPhoto>> {
        return repository.getSearchResult(params)
    }
}

FetchPhotoUseCase is in the domain layer. It returns flow so I change flow to live data in switchmap lambda.
Am I doing it right or is there a better way to achieve it..
Edit
I have updated my code to work on both dispatchers like below..
suspend fun getPhotos(queryString: String) = withContext(Dispatchers.IO){
        fetchPhotoUseCase.execute(queryString)
    }

    fun getImages(queryString: String) = liveData(Dispatchers.Main) {
        getPhotos(queryString).collect {
            emit(
                it.map { unsplash ->
                    unSplashMapper.mapFromEntity(unsplash)
                }
            )
        }
    }

A: There is a handy method asLiveData, which already implements of what you have written:
val photos = currentQuery.switchMap { queryString ->
    fetchPhotoUseCase.execute(queryString).asLiveData(Dispatchers.Main)
}

Dependency to use asLiveData() extension function:
def lifecycle_version = "2.4.0"

implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"


text:
Q: How find values in an array that meet two conditions using Python I have an array
a=[1,2,3,4,5,6,7,8,9]

and I want to find the indices of the element s that meet two conditions i.e.
a>3 and a<8
ans=[3,4,5,6]
a[ans]=[4,5,6,7]

I can use numpy.nonzero(a>3) or numpy.nonzero(a<8)
but not
numpy.nonzero(a>3 and a<8) which gives the error:
ValueError: The truth value of an array with more than one element is
ambiguous. Use a.any() or a.all()

When I try to use any or all I get the same error.
Is it possible to combine two conditional tests to get the ans?

A: An alternative (which I ended up using) is numpy.logical_and:
choice = numpy.logical_and(np.greater(a, 3), np.less(a, 8))
numpy.extract(choice, a)

A: numpy.nonzero((a > 3) & (a < 8))

& does an element-wise boolean and.

A: if you use numpy array, you can directly use '&' instead of 'and'.
a=array([1,2,3,4,5,6,7,8,9])
a[(a>3) & (a<8)]
ans=array([3,4,5,6])

A: Side note, this format works for any bitwise operation.
numpy.nonzero((a > 3) | (a < 8)) #[or]
numpy.nonzero((a > 3) & (a < 8)) #[and]


text:
Q: SQL Server stored procedure based on input parameters value create procedure sp1
(
    @p1 int = null
)
as
begin
    select f1, f2, f3
    from table1;
end

How to add the "where" clause to the select query (where f1=@p1) only when @p1 is not null? if @p1 is null then return all rows!

A: Try this. The where clause will work only when @p1 is not null
SELECT f1,
       f2,
       f3
FROM   dbo.table1
WHERE  @p1 IS NOT NULL
       AND f1 = @p1

If you want to return all the values if @p1 is null then just a ISNULL function. If @p1 is Not Null then f1=@p1 values will be returned else all the values will be returned. Try this
SELECT f1,
       f2,
       f3
FROM   dbo.table1
WHERE  f1 = isnull(@p1,f1)

A: create procedure dbo.sp1
(
    @p1 int = null
)
as
begin
select f1, f2, f3
from dbo.table1 where(@p1 is not null and f1=@p1)
end

OR
You can Use
Here Query Returns all rows if @p1 is null (Because @p1 return true when NULL)
  create procedure dbo.sp1
(
    @p1 int = null
)
as
begin
select f1, f2, f3
from dbo.table1 where(@p1 is null OR f1=@p1)
end

A: In case @p1 is null, below will return every thing and if there is a value, it will apply the condition.
 WHERE @p1 is NULL OR f1=@p1


text:
Q: firewalld: two NICs, two zones. Zone is ignored I have a server running CentOS/RHEL 7.7 with two network interfaces.  These interfaces are configured and work properly.  The first interface, ens33, is part of the firewalld "public" zone.  All the rules applied to this zone work properly.  The second interface, ens37, also works as expected when a member of the "public" zone.  I've created a second zone, "GLZ", which has a set of rules specific to the function of the second interface.  I am unable to get any rules from the GLZ zone to take effect on this interface.  I've configured this type of setup using iptables many times in the past but cannot seem to get the desired effect with firewalld.  I feel like I must be missing something fundamental with firewalld but I don't know what it might be.  Below are the specifics:
Setup script:
NEWZONE="GLZ"

# create the new zone
firewall-cmd --permanent --new-zone=$NEWZONE
firewall-cmd --reload

# add the second NIC to the zone
firewall-cmd --permanent --zone=$NEWZONE --change-interface=ens37
# set zone target
firewall-cmd --zone=$NEWZONE --permanent --set-target=default
firewall-cmd --reload

# open necessary ports
firewall-cmd --permanent --zone=$NEWZONE --add-rich-rule='rule family=ipv4 source address=0.0.0.0/0 port protocol=tcp port=80 accept'
firewall-cmd --permanent --zone=$NEWZONE --add-rich-rule='rule family=ipv4 source address=0.0.0.0/0 port protocol=tcp port=443 accept'
# setup forwarding (see https://docs.fedoraproject.org/en-US/Fedora/19/html/Security_Guide/sec-Configure_Port_Forwarding-CLI.html)
firewall-cmd --permanent --zone=$NEWZONE --add-masquerade
firewall-cmd --permanent --zone=$NEWZONE --add-forward-port=port=22:proto=tcp:toport=2222
firewall-cmd --reload

This appears to look fine based on the output of --info-zone.  Both zones are active and the appropriate network interface is assigned to each zone.  Any changes I make the public zone affect traffic on both interfaces and none of the rules I add or remove from the GLZ zone make any difference at all.
Output:
$ sudo firewall-cmd --info-zone=public
public (active)
  target: default
  icmp-block-inversion: no
  interfaces: ens33
  sources:
  services: dhcpv6-client ssh
  ports:
  protocols:
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:
    rule family="ipv4" source address="10.0.0.0/8" port port="3306" protocol="tcp" accept
    rule family="ipv4" source address="10.0.0.0/8" port port="80" protocol="tcp" accept
    rule family="ipv4" source address="10.0.0.0/8" port port="443" protocol="tcp" accept
    rule family="ipv4" source address="10.0.0.0/8" port port="8080" protocol="tcp" accept

$ sudo firewall-cmd --info-zone=GLZ
GLZ (active)
  target: default
  icmp-block-inversion: no
  interfaces: ens37
  sources:
  services:
  ports:
  protocols:
  masquerade: yes
  forward-ports: port=22:proto=tcp:toport=2222:toaddr=
  source-ports:
  icmp-blocks:
  rich rules:
    rule family="ipv4" source address="0.0.0.0/0" port port="80" protocol="tcp" accept
    rule family="ipv4" source address="0.0.0.0/0" port port="443" protocol="tcp" accept


text:
Q: Random sample from sql database uniformly over time I'd like to sample rows from a table uniformly over time, here is the naive way to do this:
SELECT * FROM table ORDER BY RAND() LIMIT 10000

Unfortunately, executing this query causes the table to first get sorted, which can take very very very long if it is large, and the query freezes. There are other ways for dealing with random sampling in sql, but they are really complicated. Is there any shortcut to doing this with a DatabaseLink` command?
Code to get started
Here's how to I set up my connection:
<< DatabaseLink`
DatabaseExplorer[] (* wizard to create the connection "database_name"*)
conn = OpenSQLConnection["database_name"];

For the query DatabaseLink uses the function SQLSelect, which has these options:

Update:
Here are the table structure details:

*

*Generic mysql db with single table (381 Gb)

*Uses InnoDB storage engine

*All columns have btree indices

*The table has a primary key and 589 million rows

*The column I'm random sampling from is 'created_at' of type datetime

*The table's schema look like this:
CREATE TABLE photos (
  id int(10) unsigned NOT NULL AUTO_INCREMENT,
  tweet_id varchar(255) DEFAULT NULL,
  created_at datetime NOT NULL,
  hashtags varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  text varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  source varchar(255) DEFAULT NULL,
  image_hash text,
  PRIMARY KEY (id),
  UNIQUE KEY photos_tweet_id (tweet_id),
  KEY photos_date (object_date)
) ENGINE=InnoDB AUTO_INCREMENT=589069903 DEFAULT CHARSET=latin1


text:
Q: nav pills trazendo informações do mysql em pdo

Mídias

  <?php
  // Atribui uma conexão PDO
  $conexao = Connection::getInstance();

  $controle_ativo = 2;
  //$controle_num_slide = 1;
  $sql = "SELECT * FROM db_post WHERE status=1 AND category='Mídia' ORDER BY created DESC LIMIT 3";

  $stm = $conexao->prepare($sql);
  $stm->execute();

  while($post = $stm->fetch(PDO::FETCH_OBJ)) {
    if($controle_ativo == 2) { ?>

        <a class="nav-link active" id="nav-pills-01" data-toggle="pill" href="#<?=$post->post_id?>"><?=$post->title?>

    <?php
      $controle_ativo = 1;
    } else {
    ?>

        <a class="nav-link" id="nav-pills-02" data-toggle="pill" href="#<?=$post->post_id?>"><?=$post->title?>

    <?php
      //$controle_num_slide++;
    }
  }
  ?>

  <?php
  // Atribui uma conexão PDO
  $conexao = Connection::getInstance();

  $controle_ativo = 2;
  $sql = "SELECT * FROM db_post WHERE status=1 AND category='Mídia' ORDER BY created DESC LIMIT 3";

  $stm = $conexao->prepare($sql);
  $stm->execute();

  while($post = $stm->fetch(PDO::FETCH_OBJ)) {
    if($controle_ativo == 2) { ?>
  <div class="tab-pane fade show active" id="<?=$post->post_id?>" role="tabpanel">

          <iframe class="embed-responsive-item" src="<?=$post->url?>">

<?=$post->content?>

            Publicado em <?=date('M,d',strtotime($post->created))?>

    <?php
      $controle_ativo = 1;
    } else {
    ?>
  <div class="tab-pane fade" id="<?=$post->post_id?>a" role="tabpanel">

          <iframe class="embed-responsive-item" src="<?=$post->url?>">

<?=$post->content?>

            Publicado em <?=date('M,d',strtotime($post->created))?>

    <?php
    }
  }
  ?>

Há aba ativa está perfeita quando clico na segunda ou terceira aba nada acontece (não abre), tenho que deixar dinâmico. Ainda pergunto existe uma maneira com javascript para ativar a aba e seu conteúdo.

A:

Mídias

  <?php
  // Atribui uma conexão PDO
  $conexao = Connection::getInstance();

  $controle_ativo = 2;
  $sql = "SELECT * FROM db_post WHERE status=1 AND category='Mídia' ORDER BY created DESC LIMIT 3";

  $stm = $conexao->prepare($sql);
  $stm->execute();

  while($post = $stm->fetch(PDO::FETCH_OBJ)) {
    if($controle_ativo == 2) { ?>

        <a class="nav-link active" id="nav-pills-01" data-toggle="pill" href="#**navtabs**<?=$post->post_id?>"><?=$post->title?>

    <?php
      $controle_ativo = 1;
    } else {
    ?>

        <a class="nav-link" id="nav-pills-02" data-toggle="pill" href="#**navtabs**<?=$post->post_id?>"><?=$post->title?>

    <?php
    }
  }
  ?>

  <?php
  // Atribui uma conexão PDO
  $conexao = Connection::getInstance();

  $controle_ativo = 2;
  $sql = "SELECT * FROM db_post WHERE status=1 AND category='Mídia' ORDER BY created DESC LIMIT 3";

  $stm = $conexao->prepare($sql);
  $stm->execute();

  while($post = $stm->fetch(PDO::FETCH_OBJ)) {
    if($controle_ativo == 2) { ?>
  <div class="tab-pane fade show active" id="**navtabs**<?=$post->post_id?>" role="tabpanel">

          <iframe class="embed-responsive-item" src="<?=$post->url?>">

<?=$post->content?>

            Publicado em <?=date('M,d',strtotime($post->created))?>

    <?php
      $controle_ativo = 1;
    } else {
    ?>
  <div class="tab-pane fade" id="**navtabs**<?=$post->post_id?>" role="tabpanel">

          <iframe class="embed-responsive-item" src="<?=$post->url?>">

<?=$post->content?>

            Publicado em <?=date('M,d',strtotime($post->created))?>

    <?php
    }
  }
  ?>

Após uma leitura no endereço: https://getbootstrap.com/docs/4.1/components/navs/#pills o problema foi resolvido e a correção está em negrito.


text:
Q: Pure Virtual Method Called Error Google Protocol Buffer Right now I have a QList of protobuf Messages.  Inside of a while loop, I create messages and add them to the QList. I try to use the DebugString Method to print them out and in the while loop it works fine with no errors.  When I try to call the exact same ->DebugString() method outside of the while loop I get:

Abort (Core dumped).
pure virtual method called terminate called without an active
  exception

QList<const ::google::protobuf::Message*> allMessages;

while() {
    msgs::sensor::Plot nextMsg;
    ....
    allMessages.append(&nextMsg);
    std::cout << allMessages.at(0)->DebugString();
}
std::cout << allMessages.at(0)->DebugString();

A: nextMsg is a local variable inside the while loop, it will be destroyed when get out of the loop, and then address saved in allMessages becomes dangled. Any dereference on it is just UB.
If you want to use the pointers outside of the loop, you need to new them inside the loop (and delete them at last), or use smart pointers to avoid manual memory management.


text:
Q: emulate dual monitor using a second machine I have monitors of my two machines side by side and I use them both with a single keyboard/mouse using Synergy+ (now hosted at Google Code) which works great.
But is it possible to use the monitor of my secondary machine as the secondary monitor of my primary? I am on XP so from what I understand I cannot just rdc from secondary to this primary. In any case that would be a different session altogether and I would prefer to be able to extend my desktop over the two monitors.
Any solutions or suggestions? Thanks in advance.

A: MaxiVista
I don't know any free solutions unfortunately. I wanted to do something similar myself and settled on MaxiVista after I couldn't find any alternative (short of modifying Synergy myself, which I didn't have the patience for).


text:
Q: cant get list of objects using lambda with condition I have an Entity in the db :
public double? CompletedAtRate { get; set; } = default!;
public string? NettingStatus { get; set; } = default!;

public ICollection<ConvertedQidEntity> IncludedQids { get; set; } = default!;

public DateTime LastUpdate = DateTime.Now;

public bool IsTransfered { get; set; }

public string TransactionEntityGuid { get; set; } = default!;
public int ConversionID { get; set; } = default!;

I'm trying to run the following query but I get an error saying Int does not contain definition for transactionEntityGUID. I want to get the list of all ConvesitionIds:
var listOfInvolvedConversions = db.ConversionEntities
    .Select(f => f.ConversionID)
    .Where(s => s.TransactionEntityGuid = transferGuid)
    .ToList();

transferGuid is an incoming parameter which is  a string
What am I doing wrong?

A: According to @mulkraj: replace the assigment operator = by the equality operator ==.
According to @AlexanderPetrov: Swap Select and Where.
var listOfInvolvedConversionIds = db.ConversionEntities
    .Where(s => s.TransactionEntityGuid == transferGuid)
    .Select(f => f.ConversionID)
    .ToList();


text:
Q: Backbone - performing multiple fetch() before rendering a view I was wondering about the best pattern/approach here. This is a function in my router, so the user hits 'quotes/:id', but for that view to render, I need a list of their projects, customers and currencies. What would be the best way to make sure all 3 fetches() have occurred before trying to instantiate the quotesEdit view? Is it considered bad practice to grab all the information when the user clicks something?
    quotesEdit: function(id) {
        kf.Collections.quotes = kf.Collections.quotes || new kf.Collections.Quotes();
        kf.Collections.projects = kf.Collections.projects || new kf.Collections.Projects();
        kf.Collections.currencies = kf.Collections.currencies || new kf.Collections.Currencies();
        //do a fetch() for the 3 above
        kf.Collections.customers = kf.Collections.customers || new kf.Collections.Customers();
        var quote = kf.Collections.quotes.where({Id: parseInt(id, 10)});
        kf.Utils.ViewManager.swap('sectionPrimary', new kf.Views.section({
          section: 'quotesEdit',
          model: quote[0]
        }));
    }

A: I find a combination of jQuery deferreds and underscore's invoke method solves this elegantly:
//call fetch on the three collections, and keep their promises
var complete = _.invoke([quotes, projects, currencies], 'fetch');

//when all of them are complete...
$.when.apply($, complete).done(function() {
   //all ready and good to go...
});

A: Backbone's fetch returns a jQuery Deferred object (a promise). So you can use jQuery's when function to wait for all of the promises to resolve:

quotesEdit: function(id) {
  kf.Collections.quotes = kf.Collections.quotes || new kf.Collections.Quotes();
  kf.Collections.projects = kf.Collections.projects || new kf.Collections.Projects();
  kf.Collections.currencies = kf.Collections.currencies || new kf.Collections.Currencies();

  //do a fetch() for the 3 above
  var quotePromise = kf.Collections.quotes.fetch();
  var projectsPromise = kf.Collections.projects.fetch();
  var currenciesPromise = kf.collections.currencies.fetch();

  // wait for them to all return
  $.when(quotePromise, projectsPromise, currenciesPromise).then(function(){

    // do stuff here, now that all three have resolved / returned

    kf.Collections.customers = kf.Collections.customers || new kf.Collections.Customers();
    var quote = kf.Collections.quotes.where({Id: parseInt(id, 10)});
    kf.Utils.ViewManager.swap('sectionPrimary', new kf.Views.section({
      section: 'quotesEdit',
      model: quote[0]
    }));

  };

}

I've written a bit about promises and jQuery's when, here:
http://lostechies.com/derickbailey/2012/03/27/providing-synchronous-asynchronous-flexibility-with-jquery-when/
http://lostechies.com/derickbailey/2012/07/19/want-to-build-win8winjs-apps-you-need-to-understand-promises/
that second link is still valid, in spite of the primary subject being Win8 JS

A: Promises! Specifically jQuery.when
You can do something like this:
$.when(
  kf.Collections.quotes.fetch(),
  kf.Collections.projects.fetch(),
  kf.Collections.currencies.fetch()
).then(function(){
  // render your view.
});

jQuery.ajax (and by extension backbone fetch) returns a promise and you can use $.when to set a callback function once multiple promises are resolved.


text:
Q: Tracable anonymous recurring records I have an application where users fill out surveys on a regular basis.
Surveys are sent via e-mail and need to be semi-tracable, meaning, that I need to follow what kind of question categories are sent to each user on each survey. Right now after answering the survey, answers are saved in a separate table and any association to a particular user is removed to guarantee anonymity.
What I would like to achieve is a way where it is not possible to map any anwser with a particular user BUT it is possible to get all answers that any one user has submitted. We want to do this for analysis purposes to track how user's answers change over time, but at the same time preserve complete anonymity on a database level.
Users fill out surveys using several devices so private key storing on their device is not an option.
Application is written in Rails with PostgreSQL, but the solution can also involve other languages if it is not possible in ruby.

A: One of the simple solutions would be feeding a fixed set of user data to a hash function to calculate an identifier for that user, save it into the separate table along with the answers.
This way you'll be able to gather all submissions per user but there will be no relation to the user record.
A drawback is that if you would still want it you can trace a user by calculating all the hashes for your "users" table and associating it with the "answers" table. Unless you give up control over either "users" or "answers" entity to another team/business unit etc.


text:
Q: Get only the children of a clicked div element So I'm building this webpage and I have some photos for slideshow inside divs that open up a modal. I want to get all children of clicked div (myModal). I want to get all divs with class "mySlides" who are the children of a click div with class "myModal". This is my code:

var slideIndex = 1;
    showSlides(slideIndex);

    function plusSlides(n) {
     showSlides(slideIndex += n);
    }

    function currentSlide(n) {
     showSlides(slideIndex = n);
    }

    function showSlides(n) {
     var i;
     var slides = document.getElementsByClassName("mySlides");
     console.log(slides);
     var dots = document.getElementsByClassName("dot1");
     if (n > 3) {
      slideIndex = 1;
     }
     if (n < 1) {
      slideIndex = slides.length;
     }
     for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none";
     }
     for (i = 0; i < dots.length; i++) {
      dots[i].className = dots[i].className.replace(" active1", "");
     }
     slides[slideIndex-1].style.display = "block";
     dots[slideIndex-1].className += " active1";
    }

        ×

smth

1 / 3

Opis slike1

2 / 3

Opis Slike2

3 / 3

Opis Slike3

         <button class="prev1" onclick="plusSlides(-1)">❮</button>
         <button class="next1" onclick="plusSlides(1)">❯</button>

I tried using $(this).children but no luck like that:
function getSlides() {
    var slides1 = $(this).children('img').attr('src');
    console.log(slides1);
}

How can I achieve this? I have multiple reference items in my page all with different 3 images to show on modal open. But I want to select only those that are children to the clicked element (as now it returns me all "mySlides" divs).

A: You can remove onclick="getSlides()" from DOM and Use this Jquery
$('.myBtn').off().on('click',function(){
$(this).next('.myModal').find('.mySlides').each(function(i,v){
    console.log($(v)[0].outerHTML);
   });
});

A: Look at this. You have to pass getSlides(var) a new variable postContainer.  In this case is:

function getSlides(postContainer) {
    $('.'+postContainer+' .mySlides').each(function(){
       var slideSrc = $(this).find('img').attr('src');
       console.log(slideSrc);
    });
}

Lets start again:
Using the self object to find the slides

//Pass the object to the function

function getSlides(dis) {
    //Search from the object, the nexts .mySlides
    $(dis).next().find('.mySlides').each(function(){
       var slideSrc = $(this).find('img').attr('src');
       console.log(slideSrc);
    });
}


text:
Q: Efficient way to parse HTML dump found in the form of string Please deal with this trivial question. It is available in bits and pieces on stackoverflow.
I have HTML dump of a website in the form of String. I want to extract text from the specific tags of it.
In other way, I want to mimic
Document doc = Jsoup.connect(url).userAgent("Mozilla").get();
Elements links = doc.getElementsByTag("cite");

I am not using Jsoup because I don't want it to connect to the website (I have another service for that which returns html dump in the form of text). I found HTMLEditorKit for converting text to HTMLDocument but it doesn't seem to be very easy to use(like Jsoup or HTMLParser) or I am unable to get it.
Any help would be useful.
Thanks.

A: If you have used Jsoup and it worked yet, you should continue using it.
Document doc = Jsoup.parse("<html>...");

should do.
see: The API


text:
Q: how to use compound bash functions from different directories I have some directory e.g. /ice/cream which contains some files that I want to want to sort in size, and then find a minimum value in the largest file; however I want to do this from the parent directory /ice.
The bash line I wrote only works within /ice/cream, i'd like to make it work from /ice, I tried
awk 'BEGIN {min = 0} {if($7<min) min=$7} END {print min}' $(ls -lS cream/ | head -n 2 | awk '{print $9}')

which does not work because awk doesnt know the path to the file found by the second $() function; please help! Cheers

A: A safer way to get the largest file; the call to stat may differ depending on your implementation:
max_file () {
    local max_size size
    max_size=0
    for f in "$1"/*; do
        size=$(stat -c %s "$f")
        if (( size > max_size )); then
            max_file="$f"
            max_size="$size"
        fi
    done
    echo "$max_file"
}

awk '...' "$(biggest_file cream/)"

A: Your ls pipeline is way too complicated, and you need a * after the dir/ to get the relative name output:
awk 'BEGIN {min = 0} {if($7<min) min=$7} END {print min}' $(ls -S cream/* | head -1)

A: As first answered by @Etan Reisner in comment, the line was missing a *; working code is:
awk 'BEGIN {min = 0} {if($7<min) min=$7} END {print min}' $(ls -lS cream/* | head -n 1 | awk '{print $9}')

Thank you.


text:
Q: Writing a vector has a linear combination of two vectors: is the solution unique? Problem:
Consider the vectors $u = (1,2,3)$ and $v = (2,3,1)$ in $R^3$. Write
$w = (1,3,8)$ as a linear combination of $u$ and $v$.
Answer:
$$ c_1( 1,2,3) + c_2( 2,3,1 ) = (1,3,8) $$
Now to find $c_1$ and $c_2$ we setup a matrix.
$$
\begin{bmatrix}
1 & 2 & 1 \\
2 & 3 & 3 \\
3 & 1 & 8
\end{bmatrix}
\sim
\begin{bmatrix}
1 & 2 & 1 \\
0 & -1 & 1 \\
0 & -5 & 5
\end{bmatrix}
$$
This gives us $c_2 = -1$.
\begin{align*}
c_1 + 2c_2 &= 1 \\
c_1 + 2(-1) &= 1 \\
c_1 &= 3 \\
\end{align*}
Hence the solution is $w =  3u - v$. This answer matches the back of the book; however it seems to me that there should be more than one solution. Is this solution unique?

A: If $\{ v_1, v_2 \}$ is linearly independent then the linear combinations are unique. This is also true in the case $\{v_1, \ldots, v_n \}.$
For see this suppose we have $w=c_1 v_1 + c_2 v_2 = d_1v_1 + d_2v_2$. Then
$$ (c_1 - d_1) v_1 + (c_2-d_2)v_2=0. $$
As $\{v_1, v_2\}$ is linearly independent we know that $c_1-d_1=0$ and $c_2 - d_2=0$, i.e. $c_1=d_1$ and $c_2=d_2$.

A: To check for uniqueness, the basic approach is to assume there exists two different solutions, and see what happens. If the problem is truly unique, then you will run into a contradiction.
Suppose there were two combinations, $c_1, c_2$ and $d_1, d_2$. Then,
$$(1,3,8) = c_1(1,2,3) + c_2(2,3,1) = d_1(1,2,3) + d_2(2,3,1)$$
This gives,
\begin{align}
c_1 + 2c_2 &= d_1 + 2d_2 \\
2c_1 + 3c_2 &= 2d_1 + 3d_2 \\
3c_1 + c_2 &= 3d_1 + d_2 \\
\end{align}
Rearranging, we get
$$ c_1 - d_1 = 2(d_2 - c_2) = \frac{3}{2} (d_2 - c_2) = \frac{1}{3} (d_2 - c_2) $$
If the two combinations are different (i.e. $c_1 \neq d_1, c_2 \neq d_2$), then the above yields a contradiction that $2 = \frac{3}{2} = \frac{1}{3}$. To avoid this contradiction, the two combinations must be the same. Therefore, the problem has at most one unique solution.


text:
Q: Restlet using Get and Post Methods Hiiii,
I am developing a small app using Restlet 2.0 API..
I want just to know how to create a URI which accepts more than one parameter for insert query.
Ex:
router.attach("/{patient}/insertpatient", insertpatient);

I want to insert all the info about the patient using POST.
Or Search by ID and address for instance using GET.
thanks,

A: For the "insert patient" operation, I'd suggest something like a POST to /patients (if the server generates the patient ID) or a PUT to /patients/{patient-id} (if the client generates the patient ID).  Either way, the body of the message would contain all of the input data needed to create a new patient entity.  Two simple options for serializing the data would be as a URL-encoded form or as JSON.
Lookup by by ID could be a simple as a GET on /patients/{patient-id}.  Lookup by address could also be a GET, possibly using a URL-encoded query parameter.  For example, you could fetch the patient at address "123 Main Street, apt 4, Anytown, USA, 98765" with a GET on /patients?addr=%20Main%20Street%2C%20apt%204%2C%20Anytown%2C%20USA%2C%2098765


text:
Q: What percent of Fry's DNA comes from his Grandfather in Futurama? In the episode Roswell That Ends Well Fry's abnormal parentage is revealed. During the commentary David X Cohen challenges viewers to describe that parentage. I would expect to see all possible answers to the question. Those answers would be:

 In a predestinous universe, that is one where Fry always got some % of his DNA from himself; and in a multidimensional universe, where Fry would have at first gotten his DNA from his proper grandfather, but in all future universes somehow gets those same pieces of his DNA from himself. Also, please address the origin of his Y chromosome.

I have seen pieces of this puzzle discussed elsewhere online, however I haven't seen a fully-realized solution.

 So, What percent of Fry's DNA really does come from himself? And where does his Y chromosome come from?

A: It's been a while since I watched the episode, so you'll have to forgive the fuzzy details. I believe the grandfather in question is Fry's paternal grandfather (father's father), but please correct me if I'm wrong. I have also not listened to the DVD commentary you refer to, so you may well have insight that I lack.
First, the science.
As for the genetics of family; let's talk about general chromosomes, then sex chromosomes. There are 23 pairs of chromosomes in the human body; and one half of each pair of chromosomes comes from each parent (ie 23 single chromosomes from each parent). There are exceptions and fringe cases (Down's Syndrome, for example) but these are unimportant for the purposes of this discussion.
Thus, 50% of Fry's DNA comes from Fry's father, and 50% of Fry's father's DNA comes from HIS father. What is interesting is the way in which genes mutate before they are passed on to offspring. Essentially, in each pair of chromosomes, they can swap around parts of themselves (a process known as crossing over); so that each chromosome the parent supplies to his child is a mixture of both the chromosomes of the parent. Thus a parent is extremely unlikely to pass on his father's or his mother's copy of the chromosome as he received it.
This diagram from wikipedia should help visualise the process a bit.
So (excluding sex chromosomes) it is impossible to say how much of fry's DNA comes from his grandfather. But we can assume that of the DNA Fry's father passed on to him, around 50% of that will have come from Fry's grandfather, and the rest from his grandmother; although the exact percentage could be much less or more. You will note that in the wikipedia meiosis diagram, each of the 4 gametes produced has a different composition of red and blue DNA; which is what I am driving at.
But statistically speaking, around 25% of the DNA in Fry's chromosomes comes from his grandfather, or more correctly, around 50% of the DNA in the chromosomes Fry obtained from his father comes from his grandfather.
With sex chromosomes, it's a different story. Each person contains one pair of sex chromosomes; of which there are two types: X and Y. In a normal human (we will again discount rare genetic disorders, such as Kleinfelter's Syndrome), a male has an XY configuration, and a female has an XX configuration. The important part of sex chromosome inheritance is that a male's X chromosome always comes from his mother, and his Y chromosome always comes from his father. This is an important element of sex-linked genetic diseases; which tend to be much more common in males because they only have a single X chromosome. So Fry's Y chromosome will have come entirely from his father, who will have gotten his Y chromosome from HIS father; Fry's grandfather.
So, since we can assume Fry, his father, and his (original) grandfather are all normal human males, it is safe to say that Fry's Y chromosome is that of his paternal grandfather.
That is where the actual science ends. Now we turn to science fiction to deduce the identity of Fry's paternal grandfather. And that depends on the theory of time travel.
If I'm missing any major theories on time-travel please tell me, but I think these are the relevant two options.
First option is that history is fixed, and that travelling back in time to the past and changing something is impossible, because it already happened that way. In this theory, Fry is his own grandfather. Enos is irrelevant, because he never fathered Fry's father;  it was Fry himself who fathered his father all along. In this version of events we quickly reach a paradox. Fry gave his Y chromosome to his son, who gave it to fry, who gave it to his son, and so on infinitely. The Y chromosome has no origin. Likewise for around 25% of Fry's DNA.
The second option is that Fry's personal history is fixed, and that changing something in the past will create a new "alternate timeline". So Enos is Fry's paternal grandfather, Fry travels back in time and kills Enos, and copulates with his paternal grandmother. The result of this copulation is irrelevant to Fry's genetics and Fry's timeline, because he has already been born; and already contains Enos's DNA. The paradox in this version of events is that if Fry returns to his original timeline, then the events of Roswell in the past are ignored completely; though this would mean that Bender was never buried there waiting to be rescued in the present. Whereas, if Fry returned to the new alternate timeline's Future, he would never have been born because he killed his grandfather; and the offspring of his encounter with his grandmother (if any) would not have been Fry's father himself.
A third option is that the original Fry came from the second theory of events; and then conceived a first theory Fry's father when  he travelled into the past. The resulting Fry would then conceive another Fry's father when HE travelled into the past, and so on. This version of events seems to resolve most paradoxes. There is an ultimate origin of Fry's DNA (Enos), so we know where the original Fry's DNA came from; and we know how that first Fry would pass on that DNA to any "next generation" Fry's. We also have a "multiverse" theory allowing for the branching of timelines, which allows for a rational explanation of how Fry could in fact be his own grandfather; although the question of which timeline Fry returns to after Roswell is still not answered. If the Fry who travelled back in time returned to his own timeline, Bender would not have buried himself in New Mexico for the gang to find in the present. But if he returned to a newly-altered timeline, would he still be the genetic original Fry, or would he be a newly altered Fry who was the result of the encounter with his grandmother?
I don't believe there is (or was meant to be) a definitive answer, but puzzling it out certainly helps make it one of Futurama's strongest episodes!
If anyone can find a flaw in my science or in my time travel logic, please let me know!

A: I do not know much about human evolution and DNA. But I will try to explain to the best of my knowledge. Half of Eno's DNA and half of Mildred Fry's DNA would be in the original Philip J. Fry's DNA(Fry1). Since it now would be Fry1 and Milred Fry. Half of Fry1's DNA would be used which would make it between 0%-49% of Eno's DNA.(I say 49% because if it was exactly 50% then it would go as normal.)


text:
Q: Vue JS Ajax Calls I am trying to make the change from jQuery to Vue.js and am having some difficulty running an Ajax Call using vueresource. Below is a sample script I am using, with both jQuery and Vuejs. Both trying to access the same ajax call. The jQuery call works, the vuejs call doesn't. The sendAjax method is being called because the first 2 alerts show - then nothing.
Edit - this is only causing an error while running the Ajax call through Wordpress. Outside of WP, it does work. Any ideas??
<!DOCTYPE html>
<html>
    <head>
        <title>Vue Resource</title>

        <script src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js"></script>
        <script src="https://cdn.jsdelivr.net/vue/latest/vue.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/vue-resource@1.5.1"></script>
    </head>

    <body>
        <button id="jQueryAjax">Jquery AJAX</button>

        <div id="myvue">
            <button @click.prevent="sendAjax()">AJAX</button>
        </div>

        <script>
            let AjaxUrl = "http://localhost:8888/mySite/wp-admin/admin-ajax.php";
            const postData = { action: 'my_ajaxcall', function: 'AjaxTest' };

            Vue.use(VueResource);

            const ajax_app = new Vue({
                el: '#myvue',
                methods: {
                    sendAjax() {
                        alert("VueAjax");
                        alert(JSON.stringify(postData));

                        this.$http.post(AjaxUrl, postData).then(res => {
                          alert(JSON.stringify(res));
                        });
                    }
                }
            });

            $("#jQueryAjax").click(function() {
                alert("jQueryAjax");
                alert(JSON.stringify(postData));
                alert(AjaxUrl);

                $.ajax({
                    type: 'POST',
                    url: AjaxUrl,
                    data: postData,
                    dataType: 'json',
                    success: function(data) {
                        alert(JSON.stringify(data));
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert("Error");
                    }
                });
            });
        </script>
    </body>
</html>

A: You AJAX call probably encounters an error and you handle only the successful calls. Please extend your sendAjax function like this:
this.$http.post(AjaxUrl, postData).then(res => {
    alert(JSON.stringify(res));
}, err => {
    alert(err);
});

Now an error should be alerted.
BTW: It is better to use console.log() instead of alert(), it is much more readable and you won't have to confirm every alert.

A: After @mbuechmann pointing me to be able to see the actual error, I was able to determine that the issue I was having was actually to do with Wordpress. In order to use the Wordpress Ajax handler, you need to send an action to the REQUEST header. To do this, you need to send FormData, and without sending headers.
This code was found in this question : Custom Shortcode AJAX 400 Bad Request and enabled me to get my Fetch working with Wordpress.
var data = new FormData();

data.append( 'action', 'aj_ajax_demo' ); data.append( 'nonce', aj_ajax_demo.aj_demo_nonce );

fetch(aj_ajax_demo.ajax_url, {
    method: 'POST',
    body: data, }).then(response => {
    if (response.ok) {
        response.json().then(response => {
            console.log(response);
        });
    } });


text:
Q: Create a html element and find a div by id before adding in DOM I'm trying to find a the div with id old-price  and remove it, before inserting in the document ( before main.appendChild(newDiv);).
p.s.: Can't use JQuery
I already tried this:

newDiv.getElementById("old-price").innerHTML = "";

but it does not work
Any help will be appreciated.

var divString = "

 Black Shoes with red stripes
                  250
250
         BUY

 ";

var newDiv = document.createElement('div');
newDiv.innerHTML = divString;
//remove the div with id old-price
var main = document.getElementById("main");
main.appendChild(newDiv);

A: use newDiv.querySelector("#old-price").remove().

var divString = "

 Black Shoes with red stripes
                  250
250
         BUY

 ";

var newDiv = document.createElement('div');
newDiv.innerHTML = divString;
//remove the div with id old-price
newDiv.querySelector("#old-price").remove()
var main = document.getElementById("main");
main.appendChild(newDiv);

A: Try this:
var divString = "

 Black Shoes with red stripes
                  250
250
         BUY

 ";
var newDiv = document.createElement('div');
newDiv.innerHTML = divString;

//remove the old price
newDiv.getElementsByClassName("old-price")[0].innerHTML="";

var main = document.getElementById("main");
main.appendChild(newDiv);

A: You can try to hide it by this:
document.getElementById("old-price").style.display = 'none';

Or remove it as child from parent element (replace parent ID):
document.getElementById("parentID").removeChild("old-price");


text:
Q: How to match both .ASM and .S in Emacs regular expression for auto-mode-alist?
How to match both .ASM and .S in Emacs regular expression for auto-mode-alist?

I've tried to write a regular expression as below, but it doesn't work, i.e. .asm and .s files are not recognized as belonging to nasm-mode.
(require 'nasm-mode)
(add-to-list 'auto-mode-alist '("\\.\(ASM\)\|S\\'" . nasm-mode))

However, the simplified version matching only .asm works just fine:
(require 'nasm-mode)
(add-to-list 'auto-mode-alist '("\\.ASM\\'" . nasm-mode))

Also, why do I use uppercase characters? (I've followed the description in nasm-mode.el).

A: Direct answer to the question (always use double \, as string interpretation "uses" the first and regex code the second):
(add-to-list 'auto-mode-alist '("\\.\\(ASM\\|S\\)\\'" . nasm-mode))

Alternative way I would use
(add-to-list 'auto-mode-alist '("\\.ASM\\'" . nasm-mode))
(add-to-list 'auto-mode-alist '("\\.S\\'" . nasm-mode))

A: (add-to-list 'auto-mode-alist `(,(concat (regexp-opt '(".ASM" ".S")) "\\'") . nasm-mode))

regexp-opt takes a list of strings (not regexps), and builds a regexp that matches any of those strings.  It's kind of overkill here, but it's great for matching longer lists of strings.


text:
Q: Apache Tika exclude some html tags I am testing Apache Tika REST Api via python for parsing HTML files. Everything works except one thing. Interior of <noscript> tags is also parsed as text and I am having some css styling content in my text, which is undesirable. Also, body of  <div style="display:none"> is extracted as well. Is there a way to blacklist some html tags in the Tika rest API?

A: I don't have an immediate solution, but the request seems reasonable so please open an issue on our JIRA for the team to discuss: https://issues.apache.org/jira/projects/TIKA/summary


text:
Q: c programming - printing sentences this is my first time using this site as well as learning c programming.
I'm trying to write a code which lets a user type in a sentence and the code prints it back out.
My attempt:
#include<stdio.h>
int main()
{
    char array[1000];
    printf("Please enter a phrase: ");
    int index = 0;
    while(array[index]!= '\0')
    {
        scanf("%c",&array[index]);
        ++index;
    }
    index = 0;
    while(array[index]!= '\n')
    {
        printf("%c",array[index]);
        ++index;
    }
}

I can't find the reason to why this code does not work.

A: You can get expected output using your concept also.. Try something using following code.
#include<stdio.h>
int main()
{
char array[1000];
printf("Please enter a phrase: ");
int index =0;
    scanf("%c",&array[index]);
while(array[index]!='\n')
{
    scanf("%c",&array[++index]);
}
index=0;
while(array[index]!= '\n')
{
    printf("%c",array[index]);
    ++index;
}

printf("\n");
}

A: Okay, so first and foremost you'll need to initialize all your array. If you don't, the user input will print along with lots of meaningless garbage.
Secondly, the test portion of your first while loop checks for a null character which will never exist because "array[]" is just a simple character array (not a string) therefore, a call to scanf() doesn't insert the null character at the end. This causes an infinite loop.
Thirdly, your first while loop should be a do-while so that you first read a character, then test the character, otherwise if the "index" variable increments first...
Lastly, I posted the code that i used to get it to run using the method that you chose. However, as an alternative to the method you chose, the c standard library has the gets() function, which will allow you to read an entire line of input and return the string entered (actually it returns a pointer to the character array created but i think you catch my drift), and the puts() function which prints a string pointed to by the pointer used as an argument.
For more info on this problem in general, including gets() and puts(), refer to "C Programming A Modern Approach" by K.N. King, Chapter 13: Strings.I hope this helps.
Happy Coding!! :)
#include <stdio.h>

int main()
{
    int index = 0;

   char array[1000];

    while(index < 1000){
        array[index] = '0';
        index++;
   }

    printf("Please enter a phrase: ");

    index = 0;

    do {
            scanf("%c", &array[index]);

        } while(array[index] != '\n' && index++ < 1000);

    index = 0;

    while(index < 1000)
    printf("%c", array[index++]);

}

A: I think your looking for this:
#include<stdio.h>

int main() {

    char array[1000];
    printf("Please enter a phrase: ");

    scanf ("%[^\n]%*c", array);

    printf("\n%s", array);

    return 0;

}


text:
Q: Prediction Probabilty question My questions concerns the probability/ likelihood of an event occurring again.
In a horse race, a horse has had 10 races.
It's speed figures have been 50, 74, 65, 58, 65, 80, 76, 64, 81, 78.
It is 5yrs old (they don't improve with age)
Question 1
All other things being equal, what is the likelihood that it will equal or run a speed figure better than its best (the 81 speed figure) or even an 80 in its 11th race today?
Question 2
What will it's likeliest next figure be (today - in its 11th race)?
If the question is unanswerable with the given information, what other data might I need to answer /  create a formula that can predict/ provide an estimation of  such an outcome?
I am a newbie to anything other than basic arithmetic.
Thank you

A: I know nothing about horses or their speeds. The question is not answerable
without additional information or assumptions.
The sample mean and standard deviation of the past running times are 69.1 and 10.32,
respectively. If we assume that the horse's next running time $X$ will be normal
with population mean 69.1 and standard deviation 10.32, then
$P(X > 81) = 1 - P(X \le 81) \approx 0.12.$ (You could get that probability by standardizing and using a printed normal table; I used R statistical software below.)
mean(x); sd(x)
## 69.1
## 10.32204

1 - pnorm(81, 69.1, 10.32)
## 0.1244345

However, even if it is true that running times are normal, the sample
mean and standard deviation of only ten runs would not give very reliable
estimates of population mean and standard deviation. So this is more wild
speculation that statistical prediction.


text:
Q: How to add image to loop from adv custom fields and custom post type  <?php
          // the query
          $loop = new WP_Query( array( 'post_type' => 'features', 'orderby' => 'post_id', 'order' => 'ASC' ) ); ?>

            <?php if ( $loop->have_posts() ) : ?>

              <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>

               <img src="<?php the_field('image'); ?>">

              <?php endwhile; ?>

              <?php wp_reset_query();  // Restore global post data stomped by the_post(). ?>
          <?php else : ?>

<?php _e( 'Sorry, no posts matched your criteria.' ); ?>

        <?php endif; ?>

I have a problem with adding image to loop.
I create an custom image field assigned to custom post type "features" and I want to add this image field to loop.
This way is bad becouse in console in src="" is:
http://localhost/konkursy/wp-content/uploads/2019/01/smartphone_samsung.png, http://localhost/konkursy/konkursy_internetowe/caruzela-1/smartphone_samsung/, balbla, 1, sad, asd, smartphone_samsung, inherit, 56, 2019-01-02 10:56:12, 2019-01-02 12:06:21, 0, image/png, image, png, http://localhost/konkursy/wp-includes/images/media/default.png, 200, 150, Array">
I don't know how to do this with array becouse this field is assigned to post type not to template page
<?php
$image = get_field('image');
?>
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />

This way is not working
Maybe someone who wants to help me can help this:
https://www.advancedcustomfields.com/resources/image/

A: Problem solved.
In adv custom field options you can change array to URL;
or second option: add array to loop not to WP_Query like (like I so far)


text:
Q: How are the wolfram alpha pikachu curve and others generated? If you type in "pikachu curve" or other famous fictional characters on wolfram alpha it generates a function to trace out the curve that resembles the character. See http://www.wolframalpha.com/input/?i=pikachu+curve .
Does anyone know how these curves are generated? It seems that this has been done for several characters so I doubt that they worked out the details by hand.
Related: Is this Batman equation for real?

A: Visit Wolfram's blog. It has many nice applications of Mathematica.


text:
Q: reduce passwords I must type How can I reconfigure my MBP to require me to type username & password only once, going all the way from shut down to functional?
I think industry-standard naming is confusing in this area: the term "login" is ambiguous, sometimes meaning "the username," sometimes meaning "the username and password," and sometimes meaning "the act of entering username and password into the system." I will try to use these terms consistently:

*

*username means the string which identifies the user

*password means the string which proves the human at the keyboard is the claimed user

*credentials means the pair of strings (username, password)

*login means the act of entering credentials

I have seen various similar MBPs exhibit different behavior in this regard: some do it as desired (one login); some require two logins; some require three. I have learned, through search and experiment, that the "3" case can be improved to "2" by ensuring that the account password matches that of the keychain item which is (also) named "login."  So far, so good.
I tried essentially the same trick to eliminate the second login: I made the FileVault 2 credentials match the account credentials. On one computer, this worked: I can now log in to this computer via a single typing of credentials. But on another computer, this did not work: all credentials are the same, yet it takes two logins to get in.
I believe OS X normally keeps all these credentials in sync, so the fact that they were out of sync to begin with may be significant. Unfortunately, in considering the computer that works as I want, it is impractical to recover the history of how it got there, due to limited expertise of the owner.

A: This is pretty simple.
In System Preferences

*

*go to the Users & Groups Preference Pane

*click on Login Options

*click to unlock (bottom left) if needed and authenticate

*verify Automatic Log in is on the user you wish to use

*go to the Security & Privacy preference Pane

*enable your user for FileVault

*reboot

You will select your user from the picker and then enter your password one time and then you should be logged in. If you have a bad user, you can add a new admin user, let it unlock FileVault - remove the problematic user but do not delete the home folder. Then rename the /Users/whatever (deleted) to be the short name you wish and re-create the user. Be sure the keychain is unlocked when that new user password is set up when you log in. Authenticate the new user to FileVault and remove the "new admin" user from above.


text:
Q: get Ubuntu Linux's grep to only get emails from a certain domain in a file? I'm sifting through a .asc file trying to get all the instances of emails registered at a certain domain, say 'abc.def' just as an example.
I try this:
grep -o ,*@abc.def somefile.asc

which does nothing, although I know for a fact that such emails exist in the file.
Is something wrong with my regular expression? Keep in mind that the file is essentially a csv file, hence the comma at the front. I've tried escaping it with \ but still no results.

A: grep -o ,*@abc.def somefile.asc

This will find zero or more commas followed by @abc then any character (since dot is unescaped) and then def in any line.
What you probably want is this:
grep -oE '[^[:blank:]@,]+@abc\.def' somefile.asc

*

*[^[:blank:]@,]+: Uses a negated bracket expression to match any character that is not white-space and @ and @

*@: Match literal @

*abc\.def: Match literal text abc.def (note how dot must be escaped to match literal .)


text:
Q: Communicate with running service I've written my first windows service in .Net. Can I communicate with this service from other .Net application? Can I execute methods on a service object from remote .net applications?

A: Yes. A Windows Service (or just about any other kind of .NET program) can host a WCF Service. Clients can call this service in order to make requests.

A: WCF is definitely the .NET way of doing this.  If you are not familiar with WCF, I would suggest starting with this dnrTV video:  Keith Elder Demystifies WCF.  It does a pretty decent job of explaining how simple WCF is.  For your situation, just host the WCF service in the OnStart() method of your Windows service.  At that point, any remote application can connect to your WCF service hosted in your Windows service.
When you feel comfortable with WCF itself, you can check out this dnrTV video:  Extreme WCF.  This one gives you some best practices of how to "do" WCF inside Visual Studio.
To buttress these two videos, check out Juval Lowy's website, IDesign.net.  Juval has a lot of examples and usable WCF code that's freely available.


text:
Q: Android IME - how to detect entering a View? I am trying to write a custom IME for the Android OS. However, I cannot figure out how to detect when the user is entering e.g. an EditText.
I have already tried overriding some of the on...() methods of InputMethodService to no avail.
The documentation hasn't been particularly helpful to me here, I'm having a hard time understanding the description of the InputMethodService class.

A: Use TextWatcher to find out when a user is entering text into an EditText. Otherwise, for any other view, you should be able to override the onFocusChanged method.

A: Just for documentation purposes: I found the answer myself.
When a view is entered, the InputMethodService's onStartInput(EditorInfo attribute, boolean restarting) method is called. If the EditorInfo's InputType is != 0, the view is editable, it seems.


text:
Q: How will I parse a tag with space in its value using antlr? I have the following grammer.
meta
    : '<' NAME '>' TEXT '</' NAME '>'
    | '<' NAME S* attribute* '>';

dl : '<' NAME '><' TEXT '>' dt* '</' NAME '><' TEXT '>';

dt : '<' NAME '><' NAME S* attribute* S* '>' TEXT '</' NAME '>';

attribute : attributeName '=' attributeValue;

attributeName : NAME;

attributeValue : VAL;

NAME : [A-Z0-9_-]+;

VAL : '"'.*?'"';

TEXT : [A-Za-z0-9:\/\.@\-;\s*]+;

S : [ \t\r\n]+ -> skip;

The string is
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<TITLE>Abcd</TITLE>

Abcd

Foo bar

I am getting the following error:
ParseError extraneous input 'bar' expecting '</'  clj-antlr.common/parse-error (common.clj:146)

The problem is that the space is skipped so when Foo bar has a space it is giving an error. But if I am not skipping the space I get another error in the META parsing. (The S* is not required when skipping spaces).
ParseError extraneous input ' ' expecting {'>', NAME}
mismatched input '>' expecting '><'
mismatched input '<' expecting {<EOF>, COMMENT, S}  clj-antlr.common/parse-error (common.clj:146)

Here is my tokens file generated by antlr:
T__0=1
T__1=2
T__2=3
T__3=4
T__4=5
DTD=6
COMMENT=7
NAME=8
VAL=9
TEXT=10
S=11
'<'=1
'>'=2
'</'=3
'><'=4
'='=5

And when I run using grun I get the following, but I don't see any errors in the token reported. It is similar to the grammar I defined. How can I accept spaces in tag values?
$ grun MyGrammer r -tokens
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
[@0,0:0='<',<1>,1:0]
[@1,1:4='META',<8>,1:1]
[@2,5:5=' ',<11>,1:5]
[@3,6:15='HTTP-EQUIV',<8>,1:6]
[@4,16:16='=',<5>,1:16]
[@5,17:30='"Content-Type"',<9>,1:17]
[@6,31:31=' ',<11>,1:31]
[@7,32:38='CONTENT',<8>,1:32]
[@8,39:39='=',<5>,1:39]
[@9,40:65='"text/html; charset=UTF-8"',<9>,1:40]
[@10,66:66='>',<2>,1:66]
[@11,67:67='\n',<11>,1:67]
[@12,68:67='<EOF>',<-1>,2:0]
No method for rule r or it has arguments

Thanks.

A: If you put a space between foo and bar the lexer produces it as  two Tokens (of type TEXT) but the grammar states that only one name token is allowed. To solve your problem you simply have to allow a few TEXTs in a seqnece via the plus-operator:
dt : '<' NAME '><' NAME S* attribute* S* '>' TEXT+ '</' NAME '>';

Also notice that you might run into problems as the Lexer will convert quite a few inputs in NAMEs and not in TEXTs as they both can match the pattern [A-Z0-9]+


text:
Q: Laravel job executing real time without queue being started Running on Laravel 5.8
I am creating a large number of Jobs which I believe should be executed once the queue has been initiated.
My issue is that the jobs get executed then and there when I haven't even started the queue.
They are not even being inserted in to the jobs table created by the migration.
Below are the settings and the piece of code I believe is relevant. Please let me know if more info is needed.
On a fresh installation:
php artisan queue:table
php artisan migrate

.env file
QUEUE_CONNECTION=database

Created the queuedtask
class FulfillmentTask implements ShouldQueue{
//code here
}

Controller
use App\Jobs\FulfillmentTask;

//rest of the class here

public function somefunction(Request $request){
//some code here
//read csv file
foreach ($fileContents as $row){
            FulfillmentTask::dispatch($orderId, $client, $request->sendEmail)->onQueue('database');
        }
}

Issue is the FulfillmentTask is executed without the queue:work command being given in the terminal.
Any idea on why this is happening?

A: "database" is a queue connection. Pls dispatch your job to that connection.
FulfillmentTask::dispatch($orderId, $client, $request->sendEmail)->onConnection('database');

And that seems to be the default connection so you just dispatch the job.
FulfillmentTask::dispatch($orderId, $client, $request->sendEmail);


text:
Q: Parameterising the intersection of a plane and paraboloid Suppose we have the paraboloid $z=x^2+y^2$ and the plane $z=y$. Their intersection produces a curve $C$, and certain surfaces bounded by it, for example the disc $S$ which directly fills the area of $C$ and the paraboloid $S'$ given by $z=x^2+y^2$ which extends from $C$ downwards and is bounded by $C$.
My question is on how to parameterise these objects. My initial instinct is to substitute one equation into the other giving the circle $(y-\frac{1}{2})^2+x^2=\frac{1}{4}$. Now I could go ahead and parameterise this circle using polars or even do integrals directly using $x$ and $y$. But this gives the projection of the intersection of the plane and paraboloid in the xy-plane. But I have not directly parameterised $C$. Since the $z=y$ plane makes a $45$ degree angle with the xy-plane, I think that we can introduce a factor of $\sqrt2$ into our parameterisation, but I would like to know if there is a way to directly parameterise $C$ (and also the surfaces $S$ and $S'$)?
Note my question is similar to this one except instead of being level, my disc is slanted (and I would also like to find out how to parameterise the 'bowl shaped' surface).
Many thanks for any help.

A: The surfaces intersect when $y = x^2 + y^2$ so the curve of intersection is
$$ C = \left \{ (x, y, z) \, | \, \left( y - \frac{1}{2} \right)^2 + x^2 = \frac{1}{4}, z = y \right \}. $$
Assume for a minute that you would have the equation $x^2 - \left( y - \frac{1}{2} \right)^2 +  = \frac{1}{4}$ in $\mathbb{R}^2$. This is the equation of a circle with radius $\frac{1}{2}$ centered at $\left( 0, \frac{1}{2} \right)$. To parametrize this circle, you can use polar coordinates centered at $\left( 0, \frac{1}{2} \right)$. Namely, let
$$x = \frac{1}{2} \cos \theta, \,\, y = \frac{1}{2} + \frac{1}{2} \sin \theta = \frac{1}{2}( 1 + \sin \theta)$$
and then the circle is described by
$$\left \{ \frac{1}{2}(\cos \theta, 1 + \sin \theta) \, | \, \theta \in [0,2\pi] \right \}.$$
Returning to your original problem, you can do the same and then use the equation $z = y$ to get the "slanted circle"
$$ C = \left \{ \frac{1}{2} \left( \cos \theta, 1 + \sin \theta, 1 + \sin \theta \right) \, | \, \theta \in [0, 2\pi] \right \}. $$
Note that this curve is actually an ellipse on the $z = y$ plane and not a circle (precisely because you intersect the paraboloid with a slanted plane). Only the projection of this ellipse to the $xy$ plane results in a circle.

A: Let,
$$y-\frac{1}{2}=\frac{1}{2}\sin (\theta)$$
$$y=\frac{1}{2}(\sin (\theta)+1)$$
$$x=\frac{1}{2}\cos (\theta)$$
That way $(y-\frac{1}{2})^2+x^2=\frac{1}{4}$.
With $\theta \in [0,2\pi]$. Because we also intersect $z=x^2+y^2$. Then,
$$z=x^2+y^2$$
$$=(\frac{1}{2}(\sin (\theta)+1))^2+(\frac{1}{2}\cos (\theta))^2$$


text:
Q: Cannot refresh provisioning profiles in Xcode after changing Apple ID password I am an individual developer signed up with both the iOS and Mac development programs.  My account is paid up and in good standing.  Recently when logging into iTunes Connect, I was told that my password was too old and was asked to change it, which I did.  I also decided to set up two factor authentication on my Apple ID while I was at it.
Unfortunately I can now no longer refresh my provisioning profiles in Xcode (5.0.2 (5A3005)) I get the error
An unexpected error occurred. Please try again.  If the problem persists, please contact Apple Developer Program Support.
https://developer.apple.com/support

(before you ask, yes I remembered to change the password in Xcode preferences)
In Console I see the following error:
12/10/13 12:51:30.769 AM Xcode[34131]:  DeveloperPortal: Completed request ABD4EE26-85F8-4053-BD5E-DFCF0E451638 (failure): {
    "DTDK_Platform" = ios;
    creationTimestamp = "2013-12-10 08:51:30 +0000";
    protocolVersion = P5Y9MG;
    requestId = "ABD4EE26-85F8-4053-BD5E-DFCF0E451638";
    requestUrl = "http://developerservices2.apple.com/services/P5Y9MG/ios/listProvisioningProfiles.action?clientId=XABBG36SBA";
    responseId = "a035c476-1a3d-40c2-bf69-d32109f9ee3c";
    resultCode = "-1";
    resultString = ObjectNotFoundException;
    teamId = TJHY9SDE3V;
    userLocale = "en_US";
    userString = "An unexpected error occurred. Please try again.  If the problem persists, please contact Apple Developer Program Support.\nhttps://developer.apple.com/support";
}

I have tried deleting my account from Xcode Preferences and re-adding it from scratch, but that does not help at all.  FYI I can log in to the developer.apple.com website just fine, access the member center, certs/IDs/profiles, forums, etc.  No problems.  I can also log into iTunes Connect perfectly.  My certificates and private keys are all in Keychain Access and are valid (i.e. not expired, etc.)
I'm at my wit's end here.  Does anyone have any ideas as to what's going on here?  Is this something that I need to use one of my 2 developer technical support incidents on?


text:
Q: Why ajax method calls error function? I have jquery script, which sends ajax request to servlet. It works, it posts text data to servlet correctly, but then it calls error function, instead of success function(I checked, servlet send back to ajax not null string).
Why ajax method calls error function?
Here's code of script
    $(document).ready(function () {
        $("#login-button").click(function () {
            var userPassword = $("input#userPassword").val();
            var userLogin = $("input#userLogin").val();
            $.ajax({
                type: "POST",
                url: "http://localhost:8181/library/login",
                data: {login: userLogin, password: userPassword},
                dataType: "text",
                success: function (data) {
                    if (data == "1") {
                        document.location.href = "http://localhost:8181/library/workshop.html";
                    }
                    if (data == "2") {
                        document.location.href = "http://localhost:8181/library/library.html";
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert("Error report\n" + "jqXHR = " + jqXHR + "\n" + "textStatus = " + textStatus + "\n" +
                            "errorThrown =  " + errorThrown);
                }
            });
        });
    });

Here's code of servlet
    public class LoginServlet extends HttpServlet {

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    PrintWriter out = response.getWriter();
    String login = request.getParameter("login");
    String password = request.getParameter("password");
    SocketConnection.output.println("log_in " + login + " " + password);
    out.print(SocketConnection.input.readLine());
    out.close();
        }

    }

The textStatus value is error, the errorThrown value is void, in the error report.

A: if it is returning status 200
your function contains the following setting
dataType: "text",

it might be not sending the text. just try to remove this setting and I hope it will work fine


text:
Q: How send data to php with ajax on button click i have products on my website and i made ajax call to insert product to shopping cart, but there is problem with clicking button. when i click on first product in list everything works but other product buttons do not react
    <?php foreach ($products as $product):?>
       <?php if($product['kateg'] == "men"):?>

<?php echo $product['dasax']?>

Old price: <?php echo round($product['fasi1'], 2)?> GEL

New Price: <?php echo round($product['fasi2'], 2)?> GEL

        <input type="hidden" value="<?php echo $product['id']?>" id="product_id">
        <input type="hidden" value="<?php echo $product['dasax']?>" id="product_name">
        <input type="hidden" value="<?php echo $product['fasi2']?>" id="product_price">

        <button class="btn btn-primary" type="submit" id="add_to_cart">Add</button>
        <?php endif;?>
    <?php endforeach;?>

I figured out how to solve the problem above, i have another question how can i add multiple products with this code. for now i only can add one product when i click on another product the old one dissepears.

A: You can get the data from data-*="" attribute on the button. So no need hidden inputs. For the click event you should use class name. Other case ID wont be unique. Please try following code.
    <?php foreach ($products as $product):?>
       <?php if($product['kateg'] == "men"):?>

<?php echo $product['dasax']?>

Old price: <?php echo round($product['fasi1'], 2)?> GEL

New Price: <?php echo round($product['fasi2'], 2)?> GEL

        <button class="btn btn-primary" type="submit" class="add_to_cart" data-id="<?php echo $product['id']?>" data-name="<?php echo $product['dasax']?>" data-price="<?php echo $product['fasi2']?>">Add</button>
        <?php endif;?>
    <?php endforeach;?>

A: Now that we have the form, and jQuery included in our document, we need to store it's values in 2 variables, ( val1 and val2 ) so then we can pass it to the PHP file to process it.
$('#button').click(function() {
    var val1 = $('#text1').val();
    var val2 = $('#text2').val();
    $.ajax({
        type: 'POST',
        url: 'process.php',
        data: { text1: val1, text2: val2 },
        success: function(response) {
            $('#result').html(response);
        }
    });
});

As you can see in the code above, we create a .click event. This means that when the button with the ID of #button is click, out function will run. Then we get the value of each text field and store it in val1 and val2.


text:
Q: LINQ + TransactionScope will not change isolation level in SQL Server Profiler I'm using the following format for commiting changes to my db using linq.
Begin Transaction (Scope Serialized, Required)
    Check Business Rule 1...N
    MyDataContext.SubmitChanges()
    Save Changes Done In Previous Query To Log File
End Transaction Scope

But in the SQL Server profiler I see the following line in the Connection:Start.
set transaction isolation level read committed

I went through this (http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/93a45026-0425-4d49-a4ac-1b882e90e6d5) and thought I had an answer;
Until I saw this (https://connect.microsoft.com/VisualStudio/feedback/details/565441/transactionscope-linq-to-sql?wa=wsignin1.0) on Microsoft Connect.
Can someone please tell me whether my code is actually executed under Serialized Isolation Level or whether it is infact just running under read committed?

A: It depends on how you created the transaction.
If you executed inline SQL to begin it (EG. BEGIN TRAN), L2S will not be aware of the transaction and will spin up a new nested one in READ COMMITTED.
However, if you used System.Transaction, or have a transaction set on your DataContext, SubmitChanges will participate in that transaction.
You can see these transaction starting and stopping in Profiler if you choose the TM: Begin Tran and TM: Commit Tran event classes.
Note: ADO.Net does not issue BEGIN TRAN nor does it issue SET TRANSACTION ISOLATION in batches, this is done at a lower level.
If you really want to confirm the behavior, create a trigger on a table that inserts the current isolation level into a logging table and check on it.
You can pick up your current isolation level by running:
SELECT CASE transaction_isolation_level
WHEN 0 THEN 'Unspecified'
WHEN 1 THEN 'Read Uncommitted'
WHEN 2 THEN 'Read Committed'
WHEN 3 THEN 'Repeatable Read'
WHEN 4 THEN 'Serializable'
WHEN 5 THEN 'Snapshot' END AS TRANSACTION_ISOLATION_LEVEL
FROM sys.dm_exec_sessions
where session_id = @@SPID

A: My guess is you created the DataContext, then used the TransactionScope.  You have to open the connection inside the TransactionScope in order for it to enlist.

A: From http://entityframework.codeplex.com/workitem/1712
TransactionScope uses remote API calls rather than SQL commands to perform transactions in SQL Server. Those API calls are not included in the a standard trace in SQL Profiler.
You can include them by going to the "Event Selection" page, clicking on the "Show all events" checkbox and the selecting all the events from the Transactions category. This will allow you to see when such events as 'TM: Begin Tran Starting', 'SQLTransaction' and 'TM: Begin Tran Completed' actually occur.
You can also check the TransactionID column for the TSQL events in the "Event Selection" page to see the to which transaction each SQL batch being executed is associated.
Unfortunately I don't know of a direct way to observe the effective isolation level under which each command is being executed in SQL Profiler. But there is an indirect way...
When a connection is opened you will see an 'Audit Login' event in the trace. In many cases this event will contain the isolation level. Now, the 'Audit Login' happens before the actual isolation level is set, so the reported isolation level won't accurately reflect the isolation level of the transaction that is about to start. Here are some tips on how to interpret it:
When a connection opening actually hits a new connection it will always report the default transaction isolation level, e.g. you will see 'set transaction isolation level read uncommitted' (as I said, this is unrelated to the effective isolation level of your transaction as that one will be set at a later point)
After a connection has been opened and then returned to the connection pool (i.e. closed), subsequent connection openings will actually reuse that existing connection from the pool. In this case the 'Audit Login' will report the isolation level that was set when the connection got returned to the pool the last time. This can help you see the isolation level that was used, after the fact.
E.g. in your code snippet, the connection is open for a last time to roll back the transaction (because you have not marked the transaction as completed explicitly). In that 'Audit Login' event you should be able to see the isolation level that was effective when the connection was previously used to execute the query, represented by the line 'set transaction isolation level read uncommitted'.


text:
Q: Datetime won't convert from string x = '2022-08-01 12:15:36'
y = datetime.datetime.strptime(x, '%Y-%m-&d %H:%M:%S')
print(y)

I get this error:
ValueError: time data '2022-08-01 12:15:36' does not match format '%Y-%m-&d %H:%M:%S.%f'

I am pretty sure the format I have got is okay? I want to be able to find times within a window of this time but can't add time to a string so I need it in date time format.

A: You have a problem with the format on "&d".. it should be this one
y = datetime.datetime.strptime(x, '%Y-%m-%d %H:%M:%S')