text:
Q: Prevent overlapping async code execution I have read about async-await patterns and that Mutex is incompatible with asynchronous code so I wonder how to write the following method in a lightweight way, without object allocations (not even for a Task<>) but without excessive encumberance (from a pattern).
The problem is as follows. Look at this method:
    public async void SendAsync(Stream stream, byte[] data)
    {
        await stream.WriteAsync(data.Length);
        await stream.WriteAsync(data);
        await stream.FlushAsync();
    }

Now, this method probably is not very useful. In fact there is plenty more code, but for the problem at hand it's perfectly complete.
The problem here is that I have a single main thread that will invoke the method very quickly without await:
for (i = 0; i < 10; i++)
{
    SendAsync(stream[i], buffer[i]);
}

All I want is that the main thread loops through quickly without blocking.
Now, this loop is looped over, too:
while (true)
{
    for (i = 0; i < 10; i++)
    {
        SendAsync(stream[i], buffer[i]);
    }

    // TODO: add a break criterion here
}

My suspicion (fear) is that a very chunky buffer (say 1 MB) on a congested stream[i] (yes, it's a TCP/IP NetworkStream underneath) may cause the nth invocation to occur before the preceding n-1th invocation was reentrant (returned from the invocation).
The two tasks will then interfere with each other.

I don't want any of these two solutions I've already discarded:

*

*(Non-)Solution 1: Mutex

This will throw an exception because Mutex has thread affinity and async code is thread-agnostic:
    public async void SendAsync(Stream stream, byte[] data)
    {
        mutex.WaitOne(); // EXCEPTION!

        await stream.WriteAsync(data.Length);
        await stream.WriteAsync(data);
        await stream.FlushAsync();

        mutex.ReleaseMutex();
    }

*Solution 2: return a Task to *.WaitAll()
The loop is in consumer land while SendAsync() is in framework land, I don't want to force consumers to use an intricate pattern:
while (true)
{
    for (i = 0; i < 10; i++)
    {
        tasks[i] = SendAsync(stream[i], buffer[i]);
    }

    Task.WaitAll(tasks);

    // TODO: add a break criterion here
}

Furthermore I don't ABSOLUTELY want Tasks to be allocated on each loop, this code will run at a moderate frequency (5-10 Hz) with 1000+ open streams. I cannot allocate 10000+ objects per second, it would GC like crazy. Mind that this is minimal code per SO policy, the actual code is much more complex.

What I'd like to see is some kind of outside-loop-allocation that allows to wait for completion only when absolutely necessary (like a Mutex) but at the same time does not allocate memory inside the loop.

A: Let's say you have a wrapper class over the stream, you could do something like this :
private Stream stream;
private Task currentTask;

public async void SendAsync(byte[] data)
{
    currentTask = WriteAsyncWhenStreamAvailable(data);
    await currentTask;
}

private async Task WriteAsyncWhenStreamAvailable(byte[] data)
{
    if (currentTask != null)
        await currentTask.ConfigureAwait(false);
    await WriteAsync(data);
}

public async Task WriteAsync(byte[] data)
{
    await stream.WriteAsync(data.Length).ConfigureAwait(false);
    await stream.WriteAsync(data).ConfigureAwait(false);
    await stream.FlushAsync().ConfigureAwait(false);
}

This way you always wait for the previous WriteAsync to end before sending the new data. This solution will ensure the buffers to be sent in requested order.

You could use an async SemaphoreSlim instead of a Mutex
private SemaphoreSlim semaphore = new SemaphoreSlim(1);

public async void SendAsync(Stream stream, byte[] data)
{
    await semaphore.WaitAsync(); // EXCEPTION!

    await stream.WriteAsync(data.Length);
    await stream.WriteAsync(data);
    await stream.FlushAsync();

    semaphore.Release();
}

Beware of OutOfMemoryException if you blindlessly produce new data without taking in account the size of pending buffers...


text:
Q: XSLT creation from XML and load into CSV file i need to convert XML files into CSV .
Expected Output :
tag1  tag2   Typearray
Name1 Name2     1
Name1 Name2     13

using XSLT am able to get only one record the second record in the array is getting rejected.
tag1,tag2,CommOffer,TypeArray
name1,name2,1

Can you please let me know how to read the array value using XSLT ?
Sample XML :
    <Master2>
       <Child1>
          <tag1>name1</tag1>
          <tag2>name2</tag2>
          <TypeArray>
             <value>1</value>
             <value>13</value>
          </TypeArray>
      </Child1>
    </Master2>
</Master1>

XSLT :
  <xsl:template match="/">
      <xsl:text>tag1,tag2,TypeArray</xsl:text>
         <xsl:text>
</xsl:text>
         <xsl:for-each select="Master1/Master2/Child1">
             <xsl:call-template name="CsvEscape"><xsl:with-param name="value" select="normalize-
              space(tag1)"/></xsl:call-template>
             <xsl:text>,</xsl:text>
             <xsl:call-template name="CsvEscape"><xsl:with-param name="value" select="normalize-
              space(tag2)"/></xsl:call-template>
             <xsl:text>,</xsl:text>
    <xsl:call-template name="CsvEscape"><xsl:with-param name="value" select="TypeArray/value"/>
         <xsl:text>
</xsl:text>
    </xsl:for-each>
 </xsl:template>

A: It is difficult to deduce the required logic from a single example. If - as it seems - you want to create a row for each TypeArray/value, with the tag1 and tag2 values repeated in each row, you could do something like:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8" />

<xsl:template match="/Master1">
    <!-- header -->
    <xsl:text>tag1,tag2,TypeArray
</xsl:text>
    <!-- data -->
    <xsl:for-each select="Master2/Child1">
        <xsl:variable name="tags">
            <xsl:value-of select="tag1"/>
            <xsl:text>,</xsl:text>
            <xsl:value-of select="tag2"/>
            <xsl:text>,</xsl:text>
        </xsl:variable>
        <xsl:for-each select="TypeArray/value">
            <xsl:value-of select="$tags"/>
            <xsl:value-of select="."/>
            <xsl:text>
</xsl:text>
        </xsl:for-each>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

redpajama_set_name: RedPajamaStackExchange


text:
Q: How does IIS persist a user's identity from page to page in an ASP.net application? Web pages are, by nature, state-less objects.  When you click from page to page in an ASP.net application, each request for a page is treated as a brand-new request.  We use things like cookies, session-variables, and query strings to maintain state from page to page.
When you log in to an ASP.net web application using Windows Authentication, how does IIS persist your identity between pages?

A: If you use something like Fiddler2, or any other web proxy tool, you can look at the header and see that for Windows Integrated Authentication, it gets the domain/username from the header, so it is able to know who you are, and then it will probably be using a session to help keep state between pages.

A: The browser "helps out" in the case of domain authentication.  Instead of asking you on every request, it remembers what you entered the first time and keeps re-sending it along with every request for that site.

A: Session is identified usually by a cookie (the 'session cookie') unless you set your app to be "cookieless", in which case the identifier is  in the url.
http://msdn.microsoft.com/en-us/library/aa479314.aspx


text:
Q: Discord py delete voicechannel if its empty Well im trying to create a voice channel by command so i can join it.
And as soon i leave the channel its supposed to get deleted.
What i tried:
if message.content.startswith('/voice'):
    guild = message.guild
    voicechannel = await guild.create_voice_channel(f"{str(message.author)}")
    await asyncio.sleep(5)

    while True:
       if len(voicechannel.voice_states) == 0:
           await voicechannel.delete()
           break

doesnt even work tho

A: I believe that your issue is that you are stuck in an infinite while True loop. I would first suggest that you switch to using discord.ext.commands, it simplifies the process of creating a Discord Bot by a great deal. If you were using discord.ext.commands.Bot, you would be able to use the wait_for() function to wait until the voice channel is empty.
from discord.ext.commands import Bot

client = Bot(command_prefix="/")

@client.command(name="voice")
async def voice(ctx):
    guild = ctx.guild
    voice_channel = await guild.create_voice_channel(f"{str(ctx.author)}")

    def check(member, before, after):
        return member == ctx.author and before.channel == voice_channel and after.channel is None

    await client.wait_for("voice_state_update", check=check)
    await voice_channel.delete()

client.run("TOKEN")

The only issue that I think could happen, is if the member never joins the voice channel. To counter this, we can set up another wait_for() function to determine if the member ever joins before waiting for the member to leave the voice channel.
from asyncio import TimeoutError

@client.command(name="voice")
async def voice(ctx):
    guild = ctx.guild
    voice_channel = await guild.create_voice_channel(f"{str(ctx.author)}")

    def check(member, before, after):
        return member == ctx.author and before.channel is None and after.channel == voice_channel

    try:
        await client.wait_for("voice_state_update", check=check, timeout=60)
    except TimeoutError:
        await voice_channel.delete()
        return


text:
Q: Uso de la propiedad CSS background-img en Laravel Estoy intentando aplicar un estilo de background-img a mi imagen en Laravel:
HTML:

CSS:
img::before{
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('../assets/img/splash.jpg');
  background-size: 100%;
  background-position: center;
  mix-blend-mode: screen;
}

El problema es que en los estilos del selector ::before no se me aplica su bg-image. ¿Existe alguna forma de lograr el resultado?

A: Vale según el video que me has mandado, lo he probado y va.

*

*Usa un div o una etiqueta como section, aside... y no pongas el img para hacerlo.

*Ahora al div le aplicas los estilos que dice, sobre todo el de la imagen para que la cargue como fondo en el div (no verás nada en la pantalla porque no coge ninguna imagen, no encuentra imágenes online así de rápido. Así que úsalo en tu código. Yo con unas mías si funciono. No perfecto, luego le das tus detalles, básicamente es igual que el vídeo que pasaste.

div {
position: relative;
widht: 100%;
min-height: 100vh;
background: url(tu imagen de atras);
background-size: cover;
}

div:before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: url("Tu imagen superpuesta");
background-size: 1800px;
background-position: center;
mix-blend-mode: screen;
}

Lo que he visto es que tu le insertas la imagen desde el img y eso, que yo sepa no lo hará un fondo. Si se usa fondo de normal se usa un div u otra etiqueta y se le da en css el fondo.
Ten en cuenta el formato de imagen que uses para poner encima, puede que tape entero. En el video son jpg pero blanco y negro únicamente.
Comprueba que te va enlazando imágenes reales jaja y toquetea los valores como vh y demás para ir ajustándolo como prefieras. Espero haberte ayudado.


text:
Q: Update with subselect and where The following code works fine in T-SQL, but not in JET SQL, in Access:
UPDATE Superliste_Temp
SET [Plan-TGrp-Spanne_Stfl1] =
(SELECT [Plan-TGrp-Spanne_Stfl1]
 FROM Superliste_Temp
 INNER JOIN dbo_Common_preferences
     ON Superliste_Temp.Teil = dbo_Common_preferences.AktivesTeil)
WHERE [Teilegruppe] =
(SELECT [Teilegruppe]
 FROM Superliste_Temp
 INNER JOIN dbo_Common_preferences
     ON Superliste_Temp.Teil = dbo_Common_preferences.AktivesTeil);

Why does it not work!?

A: I have a hard time looking at that SQL to figure out what it's trying to do, but I know that Jet SQL needs the SET statement after the JOINS, so my best guess is:
UPDATE Superliste_Temp, Superliste_Temp AS ST1
    INNER JOIN dbo_Common_preferences AS pref1
    ON ST1.Teil = pref1.AktivesTeil
SET Superliste_Temp.[Plan-TGrp-Spanne_Stfl1] = [ST1]![Plan-TGrp-Spanne_Stfl1]
WHERE (((Superliste_Temp.Teilegruppe)=[ST1]![Teilegruppe]));


text:
Q: How should I represent a latitude and longitude in Postgres without using PostGIS? How should I represent a latitude and longitude in Postgres without using PostGIS? The system I am using does not allow SQL passthrough so I cannot use POSTGIS.

A: You could also either use separate columns for latitude and longitude or create your own type. Either way it may be good to constrain the allowed values, in this example I also use domains to avoid repeating constraints if the type is used in more than one table:
create domain latitude_t as double precision not null
                                             check(value>=-90 and value<=90);
create domain longitude_t as double precision not null
                                              check(value>-180 and value<=180);

create type geocoord_t as (latitude latitude_t, longitude longitude_t);

create table my_table(id serial, geocoord geocoord_t);

insert into my_table(geocoord) values ((31.778175,35.22995));

select id, (geocoord).* from my_table;
 id | latitude  | longitude
----+-----------+-----------
  1 | 31.778175 |  35.22995

A: For non GIS application I just use columns, as suggested by Jack, though I don't bother with with the check value. It is a good idea to also specify the datum (IE NAD27) in an additional column, as the datum is important for proper interpretation of the values.

A: You can use the builtin POINT datatype without postgis.


text:
Q: Sum of Calculated Column I have calculated column Importance_Weight of which I need to create measure that sum questions for related line number.
Importance_Weight = (ColumnX * Average(ColumnY) )/100
Calculated column values for each question is correct as below but when aggrigated by line number the sum is wrong as blow

I used following measure to calculate sum of questions (q) i.e. L1
LT_WeightPerQuestion:=SUMX(DimQuestion, AVERAGE(Survey[Importance_Weight]))
Thanks in advance.

A: Use measure as below
LT_WeightPerQuestion = SUM(Survey[Importance_Weight])


text:
Q: Alamofire 4 get request something wrong I have to make this get request
curl --request GET \
  --url http://site.exampleTest \
  --header 'authorization: longtoken'

so I've made this function:
    class func getRequest(endPoint: String, headers: [String : String], success:@escaping(JSON) -> Void,  failure:@escaping(NSError) -> Void) {

        Alamofire.request(myBaseURL + endPoint, headers: headers).responseJSON { (responseObject) in
            print(responseObject)

            if responseObject.result.isSuccess {
                let resJson = JSON(responseObject.result.value!)
                success(resJson)
            }
            if responseObject.result.isFailure {
                let error = responseObject.result.error!
                failure(error as NSError)
            }
        }

    }

and I launch it like this:
let headerRequest = ["authorization":getUserDefaultElement(key: "token")]

    APIManager.getCurrentChatRequest(endPoint: "chats", headers: headerRequest, success: { (JSONObject) in
            print(JSONObject.debugDescription)
        }, failure: { (error)  in
            print(error)
        })

FAILURE:
  responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error
  Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character
  0." UserInfo={NSDebugDescription=Invalid value around character 0.})) Error Domain=Alamofire.AFError Code=4 "JSON could not be serialized
  because of error: The data couldn't be read because it isn't in the
  correct format."

With the same token I have no errors in postman, so where am I wrong?
edit
my get should be this
    {
      "data": [
        {
         stuff in here
         }
       ]
    }

edit 2
here's the swift way, picked from postman in which i get 200 OK:
let headers = [
  "authorization": "token" //modified by me
]

let request = NSMutableURLRequest(url: NSURL(string: "http://link.api.me")! as URL, //modified by me
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()

A: Give this a try. I believe you weren't putting the headers in the right format.
class func actualReq() {
    let headerRequest: HTTPHeaders = [
        "authorization":getUserDefaultElement(key: "token")
    ]

    APIManager.getCurrentChatRequest(endPoint: "chats", headers: headerRequest, success: { (JSONObject) in
        print(JSONObject.debugDescription)
    }, failure: { (error)  in
        print(error)
    })
}

class func getRequest(endPoint: String, headers:HTTPHeaders, success:@escaping(JSON) -> Void,  failure:@escaping(NSError) -> Void) {

    Alamofire.request(myBaseURL + endPoint, method: .get, headers: headers).responseJSON{ responseObject in
        switch response.result {
        case .success(let value):
            let swiftyJson = JSON(value)
            print(value)
            success(resJson)
        case .failure(let error):
            print("Error: \(error)")
            failure(error as NSError)

        }
    }
}

Another method:
Alamofire.request(myBaseURL + endPoint, method: .get, headers: headers).responseJSON{ responseObject in
        if response.response?.statusCode == 200 {
            print ("success")
        }else {
            guard let responseCode = response.response?.statusCode else {return}
            print ("code: \(responseCode)")
        }
    }
}


text:
Q: activity stack corrupted after update? Initial Activity (A) launches activity (B).  When the user is on (B), presses home, and then returns to the app, (B) is shown again.  If you update the app (I am updating from an email as it is not published yet) and launch it from the update screen, it will no longer remember to return to (B).  It just restarts activity (A).
If you exit the app by pressing the back button, then from there on it continues to work correctly.
I see something like this described here: Activity history stack wrong upon first install on device?.  Is this a known Android bug?  I am running honeycomb and ICS.

A: The answer to this question is the same answer as described here: https://stackoverflow.com/a/3890397/758074
From what I can tell, the issue is that when you launch an app from the android installer it launches an instance of Activity (A) into the existing Task.  As described in the answer link above, the bug is described
here: http://code.google.com/p/android/issues/detail?id=2373
and here: http://code.google.com/p/android/issues/detail?id=26658
This code in Activity (A) onCreate() did workaround the issue.
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    if (!isTaskRoot())
    {
        Log.d("SplashActivity", "Splash is not Task Root, finish()");
        finish();
        return;
    }
}


text:
Q: CSS wrapping li items in fixed height menu I'm a bit stumped. I'm trying to create a simple menu structure using parent/child un-ordered lists. I've run into a road block trying to figure out the css needed to achieve the menu display listed in the image below:

Here is an example html menu structure

Item

Item

Item

Item

Item

Item

Item

Item

Item

Item

Item

Item

Item

Item

Item

Item

Item

Item

Item

Item

Item

Item

Item

Item

Item

Item

Item

Item

Item

Item

Item

Item

Item

As you can see the level 1
 has 6
 items of varying heights depending on the contents on the level 2
.
For some reason, I'm completely drawing a blank on how to achieve this display effect with css. display:inline-block; won't work, as
 numbers 5 and 6 would just display on a new line, with lots of empty space below
 2, 3, and 4.


text:
Q: Trying to compile x64 app on linux with mono gives PE32Plus error? the full error is

Error CS8088: Your .NET Runtime does not support `PE32Plus'.
     Please use the latest Mono runtime instead. (CS8088) (test)

this is on a x86_64 linux system with mono and monodevelop installed as x86_64. This happens with any application I try to compile as x64 including an empty test program.
I have mono 2.6.7 install and monodevelop 2.4.3, Can anybody out there provide insights.
from what I can tell PE32Plus is a filetype for 64bit applications but mono's website says they support x64 environments

A: Managed applications are run via 'mono myApp.exe' on Linux. The version of 'mono' specified determines whether the app is 64-bit or 32-bit. If you use a 32-bit mono runtime, the managed application will be run in 32-bit mode. If you use a 64-bit mono runtime, the managed application will be run in 64-bit mode. Windows supports launching a managed executable directly via OS support, and uses the platform information to determine whether to launch the managed code as 32 or 64 bit.
So, platform information only matters on Windows with .Net. Mono ignores this information. I believe the most recent mono's support compiling with the x64 platform switch. If not, it's fine to compile it as x86 and run it with a 64-bit mono runtime.

A: I recently asked the same on mono's IRC channel and it seems that it's not supported.
Specifically, I was told not to use "-platform:x64" because not only the runtime ignores it but the SRE (System.Reflection.Emit) implementation doesn't know how to emit PE32+ binaries.


text:
Q: Using Boost with getters and setters? I want to serialize a class I don't have write access to. I.e., I can't change the source file nor the header file. Furthermore, most fields are private and are accessed through getter and setter functions.
Can anyone tell me whether it is a good idea (or not) to just create different functions for saving and loading (as explained in the boost tutorial)...
template<class Archive>
void save(Archive & ar, gps_position &g, const unsigned int version) const
{
    // note, version is always the latest when saving
    ar  & g.deg;
    ar  & g.min;
}
template<class Archive>
void load(Archive & ar, gps_position &g, const unsigned int version)
{
    if(version > 0)
        ar & g.deg;
        ar & g.min;
}
BOOST_SERIALIZATION_SPLIT_MEMBER()

... and there use the public functions:
ar & g.getDeg();

instead of
ar & g.deg;

(similar for setter)?? I'm really new into c++ and serialization and I'm very thankful for any hints!
best, alex
edit: added link to boost tutorial

A: template<class Archive>
void load(Archive & ar, gps_position &g, const unsigned int version)
{
    if(version > 0)
    {
        int d = 0;
        ar & d;
        g.setDeg(d);
        int m = 0;
        ar & m;
        g.setMin(m);
    }
}

something like this. declare variable -> read from archive -> set to member by calling setter function.

A: This is the tutorial that the OP is talking about:
http://www.boost.org/doc/libs/1_50_0/libs/serialization/doc/tutorial.html
I have found that using the split functions is sometimes necessary and not a bad idea when it is necessary.  Using the single void serialize(...) function is really convenient, but I've had to split them up when the class I am trying to serialize can't be changed (like what you are encountering).  I definitely wouldn't shy away from splitting void serialize(...) into void save(...) and void load(...) if that's what it is going to take.  If memory serves me right, I had to split into 2 functions cos I __gnu_cxx::hash_map support wasn't very good at one point several years ago, so I did some hack around it to get the data serialized.
The tutorial gets you going, but it is a little lacking and I run into some kind of difficulty every time I use Boost.Serialization.  It's a convenient library to use though.


text:
Q: knights tour in c++ using recursion I have created a class Board which deals with 2d vectors specifically for this purpose. I am trying to solve the Knight's Tour. I want to print out the thing when it is done. Using the recursive voyagingKnight() function I find that it does not do anything, does not print the result. It seems that I would want to increment the step number for the recursive call but this is not working.
The vector argument incs is a 2d vector of increments for moving the knight, in each row a row move in the first colum and a column move in the second column.
Does anyone have any suggestions as to a flaw in my reasoning here?
The relevant code
    bool voyaging_knight( Board &board, int i, int j, int steps ,vector< vector<int> > &increments)
    {
        if( !newplace(theboard, i, j) ) return false;
        board.setval(i,j,step);

        if( gone_everywhere( board, steps) )
        {
        cout <<"DONE" << endl;
        board.showgrid();
         return true;
        }

        int n;
        int in, jn;
        for(n=0; n<8; n++ )
        {
            in = i + increments[n][0];
            jn = j + increments[n][1];

            if( inboard(board, i, j)&& newplace(board,i,j) )
            {

             voyaging_knight( board, in, jn, steps+1 ,increments);

            return true;
            }
        }

        theboard.setval(i,j,-1);

    }

A: Yes, change this:
voyagingKnight( theboard, inext, jnext, step+1 ,incs);
return true;

To this:
return voyagingKnight( theboard, inext, jnext, step+1 ,incs);

In addition, it seems that you need to return something (probably false) at the end of the function.
BTW, I'm assuming that you have all the entries in theboard initialized to -1.

A: I'm guessing that you want 1 continuous path made by horse movements on a (chess)-board found by backtracking.  In that case you have to pass the board by value, so each path you take has its own instance to fill.  By passing by reference, every path fills the same board, so you can never take all the steps.
Also you should pass a result by value and fill it with the positions you visited and return that from the recursive function, so each path has its own instance of resulting positions and by returning it, you end up with the final result.
You should not pass inc because that is just a helper container that doesn't change.

A: Make the board a global variable, and build up a sequence of visited squares in a global variable too. Make sure that when retracting each tentative step you undo any changes (square visited, last step of sequence). Call your knight's tour function, make it return success if it reaches the end, and do any output after finishing.
Package the whole shebang in a file or as a class, so as to not expose private details to prying eyes.


text:
Q: I need a hint for sqlite3 I am trying to retrieve values from db and I am stack from start because sqlite3 is unable to open the db file after I was giving the right path.
Version 1:
sqlite_file = os.environ.get('DATABASE_URL', 'sqlite:///db.sqlite')
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()

Version 2:
sqlite_file = app.config['SQLALCHEMY_DATABASE_URI']
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()

Where:
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', 'sqlite:///db.sqlite')

In both situations the error is
Error on request:
Traceback (most recent call last):
  File "/home/ubuntu/workspace/avb/venv/lib/python3.6/site-packages/werkzeug/serving.py", line 209, in run_wsgi
    execute(self.server.app)
  File "/home/ubuntu/workspace/avb/venv/lib/python3.6/site-packages/werkzeug/serving.py", line 197, in execute
    application_iter = app(environ, start_response)
  File "/home/ubuntu/workspace/avb/venv/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/home/ubuntu/workspace/avb/app.py", line 222, in <module>
    conn = sqlite3.connect(sqlite_file)
sqlite3.OperationalError: unable to open database file

A: For sqlite3.connect() start out using the actual filename (e.g. example.db) as the argument.
Same for environ.get(): use the actual filename, not the sqlite:/// address.


text:
Q: Export multi charts in one PNG file referring to Google Charts documentation I can get the chart Image URI using chart obj function getImageURI . works well for one chart.
I have multiple charts in one page and I would like to export them in one png image. Is that doable?
code:
jsFiddle
docs link:
Printing PNG Charts


text:
Q: Opera: position: fixed & background-image On my page I have an element with the following CSS rules:
.pointer {
    position: fixed;
    background-repeat: no-repeat;
    background-position: center;
    top: 70%;
    z-index: 1;
    width: 3%;
    height: 6%;
    text-indent: 100%;
    white-space: nowrap;
    overflow: hidden;
    float: left;
    left: 0;
    background-image: url("img/myImage.jpg");
}

Works good in the browsers I tested, only Opera does not like it. When I scroll, the background image also gets "scrolled" and therefore disappears as is gets out of the container.
I believe that is a known problem, but still I wasn't able to find a solution.
On this page a method is described how to hide CSS rules from Opera, but besides the fact that this post is anno 2002, I actually don't want to use CSS hacks.
Removing overflow: hidden does not fix it, adding background-attachment: fixed didn't help either. Any other ideas or solutions?
EDIT:
http://jsfiddle.net/mvV7G/

A: I have taken a look at your fiddle project. I believe that the problem is caused by having the background image and border radius applied to the same element, I honestly can't explain why this only happens in opera.
But a simple solution is to wrap the anchor in a div and split the styling between each, ensuring that the background image and radius are on separate elements.
I have created a fiddle with a possible solution, it needs some tidying up but I think it will get you on track - http://jsfiddle.net/zyj6Z
The CSS is below:
.link {
-ms-filter:"progid:DXImageTransform.Microsoft.gradient(startColorstr=#4d000000, endColorstr=#4d000000)";
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#4d000000, endColorstr=#4d000000);
zoom: 1;
background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+PHBvbHlnb24gZmlsbD0iI2ZmZiIgcG9pbnRzPSIyLjc2OSw3Ljk5MiAxMC43NjIsMCAxMy4xMzIsMi4zNjIgNy42MDQsNy44OTkgMTMuMjMxLDEzLjUyOCAxMC43NjIsMTYgMi43NjksOC4wMDcgMi43NzYsOCIvPjwvc3ZnPg==");
background-position: center;
background-repeat: no-repeat;
width: 10%;
height: 10%;
position: fixed;
top: 70%;
left: 0;
}
.test {
width: 10%;
height: 10%;
position: fixed;
top: 70%;
left: 0;
-webkit-background-clip: padding-box;
-moz-background-clip: padding;
background-clip: padding-box;
overflow: hidden;
-webkit-border-radius: 0 5px 5px 0;
-moz-border-radius: 0 5px 5px 0;
border-radius: 0 5px 5px 0;
background-color: #000000;
background-color: transparent\9;
background-color: rgba(0, 0, 0, 0.3);
text-indent: 100%;
white-space: nowrap;
}

and HTML here:

Stuff

        Hide me!

I hope this helps.


text:
Q: trouble with labels in css. can't edit html I need to align fields with their labels, all in 1 straight horizontal line. I'd normally fix this in the HTML, but I can't edit it, so I need it to be fixed with CSS.
This is the jsfiddle demo: http://jsfiddle.net/83hxF/
My HTML:
  name
  <input id="field_21770004" type="text" title="Please fill out this field." placeholder="" name="fields[21770004]"></input>

    depart
    <select id="field_21927140" title="Please fill out this field." placeholder="" name="fields[21927140]"></select>

    platform
    <select id="field_21769174" title="Please fill out this field." placeholder="" name="fields[21769174]"></select>

My CSS:
#field_21770004 {
    width: 150px;
}

#field_21927140 {
    position: absolute;
    top: 10px;
    left: 250px;
}

#field_21769174 {
    position: absolute;
    top: 10px;
    left: 350px;
}

A: It's not really clear to me what you mean. Align the labels where?
This is a solution that will align them in a tabular way, the label next to the input/select fields, each in their own line.)
label {
    display: inline-block;
    width: 6em;
}

.validation {
    margin-bottom: 2em;
}

(This assumes that the display: none; on the validation error field can be removed or altered. What is it there for in the first place? Can't this be done in the CSS file as well?)
Please try to explain a little better so I can be of better help.

A: There are several ways that you can do that, have them aligned vertically or horizontally.
1st method:
HTML:
name
<input id="field_21770004" type="text" title="Please fill out this field." placeholder="" name="fields[21770004]"></input>

depart
<select id="field_21927140" title="Please fill out this field." placeholder="" name="fields[21927140]"></select>

platform
<select id="field_21769174" title="Please fill out this field." placeholder="" name="fields[21769174]"></select>

CSS:
#field_21770004 {
    width: 150px;
    display:inline;
}

Demo: http://jsfiddle.net/83hxF/4/
2nd method:
HTML:
name
<input id="field_21770004" type="text" title="Please fill out this field." placeholder="" name="fields[21770004]"></input>

depart
<select id="field_21927140" title="Please fill out this field." placeholder="" name="fields[21927140]"></select>

platform
<select id="field_21769174" title="Please fill out this field." placeholder="" name="fields[21769174]"></select>

CSS:
#field_21770004 {
    width: 150px;
}
#field_21927140 {
    top: 10px;
    left: 250px;
}
#field_21769174 {
    top: 10px;
    left: 350px;
}

Demo: http://jsfiddle.net/83hxF/5/
3rd method: (Changing CSS only)
#field_21770004 {
    width: 150px;
}
#field_21927140 {
    top: 10px;
    left: 250px;
}
#field_21769174 {
    top: 10px;
    left: 350px;
}

#field_21770004_errors{
    display:none;
}

#field_21769174_errors{
    display:none;
}

Demo: http://jsfiddle.net/83hxF/15/

A: Try floating the inputs/selects left and clearing right, and floating the labels left and clearing left.
input, select {
    float: left;
    clear: right;
}
label {
    float: left;
    clear: left;
}

Here's an updated fiddle: http://jsfiddle.net/ZHVpc/


text:
Q: Unicode character by name It is possible in julia 0.6 obtain the unicode character by its name?
In python it is possible by doing
s = u'\N{SECTION SIGN}'

There is something alike?
I know I can do
s =  '\u00a3'

but I want to do it by name.
Thank you

A: StringLiterals.jl lets you do this.
via s = f"\N{SECTION SIGN}"
StringLiterals.jl was just registered the other day.
You can install it via Pkg.add("StringLiterals")
Examples
julia> using StringLiterals

julia> s = f"\N{SECTION SIGN}" #Unicode Entity
"§"

julia> f"\N{SNOWMAN}" #Unicode Entity
"☃"

julia> f"\:mage:" #Emoji Entity
"\U1f9d9"

julia> f"\<sun>" #LaTeX Entity
"☼"

julia> f"\€" # HTML Entity
"€"


text:
Q: Is MOSIX the easiest way to build a redundant system? I'm trying to figure out the easiest way to build a server with HA.
I looked into Linux-HA, Heartbeat, Mesos.
I then found MOSIX. I don't know if it's a thing from the past that no one uses, but wouldn't make it a no-brainer to create a high-availability cluster that would be totally transparent to the software (and therefore easier to setup and configure)?
Thanks in advance.

A: Mosix has a different purpose. It's meant for parallel systems for HPC (high performance computing), not as a high availability solution.


text:
Q: CSS family tree alignment issues with name length I started with the experimental multi-parent version of the CSS3 Family Tree: http://thecodeplayer.com/experiment/css3-family-tree/2
However I am having some alignment issues with multiple parents (partners in a family tree), which seem to be caused by the length of the text in boxes. If two boxes have the same length text they line up, otherwise the longer one is higher, and the difference in height is proportional to the difference in length.
Also, any child on there own seems to float off to the left rather than sitting centrally as they should. EDIT: THIS PART HAS BEEN ANSWERED
Examples here: http://jsfiddle.net/7g7fz2tL/5/

* {
  margin: 0;
  padding: 0;
}

.tree ul {
  padding-top: 20px;
  position: relative;
  -webkit-transition: all 0.5s;
  -moz-transition: all 0.5s;
  transition: all 0.5s;
}

.tree li {
  float: left;
  text-align: center;
  list-style-type: none;
  position: relative;
  padding: 20px 5px 0 5px;
  -webkit-transition: all 0.5s;
  -moz-transition: all 0.5s;
  transition: all 0.5s;
}
/*We will use ::before and ::after to draw the connectors*/

.tree li::before,
.tree li::after {
  content: "";
  position: absolute;
  top: 0;
  right: 50%;
  border-top: 1px solid #ccc;
  width: 50%;
  height: 65px;
  z-index: -1;
}

.tree li::after {
  right: auto;
  left: 50%;
  border-left: 1px solid #ccc;
}
/*We need to remove left-right connectors from elements without
any siblings*/

.tree li:only-child::after,
.tree li:only-child::before {
  display: none;
}
/*Remove space from the top of single children*/

.tree li:only-child {
  padding-top: 0;
}
/*Remove left connector from first child and
right connector from last child*/

.tree li:first-child::before,
.tree li:last-child::after {
  border: 0 none;
}
/*Adding back the vertical connector to the last nodes*/

.tree li:last-child::before {
  border-right: 1px solid #ccc;
  border-radius: 0 5px 0 0;
  -webkit-transform: translateX(1px);
  -moz-transform: translateX(1px);
  transform: translateX(1px);
  -webkit-border-radius: 0 5px 0 0;
  -moz-border-radius: 0 5px 0 0;
  border-radius: 0 5px 0 0;
}

.tree li:first-child::after {
  border-radius: 5px 0 0 0;
  -webkit-border-radius: 5px 0 0 0;
  -moz-border-radius: 5px 0 0 0;
}
/*Time to add downward connectors from parents*/

.tree ul ul::before {
  content: "";
  position: absolute;
  top: -60px;
  left: 50%;
  border-left: 1px solid #ccc;
  width: 0;
  height: 80px;
  z-index: -1;
}

.tree li a {
  border: 1px solid #ccc;
  padding: 5px 10px;
  text-decoration: none;
  color: #666;
  font-family: arial, verdana, tahoma;
  font-size: 11px;
  display: inline-block;
  background: white;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
  -webkit-transition: all 0.5s;
  -moz-transition: all 0.5s;
  transition: all 0.5s;
}

.tree li a+a {
  margin-left: 20px;
  position: relative;
}

.tree li a+a::before {
  content: "";
  position: absolute;
  border-top: 1px solid #ccc;
  top: 50%;
  left: -26px;
  width: 25px;
}
/*Time for some hover effects*/
/*We will apply the hover effect the the lineage of the element also*/

.tree li a:hover,
.tree li a:hover~ul li a {
  background: #c8e4f8;
  color: #000;
  border: 1px solid #94a0b4;
}
/*Connector styles on hover*/

.tree li a:hover~ul li::after,
.tree li a:hover~ul li::before,
.tree li a:hover~ul::before,
.tree li a:hover~ul ul::before {
  border-color: #94a0b4;
}

.tree li a {
  height: 60px;
  width: 60px;
}

.tree > ul > li > ul:before {
  top: -40px;
}
.tree ul li.great-grandchild {
    float: none;
}
}

      Root

          Child with name
          Child with name

              Grandchild with name
              Grandchild with longer name

                  Great Grandchild

              Grandchild with name
              Grandchild with much longer name

                  Great Grandchild

Any ideas what could be causing this/how I can fix it?

A: Adding the missing vertical alignment.
http://jsfiddle.net/7g7fz2tL/6/
.tree li a {
  height: 60px;
  width: 60px;
  vertical-align: top; /*THIS*/
}

A: add a class to the great grandchildren and set float to none like so:
ul li.great-grandchild {
    float:none;
}

here is a link to a working example


text:
Q: not set value in formArray i have edit page in angular 8 . in this page i have a formArray and i need fill it .
i set value form with formArray .
now i use this code for set value :
ts :
createForm(): void {
    this.editQuestionFG = new FormGroup({
      title: new FormControl(this.questions.title, Validators.required),
      courseExamId: new FormControl(this.questions.courseExamId, Validators.required),
      courseOptions: this._formBuilder.array([])
    });
  }

  createItem(): FormGroup {
    return this._formBuilder.group({
      optionTitle: new FormControl('', Validators.required),
      isCorrect: new FormControl(true, Validators.required)
    });
  }

  setItem(item: Options[]) {
    const formArray = new FormArray([]);
    for (let x of item) {
      formArray.push(this._formBuilder.group({
        isCorrect: x.isCorrect,
        optionTitle: x.optionTitle
      }));
    }
    this.editQuestionFG.setControl('courseOptions', formArray);
    console.log(this.editQuestionFG.controls['courseOptions'].value)
  }

and this is html code :

                            <ng-container [formGroupName]="i">

                                    <mat-form-field class="mat-form-field-fluid" appearance="outline">
                                        <mat-label>{{'GENERAL.TITLE' | translate}} *</mat-label>
                                        <input matInput formControlName="optionTitle"
                                            [placeholder]="'GENERAL.TITLE' | translate">
                                    </mat-form-field>

                                    <mat-radio-group name="radp" aria-label="Select an option"
                                        formControlName="isCorrect">
                                        <mat-radio-button value='true'>صحیح</mat-radio-button>
                                    </mat-radio-group>

                            </ng-container>

                            <button (click)="AddItems()" mat-raised-button type="button"
                                color="accent">{{'COURSE_QUESTION.ADD_NEW_OPTION' |translate}}</button>

when i use this code it fill the optionTitle but it not set the isCorrect  in radio-button value .
whats the problem ? how can i solve that????


text:
Q: C# - Trying to convert Dictionary to JSON Here is my code:
public class JsonData
{
    public string header;
    public Dictionary<string, string> data = new Dictionary<string, string>();
    public int connectionId;
}

JsonData SendData = new JsonData();
SendData.header = "01";
SendData.data.Add("text", "What is Lorem Ipsum?Lorem ");
SendData.data.Add("accId", "123");
SendData.connectionId = 12;

string json = JsonUtility.ToJson(SendData);

Everything is fine but somehow the key data in the converted JSON string does not appear at all.
The string json looks like this:
{"header":"01","connectionId":12}

instead of:
{"header":"01","data":{"text":"What is Lorem Ipsum?Lorem ","accId":"123"},"connectionId":12}

Where is my mistake ?
Why i can not receive result like this ?

A: Use Newtonsoft.Json to get the right json. Given you have it referenced on your project use the namespace:
using Newtonsoft.Json;

And use the JsonConvert.SerializeObject static method:
string json = JsonConvert.SerializeObject(SendData);

A: From https://docs.unity3d.com/ScriptReference/JsonUtility.ToJson.html.

Note that while it is possible to pass primitive types to this method,
  the results may not be what you expect; instead of serializing them
  directly, the method will attempt to serialize their public instance
  fields, producing an empty object as a result. Similarly, passing an
  array to this method will not produce a JSON array containing each
  element, but an object containing the public fields of the array
  object itself (of which there are none). To serialize the actual
content of an array or primitive type, it is necessary to wrap it in a
class or struct.

Try exposing the contents of data in a property, like the following.
    public string dataOutput
    {
        get
        {
            return string.Join(",", data.Select(x => string.Format("\"{0}\":\"{1}\"", x.Key, x.Value)));
        }
    }


text:
Q: How can I get a person's country from this database? I'm having a real bad time with an assignment with a given database, a fake simulator on Mysql. My problem is, I need a Query to get the data from a client's Country, but Client's table only contains a City data. Tables are:
tbl_Client:
/ ID*
/ Name
/ Birthday
/ ID_City (FK)

tbl_City:
/ ID_City *
/ vchCityName
/ ID_State (FK)

tbl_State:
/ ID_State *
/ vchStateName
/ ID_intRegion (FK)

tbl_Region:
/ ID_Region *
/ vchRegionName
/ ID_Country (FK)

tbl_Country:
/ ID_Country *
/ vchCountryName

So, my question is, how can I get a Client's country to compare it with other data? (The big question is comparing a client's nationality with a musician they prefer, but what I can't seem to manage is the client part). I was trying something very basic, but it doesn't work.
(...)tbl_Client CL, tbl_City CT, tbl_State ST, tbl_Region R, tbl_Country C
WHERE CT.ID_City = ST.ID_City
AND ST.ID_Region = R.ID_Region
AND R.ID_Contry = C.ID_Contry

And then I tried to compare that C.ID_Country, and well, I tried a lot of things and still got nothing... I would really appreciate if someone could enlighten me on this.
Thanks a lot everyone!

A: With this you get all the data in relation
select tbl_Client.*, tbl_City.*, tbl_State.*, tbl_Region.*, tbl_Country.*
from tbl_Client
inner join tbl_City on tbl_Client.ID_City = tbl_City.ID_City
inner join tbl_State on tbl_State.ID_State = tbl_City.ID_State
INNER join tbl_Region on tbl_Region.ID_Region = tbl_State.ID_Region
INNER join tbl_Country on tbl_Country.ID_Country =tbl_Region.ID_Country;

if you need the country for a client ID eg id = 3
select tbl_Client.* , tbl_Country.*
from tbl_Client
inner join tbl_City on tbl_Client.ID_City = tbl_City.ID_City
inner join tbl_State on tbl_State.ID_State = tbl_City.ID_State
INNER join tbl_Region on tbl_Region.ID_Region = tbl_State.ID_Region
INNER join tbl_Country on tbl_Country.ID_Country =tbl_Region.ID_Country
where tbl_Client.ID = 3;


text:
Q: Convert .CSV to HTML Table I want to convert a .csv file to a HTML Table in jQuery. To accomplish that, I'm using a jQuery Plugin called CSVToTable.
The way I used it in my code is as follow:
I called the .CSVToTable('path/to/file.csv') on my

:
$("#ItemTable").CSVToTable('ItemDatabase.csv', {
  loadingImage: 'img/loading.gif',
  startLine: 0
});

Everything seemed to work, as well as the loading.gif (which was included in the download).
My first try was running it on the ItemDatabase.csv, which is a .csv that contains approx. 350 lines. It kept loading and loading, and after 15 minutes, I tried it with a smaller file that contains 5 lines. It made no difference.
I looked at the source of their website with a demo, which worked fine, replaced the code, but made no difference.
If somebody could tell me what I'm doing wrong, that would be very helpful.
Note: I checked the file paths, and everything is initialized correctly
EDIT: For @sakir, the first 4 lines of my .csv file:
Name,Tier,Kind,Lvl,mDam,xDam,HR,MR,SD,LS,MS,XB,LB
Depressing Bow,Depressing,Bow,1,0,0,NONE,NONE,NONE,NONE,NONE,NONE,NONE
Oak Wood Bow,Basic,Bow,1,4,6,NONE,NONE,NONE,NONE,NONE,NONE,NONE
Birch Wood Bow,Basic,Bow,6,6,10,NONE,NONE,NONE,NONE,NONE,NONE,NONE

A: You can not use file from the local-file system. Please copy your file on the web-server and provide the url to that file in the .CSVToTable(url_file).

A: Try this way mate.But be sure to load required javascript and path to csv file.Inform me if it works for.Best of luck
csv file structure(test.csv)
Name,Tier,Kind,Lvl,mDam,xDam,HR,MR,SD,LS,MS,XB,LB
Depressing Bow,Depressing,Bow,1,0,0,NONE,NONE,NONE,NONE,NONE,NONE,NONE
Oak Wood Bow,Basic,Bow,1,4,6,NONE,NONE,NONE,NONE,NONE,NONE,NONE
Birch Wood Bow,Basic,Bow,6,6,10,NONE,NONE,NONE,NONE,NONE,NONE,NONE

code to  convert csv 2 table
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>jQuery CSVToTable</title>

    <link rel="stylesheet" href="css/csvtable.css" type="text/css" />

 CSV To Table:


text:
Q: Log Apache Beam WriteToDatastore result to BigQuery - Python I have a very simple pipeline in python
 with beam.Pipeline(options=create_pipeline_options(pipeline_args)) as p:
            rows = (p | 'ReadFromBigquery' >> beam.io.ReadFromBigQuery(table=f"{known_args.project}:{known_args.datasetId}.{known_args.tableId}", use_standard_sql=True))
            entities  = (rows | 'GetEntities' >> beam.ParDo(GetEntity()))
            updated = (entities | 'Update Entities' >> beam.ParDo(UpdateEntity()))
            _ = (updated | 'Write To Datastore' >> WriteToDatastore(known_args.project))

I want to log which entities have been correctly updated after WriteToDatastore has finished running so I could write them in a bigquery audit table. Ideally it would look something like this
successful_entities, failed entities = (updated | 'Write To Datastore' >> WriteToDatastoreWrapper(known_args.project))
 _ = (successful_entities | 'Write Success To Bigquery' >> beam.io.WriteToBigQuery(table=f"{c.audit_table}:{known_args.datasetId}.{known_args.tableId}"))
 _ = (failed_entities| 'Write Failed To Bigquery' >> beam.io.WriteToBigQuery(table=f"{c.audit_table}:{known_args.datasetId}.{known_args.tableId}"))

Is this possible to achieve?
Alternatively if the whole batch fails after n numbers of retries, is it possible to catch that failure and log which batch has failed (assuming I have some sort of runId to keep track of batches)

A: I hope it can help.
I propose you a solution with a dead letter queue before writing the result to Datastore.
Beam suggests using a dead letter queue in this case, and we can achieve that with TupleTags.
You can write it with Beam native but the code is verbose.
I created a library in Beam Java and Python called Asgarde :
Here the link of the Python version : https://github.com/tosun-si/pasgarde
You can install the package with pip :
pip install asgarde==0.16.0

With Asgarde, you can catch errors in each step of the pipeline, before writing the result with the IO (Datastore in this case)
Example :
input_teams: PCollection[str] = p | 'Read' >> beam.Create(team_names)

result = (CollectionComposer.of(input_teams)
            .map('Map with country', lambda tname: TeamInfo(name=tname, country=team_countries[tname], city=''))
            .map('Map with city', lambda tinfo: TeamInfo(name=tinfo.name, country=tinfo.country, city=team_cities[tinfo.name]))
            .filter('Filter french team', lambda tinfo: tinfo.country == 'France'))

result_outputs: PCollection[TeamInfo] = result.outputs
result_failures: PCollection[Failure] = result.failures

Asgarde proposes a wrapper with CollectionComposer class instantiated from a PCollection.
Then each operator like map, flat_map, filter applies the operation while error handling.
The result of CollectionComposer is a Tuple with :

*

*PCollection of successful outputs

*PCollection of Failure
Failure is an object given by Asgarde :
@dataclass
class Failure:
    pipeline_step: str
    input_element: str
    exception: Exception

This object gives the current input_element concerned by the error and the current exception.
pipeline_step is the current name used for the transformation.
Your pipeline can be adapted in the following way with Asgarde :
with beam.Pipeline(options=create_pipeline_options(pipeline_args)) as p:
     rows = (p | 'ReadFromBigquery' >> beam.io.ReadFromBigQuery(table=f"{known_args.project}:{known_args.datasetId}.{known_args.tableId}", use_standard_sql=True))

     result = (CollectionComposer.of(rows)
                .map('GetEntities', lambda el : get_entity_function(el))
                .map('Update Entities', lambda entity : update_entity_function(entity)))

     result_outputs = result.outputs
     result_failures: PCollection[Failure] = result.failures

     (result_outputs | 'Write To Datastore' >> WriteToDatastore(known_args.project))

     (result_failures
         | 'Map before Write to BQ' >> beam.Map(failure_to_your_obj_function)
         | 'Write Failed To Bigquery' >> beam.io.WriteToBigQuery(table=f"{c.audit_table}:{known_args.datasetId}.{known_args.tableId}"))

You can also apply the same logic with Beam native, I share you an example from my personal Github repository :
https://github.com/tosun-si/teams-league-python-dlq-native-beam-summit/blob/main/team_league/domain_ptransform/team_stats_transform.py


text:
Q: Perform vector-based operation on data.frame by group I have seen some fairly similar questions answered here, however, my brain is having some trouble making the leap to apply what I read directly to my data.
I would like to subtract a vector contained in a data.frame from a larger data frame that's organized into groups. In this scenario I have a standard reference (dfRef) that I would like to subtract from several repeated experimental measures (dfMeasured) to get a data.frame of the difference (dfDelta).
The data is organized as such:
dfRef
# input output
# 0     4
# 1     7
# 2     8
# 3     1

dfMeasured
# input output group
#  0      4      A
#  1      5      A
#  2      9      A
#  3      1      A
#  0      2      B
#  1      3      B
#  2      5      B
#  3      8      B
#  0      1      C
#  1      4      C
#  2      2      C
#  3      9      C

I would like my output to be something like:
dfDelta
# input output group
#  0      0      A
#  1      -2     A
#  2      1      A
#  3      0      A
#  0      -2     B
#  1      -4     B
#  2      -3     B
#  3      7      B
#  0      -3     C
#  1      -3     C
#  2      -6     C
#  3      8      C

A: One way is join on 'input' and then assign the value to 'output
library(data.table)
setDT(dfMeasured)[dfRef, output := output - i.output,on = .(input)]
dfMeasured
#    input output group
# 1:     0      0     A
# 2:     1     -2     A
# 3:     2      1     A
# 4:     3      0     A
# 5:     0     -2     B
# 6:     1     -4     B
# 7:     2     -3     B
# 8:     3      7     B
# 9:     0     -3     C
#10:     1     -3     C
#11:     2     -6     C
#12:     3      8     C


text:
Q: install application data from SD card of emulator to android device I have a media player application, where videos are saved in SDcard image of emulator. Now, i want to run same application on android device.
How to transfer video from SDcard image to device memory?
what are the changes need to be made for my program...
Code:
  final String MEDIA_PATH = new String("/sdcard/");
  //path of sdcard image on emulaotr

public ArrayList<HashMap<String, String>> getPlayList()
    {
        File home = new File(MEDIA_PATH);

        if (home.listFiles(new FileExtensionFilter()).length > 0)
        {
            for (File file : home.listFiles(new FileExtensionFilter()))
            {
                HashMap<String, String> song = new HashMap<String,String>();
                song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
                song.put("songPath", file.getPath());

                // Adding each song to SongList
                songsList.add(song);
            }
        }

        return songsList;
    }

    class FileExtensionFilter implements FilenameFilter
    {
        public boolean accept(File dir, String name)
        {
            return (name.endsWith(".mp3") || name.endsWith(".MP3") || name.endsWith(".mp4") || name.endsWith(".MP4"));
        }
    }


text:
Q: JS: "this" in function context in strict mode, MDN spec doesn't match chrome 67 implementation From MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this, it says:
In strict mode, however, the value of this remains at whatever it was set to when entering the execution context, so, in the following case, this will default to undefined:
function f2() {
  'use strict'; // see strict mode
  return this;
}

f2() === undefined; // true

This suggests that if I (1) 'use strict'; and (2) define f2 inside another function that invoking f2 would bind the outside function's this for f2.
BUT!
It doesn't work...

'use strict';

function AlarmClock(clockName) {
  this.clockName=clockName;
}

console.log("hello, let's see some weird stuff");

console.log("THIS in global", this);

AlarmClock.prototype.start = function(seconds) {
  console.log('outer', this);
  var testInside = function() {
    console.log('inner', this);
  }
  testInside();
}

var clock = new AlarmClock("Horizons")
clock.start(1);

// WITHOUT CONSTRUCTORS

function withoutOut() {
  console.log("withoutOut", this)
  this.howard="notSoBad";
  console.log("modifiedTheThis, should have Howard", this)
  function withoutIn1() {
   console.log("withoutIn1", this);
   console.log("Strict should set to the defining object's this");
  }
  var withoutIn2 = function() {
    console.log("withoutIn2", this);
    console.log("Strict should set to the defining object's this");
  }
  withoutIn1();
  withoutIn2();
}

withoutOut.bind({Moose: "genius"})();

console.log("DONE");

Gives this output:
hello, let's see some weird stuff
THIS in global {}
outer AlarmClock { clockName: 'Horizons' }
inner undefined
withoutOut { Moose: 'genius' }
modifiedTheThis, should have Howard { Moose: 'genius', howard: 'notSoBad' }
withoutIn1 undefined
Strict should set to the defining object's this
withoutIn2 undefined
Strict should set to the defining object's this
DONE

NOTE: I ran this with node v10.5.0, from a mac osx command line.
NOTE2: If you run in devtools, you have to follow these steps for use strict.
NOTE3: Basically, I want to find someway to get inner, withoutIn1 or withoutIn2 to NOT be undefined. And, I know you can do this with an explicit bind, but I want to specifically get the behavior specified in the MDN doc.
If you agree with me, MDN should change the "this" doc to just say, in function context with "use strict", this is set to undefined ALWAYS. (author likes)
Or, Chrome should change the implementation. (author dislikes)

A: The value of this when a function is called has nothing at all to do with how or where the function is defined. It has to do only with how the function is called. Calling your inner functions:
AlarmClock.prototype.start = function(seconds) {
  console.log('outer', this);
  var testInside = function() {
    console.log('inner', this);
  }
  testInside();
}

like testInside() without any object reference means that there's nothing to bind to this, and in strict mode that means this is undefined. However, if you had written instead
  testInside.call(this);

then there'd be a context value. The fact that a function is "inside" another function, again, has absolutely no impact on how this is bound. Alternatively:
  this.testInside = testInside;
  this.testInside();

it'd also work, because once again there's a context.
Oh, and also also, the new(ish) arrow function mechanism does let you create functions that effectively "inherit" the this value from their lexical environment. So:
AlarmClock.prototype.start = function(seconds) {
  console.log('outer', this);
  var testInside = () => {
    console.log('inner', this);
  }
  testInside();
}

would work, because calling an arrow function does not involve any this binding; this behaves essentially like a variable in the closure.


text:
Q: Unhandled Rejection (TypeError): user.getSession is not a function I am using AWS amplify in my app, I implemented a login function with google. But after login, i get this error Unhandled Rejection (TypeError): user.getSession is not a function .
I have used Auth.federatedSignIn function for the login.
Here is my code:
       const responseGoogle = async (response) => {
    try {
      setLoading(true);
      const user = {
        name: response.profileObj.name,
        email: response.profileObj.email
      };

      const password = await Auth.forgotPassword(user.email);

      let expires_at = addMilliseconds(new Date(), 3600 * 1000).getTime();

      const result = await Auth.federatedSignIn(
        'google',
        { token: response.tokenId, expires_at },
        user
      );

      console.log(result);
      console.log('heree');

      history.push('/classes/google');
      setLoading(false);
      setUserInfo(loadedUsers, email);
    } catch (error) {
      console.log(error);
      if (error.message !== `Cannot read property 'name' of undefined`) {
        enqueueSnackbar(error.message, { variant: 'error' });
      }
      setLoading(false);
    }
  };

The response is the response that I get from google.
does anyone know why I am getting this error? appreciated any type of help. Thanks

A: Firstly you have to check all restrictions auth is at the config json when you create auth function
The second thing is you have to pass three parameters in order to change passwords such as

*

*User
Is the user session and you can get it by fetch the current sesion token and auth data.

*Oldpassword

*New Password


text:
Q: Python code modification to make output file as XML and not CSV The following code gives me the data for all the folders, subfolders and files along with the size of each. Currently, this is saving the data in a CSV file. But I believe this kind of data (nested data) is best suited for XML. I am not very well versed with XML. Any help to modify the code will be appreciated
import os
import csv

def GetHumanReadable(size,precision=2):
    suffixes=['KB','MB','GB','TB']
    suffixIndex = 0
    while size > 1024:
        suffixIndex += 1 #increment the index of the suffix
        size = size/1024.0 #apply the division
    return "%.*f %s"%(precision,size,suffixes[suffixIndex])

def list_files(startpath):
    with open('output.csv','w') as file:
        for root, dirs, files in os.walk(startpath):
            level = root.replace(startpath, '').count(os.sep)
            indent = ' ,' * 4 * (level)
            file.write('{}{}/\n'.format(indent, os.path.basename(root)))
            subindent = ' ,' * 4 * (level + 1)
            for f in sorted(files, key=lambda f: os.path.getsize(root + os.sep + f)):
                converted_size = GetHumanReadable(os.path.getsize(root + os.sep + f))
                file.write('{}{},{}\n'.format(subindent, f, converted_size))

A: You can take help of import xml.etree.ElementTree to make an output xml file.
here is an example
import xml.etree.ElementTree as ET
data='''
<root>
<H D="14/11/2017">
<FC>
    <F LV="0">The quick</F>
    <F LV="1">brown</F>
    <F LV="2">fox</F>
</FC>
</H>
<H D="14/11/2017">
<FC>
    <F LV="0">The lazy</F>
    <F LV="1">fox</F>
</FC>
</H>
</root>
'''
root= ET.XML(data)

with open('d:\output.xml', 'wb') as file:
    Et.ElementTree(root).write(file, encoding='utf-8', xml_declaration=True)


text:
Q: Opt-In status of a particular number in gupshup api I am integrating WhatsApp thru gupshup Platform. Need to know how to check opt-In status of a particular number in gupshup api. I gives me the list of all users. After sending the opt-in link to another user I need to check the opt-in status of that user only

A: Go to your WhatsApp Dashboard, you will see "View Opt-In" WhatsApp Dashboard-Send Message:

You will see list of all Opt-in users


text:
Q: symfony 4 dynamic route with array I'm quiet new to symfony and spend hours trying to find a solution.
I'm building a multilingual website where page slugs are differents.
For example :
www.mywebsite.com/products EN will be www.mywebsite.com/produits FR but both use the same controller
I have to build a dynamic route and here is the way I did I'm pretty sure I can do better, could you help me?
<?php
namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class websiteController{

    public function __construct(){

        $this -> route = array(
            'about' => 'page_about',
            'contact' => 'page_contact',
        );

    }

     /**
     * @Route("/{page}", name="page")
     */
    public function pageAction($page)
    {

        if($page == $this -> route['about']){
            return new Response('page about');
        }

        if($page == $this -> route['contact']){
            return new Response('page contact');
        }

    }
}
?>

A: There is a bundle for routing internationalization called BeSimpleI18nRoutingBundle but it is not available for symfony 4 right now.

Core symfony implementation
With core symfony you could use multiple routes for each controller, that would have a {_locale} parameter with default value, here the problem would be that two different URLs would be returning the same page.
e.g /test would be the same as /test/en
This might cause problems with SEO
here how the annotations would look like if you wish to implement this method
/**
 * @Route("/test/{_locale}", defaults={"_locale"="en"}, requirements={"_locale":"en"}, name="default_en")
 * @Route("/δοκιμή/{_locale}", defaults={"_locale"="el"}, requirements={"_locale":"el"}, name="default_el", options = {"utf8": true})
 * @Route("/tester/{_locale}", defaults={"_locale"="fr"}, requirements={"_locale":"fr"}, name="default_fr")
 */
public function test($_locale)
{
    return new Response("Your current locale is : $_locale");
}

Dynamic Route
Another option is to create a Routing Service that would apply your logic.
Here is an example.
this would be the controller that handles all the paths
Controller
namespace App\Controller;

use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use App\Service\Router;

class RouterController extends Controller {

    /**
    * @Route("/{path}", name="router", requirements={"path" = ".+"})
    */
    public function router($path,Request $request,Router $router) {

        $result=$router->handle($path);

        if($result){
            $result['args']['request']=$request;
            return $this->forward($result['class'], $result['args']);
        }

        throw $this->createNotFoundException('error page not found!');
    }

}

This Controller Action depends on a service called Router so you will have to create a Router service that would return the an array (you can change it to return a custom object) with keys class and args that would be used to forward the request to a controller action.
Service
/src/Service/Router.php
Here you should implement a function called handle and you can apply any logic to it
here is a basic example
namespace App\Service;

class Router
{

    public function handle($path)
    {
        switch ($path) {
            case "test":
                return [
                    "class" => "App\Controller\TestController::index",
                    "args"  => [
                        "locale" => 'en'
                    ]
                ];
            case "tester":
                return [
                    "class" => "App\Controller\TestController::index",
                    "args"  => [
                        "locale" => 'fr'
                    ]
                ];
            default:
                return false;
        }
    }
}

The code above would forward the request to TestController::index function and will add as parameter to that function the locale variable and also it will include the Request object
You could store the routes in a yaml file or database or any other location you like. You can manipulate the $path variable to extract information about id, page etc.


text:
Q: how to pass expect.toMatchObject() with Date as one of the expected property value using jest? I have an express API endpoint which returns an object and on that object there is a property(property3 in our example below) which has a date as it's value.
For e.g
  res.body = {
       "property1": "value1"
       "property2": "value2"
       "property3": new Date()
    }

I am performing test on this endpoint using jest and supertest.
Since date.now() !== date.now(), how will i pass
expect(res.body).toMatchObject(<expectedObject>)

A: You can use expect.objectContaining which matches subset properties only. Above example can write as following:
expect(res.body).toMatchObject(expect.objectContaining({
  "property1": "value1"
  "property2": "value2"
}))


text:
Q: HTTP Handler works using Cassini, but not with IIS 6 I've created a sample project to simplify my problem.  I have this simple handler:
public class HandleThis : IHttpHandler, IRequiresSessionState
{

    public void ProcessRequest( System.Web.HttpContext context )
    {
        // Score.aspx just says "success"
        context.Response.Redirect( "Score.aspx" );
    }

    public bool IsReusable { get { return true; } }
}

Then, in my config, I have this:
<httpHandlers>
<add verb="*"
path="Survey"
type="HttpHandlerTest.HandleThis, HttpHandlerTest" />

Now when I hit http://server/Survey my handler fires.
If I change my project to run with IIS 6, it won't fire (404).
I tried manually adding the handler in IIS via:
- Web Site Properties
- Home Directory
- Configuration
- Add (browse to my site's .dll), Extension: Survey, uncheck "Verify that file exists"
I notice that IIS (so helpfully) adds the "." in front of my extension, so I hit the site with "b.Survey"; still 404.
Surely it's possible to add a handler in IIS 6?

A: "I tried manually adding the handler in IIS via: - Web Site Properties - Home Directory - Configuration - Add (browse to my site's .dll), Extension: Survey, uncheck Verify that file exists"
It sounds like you're using the wrong "executable" path. The executable path should point to the aspnet isapi dll, not the dll that contains your HttpHandler implementation.
Try using the same path that the .aspx extension is mapped to (often this is: c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll).

A: In Cassini everything goes through your dev server, even though the programming in the server will throw an exception if you try to use it in integrated mode.
In IIS7 it would work, if you are running the application in integrated mode.
In IIS6 you either have to assign path="*" to ASPNET_ISAPI.dll and then have the same quoted code as above in your web.config, or you have to assign the extension in the path for your handler.
If you're having trouble adding the aspnet isapi as * in IIS6, google for "extensionless IIS6" or something similar for step-by-step tutorials.


text:
Q: Texto dentro do cardview pela metade Gostaria de saber como coloco o texto dentro de um cardview mais para cima.

No meu código está assim:
        <android.support.v7.widget.CardView
        android:id="@+id/card_view8"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_gravity="center"
        android:layout_margin="5dp"
        android:background="@color/colorPrimaryDark"
        card_view:cardCornerRadius="2dp"
        card_view:contentPadding="10dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/textView26"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_alignParentTop="true"
                android:text="DETALHES"
                android:layout_centerInParent="true"
                android:textAppearance="?android:attr/textAppearanceLarge" />

        </RelativeLayout>
    </android.support.v7.widget.CardView>

A: A altura do CardView está definida com 50dp o que parece não ser suficiente para a altura do texto.
Defina a altura do CardView, RelativeLayout e TextView como wrap_content:
<android.support.v7.widget.CardView
    android:id="@+id/card_view8"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_margin="5dp"
    android:background="@color/colorPrimaryDark"
    card_view:cardCornerRadius="2dp"
    card_view:contentPadding="10dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/textView26"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:text="DETALHES"
            android:layout_centerInParent="true"
            android:textAppearance="?android:attr/textAppearanceLarge" />

    </RelativeLayout>
</android.support.v7.widget.CardView>


text:
Q: parse txt with different types in string I have txt files with semistructured data, I have to write it in cassandra through spark-cassandra. But for the first I what to parse in only in scala.
my code :
import java.io.File
import scala.io.Source

object parser extends App {
  val path = "somepath"
  val fileArray = (new java.io.File(path)).listFiles()
   for (file <- fileArray)
    for (line <- Source.fromFile(file).getLines())

So how can I parse each string and get values to put it in cassandra?
for example I have (int, text, timestamp, int, text, char, int, text)?
I have to split line for delimiter(" ")? and put them in a tuple? or each of them to convert to readable format?

A: What you probably could do is to handle it as csv file with delimiter(" ")? So let Spark do the parsing for you.
val spark = SparkSession.builder.config(conf).getOrCreate()
val dataFrame = spark.read.option("inferSchema", "true").option("delimiter", " ").csv(csvfilePath)


text:
Q: Scrollspy in Bootstrap not working Simple question, somebody help out? Confused on this.
The navbar in question is hidden when the page loads, and is shown after a form submission along with all the content.
Here is the navbar code:

<navbar inner code>

</navbarcode>

Content with all the anchors

It isn't attaching itself to the screen, it isn't spying on the content as I scroll or anything.
Not quite sure.  I'm using bootstrap so all relevant files are included.  I've copied multiple examples verbatim and can't get it to work.
Here's a jsfiddle with the full code: http://jsfiddle.net/ccRnM/7/
Note: This navbar is not at the top of the page, there is an image that sets above it and I want to be able to scroll past that into the page content and have the navbar then take hold, somewhat like they do in their example on the bootstrap site.
Ideas?

A: Here is one way of doing this.  http://jsfiddle.net/panchroma/8jPNm/
Instead of using scrollspy via javascript I used

85 is the distance the screen needs to scroll before the navbar affixed, so play with this.
I also added some CSS to position the navbar after it's affixed, and added the bootstrap.min.js to the page resources.
Good luck!


text:
Q: Invariants of Connection Form I am somewhat going out "on a limb" here, since I am much more grounded in the physics side of things than I am in mathematics. Nonetheless, I am wondering if someone is able to comment on the following : given a connection form defined on a differential manifold, one can derive a tensorial invariant of this, the curvature form. If there is a soldering form present, one can also define torsion as an invariant of the connection form.
My question now is - are there any invariants other than curvature and torsion that can be derived from a connection on a differentiable manifold? My interest here is again motivated by physics, specifically gravitation theory; here using the torsion-free Levi-Civita connection will give us GR, and allowing torsion into the picture will give us Einstein-Cartan gravity. To me, this raises the question if - mathematically speaking - there are other options based on other connection invariants that I am not myself aware of.
I apologise if the question turns out to be meaningless - I am not a mathematician, and was not immediately able to find conclusive answers to this through a Google search.

A:
Are there any other invariants other than curvature or torsion that can be derived from a connection on a differentiable manifold?

The $n$th Chern number $c_n$ of a manifold is a topological invariant. For example,
$$c_1=\frac{i}{2\pi}\int_{M} \, \mathrm{Tr}[\mathcal{R}]$$
where $\mathcal{R}$ is the curvature $2$-form. Technically, it is another quantity, even though it is derived from the curvature. Although, the fact that $c_1$ is a topological and not just geometrical invariant is not immediately obvious from the expression. If I interpret your 'invariance' as invariance under $\mathrm{Diff}(M)$, then scalars constructed from tensors through contractions such as,$^{\dagger}$
$$R^a_{bcd}R^{b}_{a}R^{cd}$$
are invariants. Another example, interpreting 'invariance' as topological invariance, is the Chern-Simons term (used in topological quantum field theory),
$$S=\frac{k}{4\pi}\int_M \, \mathrm{Tr}\left[ A \wedge dA + A\wedge A \wedge A\right]$$
which meets your requirements as $A$ is both a gauge field, and a connection on a bundle of a manifold. There are many other examples of different types of invariants; your question is quite broad and ill-defined.

$\dagger$ The reason we check curvature scalars to see whether our space truly possesses a singularity is precisely because they are invariant under coordinate transformations, and we know inadequate coordinates can lead to the metric being singular when the space is not.


text:
Q: Rhythmbox crashes after Update to Ubuntu 16.04 Since I updated to Ubuntu 16.04 two days ago, Rhythm Box always crashes after about 10 seconds into opening.
This is the terminal output:
(rhythmbox:7725): Gtk-WARNING **: Duplicate child name in GtkStack: Zur Wiedergabeliste hinzufügen
(rhythmbox:7725): Gtk-WARNING **: Duplicate child name in GtkStack: Zur Wiedergabeliste hinzufügen
(rhythmbox:7725): Gtk-WARNING **: Duplicate child name in GtkStack: Zur Wiedergabeliste hinzufügen
(rhythmbox:7725): Gtk-WARNING **: Duplicate child name in GtkStack: Zur Wiedergabeliste hinzufügen
(rhythmbox:7725): Gtk-WARNING **: Duplicate child name in GtkStack: Zur Wiedergabeliste hinzufügen
(rhythmbox:7725): Gtk-WARNING **: Duplicate child name in GtkStack: Zur Wiedergabeliste hinzufügen
(rhythmbox:7725): Gtk-WARNING **: Duplicate child name in GtkStack: Zur Wiedergabeliste hinzufügen
(rhythmbox:7725): Gtk-WARNING **: Duplicate child name in GtkStack: Zur Wiedergabeliste hinzufügen
(rhythmbox-metadata:7741): GStreamer-WARNING **: Trying to set string on structure field 'owner', but string is not valid UTF-8. Please file a bug.
(rhythmbox-metadata:7741): GStreamer-WARNING **: Trying to set string on structure field 'owner', but string is not valid UTF-8. Please file a bug.
(rhythmbox:7725): RhythmDB-CRITICAL **: rhythmdb_entry_get_entry_type: assertion 'entry != NULL' failed
Speicherzugriffsfehler (Speicherabzug geschrieben)

I miss my Rhythmbox very much. Unfortunately I don't have any computer skills and really have no idea how to fix this.


text:
Q: Equivalent of substring in Impala -- else left(wof.ro_end_date, 4) + '-' +
        substring(cast(wof.ro_end_date as varchar(20)), 5, 2) + '-' +
        right(wof.ro_end_date, 2)

This is the code that was originally used in SQL Server Management Studio. Is there any way to do this in the Impala data lake?

A: Try this:
substr(cast(wof.ro_end_date as string),5,2) + '-' + strright(wof.ro_end_date, 2)


text:
Q: How to calculate the derivate of a function for a set variable? Let's say I input following sentences:
x = 5
y = x.^2
z = diff(y)

But I'll be getting
z =

     []

as result, while I'd like to get the actual value of 2x as result, that is 10.
I know the existance of syms and I've tried adding it for x and y values but got not results.

A: You need to use symbolic expression:
syms x y            % creates symbolic variables x,y
y = x^2;            % symbolic expression
t = diff(y);        % t = 2*x (differentiate symbolic expression of y)
z = subs(t, x, 5)   % evaluate t, i.e. z=2*5=10


text:
Q: How to open a VxWorks project using PROFILE_BOOTAPP Configuration profile I am trying to create a custom boot loader in vxworks. When I try to open a project with configuration profile "PROFILE_BOOTAPP". There is no such option. Has anyone faced a similar situation??

A: If during the project creation the PROFILE_BOOTAPP option is not available, it's most likely because you based the project on a SMP Source Build. Redo the VSB with Uniprocessor (UP) and try again.


text:
Q: Filtering objects in Django based on optional arguments Many times I find myself writing code similar to:
query = MyModel.objects.all()
if request.GET.get('filter_by_field1'):
    query = query.filter(field1 = True)
if request.GET.get('filter_by_field2'):
    query = query.filter(field2 = False)
field3_filter = request.GET.get('field3'):
if field3_filter is not None:
    query = query.filter(field3 = field3_filter)
if field4_filter:
    query = query.filter(field4 = field4_filter)
# etc...
return query

Is there a better, more generic way of building queries such as the one above?

A: If the only things that are ever going to be in request GET are potential query arguments, you could do this:
query = MyModel.objects.filter(**request.GET)


text:
Q: Keras output dimension mismatch in LSTM I have been working on a sales prediction model. The model has to predict the product sales for the next 11 days.
The dataset is of this form :
Productid, Sales_on_date_1,........Sales_on_date_142
I have taken the first 131 samples as feature set for the products and 11 samples as labels.
There are in total 1636 products. I have modelled this as a multivariate multistep time series forecasting.
There are 142 time steps.
There is 1 sample for each product.
My code is as follows:
    X=train_data[:,:131]
    y=train_data[:,131:]
    X=X.reshape((1,131,1636))
    y=y.reshape((1,11,1636))
    model=Sequential()
    model.add(LSTM(units=50,return_sequences=True,input_shape=(X.shape[1],X.shape[2])))
    model.add(Dropout(0.2))
    model.add(Dense(units=11))
    model.compile(optimizer = 'adam', loss = 'mean_squared_error')
    model.fit(X, y, epochs = 100, batch_size = 1)

This is the error I get.
ValueError: Error when checking target: expected dense_3 to have shape (131, 11) but got array with shape (11, 1636)
I am doing LSTM for the first time. Can somebody please help me on how should I model the dimensions of the label data ?

A: Since you want to predict one product at a time your training data should be of shape (#ofSamples, sizeOfSample, sampleDimensions) which is in your case (1636, 311, 1) and your labels accordingly (1636, 11). This means you don't have to reshape your data, just need to add a dimension to X. Try this:
X=train_data[:,:131,np.newaxis]
y=train_data[:,131:]
model=Sequential()
model.add(LSTM(units=50,return_sequences=True,input_shape=(X.shape[1],X.shape[2])))
model.add(Dropout(0.2))
model.add(Dense(units=11))
model.compile(optimizer = 'adam', loss = 'mean_squared_error')
model.fit(X, y, epochs = 100, batch_size = 1)


text:
Q: Create array of key value from Object ES6 I have this Object
var obj = {
  'names-1-1': 0,
  'names-1-2': 0.94,
  'names-1-3': 0,
  'names-2-1': 0.95,
  'names-2-2': 0.96,
  'names-2-3': 0.2,
  'names-3-1': 0.96,
  'names-3-2': 99999,
  'names-3-3': 2.4
};

But i need a array of arrays(key, value) something like this:
   0 :{
        names-1-1 : 0
        names-1-2 : 0.94
        names-1-3 : 0
      }
   1 :{
        names-2-1 : 0.95
        names-2-2 : 0.96
        names-2-3 : 0.2
      }
   2 :{
        names-3-1 : 0.96
        names-3-2 : 99999
        names-3-3 : 2.4
      }

where names-{index}-1 index its a var.
How to aproach this using React & javascript ES6?

A: Object.keys has been around since ECMA 5.1
const obj = {
  test: 'some test',
  test2: 'another test'
};

const keys = Object.keys(obj); // ['test', 'test2']

Or Object.entries which was added in ECMA 2017
const obj = {
  test: 'some test',
  test2: 'another test'
};

const entries = Object.entries(obj);
// [['test', 'some test], ['test2', 'another test']]

A: You could do this:
myObject = {
    "names-1-1": .5,
    "names-1-2": .3,
    "names-2-1": .1,
    "names-2-2": .6
}
var out = [];
for (var i in myObject) {
    var index = i.substr(6,1);
    out[index-1] = out[index-1] || {};
    out[index-1][i] = myObject[i];
}
console.log(out);
//[{"names-1-1":0.5,"names-1-2":0.3},{"names-2-1":0.1,"names-2-2":0.6}]

A: You can use Array#reduce method to generate the array.

var obj = {  'names-1-1': 0,  'names-1-2': 0.94,  'names-1-3': 0,  'names-2-1': 0.95,  'names-2-2': 0.96,  'names-2-3': 0.2,  'names-3-1': 0.96,  'names-3-2': 99999,  'names-3-3': 2.4};

var res = Object.keys(obj) // get all the keys
  // iterate to generate the result array
  .reduce(function(arr, k) {

    // get the index from property name using regex
    // or use k.split('-')[1]
    var i = k.match(/names-(\d+)/)[1];
    // define index if not defined
    arr[i - 1] = arr[i - 1] || {};
    // set the property in the object
    arr[i - 1][k] = obj[k];
    // return the array reference
    return arr;

    // set initial value as an empty array
  }, []);

console.log(res);


text:
Q: problems running Docker container in Cypress The docker container 'will build' but for some reason 'will not run'.  I've trying to resolve this but I think I need a fresh pair of eyes on it.
Here is the code:
Docker file:
FROM cypress/included:6.8.0
WORKDIR /app
COPY . /app
RUN npm install
RUN $(npm bin)/ cypress  verify
RUN $(npm bin)/cypress

The docker ignore file
node_modules

The docker-compose.yml file
version: '3'
services:
    e2e:
        image: cypress
        build: .
        container_name: cypress
        command:
            npx cypress run

I got the following error message in my terminal
docker-compose -f docker-compose.yml up
Building e2e
[+] Building 293.8s (9/10)
 => [internal] load build definition from Dockerfile                                        0.1s
 => => transferring dockerfile: 36B                                                         0.0s
 => [internal] load .dockerignore                                                           0.0s
 => => transferring context: 34B                                                            0.0s
 => [internal] load metadata for docker.io/cypress/included:6.8.0                           0.0s
 => [1/6] FROM docker.io/cypress/included:6.8.0                                             0.0s
 => [internal] load build context                                                           0.0s
 => => transferring context: 1.14kB                                                         0.0s
 => CACHED [2/6] WORKDIR /app                                                               0.0s
 => [3/6] COPY . /app                                                                       0.1s
 => [4/6] RUN npm install                                                                 292.0s
 => ERROR [5/6] RUN $(npm bin)/ cypress  verify                                             1.4s
------
 > [5/6] RUN $(npm bin)/ cypress  verify:
#9 1.387 /bin/sh: 1: /app/node_modules/.bin/: Permission denied
------
executor failed running [/bin/sh -c $(npm bin)/ cypress  verify]: exit code: 126
ERROR: Service 'e2e' failed to build
xxx-MacBook-Air CypressDocker %

@mosaad. I just tried your answer.  However I got the following error message
  => ERROR [5/6] RUN $(npm bin)/ cypress  verify                                             1.8s
------
 > [5/6] RUN $(npm bin)/ cypress  verify:
#9 1.705 /bin/sh: 1: /app/node_modules/.bin/: not found
------
executor failed running [/bin/sh -c $(npm bin)/ cypress  verify]: exit code: 127
ERROR: Service 'e2e' failed to build

A: You should copy after npm install so that node_modules are copied too.
This should work:
FROM cypress/included:6.8.0
WORKDIR /app
RUN npm install
COPY . /app
RUN $(npm bin)/ cypress verify
RUN $(npm bin)/cypress

A: Many thanks to everyone who took a moment to take a look at my problem. I rewrote the docker-compose.yml file code again and it now works perfectly.   If this can help anyone in the future here is the corrected code.
FROM cypress/included:6.8.0
WORKDIR /app
COPY . /app
RUN npm install
RUN $(npm bin)/cypress verify
RUN $(npm bin)/cypress


text:
Q: Repairing 'burnt' solder points I recently came across a pcb.
This is the picture of the aforementioned PCB.

As you can see, some solder points seem burnt. The copper trace has been removed.
Does this mean the PCB is dead? If I solder the component on the solder points, will it work?
Maybe I should do prework, like remove pieces of solder with solder wick?

A: This horrific butchering 'repair job' can be repaired with time and patience, assuming the reasonable skills are there. The person who did this can be immediately disqualified by virtue of the latter requirement.
Presumably the part removed is known- maybe a SIP audio amplifier IC or a switch. The part needs to be replaced with a good one (hopefully that's all that is wrong). The pads are all lifted, including the ones that were for primarily mechanical reasons. For the latter perhaps epoxy to provide the mechanical support, but that  can wait until it is working.
First, clean the board with a mild solvent such as 99% isopropanol and one of those manual toothbrushes that the dentists give you at every visit (obviously it should be new, clean and not used for teeth afterward). Then inspect the damage.
I would run a thin (eg. AWG30-AWG24) insulated wire back to the nearest pad that used to be connected to those missing pads- follow the traces to where they went. This is a single-side paper-based phenolic board, so all the circuit is visible. The pads are also very weakly attached to the substrate. Make absolutely sure you get the connections to the right place- a mistake at this point could greatly compound the disaster. You can see that some traces  are peeled back by the ham-fisted thug that worked on it.

Use a sharp Xacto knife or similar fine blade to trim off the loose ends of the ripped traces so they can't get into trouble.
Make sure that the big pins or tabs are connected to the proper places in the same way  (with wires) as the copper around those pads is missing or compromised  (lifted). Looks like they were connected together and to a ground (?) pour via a thermal relief(s).
If you get the device working, make sure you provide mechanical support with something like epoxy.
Some of the unrelated component leads look a bit like cold solder joints, it might not hurt to carefully touch them up. If the device was intermittent that might have been the root cause.

A: You will be able to restore it, given the following

*

*you know what part was originally in. Initially I thought it is some transformer, but most probably it is some IC on the heat sink because both big pads were connected to ground. I might be wrong with it though :)

*Metallization of one of mounting holes is not yet damaged, another one is severely damaged but you will be able to fix connection by soldering a thick pin you usually cut off the through-hole resistors and capacitors when soldering them.

*pin pads are really damaged, thus your task here is to clean everything using spirit of other dissolvent. I do not think you will be able to restore tracks up to good contact with existing copper. You will need to ensure assembly you insert is well fixed through big holes, and then just use air-wires with decent isolation routing to nearest pads. It is very important to know temperature mode of the component you solder to with wires, if it will heat much wire may just disconnect and cause damage to device or even fire.

P.S. For me it seems to be single layer PCB. Device is probably TV, monitor, or some other low-integrated one.

A: That PCB has been butchered during the removal of what looks like the switch-mode power supply transformer. The visible traces have been stripped and probably the through-hole plating and other side too.
Repair will be time-consuming, difficult and will require an identical transformer.
Recommendation: send for recycling.

A: Generally if this happens your only choice is to repair the pads (which can be a painstaking process) or you can solder jumper wires to the nearest pads that used to be connected to the pads that are now removed. There is a such thing as "BER", or "Beyond Economical Repair". You really need to ask yourself, is it worth the trouble? Obviously the final decision is up to you. You probably won't be able to reuse the old pad locations either way, though.

A: The traces could be repaired. They make a pen that costs about 25 bucks it has low resistance silver conductor impregnated with an adhesive. It draws very fine lines. If you want to be fancy they even make a 30 dollar pen to put the green back on the board, Caig labs.
I'm not a salesman - just don't let people tell you you cant do something, you can.
Sorry for resurrecting an old post but I don't want people looking this up and thinking they have to throw something away that they really want to keep. Plus they gain another tool and another skill.


text:
Q: ElasticSearch Nested Range Filter I am attempting to construct an ElasticSearch query and am not getting the results I expect. Any help would be really appreciated!
Mapping Details:
I have indexed documents representing volunteer opportunities. Within each opportunity are fields for:

*

*title of the opp,

*summary,

*approval status, and

*privacy setting.

In addition, each opportunity document has:

*

*one nested nonprofit document representing the nonprofit host of the volunteer opportunity,

*one or more nested cause documents representing the causes addressed by the opportunity,

*zero or more nested skills documents representing the skills needed from volunteers, and

*zero or more nested shift documents representing the time periods available for volunteers to sign up for.

Each nested shift document contains, for now, one nested calendarBlock document with start and end datetime fields as well as a field for the maximum number of volunteers that can sign up for that shift.
The Query
The query I am attempting to construct is a filtered query. A query string is passed in from a form on the web. Then, I need to programmatically attach at least three filters to this query:

*

*A terms filter to return only opportunities with "approved" : "y"

*A terms filter to return only opportunities with "private" : "n"

*A range filter to return only opportunities with at least one shift with a calendarBlock end field that is greater than the current date/time. (IE: Filter out all past shifts.)

The first two filters are working fine. The third one is where I'm stuck. I think the problem might have something to do with the complicated nesting structure. I attempted a nested filter, but I'm not sure if I did this correctly. Also the date fields are actually nested two levels deep. I am still getting results with past shifts when I attempt the query.
What is the proper way to accomplish filtering out all the opportunities with no future shifts scheduled?

A: My problem had to do with the way I was formatting my datetimes.


text:
Q: How to run local node server on subfolder? For an vuejs application.
I need to emulate, in local, a production environment in witch deploy is on a subfolder, like www.domain.com/subfolder1.
How can I configure my local node server so I the local application run on localhost:port/subfolder1?

A: With an already build on /dist folder. This let me try at localhost:8080/custom-sub-path
var express = require('express');
var app = express();
var path = require('path');

app.use('/custom-sub-path/static', express.static('dist/static'));
app.use('/custom-sub-path', express.static('dist'));

app.get('/custom-sub-path/', function(req, res) {
    res.sendFile(path.join(__dirname + '/dist/index.html'));
});

console.log('serving port 8080');

app.listen(8080);

A: Welcome to StackOverflow.
If I understand your question right, I believe you would like to setup a Node.js process running a server (example localhost:1337) and you would like to access it @ http://localhost/subfolder.
For that you will need to setup a reverse proxy, such as NGINX
and create a configuration for forwarding connections to the proccess :
server {
   listen 80 default_server;
   location /subfolder {
        # Forward Real IP
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass http://127.0.0.1:1337;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

NGINX will receive the requests at port 80 and when requested with /subfolder it will forward requests to your Node.js Server running at port 1337.
Hope this helped. Good Luck.


text:
Q: Simple C++ CLR stopwatch For a project, I need to create a simple timer.  A button is pressed to start the stopwatch until the button is pressed again.  The running time is displayed until the stop button is pressed.  It only needs to be accurate to a hundredth of a second.  My question is if the System.Diagnostics::Stopwatch class is the best choice for this application?

A: No, the Stopwatch class is intended for very precise (microseconds or better) measurements, not for accuracy (it may not be synchronized with wall time).
The best way to implement this is to start a regular UI timer and record the start time (perhaps DateTime.UtcNow). Whenever the timer ticks just update the display with the current time minus the start time.


text:
Q: facebook comment system using smarty and prestashop I'm trying to add some comments box to a specific page of my website
but I met some trouble
using smarty I've seen in the documentation that in order to get the current url we should use that synthax  {$smarty.server.HTTP_HOST}{$smarty.server.REQUEST_URI}
that's actualy what I did putting that code in my tpl.
{literal}

 {/literal}

The trouble I have is that it return to me that message
href URL is not properly formatted

The code for getting url does not seems to be interpreted in the source code.
anykind of help will be much appreciated.

A: You are missing a closing
 at the end of your code block  right before the {/literal} tag.
 {literal}

    {/literal}