text:
Q: Google Cloud Storage generate upload/download URL fails with unicode characters in blobname I have been testing uploading & downloading on GCS lately, I was able to generate upload & download URLs without problems as long as the blobname or "path" was all English letters including spaces and special characters.
However once I use unicode characters in the file name (blobname) it fails with KeyError
The docs mentions that unicode is supported:

The name of the blob. This corresponds to the unique path of the
object in the bucket. If bytes, will be converted to a unicode object.
Blob / object names can contain any sequence of valid unicode
characters, of length 1-1024 bytes when UTF-8 encoded.

Code is a few lines:
generate_download_signed_url_v4("storage_files", "202209/جراج.png")

def generate_download_signed_url_v4(bucket_name, blob_name):
    storage_client = storage.Client.from_service_account_json('s_account.json')
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(blob_name)

    url = blob.generate_signed_url(
        expiration=datetime.timedelta(minutes=10), # This URL is valid for 10 minutes
        method="GET", # Allow GET requests using this URL.
    )

    print "Generated GET signed URL:", url
    return url

Error is referring to a keyerror along with the unicode value of the first character in the unicode file name portion (blobname)
  Traceback (most recent call last):
  File "/Users/k/Documents/app30/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1529, in __call__
    rv = self.router.dispatch(request, response)
  File "/Users/k/Documents/app30/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher
    return route.handler_adapter(request, response)
  File "/Users/k/Documents/app30/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1102, in __call__
    return handler.dispatch()
  File "/Users/k/Documents/app30/gae/users_app/helpers.py", line 68, in dispatch
    webapp2.RequestHandler.dispatch(self) # dispatch the main handler
  File "/Users/k/Documents/app30/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 572, in dispatch
    return self.handle_exception(e, self.app.debug)
  File "/Users/k/Documents/app30/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 570, in dispatch
    return method(*args, **kwargs)
  File "/Users/k/Documents/app30/gae/users_app/helpers.py", line 431, in check_admin
    return myfunction(self, *args, **kwargs)
  File "/Users/k/Documents/app30/gae/users_app/main.py", line 10796, in get
    my_file_link = self.generate_download_signed_url_v4(root_bucket_name, "572680296//202209/جراج.png")
  File "/Users/k/Documents/app30/gae/users_app/main.py", line 10863, in generate_download_signed_url_v4
    method="GET", # Allow GET requests using this URL.
  File "/Users/k/Documents/app30/gae/users_app/lib/google/cloud/storage/blob.py", line 338, in generate_signed_url
    quoted_name=quote(self.name))
  File "/Users/k/Documents/app30/google-cloud-sdk/platform/google_appengine/google/appengine/dist27/urllib.py", line 1294, in quote
    return ''.join(map(quoter, s))
KeyError: u'\u062c'
*******> Exception: u'\u062c'

Worth mentioning that this is on the local dev server v.340

A: This issue was fixed in 2018. Looking at the line number and code in
 File "/Users/k/Documents/app30/gae/users_app/lib/google/cloud/storage/blob.py", line 338, in generate_signed_url
    quoted_name=quote(self.name))

confirms are using a version from before that fix (they match this which was changed by this commit). Upgrade to a version of the library later than 1.11.0.


text:
Q: Two variables plotted in a same graphic using 'scatterPlot' from package 'openair' About the command 'scatterPlot' from package 'openair' of R, I used the following command:
data(mydata)

scatterPlot(mydata, x = "nox", y = "no2", method = "hexbin",
            colorcut = seq(0, 1, length = 7), cols =  "default", trans=log, inv=exp)

and I got this graphic:

I need to know if it is possible to have two Scatterplots on the same graph, one with the method "hexbin" and other with the method "scatter"?
Or, more specifically, it is possible to plot points of another variable
over a scatterplot hexbin? I tried to do this for a while, but I did not get hit.
I appreciate any help.

A: I'm here to say that professor Carslaw (the author of the 'openair' package, which have the 'scatterPlot' command) answered my email with the following solution that worked for me:
library(latticeExtra)
plt <- scatterPlot(mydata, method = "hexbin", col = "jet")
b <- scatterPlot(head(mydata, 200), col = "black", pch = 16, cex = 0.5)
plt$plot + as.layer(b$plot)

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the Docker cross platform architecture Docker isn't a VM so it only runs apps native to the OS, right? Does that mean Docker for Windows only runs Windows .exe files? So Docker containers for Windows and Linux, what do they have in common, if anything? Are containers reusable on different operating systems in any way?

A: *

*"Docker isn't a VM"
Correct, containers should be considered as processes running in a sandbox. If you search about how this isolation takes place in Linux, you'll definitely run into namespaces & cgroups. One definition of containers I've seen lately states that:

"containers are processes born from tarballs, anchored to namespaces and controlled by cgroups"

photo by Dan Mayer, #LeadDevLondon - June 2018
You can also find some interesting stuff regarding linux containers here: Anatomy of a Container: Namespaces, cgroups & Some Filesystem Magic - LinuxCon by  Jérôme Petazzoni

*

*Docker for Windows only runs Windows .exe files?
No. Consider that a developer with a Windows PC might work on linux based containers that are later deployed to the cloud. Docker for Windows brings this flexibility, BUT if you run linux containers, these will be running on some kind of virtualization environment. Initially, Docker toolbox was using Oracle Virtualbox, now Docker for Windows uses Hyper-V.
I don't know much about how the isolation takes place inside the Windows OS but I think the logic is similar to Linux. Some info about Windows containers:

Windows Container Types
Windows Containers include two different container types, or runtimes.
Windows Server Containers – provide application isolation through process and namespace isolation technology. A Windows Server Container shares a kernel with the container host and all containers running on the host. These containers do not provide a hostile security boundary and should not be used to isolate untrusted code. Because of the shared kernel space, these containers require the same kernel version and configuration.
Hyper-V Isolation – expands on the isolation provided by Windows Server Containers by running each container in a highly optimized virtual machine. In this configuration, the kernel of the container host is not shared with other containers on the same host. These containers are designed for hostile multitenant hosting with the same security assurances of a virtual machine. Since these containers do not share the kernel with the host or other containers on the host, they can run kernels with different versions and configurations (with in supported versions) - for example all Windows containers on Windows 10 use Hyper-V isolation to utilize the Windows Server kernel version and configuration.
Running a container on Windows with or without Hyper-V Isolation is a runtime decision. You may elect to create the container with Hyper-V isolation initially and later at runtime choose to run it instead as a Windows Server container.

*

*Windows and Linux, what do they have in common, if anything?
In general, I would answer that containers serve the idea of Microservices, separation of concerns, do one thing & do it well.

*

*Are containers reusable on different operating systems in any way?
Yes and No. You may face limitations. For example, if you have an application that starts FROM ubuntu:latest and want to make it work on a raspberry Pi, you will have to build a new container from a base image that is made for arm architecture. Docker is not an abstraction that will take any container and make it work on any architecture, OS... You have to know what you are trying to achieve and carefully make your decisions on what you finally choose to use.


text:
Q: How to detect the user when using a jwt token (Slim-jwt-auth) I'm currently using Slim with slim-jwt-auth.
My project is based on the slim-api-skeleton (https://github.com/tuupola/slim-api-skeleton).
I need to allow a route only for the user who has created the token.
I've done it with the following code:
        //check if it is the right user
        $user = \User::find($args["uid"]);

        $token = $request->getHeader('HTTP_AUTHORIZATION');
        $token = str_replace("Bearer ", "", $token);
        $secret = getenv("JWT_SECRET");
        $decoded = JWT::decode($token[0], $secret, array("HS256"));

        if ($decoded->sub != $user->email)
        {
            throw new ForbiddenException("User not allowed to read.");
        }

Is it correct ? or is there a better way to do it?

A: That is one way to do it. Although I would not parse the token manually. By default the parsed values of JWT are stored in $request->token attribute. Using this you can shorten your code to the following.
$app->get("/user/{uid}", function ($request, $response, $arguments) {
    $user = \User::find($arguments["uid"]);

    $token = $request->getAttribute("token");

    if ($token->sub !== $user->email) ) {
        throw new ForbiddenException("User not allowed to read.");
    }
});

You can change this behaviour using attribute setting.


text:
Q: How do you select a specific item from a dropdown list using JQuery? The current code I have is as follows:
function SetDefaultCarrier(orderCarrier) {
    $("#carrierdropdown option:contains(" + orderCarrier + ")").attr('selected', true);
}

The issue is that this will select the first option found in the list which contains the string orderCarrier. For instance, if orderCarrier is "UPS IG", the function will sometimes select the value "UPS IG C" since the former is a substring of the latter. How do I make it only select an exact match?

A: As commented, the following is what I was looking for:
function SetDefaultCarrier(orderCarrier) {
    $("#carrierdropdown").val(orderCarrier).attr('selected', true);
}


text:
Q: What should the number of trials $n$ be? This is the question:  Strings of Christmas tree lights were designed so that if any one of the bulbs failed, none of the bulbs would light up. Each string has places for $12$ bulbs.  I'll fill them up with bulbs left over from last Christmas. I have a large box of bulbs but $5$% are burned out. I select at random from the bulbs in the box to fill up the strings of lights.
If $X =$ number of good bulbs in a string of $12$. What is the probability that a string will light up?
I know the formula to solve the problem, but I'm not sure what $n$, which is the number of trials, should be.

A: The string will only light up if all 12 bulbs are in working condition.  The probability that the first bulb you pull is in working condition is $0.95$, since 5% of the bulbs don't work.  If your box is big enough, we can assume that the second bulb will also work with probability $0.95$.  (In reality, we've now removed 1 working bulb, which means the percentage of bulbs that work is slightly lowered.  This is typically ignored.)  So the probability that both bulb 1 and bulb 2 work is $0.95\cdot 0.95=(0.95)^2$.  The probability that the first three bulbs all work is $0.95\cdot 0.95\cdot 0.95=(0.95)^3$.  Can you now see how to compute the probability that all 12 bulbs work?


text:
Q: Wordpress plugin to generate .zip file dynamically I have a Wordpress website. In some pages the user can download several documents (.pdf files) and I would like to have a "Download all"  option. So the user is able to download all the documents on that page by once in a zip format.
Since the documents change frequently, I would like that the zip generation is dynamic (I mean by code/plugin) so I don't have to replace the zip manually every time a document changes.
I did some research for Wordpress plugins but the keywords for searching that I am using do not point me in the right direction.

A: You could search the keyword wordpress plugin zip-attachments


text:
Q: Anything Python related causes crash to ArcGIS for Desktop? Problem: ArcMap 10.3 crashes to desktop anytime I use a Python related function (Toolboxes, Field Calulator, Etc)
How I got to this point: I was trying to gain some familiarity with Python programming and opted to use the guide of Learn Python The Hard Way.
This involved downloading, installing Python and setting your environment using Powershell.
I believe this caused some issues since there was already an installation of Python in effect from having ArcGIS Installed. There was already a "Python27" folder on my main HDD.
Question: How do I tell my ArcMap to look in the "Python27\ArcGIS10.3" folder for Python? I'd prefer to avoid re-installing ArcGIS entirely.
Screenshots for thought:

^ From initial research, I found that I should have some sort of Python directory entered into these fields, but I'm not sure what specifically needs to go in there.

A: To resolve the issue I did the following:

*

*Deleted extra installs/instances of Python outside of my ArcGIS10.3 folder.

*Reset my environment by following the steps in "Learn Python The Hard Way" by telling it to look in "Python27\ArcGIS10.3"

*Used "Repair Program" from the Setup application within the main folder for ArcGIS\Desktop

Things seem to be stable and operational now.


text:
Q: insert line in HTML code job using shell Hi I have following sample HTML code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <HTML>
       <HEAD>
         <script src="../2.js"></script>
       </HEAD>
      <body>
        hello all!
      </body>
    </html>

I am trying to insert a <script> line in <HEAD> section.
I tried following command:
sed  '/\<HEAD\>/a \<script src="../blabla.js"\>\</script\>' input.html > temp.html && mv temp.html input.html

But this command is inserting the line twice, one is after <HEAD> and another after </HEAD>
I want to insert only once. How I can overcome this?

A: Replace \<HEAD\> with <HEAD>.  In other words, use:
sed  '/<HEAD>/a <script src="../blabla.js"></script>' input.html

Under GNU sed, the basic regex \<HEAD\> matches the word HEAD because \< matches the start of a word and \> matches the end of a word. This is in contrast to <HEAD> which matches what you want: <HEAD>.
\<HEAD\> matches both occurrences of the string HEAD in your HTML code.  The surrounding angle brackets or slashes are not matched.
In the replacement part of the substitution command, GNU interprets the escaped angle brackets to mean the same thing as just plain angle brackets.  Thus, the escapes are superfluous and are best removed.


text:
Q: Copying references down rows but offsetting 1 column In K41:W41, I have references that start at K10 and go through W10. How can I copy this reference set down rows but have the references offset by 1 column for each row down. So, in K42:W42, I would I have L11:X11, and so on. Thanks.

A: Put this in K41:
=OFFSET($K$11,ROW(1:1)-1,COLUMN(A:A)-1+ROW(1:1)-1)

Copy over and down.

Or this non volatile function:
=INDEX($K$11:$BD$40,ROW(1:1),COLUMN(A:A)+ROW(1:1)-1)


text:
Q: Facing Trouble in making Android Application
Possible Duplicate:
Slow Android emulator

My laptop configuration is

CPU:AMD Dual-core Processor C-60 1 ghz 2 GB DDR3 RAM WINDOWS 7 starter

So creating android application takes too much time and emulator usually goes on not responding mode. What can be optimum solution to fix it?
Can anybody suggest?

A: Yes usually the emulator takes bit time to run.
What you can do is directly run your application on the actual device, thats the best solution and also finally your application should work on the actual device and not on the emulator.

A: You can use Android-x86 running on VirtualBox/VMware


text:
Q: Unnest(String_to_array) conversion in oracle I am migrating procedural structure of PostgreSQL code to Oracle. Is there any alternative function present in Oracle for PostgreSQL's unnest(string_to_array)?
select a.finalval
from   (select unnest(string_to_array(vturs_id, ',')) as finalval)

A: Use a table collection expression and, rather than using a delimited string, use a collection or VARRAY (like SYS.ODCINUMBERLIST):
SELECT COLUMN_VALUE as finalval
FROM   TABLE( SYS.ODCINUMBERLIST( 1, 2, 4 ) )

outputs:

| FINALVAL |
| -------: |
|        1 |
|        2 |
|        4 |

db<>fiddle here
If you have to use delimited string (don't) then you can use a recursive sub-query factoring clause to parse the string:
WITH test_data ( delimited_string ) AS (
  SELECT '1,2,40,-5,72' FROM DUAL
),
bounds ( delimited_string, start_idx, end_idx ) AS (
  SELECT delimited_string,
         1,
         INSTR( delimited_string, ',', 1 )
  FROM   test_data
UNION ALL
  SELECT delimited_string,
         end_idx + 1,
         INSTR( delimited_string, ',', end_idx + 1 )
  FROM   bounds
  WHERE  end_idx > 0
)
SELECT CASE end_idx
       WHEN 0
       THEN SUBSTR( delimited_string, start_idx )
       ELSE SUBSTR( delimited_string, start_idx, end_idx - start_idx )
       END AS finalval
FROM   bounds;

outputs:

| FINALVAL |
| :------- |
| 1        |
| 2        |
| 40       |
| -5       |
| 72       |

db<>fiddle here


text:
Q: How do I force the overwriting of a git branch I pushed and rebased? Using Git, I was working on a feature branch.  I pushed the branch to github so someone could look at it.  Then, it had been a while, so I rebased it.  How do I push my rebased branch over the old one?  What pitfalls must I avoid?  I think it's just git push --force (or --mirror?), but I'm never sure.
Some relevant links:

*

*https://stackoverflow.com/a/255080/237091

*https://stackoverflow.com/a/930160/237091

A: You want to use git push --force but please remember that you are rewriting public history.
Rewriting public history is a very bad idea. Anyone else who may have pulled the old history will have to git pull --rebase and even worse things if they have tagged or branched from the rewritten history, so you must publish your humiliation so they know what to do.
The server may not allow this (but will on github). See receive.denyNonFastForwards (git-config)


text:
Q: Steam library sharing question If I have 3 steam accounts, a primary one - the one that has all the games; and 2 empty ones. If I share my library on the primary account to the other two, can both of the other accounts play at the same time (not the same game obviously)?
So for instance: Account 1 Shares 2 games to account 2 and account 3, can account 2 play game 1 while account 3 plays game 2? Or as soon as account 3 comes online account 2 gets disconnected?

A: No, at least not without shenanigans that break the terms and conditions.
A single shared library can only be used by one account at once. If that library is in use by account 2, account 3 will be unable to access it at all. Account 1, if it is the owner of the game, can access it but will force account 2 to disconnect.

A: It could be done if after account 2 fires up their game, they disconnect from the internet and play the game in offline mode before account 3 fires up their game but I haven't tried this in a number of years but I believe the method should still work. Ignore this though if you are trying to keep all 3 accounts online at the same time.


text:
Q: Is there a typo in this statement on the uniqueness of maximum likelihood estimators? Working through a textbook on maximum likelihood estimation and the following is said:
"the uniqueness of the maximum likelihood estimator is not guaranteed, there may exist at least two parameter values $\hat{\theta}_1\not = \hat{\theta_2}$ with $L(\hat\theta_1)= L(\hat\theta_2)=argmax_{\theta\in{\Theta}}L(\theta)$"
Doesn't "$argmax_{\theta\in{\Theta}}L(\theta)$" represent the value that of $\theta$ that maximises $L(\theta)$, not the maximum value of $L(\theta)$


text:
Q: Which one is good to use - Zoidberg or Term::Shell ( Perl Modules ) to implement the customize shell in Perl? I am going to write the code for my own shell which has some customized commands and i want to code it in Perl. I have found two modules on CPAN which can help me for the same.
1) Term::Shell ( http://search.cpan.org/~shlomif/Term-Shell-0.06/lib/Term/Shell.pod )
2) Zoidberg ( https://metacpan.org/pod/Zoidberg )
Which module shall i use for the implementation?
Is Term::Shell older then Zoidberg and lacking features then Zoidberg?
OR is there any other module which can help me better?

A: It depends what you want.
If you want something a bit like a Unix shell, with built in commands like cd, and that will launch external programs like Firefox just by typing firefox, which you can then customize to add your own commands, then go with Zoidberg.
If you want to start with a blank slate and create your own commands so that you have a shell that just includes what you want and nothing else, then go with Term::Shell.
Personally though for the latter case, I'd use App::Cmd and write each command that I wanted my shell to support as an App::Cmd subcommand of my app. Then use an approach like this to add an interactive shell.


text:
Q: Index to scalar variable assignment in Python is not clear for a float error I am new to Python and wanted to code the VWAP Stock indicator by hand. I download a JSON over the net and then try to create the necessary placeholder arrays. Not sure what goes wrong with the totalVolume Array.
I have declared the totalVolume as Array of float. Still I get scalar error on line 81.
totalVolume[i] = volume[i] + totalVolume[i-1]
IndexError: invalid index to scalar variable.
import requests
import csv
import os
import threading
import time
import talib
import numpy
import json
from pyalgotrade.technical import vwap

exitFlag = 0

class myThread (threading.Thread):
   def __init__(self, threadID, name, counter, url):
    # Stock URL https://www.programcreek.com/python/?project_name=doncat99%2FStockRecommendSystem#
    #https://www.quantopian.com/posts/sample-talib-macd
    #https://www.daytrading.com/vwap
      threading.Thread.__init__(self)
      self.threadID = threadID
      self.name = name
      self.counter = counter
   def run(self):
      print "Starting " + self.name
      print_time(self.name, 5, self.counter)
      print "Exiting " + self.name

def print_time(threadName, counter, delay):
   while counter:
      if exitFlag:
         threadName.exit()
      time.sleep(delay)
      print "%s: %s" % (threadName, time.ctime(time.time()))
      counter -= 1

def clean(url):
    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36", "Referer": "http://example.com"}
    r = requests.get(url, headers=headers, timeout=50)
    #print(r.content)
    data  = json.loads(r.content)
    #print(data['t'])
    close = data['c']
    closeArray = numpy.array(close)
    #print(close)
    RSI = talib.RSI(closeArray, timeperiod=14)
    print(RSI[-1])
    macd, signal, hist = talib.MACD(closeArray)
    msdiff = macd[-1] - signal[-1]
    print(msdiff)
    getVWAP(data)

def getVWAP(data):
    open = numpy.array(data['o'])
    low = numpy.array(data['l'])
    high = numpy.array(data['h'])
    close = numpy.array(data['c'])
    volume = numpy.array(data['v'])
    print(len(open))
    print(len(low))
    print(len(high))
    print(len(close))
    print(len(volume))
    typicalPrice = [float]*len(open)
    VP = [float]*len(open)
    totalVP = [float]*len(open)
    VWAP = [float]*len(open)
    totalVolume = numpy.zeros(len(open))

    for i in range(0, len(open)):
        totalVolume[i] = 0
        print("A"),

    for i in range(0, len(open)):
         typicalPrice[i] = (open[i] + high[i] + low[i])/3.0
         VP[i] = volume[i] * typicalPrice[i]
         if i==0:
            totalVP[0] = VP[0]
            totalVolume = volume[0]
            VWAP[0] = typicalPrice[0]
         else:
            totalVP[i] = VP[i-1] + volume[i]
            totalVolume[i] = volume[i] + totalVolume[i-1]
            VWAP[i] = (totalVP[i])/totalVolume[i]
         print("@"),

    print("Abhi3")

# Create new threads
thread1 = myThread(1, "Thread-1", 1, "")
thread2 = myThread(2, "Thread-2", 2, "")

# Start new Threads
#thread1.start()
#thread2.start()
url1 = "https://tvc4.forexpros.com/b08251ec88a94408cab3716001818cc2/1596166039/56/56/23/history?symbol=18270&resolution=5&from=1595872548&to=1596304608"
url2 = "https://tvc4.forexpros.com/b08251ec88a94408cab3716001818cc2/1596166039/56/56/23/history?symbol=18270&resolution=5&from=1595872548&to=1596304608"
clean(url1)
clean(url2)
print talib.get_functions()

A: def getVWAP(data):
    # if data is a pandas dataframe, just use data['o'].values instead
    open = numpy.array(data['o'])
    low = numpy.array(data['l'])
    high = numpy.array(data['h'])
    close = numpy.array(data['c'])
    volume = numpy.array(data['v'])

    # it's better to use logging.debug for debug output
    print(len(open), len(low), len(high), len(close), len(volume))

    # default dtype is float, but you can be more explicit
    typicalPrice = np.zeros(len(open), dtype=float)
    # another way to improve this is to use zeros_like,
    # which will generalize beyond 1D arrays
    VP = np.zeros_like(open)
    # but actually, we don't need to initialize these arrays at all
    # because we calculate them directly (see below)

    # numpy arrays can be added/subtracted/... directly
    # it is actually quite a bit faster
    typicalPrice = (open + high + low)/3
    VP = volume * typicalPrice
    totalVolume = np.cumsum(volume)
    totalVP = np.cumsum(VP)
    VWAP = totalVP/totalVolume

    # this line is different. A typo?
    VWAP[0] = typicalPrice[0]


text:
Q: Content in single page or divide into components Suppose i want to create a page as follow in angular with requirement:
1) Each of the section will not be reused in any other page
2) If one of the api fail, the whole page will return blank with a single error message
Which approach should i choose in inplementing?
a) divide each section into components (with separate request on each component) and use the component in the page
b) put everything into single page (with parallel http request)
Or any other prefer method?

A: Since

1) Each of the section will not be reused in any other page
  2) If one
  of the api fail, the whole page will return blank with a single error
  message

The best way to do it would be

Put everything into single page (with parallel http request)

That way you avoid all the parent-child component communication in case any of the requests fail, and you can handle the status of the entire page in a single place. And also since the requests are going to be sent in a parallel way, doing this won't affect the loading time of the page either.
Note: The only scenario where creating several child components would be still recommended is if each component has a lot of complex logic/calculations. In that case, it'd be better to split the logic and put each piece of it only where it's needed (instead of having a page with several hundreds of lines of code).


text:
Q: JFlex + byaccj exercise's not working correctly First of all, sorry for my bad English but I'm not native.
I'm studying jflex and byaccj at university and I've done a simple exercise to learn how things work.
I've a test.xml file like this:
<collezione_film><film></film></collezione_film>

My exercise.flex is
%%
%byaccj

%{

 private Parser yyparser;
 public Yylex(java.io.Reader r, Parser yyparser) {
   this(r);
   this.yyparser = yyparser;
 }
%}

%x IN_GROUP IN_PROPERTY

%state COLLEZIONE_FILM

TAG_COLLEZIONE_FILM_START = <collezione_film>
TAG_FILM_OPEN_START = <film+[ \t]
%%

<YYINITIAL> {
  {TAG_COLLEZIONE_FILM_START} {
    yyparser.yylval = new ParserVal("collezione_film");
    yybegin(COLLEZIONE_FILM);
    return Parser.TAG_START;
  }
  [^] { /* Non fare nulla */ }
}

<COLLEZIONE_FILM> {
  {TAG_FILM_OPEN_START} {
    yyparser.yylval = new ParserVal("film");
    return Parser.TAG_START;
  }
  [^] { /* Non fare nulla */ }
}

and my exercise.y is
%token<sval> TAG_START
%type<sval> tags

%%

config :    tags { System.out.print($1); }

tags :      TAG_START tags {
                $$ = $1 + " " + $2;
            }
            | TAG_START { $$ = $1; }
            ;

%%

private Yylex lexer;
private int yylex () {
  int yyl_return = -1;
  try {
    yylval = new ParserVal(0);
    yyl_return = lexer.yylex();
  }
  catch (java.io.IOException e) {
    System.err.println("IO error :"+e);
  }
  return yyl_return;
}

public void yyerror (String error) {
  System.err.println ("Error: " + error);
}

public Parser(java.io.Reader r) {
  lexer = new Yylex(r, this);
}

public static void main(String args[]) throws java.io.IOException {
  Parser yyparser;
  if ( args.length > 0 ) {
    yyparser = new Parser(new java.io.FileReader(args[0]));
    yyparser.yyparse();
  }
  else {
    System.out.println("Nessun file specificato.");
  }
}

I understand that you can't use this code to a more general example, but my question is: Why the parser in this particular example (see test.xml) prints only "collezione_film" and not "collezione_film film"? What I'm missing?


text:
Q: Is there a way to download C files/project from embedded system I am asking this question in a hope that someone might have done this before.I want to download software from embedded system so that modification can be done in the software.
Is it possible to do and how?
Information I have for the system is :
Platform :  iMX7 ARM
Thank you

A: Since the job of a C compiler is to translate source code to machine code assembler before the program is downloaded in a microcontroller, then no, you cannot upload C code from it.
Also, for the past 20 years or so, "copycat" read protection of microcontrollers has been a standard feature. Meaning an on-chip hardware restriction that forces you to erase the flash before you can access it. So it might even be impossible to upload the raw assembler.
In case the MCU isn't protected and you have the original debugger files corresponding to the code downloaded, then decent debuggers can connect to the existing program "on the fly" and then view it together with the C source, without re-programming anything. (This is useful for investigating NVM changes and memory corruption.) But again, you would need access to the original files.


text:
Q: Google sheets - on clicking a tab/sheet trigger a action In Google sheets, I have multiple sheets/tab in one spreadsheet file.  I want to trigger a action when I switch from one tab to another i.e. when I click on the tab name / sheet name. Is this possible?

A: I'm looking for the same solution. The only answer I've come up with is to hide all sheets but one and force the user to click a button to select a sheet to be unhidden, afterwhich the current sheet is hidden.


text:
Q: Sqoop-Job Command Fails when Try to Connect to SQL Server while Sqoop-Import does not I am trying to create and execute a sqoop job to get data from a SQLSERVER and import it into Hive, but the command fails in the authentication process. However if I execute the exactly same command by using sqoop import it does work.
What am I doing wrong?
Please, consider the example:
$CONNECTION_CFG_DATABASE_USERNAME and $CONNECTION_CFG_DATABASE_PASSWD are 'admin'

"sqoop job --create $EXTRACTION_NAME -- import --connect '$CONNECTION_CFG_PREFIX_QUERY_STRING$CONNECTION_CFG_DATABASE_IP:$CONNECTION_CFG_SQLSERVER_
PORT;database=$CONNECTION_CFG_DATABASE_NAME' --username $CONNECTION_CFG_DATABASE_USERNAME --password $CONNECTION_CFG_DATABASE_PASSWD --table $CONNECTION_CFG_HIVE_TABLE_
NAME --target-dir $EXTRACTION_TARGET_DIR/$ID --hive-import --hive-database $CONNECTION_CFG_DATABASE_NAME --hive-table $CONNECTION_CFG_HIVE_TABLE_NAME --hive-partition-k
ey $HIVE_TABLE_PARTITION_KEY --hive-partition-value $ID -m $SQOOP_PARALLELISM --check-column $INCREMENTAL_FIELD --incremental lastmodified"

This above one fails. I get the following output:

ERROR manager.SqlManager: Error executing statement: com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'admin'. ClientConnectionId:25424a39-dd01-4439-bfc6-d7ef21c8b1a0

However, this one below works!

"sqoop --import --connect '$CONNECTION_CFG_PREFIX_QUERY_STRING$CONNECTION_CFG_DATABASE_IP:$CONNECTION_CFG_SQLSERVER_PORT;database=$CONNECTION_CFG_DATABASE_NAME' --username $CONNECTION_CFG_DATABASE_USERNAME --password $CONNECTION_CFG_DATABASE_PASSWD --table $CONNECTION_CFG_HIVE_TABLE_NAME --target-dir $EXTRACTION_TARGET_DIR/$ID --hive-import --hive-database $CONNECTION_CFG_DATABASE_NAME --hive-table $CONNECTION_CFG_HIVE_TABLE_NAME --hive-partition-key $HIVE_TABLE_PARTITION_KEY --hive-partition-value $ID -m $SQOOP_PARALLELISM --check-column $INCREMENTAL_FIELD --incremental lastmodified"

I need to use sqoop job since I do not know the value of last-value parameter and I would like to sqoop handle it automatically for me.
Any help would be really appreciated.


text:
Q: How to fall back to log4j2.xml when custom configurationFile is missing My environment : JBoss EAP 7 with a "log4j2.xml" in classpath (historic behavior).
I would like to introduce a way to have a (non mandatory) custom log4j2 configuration file (per EAR application) but still use (fall back) to (existing) "log4j2.xml" if the custom configuration file is missing.
To me, the only way to accomplish this was to use composite configuration by using "log4j2.configurationFile" property (within log4j2.component.properties) and set both the "log4j2.xml" and the custom configuration filename (separated by a comma).
But if the custom file is missing, even the generic "log4j2.xml" is ignored.
When looking at log4j2 (v2.12.1) code (https://github.com/apache/logging-log4j2/blob/log4j-2.12.1/log4j-core/src/main/java/org/apache/logging/log4j/core/config/ConfigurationFactory.java#L380) I can see that indeed if one config file is missing, none config file (of the list) is used (-> "return null")
Is there a way to accomplish the behavior I want?
Thanks


text:
Q: Vertica 6.1: vsql creashes with large resultset I'm writing a script to export data from our Vertica cluster.
The command I'm using is:
vsql MY_DB_NAME -At -F$'\t' -o /data/vertica_archive/MY_DATA_2015_07_01.tsv  -c "select * from DATA_TABLE where ts_date ='2015-07-01';"

Sporadically resulting with:
server closed the connection unexpectedly
        This probably means the server terminated abnormally
        before or while processing the request.
connection to server was lost

All of our queries are simple "select * from TABLE where ts_date=DATE", but some of the queries result-set will generate a 10GB files.
Example row count:
MY_DB=> select count(*) from DATA_TABLE where ts_date ='2015-07-01';
  count
----------
 18213295
(1 row)

Is there any exit code documentation or can any one suggest how to debug?

A: Without knowing your environment, there are a couple things you can try. The first being adding an additional filter to make the output file smaller. The other is using a pipe viewer to monitor the progress.
If you're using the enterprise edition, you should report the issue to support.

A: Take a look at the RUNTIMECAP or QUEUETIMEOUT of the resource pool used for this query.
 I do hope you are doing this locally on the server and then copy them out of your server.
 Try to zip before moving it.
See example:
vsql -U dbadmin -w dbadmin -F $'|' -At -c "SELECT * FROM table" | gzip -c > '/vertica/backup_table_one.gz'

You will save bandwidth and time as well.


text:
Q: using page-object-gem obtain count of nested elements What is the most efficient way to obtain a count of nested elements using the page-object-gem
Given some sample HTML

Review

Assign

Retrieve

Where we have our page-object defined as
class MyPage
  include  PageObject

  unordered_list(:steps, :id => 'templateFields')
end

Looking for the count of the nested ordered_list elements?

A: An unordered list element has a list_items method that returns its li elements. You could count how many elements are returned:
page.steps_element.list_items.count
#=> 3

If you do this frequently, you may be better of defining an accessor for the list items themselves.
class MyPage
  include PageObject

  unordered_list(:steps, :id => 'templateFields')
  list_items(:step_item, :css => '#templateFields li')
end

Then you would simpliy call:
page.step_item_elements.count
#=> 3


text:
Q: How does "cat" handle large files when used as part of a pipe? Suppose I cat a file having size of say 10 GB, and I pipe that to head,  would cat work if my system only has 2 GB of RAM and 1 GB of swap space?  I want to know the internal details.

A: cat doesn't need to remember any parts of the file that it has already sent along from its input to its output. In other words, it uses O(1) memory.
head also doesn't need to remember parts of the file it has already sent along, it only needs to count them. Furthermore, it doesn't even need to read the whole of its input; it can stop when it reaches the amount of lines requested on output.


text:
Q: Android - Programmatically adding button, setting ID crashes I am programmatically adding x amount of buttons to my view depending on a config loaded (lets just use 10 for an example). I create the 10 just fine, and it works when I don't set an ID, or when I use Androids generateId() function, but I want to use my iterator (i) to set the id, so that each value of the iteration matches the button it creates
i.e.
(for i=0; i<10; i++)
{
     button.setId(i);
 }

I want this so that when I switch fragments, it saves the buttons and I don't recreate them with onCreate. As it stands, I get this error:
 01-25 17:46:18.197  13236-13236/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.ClassCastException: android.view.AbsSavedState$1 cannot be cast to android.widget.CompoundButton$SavedState
        at android.widget.CompoundButton.onRestoreInstanceState(CompoundButton.java:379)

A: You can use generateViewId within your for and create a method to get your buttons from an ArrayList.
Try this:
public class YourClass {

    public ArrayList<Integer> ids = new ArrayList<>();

    public void generateButtons(){
        for (int i = 0; i< 10; i++) {
            ids.add(View.generateViewId());
            // your code to create the button
            button.setId(ids.get(i));
        }
    }

    public Button getButton(int index){
        return (Button) findViewById(ids.get(index));
    }

}

Or just create an ArrayList of buttons...


text:
Q: OpenCL clCreateFromGLTexture using a different texture target The aim of my project is to get live camera feed from on an Android device, use OpenCL to perform real-time filtering on those images and render the output on display.
I aim to do this in real-time that's why I am using OpenCL-OpenGL interop.
I have successfully managed to create a shared context using EGLContext and EGLDisplay. Now I am trying to use clCreateFromGLTexture so I can access these images in OpenCL kernel. The problem however is android requires that when bind the texture the target must be GL_TEXTURE_EXTERNAL_OES as it says here: (http://developer.android.com/reference/android/graphics/SurfaceTexture.html), however this texture target is not valid texture target when using clCreateFromGLTexture (https://www.khronos.org/registry/cl/sdk/1.1/docs/man/xhtml/clCreateFromGLTexture2D.html).
So I am not sure how to go about this.
This is how I create a GL Texture in android:
    GLES20.glGenTextures(1, texture_id, 0);
    GLES20.glBindTexture(texture_target, texture_target);

and this is how I am trying to create a cl memory object:
    glTexImage2D(texture_target, 0, GL_RGBA, 640, 480, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
    cl_mem camera_image = clCreateFromGLTexture(m_context, CL_MEM_READ_WRITE, texture_target, 0, texture_id, &err);

The error I get when I try to create cl memory object from GL texture is CL_INVALID_VALUE.
I am pretty new to OpenGL so there could be something basic I might have over looked.

A: The texture you receive from the camera is not the usual texture you'd expect. You even have to specify the extension in a shader if you read from it.
You need to perform an additional copy from the GL_TEXTURE_EXTERNAL_OES target to another texture which is created in the usual way. With luck you can bind both of them into fbo's and then just issue blit. If that doesn't work you can always use the normal texture as a rendertarget and simply draw a quad textured with the camera image.


text:
Q: Zero'ing an array before adding an entry Does the following zero out a list and then add the first entry? Or does it just add the first entry to handlers?
 Logger = (struct logger) {.level=INFO, .format=DEFAULT_FORMAT, .num_handlers=1, .handlers[0]=stdout};

For example, does this do:
Logger.handlers = {0};
Logger.handlers[0] = stdout;

Or is there no clearing involved?

A:
For example, does this do:
Logger.handlers = {0};
Logger.handlers[0] = stdout;

Answer: Yes (but not specifically in that order)
There are three standard sections (actually 4 if you take the section that specifically makes the following two applicable to "aggregate objects" (struct and arrays)) under the section C11 Standard § 6.7.9 - Initialization. Your case asks "What happens to the other elements of Logger.handlers if only Logger.handlers[0] = stdout; is provided a value during initialization?"
To answer that question, you need to look at § 6.7.9 Initialization (p19) and § 6.7.9 Initialization (p21)
The first specifies how initialization of structs occurs in "list order" and that "all subobjects that are not initialized explicitly shall be initialized implicitly the same as objects that have static storage duration." So if you provide fewer than all values to fully initialize a subobject, those not provided a value are initialized as if they have static storage duration. (objects with static storage duration, not explicitly initialized, are initialized to zero (or NULL, as appropriate for type), See: § 6.7.9 Initialization (p10))
Paragraph 21 specifically covers your case where fewer initializers are provided within a brace enclosed list -- "all subobjects that are not initialized explicitly shall be initialized implicitly the same as objects that have static storage duration." § 6.7.9 Initialization (p21)
So putting it altogether, what actually happens for the initialization of Logger.handlers is the first element is initialized to stdout and that all other elements are initialized NULL (since stdout is a pointer of type FILE*). So what you would actually have is:
Logger.handlers[CONST] = { stdout, NULL, NULL, ... };

Look things over (read all of § 6.7.9), and let me know if you have further questions.

A: The latter Logger.handlers[0] = stdout;.  This is why the API has a .num_handlers field to tell called code know how many of the handlers are valid.


text:
Q: How to get certain data from custom rich text field There is the following custom field called Url__c of type Account I am using and the data added to the field is mainly urls and websites.
The problem is that the field is rich text and the data entered in the field Url__c is not the proper format.
What I mean by not a proper format is:

    https://www.merchant.com/store

Account

I'll need your advise what can be done in order to be able to get the urls in the proper format.
What I would like to know is how to get beginning and the end of the url.
For instance I need to get either the 'http', 'https' or 'www' and the end of the url.
The end of the url turned out to be more difficutl to get because in table Account in the field Url__c is rich text and for the added text there is no certain criterium on how to know for certain where the ulr will fininsh.
Therfore I've decided to use regular expressions which should give me the url of the added text.
The other solution to the problem is to change the field type from rich text to url but the problem is that the url field type is restricted
in terms of characters or symbols and it does not allow to enter many web adresses.
Could you please advise an appropriate approach on how to get the urls out the added text in the Url__c field
Have you used similar approach with regular expressions and if you have could you please send examples.
Regards,
Dilyan

A: Regular expression to get all urls
(?:(?:(?:[a-z]{3,9}:(?://)?)(?:[-;:&=+$,w]+@)?[a-z0-9.-]+|(?:www.|[-;:&=+$??,w]+@)[a-z0-9.-]+)((?:/[+~%/.w-]*)?\\??(?:[-+=&;%@.w]*)#?w*)?)

Option 1

https://www.merchant.com/store

Account

Use string stripHtmlTags(htmlInput) method
List<Account> lst = [SELECT Id, Url__c FROM Account WHERE Url__c != null];

for(Account obj: lst)
{
   obj.Url__c = obj.Url__c.stripHtmlTags();
}

update lst;

This will remove all the html and return only content
Output

https://www.merchant.com/store
Account

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_string.htm#apex_System_String_stripHtmlTags

Option 2
What you can do query all the accounts with Url__c
List<Account> lst = [SELECT Id, Url__c FROM Account WHERE Url__c != null];

for(Account obj: lst)
{
   obj.Url__c = obj.Url__c.unescapeHtml4();
}

update lst;

Run this code from developer console.This will make you rich text area well formatted.
Output:

https://www.merchant.com/store
Account

here Account will display as link


text:
Q: how to debug curl call to amazon s3 when it get stuck I'm using the PHP S3 class and this backup script to backup ~500Mb file from Linux server to S3. The call to s3 gets stuck (never returns) and top shows httpd process which consumes 100% CPU and 1% memory. smaller files do get copied correctly.
my question is how can I debug this (its basically a CURL call done by the S3 class) when nothing is returned and the code gets stuck indefinitely.
Additionaly, any ideas on how to solve the issue in general are very appreciated.
Things I tried so far- no timeout for the php script. Removed SSL support from the call to S3, enabled 128M memory for the script.

A: You probably need to alter the S3 script directly to find out which step is failing, and probably set some additional curl options from this page.  Some likely settings to look at are:

*

*CURLOPT_CONNECTTIMEOUT

*CURLOPT_LOW_SPEED_LIMIT

*CURLOPT_LOW_SPEED_TIME

The last two work together to specify when to give up the curl request, the first is just when making the initial connection.
For debug output from curl itself, you can set CURLOPT_VERBOSE and assign a file to CURLOPT_STDERR to capture the output.  This should help track down what the problem is.


text:
Q: Android - "reuse" TCP Client? I want my android client to connect on startup, and then use the same TCP connection to send and receive data every few seconds. How do I do this?
I tried declaring a global socket and using an AsyncTask to send data every second. I checked my server and the client only sent a single message.


text:
Q: Assign column name based on key in preceding column I am importing a data set from a csv
the top two lines are key value pairs

UTC
BSP
AWA
TWA

1.
2.
3.
4.

Then the data below this has a column containing the value and then the corresponding data. for example

1
41223
2
0
3
045
4
026

1
41224
2
0
3
052
4
035

1
41225
2
0
3
087
4
040

1
41226
2
0
3
023
4
041

2
0
3
052
4
082

I want it to become

UTC
BSP
AWA
TWA

41223
0
045
026

I tried putting the key value pairs in a list
test <- read.csv("my.csv",
                  nrows=2, header=FALSE)
key <- as.character(test[1,])
value <- as.numeric(test[2,])

mylist <- list()
for(i in 1:length(key)){
  mylist[key[i]] <- value[i]
}

And then I was trying to match or reference the previous column with the values in the list.  I have not managed to do.
Any help much appreciated
Thanks


text:
Q: Inline SELECT within CTE inside VIEW that uses a table from the VIEW Hi I want to create a VIEW, with CTE inside, here is my original query (much simplified):
SELECT  ISNULL(( SELECT col_a
                 FROM   Table_A a
                 WHERE  a.id = b.id
               ), 'N/A') ,
        b.*
FROM    Table_B b

If I want to turn that into a VIEW with CTE, I received the error saying The multi-part identifier "b.id" could not be bound.
Here is what I have tried
CREATE VIEW my_view
AS
    WITH    my_CTE
              AS ( SELECT   ISNULL(( SELECT col_a
                                     FROM   Table_A a
                                     WHERE  a.id = b.id
                                   ), 'N/A') my_col
                 )
    SELECT  ( SELECT    *
              FROM      my_CTE
            ) CTE_col ,
            b.*
    FROM    Table_B b

Notice that the requirement is to have ISNULL go inside the CTE, but that means a.id is an inline query inside CTE, which means I can't do a WHERE clause inside the SELECT of the view.

A: This is the query:
WITH my_CTE AS (
      SELECT ISNULL((SELECT col_a
                     FROM Table_A a
                     WHERE a.id = b.id
                    ), 'N/A'
                   ) my_col
     )
SELECT (SELECT * FROM my_CTE) CTE_col, b.*
FROM Table_B b;

The CTE references b in the subquery.  It is not defined at that point.  You cannot split off a correlated subquery in a CTE.
You might be able to do what you want with cross apply:
SELECT my_CTE.my_col CTE_col, b.*
FROM Table_B b CROSS APPLY
     (SELECT ISNULL((SELECT col_a
                     FROM Table_A a
                     WHERE a.id = b.id
                    ), 'N/A'
                   ) my_col
     ) my_CTE

There are other ways to simplify your specific query, but this might solve your larger problem.

A: I would remove the WHERE clause inside the CTE and join then the CTE and your Table_B together. It should look like this:
CREATE VIEW my_view
AS
    WITH    my_CTE
              AS ( SELECT   my_col = ISNULL(col_a, 'N/A') ,
                            a.id
                   FROM     Table_A a
                 )
    SELECT  CTE_col = my_CTE.my_col ,
            b.*
    FROM    Table_B b
            JOIN my_CTE ON b.id = my_CTE.id

EDIT:
I have never worked with FOR XML PATH so far, so I´m not certain if this is what you want.
Here is a CTE for joining the two tables and a CTE just for the XML.
Maybe the JOIN needs to be a LEFT JOIN but that depends on your data.
If Table_A always has corresponding IDs and col_a is just nullable, the INNER JOIN is sufficient.
If you want to display N/A for a not existing record in Table_A you will need a LEFT JOIN.
CREATE VIEW my_view
AS
    WITH    my_CTE
              AS ( SELECT   my_col = ISNULL(a.col_a, 'N/A') ,
                            b.*
                   FROM     Table_A a
                            INNER JOIN Table_B b ON a.id = b.id
                 ),
            xml_cte
              AS ( SELECT   my_col
                   FROM     my_CTE
                   FOR      XML PATH
                 )
    SELECT  *
    FROM    my_CTE

A: Alternative:
(The code below is complete. Had posting issues similar to discussion in comments of https://meta.stackexchange.com/q/185681. I actually cannot post the answer without leaving this SO link in the text. ??? I apologize.)
WITH my_CTE(b_id, col_A) AS
(
          SELECT b.id, ISNULL(a.col_a, 'N/A')
            FROM Table_B b
 LEFT OUTER JOIN Table_A a ON b.id = a.id
)
        SELECT my_CTE.col_A, b.*
          FROM Table_B b
    INNER JOIN my_CTE ON b.id = my_CTE.b_id


text:
Q: What is the meaning of "unchanged to" in the sentence? I could not figure out what the meaning of the sentence?

In this case, the analysis applies unchanged to the worst-case ratios of the lengths of shortest grid paths and shortest paths.

what is the meaning of "applies unchanged to"?

A: Here's a rewrite that should clarify the meaning:

In this case, the same analysis could be applied to the worst-case
  ratios of the lengths of shortest grid paths and shortest paths.


text:
Q: android api call return simple array i am calling an api which should return an array of length between 0 to 9. Now i am not understanding how to get that array. for getting simple string other api's
My code is:are working fine according to this code.
private String test(String url)
{
    String str = null;
    int c;
    try
    {
    URL hp = new URL(url);  //The String hp1 is passed in URL

    URLConnection hpCon = hp.openConnection();
    hpCon.setUseCaches(false);
    hpCon.setConnectTimeout(10000);
    System.out.println("*url content for: " + url);
    InputStream input=hpCon.getInputStream();
    StringBuffer sb = new StringBuffer();

    while(((c=input.read())!= -1))
    {
        sb.append((char)c);
    }
    str=sb.toString();
    sb = null;
    //System.out.print(str);

    input.close();
    input = null;
    hpCon = null;
    hp = null;
    }
    catch(Exception e)
    {

    }
    return str;
}


text:
Q: Обновление данных в MSSQL Есть данные в иерархическом виде- индексы файлов и папок. Нужно создать хранимую процедуру для обновления. То есть, просматриваем ФС на предмет изменений. Есть файл- проверить, что он есть и в базе. Если отсутствует в базе, но есть в ФС - добавить в базу. Если есть в БД, но отсутствует в ФС- удалить соответствующую запись из БД.
Мне сказали, что эту процедуру лучше реализовать с помошью триггеров. Действительно ли лучше?
Если кто-то сталкивался с подобной ситуацией- то отправьте на нужный ресурс, пожалуйста.
A: По опыту работы могу посоветовать на выбор пару технологий автоматизации.

*

*Использовать SSIS. Достаточно легко работать с ФС, ещё легче с БД. Но возможно, чтобы докрутить нужный функционал, придется использовать сторонние разработки, которые позволяют следить за изменениями в ФС. Например: SQLIS File Watcher Task.

*Написать небольшую утилитку (а может даже windows-сервис), который будет следить за изменениями ФС. Делается это с помощью подписывания на события файловой системы с помощью: FileSystemWatcher
Если же вы хотите реализовать всё только с помощью MSSQL, то вам может помочь SQL Agent, который будет запускать задачу по расписанию. А в задачу вы можете впихнуть, например, хранимую процедуру. У SQL Server есть недокументированные функции: xp_subdirs и xp_dirtree.
Используйте первую, чтобы получить список всех поддиректорий указанной директории, например, так:
EXEC master..xp_subdirs 'C:\\'

Используйте вторую, чтобы получить список всех директории рекурсивно, а также глубину вложенности.
EXEC master..xp_dirtree 'C:\\'

Чтобы получить список файлов в папке, уже придется обращаться с командной строке с помощью другой функции xp_cmdshell:
EXEC master..xp_cmdshell 'DIR /b C:\'

Проверка на наличие файла в ФС:
EXEC Master.dbo.xp_fileexist 'C:\boot.ini'

Вот, пожалуйста, ещё материалы для размышления, вариант - только T-SQL:

*

*Stored procedures to retrieve directory listing – Undocumented XPs

*List Directories and Files using T-SQL

*Get list of files in directory using a SP


text:
Q: Get the first key element out of an associative multidimensional array in PHP $json = '{
    "currency": {
        "19:15": {
            "1": "1.20585"
        },
        "19:14": {
            "1": "1.22585"
        }
    }
}';

I want to retrieve value "1.20585" out of this array in PHP.
The time "19:15" changes every minute, but I want always the upper first one (most recent).
$array["currency"][0]["1"] didn't solve it for me. Does someone know one-line solution that will retrieve the value?


text:
Q: Flutter FAILURE: Build failed with an exception Keystore file not set i just signed my app and created a key. Now when I run flutter build apk or flutter build appbundle then I run into this failure:
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:validateSigningRelease'.
> Keystore file not set for signing config release
> Keystore file not set for signing config release

What can I do to avoid this?

A: To sign your App after creating a key you have to reference the key in a keys.properties file. You also after to add some reference at the build.gradle file located at [project_dir]/android/app/. Try following the steps described in this article from flutter.dev; https://flutter.dev/docs/deployment/android duly and  you should be able to build a release for your app afterwards.


text:
Q: How to interpret auto.arima() output from R? auto.arima(ldeaths)
Here is the output I got from R, but I am not sure how to read ARIMA(1,0,0)(2,0,0)[12]. What does it mean? How to put ar1, sar1, and sar2 into a model?
Series: ldeaths
ARIMA(1,0,0)(2,0,0)[12] with non-zero mean

Coefficients:
         ar1    sar1    sar2  intercept
      0.4418  0.3098  0.5078  2058.2234
s.e.  0.1345  0.0973  0.0998   175.8665

Ok the data came from R. ldeaths...and I just analyzed it.

A: You have an implied loss of $12+12+1 =25$ starting values. This is indeed a very unusual model and sets a red flag for me. Why don't you post your data in a column oriented csv file. All ARIMA model can be expressed as a weighted average of the past which goes a long way (pun) to "explain" the model and it's implications for the future.


text:
Q: Qualified Col Names Error in bq command line I ran a script via bq command line and got this response (all col. names are fully qualified)
job_134e61cebe274ba4ab73dd6b22a2f38a
Unable to determine schema of SELECT * in this query. Please list column names explicitly.
Exact same request pasted to web UI worked fine.
Thanks!

A: Looking at your query, it appears that the query parser is having trouble computing the column names needed in the query. One suggestion is to take the tables on the right side of the join operations (periods, location, item) and wrap the table name in a subselect with exactly the fields you need -- e.g.
change LEFT OUTER JOIN item to LEFT OUTER JOIN (SELECT a, b, c FROM item).
Let me know if this workaround works for you. I'll file an internal bug to track this.


text:
Q: Is there any documentation for smalltalk language? I was looking for smalltalk documentation to learn about its features and design not syntax, I just want to know the general features of this language and its design. like Message passing, Dynamic and strong typing, Reflection, Object-orientation....., thanks.

A: If you searched a little longer you could have found this question...
Within that question there are many links to different documentation/tuts in which you may find helpful.


text:
Q: Filter constructor injection using Ninject I am trying to find a way to use Ninject to inject constructor dependencies into filters. I am finding many articles describing property injection which is now advised against, but the remainder of articles involve complex setups with factories, locators, global wrappers or stub attributes.
With MVC allowing you to override almost any part of it's operation I would have thought it would be simply a case of creating your own filter provider in a similar fashion to how you create your own dependency resolver.
What is the now correct way to allow injection, or does it become easier if you use certain types of filters vs others?
 public class UserValidationAttribute : ActionFilterAttribute
 {
    private IRepository repository;

    public UserValidationAttribute(IRepository repository)
    {
        this.repository = repository;
    }
}

A: Assuming that the attribute is to be a part of the metadata, which means that it should be instantiated at the compile time, it is not possible to have a repository injected into an attribute by any ioc container. Containers operate in run time.

A: There is a way to use constructor injection.
First you replace your attribute with an 'empty' one which you will just use as a marker
public class UserValidationAttribute : Attribute { }

Then you create a filter class as an IActionFilter.
public class UserValidationFilter : IActionFilter
{
    private readonly IRepository repository;

    public UserValidationFilter(IRepository repository)
    {
        this.repository = repository;
    }

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //do something
    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        //do something
    }
}

Then you can register it with something like
private static void RegisterServices(IKernel kernel)
{
    kernel.BindFilter<UserValidationFilter>(FilterScope.Action, 0)
        .WhenActionMethodHas<UserValidationAttribute>();
}

If your attribute itself has constructor parameters, you can pass them in like
kernel.BindFilter<UserValidationFilter>(FilterScope.Action, 0)
    .WhenActionMethodHas<UserValidationAttribute>();
    .WithConstructorArgumentFromActionAttribute<UserValidationAttribute>("myParameter", attr => attr.MyParameter);

The BindFilter syntax is part of Ninject.Web.Mvc.FilterBindingSyntax.

A: If you want to inject dependencies to a filer, you want to use property injection instead of constructor injection.
public class UserValidationAttribute : ActionFilterAttribute
{
    [Inject]
    private IRepository repository { get; set; }

    public UserValidationAttribute()
    {
    }
}

https://stackoverflow.com/a/7192754/296861


text:
Q: lbl: break lbl; in JavaScript Apparently, lbl: break lbl; is perfectly valid in JavaScript (but not lbl: continue lbl;).
Is there any obscure use for this construct?

A: You can put a label before any statment. continue is only allowed inside loops (for, for-in, while, do-while) as already said by boltclock in the comments to the question. break can be used inside loops, switch-statements, and any statement (as already commented by rob-w).
lbl: break lbl;

The above statement is valid. As already commented by frederic-hamidi "it breaks out of itself" and isn't very useful by itself, but see example below of how it could be useful.
lbl: continue lbl;

The above statement is invalid because it isn't a loop.
An example of how break label could be used in a block:
function test() {
  var x='';
  lb1: {
    x+='1';
    if(x.length >2) break lb1;
    x+='2';
  }
  lb2: {
    x+='3';
    if(x.length >2) break lb2; //Can't break to lb1 because it isn't inside this block
    x+='4';
  }
  console.log(x);
}

test();

Outputs:

123

This is an example of how break label could be used inside a loop:
outer: for(var idxo=0; idxo < 5;++idxo) {
  inner: for(var idxi=0; idxi < 5;++idxi) {
    if (idxi==3) break outer;
    console.log(idxo,idxi);
  }
}

Outputs:

0 0, 0 1, 0 2

This is an example of how continue label could be used inside a loop:
outer: for(var idxo=0; idxo < 5;++idxo) {
  inner: for(var idxi=0; idxi < 5;++idxi) {
    if (idxi==3) continue outer;
    console.log(idxo,idxi);
  }
}

Outputs:

0 0, 0 1, 0 2, 1 0, 1 1, 1 2, 2 0, 2 1, 2 2, 3 0, 3 1, 3 2, 4 0, 4 1, 4 2

ECMA262:5 12.12

12.12 Labelled Statements
Syntax
LabelledStatement :
Identifier : Statement
Semantics
A Statement may be prefixed by a label. Labelled statements are only used in conjunction with labelled break and continue statements. ECMAScript has no goto statement.
An ECMAScript program is considered syntactically incorrect if it contains a LabelledStatement that is enclosed by a LabelledStatement with the same Identifier as label. This does not apply to labels appearing within the body of a FunctionDeclaration that is nested, directly or indirectly, within a labelled statement.
The production Identifier : Statement is evaluated by adding Identifier to the label set of Statement and then evaluating Statement. If the LabelledStatement itself has a non-empty label set, these labels are also added to the label set of Statement before evaluating it. If the result of evaluating Statement is (break, V, L) where L is equal to Identifier, the production results in (normal, V, empty).
Prior to the evaluation of a LabelledStatement, the contained Statement is regarded as possessing an empty label set, unless it is an IterationStatement or a SwitchStatement, in which case it is regarded as possessing a label set consisting of the single element, empty.


text:
Q: Building dynamic Aggregation query based on user input in elasticsearch I want to build aggregation query dynamically based on the user input(may be terms, nested, filters).
input is:
{
    "search": [

{

            "aggr": "terms",
            "field": "team",
            "filterFields": []

},

        {
            "aggr": "nested",
            "field": "stage_test.sutname",
            "filterFields": []
        },

        {
            "aggr": "sum",
            "field": "stage_test.stage_run_time"
        }
    ]
}

I want each objects in this list as a sub aggregation in order
I am Parsing this list  and inside a for loop am building the query:
for (SearchData data : searchInput.getSearch()) {
            System.out.println(data.getField());
            System.out.println(data.getAggr());
            if (termsBuilder != null) {

                 if(data.getAggr().equalsIgnoreCase("sum")){
                    termsBuilder = termsBuilder.subAggregation(AggregationBuilders.sum("sum").field(data.getField()));
                }
                else if(data.getAggr().equalsIgnoreCase("nested")){
                    termsBuilder = termsBuilder.subAggregation(AggregationBuilders.nested(data.getAggr()).path(data.getField())
                            .subAggregation(AggregationBuilders.terms(data.getField()).field(data.getField())));
                    System.out.println(XContentHelper.toString(termsBuilder));
                }
            }
            else {
                if(data.getAggr().equalsIgnoreCase("terms"))
                {
                    if(data.getFilterFields().size() == 0){
                        termsBuilder =  AggregationBuilders.terms(data.getField()).field(data.getField())
                                .size(0);
                    }
                    else{
                        String includeinput[] = new String[data.getFilterFields().size()];
                        includeinput = data.getFilterFields().toArray(includeinput);
                        termsBuilder =  AggregationBuilders.terms(data.getField()).field(data.getField())
                                .include(includeinput).size(0);
                    }

                }

            }
        }

I tried to print the query builded:
{

  "team" : {

    "terms" : {

      "field" : "team",
      "size" : 0
    },
    "aggregations" : {
      "nested" : {
        "nested" : {
          "path" : "stage_test.sutname"
        },
        "aggregations" : {
          "stage_test.sutname" : {
            "terms" : {
              "field" : "stage_test.sutname"
            }
          }
        }
      },
      "sum" : {
        "sum" : {
          "field" : "stage_test.stage_run_time"
        }
      }
    }
  }
}

As in query the last part (i.e.. sum) I wanted that as sub aggregation but it came out of aggregation


text:
Q: Spring Boot application failing on AutoConfigurationImportFilter not being able to be built but no class specified So I go to start my app and it gives me this error:
java.lang.IllegalArgumentException: Unable to instantiate factory class: org.springframework.boot.autoconfigure.AutoConfigurationImportFilter
at org.springframework.core.io.support.SpringFactoriesLoader.instantiateFactory(SpringFactoriesLoader.java:167)
at org.springframework.core.io.support.SpringFactoriesLoader.loadFactories(SpringFactoriesLoader.java:104)
at org.springframework.boot.autoconfigure.AutoConfigurationImportSelector.getAutoConfigurationImportFilters(AutoConfigurationImportSelector.java:266)
at org.springframework.boot.autoconfigure.AutoConfigurationImportSelector.filter(AutoConfigurationImportSelector.java:237)
at org.springframework.boot.autoconfigure.AutoConfigurationImportSelector.selectImports(AutoConfigurationImportSelector.java:102)
at org.springframework.boot.autoconfigure.AutoConfigurationImportSelector$AutoConfigurationGroup.process(AutoConfigurationImportSelector.java:386)
at org.springframework.context.annotation.ConfigurationClassParser$DeferredImportSelectorGrouping.getImports(ConfigurationClassParser.java:828)
at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:563)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:188)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:316)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:233)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:271)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:91)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:692)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:530)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:386)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:307)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1242)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1230)
at com.bayer.aws.agent.GeneEditBarcodeAgentApplication.main(GeneEditBarcodeAgentApplication.java:12)
Caused by: java.lang.IllegalArgumentException: Class [org.springframework.boot.autoconfigure.condition.OnBeanCondition] is not assignable to [org.springframework.boot.autoconfigure.AutoConfigurationImportFilter]
at org.springframework.core.io.support.SpringFactoriesLoader.instantiateFactory(SpringFactoriesLoader.java:162)
... 20 common frames omitted

It's not specifying what class it's failing to build however and I've got beans for all the classes that spring would try to build so I'm just confused on how to figure out what class it's missing. I really don't want to build beans for all of the classes in my apps. (like my models and controllers) Does anyone know how to go about finding out what class spring is unable to build? I can post up some of my code here but I have to be careful as this is for work so I will post up code by request for anyone that needs to see something. Thanks so much in advance for any help you can give me!
Thanks,
Jon
Edit: Here's the code for the application
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GeneEditBarcodeAgentApplication
{
    public static void main(String[] args)
    {
        System.out.println("Starting app");
        SpringApplication.run(GeneEditBarcodeAgentApplication.class, args);
    }
}

A: I had same issue. It got resolved by deleting spring-boot-autoconfigure folder under C:\Users\currentUser\.m2\repository\org\springframework\boot
Then in eclipse do maven update.


text:
Q: Need further explaining with a specific situation of .reduce() method So I have this simple function:
function exampleFn (firstArray, secondArray) {
  return firstArray.map((x, y) =>
    Math.abs(x - secondArray[y]))
    .reduce((a, b) => a + b * b) / firstArray.length;
}

The function:

*

*accepts two integer arrays of equal length

*compares the value of each member in one array to the corresponding member in the other

*squares the absolute value difference between those two values

*and returns the average of those squared absolute value differences between each member pair.

It works with these values: [10, 20, 10, 2], [10, 25, 5, -2] //16.5 == 16.5.
Also works with: [-1, 0], [0, -1] //1 == 1.
BUT it doesn't work with: [1, 2, 3], [4, 5, 6] //should be 9, instead returns 7
Why does this happen, and how do I fix this (I want to do this in only one line, long or short)? What do  I miss about .reduce()?

*

*[3, 3, 3].reduce((a, b) => a + b*b) -----> returns 21 when I think it should return 27.

A: Let's step through the reduce example that you included as the last part of your question:
[3, 3, 3].reduce((a, b) => a + b*b)

The reduce function gets called twice.

*

*a=3, b=3 executes 3 + 3 * 3, yielding 12

*a=12, b=3 executes 12 + 3 * 3, yielding 21

You're trying to calculate the sum of squares. You could first square each element, and then sum them like this:
[3, 3, 3].map(n => n * n)
         .reduce((a, b) => a + b)

That yields 27.
So, the solution to your whole function would look like this:

function exampleFn (firstArray, secondArray) {
  return firstArray.map((x, y) => Math.abs(x - secondArray[y]))
                   .map(n => n * n)
                   .reduce((a, b) => a + b) / firstArray.length;
}

console.log(exampleFn([10, 20, 10, 2], [10, 25, 5, -2]) === 16.5)
console.log(exampleFn([-1, 0], [0, -1]) === 1)
console.log(exampleFn([1, 2, 3], [4, 5, 6]) === 9)


text:
Q: How do I override extended theme's styles and remove plugins? I've made my custom theme and extended the basic theme using configuration (index.js):
extend: '@vuepress/theme-default'
What I can't accomplish is disabling the plugins and overriding the default styles using (config.js):
module.exports = {
    // Disabling plugins we received from parent theme
    plugins: {
        '@vuepress/active-header-links': false,
        '@vuepress/search': false,
        '@vuepress/plugin-nprogress': false,
    },
    ...

and (index.styl):
// For example
body
    background-color: red !important;

When I run the dev server using the npm run dev or even after I build the website with npm run build, the result is the same. The old theme's plugins and styles stay.
I can even see them when I inspect the fetched CSS files.
I've read the docs but can't understand if this is an issue, or if I got something wrong.

A: *

*For you to inherit a theme you must to create the file docs/.vuepress/index.js :

// docs/.vuepress/index.js
module.exports = {
  extend: '@vuepress/theme-default',
};

*If you want to disable plugins, you must to declare the plugin-name with false:

// docs/.vuepress/index.js
module.exports = {
  extend: '@vuepress/theme-default',
  plugins: [
    ['@vuepress/active-header-links', false],
    ['@vuepress/search', false],
    ['@vuepress/plugin-nprogress', false],
    ['smooth-scroll', false]
  ],
};

For more information about this click here

*If you want to replace styles, you must to create the file docs/.vuepress/styles/index.styl:

/* docs/.vuepress/styles/index.styl */
body {
  background-color: yellow !important;
}

This also applies to others styles files present in default-theme. But you should pay attention to that:

Both the user's styles/index.styl and the theme's styles/index.styl are generated into the final CSS file, but the user's style is generated later and therefore has higher priority.

Click here for more information.

*If you have a lot of changes to the default theme, it is worth creating a new theme, because the inheritance is intended for minor corrections.


text:
Q: Authenticating a Request with FormUrlEncoded Body I have a scenario where I want to verify that every request has a valid header attribute. This attribute is a digital signature which essentially is a hash of the request url and the request body, in this case a form-url-encoded body.
So I did the typical thing and created an action filter as follows:
class SomeActionFilter @Inject()(val executionContext: ExecutionContext) extends ActionFilter[Request] {

  override protected def filter[A](request: Request[A]): Future[Option[Result]] = Future.successful {
    // here I want to get the request body which I know is a form url encoded request body
    val body = request.body //problem here is that body is of type A

  }

}

What I really want is to get request.body to be of type Option[Map[String, Seq[String]]] which is what a form url encoded body is. I could do this, ie swap the type parameter A with AnyContent like this and then I can get at a request.body.asFormUrlEncoded
class SomeActionFilter @Inject()(val executionContext: ExecutionContext) extends ActionFilter[Request] {

  override protected def filter[AnyContent](request: Request[AnyContent]): Future[Option[Result]] = Future.successful {
encoded request body
    val body = request.body.asFormUrlEncoded

  }

}

Is that the right thing to do here, to swap the type parameter like this? Or do I check if the body is of type Option[Map[String, Seq[String]]] using asInstanceOf and reject the request if it isn't? I'm a bit lost on how to approach this.


text:
Q: C FILE creation not working I am writing the
function to insert the book. The function is inslivros();. Here is the code:
int inslivros()
{
    char livro[30];
    int categoria;
    printf("Qual é o nome do livro que vai inserir?\n-> ");
    gets(livro);
    printf("Qual é a categoria do livro?\n1- Romance\n2- História\n-> ");
    scanf("%d", &categoria);
    if(categoria == 1)
    {
        FILE *livros;

        livros = fopen("C:\Livros\inserelivros.txt", "w+");
        fputs(livro, livros);
        fclose(livros);

        FILE *romance;

        romance = fopen("C:\Livros\romance.txt", "w+");
        fputs(livro, romance);
        fclose(romance);

        system("cls");
        printf("Livro inserido com Sucesso!\n");
    }
    else
    {
        int escolha;
        system("cls");
        printf("Nome inválido!\n");
        printf("1- Adicionar livro\n0- Voltar para o menu\n-> ");
        scanf(escolha);
        switch(escolha)
        {
        case 1:
            system("cls");
            inslivros();
        case 2:
            system("cls");
            main();
        }
    }

}

When categoria == 1, the folder and file are not being created. Where did I go wrong?

A:
When categoria == 1, the folder and file are not being created. Where did I go wrong?

fopen doesn't create folders/directories for you - it only create files. So if C:\Livros doesn't exist when running the program, the program will fail.
To create the folder/directory look at mkdir

A: the following proposed code:

*

*implements most of the comments to the question

*avoids recursion

*separates the decision to continue adding entries from the actual adding of a new entry.

*cleanly compiles

*documents why each header file is being included

*caveat: most items are properly error checked; however, the calls to fputs() should also be error checked

I'll leave it to you to use mkdir to create any missing directories.
Remember to check if the call to mkdir was successful, or not where the first time the program is run it may or may not be successful.  All following runs of the program should see mkdir fail.
And now the proposed code:
#include <stdio.h>   // perror(), printf(), fprintf(),
                     // fgets(), fputs(),
                     // fopen(), fclose()
#include <stdlib.h>  // system(), exit(), EXIT_FAILURE
#include <string.h>  // strlen(), strchr()

#define MAX_NOME_LEN 30

// prototypes
void inslivros( void );

int main( void )
{
    int escolha = 1;

    system("cls");

    while( escolha )
    {
        printf("1- Adicionar livro\n"
               "0- Voltar para o menu\n-> ");
        if( 1 != scanf( "%d", &escolha) )
        {
            fprintf( stderr, "scanf for escolha failed\n" );
            exit( EXIT_FAILURE );
        }

        // implied else, scanf successful

        switch(escolha)
        {
            case 1:
                inslivros();
                break;

            case 0:
                puts( "exiting" );
                break;

            default:  // user entered an invalid menu selection
                puts( "invalid menu selection, try again" );
                break;
        }  // end switch()
    } // end while()
} // end function: main

void inslivros()
{
    char livro[ MAX_NOME_LEN ];
    int categoria;

    printf( "Qual é o nome do livro que vai inserir?\n-> " );
    //gets(livro);
    if( ! fgets( livro, sizeof livro, stdin ) )
    {
        perror( "fgets for line to insert failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, fgets successful

    // remove trailing newline
    char * newline;
    if( (newline = strchr( livro, '\n' ) ) )
    {
        *newline = '\0';
    }

    printf( "Qual é a categoria do livro?\n"
            "1- Romance\n"
            "2- História\n-> " );

    if( 1 != scanf("%d", &categoria) )
    {
        fprintf( stderr, "scanf to input the 'categoria' failed\n" );
        exit( EXIT_FAILURE );
    }

    //implied else, scanf successful

    FILE *livros = NULL;

    switch( categoria )
    {
        case 1:
            if( ! (livros = fopen("C:\\Livros\\inserelivros.txt", "a") ) )
            {
                perror( "fopen for inserelivros.txt failed" );
                exit( EXIT_FAILURE );
            }

            // implied else, fopen successful

            fputs(livro, livros);
            fclose(livros);

            FILE *romance;

            if( !(romance = fopen("C:\\Livros\\romance.txt", "a")) )
            {
                perror( "fopen for romance.txt failed" );
                exit( EXIT_FAILURE );
            }

            // implied else, fopen successful

            fputs( livro, romance );
            fclose( romance );

            system("cls");
            printf( "Livro inserido com Sucesso!\n" );
            break;

        case 0:
            printf( "Historia not yet implemented\n" );
            break;

        default:
            system("cls");
            //printf("Nome inválido!\n");
            printf( "invalid menu selection\n" );
            break;
    } // end switch()
} // end function: inslivros


text:
Q: Want to tag runs I need to tag a TextRange (specifically a TextRange returned by Runs() ), but VBA in PowerPoint only allows you to tag presentations, slides, and shapes.
Working my way back up the object tree (run > TextRange > textframe > items > shapes), I discover that shapes are the closest taggable object.
I could do the tagging in the shape that contains the run, but I need a way to uniquely identify the run.
For instance, I could envision tagging the shape with key=unique_id_of_the_run, value=whatever, but I don't know of anyway in VBA to get a unique for a run.
If there was a way to get a unique I'd (or memory address) of objects in general, I could use that as my unique key, but I don't know how to get an object's unique is in VBA.
Any suggestions? Thanks.


text:
Q: How can I change the color to the arrows navigation of the ngb-datapicker? I am using this datapicker (the range selection) on a project and the blue color of the arrows in the navigation bar is not the right one and I want to change it. I searched on google and here and I can not found an answer that solve my problem.
I have this HTML:

  <ngb-datepicker #dp (select)="onDateSelection($event)" [displayMonths]="2" [dayTemplate]="t" outsideDays="collapsed"></ngb-datepicker>

  <ng-template #t let-date let-focused="focused">

            {{ date.day }}

  </ng-template>

And I try all of this CSS:
.bnt-link {
    color: #12A19A !important;
}

::ng-deep ul {
    background-color: #12A19A !important;
}

ngb-datepicker {
    position: absolute;
    background-color: white;

    .ngb-dp-header {
        background-color: rgba(52,104,191,1);
    }

    select {
        background-color: rgba(52,104,191,1);
        color: white;
    }
}

::ng-deep .ngb-dp-arrow-btn {
    background-color: black;
}

And I can not figure out how to change the color of the blue arrows in the datapicker

A: You will need to utilize the ::ng-deep pseudo class selector to target the children of the component.  A description of this process is described here:
https://blog.angular-university.io/angular-host-context/
Please note that ::ng-deep is going to soon be depricated and removed. My understanding is that there is not replacement solution yet in place, so for the time being, we need to continue using it.
EDIT: This code worked on my project, I placed it on the component CSS for the component where I called the ngb-datepicker:
::ng-deep div.ngb-dp-arrow > button {
  color: red;
}


text:
Q: Mixing variable assigment and data retrieval - MySQL vs MS SQL Server I am trying to refresh my skills with sql queries, which I have not used in many years.
While making some excercises I came across a problem which is quite simple to solve in MySql but more complicated in sql server. I'd like to know if there is a simpler way to do it.
I will oversimplify the problem for the sake of the question (to avoid complicated code)
So, I have a sequence of numbers. Within this sequence I want to identify and number subsequences of numbers < 10. When a number >= 10 is met a new subsequence starts identified by the seqno counter. Below the mysql query + result
create table myt1(mynum int);
insert into myt1 values (13), (5), (8), (15), (2), (5), (18), (3), (6), (9), (8), (12);
set @seqno = 0;
select mynum, @seqno := case when mynum < 10 then @seqno else @seqno+1 end as seqno
from myt1

Now with SQL server things get more complicated because it's not allowed to do in the same SELECT statement both data retrieval and variable assignment. My workaround to get the same result was to copy the table into a temp table with an additional column and then update the table/colum with the following code
create table myt1(mynum int);
insert into myt1 values (13), (5), (8), (15), (2), (5), (18), (3), (6), (9), (8), (12);
select *, 1 as seqno
into #tempt1
from myt1

declare @seqno int;
set @seqno = 0;
update #tempt1
set
    seqno = @seqno,
    @seqno = case when mynum < 10 then @seqno else @seqno+1 end

select * from #tempt1

Can anyone tell me if there is a simpler way to write this query in mssql and why there is a limitation that is not found in mysql?
Thanks!

A: You seem to want a cumulative count of the values over 10:
select mynum,
       sum(case when mynum >= 10 then 1 else 0 end) over (order by id) as seqno
from myt1;

Here is a db<>fiddle.
Note that SQL tables represent unordered sets.  Your query assumes an ordering of the table -- which is not valid in SQL in general or in either database.  Your query does seem to work in MySQL, but there are no guarantees.
I have added an id column to capture the ordering, so the query will work.
Incidentally, this is also the preferred method in MySQL 8+; the use of variables is being deprecated.


text:
Q: how can I add main link to sublink html, so that link can be called? this is my code that gives a list of particular news links from HTML page, it contains only resource name and parameters, I want to include main domain name so that link can be operatable.
import requests
from bs4 import BeautifulSoup

def get_cric_info_articles():

    cricinfo_article_link = "http://www.espncricinfo.com/ci/content/story/news.html"

    r = requests.get(cricinfo_article_link)
    cricinfo_article_html = r.text

    soup = BeautifulSoup(cricinfo_article_html, "html.parser")
    # print(soup.prettify())

    cric_info_items = soup.find_all("h2",
                                    {"class": "story-title"})
    cricinfo_article_dict = {}

    for div in cric_info_items:
        cricinfo_article_dict[div.find('a').string] = div.find('a')['href']

    return cricinfo_article_dict

print(get_cric_info_articles())

what I'm getting {'Bell-Drummond leads MCC in curtain-raiser': '/ci/content/story/1135157.html', 'Scotland pick Brad Wheal, Chris Sole for World Cup qualifiers': '/scotland/content/story/1135152.html', 'Newlands working to be water independent': '/southafrica/content/story/1135120.html'}
I'm trying to attach this '/ci/content/story/1135157.html'to http://www.espncricinfo.com/
so the final link will be http://www.espncricinfo.com/ci/content/story/1135157.html', how can I do this? sorry for the long post
changes I did
for div in cric_info_items:
        a = div.find('a')['href']
        b = 'http://www.espncricinfo.com/'
        c = urljoin(b,a)
        cricinfo_article_dict[div.find('a').string] = c

A: You can use the urllib.parse module for this:
from urllib.parse import urljoin
urljoin('http://www.espncricinfo.com/', '/ci/content/story/1135157.html')

Hope it helps.

A: ...
# if protocol is not specified in the link, assume it's relative
for div in cric_info_items:
    url = div.find('a')['href']
    if "://" not in url:
        url = cricinfo_article_link + url
    cricinfo_article_dict[div.find('a').string] = url
...

or, using dict comprehension:
return {
    div.find('a').string : ("" if "://" in div.find('a')['href'] else cricinfo_article_link) + div.find('a')['href']
    for div in soup.find_all("h2", {"class": "story-title"})
}

Upd: a potential border case is links starting with //, e.g. //google.com/?q=foo. This type of links sometimes is used for resources (css and javascript) and is not common for external links. However, you might want to handle this as well


text:
Q: Parse an elementTree to return a string in XML form - Python is there a way to parse an entire ElementTree from a file and return it as a string in python? I would like to read the entire file into a single string value, for example grabbing the entire output of dump(tree)? Any help or advice would be greatly appreciated!
xml
import xml.etree.ElementTree as ET

print "Enter a filename"
filename = input()
tree = ET.parse(filename)
string = tree.tostring() ##is there a way to do something like this?

test.xml
<data>

     <serial>

     <serial name = "serial">SN001</serial>

     </serial>

     <items>

    <item>Test1 = Failed</item>

    <item>Test2 = Passed</item>

    <item>Test3 = Passed</item>

      </items>

</data>

A: tostring is a module function, not a method.
string = ET.tostring(tree.getroot())


text:
Q: Fedora 32 System Settings Missing In the process of installing the nvidia proprietary driver on my Fedora 32 machine, somehow the system settings application has lost its menu bar on the left.  All I have are a few "common" items to choose from.  Can anyone tell me how I might go about recovering this?  I did not remove any KDE applications.  This seems to have happened while I was getting the displays configured.  Here is a screen capture of the system settings application.  Anyone?
Thanks in advance,
Dave


text:
Q: Using tensors as indexes in a network My network has multiple inputs where one of those inputs is an index that is used in the network to index into other tensors.
I am having issues using the tensor as an index.
class MemoryLayer(tf.keras.layers.Layer):
  def __init__(self, memory_size, k, **kwargs):
    super().__init__(kwargs)
    self.memory_size = memory_size
    self.k = k

  def build(self,input_shape):
    # Set up the memory_var

  # Shape of input is [(1,3,6), (1,3)]
  def call(self, input):
    for i in range(3):
      statement = input[0][0,i]
      cluster = input[1][0,i]
      old_sub_mem = self.memory_var[cluster, :-1] #Error here

      # Here should be a bunch of stuff I removed because its not relevant

    return tf.expand_dims(self.memory_var, axis=0)

I get a TypeError saying that <tf.Tensor 'memory_layer_19/strided_slice_2:0' shape=() dtype=float32> isn't a valid index. I tried calling .numpy() on input[1] but this doesn't work as the tensor has no shape. From the data I input cluster should be a single number.

A: By default, input to layers are tf.float32. However, to index a tensor, you need integers. You can either cast the inputs of your layer to integers, or you can specify that the input of that layer should be of the integer type.
With casting
cluster = tf.cast(input[1], dtype=tf.int32)[0,i]
old_sub_mem = self.memory_var[cluster, :-1]

Specifying the type of the input
I use the functional API in that example:
inp_statement = tf.keras.Input(shape=(3,6))
inp_cluster = tf.keras.Input(shape=(3,), dtype=tf.int32)
memory = MemoryLayer(memory_size=10)([inp1,inp2])

Note: I don't exactly understand what you are trying to achieve, but this for loop could probably be optimized out with a call to tf.gather or tf.gather_nd.


text:
Q: Is this an equivalent "while" replacement for the "for"? Supposing we have defined a class T with no restrictions and three functions cond, next and f returning bool, void and anything respectively, are
for(T k = T(); cond(); next())
    f();

and
{
T k = T();

while(cond()) {
    f();
    next();
}
}

the same algorithmically speaking?

A: Absolutely. A for (init; cond; step) {statements} syntax is equivalent to
{
    init;
    while (cond) {
        statements;
        step;
    }
}

So they are totally interchangeable (except for readability in certain cases).
The purpose of the standalone braces in the first and the last line is to restrict the scope of the initialized variables to the loop itself.

A: Since in both the cases you have initialized the class object and then the check condition and then the next step to be followed are identically placed both will work similarly algorithmically as well as in execution owing to the fact that both FOR and WHILE are interconvertible .


text:
Q: AzureFileCopy task failing in YAML pipeline - works in Release pipeline I am trying to convert a release pipeline into a multi-stage YAML pipeline and I am running into an issue with the AzureFileCopy@4 task. When I run the task in a release pipeline, the task succeeds and files are copied to the remote VM.  When I run the task in a multi-stage YAML pipeline, the task fails.  Specifically, the following command within the task fails:
New-PSSession -ComputerName 'vmname.eastus.cloudapp.azure.com' -Port 5986 -Authentication Default -Name '68fe512f-477d-4d56-9217-5ab84517a53b' -Credential $credential -UseSSL -ErrorAction 'SilentlyContinue' -ErrorVariable sessionErrors -ConfigurationName 'microsoft.powershell'

The error message that is generated is:
Connecting to remote server vmname.eastus.cloudapp.azure.com failed with the following error message : Access is denied.

I don't suspect a problem with the WinRM configuration, since I am connecting just fine in the Release Pipeline. Given the error and the command, I would say that it is the credentials, but I have looked at them over and over and they are exactly the same.
The inbound rules on the NSG have the WinRM port 5986 open to any source, so it doesn't appear that there is a restriction on which machines can start a new pssession.
UPDATE 12/22/20
Below is a sanitized version of the stage that is failing.  The filecopy mostly works when it is in my build stage, but not when it is part of a deployment stage using a deploy job
- stage: deploy
  jobs:
  - deployment: DeployR50
    displayName: Deploy R50 App
    pool:
      vmImage: 'windows-latest'
    environment:
      name: 'QA'
      resourceName: 'Test'
      resourceType: virtualMachine
    strategy:
      runOnce:
        deploy:
          steps:
          - task: AzureFileCopy@4
            inputs:
              SourcePath: '$(Pipeline.Workspace)\R50\*'
              azureSubscription: 'Joe MSDN Azure'
              Destination: 'AzureVMs'
              storage: 'mytest'
              resourceGroup: 'TEST'
              MachineNames: 'Test'
              vmsAdminUserName: '***'
              vmsAdminPassword: $(VM_PASSWORD)
              TargetPath: 'c:\R50'

A: According to your description, you can successfully run this task in the release pipeline, so the VM settings are correct.
Based on my test, I try to export the pipeline to Yaml and it still could work fine.
You can try the following steps to check your Yaml pipeline:

*

*When you export the Yaml file, you could directly upload the file to the repo instead of copying the code.

Then when you create the Yaml Pipeline, you could use the  existing YAML file.

*

*In the output yaml file, you need to check whether there are extra spaces or special characters.

This issue could be caused by incorrect username and password.

*

*You can try to manually re-add this task in the yaml pipeline and check if it could work.


text:
Q: with pandas read_sql, how do I run procedure with parameters? I have a stored procedure which as been created like this :
create or replace PROCEDURE MyTestProcedure(p_date IN DATE)
AS
OUTPUT SYS_REFCURSOR;
BEGIN
END

I would like to execute it doing :
pd.read_sql("""EXECUTE MyTestProcedure @p_date=(TO_DATE('2022-02-01','YYYY-MM-DD'))"""

but this does throw an error :
DatabaseError: Execution failed on sql 'EXECUTE MyTestProcedure @p_date=(TO_DATE('2022-02-01','YYYY-MM-DD'))': ORA-00900: invalid SQL statement

what am I missing there ?


text:
Q: How to have \n when stringifying JSON? I am using gh API to get package and lock files of npm from a project. This gives us encoded data. Data is presentable after decoding and parsing the data. After parsing and updating the data, I need to send the changes to github using API. To do that I need to stringify and encode the data again. Now the problem is, when I stringify the data it becomes a string in one line. To resolve this issue I need to have \n in the string. I have got no idea how.
I want the data to look like this :
"{\n  \"name\": \"test-1\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n  },\n  \"keywords\": [],\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"dependencies\": {\n    \"axios\": \"^0.15.2\",\n    \"bluebird\": \"^2.0.7\",\n    \"body-parser\": \"^1.8.3\",\n    \"express\": \"^2.4.5\",\n    \"istanbul\": \"^0.1.31\",\n    \"mongoose\": \"^4.5.8\"\n  }\n}\n"
But stringifying data gives me this :
{"name":"test-1","version":"1.0.0","description":"","main":"index.js","scripts":{"test":"echo \"Error: no test specified\" && exit 1"},"keywords":[],"author":"","license":"ISC","dependencies":{"axios":"^0.15.2","bluebird":"^2.0.7","body-parser":"^1.8.3","express":"^2.4.5","istanbul":"^0.1.31","mongoose":"^4.5.8"}}

A: You can add spaces in JSON.stringify. JSON.stirngify takes 3 parameters: data, replacer funciton, spaces respectively.
JSON.stringify(data, null, 2);