text:
Q: Unique Element only in Order Indicator Is there a way to make elements unique in same sequence (choice, all) but not on the whole document.
For example this should work (Both John and Jane have Francis as middlename):
<students xsi:noNamespaceSchemaLocation="stack.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <student>
        <name>John</name>
        <middlename>Francis</middlename>
        <middlename>Mike</middlename>
        <lastname>Doe</lastname>
    </student>
    <student>
        <name>Jane</name>
        <middlename>Francis</middlename>
        <lastname>Doe</lastname>
    </student>
</students>

But this should not work (John has two similar middle names):
<students xsi:noNamespaceSchemaLocation="stack.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <student>
        <name>John</name>
        <middlename>Francis</middlename>
        <middlename>Francis</middlename>
        <lastname>Doe</lastname>
    </student>
</students>

I have tried so far following on my .xsd file:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="students">
        <xs:complexType>
            <xs:sequence maxOccurs="unbounded">
                <xs:element name="student">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="name" type="xs:string"/>
                            <xs:sequence minOccurs="0" maxOccurs="5">
                                <xs:element name="middlename" type="xs:string"/>
                            </xs:sequence>
                            <xs:element name="lastname" type="xs:string"/>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>

        <xs:unique name="middlename_unique">
            <xs:selector xpath="student/middlename"/>
            <xs:field xpath="."></xs:field>
        </xs:unique>
    </xs:element>
</xs:schema>

But this only makes middlename in general unique not for a single student...

A: https://www.w3.org/TR/xmlschema-0/#specifyingUniqueness says

XML Schema enables us to indicate that any attribute or element value
must be unique within a certain scope. To indicate that one particular
attribute or element value is unique, we use the unique element first
to "select" a set of elements, and then to identify the attribute or
element "field" relative to each selected element that has to be
unique within the scope of the set of selected elements.

So I think you want
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="students">
        <xs:complexType>
            <xs:sequence maxOccurs="unbounded">
                <xs:element name="student">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="name" type="xs:string"/>
                            <xs:sequence minOccurs="0" maxOccurs="5">
                                <xs:element name="middlename" type="xs:string"/>
                            </xs:sequence>
                            <xs:element name="lastname" type="xs:string"/>
                        </xs:sequence>
                    </xs:complexType>
                    <xs:unique name="middlename_unique">
                        <xs:selector xpath="middlename"/>
                        <xs:field xpath="."/>
                    </xs:unique>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>


text:
Q: How to build a simple recommendation system? How to build a simple recommendation system? I have seen some algorithms but it is so difficult to implement I wish their is practical description to implement the most simple algorithm?
i have these three tables
        Users
  userid      username
   1            aaa
   2            bbb

and
        products
  productid        productname
     1                laptop
     2                mobile phone
     3                car

and
      users_products
  userid        productid
    1                1
    1                3
    3                2
    2                3

so I want to be able recommend items for each of the users depending on the items they purchased and other users' items
I knew it should something like calculating the similarites between users and then see their prosucts but how can be this done and stored in a database because this will require a table with something like this
      1    2   3   4   5   6 << users' ids
 1)   1   .4  .2  .3  .8  .4
 2)  .3    1  .5  .7  .3  .9
 3)  .4   .4   1  .8  .2  .3
 4)  .6   .6  .6   1  .4  .2
 5)  .8   .7  .4  .2   1  .3
 6)   1   .4  .6  .7  .9   1
 ^
 ^
users'
 ids

so how can similarty beween users calculated?
and how could this complex data stored in ad database? (it requires a table with column for every user)?
thanks

A: Maybe reading "Programming Collective Intelligence" will help you.

A: How you want to actually store the recommendations is as a question completely unrelated to how one would actually implement a recommendation engine. I leave that to your database architecture. On to the recommending.
You said "simple", so a Pearson correlation coefficient might be the thing you need to read up on.
Calculating such a thing is dead simple. Concept, example code.

A: The table can be stored in three columns
user_left
user_top
correlation
(I have no experience with determining correlation, though)

A: You most certainly do not need a column for each user.  You need a correlation matrix, that is true, but an actual database table is unnecessary.  Instead you can imiplement it as
table: user_correlation_matrix
columns: user1_id user2_id correlation_factor

A: I saw this in one of Joe Celko's books. I believe it's this one Here. I don't have access to mine at the moment. Try heading over to a near by Barnes & Noble or Borders and check it out. I'll dig mine as soon as I have access and follow up.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Map Only MapReduce Job with BigQuery We have a Mapreduce job created to inject data into BigQuery. There is not much of filtering function in our job so we'd like to make it map-only job to make it faster and more efficient.
However, the java class "com.google.gson.JsonObject" accepted by BigQuery doesn't implement the Writable interface needed for hadoop Mapper interface. JsonObject is also final and we can not extend it ...
Any suggestions on how we get around the issue?
Thanks,

A: To add-on to William's response: I wanted to test this myself and I created a new cluster with the bigquery connector installed and then ran the following map-only job:
import com.google.cloud.hadoop.io.bigquery.BigQueryConfiguration;
import com.google.cloud.hadoop.io.bigquery.BigQueryOutputFormat;
import com.google.common.base.Splitter;
import com.google.gson.JsonObject;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.util.GenericOptionsParser;

import java.io.IOException;
import java.util.regex.Pattern;

/**
 * An example MapOnlyJob with BigQuery output
 */
public class MapOnlyJob {
  public static class MapOnlyMapper extends Mapper<LongWritable, Text, LongWritable, JsonObject> {
    private static final LongWritable KEY_OUT = new LongWritable(0L);
    // This requires a new version of guava be included in a shaded / repackaged libjar.
    private static final Splitter SPLITTER =
        Splitter.on(Pattern.compile("\\s+"))
            .trimResults()
            .omitEmptyStrings();
    protected void map(LongWritable key, Text value, Context context)
        throws IOException, InterruptedException {
      String line = value.toString();
      for (String word : SPLITTER.split(line)) {
        JsonObject json = new JsonObject();
        json.addProperty("word", word);
        json.addProperty("mapKey", key.get());
        context.write(KEY_OUT, json);
      }
    }
  }

  /**
   * Configures and runs the main Hadoop job.
   */
  public static void main(String[] args)
      throws IOException, InterruptedException, ClassNotFoundException {

    GenericOptionsParser parser = new GenericOptionsParser(args);
    args = parser.getRemainingArgs();

    if (args.length != 3) {
      System.out.println("Usage: hadoop MapOnlyJob "
          + "[projectId] [input_file] [fullyQualifiedOutputTableId]");
      String indent = "    ";
      System.out.println(indent
          + "projectId - Project under which to issue the BigQuery operations. "
          + "Also serves as the default project for table IDs which don't explicitly specify a "
          + "project for the table.");
      System.out.println(indent
          + "input_file - Input file pattern of the form "
          + "gs://foo/bar*.txt or hdfs:///foo/bar*.txt or foo*.txt");
      System.out.println(indent
          + "fullyQualifiedOutputTableId - Output table ID of the form "
          + "<optional projectId>:<datasetId>.<tableId>");
      System.exit(1);
    }

    // Global parameters from args.
    String projectId = args[0];

    // Set InputFormat parameters from args.
    String inputPattern = args[1];

    // Set OutputFormat parameters from args.
    String fullyQualifiedOutputTableId = args[2];

    // Default OutputFormat parameters for this sample.
    String outputTableSchema =
        "[{'name': 'word','type': 'STRING'},{'name': 'mapKey','type': 'INTEGER'}]";

    Configuration conf = parser.getConfiguration();
    Job job = Job.getInstance(conf);
    // Set the job-level projectId.
    conf.set(BigQueryConfiguration.PROJECT_ID_KEY, projectId);
    // Set classes and configure them:
    job.setOutputFormatClass(BigQueryOutputFormat.class);
    BigQueryConfiguration.configureBigQueryOutput(
        job.getConfiguration() /* Required as Job made a new Configuration object */,
        fullyQualifiedOutputTableId,
        outputTableSchema);
    // Configure file-based input:
    FileInputFormat.setInputPaths(job, inputPattern);

    job.setJarByClass(MapOnlyMapper.class);
    job.setMapperClass(MapOnlyMapper.class);
    // The key will be discarded by BigQueryOutputFormat.
    job.setOutputKeyClass(LongWritable.class);
    job.setOutputValueClass(JsonObject.class);
    // Make map-only
    job.setNumReduceTasks(0);

    job.waitForCompletion(true);
  }
}

And I have the following dependencies:
<dependency>
  <groupId>org.apache.hadoop</groupId>
  <artifactId>hadoop-core</artifactId>
  <version>1.2.1</version>
  <scope>provided</scope>
</dependency>
<dependency>
  <groupId>com.google.cloud.bigdataoss</groupId>
  <artifactId>bigquery-connector</artifactId>
  <version>0.7.0-hadoop1</version>
</dependency>
<dependency>
  <groupId>com.google.guava</groupId>
  <artifactId>guava</artifactId>
  <version>18.0</version>
</dependency>

A: You should be able to use the BigQuery connector for Hadoop (see https://cloud.google.com/hadoop/bigquery-connector) which provides an implementation of the Hadoop OutputFormat class.


text:
Q: Partial fractions and Integration For the equation:
The indefinite integral of $\frac{1}{x^4+1}$
My question is, without partial fractions to turn this into "integrable" form what can I do?
Is it algabraically possible to manipulate this to fit any of the standard integration rules?  Possibly letting $u=x^2$, giving $\frac{1}{u^2+1}$.
Thanks


text:
Q: Creating a Springboot Web Service SOAP client I am creating a simple Springboot application (1.5.2) with a dependency on springboot-starter-web-services.
I have the WSDL for the service I need to consume and have generated all of the classes by using wsimport. One thing I noticed was the generated classes includes an interface with all of the remote methods & their annotations.
My question, should I be using this interface? If so, how do I configure spring to use it?
I followed the Springboot tutorial found here but do not see this generated interface class mentioned anywhere. I attempted to call the webservice just like the tutorial says, but I am getting an error such as "The endpoint reference (EPR) for the operation not found is "http://mydefaulturi.com" and the WSA action ="
The generated interface has all of the methods the webservice supports as well as some annotations such as @WebMethod, @WebResult, @RequestWrapper & @ResponseWrapper. I suspect these annotations are required at the client end when making the request, but I am not using this interface.

A: I followed the Springboot tutorial found here but do not see this generated interface class mentioned anywhere.
Below line in Springboot tutorial found here, uses WSDL generated classes (GetQuote and GetQuoteResponse).
In this method, both the GetQuote and the GetQuoteResponse classes are derived from the WSDL and were generated in the JAXB generation process described in the previous step.

Should I be using this interface?
I think yes. In the example, the classes will be generated under hello.wsdl package, mentioned under Generate domain objects based on a WSDL section. It uses jaxb2 plugin and you are using wsimport. Both should work properly.
Hope this helps you.
(It will be helpful if you can provide some client and configuration classes similar to your implementation)


text:
Q: I cant use bootstrap modals in a map function first iframe works. but second iframe is in the bootstrap modal doesnt get my src attribute. shows empty in the console.
if i type src="youtube.com/url" instead of src={musics.musicEmbed} this also works. but i want to use bootstrap modals in my map function how can i do that?
{musicList.map((musics) => {
       return (

{musics.musicTitle}

               <Button variant="warning" onClick={handleShow}>
                 Start Game
               </Button>
               <Modal
                 size="lg"
                 id="mods"
                 show={show}
                 onHide={() => setShow(false)}
                 aria-labelledby="example-modal-sizes-title-lg"
               >
                 <Modal.Body>

                 </Modal.Body>
                 <Modal.Footer>
                   <Button variant="warning" onClick={handleClose}>
                     Close
                   </Button>
                 </Modal.Footer>
               </Modal>

       );
     })}

A: i solved with creating another modal component and pass it to main map component. ^^
 {musicList.map((musics) => {
        return (

{musics.musicTitle}

                <MusicModal
                  musicImage={musics.musicImage}
                  musicTitle={musics.musicTitle}
                  musicEmbed={musics.musicEmbed}
                />

        );
      })}


text:
Q: In LaTeX3, what is the best data type for storing, parsing and outputting free user input? I'm working on a mini-parser that takes free user input and interprets certain inputs as commands. For example, the parser interprets + as \oplus or [ as "start a pre-configured array with the bracket as a delimiter". The parser would ultimately enable convenient inserting of a certain kind of data-structure used in linguistics (called AVM), for which there is currently no package on CTAN.
The parser is currently based on looping through an input token list (wit \tl_map_inline:nn). But looping through spaces and control sequences from the user input gives me a headache. For example, the user input could contain:
Hello World
\textit{Hello World}

Since \tl_map_inline:nn loops over the items of the token list, the outputs will be come "HelloWorld" and "HelloWorld".
Of course, the protected input
Hello{~}World
{\textit{Hello World}}

will give the desired result, but users are unlikely to type their input in that way. Also, the two inputs above really are quite different: Hello{~}World is a token list with 11 items, but {\textit{Hello World}} has just 1. In the mapping, I'd like to parse the contents of a command like \textit as individual letters, not a single token (because its argument could contain characters that the parser should be sensitive to, like the + mentioned above).
That got me thinking that maybe there is a better way to implement the parser than using a token list and a mapping on it. If the token list is the best way, then what methods are there to:

*

*prepare the user input so that spaces will be kept as items? (maybe replace them with ~, but how?)

*properly forward control sequences to the output and be able to access the
tokens their arguments are made of?

In this answer, @egreg suggested receiving the user input as a sequence, splitting that at each space into token lists, and then parsing the token lists (with a space added to the output after every tl). Can this approach be applied to carry along commands in the example of \textit?
(Is it true that the difference between item and token is at the core of the issue?)

Here's the bare skeleton of my approach (the actual one also contains a mode switch so that the user can disable replacement of, e.g. [ so that one can still enter commands with optional arguments in the scope of the parser):
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn

\NewDocumentCommand{\parse}{+m}{
    \avm_parse:n { #1 }
}
\tl_new:N \l_avm_output_tl
\cs_new:Nn \avm_parse:n {
    \tl_clear:N \l_avm_output_tl
    \tl_map_inline:nn {#1} {
        \tl_put_right:Nn \l_avm_output_tl {##1}
    }
        \tl_use:N \l_avm_output_tl
}
\ExplSyntaxOff
\begin{document}
    \noindent
    \parse{Hello World}\\
    \parse{\textit{Hello World}}\\
    \parse{Hello{~}World}\\
    \parse{{\textit{Hello{~}World}}}
\end{document}

A: It's possible to parse the entire token list while preserving spaces and groups, but it's a lot more work than "normal" \tl_map_inline:nn parsing (see here for a more complete explanation). The issue is that \tl_map_inline:nn, as its documentation in interface3 says, does not iterate on tokens, but on items, and it removes outer braces. All of XX, X X, X{X}, and {XX}{XX} are lists of two items (in the last one, each item has two tokens). This space and brace removal happens at a low level of TeX because when it grabs an argument, all of \next X, \next{X} and \next <spaces>X grab X as argument: this is what defines an item.
To iterate on proper tokens, you need to specifically check for the case of spaces and braces. expl3 has three conditional functions, \tl_if_head_is_space:n(TF) to check whether the first token in the argument token list is a space, \tl_if_head_is_group:n(TF) for the case of a grouped list of tokens, and \tl_if_head_is_N_type:n(TF) for all other cases. This allows you to process the argument token list conditionally for spaces and groups, and thus preserve them in the process. This method is also used by expl3's \text_uppercase:n (former \tl_upper_case:n), \tl_count_tokens:n, \tl_reverse:n, and a few others.
Here I defined the \avm_parse:n function so that it iterates on each token of the argument, and in case the token is of N-type, it checks if the current token is a + or a [ (using \str_case:nnF) and calls the appropriate function to process each case. You can change the definition of \__avm_special_plus: and \__avm_special_lbrack:w to do what you expect (I made the + produce \ensuremath{\oplus} and [<tokens>] produce \textbf{<tokens>} (and also parse the <tokens> with \avm_parse:n).
Here's the code:
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewExpandableDocumentCommand {\parse} {+m}
  { \avm_parse:n {#1} }
\cs_new:Npn \avm_parse:n #1
  { \exp_args:No \exp_not:o { \__avm_parse:n {#1} } }
\cs_new:Npn \__avm_parse:n #1
  {
    \exp:w
      \group_align_safe_begin:
        \__avm_parse_loop:w #1
          \q_recursion_tail \q_recursion_stop
        \__avm_result:n { }
  }
\cs_new:Npn \__avm_end:w \__avm_result:n #1
  {
      \group_align_safe_end:
    \exp_end:
    #1
  }
\cs_new:Npn \__avm_parse_loop:w #1 \q_recursion_stop
  {
    \tl_if_head_is_N_type:nTF {#1}
      { \__avm_N_type:N }
      {
        \tl_if_head_is_group:nTF {#1}
          { \__avm_group:nw }
          { \__avm_space:w }
      }
    #1 \q_recursion_stop
  }
\cs_new:Npn \__avm_N_type:N #1
  {
    \quark_if_recursion_tail_stop_do:Nn #1
      { \__avm_end:w }
    \__avm_parse_specials:N #1
  }
\cs_new:Npn \__avm_parse_specials:N #1
  {
    \str_case:nnF {#1}
      {
        { + }{ \__avm_special_plus: }
        { [ }{ \__avm_special_lbrack:w }
      }
      { \__avm_non_special:N #1 }
  }
\cs_new:Npn \__avm_group:nw #1
  { \exp_args:NNo \exp_args:No \__avm_group:n { \__avm_parse:n {#1} } }
\cs_new:Npn \__avm_group:n #1 { \__avm_add_result:nw { {#1} } }
\exp_last_unbraced:NNo
\cs_new:Npn \__avm_space:w \c_space_tl { \__avm_add_result:nw { ~ } }
\cs_new:Npn \__avm_add_result:nw #1 #2 \q_recursion_stop \__avm_result:n #3
  { \__avm_parse_loop:w #2 \q_recursion_stop \__avm_result:n {#3 #1} }
\cs_new:Npn \__avm_non_special:N #1 { \__avm_add_result:nw {#1} }
%
\cs_new:Npn \__avm_special_plus:
  { \__avm_add_result:nw { \ensuremath { \oplus } } }
\cs_new:Npn \__avm_special_lbrack:w #1 ]
  {
    \exp_args:No \__avm_add_result:nw
      { \exp:w \exp_args:NNf \exp_end: \textbf { \avm_parse:n {#1} } }
  }
\ExplSyntaxOff
\begin{document}
\noindent
\parse{Hello World}\\
\parse{\textit{Hello World}}\\
\parse{Hello{~}World}\\
\parse{{\textit{Hello{~}World}}}\\
\parse{Hello [World]}\\
\parse{\textit{Hell[o W]orld}}\\
\parse{Hell[o{~+}W]orld}\\
\end{document}

and the output of the examples:

A: I find the recursion approach understandable, but somewhat harder to understand than the analysis function family; and it's not easy to preserve the charcode of {}.
Remark: In the simple cases, if a regex replacement suffices, just use that. Also it's faster.
Alternative approaches include

*

*use regex to temporarily replace all space with some placeholder, process, then replace back.

*tokcycle or etl package.

An example of using \tl_analysis_map_inline needless to say, in real code don't redefine important LaTeX macros such as \f, \a etc.:
\ExplSyntaxOn
\def \f #1 {
    \tl_build_begin:N \a
    \tl_analysis_map_inline:nn {#1} {
        \int_compare:nNnTF {##2} = {`[} {
            \tl_build_put_right:Nn \a {
                \iftrue \noexpand\textbf{ \else } \fi  % this will x-expand to '\textbf{'
            }
        } {
            \int_compare:nNnTF {##2} = {`]} {
                \tl_build_put_right:Nn \a {
                    \iffalse { \else } \fi  % this will x-expand to '}'
                }
            } {
                \int_compare:nNnTF {##2} = {`+} {
                    \tl_build_put_right:Nn \a { $\noexpand \oplus$ }
                } {
                    \tl_build_put_right:Nn \a {##1}
                }
            }
        }
    }
    \tl_build_end:N \a
    \tl_set:Nx \a {\a}
}

\ExplSyntaxOff
\f{a [Hello + world] b}
\a

The method to build partially-unbalanced intermediate token list is also demonstrated in the answer. (see explanation in my other answer here)
The output is , and the token list content after being processed is .
The disadvantage of this method however, is that it's necessary to manually count the number of open braces and close braces if you want to either

*

*grab an item, or

*only operate on the top level.

(while tokcycle package can do that automatically, but it ignores charcode of {})


text:
Q: Prevent custom command to run at terminal startup I am on Debian Jessie with Mate (v1.8.1) desktop environment.
I have installed byobu and wanted to launch it every time I open a terminal so I went into the profile preferences, checked Run a custom command instead of my shell and add the following command:
/usr/bin/byobu
It worked fine but I had the annoying startup message from byobu on each opening so I tried to mask the output by changing naively the command to:
/usr/bin/byobu > /dev/null
And here was my mistake... Now every time I launch a terminal it is closed immediately : I have no longer access to my profile preferences to edit the command.
I do have access to Xterm though (i.e. I have a way to execute command lines).

*

*How can I prevent the custom command to run on terminal launch ?

*Where is stored the mate-terminal config file ? (so I can maybe manually removed the profile preferences)

P.S. I am aware of the --profile=PROFILE_NAME option of mate-terminal that I could launch from Xterm, unfortunately I have only one profile : the corrupted one.
I cannot find an option to launch mate-terminal with no preferences...

A: I couldn't find the location of terminal profile configuration file so here is what I did:

*

*install dconf (GUI editor for desktop environment settings)

*launch dconf-editor

*Go to org > mate > terminal > profiles > profile0

*edit the key "custom command" (set it to empty)

After that I was able to launch the terminal without executing my custom command and had access to profile preferences again.


text:
Q: How do I specify a minimum package version in pipit setup.cfg I am trying to specify a minimum package version in a pypi setup.cfg file.  I have written this:
install_requires =
   cocotb>=1.5.2

But I get this error message when I test my package installation:
ERROR: Could not find a version that satisfies the requirement cocotb>=1.5.2 (from pyuvm) (from versions: 1.0.20170128)
ERROR: No matching distribution found for cocotb>=1.5.2

It seems to be using the version number as part of the package name. When I install cocotb manually I see the correct version:
(clean) (base) raysalemi@RayProMac pyuvm % pip list
Package    Version
---------- -------
cocotb     1.5.2

All the help I've seen on this refers to the setup.py file, but I am working with the setup.cfg file.  What is the syntax to specify a module and version?

A: The syntax is correct. The problem was that cocotb 1.5.2 is not on test.pypi.org


text:
Q: electron add onclick dynamically fails I try to add elements dynamically in the render process like the following:
import {remote, ipcRenderer} from 'electron'
var userResponseString = ipcRenderer.sendSync('getUserData');
var userResponseData = JSON.parse(userResponseString)
parseTeams(userResponseData.teams);
function parseTeams(teamArray) {
  let teams = document.getElementById('teams')
  teamArray.forEach(element => {
    let item = document.createElement('li');
    item.innerText = element[1];
    // item.onclick = function(){
    //   ipcRenderer.sendSync('getTeamData', {id:element[0]})
    // }
    item.addEventListener('click', function(e) {
      ipcRenderer.sendSync('getTeamData', {id:element[0]})
    })
    teams.append(item)
  });
}

However, neither setting onclick nor addEventListener works. Elements are edit, texts are shown, but not clickable. What is the proper way to do this? Many thanks.


text:
Q: Clojure vector -> vector function using # and % syntax sugar? Is it possible to code using #, %1, %2 for the below?
(defn fib-step [[a b]]
  [b (+ a b)])

(defn fib-seq []
  (map first (iterate fib-step [0 1])))

user> (take 20 (fib-seq))
(0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181)

In short, I'd like to know how to write
 vector -> vector function using # and % syntax sugar.
Thanks

A: You can easily produce a vector using the #() reader form with the -> threading macro. For example, the following two functions are equivalent:
(fn [a b] [b a])
#(-> [%2 %])

However, if you need to do destructuring, as in your case, you're best off just sticking with one of the fn forms with an explicit parameter list. The best you'd get with #() is something like this:
#(-> [(% 1) (+ (% 0) (% 1))])

or
#(-> [(% 1) (apply + %)])

Using the higher-order juxt function is another nice way to create vectors, but unfortunately in this case it doesn't buy you much either:
(def fib-step (juxt second #(apply + %)))

I think out of all the options, using fn is still the best fit because of its easy support for destructuring:
(fn [[a b]] [b (+ a b)])

A: Here is the code:
(def step #(-> [(% 1) (+ (% 0) (% 1))]))
(def fib #(map first (iterate step [0 1])))

(println
 (take 20 (fib))
)

or
(def step #(-> [(% 1) (+ (% 0) (% 1))]))
(def fib (->> [0 1]
              (iterate step)
              (map first)))

(println
  (->> fib
       (take 20))
))

A: I would suggest making fib-step take 2 parameters rather than a vector as that would make things more clear that this function need two values whereas a vector as param means it can take any number of values as param (in the form of the vector).
(def fib-step #(-> [%2 (+ %1 %2)]))

(defn fib-seq []
  (map first (iterate (partial apply fib-step) [0 1])))

A: I think using the vector function is clearer than the (-> [...]) "trick":
#(vector (% 1) (apply + %))

Though in this instance, with destructuring, I'd just use a named function or (fn [...] ...)  anyway.


text:
Q: How can I integrate handlebars with backbone I have a simple single page application which is for my own learning. The page has a UL of all the services that I provide. This list comes from a JSON. Next to each service there is a price for it, and a check-box which the user can select if he needs the service.
Under the list there is a total price value for all the services selected. Based on this, can you please tell me what wrong am I doing? I am trying to integrate the list of services as a handlebar template.
Here is the HTML

    <meta charset="utf-8" />
    <title>Your first Backbone.js App | Tutorialzine </title>

    <link href="http://fonts.googleapis.com/css?family=PT+Sans:400,700" rel='stylesheet' />

    <link href="http://localhost/backbone-demo/assets/css/style.css" rel="stylesheet" />

    <form id="main" method="post" action="submit.php">

My Services

total: $0

        <input type="submit" id="order" value="Order" />

    </form>

Here is the Javascript:
$(function(){

// Create a model for the services
var Service = Backbone.Model.extend({

    // Will contain three attributes.
    // These are their default values

    defaults:{
        title: 'My service',
        price: 100,
        checked: false
    },

    // Helper function for checking/unchecking a service
    toggle: function(){
        this.set('checked', !this.get('checked'));
    }
});

// Create a collection of services
var ServiceList = Backbone.Collection.extend({

    // Will hold objects of the Service model
    model: Service,

    // Return an array only with the checked services
    getChecked: function(){
        return this.where({checked:true});
    }
});

//Retrieve the list of services
$.ajax({
    type: "GET",
    url: "assets/services.json",
    async: true,
    success: function(response){
        // Prefill the collection with a number of services.
        var services = new ServiceList(response);
        var ServiceView = Backbone.View.extend({
            tagName: 'li',

            events:{
                'click': 'toggleService'
            },

            initialize: function(){

                // Set up event listeners. The change backbone event
                // is raised when a property changes (like the checked field)
                this.listenTo(services, 'change', this.render);
            },

            render: function(){
                var tpl = Handlebars.compile($("#services-template").html());
                //console.log(this.$el.selector);
                this.$el.html(tpl({services: services.toJSON()}));
                //console.log(this.$el);
                $('#serviceTable').append(this.$el);

                //document.getElementById('serviceTable').innerHTML = serviceData;
                // Create the HTML
                /* this.$el.html('<input type="checkbox" value="1" name="' + this.model.get('title') + '" /> ' + this.model.get('title') + '$' + this.model.get('price') + '');
                this.$('input').prop('checked', this.model.get('checked')); */

                // Returning the object is a good practice
                // that makes chaining possible
                return this;
            },

            toggleService: function(){
                this.model.toggle();
            }
        });

        // The main view of the application
        var App = Backbone.View.extend({

            // Base the view on an existing element
            el: $('#main'),

            initialize: function(){

                // Cache these selectors
                this.total = $('#total span');
                this.list = $('#services');

                // Listen for the change event on the collection.
                // This is equivalent to listening on every one of the
                // service objects in the collection.
                this.listenTo(services, 'change', this.render);

                // Create views for every one of the services in the
                // collection and add them to the page

                services.each(function(service){

                    var view = new ServiceView({ model: service });
                    this.list.append(view.render().el);

                }, this);   // "this" is the context in the callback
            },

            render: function(){

                // Calculate the total order amount by agregating
                // the prices of only the checked elements

                var total = 0;
                console.log(services.getChecked());

                Handlebars.each(services.getChecked(), function(elem){
                    console.log(total);
                    total += elem.get('price');
                });

                // Update the total price
                this.total.text('$'+total);

                return this;

            }

        });

        new App();

    }
});

});

A: Below is a workable snippet of your code. You have defined a ServiceView, which is created for each service in your set, however within this view, you are working with the collection as a whole, not this.model and your handlebars template has a for loop in it.
This means that you end up displaying the collection as many times as there are models in the collection. The example below duplicates the list twice as there are 2 records in the list.
There are 2 possible solutions:

*

*Rename your ServiceView to ServicesView and remove the loop within App initialize.

*Remove the loop in your template and change the call to this.$el.html(tpl(this.model.toJSON()));

// Create a model for the services
var Service = Backbone.Model.extend({

    // Will contain three attributes.
    // These are their default values

    defaults:{
        title: 'My service',
        price: 100,
        checked: false
    },

    // Helper function for checking/unchecking a service
    toggle: function(){
        this.set('checked', !this.get('checked'));
    }
});

// Create a collection of services
var ServiceList = Backbone.Collection.extend({

    // Will hold objects of the Service model
    model: Service,

    // Return an array only with the checked services
    getChecked: function(){
        return this.where({checked:true});
    }
});

//Retrieve the list of services
$.ajax({
    type: "GET",
    url: "http://www.mocky.io/v2/588b429d300000d11afa8d97",
    async: true,
    success: function(response){
        // Prefill the collection with a number of services.
        var services = new ServiceList(response);
        var ServiceView = Backbone.View.extend({
            tagName: 'li',

            events:{
                'click': 'toggleService'
            },

            initialize: function(){

                // Set up event listeners. The change backbone event
                // is raised when a property changes (like the checked field)
                this.listenTo(services, 'change', this.render);
            },

            render: function(){
                var tpl = Handlebars.compile($("#services-template").html());
                //console.log(this.$el.selector);
                this.$el.html(tpl({services: services.toJSON()}));
                //console.log(this.$el);
                $('#serviceTable').append(this.$el);

                //document.getElementById('serviceTable').innerHTML = serviceData;
                // Create the HTML
                /* this.$el.html('<input type="checkbox" value="1" name="' + this.model.get('title') + '" /> ' + this.model.get('title') + '$' + this.model.get('price') + '');
                this.$('input').prop('checked', this.model.get('checked')); */

                // Returning the object is a good practice
                // that makes chaining possible
                return this;
            },

            toggleService: function(){
                this.model.toggle();
            }
        });

        // The main view of the application
        var App = Backbone.View.extend({

            // Base the view on an existing element
            el: $('#main'),

            initialize: function(){

                // Cache these selectors
                this.total = $('#total span');
                this.list = $('#services');

                // Listen for the change event on the collection.
                // This is equivalent to listening on every one of the
                // service objects in the collection.
                this.listenTo(services, 'change', this.render);

                // Create views for every one of the services in the
                // collection and add them to the page

                services.each(function(service){

                    var view = new ServiceView({ model: service });
                    this.list.append(view.render().el);

                }, this);   // "this" is the context in the callback
            },

            render: function(){

                // Calculate the total order amount by agregating
                // the prices of only the checked elements

                var total = 0;
                console.log(services.getChecked());

                Handlebars.each(services.getChecked(), function(elem){
                    console.log(total);
                    total += elem.get('price');
                });

                // Update the total price
                this.total.text('$'+total);

                return this;

            }

        });

        new App();
      }
  });
<form id="main" method="post" action="submit.php">

My Services

total: $0

        <input type="submit" id="order" value="Order" />

    </form>


text:
Q: Jsoup getting different html compared to Firefox and other browsers I'm in trouble with some url's from a web-store called Kabum.
The url is http://www.kabum.com.br/cgi-local/kabum3/produtos/descricao.cgi?id=01:02:23:55:159
If I enter the site in the address bar, or click the link, I got a page with the product, but If I use Jsoup, I get a page with only a meta refresh to the same address.
Tried setting the user agent, the referrer and follow the link in meta, but I got the same page.
My code is here:
Document doc;
String url = "http://www.kabum.com.br/cgi-local/kabum3/produtos/descricao.cgi?id=01:02:23:55:159";
try {
    String ua = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0";
    String referrer = "http://www.google.com";
    doc = Jsoup.connect(url).timeout(20000).userAgent(ua).referrer(referrer).get();
    Elements meta = doc.select("html head meta");
    for (Iterator<Element> it = meta.iterator(); it.hasNext();) {
        Element element = it.next();
        if (element.attr("http-equiv").matches("refresh")) {
            String novaUrl = element.attr("content").replaceFirst("\\d?;url=", "");
            System.out.printf("redirecting to %s%n", novaUrl);
            doc = Jsoup.connect(novaUrl).userAgent(ua).referrer(referrer).get();
            break;
        }
    }
} catch (IOException ex) {
    Logger.getLogger(Teste1.class.getName()).log(Level.SEVERE, null, ex);
    return;
}
System.out.println(doc);

A: Very interesting.
Yeah, the following line: <meta http-equiv="refresh" content="0;url=kabum.com.br/cgi-local/kabum3/produtos/…; /> is telling the browser to refresh the current url.
So it looks like the page tells the browser to keep refreshing the page until the server has satisfied whatever criteria it is looking for.
You'll have to figure out what criteria the server is looking for. The first things to check might be (1) the redirect limit that jsoup is set to (if it has "follow redirect" capability and can understand that meta tag), and (2) cookies.

A: You need to re-send a request with the cookies. The site is returning one session cookie which it expects to see in the next request.
String url = "http://www.kabum.com.br/cgi-local/kabum3/produtos/descricao.cgi?id=01:02:23:55:159";
Map<String, String> cookies = Jsoup.connect(url).execute().cookies();
Document document = Jsoup.connect(url).cookies(cookies).get();
System.out.println(document.html());

Note that you should use the same cookies on every subsequent request you'd like to fire in the same session.


text:
Q: Remove push notifications listener React Native Expo I'm desperate trying to find out how to remove a listener.  In one of my screens I'm placing the listener inside the useEffect. However, I need to remove it once the persons leave, cancels or restarts the process.  Any help will be greatly appreciated!!
useEffect(() => {
Notifications.addListener(handlesNotifications);
}, []);

A: What you have to do is remove the listener with a return in your useEffect:
useEffect(() => {
    Notifications.addListener(handlesNotifications);

    return () => {
        Notifications.removeListener();
    }
}, []);


text:
Q: How do I get integrity error to continue inserting into db -- python? I have a postgres DB that looks like this:
                                                        Table "public.available_dates"
   Column   |            Type             |                          Modifiers                           | Storage | Stats target | Description
------------+-----------------------------+--------------------------------------------------------------+---------+--------------+-------------
 id         | integer                     | not null default nextval('available_dates_id_seq'::regclass) | plain   |              |
 unix_day   | integer                     |                                                              | plain   |              |
 hour       | integer                     |                                                              | plain   |              |
 created_at | timestamp without time zone |                                                              | plain   |              |
 updated_at | timestamp without time zone |                                                              | plain   |              |
Indexes:
    "available_dates_pkey" PRIMARY KEY, btree (id)
    "index_available_dates_on_unix_day_and_hour" UNIQUE, btree (unix_day, hour)
    "index_available_dates_on_unix_day" btree (unix_day)
Has OIDs: no

This is hooked into a rails app I'm developing and a python app that runs as a service, I use peewee as the orm for python. The rails app runs fine, and I need each of the indexes on this db.
The python application looks at files, and adds dates to the db. The problem I am having is if the date+hour exists, it fails and ends the python app. I don't want dupes in the db, but I also want the app to continue running if this integrity error is thrown. This is the code I have so far:
data_source = [{'unix_day': 1370044800, 'created_at': datetime.datetime(2014, 7, 14, 10, 12, 57, 488000), 'updated_at': datetime.datetime(2014, 7, 14, 10, 12, 57, 488000), 'hour': 1},
...
]

        try:
            with db.transaction():
                Available_Dates.insert_many(data_source).execute()
        except IntegrityError as e:
            print e
            db.rollback()
            pass
        else:
            db.commit()
        db.close()

Which fails (as it should):
duplicate key value violates unique constraint "index_available_dates_on_unix_day_and_hour"
    DETAIL:  Key (unix_day, hour)=(1370044800, 10) already exists.
How do I get my code to say, "That failed? Oh well... I just try the next one."
Note: I expect it will fail more than it will succeed.
Edit: Option 1 as per first answer:
for data in data_source:
            try:
                av_date = Available_Dates()
                av_date.unix_day = data['unix_day']
                av_date.hour = data['hour']
                av_date.created_at = data['created_at']
                av_date.updated_at = data['updated_at']
                av_date.save()

            except Exception as e:
                pass

This seems not great as I'm catching all exceptions... Also, I have to assign every member separately which seems inefficient. It also fails because there is a lock on the db.
duplicate key value violates unique constraint "index_available_dates_on_unix_day_and_hour"
DETAIL:  Key (unix_day, hour)=(1370044800, 1) already exists.

current transaction is aborted, commands ignored until end of transaction block

current transaction is aborted, commands ignored until end of transaction block

current transaction is aborted, commands ignored until end of transaction block

current transaction is aborted, commands ignored until end of transaction block

current transaction is aborted, commands ignored until end of transaction block
 ...

A: I'm doing this, in case it's useful
data = [(a,b), (a,b), (a,b)]

with database.atomic():
    # try bulk
    try:
        MyModel.insert_many(data, fields=[MyModel.field1, MyModel.field2]).execute()
    # if it fails, switch to individually adding (slower)
    except IntegrityError:
        for d in data:
            try:
                entry = MyModel(
                    field1=d[0],
                    field2=d[1],)
                entry.save()
            except IntegrityError:
                pass

A: I think if you insert everything with a single function, insert_many in this case, that's going to make it more difficult to continue in the face of an exception. My suggestion would be to insert each item one at a time, in a for loop, and wrap each individual insert in a try-except instead of the whole thing.

A: Here is what I did (thanks to ZJS):
for data in data_source:
            try:
                exists = Available_Dates.get(Available_Dates.unix_day == data['unix_day'],
                                             Available_Dates.hour == data['hour'])
            except Available_Dates.DoesNotExist:
                av_date = Available_Dates.create(**data)
                print av_date.id, "added to the database."
            except Exception as e:
                print e, type(e)
                pass


text:
Q: How to create comparing sql database, with combobox and textbox, aka pre-pass protected from Hello I want to create a first form with pass protected proceeding. So I have a SQL database table Users with columns id, name (you see it in combobox) and password.
Now I want if I choose from combobox user name and enter right password into textbox below (matching with the one in database) when I press button proceed close this form and go on 2nd.
I don't know how to match the password in the textbox and the database.
Picture of my form: Picture
This is my code:
private void usersBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
   this.Validate();
   this.usersBindingSource.EndEdit();
   this.tableAdapterManager.UpdateAll(this.usersDataSet);
}

private void Pass_Load(object sender, EventArgs e)
{
   // TODO: This line of code loads data into the 'usersDataSet.Users' table.
   //       You can move, or remove it, as needed.
   this.usersTableAdapter.Fill(this.usersDataSet.Users);
}

private void BtnOk_Click(object sender, EventArgs e)
{
   if (ComboIme.SelectedValue == "Matjaz Pecavar")
   {
     // passtxt.Text = ;
   }
}

A: I assume what you are asking is that you want to put in a password and then look up in a sql database whether the password/name combo is a match.
Assume you have a database with two columns [name] and [password]
you can query the password of the name using a sql query which you can configure using the datasource designer.
Select [password]
from dbo.users
where [name] = @myname

this should return just one value, so then check to see if the value returned is a match to the value in the textbox
string pword = tableadaptermanager.getpassword(usernamebox1.text).tostring();
if (pword == passwordbox1.text)
{
    do something useful
{

Hope that helps. Cheers.


text:
Q: Unable to fill data in dropdown from $scope variable in angularjs I am unable to fill data in dropdown in template file from $http post method in controller. I have also tried $timeout but it also didn't worked as well. Here is my controller post mathod.
$http.post('api/getRecords.php', dataObjCat).
            success(function (data, status, headers, config) {
              $timeout(function(){
                 $scope.categories = data.data;
                 console.log($scope.categories);
              },3000)

            }).
            error(function (data, status, headers, config) {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
            });

I have to post mathods like above (including above method), and both of them unable to fill in the dropdown.
I can print $scope variable in the post success. But unable to print it in the template file.
Note: this functionality works very well in local machine but not working on server.

A: Given that your server seems to respond correctly, your issue is most likely due to an issue in your html. You should make sure that you have an ng-repeat in the "option" tag to show your categories. Your code might look like this:

<select ng-model="YOURMODELHERE">
  <option ng-repeat="category in categories">{{category}}</option>
</select>

Ideally, you should post your HTML for us to see what's wrong ;)


text:
Q: UITabBarController does not show "More" button I'm using MvxTabBarViewController that is attributed with:
[MvxFromStoryboard("Main")]
[MvxRootPresentation(WrapInNavigationController = true)]

It does not present "More" button when I have more than five tabs added to the controller. Instead only the first four are shown.
The tabs are MvxViewControllers that are attributed with:
[MvxFromStoryboard("Main")]
[MvxTabPresentation(WrapInNavigationController = false, TabIconName = "icon", TabName = "Tab 1")]

They are presented from ViewWillAppear(bool animated) method using NavigationService.Navigate(TabOneViewModel)
I tried setting WrapInNavigationController to false, but still no luck.
Any help would be appreciated.

A: When using a Storyboard, in order to add a TabBarController to your application you need to drag and drop a UITabBarViewController instead of a plain UIViewController. Otherwise some properties are not correctly derived (like the TabBar in this case - please see my screenshot).
Just make sure you delete the automatically created TabBar items!


text:
Q: Pygame in Windows: ImportError: DLL load failed I just installed PyGame 1.9.1 (onto an existing python 2.6.4). Python and it standard libraries work, however, there is a problem with python even being able to find the pygame modules (correctly).
Traceback (most recent call last):
  File "C:\foo\bar\firstGame.py", line 2, in <module>
    import pygame
  File "C:\python264\lib\site-packages\pygame\__init__.py", line 95, in <module>
    from pygame.base import *
ImportError: DLL load failed: The specified module could not be found.

Why is is this happening? Googling yielded the following responses, which I have tried to no avail:

*

*http://www.daniweb.com/forums/thread181323.html I have checked that indeed base.pyd can be found in C:\python264\lib\site-packages\pygame

*http://www.kelvinsthunderstorm.com/py2exe-and-pygame-dlls/ The problem appears to be not that only select DLLs are missing, but rather that all of them are

Anyone out there fixed problems in win + pygame?
Thanks

EDIT: more information added as requested:
 - Windows version: Windows Vista (updated regularly)
 - Installer used: Windows MSI installers
 - Installed for: All users
 - Number of files in C:\python264\lib\site-packages\pygame:

*

*DLL : 14

*PYD : 34

*PY : 19

*PYC : 1

A: Are you sure you have got pygame for Python 2.6? The version for 2.5 wont work and produce this error msg, because the pyd file wont find the python 2.5 dll.

A: I have faced this error on a Windows 64 bit. I have uninstalled my python 3.4.1 and I have installed: python-3.4.1.amd64.msi then pygame-1.9.2a0.win-amd64-py3.4.exe from link mentioned above. And it worked.

A: If you are running a 64 bit version of windows, with a 64 bit python, the default installers on the Pygame site don't seem to work.
The pygame website led me there: There are some pre release binaries for 64bit windows, and for python 2.7 at http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame

A: This actually happened to my installation as well. I have Python 2.6.6 installed, but the installation did not include Pygame. I downloaded Pygame 1.9.1 with Python 2.6, and identified where the directory was located, the installation seemed to work. However, from the IDLE, I entered import pygame, and received the very error originally posted.

A: To check exactly which DLL's are missing use the CMD like python console. It will show a pop-up message indicating the missing DLL. Pygame works for me.

A: I had the exact same error however i ran a small program i found the used pygame without the IDLE(by saving the code and then just double clicking on the .py file) and it worked 100% fine.

A: I had this error and after much digging discovered that the version of python interpreter MUST match the version of pygame installed.
If you have an erroneous combination, your best bet is to uninstall what you have via Start -> Control Panel -> Uninstall Programs.
A combination that works (Install in this order) -
Python 3.2.5 - Msi download this file for Windows Vista 32-bit-
www.python.org/download/releases/3.2.5/ - Windows x86 MSI Installer (3.2.5) <- This link, about halfway down the page
Pygame - pygame.org/download.shtml -
pygame-1.9.2a0.win32-py3.2.msi <- This download link, bottom of the top list on the page.
Now you should be able to open IDLE (The default development environment) by finding the python folder from your start menu. Once it's open, type 'import pygame'. Hopefully, you'll get no errors and pygame was imported properly. I wish you luck with your programming endeavours.
If you're dissatified with the IDLE environment and want to use another, I personally use the LiClipse IDE. I have no rep, but a google search should turn that one out ;)


text:
Q: How can I get children in nested documents with some conditions? I have a collection :
{
    _id : ...
    children : [
        {
            code:0
        },

        {
            code:1
        },

        {
            code:2
        }
    ]
},

{
    _id : ...
    children : [
        {
            code:3
        },

        {
            code:4
        },

        {
            code:5
        }
    ]
},

{
    _id : ...
    children : [
        {
            code:6
        },

        {
            code:7
        },

        {
            code:8
        }
    ]
}

In this collection, I wanna get children width some code.
For example, if I want children coded 1, 4, 6, the result I need is:
{
    code:1
},

{
    code:4
},

{
    code:6
}

Every document has some children. Every child has a attribute code. How can I do this for this achievement?

A: The query always returns a document, so you might not get the very specific result you need, you can search by the children code but ultimately the result will be a collection of document with children attribute.
However this can be achieved by aggregation
db.test.aggregate([{$unwind : "$children"},{$match : {$or:[{'children.code':1},
{'children.code':4},{'children.code':6}]}},{$project : {_id:0, code : "$children.code"}}]);

Not sure about the syntax but basic idea remain same.

A: Can try it
db.CollectionName.aggregate([
  {$unwind : "$children"},
  {$match : {"children.code": {$in :[1,4,6]}}},
  {$project : {_id:0, code : "$children.code"}}
]);


text:
Q: Basic Java program wont run in Blue-J So I am supposed to make a vending machine for my intro to programming class Lab. So far this is what my Java code looks like.
import java.util.Scanner;
public class VendingMachine
{
       public static void main (String[] args)
    {
 Scanner keyboard = new Scanner(System.in);

final int quarter = 25;
final int dime = 10;
final int nickel = 15;
int cost = keyboard.nextInt ();

int totalChange = 100 - cost;
int totalQuarters= totalChange/quarter;
totalChange = totalChange % quarter;
int totalDimes = totalChange/dime;
totalChange = totalChange % dime;
int totalNickels = totalChange/nickel;
totalChange = totalChange % nickel;

System.out.print("Enter Price for your item" + "30" );

 }
}

What I need it to do is this.
Enter a price for item (from 25 cents to a dollar, in 5-cent increments): 45

You bought and item for 45 cents and gave me a dollar, so your change is

 2 quarters,

 0 dimes, and

 1 nickels.

With the values 30 , 65, and 100. For some reason the program will not start up in Blue J..so I know Eclipse is recommended but I think I want to finish this lab with Blue J, anyone have any tips?

A: My guess is that the program is starting, but you don't realize it because it is waiting for input.
Move the line containing System.out.print("Enter Price for your item" + "30" ); above your keyboard.nextInt scanning for input. Like so:
System.out.print("Enter Price for your item" + "30" );
int cost = keyboard.nextInt ();


text:
Q: Using anchor link for form submission Can i use an anchor tag to submit a form? In this code i am using a submit button which is standard but how to use a anchor tag Remove
I tried this, but the doGet() method is being called in the servlet. I want to call the doPost() method obviously. So could i use a better approach.
<c:forEach items="${lstCart}" var="cartItem" varStatus="count">
    <form action="Cart" method=Post>

        ${count.count}
        ${cartItem.productName}
        ${cartItem.quantity}
        ${cartItem.unitPrice}
        ${cartItem.totalPrice}

        <input type="hidden" name="id" value="${cartItem.productId}" />
        <input type=submit value="x">

    </form>
</c:forEach>

A: You need to use JavaScript to make an anchor link do a post. You might use CSS to style your submit button and make it look more like a link, though.

A: Yep as @JB said you can post the form using JScript. One example that comes to my mind is below with struts, here you are actually passing the product id as a variable to JS method (I changed the names so it matches your example).

Remove

You can then have JS method to be
function removeProduct(productId) {
document.forms["formname"].elements["productId"].value =
productId;
document.forms["formname"].submitTestPost.click();
}

This also assumes the following is defined in the page (so JS can set it) and the submit property (tag SubmitTag). I am not sure in your case the setup but perhaps you can draw some points.
<input type="hidden" name="productId"/>


text:
Q: Unable to exchange OAuth auth code for access token I'm just trying to make a simple app, but I can't even get past authenticating the user. I am using the Google OAuth Client Library for Java.
These are the current steps I am taking:

*

*Start local web server to listen for the loopback response after the OAuth authentication.

*Generate the auth URL:
String url = new AuthorizationCodeRequestUrl(AUTH_URL, CLIENT_ID)
        .setScopes(scopes) // Contains https://www.googleapis.com/auth/drive.readonly
        .setRedirectUri(LOCALHOST + r.getPort()) // Port of local web server
        .build();

*Use URL to authenticate account.

*Google returns auth code.

*Exchange auth code for access token.
TokenResponse token = new AuthorizationCodeTokenRequest(...)
.setRedirectUri("http://localhost") // <--
.setClientAuthentication(getClientAuth()) // ClientParametersAuthentication object
.execute();

This is where my problem occurs. No matter what value I put in for redirect_uri, I always get {"error":"redirect_uri_mismatch","error_description":"Bad Request"} in return.
Searching Google for the error, every single result says that it's because the redirect_uri I sent is not registered in the API console.
When I download the credentials json file, the redirect_uris section contains "urn:ietf:wg:oauth:2.0:oob","http://localhost", but it's all the same error no matter what I put in.
I went to the Credentials section of the project to fix it, but since this is an installed application, creating credentials for the project gives me no option to set any redirect uris. The only way to get access to changing redirect_uris are to create the credentials for "Web application," but this isn't a web application and I don't have a domain it can redirect to.
So I'm stuck, redirect_uri options are not available to me and no value that I use works, I honestly don't know what else to try. What steps can I take to fix this?

A: It turns out that the same redirect_uri must be used for the auth code and access token even if it's not going to be used for retrieving the access token.


text:
Q: Does wp-cron runs all tasks scheduled at same time together or one after other? I am developing a plugin and want to add a cron task(let's say cron_task_test) but have a doubt. In case 15 tasks(they may be scheduled by multiple plugins or the user himself) are scheduled to run at a time along with my task(cron_task_test), will wp-cron pick them one by one i.e. pick another task after first has finished or if the first task has taken more than a minute? Or does all will be fired one after another
In short, how does cron_lock works? In case it executes one after another, will not the main cron thread running all tasks one by one itself exceed maximum execution time limit of the server(generally 30 seconds)?
What will happen if any other cron task before my task(cron_task_test) has thrown an error or exceeded time-limit?

A: For example about 12:00 it should run 3 tasks.
If You use wp-cron it will start when someone visit Your page about 12:00. ( Here is small complication because when two users visit Your page exactly in the same moment cron can start twice and do everything twice ).
However someone opens our page round 12:00 and cron starts. It pulls all the scheduled events in array. Set transient that cron is busy and start all process inside foreach statement using call_user_func_array  ( it is almost the same as do_action but for array ).
Procedure in foreach:

*

*reschedule if necessary;

*unschedule before start of job;

*call_user_func_array ( do the job );

*check cron lock because if the hook ran too long and another cron process stole the lock, cron quits loop;

My small tips:

*

*crontab can be better solution;

*don't forget about some logging to test your cron task;

*if cron's one of jobs fails it has no impact on other tasks ( if i am wrong please correct me );

Here You have some extra information wrote in article  by my friend:
Cron solutions for wordpress


text:
Q: Weak convergence of a sequence of probability measures implies integrability of the limiting probability measure Let $(X_{n})_{n \in \mathbb{N}}$ be a sequence of uniformly integrable random vectors with values in some normed vector space $V$ with $\mathbb{E}[\|X_n\|] < \infty$. This means that
$$
\lim_{C \to \infty} \sup_{n \in \mathbb{N}} \mathbb{E}[ \| X_{n} \|  \mathbb{1}_{\{\| X_{n} \| > C\}} ] = 0.
$$
Furthermore, suppose that $\mu$ is a probability measure on $V$ and the sequence $(X_{n})_{n \in \mathbb{N}}$ converges weakly to $\mu$. This means that for every bounded Lipschitz continuous function $f \colon V \rightarrow \mathbb{R}$ it holds
$$
\lim_{n \rightarrow \infty} \int_{V}f dP_{X_{n}} = \int_{V} f d\mu.
$$
How can I show that then $\int_{V} \| x \| d\mu(x) < \infty$?

A: By the uniform integrability of $(X_n)_{n \in \mathbb{N}}$ we have $$M := \sup_{n \geq 1} \mathbb{E}(|X_n|) < \infty. \tag{1}$$ On the other hand, the weak convergence of $X_n \to X$ entails that
$$\mathbb{E}f(X_n) \to \mathbb{E}f(X) \tag{2}$$
for any bounded Lipschitz continuous function; in particular, we can choose $f(x) := \min\{|x|,k\}$ for fixed $k \geq 1$ to get
$$\mathbb{E}\min\{|X|,k\} \stackrel{(2)}{=} \lim_{n \to \infty} \mathbb{E}\min\{|X_n|,k\} \leq \sup_{n \in \mathbb{N}} \mathbb{E}(|X_n|)=M.$$
Applying the monotone convergence theorem we conclude that
$$\mathbb{E}(|X|) = \sup_{k \geq 1} \mathbb{E}\min\{|X|,k\} \leq M < \infty.$$

A: Fix $N$ and let $f(x)=\min \{||x||,N|\}$. Claim $f$ is a bounded Lipschitz function. (The only case when this is not obvious is when $||x||<N<||y||$. In this case $|f(x)-f(y)|=|||x||-N|=N-||x||\leq ||y||-||x|| \leq ||x-y||$ by triangle inequlaity). Hence $\int f(x)d\mu(x) =\lim E(\min \{||X_n||,N\})\leq \sup_n E||X_n||$. Note that $E||X_n|| \leq E||X_n|| I_{||X_n|| >C} + E||X_n|| I_{||X_n|| \leq C}$. We can make the first term $<1$ by choosing $C$ appropriately. The second term does not exceed $C$. We have proved that $\int \min \{|X||,N|\} d\mu(x) \leq C+1$ and the bound does not depend on $N$. Letting $n \to \infty$ we get $\int |x|| d\mu (x) <\infty$.


text:
Q: GRADLE_HOME is picking /usr/share/gradle-8.0.1 instead of /usr/share/gradle-7.6 in github actions CI pipeline My project is using gradle-7.6 and the building, running fine on my local machine as well as on the GitHub actions workflows CI pipeline
But after a minor patch update on the ubuntu machine, the build started failing.
One of the major reasons seems of the failure is the Gradle version that GitHub workflow is picking.
For success builds it used to be
GRADLE_HOME=/usr/share/gradle-7.6

But now it is -
GRADLE_HOME=/usr/share/gradle-8.0.1

I tried a lot to figure out where this env GRADLE_HOME is set, but no luck.
Can anyone please help with this issue? How to override this?
Any help will be appreciated


text:
Q: how i can create report on knowledge article with article types ( ex :Product Advice)? how i can create report on knowledge article with article types ex: product advice?how i can create report on knowledge article with article types ( ex :Product Advice)?

A: Refer to below these links. It helps you.
App by Salesforce
This package provides reports and dashboards that help you monitor your knowledge base. For example, you can compare article ratings and views, analyze recent activity by authors, and determine which articles are helping solve the most cases.
https://appexchange.salesforce.com/listingDetail?listingId=a0N30000003HXO9EAO
Use Salesforce Knowledge custom reports to track how articles are created, maintained, and delivered.
https://help.salesforce.com/apex/HTViewHelpDoc?id=knowledge_custom_reports.htm


text:
Q: How can this php code be made vulnerable to sql injection and cross site scripting attacks? Im currently learning about software security vulnerabilities, specifically SQL injection and XSS attacks. Ive been given a task to make a secure application vulnerable but i have no prior background on coding PHP.
From my understanding, the application could be made vulnerable if the PDO is removed but i have no specific solution for this. Can anyone provide an answer? Im desperate
Registration
<?php
//error_reporting(0);
if(isset($_POST['signup']))
{
$fname=$_POST['fullname'];
$email=$_POST['emailid'];
$mobile=$_POST['mobileno'];
$password=md5($_POST['password']);
$sql="INSERT INTO  tblusers(FullName,EmailId,ContactNo,Password) VALUES(:fname,:email,:mobile,:password)";
$query = $dbh->prepare($sql);
$query->bindParam(':fname',$fname,PDO::PARAM_STR);
$query->bindParam(':email',$email,PDO::PARAM_STR);
$query->bindParam(':mobile',$mobile,PDO::PARAM_STR);
$query->bindParam(':password',$password,PDO::PARAM_STR);
$query->execute();
$lastInsertId = $dbh->lastInsertId();
if($lastInsertId)
{
echo "<script>alert('Registration successfull. Now you can login');</script>";
}
else
{
echo "<script>alert('Something went wrong. Please try again');</script>";
}
}

?>

Login
<?php
if(isset($_POST['login']))
{
$email=$_POST['email'];
$password=md5($_POST['password']);
$sql ="SELECT EmailId,Password,FullName FROM tblusers WHERE EmailId=:email and Password=:password";
$query= $dbh -> prepare($sql);
$query-> bindParam(':email', $email, PDO::PARAM_STR);
$query-> bindParam(':password', $password, PDO::PARAM_STR);
$query-> execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
if($query->rowCount() > 0)
{
$_SESSION['login']=$_POST['email'];
$_SESSION['fname']=$results->FullName;
$currentpage=$_SERVER['REQUEST_URI'];
echo "<script type='text/javascript'> document.location = '$currentpage'; </script>";
} else{

  echo "<script>alert('Invalid Details');</script>";

}

}

?>

A: For sql injection, you can remove the bindParam lines and write something like the following instead in say Login:
$sql ="SELECT EmailId,Password,FullName FROM tblusers WHERE EmailId='$email' and Password='$password'";

As the parameters would now be passed in to sql with string concatenation, this would make it vulnerable to sql injection on both the email amd password variables.
For XSS, you would have to output user input without encoding. For example in login, you could write the received username in the response like this:
echo "<script>alert('Invalid Details for $email');</script>";

That way the email field would be easily exploitable.
Note that these are just examples, the same can be achieved in countless different ways.


text:
Q: How to use jmeter ui on ultra high resolution display The jmeter UI on windows 8 with a 3200X1800 Lenovo Laptop is unusable.  Fonts on the far left pane are toooo small and on the right side the line spacing is too small for the fonts.  If I change my resolution to 1920X1080, it has no effect.  tried using on second monitor that is 1920X1080.  No Luck.  System is set for larges sizes. Can't seem to swap which monitor is primary either.  Anyone solve this?

A: Since version 3.1 from JMeter you can do that by modifying user.properties as per this doc:

*

*http://jmeter.apache.org/usermanual/hints_and_tips.html#hidpi

jmeter.hidpi.mode
  set to true to activate a 'pseudo'-hidpi mode allowing to increase size of some UI elements
  jmeter.hidpi.scale.factor
  set to 2.0 to scale the size of some UI elements
jmeter.toolbar.icons.size
  with these values: 22x22 (default size), 32x32 or 48x48 (Suggested value for HiDPI)
  jmeter.tree.icons.size
  with these values: 19x19 (default size), 24x24, 32x32 (Suggested value for HiDPI) or 48x48
  Additionally you can increase the font size of the text areas in some elements like JSR223 sampler by changing theses properties:
jsyntaxtextarea.font.family
  set to Hack to activate and to change the font and their size
  jsyntaxtextarea.font.size
  set to a greater value, like 28 (Suggested value for HiDPI)

Note you can also zoom in/out by using CTRL +/-

A: On Ubuntu do the following:

*

*Open bin/user.properties in Jmeter's installation directory (mine was ~/apache-jmeter-5.2.1).

*Add the following lines at the end of the file:
jmeter.hidpi.mode=true
jmeter.hidpi.scale.factor=2.0
jmeter.toolbar.icons.size=48x48
jmeter.tree.icons.size=48x48
jsyntaxtextarea.font.family=Hack
jsyntaxtextarea.font.size=28
swing.plaf.metal.controlFont=Dialog-20
swing.plaf.metal.systemFont=Dialog-20
swing.plaf.metal.userFont=SansSerif-18
swing.plaf.metal.smallFont=SansSerif-16
swing.plaf.metal.controlFont=Dialog-32
swing.plaf.metal.systemFont=Dialog-32
swing.plaf.metal.userFont=SansSerif-20
swing.plaf.metal.smallFont=SansSerif-20

*Save the file

*Open Jmeter and go to Options -> Look and Feel -> Metal

*Restart Jmeter

A: Edit as of August 2017 for version 3.2:
The answer below might be more up to date and simple

*

*https://stackoverflow.com/a/45773659/460802
I stumbled upon answer about setting Swing font at runtime and it gave me a clue how to set JMeter's fonts.
According to Swing's DefaultMetalTheme.java source, this is a list of recognized Java properties which are used to determine the font size:
  128       private static final String[] defaultNames = {
  129           "swing.plaf.metal.controlFont",
  130           "swing.plaf.metal.systemFont",
  131           "swing.plaf.metal.userFont",
  132           "swing.plaf.metal.controlFont",
  133           "swing.plaf.metal.controlFont",
  134           "swing.plaf.metal.smallFont"
  135       };

So, what you need to do is to make sure these are set appropriately before JMeter starts. This is environment dependent, but I assume you use Windows and you are launching JMeter via the jmeter.bat file.
Just add these lines somewehere near the top of the jmeter.bat file:
set JVM_ARGS=%JVM_ARGS% -Dswing.plaf.metal.controlFont=Dialog-20
set JVM_ARGS=%JVM_ARGS% -Dswing.plaf.metal.systemFont=Dialog-20
set JVM_ARGS=%JVM_ARGS% -Dswing.plaf.metal.userFont=SansSerif-18
set JVM_ARGS=%JVM_ARGS% -Dswing.plaf.metal.smallFont=SansSerif-16

Update: user lyaffe pointed out in comment that on a 4K laptop display you want to have fonts even bigger:
set JVM_ARGS=%JVM_ARGS% -Dswing.plaf.metal.controlFont=Dialog-32
set JVM_ARGS=%JVM_ARGS% -Dswing.plaf.metal.systemFont=Dialog-32
set JVM_ARGS=%JVM_ARGS% -Dswing.plaf.metal.userFont=SansSerif-20
set JVM_ARGS=%JVM_ARGS% -Dswing.plaf.metal.smallFont=SansSerif-20

Then start JMeter and make sure you use the Metal look and feel (Options -> Look and Feel -> Metal).
Unfortunately, this won't affect font used in the left pane. It is either explicitly set to some small value, I guess, or it is controlled via another Java property I missed. I wasn't able to find a comprehensive list of all Java properties used in Swing. There might be more properties for fonts. I someone knows it, tell us!

A: From Java 9 onward, use the parameter -Dsun.java2d.uiScale=200% either as command line argument or environment variable JVM_ARGS.
200% is the scale factor. It seems that only multiples of 100 are supported, such as 300% and so on.
Examples:
$ "/path/to/jmeter/bin/jmeter.sh" -Dsun.java2d.uiScale=200%

or
$ env JVM_ARGS=-Dsun.java2d.uiScale=200% "/path/to/jmeter/bin/jmeter.sh"

or
$ export JVM_ARGS="-Dsun.java2d.uiScale=200%"
$ /path/to/jmeter/bin/jmeter.sh

A: I had this same issue, the above suggestion did nothing. However, I found out if you run the .bat file as administrator it seems to solve the problem.
I am running Windows 7 - 64 bit with high resolution display. Now the text is readable, otherwise the UI was completely useless.


text:
Q: Hiding button on desktop browser and showing only on mobile devices I have bootstrap header nav bar with buttons. What I trying to do is to add button which is visible only on mobile devices and small screens - phones/tablets.
This is structure of the header

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                Toggle navigation

            </button>

Button 1

Button 2

Button 3

BUTTON 4

I want to make BUTTON 4 visible only on small screens.
So I make the button like this:

BUTTON 4

Then in css I add
.not_visible {
    display: none;
}
@media  (max-width: 767px) {
    .header{
        text-align : center;
    }

    .not_visible {
        display: inline;
    }

   .nav{
        margin-top : 30px;
   }
}

But is visible on every screen resolution. Seems like display: none; isn't working.

A: Since you're using bootstrap, you can use visible-xs class on them:

BUTTON 4

Now, it will be visible in xs-devices and hidden in other devices.

A: BUTTON 4
is best approach however if you do not follow bootstrap then simply you can use display:inline !important;
As the css which is lower on page has more priority and in your case I think there is some hierarchy problem.
Try this deisplay:inline !important;

A: It is probably late but since I noticed you are using bootstrap you can use .d-block .d-sm-none as your class to make it only visible on xs- small devices.
Use this as a guide.


text:
Q: CGAffineTransform from NSString How can I obtain a CGAffineTransform from a NSString in Cocoa?
On iOS there is CGAffineTransformFromString.

A: For lack of a better solution I'm currently doing this:
CGAffineTransform CGAffineTransformFromString(NSString *string)
{
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"[ ]"]];
    NSArray *components = [string componentsSeparatedByString:@","];
    CGAffineTransform transform;
    transform.a = [[components objectAtIndex:0] floatValue];
    transform.b = [[components objectAtIndex:1] floatValue];
    transform.c = [[components objectAtIndex:2] floatValue];
    transform.d = [[components objectAtIndex:3] floatValue];
    transform.tx = [[components objectAtIndex:4] floatValue];
    transform.ty = [[components objectAtIndex:5] floatValue];
    return transform;
}


text:
Q: Terraform 0.12 main.tfvars variables not visible in tf.var For example in main.tfvars I have declared variable
cid = "xyz"

In main.tf i am trying to use it as follow.
resource "xyzresource" "example"{
clientID=var.cid }

However it doesnt recognize it, rather it asks from stdin to pass the value to var.cid
If someone can assist will be helpful. thx

A: You're very close, you're just missing a variable declaration like the following
variable "cid" {
  type = string
}

tfvars if for specifying the values of varibles whereas a variable block (like above) is for declaring that a variable exists.
You could put this variable declaration in your main.tf but it's also common to add another file next to main.tf called variables.tf that contains all variable declarations.
For more information, the terraform docs on input variables are actually pretty good.


text:
Q: How to turn on IIS7 output cache for WCF data services (OData) I have a WCF data service which is sensitive to a quite sophisticated notion of parameters in terms of URL. The common case is having the URLs like http://host:port/DataServices/NavigationMetadataService.svc/Inventories('2.1.11.5')?$expand=Components,Items,Items/Properties,Items/Properties/Values (OData notion of parameters).
The service is supposed to return static data. This means that for one unique combination of parameters the response will always be the same (but its size is about 10-20 megabytes).
We'd like to enable the IIS7 output cache but we don't know how to do this. IIS7 management console gives lack of opportunities to tune the output cache (only the name of the extension and "Vary by query string" parameter). Apparently here I don't want to specify ".svc" in the "name of the extension" field because I want to enable the caching for only one WCF service.
There is an article about leveraging the ASP.NET output cache for the same purposes http://blogs.msdn.com/b/peter_qian/archive/2010/11/17/using-asp-net-output-caching-with-wcf-data-services.aspx . But actually it's not about the IIS7 output cache.
We'd like to use IIS7 output cache because currently we're testing the whole implementation under high load and choosing the best way of caching the responses. So practically we only need to compare the IIS7 output cache with ASP.NET output cache.
Am I missed something really obvious here? I'm quite new in WCF data services so please help
There is actually the similar question How do I cache WCF REST web service in IIS7? . But it is more likely about how to determine that the response is cache-worthy in terms of IIS7 output cache.


text:
Q: Keep linux software RAID 1 after OS change Currently I've configured software RAID 1 on ubuntu machine. However I am planning to add SSD drive just for the OS and keep my main 2 HDD for the storage with RAID. The question is, can I put now everything on these disks and later install OS on the new drive and configure these 2 HDD to be in RAID and keep the data I collected already?
Another question, Can I resize or change partition RAID disks later?

A: Installing a new OS onto a newly installed SDD and keeping your RAID partitions is no problem with all modern Linux distributions, e.g. Debian and its derivatives.
When installing just watch out for the following:
- make a complete backup of your raid partition onto an external drive and disconnect this afterwards
- make sure that you install the root file system on your new SDD and that grub is installed to the sdd.
Could you give more information on the partitioning and directory structure of your raid 1 harddisks? It may very well the better approach to make a second backup, repartition using raid 1 + lvm and restore the data.
re: resize. Raid partitions can not be resized without repartitioning. I would recommend using lvm on top of raid 1, which gives you incredible flexibility and data security.


text:
Q: how to append Double quotes (" ") For a String Array Varible in java I am working with  writing files.I have a string array as in loop
I need to append double quotes for the all values which are writing it on  files . Can any one help me how to append double quotes for the all values in String Array.Thanks in advance`

A: I guess what you might be looking for is as follows:
region.append("\"").append(a[z]).append("\"").append(',');

A: If you're using Java 8, what you probably want to do is
String region = Arrays.stream(a)
    .map(s -> String.format("\"%s\"", s)) // add double quotes around each string
    .collect(Collectors.joining(","); // comma-separate values

A: *

*for each string, surround it with quotes

*for each string, except the last one, add a comma to its end

*write all strings in the file.

ex:
int l = myStrings.length;
for(int i = 0; i < l; i++){
    // Adds " to the begning of the string and ", to the end of the string.
    myStrings[i] = "\"" + mystrings[i] + "\",";
    // if you want to use String.format:
    //myStrings[i] = String.format("\"%s\",", myStrings[i]);

    // if it is the last string, remove the unwanted comma
    if(i == l-1){
        // gets the substring of the last string in the array, excluding only
        // the last character, because it is an unwanted comma
        myStrings[i] = myStrings[i].substring(0,l);
    }

    // Write in your file here
    // region.append(myStrings[i]);
}


text:
Q: How to proxy request to a given domain name to a local port? I want to make it so that when I perform a request to test.com, it will be redirected to localhost:3001.
How can this be done in MacOS?
I know that there is /etc/hosts but it's only concerned with domain names, not with ports.

A: In short: no.
But you can use local IP-adresses instead of the localhost. (Which refers to the local adresses as you can see from the file itself.)
There may be a solution over on github, which may work (didn't try or build it myself.)
https://gist.github.com/exupero/3228103


text:
Q: Greek month with no punctuation convert to Date using Date.ParseExact I have a Greek date "08 Ιουνιου 2021" which I want to convert to Date. This is not possible because the month is missing some punctuation. The correct month is "Ιουνίου" which actually works correctly via the code below
var greek = new CultureInfo("el-GR").DateTimeFormat;
var dtFormat = DateTime.ParseExact("08 Ιουνίου 2021", "dd' 'MMMM' 'yyyy", greek, DateTimeStyles.None);

Any ideas how to get the month to be formatted correctly?

A: You can try to normalize the month name, using a diacritic insensitive comparison to retrieve the correct Month name from the CultureInfo.DateTimeFormat.MonthGenitiveNames collection, since in some cultures the genitive name is different from the nominative (the date is presented in the form:  8th of June, 2021).
A String.Compare() overload accepts both CultureInfo and CompareOptions arguments.
The IgnoreNonSpace flag: Indicates that the string comparison must ignore nonspacing combining characters, such as diacritics. [...].
This allows to search for the month name, ignoring the missing diacritics, in the MonthGenitiveNames collections and return the corresponding, proper, name.
The normalized date can then be passed to DateTime.TryParse(), along with the provided CultureInfo, to extract the DateTime object.
Sample method call:
var normalizedDateTime = NormalizeMonthDiacritics(new CultureInfo("el-GR"), "08 Ιουνιου 2021");

using System.Globalization;
using System.Linq;

internal DateTime NormalizeMonthDiacritics(CultureInfo culture, string date)
{
    string[] inputDateParts = date.Split();

    inputDateParts[1] = culture.DateTimeFormat.MonthGenitiveNames.FirstOrDefault(month =>
        string.Compare(inputDateParts[1], month, culture, CompareOptions.IgnoreNonSpace) == 0)
        ?? inputDateParts[1];

    string normalizedDate = string.Join(" ", inputDateParts);

    if (DateTime.TryParse(normalizedDate, culture, DateTimeStyles.None, out DateTime dtm)) {
        return dtm;
    }
    else {
        throw new ArgumentException("The provided date cannot be normalized",
              new Exception("Month Genitive form not available"));
    }
}

Since at least 37 cultures use month names composed of 2 or more parts, to make the method more generic and also apply the same procedure to the Abbreviated Month Genitive names, this method could be modified to parse the input date in a slight different way and also allow to specify whether the month name is provided in short format.
The date format can be then composed of these 3 parts:

*

*Numeric value representing either the Day of Month or the Year

*Month part, Genitive Name, in either long format string (MMMM) or short format (MMM)

*Numeric value representing either the Year or the Day of Month

DateTime.TryParse() can handle a DateTime format in both ways.
Call this modified method like this:
var culture = new CultureInfo("sah-RU");
string date = "2020 атырдьах ыиын 08";  // <= Should be атырдьах ыйын
var normalizedDateTime = NormalizeMonthDiacritics(culture, date, false);

Modified method:
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;

internal DateTime NormalizeMonthDiacritics(CultureInfo culture, string date, bool monthShortForm = false)
{
    string pattern = @"(\d+)\s+(.*?)\s+(\d+)";
    var parts = Regex.Match(date, pattern, RegexOptions.CultureInvariant | RegexOptions.Singleline)
                     .Groups.OfType<Capture>().Skip(1).Take(3).Select(c => c.Value).ToArray();

    var monthNames = monthShortForm
                   ? culture.DateTimeFormat.AbbreviatedMonthGenitiveNames
                   : culture.DateTimeFormat.MonthGenitiveNames;

    parts[1] = monthNames.FirstOrDefault(month =>
        string.Compare(parts[1], month, culture, CompareOptions.IgnoreNonSpace) == 0)
        ?? parts[1];

    string normalizedDate = string.Join(" ", parts);

    if (DateTime.TryParse(normalizedDate, culture, DateTimeStyles.None, out DateTime dtm)) {
        return dtm;
    }
    else {
        throw new ArgumentException("The provided date cannnot be normalized",
              new Exception("Month Genitive form not available"));
    }
}

A: I don't know exactly the extension of the problem here - whether the values come from database or whether this is just a single occurrence or whether requires more than first established -
The idea is to create a mapping between the diacritics words( in this case months) and non diacritics.
When the date value 08 Ιουνιου 2021is passed we check it against a mapping of months that contains the diacritics.
The comparison is done by
string.Compare(firstString, secondString, new CultureInfo("el-GR"), CompareOptions.IgnoreNonSpace);

From Msdn documentation - IgnoreNonSpace:
Indicates that the string comparison must ignore nonspacing combining characters, such as diacritics. The Unicode Standard defines combining characters as characters that are combined with base characters to produce a new character. Nonspacing combining characters do not occupy a spacing position by themselves when rendered.
This could/would be a potential fix:
    static string originalValue = "08 Ιουνιου 2021";
    static string[] currentMonth = originalValue.Split(' ');

    static List<string> monthMapping = new List<string>
        {
            //add others months mapping - I dont know how they are spelt -
            "Ιουνίου"
        };

    static void Main(string[] args)
    {
        DateTimeFormatInfo greek = new CultureInfo("el-GR").DateTimeFormat;

        foreach (string month in monthMapping)
        {
            if( string.Compare(currentMonth[1], month, new CultureInfo("el-GR") , CompareOptions.IgnoreNonSpace) == 0)
            {
                var dtFormat = DateTime.ParseExact($"08 {month} 2021", "dd' 'MMMM' 'yyyy", greek, DateTimeStyles.None);
            }

        }
    }