text:
Q: Send a channel alert using a slack bot over post request I used this tutorial to create a Slack bot. Now I want that Slack Bot to send an alert to the channel. However, simply including @channel in the message doesn't work.

A: Firstly, to escape a sequence use < and >.
Secondly, the @ should be replaced with a !.
The format of the message should therefore be:
<!channel> Hello World
This will notify the channel with the message Hello World.
For more information see the docs (particularly the sections on the use of < and > and Variables).


text:
Q: How can I get a clickable icon on the top right corner of a button in flutter? I'm trying to get a clickable icon on the top right corner of a button. I tried adding a FloatingActionButton to a row widget, but it just adds it to the right of the button. I want it floating over the button in the top right corner. Any help would be appreciated. I have a screenshot of how it looks now shown below.
            ButtonTheme (
              minWidth: 250.0,
              height: 80.0,
              buttonColor: Color.fromRGBO(234, 135, 137, 1.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  RaisedButton (
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10.0),
                      side: BorderSide(
                        color: Colors.transparent,
                      ),
                    ),
                    child: Text(
                      'Daily Challenge',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 22.0,
                        fontFamily: 'MuseoSans',
                      ),
                    ),
                    onPressed: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => DailyMedChallenge(uid: user.uid, qidDC: user.qidDC)),
                      );
                    },
                  ),
                  Container(
                    width: 35.0,
                    height: 35.0,
                    child: FloatingActionButton(
                      child: Icon(
                        Icons.help,
                      ),
                      backgroundColor: Colors.grey,
                      onPressed: () {

                      },
                    ),
                  )
                ],
              ),
            ),

A: you can use the Stack and Positioned widget for that

   ButtonTheme (
              minWidth: 250.0,
              height: 80.0,
              buttonColor: Color.fromRGBO(234, 135, 137, 1.0),
              child: Stack(
                 children: [
                  RaisedButton (
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10.0),
                      side: BorderSide(
                        color: Colors.transparent,
                      ),
                    ),
                    child: Text(
                      'Daily Challenge',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 22.0,
                        fontFamily: 'MuseoSans',
                      ),
                    ),
                    onPressed: () {
                     //click actions
                    },
                  ),
                  Positioned( // will be positioned in the top right of the container
                    top: 0,
                    right: 0,
                    child: Icon(
                        Icons.help,
                      ),
                   )
                ]
              )
            ),

redpajama_set_name: RedPajamaStackExchange


text:
Q: Extracting the geometry of the parts not intersecting from 2 shapes overlapping each other in postgresql? This seems simple enough, yet i do not find a clear awnser on that peculiar matter. What i am trying to do is to extract the parts of a shape that doesn't intersect with another when the 2 of them are overlapping. In short, i am looking for something like ST_intersection but in reverse.

A: ST_Difference
Returns a geometry that represents that part of geometry A that does not intersect with geometry B.
postgis.net/docs/ST_Difference.html


text:
Q: Encrypt traffic between traefik and ingress in kubernetes cluster I'm looking for solution how to encrypt traffic between Traefik frontend to kubernetes Ingress resource serving multiple application. The examples on internet, e.g. [1], show how to enable TLS support in Traefik or even use Let's Encrypt for Traefik and Ingress controller [2]. The problem is that all of them pass HTTPs request from frontend to HTTP backend. What I'm looking for is end-to-end encryption between frontend and backends.
I enabled TLS in Traefik as shown in [1], I enabled TLS in Ingress as shown [3], but still all traffic goes from HTTPs to HTTP. And, I don't know who is responsible for this decision (where it should be configured) the Traefik or Ingress.
Any suggestions?

*

*https://medium.com/@patrickeasters/using-traefik-with-tls-on-kubernetes-cb67fb43a948

*https://blog.osones.com/en/kubernetes-ingress-controller-with-traefik-and-lets-encrypt.html

*https://kubernetes.io/docs/concepts/services-networking/ingress/


text:
Q: Laravel\Vue - ajax file upload not working on the production server I have a component where I am uploading a video file, everything works fine on my local machine, and it used to work fine on the production server, Namechap is where I host the project, until only recently I have done some work and made changes, that I saw it doesn't work on the production server anymore.
I am using Vue v. 1.0.28, and this is the upload component, where in the fileInputChange() method I am posting form data, to the /upload endpoint, which on the production server for some reason I can't read in the backend:
<template>

              Upload video
              <input type="file" name="video" id="video" @change="fileInputChange" class="Image-input__input" accept="video/*">

Something went wrong. Please check the video format and try again. If you need any help please contact our support service.

              Please do not navigate away from this page, until the video has finished uploading. Your video will be available at {{ $root.url }}/videos/{{ uid }}, once uploaded.

              Upload complete. Video is now processing. Go to your videos.

                  Title
                  <input type="text" class="form-control" v-model="title">

                  Description
                  <textarea class="form-control" v-model="description"></textarea>

                  <button type="submit" class="btn btn-submit" @click.prevent="update">Save</button>

                  {{ saveStatus }}

</template>

The problem is that on upload in my controller in the store function the request object is empty on the production server, which I got when I did dd($request->all()). Then it fails to find the video, in the network inspector I get a 404 error, which is returned by firstOrFail() method, because it can't find the Video model, since it is missing $request->uid.

No query results for model [App\Video].

This is the controller:
class VideoUploadController extends Controller
{
    public function index()
    {
      return view('video.upload');
    }

    public function store(Request $request)
    {
      $player = $request->user()->player()->first();

      $video = $player->videos()->where('uid', $request->uid)->firstOrFail();

      $request->file('video')->move(storage_path() . '/uploads', $video->video_filename);

      $this->dispatch(new UploadVideo(
          $video->video_filename
      ));

      return response()->json(null, 200);
    }
}

I am not sure what is going on, since on inspecting the network tab in the console I am sending a request payload that looks like this:

------WebKitFormBoundarywNIkEqplUzfumo0A Content-Disposition: form-data; name="video"; filename="Football Match Play.mp4" Content-Type: video/mp4
------WebKitFormBoundarywNIkEqplUzfumo0A Content-Disposition: form-data; name="uid"
159920a7878cb2
  ------WebKitFormBoundarywNIkEqplUzfumo0A--

It is really frustrating since I have no idea how to fix this, when everything is fine on my local machine, not sure what is wrong on the production server and how to fix it?
Update
It started working again on its own, since I have created a ticket in the Namecheap support service, all of sudden after one day, it started working again, I haven't done any changes, and on asking the Namecheap support I have got an answer from them that they haven't done any changes either, so I have no idea what went wrong, which is still a bit frustrating since I would like to avoid that in the future, but at least everything is working now again as it should.

A: Laravel's $request->all() method only pulls from the input, thus in the store() method of VideoUploadController $request->all() return empty object.
In your script, it calls this.store() after checked the isVideo is true while file changes. As a result, there isn't a uid parameter or video parameter.


text:
Q: Another exercise on $L^p-$ spaces. Let $(\Omega,\mathcal{A},\mu)$ and $1<p<\infty$, $f\in L^p(\mu)$ and $\{f_n\}_{n\geq1}$ a bounded sequence in $L^p(\mu)$. Moreover let $$\int_A f_nd\mu\to\int_A fd\mu$$ for $n\to\infty$ and for all $A\in\mathcal{A}$. Show that for all $g\in L^q(\mu)$ such that $1<q<\infty$ we have $$\int_{\Omega}f_ngd\mu\to\int_{\Omega}fgd\mu$$ such that $1/p+1/q=1$.
My thoughts: The thing confusing me the most, is that the exercise doesn't say anything about the measure of $\Omega$. How can I conclude from $A$ to whole $\Omega$ without (sigma)finiteness?
Since $f_n$ is bounded, I know $|f_n|\leq C$ - $C$ being some constant and since $f_n\in L^p(\mu)$ we also have $||f_n||_p\leq C$. I want to argue that $\int |(f_n-f)g|d\mu\leq (\int |(f_n-f)|^p)^{1/p}\cdot(\int|g|^qd\mu)^{1/q}$ using Hölder. I think I have most of the pieces required for the exercise but I'm unable to put them together.

A: Hint: Approximate $g$ in $L^q$ by linear combinations $h$ of indicator functions of sets.
$$\left|\int_\Omega (f_n - f) g \; d\mu\right| \le
\left| \int_\Omega (f_n - f) h \; d\mu\right| + \|f_n - f\|_p \|g - h\|_q $$


text:
Q: Azure AD Import using Graph API works for random applications I am using Graph API to import users from Azure AD. In my active directory I am configuring application following this link .
In my code I am generating an accesstoken and pass that access token to get user list.
//get token

            String secretKey = EncryptionUtils.decryptAES(encodedSecretKey);
            secretKey = URLEncoder.encode(secretKey);
            String urltoConnect = loginUrlPrefix+tenantId+loginUrlSufix;
            String payLoad = "resource=https%3A%2F%2Fmanagement.core.windows.net%2F&client_id="+clientId+"&grant_type=client_credentials&client_secret=" + secretKey;
            System.out.println(payLoad);
            URL url = new URL(urltoConnect);
            URLConnection connection = null;
            connection = url.openConnection();
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setDoOutput(true);
            java.io.OutputStreamWriter wr = new java.io.OutputStreamWriter(connection.getOutputStream());
            wr.write(payLoad);
            wr.flush();
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String content;
            String html = "";
            while ((content = br.readLine()) != null) {
                if (!content.equals("") && content.length() != 0)
                    html += content.trim();
            }
            return html;

//get user list

            URL url = new URL(String.format("https://graph.windows.net/%s/users?api-version=2013-04-05", tenant,
                    accessToken));

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // Set the appropriate header fields in the request header.
            conn.setRequestProperty("api-version", "2013-04-05");
            conn.setRequestProperty("Authorization","Bearer "+ accessToken);
            conn.setRequestProperty("Accept", "application/json;odata=minimalmetadata");
            String goodRespStr = HttpClientHelper.getResponseStringFromConn(conn, true);
            int responseCode = conn.getResponseCode();
            org.json.JSONObject response = HttpClientHelper.processGoodRespStr(responseCode, goodRespStr);
            org.json.JSONArray users;

            users = JSONHelper.fetchDirectoryObjectJSONArray(response);

If I add multiple applications it works for few gives this error for rest

{   "odata.error": {
      "code": "Authorization_RequestDenied",
      "message": {
        "lang": "en",
        "value": "Insufficient privileges to complete the operation."
      }   } }

A: Once you click "Grant Permissions" button the change needs time (could be well more than 10 minutes) to be applied, can you wait for that amount of time and then try again - does the issue still exist?


text:
Q: Excel Conditional Formula I am trying to set some conditional formatting in excel. Specifically, 2 statements in one conditional rule.
I am capturing a field called 'expiry date'. When the date is exceeded I want to change the color as well as the text within the cell.
I have achieved 50% of this already with the below statement. The below statement is calculating when the date is exceeded based off of Today's date - then Excel is changing the color of the cell to RED.
 =IF($G$8="","",$G$8<=TODAY())

However, how do I get the text in the cell to then change from e.g. "in date" to "expired". I am currently selecting the text "in date" and "expired" from a data validation list.


text:
Q: WCF and SQL error I am building a simple WCF service that has to return some data from an SQL table. When i run the project i get the following error:

Failed to invoke the service. Possible causes: The service is offline or inaccessible; the client-side configuration does not match the proxy; the existing proxy is invalid. Refer to the stack trace for more detail. You can try to recover by starting a new proxy, restoring to default configuration, or refreshing the service

If i comment all the SQL part and send some static data everything is working fine.
This is the function that is giving me headache :
public Client getClient(int idClient)
{
    Client c = new Client();
    SqlConnection sql = new SqlConnection(@"Data Source=GRIGORE\SQLEXPRESS;Initial Catalog=testWCF;Integrated Security=True");
    sql.Open();

    SqlCommand cmd = new SqlCommand("Select * from Clienti where id = " + idClient);
    SqlDataReader dr = cmd.ExecuteReader();
    if (dr.Read())
    {
        c.idClient = int.Parse(dr["id"].ToString());
        c.numeClient = dr["nume"].ToString();
    }

    dr.Close();
    sql.Close();

    return c;
}

Ideas ?

A: You're not setting the Connection property of your SqlCommand instance.  You need to do this:
    SqlCommand cmd = new SqlCommand("Select * from Clienti where id = " + idClient);
    cmd.Connection = sql;  // added Connection property initialization
    SqlDataReader dr = cmd.ExecuteReader();

Or you can just inject this into your constructor:
    SqlCommand cmd = new SqlCommand("...your query text", sql);

A: Actually, your code should be more like this:
public Client getClient(int idClient)
{
    var c = new Client();
    using (var sql = new SqlConnection(@"Data Source=GRIGORE\SQLEXPRESS;Initial Catalog=testWCF;Integrated Security=True"))
    {
        sql.Open();

        using (var cmd = new SqlCommand("Select * from Clienti where id = " + idClient, sql))
        {
            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                if (dr.Read())
                {
                    c.idClient = int.Parse(dr["id"].ToString());
                    c.numeClient = dr["nume"].ToString();
                }
            }
        }
    }

    return c;
}

By placing the connection, command and reader in using blocks, you ensure that they are disposed of, even if an exception is thrown. You also don't need the explicit Close calls in this case, as disposing of the objects takes care of that for you.


text:
Q: Get DbSet from type I am attempting to make a generic table viewer/editor for an MVC 6 application.
I currently use
Context.GetEntityTypes();

To return me a list of tables.
Now I need to fetch the data for a specific type. My current implementation is:
// On my context
public IQueryable<dynamic> GetDbSetByType(string fullname)
{
    Type targetType = Type.GetType(fullname);

    var model = GetType()
        .GetRuntimeProperties()
        .Where(o =>
            o.PropertyType.IsGenericType &&
            o.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>) &&
            o.PropertyType.GenericTypeArguments.Contains(targetType))
        .FirstOrDefault();

    if (null != model)
    {
        return (IQueryable<dynamic>)model.GetValue(this);
    }

    return null;
}

With this code in my controller
[HttpGet("{requestedContext}/{requestedTable}/data")]
public IActionResult GetTableData(string requestedContext, string requestedTable)
{
    var data = Request.Query;
    var context = GetContext(requestedContext);

    if (context == null)
    {
        return new ErrorObjectResult("Invalid context specified");
    }
    var entity = context.GetEntity(requestedTable);

    if (entity == null)
    {
        return new ErrorObjectResult("Invalid table specified");
    }

    var set = context.GetDbSetByType(entity.ClrType.AssemblyQualifiedName);

    if (set == null)
    {
        return new ErrorObjectResult("Invalid table specified - DbSet could not be found");
    }

    var start = Convert.ToInt32(data["start"].ToString());
    var count = Convert.ToInt32(data["length"].ToString());
    var search = data["search[value]"];

    return new ObjectResult(set.Skip(start).Take(count));
}

As it is, this will return the data of length count and from position start. However I cannot perform queries on the specific properties of the IQueryable<dynamic>.
The problem is:

*

*This seems like a trivial thing to do, so I am almost sure I am missing something - this must be easy to do.

*If not 1, then how would I convert my object set back to a DbSet<T> so I can perform my queries? If I set a breakpoint and inspect I can see all my data just sitting there.

NOTE: This is EF7
ADDITIONAL INFO:

*The requestedTable is the fully qualified type EG: <mysystem>.Models.Shared.Users
EDIT (2016/5/5)
I ended up just doing it all in plain SQL - if anyone does manage to get this working please let me know!

A: This would be simpler by using a generic method and using DbContext.Set<TEntity>(). You can create a generic method at runtime like this:
public IActionResult GetTableData(string requestedContext, string requestedTable)
{
    var context = GetContext(requestedContext);

    if (context == null)
    {
        return new ErrorObjectResult("Invalid context specified");
    }
    var entity = context.GetEntity(requestedTable);

    if (entity == null)
    {
        return new ErrorObjectResult("Invalid table specified");
    }

    var boundMethod = s_getTableDataMethodInfo.MakeGenericMethod(entity.ClrType);
    return boundMethod.Invoke(this, new object[] { context }) as IActionResult;
}

private static readonly MethodInfo s_getTableDataMethodInfo
    = typeof(MyController).GetTypeInfo().GetDeclaredMethod("GetTableDataForEntity");

private IActionResult GetTableDataForEntity<TEntity>(DbContext context)
    where TEntity : class
{
    var data = Request.Query;
    var start = Convert.ToInt32(data["start"].ToString());
    var count = Convert.ToInt32(data["length"].ToString());
    var search = data["search[value]"];

    return new ObjectResult(context.Set<TEntity>().Skip(start).Take(count));
}

A: I know that this is a rather old question and there have been many changes over time. Nowadays in EF Core 5 & 6 the desired result can be achieved very simplistically.
In the background the EF stores a list with all types which are mapped. This can be accessed via DbContext.DbSet<T>.
This would look like this:
private IQueryable<T> GetDbSetByType<T>() where T : class
{
    return DbContext.Set<T>().ToList();
}

Of course, a more
complex query can follow. For the sake of simplicity, I have omitted this here.


text:
Q: wordpress passing parameter to custom template I am using wordpress.
I have created a page dealer-profile from admin and assigned  a template to it. Now I want to pass a parameter like
SITE-URL/dealer-profile/SUV

I have added following into my .htaccess
RewriteRule ^dealer-profile/([a-zA-Z0-9_-]+)(|/)$ index.php?pagename=dealer-profile&dealer=$1 [QSA]

I have also tried following
add_rewrite_rule('dealer-profile/([^/]+)', 'index.php?pagename=dealer- profile&dealer=$matches[1]', 'top');
flush_rewrite_rules(false);

when I am requesting SITE-URL/dealer-profile/SUV, it automatically redirects to SITE-URL/dealer-profile
Please suggest, where I am wrong.
Now I am doing following
function themeslug_query_vars( $qvars ) {
  $qvars[] = 'dealer';
  return $qvars;
}
add_filter( 'query_vars', 'themeslug_query_vars' , 10, 1 );
function add_rewrite_rules($aRules) {
    $aNewRules = array('dealer-profile/([^/]+)/?$' => 'index.php?pagename=dealer-profile&dealer=$matches[1]');
    $aRules = $aNewRules + $aRules;
    return $aRules;
}
add_filter('rewrite_rules_array', 'add_rewrite_rules');

But this is working for digits only like
- test/dealer-profile/234234/ is working
- test/dealer-profile/234234/ is not working
Solution
Ref : http://codex.wordpress.org/Class_Reference/WP_Rewrite
add_filter( 'rewrite_rules_array','my_insert_rewrite_rules' );
add_filter( 'query_vars','my_insert_query_vars' );
add_action( 'wp_loaded','my_flush_rules' );
// flush_rules() if our rules are not yet included
function my_flush_rules(){
    $rules = get_option( 'rewrite_rules' );

    if ( ! isset( $rules['(dealer-profile)/(.*)$'] ) ) {
        global $wp_rewrite;
        $wp_rewrite->flush_rules();
    }
}

// Adding a new rule
function my_insert_rewrite_rules( $rules )
{
    $newrules = array();
    $newrules['dealer-profile/(.*)$'] = 'index.php?pagename=dealer-profile&dealer=$matches[1]';
    return $newrules + $rules;
}

// Adding the id var so that WP recognizes it
function my_insert_query_vars( $vars )
{
    array_push($vars, 'dealer');
    return $vars;
}

Thanks A lot for Your Help @@jnhghy - Jantea Alexandri

A: You need to create a function to add query variables to query string and then hook that function into the query_vars hook:
function add_query_vars($aVars) {
$aVars[] = "dealer-profile"; // represents the name of the variable that you want to pass
}

// hook add_query_vars function into query_vars
add_filter('query_vars', 'add_query_vars');

then we need to add the rewrite rule:
function add_rewrite_rules($aRules) {
function add_rewrite_rules($aRules) {
$aNewRules = array('dealer-profile/([^/]+)/?$' => 'index.php?pagename=dealer-profile=$matches[1]');
$aRules = $aNewRules + $aRules;
return $aRules;
}

// hook add_rewrite_rules function into rewrite_rules_array
add_filter('rewrite_rules_array', 'add_rewrite_rules');

Getting the variable:
if(isset($wp_query->query_vars['dealer-profile'])) {
$sMsdsCat = urldecode($wp_query->query_vars['dealer-profile']);
}

and this should do the trick,
and here are some extra link for "advanced rules":
http://www.rlmseo.com/blog/passing-get-query-string-parameters-in-wordpress-url/
http://www.prodeveloper.org/create-your-own-rewrite-rules-in-wordpress.html
EDIT: let us try the steps that we have in the second article:
First let's create the tag and add it to the rewrite rules (this should work for alpha-numeric values:
function createRewriteRules() {
    global $wp_rewrite;

    // add rewrite tokens
    $dealertag = '%dealertag%';
    $wp_rewrite->add_rewrite_tag($dealertag, '(.+?)', 'dealer-profile=');

    $keywords_structure = $wp_rewrite->root . "dealer-profile/$dealertag/";
    $keywords_rewrite = $wp_rewrite->generate_rewrite_rules($keywords_structure);

    $wp_rewrite->rules = $keywords_rewrite + $wp_rewrite->rules;
    return $wp_rewrite->rules;
}
add_action('generate_rewrite_rules', 'createRewriteRules');

Then hook generate rules like this:
function add_rewrite_rules( $wp_rewrite )
{
        add_rewrite_rule('^dealer-profile/([^/]*)/?','index.php?page_id=12&dealer-profile=$matches[1]','top');
}
add_action('generate_rewrite_rules', 'add_rewrite_rules');

add the variable to query vars:
function query_vars($public_query_vars) {
    $public_query_vars[] = "dealer-profile";
    return $public_query_vars;
add_filter('query_vars', 'query_vars');

bonus:
To debug your rules you can use this function:
function dev4press_debug_rewrite_rules() {
  global $wp_rewrite;
  echo '
';
  if (!empty($wp_rewrite->rules)) {
    echo '
Rewrite Rules
';
    echo '

';
    echo 'Rule	Rewrite	';
    echo '

';
    foreach ($wp_rewrite->rules as $name => $value) {
      echo '
'.$name.'	'.$value.'
';
    }
    echo '

';
  } else {
    echo 'No rules defined.';
  }
  echo '
';
}

it's from https://docs.dev4press.com/tutorial/wordpress/debug-wordpress-rewrite-rules-matching/ and it should show you all your rules in a table format, just include it in any of your templates and check if the above functions are adding the rewrite rules correctly if not, it should give you some extra info about what didn't worked.
And you can also use the well known Developer plugin to inspect your rules, you'll get extra info with this plugin!!!


text:
Q: What is the syntax error in this sql snippet? <?php

$link = mysql_connect(`localhost`, `username`, `password`);
if (!$link) {
    die(`Could not connect: ` . mysql_error());
}
echo `Connected successfully`;
mysql_select_db(ebe);

?>

I went through the above SQL snippet a bunch of times but for some reason i cant figure out the error. I have tried changing the quotes from '' to `` but it hasn't worked either.

A: The back-tick characters are special to PHP. They run the string inside the back-ticks as a shell command.
Read the doc here: http://php.net/manual/en/language.operators.execution.php
Use single-quotes or double-quotes in PHP for string literal delimiters.
PS: There are other problems in your code, as commented by @fvu. You're using the deprecated mysql extension (you should be using PDO). You have a word ebe which looks like you're using it like a PHP constant. Not sure if you intend this to be a string or a variable.


text:
Q: ¿Cómo puedo eliminar o actualizar una registro que está relacionado con otras tablas MySQL? Necesito eliminar o actualizar este registro para un proyecto con Angular con api en Python pero está relacionado con la tabla de facturas, y para el CRUD debo hacer que un botón elimine o actualice el registro, pero siempre arroja error o no lo elimina...
Este es el método en la API:
@cross_origin()
@app.route('/delate_contact/<tabla>/<id>', methods=['DELETE'])

def delate_contact(tabla,id):
    if(tabla == "paciente"):

        columna_id = "paciId"

    elif(tabla == "odontologo"):

        columna_id = "odonId"

    elif(tabla == "factura"):

        columna_id = "facId"

    elif(tabla == "consulta"):

        columna_id = "conId"

    elif(tabla == "tratamiento"):

        columna_id = "trataId"

    cur = mysql.connection.cursor()

    #cur.execute("DELETE FROM "+str(tabla)+" WHERE "+str(columna_id)+" = "+str(id))

    cur.execute("DELETE FROM "+str(tabla)+" WHERE "+str(columna_id)+" IN ("+str(id)+")")

    mysql.connection.commit()

    # return mensajeRegistroEliminado(tabla)

    return jsonify({"Alerta":"Registro eliminado!"})

¿qué puedo hacer? he visto varias respuestas pero no sé cómo acoplarlas a lo que necesito...
¿estaría bien desvincular las tablas?


text:
Q: pyspark logs not getting logged when its been triggered using python process i am running a spark script from a bash wrapper which is being triggerd from another python script using subprocess. The issue is even though job is running fine , I don't see the spark logs in my logfile.
here is the code which actually runs the bash wrapper which includes the pyspark job.
 def run_bash_cmd(self, cmd, errormsg="FAILED : ", max_retries=3, encoding=None):
        logging.info("COMMAND : %s", cmd)
        attempt = 1
        while attempt <= max_retries:
            try:
                command = subprocess.Popen(
                    cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True
                )
                data, error = command.communicate()

                if command.poll() != 0:
                    logging.warning("Attempt %s failed. Retry in 10 seconds.", attempt)
                    attempt += 1
                    Time.sleep(10)
                    continue
                return data.decode() if encoding is None else data.decode(encoding)
            except subprocess.CalledProcessError as e:
                logging.warning("Attempt %s failed. Retry in 10 seconds", attempt)
                attempt += 1
                Time.sleep(10)

        # spark-submit writes error to stdout rather than stderr so logging stdout as well in case of error
        if encoding is None:
            logging.error(data.decode())
        else:
            logging.error(data.decode(encoding))
        logging.error(error.decode("utf-8"))
        msg = "{0}\nError while running command '{1}' on {2}".format(
            errormsg, cmd, self.server
        )

how can I improve this so that i can also see the spark logs in real time rather and buffer and print it


text:
Q: Using requests for multipart/form data for API I am trying to use requests for a multipart data submission on SpeechMatics API.
The API is declared like this in curl:
curl -F data_file=@my_audio_file.mp3 -F model=en-US "https://api.speechmatics.com/v1.0/user/17518/jobs/?auth_token=<some token>" # transcription

Where data file is supposed to be the local path and model is the language as per the documentation here, https://app.speechmatics.com/api-details#getJobs
Using the requests library, my code is as below, but seems to fail to upload the file:
import Requests

path = 'https://api.speechmatics.com/v1.0/user/userID/jobs'
token = {'auth_token':<some token>}

data_file = open('F:\\user\\Bern\\Data Files\\audio.flac','rb')
model = 'en-US'

r = requests.post(path,params=token,files={'data_file':data_file,'model':model})

I get Reponse 200 but the file seems to fail to upload.

A: I think this is what you're looking for
import requests

files = {
    'data_file': open('my_audio_file.mp3', 'rb'),
    'model': 'en-US'
}

requests.get('https://api.speechmatics.com/v1.0/user/17518/jobs/?auth_token=<some token>', files=files)

A: I was guided by a post to use both the data and files parameter for the API.
Below is the cut and paste code that I used.
post_api = 'https://api.speechmatics.com/v1.0/user/17518/jobs/?auth_token=<some token>'
path = input()
files = [os.path.join(path,f) for f in os.listdir(path) if f.endswith('.mp3')]

l = []

for file in files:
    with open(file, 'rb') as f:

        files = {
            'data_file': f
        }
        data = {'model': 'en-AU'}

        r = requests.post(post_api,data = data,files=files)
        l.append(r)

    f.closed


text:
Q: How to allow for encoded slashes in an Elastic Beanstalk Load Balancer environment I'm running into an issue where certain URLs passed to my Elastic Beanstalk Environment are containing slashes inside the URL's parameters e.g.:
https://example.com/param1=this/that/param2=....
These URL's are valid in the context that my application can process the slashes correctly in local testing. In production on EB, the Apache server EB uses as default decodes the slashes, causing 404's to be returned to the user. I am not very up to date on my Apache knowledge. What is the best and most efficient way to set the argument: AllowEncodedSlashes NoDecode in my Apache configurations dynamically on envrionment launch?
Obviously, ssh-ing into my instances to make the change is far from ideal and will not last past a reload. Is it possible to set it using my applications .ebextensions in some way?
EDIT:
To give some more details, I am using a load-balanced EB environment that uses HTTPS and is running a Django application (with mod_wsgi)
This is my wsgi.conf file taken from one of my instances:
LoadModule wsgi_module modules/mod_wsgi.so
WSGIPythonHome /opt/python/run/baselinenv
WSGISocketPrefix run/wsgi
WSGIRestrictEmbedded On

<VirtualHost *:80>

Alias /static/ /opt/python/current/app/static/
<Directory /opt/python/current/app/static/>
Order allow,deny
Allow from all
</Directory>

WSGIScriptAlias / /opt/python/current/app/test_app/wsgi.py

AllowEncodedSlashes NoDecode

<Directory /opt/python/current/app/>
  Require all granted
</Directory>

WSGIDaemonProcess wsgi processes=1 threads=15 display-name=%{GROUP} \
  python-path=/opt/python/current/app:/opt/python/run/venv/lib64/python3.4/site-packages:/opt/python/run/venv/lib/python3.4/site-packages user=wsgi group=wsgi \
  home=/opt/python/current/app
WSGIProcessGroup wsgi
</VirtualHost>

LogFormat "%h (%{X-Forwarded-For}i) %l %u %t \"%r\" %>s %b     \"%{Referer}i\" \"%{User-Agent}i\"" combined

Is this the file I have to edit? Wouldn't the EB enviornemnt overwrite my changes on an environment reboot?

A: Check below sample configuration for Apache to take care of the Encoded slashes. Remember this is just a sample. You have to manipulate your Apache code by taking reference of below code, as you have not pasted your apache host file it in your question.
<VirtualHost *:80>
  <Proxy *>
    Order deny,allow
    Allow from all
  </Proxy>

  ProxyPass / http://localhost:8080/ retry=0
  ProxyPassReverse / http://localhost:8080/
  ProxyPreserveHost on
  AllowEncodedSlashes NoDecode
  LogFormat "%h (%{X-Forwarded-For}i) %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\""
  ErrorLog /var/log/httpd/elasticbeanstalk-error_log
  TransferLog /var/log/httpd/elasticbeanstalk-access_log
</VirtualHost>


text:
Q: Accessing post or get parameters in custom authorization MVC4 Web Api Is it possible to access post or get parameters via the HttpActionContext object?
I have a set of sensors that loggs data to a web server that provides a REST api. I would like to introduce some sort of authentication/authorization by letting the sensors include their hardware id in the data and then make a lookup in a database to see if the id exists or not. Since the API provides many web api action methods I would ideally like to use a custom authorization attribute
public class ApiAuthorizationFilter : AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        return false;
    }
}

How can I access the post/get data from the actionContext?
EDIT:
Example of POST
POST /Api/api/ActionMethod/ HTTP/1.1\r\n
Content-Type: application/json\r\n
Host: localhost\r\n
Accept: */*\r\n
Content-Length:52\r\n
\r\n
{"Id": '121a222bc', "Time": '2012-02-02 12:00:00'}\r\n

Have a nice day!

A: Due to its nature the AuthoriseAttribute looks like it is called in the pipeline before the model binders and parameter bindings have run. You also run into issues when you access the Request.Content and read from it... this can only be done once and if you are going to try it in your auth attribute you may break the mediaTypeFormater...

in WebAPI, the request body (an HttpContent) may be a read-only, infinite, non-buffered, non-rewindable stream.

Update
There are different ways of specifying the execution context... http://msdn.microsoft.com/en-us/library/system.web.http.filters.filterscope(v=vs.108).aspx. The AuthoriseAttribute is "Global" and therefore it is hit too early to access the action information.
Given you want access to the model and parameters you can change your approach slightly and use an OnActionExecuting filter ("Action" filter scope) instead and throw a 401 or 403 based on your validation.
This filter is called later in the execution process and you therefore have full access to the bound data.
Very simple example below:
public class ApiAuthorizationFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        Foo model = (Foo)actionContext.ActionArguments["model"];
        string param1 = (string)actionContext.ActionArguments["param1"];
        int param2 = (int)actionContext.ActionArguments["param2"];

        if (model.Id != "1")
            throw new HttpResponseException(System.Net.HttpStatusCode.Forbidden);

        base.OnActionExecuting(actionContext);
    }
}

Example controller:
public class Foo
{
    public string Id { get; set; }
    public DateTime Time { get; set; }
}

public class FoosController : ApiController
{
    // PUT api/foos/5
    [ApiAuthorizationFilter]
    public Foo Put(int id, Foo model, [FromUri]string param1 = null, int? param2 = null)
    {
        return model;
    }
}

What the other answers were saying.... they are right you can, if you can access all you need on the URL, get at stuff via the request; however, I think the model and the request content should be left alone:
var queryStringCollection = HttpUtility.ParseQueryString(actionContext.Request.RequestUri.Query);

    //example for param1
    string param1 = queryStringCollection["param1"];
    //example for param2
    int param2 = int.Parse(queryStringCollection["param2"]);
    //Example of getting the ID from the URL
    var id = actionContext.Request.RequestUri.Segments.LastOrDefault();

A: I accessed the context route data to get the parameters from within a custom AuthorizeAttribute when calling something like /api/client/123/users:
public class CustomAuthorizeAttribute : AuthorizeAttribute
  {
     protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
     {
        var clientId = Convert.ToInt32(actionContext.ControllerContext.RouteData.Values["clientid"]);

        // Check if user can access the client account.

     }
  }

A: You can access query string values from your custom authorize attribute by using the following code:
public class ApiAuthorizationFilter : AuthorizeAttribute
{
    protected override void OnAuthorization(AuthorizationContext filterContext)
    {
        var querystring = filterContext.RequestContext.HttpContext.Request.QueryString;
        // Do what you need
    }
}

A: Although this question has already been answered. But in case someone else needs it, you can get the querystrings from ActionFilterAttribute like below:
public class ApiAuthorizationActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var queryParameters = actionContext.Request.GetQueryNameValuePairs().ToDictionary(x => x.Key, x => x.Value);

        var some_value = queryParameters.ContainsKey("some_key")
                    ? queryParameters["some_key"] : string.Empty;

        // Log Action Filter call
        base.OnActionExecuting(actionContext);
    }
}

But usually how I build API authorizations are using headers and a custom verification logic by adding keys (unique strings) to the database against user/client etc.
public class ApiAuthorizationActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var headers = actionContext.Request.Headers.ToDictionary(x => x.Key, x => x.Value);

        string api_key = headers.ContainsKey("api_key") ? headers["api_key"].FirstOrDefault() : null;

        bool canAccessApi = IsValidKey(api_key);

        if (!canAccessApi)
            actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "You do not have access to this API. Please use a valid key.");

        // Log Action Filter call
        base.OnActionExecuting(actionContext);
    }

    private bool IsValidKey(string api_key)
    {
        //Build Access Control Logic here using database keys...
        return true;
    }
}

A: You should be able to get this information from actionContext.Request
That is the way to get to the request data.
The posted data is in actionContext.Request.Content
Or if it's a GET request you could get the querystring from actionContext.Request.RequestUri


text:
Q: Connecting two hypersurfaces in R^{n+1} by embedded curves Let $M^n$ be a smooth closed embedded hupersurface in $\mathbb R^{n+1}$.
Denote by $D$ the bounded connected component of $\mathbb R^{n+1}\backslash M$.
We assume that $\mathbb R^{n+1}\backslash D$ is simply connected.
Let $B=B_R^n$ be the ball centered at the origin with radius $R>>1$ whose boundary is denoted by $S$.
Question: Does there exist a smooth map
$$F:M\times [0,1]\rightarrow \bar B\backslash D$$
such that:
1) $F(x,0)=x,$, $f(x, 1)\in S,  \forall x\in M$,
2) For any fixed $x\in M$, $F(x,\cdot):[0,1]\rightarrow \bar B\backslash D$ is injective.
The motivation of this question comes from several complex variables, where $M$ is taken to be the boundary of a bounded domain.

A: It seems that once you let your ball $B$ be large enough to contain $M$ with some its neighborhood $M\times[0,1]$, the question is about keeping the bottom copy $M\times \{0\}$ (boundary of $D$) fixed and deforming the top copy $M\times\{ 1\}$ to the sphere $S$. You can look at a compact surface in $\mathbb{R}^3$: choose an open disk on it and organize a flow outside of this disk so that it shrinks the complement of the disk to a point. This could be impossible to do if you want to deform staying always in $M\times [0,1] \subset \mathbb{R}^{n+1}$ but if you don't require this, it seems that it's easy.


text:
Q: Setting Up Fish Shell Profile I am trying to set up my fish shell profile via  the ~/.config/fish/config.fish command. I did not have a config.fish file and had to create my own after the install.
The main reason I want to update this profile is to show my current GitHub location in the terminal. I found the following settings online:
set -g -x fish_greeting ''
# fish git prompt
set __fish_git_prompt_showdirtystate 'yes'
set __fish_git_prompt_showstashstate 'yes'
set __fish_git_prompt_showupstream 'yes'
set __fish_git_prompt_color_branch yellow
# Status Chars
set __fish_git_prompt_char_dirtystate ' '
set __fish_git_prompt_char_stagedstate '→'
set __fish_git_prompt_char_stashstate '↩'
set __fish_git_prompt_char_upstream_ahead '↑'
set __fish_git_prompt_char_upstream_behind '↓'
function fish_prompt
printf ' '
set last_status $status
set_color $fish_color_cwd
printf '%s' (prompt_pwd)
set_color normal
printf '%s ' (__fish_git_prompt)
set_color normal
end
alias ls='ls -GFh'
alias fishprofile='nano ~/.config/fish/config.fish'
alias reboot='source ~/.config/fish/config.fish'
alias home='cd $HOME/Desktop'
function nvm
bass source ~/.nvm/nvm.sh ';' nvm $argv
end
cd ~/Desktop

After the code is pasted into the file path I am able to access the current GitHub terminal location, but as soon as the terminal has been relaunched this feature is gone. Any ideas on how to save this setting?

A: If you use the Fish way of doing things, there is no need for a config.fish file.  What you show above is for compatibility reasons, and attempts to appease the config-file people.  Fish's way of doing things is to define functions (instead of aliases) inside of individual files located (usually) at ~/.config/fish/functions/ .  Variables are set and exported on the command-line, and are persistent.
See this page for more information about my points.


text:
Q: Read an image file C++ and put it on a socket i'm trying to develop a little web server in C++ but i have a problem when i try to read an image file and write it in a socket buffer.
I found a similar function written in C that works perfectly, i cannot understand why my method doesn't work, when i connect to the server by browser and open an image file i got this output.
"The image "http://127.0.0.1:7777/myimage.jpg" cannot be displayed because it contains errors."
This is my method:
std::string
Client::getFileContent(const std::string& name)
{
    std::ifstream f;     f.open(name.c_str(), std::ios::binary);
    if( !f.is_open() )  {
        return (std::string(""));

    }  else  {
        f.seekg(0, std::ios::end);
        unsigned int length = f.tellg();
        f.seekg(0, std::ios::beg);

        char* buffer = new char[length];
        f.read(buffer, length);

        f.close();

        return ( std::string(buffer) );
    }

}

And then i write it in a socket buffer(use nspr socket):
void
Socket::send(const std::string& s)
{
    if(PR_Send(sock, s.c_str(), s.length(), 0, PR_INTERVAL_NO_WAIT) == -1)  {
        throw ( Exception::Exception(Exception::Exception::SOCKET_SEND) );
    }
}

And this is the function i found on web, i cannot understand why this works perfectly and mine doesn't work O.o:
    while ( (ret = read(file_fd, buffer, BUFSIZE)) > 0 ) {
        (void)write(fd,buffer,ret);

Thank you very much :)

A: You problem is here:
return ( std::string(buffer) );

Creating a string from a char * will stop at the first 0 byte, while an image may contain a lot. instead of returning a string, return a vector<char> like
return std::vector<char>(buffer, buffer + length);


text:
Q: Automapper - Map Complex object from Dictionary I'm trying to map this:
var values = new Dictionary<string, object>()
{
    ["Address.City"] = "New York",
    ["FirstName"] = "First Name",
    ["LastName"] = "Last Name"
};

into this:
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public Address Address { get; set; }
}

public class Address
{
    public string City { get; set; }
}

If I don't change any config, I get Address as null. I've tried different approaches. A resolver or just editing my dictionary in the MapperConfiguration like this:
var config = new MapperConfiguration(cfg => {
    const string addressPrefix = "Address.";

    cfg.CreateMap<IDictionary<string, object>, Person>()
    .ForMember(x => x.Address, x => x.MapFrom(c => new Dictionary<string, object>(c.Where(dic => dic.Key.StartsWith(addressPrefix)).ToDictionary(dic => dic.Key.Replace(addressPrefix, string.Empty), dic => dic.Value))));

    cfg.CreateMap<IDictionary<string, object>, Person>()
        .ForMember(dest => dest.Address, opt => opt.ResolveUsing<PersonResolver>());
});
var mapper = config.CreateMapper();
var person = mapper.Map<Person>(values);

Both cases I successfully get the Address mapped right, but I lose the First and Last Name. Is there a way to reset the mapper to default for other members?
My resolver:
public class PersonResolver : IValueResolver<IDictionary<string, object>, Person, Address>
{
    public Address Resolve(IDictionary<string, object> source, Person destination, Address destMember, ResolutionContext context)
    {
        const string addressPrefix = "Address.";
        var address = new Address();

        if (source.Keys.Any(x => x.StartsWith(addressPrefix, StringComparison.InvariantCulture)))
        {
            var addressItems = source
                .Where(dic => dic.Key.StartsWith(addressPrefix, StringComparison.InvariantCulture))
                .ToDictionary(dic => dic.Key.Replace(addressPrefix, string.Empty, StringComparison.InvariantCulture), dic => dic.Value);

            address = context.Mapper.Map<Address>(addressItems);
        }
        return address;
    }
}


text:
Q: How to get the value of the objective function from glmnet in R? I can obtain a lasso or ridge regression fit with
cvfit <- cv.glmnet(X, y)

I know how to get the best value of lambda out
lambda.min <- cvfit$lambda.min

and how to get the best mean squared error out
mse <- cvfit$cvm[cvfit$lambda == lambda.min]

How can I get the value of the objective function?

A: I'm not sure if glmnet gives access to the value of the objective function, but it is easy to calculate ourselves. Here is a little example for LASSO.
library(glmnet)

x <- as.matrix(mtcars[c("hp", "cyl", "wt", "gear")])
y <- mtcars$mpg

cvfit = cv.glmnet(x, y, alpha = 1)  # alpha = 1 for LASSO

We can use coef to get the model's coefficients, and then calculate the objective function value from its definition.
coefs <- coef(cvfit, s = "lambda.min")
objective <- sum((y - coefs[1] - (x %*% coefs[-1]))^2) +
             cvfit$lambda.min * sum(abs(coefs[-1]))
objective

Ridge regression is similar: use alpha = 0 instead and replace sum(abs(coefs[-1])) with sum(coefs[-1]^2).


text:
Q: error when setting correct resolution after install Nvidia 340 drivers I have ubuntu 14.04 and installed the recommended driver for Nvidia but resolution still 1360x768 which I need to change to 1920x1080
here is driver I installed

Xrandr values below
mohamed@mohamed-Work:~$ xrandr
Screen 0: minimum 8 x 8, current 1360 x 768, maximum 8192 x 8192
DVI-I-0 connected primary 1360x768+0+0 (normal left inverted right x axis y axis) 0mm x 0mm
   1024x768       60.0 +
   1360x768       60.0*    59.8
   1152x864       60.0
   800x600        72.2     60.3     56.2
   680x384        60.0     59.8
   640x480        59.9
   512x384        60.0
   400x300        72.2
   320x240        60.1
DVI-I-1 disconnected (normal left inverted right x axis y axis)
DP-0 disconnected (normal left inverted right x axis y axis)
DP-1 disconnected (normal left inverted right x axis y axis)
DP-2 disconnected (normal left inverted right x axis y axis)
DP-3 disconnected (normal left inverted right x axis y axis)

what I did is creating new mode like this
xrandr --newmode "1920x1080"  173.00  1920 2048 2248 2576  1080 1083 1088 1120 -hsync +vsync

then adding new mode like this
xrandr --addmode DVI-I-0 1920x1080_60.00

but I got an error below
mohamed@mohamed-Work:~$ xrandr --addmode DVI-I-0 1920x1080_60.00
X Error of failed request:  BadMatch (invalid parameter attributes)
  Major opcode of failed request:  140 (RANDR)
  Minor opcode of failed request:  18 (RRAddOutputMode)
  Serial number of failed request:  33
  Current serial number in output stream:  34

and my xorg.conf file listed below
# nvidia-settings: X configuration file generated by nvidia-settings
# nvidia-settings:  version 331.20  (buildd@roseapple)  Mon Feb  3 15:07:22 UTC 2014

Section "ServerLayout"
    Identifier     "Layout0"
    Screen      0  "Screen0" 0 0
    InputDevice    "Keyboard0" "CoreKeyboard"
    InputDevice    "Mouse0" "CorePointer"
    Option         "Xinerama" "0"
EndSection

Section "Files"
EndSection

Section "InputDevice"
    # generated from default
    Identifier     "Mouse0"
    Driver         "mouse"
    Option         "Protocol" "auto"
    Option         "Device" "/dev/psaux"
    Option         "Emulate3Buttons" "no"
    Option         "ZAxisMapping" "4 5"
EndSection

Section "InputDevice"
    # generated from default
    Identifier     "Keyboard0"
    Driver         "kbd"
EndSection

Section "Monitor"
    # HorizSync source: builtin, VertRefresh source: builtin
    Identifier     "Monitor0"
    VendorName     "Unknown"
    ModelName      "CRT-0"
    HorizSync       30.0 - 83.0
    VertRefresh     56.0 - 75.0
    ModeLine       "1920x1200_60.00"  193.25  1920 2056 2256 2592  1200 1203 1209 1245 -hsync +vsync
    ModeLine       "1920x1080_60.00"  173.00  1920 2048 2248 2576  1080 1083 1088 1120 -hsync +vsync
    ModeLine       "1360x768" 72.000 1360 1408 1440 1520 768 771 781 790 +hsync -vsync
    ModeLine       "1152x864" 81.620 1152 1216 1336 1520 864 865 868 895 -hsync +vsync
    ModeLine       "800x600" 50.000 800 856 976 1040 600 637 643 666 +hsync +vsync
    ModeLine       "680x384" 36.000 680 704 720 760 384 385 390 395 +hsync -vsync doublescan
    ModeLine       "640x480" 25.175 640 656 752 800 480 490 492 525 -hsync -vsync
    ModeLine       "512x384" 32.500 512 524 592 672 384 385 388 403 -hsync -vsync doublescan
    ModeLine       "400x300" 25.000 400 428 488 520 300 318 321 333 +hsync +vsync doublescan
    ModeLine       "320x240" 12.587 320 328 376 400 240 245 246 262 -hsync -vsync doublescan
    ModeLine       "nvidia-auto-select" 65.000 1024 1048 1184 1344 768 771 777 806 -hsync -vsync
    Option         "DPMS"
EndSection

Section "Device"
    Identifier     "Device0"
    Driver         "nvidia"
    VendorName     "NVIDIA Corporation"
    BoardName      "Quadro FX 1800"
EndSection

Section "Screen"
    Identifier     "Screen0"
    Device         "Device0"
    Monitor        "Monitor0"
    DefaultDepth    24
    Option         "Stereo" "0"
    Option         "nvidiaXineramaInfoOrder" "CRT-0"
    Option         "metamodes" "1920x1080"
    Option         "SLI" "Off"
    Option         "MultiGPU" "Off"
    Option         "BaseMosaic" "off"
    Option "ModeValidation" "AllowNonEdidModes, NoVirtualSizeCheck, NoMaxPClkCheck, NoWidthAlignmentCheck, NoExtendedGpuCapabilitiesCheck"
    SubSection     "Display"
        Depth       24
    EndSubSection
EndSection

A: I found a solution in this link
Open the file xorg.conf like this
sudo nano /etc/X11/xorg.conf

edit the section device to be like in the link above


text:
Q: Multiple images in activity causing error I'm developing an app that displays a step-by-step process for my company. Each step consist of one image and each activity shows eight to twelve images. I'm now running into the java.lang.outofmemory. It's also listing an android.view.InflateException:Binary xml error. I've resized the images to 360dpi and that only allowed a few more pics before reaching the error again. I also tried increasing the heap size, which did not change the result. Is there another way I should do this? Thanks a lot.

A: You can scale down the Image, thus reducing their memory footprint. Also, you could look into certain libraries like picasso and UIL and see if they can help you.

A: No magic here, i guess the imageview are rendering in full argb mode, so 8 bit * 4 * number of pixels. That's a lot!
How does your activity displays images ?

*

*If they are in a list, make sure to use recycling.
http://developer.android.com/training/improving-layouts/smooth-scrolling.html
You are interested in the ViewHolder

*If you are using a ViewPager and swipes left/right, make sure to destroy your fragments while you are swiping, so that you can have in memory only 3 images (1 displayed, and 2 next to it).

*If it's none of those, maybe you will have to refactor your layout :(
Last but not least, make sure to resize your bitmap to your exact screen size, as suggested before, Picasso provides a convenient mean to do it with .fit(). It will wait for the imageview to be measured, then resize the downloaded bitmap and fit it in the imageview. You don't even have to worry about networking on main thread, how wonderful !
Picasso.with(getActivity())
        .load(imageUrl)
        .fit()
        .into(imageView);

A: This is where coding approach matters. How you've implemented it might help us pin point the memory leaks.
But a general practice ( maybe not good one)
Load all Bitmaps in a constant class. ( just once)
Refer infinitely.


text:
Q: How to find second value inside a column How do I list the names of all band members with the same last name?
The column has values like this
band_NAME
-------------------
Carla Thomas
Stephen E. Rice
Cynthia P. Tree
Richard Anthony Paul
Ann Frances Smith
Lorace Black
Timothy Adam Paul

I know we would have to use instr and substr. I just don't get how we would determine the position.
I know the basic format is going to be like
SELECT band_NAME
FROM TABLE
where substr(band_name, ?, instr( ) IN
    (select substr(band_name, ?, instr( )-1)
     from table
     group by SUBSTR(band_NAME , ?, INSTR( )-1 )
     HAVING COUNT(* ) > 1 );

But what goes in the question marks and inside the instr?
Would appreciate any help on this!

A: I'm assuming that your delimiter between first and last name is a single space. More spaces in the string are a part of last name. Thus, you probably want to search for the first space character.
Return position of the first occurence of substring with instr(str, substr).
Then, use substring(str, pos) to return the substring starting at a given position (feed by instr function).
SELECT substring(band_name, instr(band_name, ' '))
FROM yourtable

A: Try this:
SELECT t1.band_NAME
FROM TABLE t1 LEFT JOIN TABLE t2
 ON SUBSTRING_INDEX(t1.band_name, ' ', - 1) = SUBSTRING_INDEX(t2.band_name, ' ', - 1)
WHERE t1.band_name <> t2.band_name

And this like your pseudocode MySQL:
SELECT band_NAME FROM TABLE
Where FIND_IN_SET (SUBSTRING_INDEX(band_name, ' ', -1),
 (Select SUBSTRING_INDEX(band_name, ' ', -1) bn
 From TABLE Group by bn
 having Count(bn) > 1
 )
)

SQL Server
SELECT band_NAME FROM TABLE
Where
 SUBSTRING(band_NAME, CHARINDEX(' ', band_NAME) + 1, LEN(band_NAME)) AS [Last Name]
IN
 (Select SUBSTRING(band_NAME, CHARINDEX(' ', band_NAME) + 1, LEN(band_NAME)) AS [Last Name]
 From TABLE Group by [Last Name] -- or SUBSTRING(band_NAME, CHARINDEX(' ', band_NAME) + 1, LEN(band_NAME)) AS [Last Name]
 having Count(*) > 1
 )
)

Additionally I thinks you can benefit from STRING_SPLIT in some way

A: Try This
 with cte as
(
select band_name, ROW_NUMBER() over(partition by SUBSTRING(band_name,CHARINDEX(' ',band_name),LEN(band_name))  order by band_name) as cnt,
        SUBSTRING(band_name,CHARINDEX(' ',band_name),LEN(band_name)) as lastname
from your_table
)
select band_name
from cte
where lastname in (select lastname from cte where cnt > 1)

A: okay,
The best solution is to change your schema and store last name in a separate column.
In the mean time you could get the last name like this,
SELECT
            [band_NAME],
            CASE WHEN CHARINDEX(' ', [band_NAME]) > 0
                THEN
                    RIGHT([band_NAME], CHARINDEX(' ', REVERSE([band_NAME])))
                ELSE
                    [band_NAME]
            END [LastName]
    FROM
            [TABLE]

You could then group them like this
SELECT
            [LastName],
            COUNT(*)
    FROM
        (
            SELECT
                     [band_NAME],
                     CASE WHEN CHARINDEX(' ', [band_NAME]) > 0
                        THEN
                            RIGHT([band_NAME], CHARINDEX(' ', REVERSE([band_NAME])))
                        ELSE
                            [band_NAME]
                   END [LastName]
                FROM
                   [TABLE]
        ) [TABLEWithLastName]
    GROUP BY
            [LastName];


text:
Q: CORS on Meteor isn't working, what am I doing wrong? Here a piece of my code at main.js:

Meteor.startup(() => {

console.log('WEBBB',WebApp);
console.log('WEBAPP.CONNECTHANDLERS', WebApp.connectHandlers)

 WebApp.connectHandlers.use(function (req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", "*");
    return next();
  })

});

And here I'm trying to redirect to the Twitter app when there is a user click:

     Twitter

But I'm receiving a message with the following error on my console at the browser from the mobile inspect:

XMLHttpRequest cannot load
  https://twitter.com/intent/tweet?text=hello. No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'http://502e070a.ngrok.io' is therefore not allowed
  access.

Here I tried to insert on my root app, on main.jsx:

Meteor.startup(() => {

 // navigator.geolocation.getCurrentPosition(success);
 if(Meteor.isCordova) {
  console.log('Cordova ===========================');
  console.log('CORDOVA', cordova);
 }

 WebApp.connectHandlers.use(function (req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", "*");
    return next();
  })

 // Rendering the App Component
 render(<AppContainer />, document.getElementById('root'));

});

But I get the message saying "use" is not defined.


text:
Q: The closure of $\mathbb{Z\times Z\times R}$ in Homeo$(\mathbb R^2)$ is the group of translations of $\mathbb R^2$ This question is related to this question but not the same -
Let $\mathbb{Z\times Z\times R}$ act on $\mathbb R^2$ by $$(m,n,r)\cdot(x,y)=(x+m+r,y+n+r\sqrt{2})$$ I need to prove the following -
If Homeo$(\mathbb R^2)$ is given the compact open topology then the closure of $\mathbb{Z\times Z\times R}$ in Homeo$(\mathbb R^2)$ is the group of all translations of $\mathbb R^2$
My attempt -
Let $f$ be in the closure of $\mathbb{Z\times Z\times R}$. Then there exist a net of points $(f_\alpha)\in\mathbb{Z\times Z\times R}$ (defined by $f_\alpha(x,y)=(x+n_\alpha+r_\alpha,y+m_\alpha+r_\alpha\sqrt{2})$ for some $m_\alpha,n_\alpha\in\mathbb Z$ and $r_\alpha\in\mathbb R$) such that $f_\alpha\longrightarrow f$. So for any $(x,y)\in\mathbb R^2$ we have
$$f_\alpha(x,y)\longrightarrow f(x,y)$$ $$\Rightarrow(x+n_\alpha+r_\alpha,y+m_\alpha+r_\alpha\sqrt{2})\longrightarrow f(x,y)$$ $$\Rightarrow (n_\alpha+r_\alpha,m_\alpha+r_\alpha\sqrt{2})\longrightarrow f(x,y)-(x,y):=(x_0,y_0)$$
Thus $(n_\alpha+r_\alpha,m_\alpha+r_\alpha\sqrt{2})\longrightarrow (x_0,y_0)$ and by Hausdorffness of $\mathbb R^2$ $(x_0,y_0)$ is independent of the choice of $(x,y)$. So$f$ is given as the translation by $(x_0,y_0)$.
This shows the closure of $\mathbb{Z\times Z\times R}$ is contained in the group of translation of $\mathbb R^2$
Can some one help me with the other way?
If $f$ is given by $f(x,y)=(x+x_0,y+y_0)$ then I need to find a net of points in $\mathbb{Z\times Z\times R}$ converging to $f$. I tried splitting $x_0$ and $y_0$ into integer and fractional part but I'm not sure how to go from there. Suggestions will be appreciated.
Thank you.

A: Let $T_{v,u}(x,y)=T(x+v,x+u)$ be the translation by $(v,u)$. We want to show that it is in the closure of your family of maps.
Since your group of maps already contains all translation with integer coefficients, we may assume that $v,u \in \mathbb{R}/\mathbb{Z}$. Now choose $r=v+k$ where $k$ is an integer, so that $r\equiv _\mathbb{Z} v$. Thus, modulo $\mathbb{Z}$ your group of actions contains a translation by $(v,v\sqrt{2}+k\sqrt{2})$ for every integer $k$. Check for yourself that the set $\{k\sqrt{2} \mid k\in \mathbb{Z} \}$ is dense in $[0,1]$ modulo $\mathbb{Z}$ so you can come close as you want to $u$.
Going back to translations in $\mathbb{R}^2$ you get that your group of translations contain the translation by $(v,u+\epsilon)$ where $\epsilon$ can be as small as you want. This sequence of translation will converge (even uniformly) to the translation by $(v,u)$.
In a little bit more geometric way, the action of $\mathbb{R}$ on the torus $\mathbb{R}^2/\mathbb{Z}^2$ sending $(x,y)$ to $(x+r,x+r\sqrt{2})$ has a dense orbit.

EDIT: To show that $\{ \sqrt{2}k \mid k \in \mathbb{Z} \}$, we first prove that for every $n$ there is some $k_n$ such that $\sqrt{2}k_n$ mod $\mathbb{Z}$ is in $(0,\frac {1}{n})$. Once you have such a $k_n$ you get that consecutive points of the form $\sqrt{2}k_n m$ for $m\in\mathbb{Z}$ have distance less than $\frac{1}{n}$. As this is true for every $n$, you can get as close as you want to any point on the unit circle (or equivalently, in $[0,1]$).
Now fix $n$ and consider $k\sqrt{2}$ for $k=0,...,n$. Since $\sqrt{2}$ is not rational, any two such points are distinct modulo $\mathbb{Z}$. Thus, divided the unit circle to n segments of the same length, by the pigeonhole principle, some of these segments contain two points $k_1\sqrt{2},k_2\sqrt{2}$ and your required $k_n$ will be their difference.


text:
Q: Jquery onclick toggleClass - three clicks required instead of two I need a cell to have three colors : first loaded by the script, second ny clicking on the cell and third by clicking on one more time. And if I click again I get the first color back.
I wrote this :

        1
        2
        3

You can see how it works : jsfiddle
My problem is that the first two clicks work fine (the color change) but the third is useless and the fourth work as the third should (get the color back to the beginning).
I need to have only three clicks.

A: I am not sure I understood your problem, but here is something to start with:

    $(document).ready(function () {
      var i = 0;
        $('.combi').on('click', function () {
          i += 1;
          if (i == 1) {
            $(this).toggleClass('highlight');
          } else if (i == 2) {
            $(this).toggleClass('highlight2');
          } else {
            $(this).removeClass();
            i = 0;
          }
        })
    })
    .highlight {
      background-color: #ffff00;
    }

    .highlight2 {
      background-color: red;
    }

        1

        8

        15


text:
Q: Creating new collection and document with Firestore REST API returning HTTP 400 Hello stackoverflow community,
I am using Firestore and not Realtime database for a test project I am working on.

*

*As a starter, I am trying to create a new document inside an existing collection and project which I manually created through the web interface. My project id is newproject-30f72 and the already created collection name is testcollection.

*I have enabled the Email/Password authentication method, and I have registered a new email-id/password user. The rule I have for auth enabled write is as follows.

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth.uid != null;
    }
  }
}

At this point, I am not sure, a barer token alone passed in the header is enough to validate the request.auth.uid != null, so most probably my rule could also be wrong, as I was using the simulator to auto generate the rule, but I verified that the rule is not causing the problem I am facing at the moment by disabling the rule completely.

*

*I have enabled rules so that only authenticated users can write to firestore. (and by authentication, I mean the idToken for a specific email/password based user and not the apiKey for a web app. I don't know if this is possible though.)

*I have enabled the Add Firebase to your web app / register app and that gave me a json object named firebaseConfig with the following details.

   var firebaseConfig = {
      apiKey: "some_api_key",
      authDomain: "newproject-30f72.firebaseapp.com",
      databaseURL: "https://newproject-30f72.firebaseio.com",
      projectId: "newproject-30f72",
      storageBucket: "newproject-30f72.appspot.com",
      messagingSenderId: "111122223333",
      appId: "1:1111:web:2222"
   };

I am using the apiKey from the above json object to get an idToken valid for some time, to write to the firestore database. The code for that is as below in python3.
import json
from urllib import request, error
from collections import defaultdict

firebase_apikey = 'some_api_key'
auth_request_url = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key={}".format(firebase_apikey)

class auth:
    def __init__(self, email: str, password: str):
        self.email = email
        self.password = password
        self.post_data = defaultdict()
        self.post_data['email'] = self.email
        self.post_data['password'] = self.password
        self.post_data['returnSecureToken'] = True
        self.headers = {"Content-Type": "application/json"}
        # print("POST DATA IS:: " + json.dumps(self.post_data))
        self.r = request.Request(auth_request_url,
                                 data=json.dumps(self.post_data).encode(),
                                 headers=self.headers)
        # self.url_open

    def get_auth_token(self):
        try:
            self.url_open = request.urlopen(self.r)
        except Exception as e:
            return e
        try:
            return json.loads(self.url_open.read())
        except Exception as e:
            return e

s = auth("someuser.somethingelse@gmail.com", "somepassword")
response = s.get_auth_token()
id_token = response['idToken']
expires_in = response['expiresIn']

I got the idToken which is a 924 character long string.
Now I am trying to write to firestore with the idToken that I received and valid for 3600(seconds I presume) using the Authorization': 'Bearer header as follows.
firestore_project_url = "https://firestore.googleapis.com/v1beta1/projects/{}/databases/(default)/documents:write".format(
    'newproject-30f72')

headers = {
    'Content-type': 'application/json',
    'Authorization': 'Bearer %s' % id_token,
}

test_data = '''
{
    "writes": [{
        "updateMask": {
            "fieldPaths": ["name"]
        },
        "update": {
            "name": "projects/newproject-30f72/databases/(default)/documents/testcollection/testdoc/",
            "fields": {
                "name": {
                    "stringValue": "test"
                }
            }
        }
    }]
}
'''

test_data_json_bytes = json.dumps(test_data).encode("utf-8")
req = request.Request(url=firestore_project_url,
                      data=test_data_json_bytes,
                      headers=headers,
                      method='POST')
print(headers)
f = request.urlopen(req)

I can see the headers as
{'Content-type': 'application/json', 'Authorization': 'Bearer eyJhbGciOiJSUzI1NiIsI........<snip>'}

but I am getting a urllib.error.HTTPError: HTTP Error 400: Bad Request error.
I was referring to Firebase Firestore REST example to check it using curl with custom headers to add the bearer token and to see if there is any possible verbosity, and I am seeing
*   Trying 74.125.68.95...
* TCP_NODELAY set
* Connected to firestore.googleapis.com (74.125.68.95) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: none
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* TLSv1.3 (IN), TLS handshake, Server hello (2):
* TLSv1.3 (IN), TLS handshake, Encrypted Extensions (8):
* TLSv1.3 (IN), TLS handshake, Certificate (11):
* TLSv1.3 (IN), TLS handshake, CERT verify (15):
* TLSv1.3 (IN), TLS handshake, Finished (20):
* TLSv1.3 (OUT), TLS change cipher, Change cipher spec (1):
* TLSv1.3 (OUT), TLS handshake, Finished (20):
* SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384
* ALPN, server accepted to use h2
* Server certificate:
*  subject: C=US; ST=California; L=Mountain View; O=Google LLC; CN=*.googleapis.com
*  start date: May 14 13:35:00 2019 GMT
*  expire date: Aug  6 13:20:00 2019 GMT
*  subjectAltName: host "firestore.googleapis.com" matched cert's "*.googleapis.com"
*  issuer: C=US; O=Google Trust Services; CN=Google Internet Authority G3
*  SSL certificate verify ok.
* Using HTTP2, server supports multi-use
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* Using Stream ID: 1 (easy handle 0x560e5884af30)
> POST /v1beta1/projects/newproject-30f72/databases/(default)/documents/testcollection3 HTTP/2
> Host: firestore.googleapis.com
> User-Agent: curl/7.64.1
> Accept: */*
> {Content-type: application/json, Authorization: Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6........<snip>}
> Content-Type: application/json
> Content-Length: 258
>
* We are completely uploaded and fine
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* old SSL session ID is stale, removing
* Connection state changed (MAX_CONCURRENT_STREAMS == 100)!
< HTTP/2 400
< content-type: text/html; charset=UTF-8
< referrer-policy: no-referrer
< content-length: 1555
< date: Fri, 31 May 2019 14:31:36 GMT
<
* HTTP/2 stream 0 was not closed cleanly: PROTOCOL_ERROR (err 1)
* stopped the pause stream!
* Connection #0 to host firestore.googleapis.com left intact
curl: (92) HTTP/2 stream 0 was not closed cleanly: PROTOCOL_ERROR (err 1)
* Closing connection 0

I was referring to the following links for references.
https://groups.google.com/forum/#!topic/google-cloud-firestore-discuss/4Le2RskC3cg
https://firebase.google.com/docs/firestore/reference/rest/v1beta1/projects.databases.documents/commit
What I am trying to achieve is

*

*use the email/password auth to get authenticated to firestore

*create collection and write docs to it.

Any help is greatly appreciated.
Thank you very much.

A: SO this is what worked for me (I used requests module but net effect is the same)
First the Auth, exactly as you do.
url = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=" + API_KEY
payload = {"email": email, "password": password, "returnSecureToken": True}
rsp = requests.post(url, data=payload)
id_token = rsp.json().get("idToken")

# User idToken from your auth for later requests
headers = {
    'Content-type': 'application/json',
    'Authorization': "Bearer %s" % id_token
}

Now create a document in a collection
# Create a doc in "testcoll"
url = "https://firestore.googleapis.com/v1beta1/projects/" + PROJECT + "/databases/(default)/documents/testcoll"
payload = {
  "fields": {
    "meaningOfLife": {"integerValue": 42}
  }
}
# Create Doc
rsp = requests.post(url, headers=headers, data = json.dumps(payload))
assert(rsp.status_code == 200)
docref = rsp.json().get("name")
print(rsp.json())

Now update the same document
# Update doc
url = "https://firestore.googleapis.com/v1beta1/" + docref
payload = {
  "fields": {
    "meaningOfLife": {"stringValue": '43'}
  }
}
rsp = requests.patch(url, headers=headers, data = json.dumps(payload))
assert(rsp.status_code == 200)
print(rsp.json())


text:
Q: How do I type out this integral? I am fairly new to TeX, and I am currently using TexStudio.
I am wondering how  I can exactly replicate the typesetting of the integral below, including the font and the upright integral sign? What packages, what font?

Thank you.

A: This seems quite similar to newtxmath with the upint option:
\documentclass{article}

\usepackage{newtxtext}
\usepackage[upint]{newtxmath}

\newcommand{\diff}{\mathop{}\!d}

\begin{document}

\[
\int x^n\diff x
\]

\end{document}

A: Basic math is included in LaTeX without any additional packages. I would write:
\documentclass{article}

\begin{document}

\[ \int x^n\, \mathrm{d}x \]

\end{document}

If you just type dx instead of \mathrm{d}x, the d will be put in italic (like in your example).

A: Ok, you are new to \LaTeX. Here is your answer. I am also teaching you how to specify the limits of integration:
$\displaystyle \int_a^b x^n \, dx$

The \, directive inserts a thinspace between the integrand and the variable of integration; this is commonly done in (good) math typography.
If you need an expression without limits of integration:
$\displaystyle \int x^n \, dx$


text:
Q: How to reset state before each test in jest? I have following classes and files
//A.ts

export abstract class A{

    protected abstract method1(arg){

    }
}

// C.ts
export interface C{
    public methodC1(){
    };
}

//CImpl.ts
export class CImpl implements C{
    public methodC1(){
        // do something
    };
}

// B.ts
    import appConfig from 'config';
    export class B extends A{
        private _enable : boolean appConfig.get('IsEnabledC');
        private init(argC:C | undefined)
        {
            if(this._enable){
                argC = new CImpl();
            }
            argC.methodC1();
            return argC;
        }
    private func(argC){
        let resource = getResource();
        switch(resource.status){
            case 1:{
                throw(some exception);
            }
            case 2:{
                throw(another exception);
            }
            default:{
                // do something
            }
    }

    private cleanup(){
        //do something;
    }
     protected async method1(arg){
            let argC: C | undefined;
            try{
                argC = init(argC);
                await this.func(argC);
            }
            catch(exception){
                this.cleanup();
            }
        }
    }

// B.spec.ts
describe("B test", () => {
    it("check if cleanup is called on resource status 1", () => {
        const varB = new B();
        const spied = jest.spyOn(B.prototype as any,"init").mockReturnValue(new CImpl(argC));
        const spied2 = jest.spyOn(B.prototype as any,"cleanup").mockImplementation(()=>{console.log("cleanup got called")});
        await varB["method1"](arg);
        expect(spied).toBeCalledTimes(1);
        expect(spied2).toBeCalledTimes(1);
    });

    it("check if cleanup is called on resource status 2", () => {
        const varB = new B();
        const spied = jest.spyOn(B.prototype as any,"init").mockReturnValue(new CImpl(argC));
        const spied2 = jest.spyOn(B.prototype as any,"cleanup").mockImplementation(()=>{console.log("cleanup got called")});
        await varB["method1"](arg);
        expect(spied).toBeCalledTimes(1);
        expect(spied2).toBeCalledTimes(1);
    });
})

I want to test two status viz. 1 and 2 for resource inside func method. I have also mocked the getResource() method and setting status 1 and 2 in test respectively. I want that cleanup method gets called only once in each test.
But eventually in second test both spied and spied2 are getting called 2 times.
When I am running each test separately then they are working fine, but when they are run together first test is getting passed and second test is getting failed in expect assertion with message jest.fn() is called 2 times.
How can I reset state after/before each test?

A: you can use these methods: beforeAll, afterAll, beforeEach, afterEach.
https://jestjs.io/docs/setup-teardown
for clearing mocks you can use .mockClear()
https://jestjs.io/docs/mock-function-api#mockfnmockclear
upd:
You can use it only on mocked functions. It can be called anywhere in a test, but you'll probably need it inside afterAll. It will look like this:
import { yourMockedFunction } from '...'

afterAll(() => {
  yourMockedFunction.clearMock();
});

// your tests here


text:
Q: JS, making a symbol into a parameter So, I am trying to make following js into a function:
SOMETHING.html(parseInt(SOMETHING.html()) + 1);

function RH_COUNT(a,b){
    return a.html(parseInt(a.html()) b 1);
};

how do I make a symbol (plus sign "+") into a function parameter?

A: You must define a plus function:
function plus(x, y)
{
    return x + y;
}

Inside RH_COUNT you use it like this:
function RH_COUNT(a, b)
{
    return a.html( b(parseInt(a.html()), 1) );
    //             ^^^^^^^^^^^^^^^^^^^^^^^^ this is the plus() invocation
}

Now you can pass it to the RH_COUNT function:
RH_COUNT(SOMETHING, plus);

In ES6 (Harmony) you can leverage the arrow syntax for a one-liner invocation without the need to define the plus function:
RH_COUNT(SOMETHING, (x, y) => x + y );
//                  ^^^^^^^^^^^^^^^ this is the "plus" lambda

A: You can add 1 or -1 as a param, and then add the two, with one multiplied by the param. Like so:
function RH_COUNT(a,b){
    return a.html(parseInt(a.html()) + 1 * b);
};

RH_COUNT( <param>, 1 );
RH_COUNT( <param>, -1 );

As you wish, you can also make a variable out of those numbers, like so:
var PLUS = 1, MINUS = -1;

function RH_COUNT(a,b){
    return a.html(parseInt(a.html()) + 1 * b);
};

RH_COUNT( <param>, PLUS );
RH_COUNT( <param>, MINUS );


text:
Q: Reload single entity followed by increment and save changes causes dirty reads I have the following code which runs in only one web application. I want to make sure that the value is incremented by 1 and that I don't get into problems because of dirty reads.
I am curious why this code may cause dirty reads sometimes?
_locker.EnterWriteLock(); // static ReaderWriterLockSlim _locker= new ReaderWriterLockSlim();
var task = _dbo.Tasks.FirstOrDefault(e=>e.TaskId == taskId);
_dbo.Entry<Task>(task).Reload();
task.Commits += noOfCommits;
_dbo.SaveChanges();
locker.ExitWriteLock();

_dbo is instantiated every request


text:
Q: Wrong Tax calculation when creating order from Admin I have an issue I can't solve from normal TAX panel.
I have all my shipping prices setted without tax in the admin and they are  calculated in the right way in the cart and checkout page in frontend. Please see image

As you can see from the picture the shipping cost is 8.20 + 22% tax and is correctly showed as 10 €.
Shipping Tax  are also well included in Tax (Tasse) row.
Now the issue I have is that if i create an order from the admin using the same customer/address/product/shipping method, the Shphipping and Handleing are wrong!! They are without tax (also if shipping method shows them including tax)
See the image below

If I click 2 times on the Radio Button of the shipping method, the Shipping and Handling value it gets right.
So once I click for a second time on the choosen shipping method radio button I get the right value of 10€ (instead of the wrong 8.20€) just as on the front page(see first image).
So it looks like Magento doen't add tax on the first click, then on the second it does.
Is that a bug of Magento 1.8 ?  How can i overwright the tax calculation for the admin block?

A: Found one solution for this
Please add following line of code into app/code/core/Mage/Adminhtml/Model/Sales/Order/Create.php
Before that override the model class in local directory or copy file into local app/code/local/Mage/Adminhtml/Model/Sales/Order/Create.php.
public function initFromOrder(Mage_Sales_Model_Order $order)

following code before quote save
$this->getQuote()->setTotalsCollectedFlag(false)->collectTotals();
$this->getQuote()->save()


text:
Q: what is the size of a block in Hyperledger v0.6? According to the answer to (How are Hyperledger transactions ordered in a block?), in Hyperledger v0.6 there is a leader that is ordering transactions in a block.
How the number of transactions in a block is set up? or it is frequency of creation a new block? How to define/modify it?
Thanks!

A: For Fabric v0.6 there is a file fabric/consensus/pbft/config.yaml. This is a configuration for PBFT consensus with default values:
general:
    batchsize: 500
    timeout:
        batch: 1s

It means that new block will be generated when one of these conditions(any of them) is met:

*

*There are 500 transactions in a buffer

*1 second passed from time when previous block was generated.

For NOOPS consensus new block is generated for every transaction.


text:
Q: Apple app site association not working over AWS CloudFront and S3 Here's my setup:

*

*I have an AWS CloudFront distribution with custom and valid SSL certificate (from ACM)

*the CF distribution points to an S3 bucket

*My domain example.com is a A record with alias to my CF distribution

*I uploaded apple-app-site-association and .well-known/apple-app-site-association to my bucket with the following parameters: Public Read, Content-Type=application/pkcs7-mime

My apple-app-site-association is as follows:
{
   "webcredentials": {
       "apps": [    "TeamID.BundleId1",
                    "TeamID.BundleId2" ]
    }
}

Of course the values are replaced with my team's ID and the bundle Ids of my 2 apps.
When I run
curl -i https://example.com/apple-app-site-association

or
curl -i https://example.com/.well-known/apple-app-site-association

I have the following result:
HTTP/2 200
content-type: application/pkcs7-mime
content-length: 156
date: Wed, 18 Dec 2019 03:08:15 GMT
last-modified: Wed, 18 Dec 2019 03:04:14 GMT
etag: "redacted"
x-amz-server-side-encryption: AES256
accept-ranges: bytes
server: AmazonS3
x-cache: Miss from cloudfront
via: 1.1 redacted.cloudfront.net (CloudFront)
x-amz-cf-pop: redacted
x-amz-cf-id: redacted

{
   "webcredentials": {
       "apps": [    "TeamID.BundleId1",
                    "TeamID.BundleId2" ]
    }
}

Which tells me the file is valid and correctly hosted.
On the Xcode side, my target has the following row in Signing & Capabilities > Associated Domains:
webcredentials:example.com

So my entitlements file looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>aps-environment</key>
    <string>development</string>
    <key>com.apple.developer.associated-domains</key>
    <array>
        <string>webcredentials:example.com</string>
    </array>
</dict>
</plist>

However when I go to my Sign Up screen on the app, I have the following console log:

[AutoFill] Cannot show Automatic Strong Passwords for app bundleID:
  BundleId due to error: Cannot save passwords
  for this app. Make sure you have set up Associated Domains for your
  app and AutoFill Passwords is enabled in Settings

I am testing on a real device on iOS 13 and AutoFill is enabled.
Note: my app is not live yet (in case I am advised to use the Apple crawler aka App Search API Validation Tool)
Thanks in advance for any help!

A: From the docs:

Note
  If your app runs in iOS 9 or later and you use HTTPS to serve the apple-app-site-association file, you can create a plain text file that uses the application/json MIME type and you don't need to sign it. If you support Handoff and Shared Web Credentials in iOS 8, you still need to sign the file as described in Shared Web Credentials Reference.

So the content-type: application/pkcs7-mime in your response seems wrong, try changing that to application/json.

A: I finally managed to get it working. I did 4 different things, I think only 2 of them are important but I'll post them all here in case it helps someone with the same issue.
1: Use my iPhone Developer ID instead of my Team ID (important)
As I was debugging the app on dev environment, the app is signed with my iPhone Developer certificate, not my team's production certificate. So I changed my apple-app-site-association file from
{
   "webcredentials": {
       "apps": [    "TeamID.BundleId1",
                    "TeamID.BundleId2" ]
    }
}

to
{
   "webcredentials": {
       "apps": [    "TeamID.BundleId1",
                    "TeamID.BundleId2",
                    "iPhoneDeveloperID.BundleId1",
                    "iPhoneDeveloperID.BundleId2" ]
    }
}

2: Invalidate AWS CloudFront cache before testing (important)
While testing, I eventually found out that I was sometimes getting an old version of my apple-app-site-association, depending on which device or software application I was using to fetch it.
So I logged in to the CF console, selected my distribution, selected the Invalidations tab, and created an Invalidation with Object Path /.well-known/apple-app-site-association.
3: Add App Links
I'm not sure whether that made any difference for my issue, as I only invalidated the cache after I tried this, but just in case it helps someone, I decided to add App Links to my app. I added the following object after webcredentials in my apple-app-site-association
"applinks": {
        "apps": [],
        "details": [
            {
                "appID": "iPhoneDeveloperID.BundleId1",
                "paths": [ "*"]
            },
            {
                "appID": "iPhoneDeveloperID.BundleId2",
                "paths": [ "*" ]
            },
            {
                "appID": "TeamID.BundleId1",
                "paths": [ "*"]
            },
            {
                "appID": "TeamID.BundleId2",
                "paths": [ "*" ]
            }
        ]
    }

Make sure the app you're testing is at the top, as the others will get discarded (the first wildcard wins). This must obviously be changed before going to production.
And I added the following entitlement to my app
<string>applinks:example.com</string>

4: Only use .well-known
Again, I don't believe this is important, but instead of having to upload my file twice for each test, I stopped using the root directory, and only uploaded to /.well-known/apple-app-site-association

A: In case it helps someone else I had similar problem with the file not being valid  with correct content type header. I re-uploaded the file using the following:
aws s3 cp --content-type "application/pkcs7-mime" public/.well-known/apple-app-site-association s3://mywebsite/.well-known/


text:
Q: Add Timeout to task I am calling a web service that will return data that I intend to put into a SQLite database for the mobile app.  The problem is that the service takes some time to return the data and the app performs a timeout and fails.
How can I incorporate a task within my HelperFile to be sure it returns successfully to the calling function?
protected async override void OnAppearing()
    {
        base.OnAppearing();
        await Task.Run(async () =>
        {
            await ProcessData();
        });

    }

    private async Task ProcessData()
    {

        HelperFile myHelper = new HelperFile();

        //Pass Information to Webservice
        Uri jsonUrl1 = new Uri(string.Format("https://www.myURL.com/page.asmx/GetMyData"));

        var result = await myHelper.GetResponseString(jsonUrl1);
        //JObject rss = JObject.Parse(result);

       jsonCredit_Union.RootObject obj = JsonConvert.DeserializeObject<jsonCredit_Union.RootObject>(result);

        foreach (KeyValuePair<string, jsonCredit_Union.JobCode> kvp in obj.Results.JobCodes)
        {
            using (SQLiteConnection conn = new SQLiteConnection(App.DB_PATH))
            {
                tblCredit_Union tcu = new tblCredit_Union()
                {
                    cuName = kvp.Value.cuName,
                    cuPhone = kvp.Value.cuPhone,
                    address1 = kvp.Value.address1,
                    city = kvp.Value.city,
                    state_id = kvp.Value.state_id,
                    zip_Code = kvp.Value.zip_Code,
                    longitude = kvp.Value.longitude,
                    latitude = kvp.Value.latitude
                };

                conn.CreateTable<tblcredit_union>();
                conn.Insert(tcu);

            }
        }
    }

Here is where it fails and returns "Task was cancelled".  Due to the timeout I am unable to get to the point of checking the ResponseCode.
    public class HelperFile
{
    //Returns a json recordset from a provided URL
    public async Task<string> GetResponseString(Uri url)
    {
        try
        {
            using (HttpClient client = new HttpClient())
            {
                using (HttpResponseMessage response = await client.GetAsync(url))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        using (HttpContent content = response.Content)
                        {
                            string myContent = await content.ReadAsStringAsync();
                            return myContent;
                        }
                    }
                    else
                    {
                        return "Error";
                    }
                }

            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

A: One thing to think about is that your app, as a client, cannot ensure the server returns your call successfully.  If its taking too long, as mentioned in the comment, you can set the timeout on the HttpClient within your helper class.
Right now, you have a try catch in the helper, but not in the ProcessData() call. So- when the task does time out and throws an exception, your app is likely crashing.  You can test this by using a network conditioner or putting the device/simulator in airplane mode.
Another scenario is that you have a call to the server and it returns a non Success Status Code.  Right now, you return a string of "Error"- but this return value is not addressed in ProcessData()
A starting point might be moving the Try/Catch out of your helper and in to your code behind (xaml.cs file).  Another idea might be to move the serialization into your Helper class....hopefully that helps point you in the right direction.


text:
Q: Convert nonlinear problem as LP with absolute value The problem asks to reformulate the following:
\begin{align*}
\min |x_1-2|+|x_2-10| & \\
\text{s.t.}\quad |x_1-x_2|+2x_2&\leq2  \\
        x_1+|x_2-4|&\leq6
\end{align*}
Here's what I've got so far:
\begin{align*}
\min t  &\\
\text{s.t.}\quad x_1+x_2-12 &\leq t  \\
     -x_1-x_2+12 &\leq t  \\
     x_1+x_2&\leq2  \\
     -x_1-x_2&\leq2  \\
     x_1+x_2&\leq10
\end{align*}
is this completely wrong?

A: COMMENT.-Deduce the answer from the figures below.


text:
Q: rspec should include tries to chomp an array Using Rails 3.2.2, I just installed rspec and tried my first test:
require 'spec_helper'

describe "Mains" do
  describe "GET index" do
    it "gets the page which has the proper content" do
      get 'index.html'
      response.status.should be(200)
      response.body.should include("one")
    end
  end
end

When I run the spec I get
Failures:

  1) Mains GET index gets the page which has the proper content
     Failure/Error: response.body.should include("one")
     NoMethodError:
       undefined method `chomp' for ["one"]:Array

This comes strait out of Ryan Bates' Railscast 257, so I'm a bit lost
thanks in advance,

A: [EDIT] The issue is corrected in rspec-expectations, on master branch. You can fix it by using this in your Gemfile:
gem 'rspec-rails', '~> 2.9'
gem 'rspec-expectations', :git => "https://github.com/rspec/rspec-expectations.git", :branch => 'master'

I encountered the same issue on Rails 3.0.12 with rspec 2.9.0. Reverting to rspec 2.8.0 / rspec-rails 2.8.1 did the trick.
I raised an issue on Github, rspec/rspec-expectations, we'll see if it's really a bug.
For reference, this is the step definition:
Then /^(?:I|they) should see "([^"]*?)" in the email body$/ do |text|
  current_email.default_part_body.to_s.should include(text)
end

... the step in the feature:
step %{I should see "changer de mot de passe" in the email body}

... which was raising:
undefined method `chomp' for ["changer de mot de passe"]:Array (NoMethodError)
  ./features/step_definitions/email_steps.rb:110:in `/^(?:I|they) should see "([^"]*?)" in the email body$/'


text:
Q: Changing the color of different stroke styles I'm running into an issue where i want to create skill bars displaying my skills in percentages. Now i've found a good code that let's me do that. I would of course rather do it myself, but i haven't found a good tutorial that teaches me how to (if you know one i'd be glad to use it).
But my question now is how do i change the colors of these different strokes?
self.context.clearRect( 0, 0, self.width, self.height );
        self.context.lineWidth = 10;
        self.context.fillStyle = "#000";
        self.context.strokeStyle = "#666";
        self.context.textAlign = "center";

The code that i had found is in the link below.
http://codepen.io/gabrieleromanato/pen/OVprOW

A: You just have to pass some arguments to the init-function.
I edited your Pen
init: function(fillStyle, strokeStyle) {
        var self = this;
        self.context.fillStyle = fillStyle,
        self.context.strokeStyle = strokeStyle,
        self.timer = setInterval(function() {
        self.run();
    }, 25);
}

Now you can call the init function with 2 parameters for strokeStyle and
fillStyle.
this.init('#0F0', '#F00');

Update:
Edited the pen to use random colors so you can see it in effect.

A: you can do same as with the width and height attributes.
store the color value in an attribute on the canvas element, and read that value
in the progress function
http://codepen.io/anon/pen/yJpNbG
<canvas class="bar-circle" color="blue"  width="70" height="70"></canvas>

this.color = element.getAttribute('color')  || "#d30000"; //default

A: Comment out the following line self.context.strokeStyle = "#d30000"; and then you can define the color you want for each of the elements in your page by giving them an id and using document.getElementById("given-id").getContext( "2d" ).strokeStyle = "#desired-color";. Example below:

/* Credits:
 * https://www.developphp.com/video/JavaScript/Circular-Progress-Loader-Canvas-JavaScript-Programming-Tutorial
 */
document.getElementById("csscan").getContext( "2d" ).strokeStyle = "#d30000";
document.getElementById("html5can").getContext( "2d" ).strokeStyle = "blue";
(function() {

 var Progress = function( element ) {

  this.context = element.getContext( "2d" );
  this.refElement = element.parentNode;
  this.loaded = 0;
  this.start = 4.72;
  this.width = this.context.canvas.width;
  this.height = this.context.canvas.height;
  this.total = parseInt( this.refElement.dataset.percent, 10 );
  this.timer = null;

  this.diff = 0;

  this.init();
 };

 Progress.prototype = {
  init: function() {
   var self = this;
   self.timer = setInterval(function() {
    self.run();
   }, 25);
  },
  run: function() {
   var self = this;

   self.diff = ( ( self.loaded / 100 ) * Math.PI * 2 * 10 ).toFixed( 2 );
   self.context.clearRect( 0, 0, self.width, self.height );
   self.context.lineWidth = 10;
   self.context.fillStyle = "#000";
   //self.context.strokeStyle = "#d30000";
   self.context.textAlign = "center";

   self.context.fillText( self.loaded + "%", self.width * .5, self.height * .5 + 2, self.width );
   self.context.beginPath();
   self.context.arc( 35, 35, 30, self.start, self.diff / 10 + self.start, false );
   self.context.stroke();

   if( self.loaded >= self.total ) {
    clearInterval( self.timer );
   }

   self.loaded++;
  }
 };

 var CircularSkillBar = function( elements ) {
  this.bars = document.querySelectorAll( elements );
  if( this.bars.length > 0 ) {
   this.init();
  }
 };

 CircularSkillBar.prototype = {
  init: function() {
   this.tick = 25;
   this.progress();

  },
  progress: function() {
   var self = this;
   var index = 0;
   var firstCanvas = self.bars[0].querySelector( "canvas" );
   var firstProg = new Progress( firstCanvas );

   var timer = setInterval(function() {
    index++;

    var canvas = self.bars[index].querySelector( "canvas" );
    var prog = new Progress( canvas );

    if( index == self.bars.length ) {
      clearInterval( timer );
    }

   }, self.tick * 100);

  }
 };

 document.addEventListener( "DOMContentLoaded", function() {
  var circularBars = new CircularSkillBar( "#bars .bar" );
 });

})();
#bars {
 margin: 2em auto;
 max-width: 960px;
 overflow: hidden;
}

.bar {
 float: left;
 width: 20%;
 text-align: center;
}

.bar h3 {
 font-size: 1.4em;
 font-weight: normal;
 margin: 0;
 text-transform: uppercase;
}

.bar-circle {
 display: block;
 margin: 0.7em auto;
}

CSS

  <canvas class="bar-circle" width="70" height="70" id="csscan"></canvas>

HTML5

  <canvas class="bar-circle" width="70" height="70" id="html5can"></canvas>

JavaScript

  <canvas class="bar-circle" width="70" height="70"></canvas>

PHP

  <canvas class="bar-circle" width="70" height="70"></canvas>

Server

  <canvas class="bar-circle" width="70" height="70"></canvas>