text:
Q: Scrapyd fails on depricated settings in environment variables We run scrapy 2.1.0 and scrapyd in python 3.6 on ubuntu 18.04 and I ran into a problem that I need help understanding how to solve the right way. I'm new to python (coming from other languages) so please speak slowly and loudly so I understand =)
The problem is that a job can get stuck as "pending" in the scrapyd schedule. When reading the latest log messages using systemctl status scrapyd.service it shows a deprecation warning.

usr/local/lib/python3.6/dist-packages/scrapy/utils/project.py:94: ScrapyDeprecationWarning: Use of environment variables prefixed with SCRAPY_ to override settings is deprecated. The following environment variables are currently defined: JOB, LOG_FILE, SLOT, SPIDER

After reading up on this issue I understand the nature of the problem and my guess is (please correct me here) that scrapyd define these environment variables in runtime, which triggers the warning in scrapy, that then stops scrapyd from continuing.
I can define LOG_FILE in the scrapy project settings.py but the other three feels very specific to scrapyd runtime/schedule and are not part of a scrapy project settings file.
My ugly workaround that seems to work is to add these variables to the list in /scrapy/utils/project.py on line 80.
scrapy_envvars = {k[7:]: v for k, v in os.environ.items() if
                  k.startswith('SCRAPY_')}
valid_envvars = {
    'CHECK',
    'PICKLED_SETTINGS_TO_OVERRIDE',
    'PROJECT',
    'PYTHON_SHELL',
    'SETTINGS_MODULE',
    'JOB',              # <<--- here...
    'LOG_FILE',         # <<--- here...
    'SLOT',             # <<--- here...
    'SPIDER',           # <<--- and here
}
setting_envvars = {k for k in scrapy_envvars if k not in valid_envvars}
if setting_envvars:
    setting_envvar_list = ', '.join(sorted(setting_envvars))
    warnings.warn(
        'Use of environment variables prefixed with SCRAPY_ to override '
        'settings is deprecated. The following environment variables are '
        'currently defined: {}'.format(setting_envvar_list),
        ScrapyDeprecationWarning
    )

This makes the deprecation warning go away and scrapyd schedule can move jobs from pending to running and then finished.
Obviously this is a very bad idea since I'm changing code inside a lib/module/package (or whatever the correct term is) and this would be overwritten by any update by package manager.
So my question is, assuming I have understood the source of the problem correctly, what is the correct way to fix this without changing code inside the scrapy core?
Thanks in advance for your input!

A: My  /scrapy/utils/project.py doesn't have those commented lines anymore, but I'm also facing this issue.
By inspecting my environment variables (thru this command at prompt: printenv) I've found SCRAPY_SETTINGS_MODULE pointing to my scrapy settings. That's exactly the warning "Use of environment variables prefixed with SCRAPY_". With unset SCRAPY_SETTINGS_MODULE I've been able to remove it from the environment.


text:
Q: ack does not work when run from "grep-find" in Emacs on Windows I'm trying to use ack-grep as a replacement for grep + find in Emacs on Windows, but ack-grep exits immediately (successfully) without printing any matches. I've tried just about every conceivable combination of command-line parameters to ack-grep, but nothing seems to work.
M-x grep-find

Enter "ack html" to search for files containing "html". Ack exits immediately, printing nothing:
-*- mode: grep; default-directory: "c:/" -*-
Grep started at Tue Feb 23 23:50:52

ack html

Grep finished (matches found) at Tue Feb 23 23:50:52

Executing the same command "ack html" in cmd.exe works fine (showing lots of various files containing the string "html".
Any ideas?

A: When running ack under Emacs in Windows, I found it sometimes got confused about whether it was supposed to search files or read from STDIN.  Here's the function I use to call ack (use M-x ack).  You can put this in .emacs.
(defvar ack-command "ack --nogroup --nocolor ")
(defvar ack-history nil)
(defvar ack-host-defaults-alist nil)
(defun ack ()
  "Like grep, but using ack-command as the default"
  (interactive)
  ; Make sure grep has been initialized
  (if (>= emacs-major-version 22)
      (require 'grep)
    (require 'compile))
  ; Close STDIN to keep ack from going into filter mode
  (let ((null-device (format "< %s" null-device))
        (grep-command ack-command)
        (grep-history ack-history)
        (grep-host-defaults-alist ack-host-defaults-alist))
    (call-interactively 'grep)
    (setq ack-history             grep-history
          ack-host-defaults-alist grep-host-defaults-alist)))

A: (setq grep-find-command "ack <nul -i ")

A: I had a similar issue using the ack-and-a-half module, closing STDIN did the trick there too. There's an issue on github: https://github.com/jhelwig/ack-and-a-half/issues/23

redpajama_set_name: RedPajamaStackExchange


text:
Q: Deployment error: "invalid cross reference id" / How do I determine which Profiles are referenced in .app metadata files? I'm attempting to migrate metadata from one org to another using a package.  But my mdapi:deploy command keeps failing with "Error  test/applications/Underwriting.app  Underwriting  invalid cross reference id"
Originally all three .app files in my metadata package were failing.  Then I did something (IDK what – I tried a bunch of stuff) that got two of the .app files to deploy and only one is failing now.
Looking at what changed in the .app files that failed but now deploy without error, I notice they no longer contain references to many standard profiles.  They only reference custom profiles and the Admin profile.  No other standard profiles besides Admin.
Also, if I look at the .app files that continues to cause problems, I see that it contains references to many if not all of the standard profiles.  As a result, I suspect it is the inclusion of these standard profiles that is causing problems.
I thought the fix would be easy: go to Setup > App Manager > App Settings > User Profiles, move the standard profiles from the Selected Profiles column to the Available profiles column and then update the package.
The problem is that it does not seem that changes I make to App Manager > App Settings > User Profiles are reflected in the .app files in my metadata.
Removing standard profiles from the app with the .app file producing the error does not remove them from the .app metadata file.  Also, adding standard profiles to the apps whose .app files do not contain standard profiles does not add the selected standard profiles to these .app files.
This has left me perplexed.  Is the issue the standard profiles in the .app file?  If not App Manager > App Settings > User Profiles, how do I control which profiles appear in my .app files?
Note: I've searched for similar errors / possible solutions.  The first link below sounds most similar but it's marked as a "fixed" known issue as of a year ago so I don't think that's the issue.  The second link says there's an invalid record ID in my code.  But the error messages I get identify the files producing the error and I'm 100% positive they do not contain any record (or other IDs).
https://success.salesforce.com/issues_view?id=a1p3A000000mCIdQAM&title=invalid-cross-reference-id-deploying-custom-app-with-profileactionoverrides-referencing-new-profiles-in-same-deployment
https://developer.salesforce.com/forums/?id=906F0000000BIhXIAW

A: Adding all Profiles to the package was the one thing that resolved the 'invalid cross reference id' errors for the apps on the deployment validation. That was after splitting out the apps from the rest of the deployment to run them after all other metadata components were deployed.
This worked for me as with Copado when we deploy profiles it only deploys the parts that refer to the other components included in the deployment package.
As per this Sf article, 'Error 'Invalid cross reference id' on App Deployment via Change Set':
https://help.salesforce.com/s/articleView?id=000390026&type=1
This issue may be of use to some:
https://issues.salesforce.com/issue/a028c00000qQ255AAC/special-characters-like-when-included-in-name-of-a-profile-being-deployed-in-an-app-can-cause-invalid-cross-reference-id-error


text:
Q: How do I get the Facebook comment count for a URL in PHP in 2021? I'm using the Facebook Comments plugin (from FB, not a WP Plugin) on my WP site.
I want to get the number of comments for a specific URL, so I can set it up to say "start the conversation" or "join the conversation"
I've done my research and found several variations on the code below posted as recently as April of this year:
$rest_url = "http://api.facebook.com/restserver.php?format=json&method=links.getStats&urls=https://my.com/".$my_slug;
$json = json_decode(file_get_contents($rest_url), true);
//  echo "Facebook Shares = " . @$json[0]['share_count'];
//  echo "Facebook Likes = " . @$json[0]['like_count'];
  echo "Facebook Comments = " . @$json[0]['comment_count'];

However, after some frustration, I realized I needed to dump $json and see what's in there:
var_dump($json);
and to just parse out the important part, there was a message inside:
"REST API is deprecated for versions v2.1 and higher (12)"
There's a lot I don't understand about APIs and Facebook's system.
But... can you tell me what the current way of getting the comment count is now? I just need it in a variable and I can go from there.
Thanks for any help!
Chris


text:
Q: Random forest gives me 0% accuracy I have tried to make a random forest with some help on youtube. I am really new to ML concept so i tried to let everything as default.
Firstly i gave my training set 2 factors which has some variance by themselves.
The main problem is that i get 0% accuracy like everything is predicted as 0 because is the major value (70% of 0 30% of 1)
The code is here:
pedes.10 <- cas.10[which(cas.10$Casualty_Type == "0"),]

pedes.10$Age_Band_of_Casualty <- as.factor(pedes.10$Age_Band_of_Casualty)

# to make Injury only on 1 and 2 value
for (i in 1:nrow(pedes.10)) {
  x <- ifelse(pedes.10$Casualty_Severity != "3", 1, 0)
  pedes.10$Injury <- x
}

#Starting the random forest
rf.train.1 <- pedes.10[, c("Age_Band_of_Casualty", "Sex_of_Casualty")]
rf.label <- as.factor(pedes.10$Injury)

set.seed(9299)

rf.1 <- randomForest(x = rf.train.1, y = rf.label, importance = FALSE, ntree = 3000)
rf.1
varImpPlot(rf.1)

I get 0% accuracy on the first case and 100% on the other. I do understand that i made something completely wrong but i do not know what to do...
Data set is here: (Casualties 2010) --> https://data.gov.uk/dataset/cb7ae6f0-4be6-4935-9277-47e5ce24a11f/road-safety-data
Thanks for help.
Letting the image here
letting the image here


text:
Q: Neo4j PHP OGM with Authentication I was wondering: what is the best practice to create a connection to Neo4j through the neo4j-php-ogm library if I am using username and password authentication?
In the documentation it states that connections are created by following:
use GraphAware\Neo4j\OGM\EntityManager;
$manager = EntityManager::create('http://localhost:7474');

So I am using the same in my graph manager:
$client = Manager::create('http://username:password@localhost:7474');

I have a feeling that this is not the safest way because I am only using http and sending the credentials in the URL. What would be a better way to establish a connection including authentication?
Sidenote: The Manager::create instead of the EntityManager::create as noted in the documentation is because installing the library via composer gets an older version than currently on GitHub if im not mistaken.

A: You can just provide them as part of the uri defined for your connection :
$manager = EntityManager::create('http://neo4j:password@localhost:7474');

Note that there are not sent as such for security reasons, instead the username and password are extracted with parse_url and provided as connection parameters.
For the second part, yes the current 1.0 branch reflects changes that are not tagged yet. I should make a new beta release this week.


text:
Q: Check if a file includes some content Thanks to a previous answer, I can test if a file exists using
if !empty(glob("filename"))
  ...
endif

I now want to check if the file filename contains text text.
If possible, I want to do this using native vimscript only, not calling system's grep etc commands.

A: if filereadable("filename") && match(readfile("filename"),"text")
   ...
endif

See :help function-list for a high-level overview of vimscript functions.

A: I use:
if match(readfile(expand("%:p")),"pattern")!=-1
   # content
endif

to check if a file contains a pattern in vimscript


text:
Q: Tracking down JavaScript event listeners for a HTML DOM element In the world of dynamically updated page fragments via Ajax (often lacking the use of best practices!), I encounter the attachment of event listeners scattered all over an application's JS. Sometimes, the developer would have adhered to some practical conventions that make it somewhat easy to track down code that attaches specific event listeners to DOM elements. Not always.
In this sad scenario, what is the best way to enumerate/view event listeners attached to a particular node/element? I enjoy using Chrome's amazing developer tools, although this is one area where the tool does not give me a whole lot of information.
Can I employ JavaScript or jQuery code to:

*

*view a list of event listeners

*track the code that sets up an event listener

Note: I originally asked about a way to examine event listeners in Chrome Dev Tools, but if there is a way to do it in code, I actually prefer that!
Edit: This answer is what I was looking for!


text:
Q: How to install PIL with zlip and jpg support in centos with pip python When i install pip install PIL then i get this
   *** TKINTER support not available
    *** JPEG support not available
    *** ZLIB (PNG/ZIP) support not available
    *** FREETYPE2 support not available
    *** LITTLECMS support not available
    --------------------------------------------------------------------

I have all the libraries and i tried this as well
sudo ln -s /usr/lib64/libfreetype.so /usr/lib/
sudo ln -s /usr/lib64/libz.so /usr/lib/
sudo ln -s /usr/lib64/libjpeg.so /usr/lib/

how can i install all of the above with pip on centos

A: You need the required headers from the corresponding libraries: libjpeg, libpng, and others.
Usually, you will need the dev packages for those libraries to have the headers.

Nevertheless, installing PIL is usually pretty complicated as it often fails to detect the libraries. You should do pip install pillow instead. pillow is an installer for PIL, which finds libraries more easily.


text:
Q: Dataframe - how to insert new row with null value, conditionally based on elapsed time? Background: My dataset aquires values at roughly 5 minute intervals, but sometimes there are gaps. I am charting my dataset using Plotly and attempting to resolve an issue where a straight line is drawn between points if there is a gap in the dataset. Plotly has a parameter connectgaps which if set to false will not connect over 'nan' values. However, my dataset looks like this:
(where I have computed the time difference using df['time_diff_mins'] = (df['datetime'].shift(-1) - df['datetime']).dt.total_seconds() / 60)
     datetime                 value   time_diff_mins
0    2022-03-09 09:25:00      98      5
1    2022-03-09 09:30:00      104     21
2    2022-03-09 09:51:00      105     3
3    2022-03-09 09:54:00      110     nan

If you look at rows 1 and 2, the time difference is 21 minutes. For this reason, I don't want the values 104 and 105 to be connected - I want a break in the line if there is a gap of greater than 15 mins and 15 seconds.
So, I am trying to insert a new row with null/nan values in my dataframe if the time difference between rows is greater than 15 mins and 15 seconds, so that Plotly will not connect the gaps.
Desired output:
     datetime                 value
0    2022-03-09 09:25:00      98
1    2022-03-09 09:30:00      104
2    2022-03-09 09:40:30      nan
3    2022-03-09 09:51:00      105
4    2022-03-09 09:54:00      110

I hope that makes sense. I know that inserting rows programmatically is probably not an optimal solution, so I haven't been able to find a good answer to this.

A: You can use a mask and pandas.concat
df['datetime'] = pd.to_datetime(df['datetime'])

delta = '15 min 15 s'

d = df['datetime'].diff().shift(-1)

out = (pd.concat([df,
                  df['datetime'].add(d/2).
                    .loc[d.gt(delta)].to_frame()
                  ])
         .sort_index()
       )

Output:
             datetime  value  time_diff_mins
0 2022-03-09 09:25:00   98.0             5.0
1 2022-03-09 09:30:00  104.0            21.0
1 2022-03-09 09:40:30    NaN             NaN
2 2022-03-09 09:51:00  105.0             3.0
3 2022-03-09 09:54:00  110.0             NaN


text:
Q: Access HTML form values in javascript Here is what I am trying to achieve, but for some reason, it does not work:
Javascript:
<script type="text/javascript">
  function  calculate() {
     var n1 = getElementById("1").value
     var n2 = getElementById("2").value
     var answer = n1+n2
     alert(answer)
  }
</script>

HTML:
<form id="form">
<input id="1" type="text" />
<input id="2" type="text" />
<input type="button onClick="calculate()" value="Go" />
</form>

I am not sure where I went wrong, Can someone help please?

A: You shouldn't start ID's with numbers - in HTML4 and CSS it isn't allowed, in HTML5 it is allowed, but it's not good practice to do so.
Also, in this context it is illegal in HTML5 - as an ID starting with a number requires at least one letter afterwards.
So, firstly replace the numbered ID's with letters/words.

Apart from this, you need to fix the syntax errors mentioned below:
Replace getElementById("id").value with document.getElementById("id").value;
and also replace <input type="button onClick="calculate()" value="Go" />
with <input type="button" onClick="calculate()" value="Go" /> (notice there was a closing " missing for "button").
Here is a working jsFiddle.

Here is the code used in the jsFiddle:
Javascript:
function  calculate() {
   var n1 = document.getElementById("aItem").value;
   var n2 = document.getElementById("bItem").value;
   var answer = n1+n2;
   alert(answer);
}

HTML:
<form id="form">
   <input id="aItem" type="text" />
   <input id="bItem" type="text" />
   <input type="button" onClick="calculate()" value="Go"/>
</form>

A: HTML:
<input id="val1" type="text" value="100" />
<input id="val2" type="text" value="200"/>
<input type="button" onclick="calculate()" value="Go" />

JavaScript:
function  calculate() {
          var n1 = +(document.getElementById("val1").value);
          var n2 = +(document.getElementById("val2").value);
          var answer = n1+n2;
          alert(answer);
         }

This will add the 2 numeric values entered rather than concatenating them.


text:
Q: Object reference not set to an instance of an object in user control from another project I have a solution with 2 projects in it. One project(TestControl) contains the aspx file. then the other(Controls) for the usercontrols. I have already made it possible for the aspx to display the user controls via referencing the Controls in the project and copying the files to the TestControl Project. But the Sub seems not to work and it sends an error "Object reference not set to an instance of an object" even at a simple response.redirect code. I tried a msgbox and it works and also placing the code in page_load. But inside a sub it's not working. Any ideas why? and a fix?
Simple code in the uc3.ascx file
   Public Sub Redirect()

        Response.Redirect("http://www.google.com")
    End Sub

Here is the error exception
System.NullReferenceException was unhandled by user code
  HResult=-2147467261
  Message=Object reference not set to an instance of an object.
  Source=System.Web
  StackTrace:
       at System.Web.UI.UserControl.get_Response()
       at Controls.uc3.Redirect() in C:\Users\Nelbin\Documents\Visual Studio 2010\Projects\TestApp\Controls\uc3.ascx.vb:line 9
       at Controls.uc1.btnUserControl3_Click(Object sender, EventArgs e) in C:\Users\Nelbin\Documents\Visual Studio 2010\Projects\TestApp\Controls\uc1.ascx.vb:line 16
       at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
       at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
       at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  InnerException:

A: From reason which I don't see from your code the control does not access Response object. Try
System.Web.HttpContext.Current.Response

intead of just Response.
Public Sub Redirect()
    System.Web.HttpContext.Current.Response.Redirect("http://www.google.com")
End Sub

In web project System.Web.HttpContext.Current should never be nothing.


text:
Q: How to solve a Compound Interest Question with yearly withdrawals? The current period is January 2015
A Principal wants to make 3 deposits in the bank:
Start of 2015,
Start of 2016,
Start of 2017,
And wants to give a $5000 scholorship for to the best student at the end of the following years:
$5000 end of 2018,
$5000 end of 2019,
$5000 end of 2020,
$5000 end of 2021,
$5000 end of 2022,
The interest rate is 6% p.a, everything is compounded yearly.
The Principal doesn't care about having money left over in the fund, he wants to use it exactly.
What are the three equal deposits in 2015,2016,2017 he needs to make so he can fund his scholorship program?
I am struggling with this problem any help?

A: At the end of the year 2022 the value of the deposits and the value of the withdrawals have to be equal.
The future value of the three deposits (x) is
$x\cdot 1.06^8+x\cdot 1.05^7+x\cdot 1.06^6=x\cdot 1.06^6\cdot(1.06^2+1.06+1)$
The future value of the withdrawals is
$\underbrace{5000\cdot 1.06^4}_{\text{FV of withd. 2018}}+\underbrace{5000\cdot 1.06^3}_{\text{FV of withd. 2019}}+\underbrace{5000\cdot 1.06^2}_{\text{FV of withd. 2020}}+\underbrace{5000\cdot 1.06^1}_{\text{FV of withd. 2021}}+\underbrace{5000\cdot 1.06^0}_{\text{FV of withd. 2022}}= 5000\cdot \frac{1.06^5-1}{0.06}$
Setting the future values equal:
$x\cdot 1.06^6\cdot(1.06^2+1.06+1)=5000\cdot \frac{1.06^5-1}{0.06}$
Now you can solve the equation for x.


text:
Q: DELETE statements must restrict all PRIMARY KEY columns with equality relations in order to delete non static columns If i understand this statement correctly
DELETE statements must restrict all PRIMARY KEY columns with equality relations in order to delete non static columns

it states that all my primary key should have equality symbol i.e =
here is the query i'm using to delete
DELETE FROM service.data WHERE product_uuid=432523b3-8094-4a0d-b93a-cc8d22100f85 AND item_uuid=a709c5cc-8f98-4cba-b1dc-264b0fd24e08 IF EXISTS;

how is the query wrong?? what is the correct one to delete a row from data table??


text:
Q: How to check if my dataset is normally distributed? I have data sets (measurements) and I need to know if values are normally distributed. I would like to get this information programmatically in my application and not via plotting and checking it visually myself. Is there some statistical method how to check it?
I have an idea to use mean and median and if median equals mean (or is very close) the distribution can be considered as normally distributed. But I'm not sure what "close" is enough.

A: This is a very wide subject - the Wikipedia article on the subject, is a good place to start.
In short, there are many methods and the "right" method for you depends on what you need:

*

*Do you know the mean and variance apriori?

*Do you need an exact estimate of how far you are from a normal distribution, or is yes / no answer good enough?

*How much computation time do you have?

I think the easiest method is to calculate the skewness and kurtosis of your data. If both are "near" enough to zero, it's normal. To get the "score" one method often used is the Jarque-Beta test which gives you the p-value given the calculated skewness and kurtosis.


text:
Q: How to make copy-paste buffer in Ubuntu system-wide not lost when application closes? It is often useful to have not full of security guards system, but user-friendly system.
Typical everyday task is copypasting text between windows in Ubuntu.
Scenario as simple as follows.
One need to fill-in the package name somewhere.
(in my case it is compizconfig-settings-manager, but wait).
First one need to obtain name. One may do
dpkg -l compiz*

...and get first phase of hair tearing: name not fully shown but shorted.
Then running synaptic and fill-in compizco. Package appears in list, but hitting Alt+Enter not work. 2nd stage of hair tearing is done.
Well, after get properties window one copying the package name, closes synaptic (of course), go to fill form window ... and see empty text buffer.
3rd final stage of hair tearing arrives.
So the question is, how to avoid 3rd phase of pain and have text buffer not lost when application closes?
I am very sorry for a bit emotional description. Thanks.

A:
dpkg -l compiz* ...and get first phase of hair tearing: name not fully
  shown but shorted.

Try so: dpkg -l compiz* | grep c


text:
Q: How to extract Geojson Schema with spark I have a Geojson file and I want to extract the schema(structtype) correspondent with spark. Any help would be appreciated
I use spark 2.3.1
Geojson:
{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "MultiLineString",
        "coordinates": [
          [
            [
              7.0847794888,
              50.7242091272
            ],
            [
              7.0859976701,
              50.7239505872
            ],
             ...
            [
              7.0946504307,
              50.722884129
            ]
          ]
        ]
      },
      "properties": {
        "strecke_id": 3,
        "auswertezeit": "2018-11-13T16:10:00",
        "geschwindigkeit": 26,
        "verkehrsstatus": "erh�hte Verkehrsbelastung"
      }
    },.....

Thank you for your help

A: val data = spark.read.json("hdfs://........./file.json")
val schema = data.schema

This should give you the schema in StructType


text:
Q: "..." being used in Java?
Possible Duplicate:
Can I pass an array as arguments to a method with variable arguments in Java?
What is … in a method signature

I first saw this when I was modding Minecraft. It had a constructor that specified (String ... line), and thought it was just some shorthand that Mojang had created. But now, I was looking over ProcessBuider, and saw it again. I was wondering what this is used for. My best guess is that it allows developers to add as many of that type of object as they want. But if that's the case, why not just use an Array or List?
So, really, I am asking two questions:

*

*What is the "..." operator, and

*Why would it be more useful than using an Array or List?

A: ... indicates a multiple argument list to a variadic function: a function that can take a variable number of arguments.
For an example of this, look at PrintStream.format. The first (required) argument is a format String, and the remaining 0 or more arguments fulfill that format.

A: It is called varargs, and as you say it is used to be able to let a method be called with any number of arguments of the specified type. It was introduced in Java 5.
You can read more in the Java tutorials - Varargs.

A: This is equivalent to a String[] line. It is Java's equivalent to the varargs keyword in C/C++. Similar to C/C++ it must appear as the last parameter.

A: You've already answered question #1 yourself.  As to why it's more useful, it's just a shorthand that requires less typing.

A: To answer your second question, one advantage of varargs is that you can call a function taking varargs parameter without passing that param. Whereas instead if your function takes in an array, and you need to call it without any value, the caller needs to explicitly pass null.


text:
Q: Access times for different partitions on same hard disk I have partitions, /dev/sda1 and /dev/sda2.
/ is mounted on /dev/sda1, while all other data is on sda2 which has more size allocated to it.
I want to save the virtual machine images (VirtualBox Disk Image)  on sda2.
My question is, should I expect any difference in performance if I access data from the second partition?
tl;dr -- is there is any difference in performance if I have to access data located on a different partition? If yes, does it make sense to decrease seek times by moving data to /dev/sda1?
Please note that this may be one of those micro-optimization issues but I want to squeeze every possible inch of performance I can for the VMs.

A:
My question is, should I expect any difference in performance if I
  access data from the second partition?

Whether or not you see any difference depends on filesystem type and the underlying device.
There should be no noticeable difference if it is the same device, same fstype.
Having the VM on a separate filesystem is certainly useful for backing up by partition or filesystem.
If you were to put the VM filesystem on a separate device, like a an SSD or fast, high RPM HD
Then you might see a noticeable difference.
As always, it depends.
How much activity is taking place on /?
What kind of activity? I/O intensive? Same questions for VM.


text:
Q: What are the advantages/disadvantages of different ways to store structured data in appengine ndb? NDB comes with a lot of property types that can be used for storing structured data:
ndb.StructuredProperty
I can see that this could be useful to store other model instances, in cases where it's not useful to store the model on it's own in app engine.
but there's also the LocalStructuredProperty. The documentation only states that the value is stored a an opaque value, but what advantages does that have?
JSONProperty and PickledProperty
Is human-readability of the data the only  advantage of storing data as JSON?

A: Docstring of class LocalStructuredProperty:

Substructure that is serialized to an opaque blob.
This looks like StructuredProperty on the Python side, but is
  written like a BlobProperty in the datastore.  It is not indexed   and
  you cannot query for subproperties.  On the other hand, the   on-disk
  representation is more efficient and can be made even more   efficient
  by passing compressed=True, which compresses the blob   data using
  gzip.

Json and pickle does not have predefined structure.


text:
Q: Image sizes are incorrect when page is rendered in MS Edge I added Instagram and Facebook links to the navigation menu of this site. On Chrome they are shown in an appropriate size, but the original image sizes are used in Edge, which looks insane

The markup for the social links is

                Facebook

                Instagram

And the CSS which restricts the size of the logos is
.social-link {
    width: 50px;
}

.social-link .menu-label {
    display: none;
}

.social-link img {
    position: relative;
    top: 5px;
}

What changes do I need to make so that the images are shown in the correct size on Edge?
It's difficult for me to resolve this by trial-and-error, because the only computer I have access to is a Mac, which I can't install Edge on.

A: .social-link img {
  position: relative;
  top: 5px;
  width: 1.3em; //


text:
Q: How to release NSManagedObjectContext's retained deletedObjects without saving it I've recently come across a behavior that is pretty much guaranteed to leak objects in a pretty common usage pattern of CoreData:

*

*Saving background contexts to the store

*Having a viewContext automatically merge changes from the store

When the viewContext merges changes, it keeps deleted objects around in its deletedObjects property. These are only cleared when the viewContext saves.
However it's my understanding that one of the objectives of this pattern is having the viewContext be read-only in order to more easily reason about what's going on and avoid conflicts with background contexts.
If there's no other way to deal with this, it seems that any pattern where a merging context is read-only is destined to leak.
Would appreciate any thoughts.


text:
Q: How to prove that $x\csc x <\pi/3$
If $x \in (0,\frac \pi6)$, then using calculus prove that $x\csc x<\frac \pi3$

My attempt:
let $f(x)=\csc x$$$\implies f'(x)=-\frac{\cos{x}}{\sin^2 x}$$ which is less than $0$ for all $x\in (0,\pi/6)$
so, $f'(x)<0$$\implies f(x)$ is decreasing function.
(as we know decreasing function reverses inequality)
$$\csc(0)>\csc(x)>2$$ (notice that inequality is reversed)and since $x$ is positive $$2x<x\csc x<\infty$$but this violates the question  and i am definitely wrong somewhere but i don't know where!
Any
Help will be appreciated :-D

A: Let
$$
f(x) = x \csc (x) = \frac{-2x\sin x}{\cos (2x) - 1},\ x \in ]0, \pi/6 [
$$
$f$ is continous everywhere on the interval, so there exists a max/min.
$$
f'(x) = \frac{-2x \sin (2x) \sin (x)}{(\cos(2x) -1 )^2} - \frac{2 \sin (x)}{\cos (2x) - 1} = -\frac{-2\sin (x)}{\cos (2x) - 1} \left( \frac{x\sin (2x)}{\cos (2x) - 1} + 1  \right) > 0
$$
so $f$ is increasing, max at $x \to \pi/6$ calculating $f(\pi/6) = \pi/3 \Rightarrow$ inequality holds.


text:
Q: Is there an Option in Eclipse to switch how selected lines are displayed? Is there some way to configure the Eclipse Editor
to show only the actual content of
selected lines
rather than the entire editor width?
For example, 2 Screenshots:
_1) this Text in Notepad++
_2) this Text in Eclipse


text:
Q: Different way of declaring a function in C I have come across this C sample code and I have no idea what it means:
#include <stdio.h>

int some_int;

int fun (some_int) int* some_int;
{

 return 0;
}

int main()
{
  return 0;
}

Why is fun declared that way and what does it even mean? I can't understand the syntax.

A: int fun (some_int) int* some_int;
{
   ...
}

is the old (pre ANSI C) way to write this:
int fun (int* some_int)
{
   ...
}

Best you forget about this, unless you need to dig into very old source code.
If you found this in a book, throw it away and get a modern C text book. (Actually don't throw it away but keep it as an antique).
BTW the int some_int; declaration right after #include <stdio.h> is a global variable whose name is totally unrelated to the some_int in the fun function.
This SO article explains it in more details.


text:
Q: Universal class for Mac OS and iOS I want to create a class for a Mac OS- and a iOS-App. Unfortunately, I can't use NSColor for iOS and no UIColor for Mac OS.
Actually I have the following code:
#if os(iOS)
    func myFunc(color: UIColor?) {
        self.myFuncX(color)
    }
#elseif os(OSX)
    func myFunc(color: NSColor?) {
        self.myFuncX(color)
    }
#endif

private func myFuncX(color: AnyObject?) {
    #if os(iOS)
        myColor = color as! UIColor
    #elseif os(OSX)
        myColor = color as! NSColor
    #endif
}

Is there any better way?

A: You should be able to use typealias for the color class, like this:
#if os(iOS)
    typealias XColor = UIColor
#elseif os(OSX)
    typealias XColor = NSColor
#endif

func myFunc(color: XColor?) {
    self.myFuncX(color)
}

The idea is to limit conditional compile to a type definition for XColor, and then using that type alias in place of UIColor or NSColor, as required on the particular system.


text:
Q: Managing SQL schema in F# Because of the presence of type providers for accessing SQL data in F#, there's not much focus on the use of ORMs, micro or otherwise. I can definitely see the logic behind this.
It also seems that many examples of using F# to play with relational data is to plug them into existing large databases, that would appear to be created elsewhere.
It feels like there's a bit of a gap here: is there a nice way to manage schema creation and migration directly from F#? The example linked to above suggests running your manual schema creation script as the first step. Is this the only option?
I've recently started a little project that is F# from the outset, and I'm looking at storing some data in a relational database (sqlite for now). I don't have an existing schema to explore, I'm designing from scratch. Is there a friendlier or more idiomatic way to manage my schema (creation and then migration) in F#?

A: You /can/ use Entity Framework with F#, and therefore get the Migrations API that it comes with, but I've found it very painful in practice - all your entity classes will require member val get set style properties (I believe) and various other bits and pieces. Jamie Dixon did a blog post on this some months ago around the same time I was experimenting with it - I did not enjoy it!
To be honest, although this isn't a great answer for you given what you're asking for i.e. DB schema management in F# - I would recommend that you use something like VS Database Projects to manage your schema outside of your code, and use (yes) either one of the SQL Type Providers to manage data within your application.
If you're dead set on using a "schema migration in code" system, EF plays much better with C# in my experience, so you could experiment theoretically with e.g. a C# / EF data access project referenced by your F# application code.
Sorry.

A: I've been trying to find a solution for this and I'm more and more inclined to try to fall back to the basics when it comes to SQL databases. One of the major parts described in the book Refactoring Databases is migrations. Having a tool that supports working with migrations solves a lot of problems as long as you can accept to write all up and down scripts in plain ol' SQL would probably be very suitable.
One tool I've found for the .NET stack is Rob Reynold's
Roundhouse. I have yet to try it out but it seems promising albeit somewhat dated.


text:
Q: How to share a common file in all lambda functions I have some lambda functions(node.js) in AWS, that will connect to postgresql and doing some query and get the results back, so i am trying to make one configuration file for database which has the user, password, database name, port ... So what will be the best way to share a common configuration file to all lambda function?

A: It is possible to share common files between different Lambda Functions using  Layers. You can create a zip file for the Layer pretty much the same way you do that for a Function.
The layer package will look more or less like this:
your-lambda-layer.zip
└ nodejs/node_modules/shared-package

In the code it can be referenced like this:
const shared = require('shared-package');

The shared-package can contain your code or configurations.

A: AWS Provides two services for this purpose.

*

*AWS Secrets Manager

*AWS Systems Manager Parameter Store
AWS Secrets Manager is the latest service which has version controlled secrets and automatically rotates keys.
You can either store is as individual keys or combine all keys, store them as one key.
Secrets Manager Example:
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SecretsManager.html#getSecretValue-property
var params = {
  SecretId: "MyTestDatabaseSecret",
  VersionStage: "AWSPREVIOUS"
 };
 secretsmanager.getSecretValue(params, function(err, data) {
   if (err) console.log(err, err.stack); // an error occurred
   else     console.log(data);           // successful response
   /*
   data = {
    ARN: "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestDatabaseSecret-a1b2c3",
    CreatedDate: <Date Representation>,
    Name: "MyTestDatabaseSecret",
    SecretString: "{\n  \"username\":\"david\",\n  \"password\":\"BnQw&XDWgaEeT9XGTT29\"\n}\n",
    VersionId: "EXAMPLE1-90ab-cdef-fedc-ba987SECRET1",
    VersionStages: [
       "AWSPREVIOUS"
    ]
   }
   */
 });

Systems Manager Parameter Store:
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SSM.html#getParameter-property
var params = {
  Name: 'STRING_VALUE', /* required */
  WithDecryption: true || false
};
ssm.getParameter(params, function(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});

EDIT1:
For sharing common files from a common storage, it is not possible as now. You can store the file in s3 and pull from there. It is going to have a heavy cold start.

A: Define your shared code in a AWS Lambda Layer using AWS::Lambda::LayerVersion or AWS::Serverless::LayerVersion and then reference to it in your lambda functions. For example with AWS SAM :
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: function_code/
      Handler: app.lambda_handler
      Runtime: nodejs8.10
      Layers:
        - !Ref MySharedLayer
  MySharedLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      LayerName: SharedLayerName
      Description: Some shared code
      ContentUri: layer_code/
      CompatibleRuntimes:
        - nodejs8.10
      LicenseInfo: 'My License'
      RetentionPolicy: Retain

The layer code will be available in the /opt folder and can be included in your lambda functions.


text:
Q: Can't boot on OS X partition after resizing Windows partition I initially had three bootable partitions:

*

*OS X

*Recovery for OS X

*Bootcamp (Windows 8)

Now, on Windows, I decided to make my Windows partition smaller, reducing its size using the native Disk Manager. I did, leaving some unallocated space at the end of the disk. Then I restarted my macbook while holding 'alt' and I was surprised to find only one bootable partition:

*

*Bootcamp (Windows 8)

Confused, I decided to revert my changes by re-expanding my Windows partition to its original size. The disk mapping looks just the same as before, except I still can't boot on OS X or Recovery for OS X, because they aren't displayed at all on Startup Manager of my macbook.

How to fix EFI (or whatever is causing the problem) and boot again on OS X?
[edit: small note, this issue was long time ago... I have reinstalled the whole computer since then]

A: Presumably Windows messed up with your OS X boot code.
You have to rebuild this code.
Since OS X tools can not handle a false flagged partition you have to set the correct partition flag and afterwards rebuild the boot code using OS X Disk Utility.
Since you can't boot from the now unaccessible recovery partition you have to have Linux-tools and a second Mac (accessing your messed up hard disk via target mode 2nd stage) or a OS X install DVD/USB-key by the hand.
Let's go:
Download the latest gParted iso file here: gParted
Burn the iso to a CD or transfer it using the tool of your choice to a USB drive.
For help to create a gParted Live-USB look here: Live-USB
Boot your Mac using gParted-Linux.
Go to the gParted-tool.
(First window will be opened automagically on the desk.)
Select the (probably your first) HFS+ partition and do the right click.
Be aware, this is not the first 200 MB EFI-partition!!!
Now edit the partition info.

*

*Tick the square for the msft-type.

*Remove the mark. Do not mark any of the available marks.

*Write out the changes.
Leave the tool and reboot into a OS X-Install-DVD or prepared OS X install-USB-key (or as forementioned connect your dead Mac-HDD to the other Mac via Firewire or TB now accessing the disk in target mode)
Open OS X Disk Utility.

*

*Tick on the Apple HDD, let Disk Utility repair the partition layout.

*Check the OS X-partition too and reboot into your OS X again.
Hold the alt-key and choose the OS X boot volume.
Be happy.
for background stuff from the sources please check search for:

*

*Apple tech notes

*steelpangolin
or search for "apple tech notes tn2166" or "steelpangolin invalid-bs_jmpboot-in-boot-block-000000/"
Update:

*

*this is for hdd that has NO hybrid partition only, sorry otherwise this is not for you

*please be prepared prior to any further coming desaster

so

*

*make a bootable copy of the stock or newly installed OSX (minimum space required ca. 10GB) to an external drive

or

*

*create a bootable setup-stick of the setup-image (contained in any OSX Install.app)
This will speed up the recovery and makes you more independent from huge downloads  esp. over slow lines.

A: May I recommend trying rEFIt? It's a boot loader for EFI partition tables. You can put it on a USB stick and boot from there - it may be able to recognise the OS X partition or otherwise repair your EFI table.
You can download rEFIt here.

A: *

*Reboot the Mac into Single User Mode by holding Command+S during boot

*At the command prompt, type:
/sbin/fsck -fy

*When fsck is complete, type "exit" or "reboot" to reboot

*Boot the Mac as usual, verify the disk again in Disk Utility, and partition as usual


text:
Q: Is it possible to stringify parameters in ruby/irb? I'm new to ruby ... wondering if the following is possible:
I currently run a test app within irb (irb -r test.rb) and manually execute
various command implemented in test.rb.  One of these functions is currently implemented as follows:
def cli(cmd)
  ret=$client.Cli(cmd)
  print ret, "\n"
end

Where $client.Cli() takes a string.  I currently type the following in the IRB prompt
> cli "some command with parameters"
This is sent over socket and results are returned
I would like to be able to do this WITHOUT the quotes.  This would be just for this command
Is there a way to do this generally in ruby?  if not how would you extend irb to do this?
For those who know 'C' this would be like the following:
#define CLI(CMD) cli(#CMD)
CLI(Quadafi and Sheen walk into a bar...)

where the pre-processed output is:
cli("Quadafi and Sheen walk into a bar...")

Thanks

A: You could actually monkey patch the gets method of the IRB::StdioInputMethod and IRB::ReadlineInputMethod classes, and perform a rewrite if the cli method is called, by adding the following to your test.rb file:
module IRB
  def self.add_quotes(str)
    str.gsub(/^cli (..+?)(\\+)?$/, 'cli "\1\2\2"') unless str.nil?
  end

  class StdioInputMethod
    alias :old_gets :gets

    def gets
      IRB::add_quotes(old_gets)
    end
  end

  class ReadlineInputMethod
    alias :old_gets :gets

    def gets
      IRB::add_quotes(old_gets)
    end
  end
end

This way, any input line matching cli ... will be replaced with cli "..." before it's evaluated.

A: I don't think it's possible, because the command that you type to irb has to parse as ruby, and all those bare words will report errors like this:
NameError: undefined local variable or method `hello' for main:Object

(My first attempt, I just called it via cli hello.)
But if you didn't mind a more radical change, you could do something like this:
$ cat /tmp/test_cases
hello world
one
two
three
riding the corpse sled

$ ruby -e 'def f(arg) puts arg end' -ne 'f($_)' < /tmp/test_cases
hello world
one
two
three
riding the corpse sled

I just defined a simple function f() here that would show how it works; you could replace f($_) with $Client.cli($_), and set up the $Client global variable in the first -e argument. And you can leave off the < /tmp/test_cases if you want to type them in interactively:
$ ruby -e 'def f(arg) puts arg end' -ne 'f($_)'
hello
hello
world
world

Of course, if you want it to be any more advanced than this, I'd just write a script to do it all, rather than build something hideous from -pe or -ne commands.


text:
Q: Can not access webserver started by running gruntscript in jenkins I am trying to set up a webserver using jenkins but I am failing misserably.
I have a gruntfile which creates a webserver on

hostname: '0.0.0.0'
port: 8000

When running it locally on my computer, this works perfectly. Now I have to add this job to jenkins. The job I run is an infinite job so I run it in the background like suggested here. Except for the fact that I am working with a windows server
When I run the gruntscript through jenkins, I get the following output:
Waiting forever...
Started connect web server on http://localhost:8000
But when I go to http://%jenkinsserver%:8000 I don't get anything. I am sure there is something running on that port. At first I thought there were some issues with the firewall, but after accessing the server directly, I still could not find the webpage.
Thanks for your help!


text:
Q: How to create a Oozie workflow using restful instead of Editor UI? Normally, we create an oozie workflow using the Editor UI such as:

The workflow could also be exported into a json file and import by a json file too. Could someone tell me, there is a way to import/create a workflow with json file and restful(using python, java, c++ or any other language).

A: When I create a new workflow, I specify "HDFS deployment directory".editor and remove the need to manually edit the XML. Romain.


text:
Q: Why can't I simply overwrite < in a priority queue of pairs? I'm aware that I can just do priority_queue < P, vector<P>, Compare > queue;, where Compare is a functor. But since the default comparator is less<P>, and it is the same as <, why doesn't it work when I do the following:
typedef pair<int, int> P;

bool operator<(const P& a, const P& b){
    return (a.second < b.second);
}

int main(int argc, char const *argv[]){
    int vec[] = {3, 6, 7, 8, 1, 2}; // just for testing
    priority_queue <P> queue;
    for(int i = 0; i < 6; ++i){
        queue.push(make_pair(i, vec[i]));
    }
    cout << queue.top().second << endl; // returns 2
    return 0;
}

A: std::pair already has an operator< declared inside namespace std.
As this is in the same namespace as pair,  std::less will find that one first and then not look any further.

A: This is the correct way to do this:
#include <utility>
#include <queue>
#include <vector>
#include <iostream>

using namespace std;

typedef pair<int, int> P;

struct comp {
    bool operator()(const P& a, const P& b){
        return (a.second < b.second);
    }
};

int main(int argc, char const *argv[]){
    int vec[] = {3, 6, 7, 8, 1, 2}; // just for testing
    priority_queue <P, std::vector<P>, comp> queue;
    for(int i = 0; i < 6; ++i){
        queue.push(make_pair(i, vec[i]));
    }
    cout << queue.top().second << endl; // returns 2
    return 0;
}

A: namespace std {
    bool operator<(const P& a, const P& b) {
        return (a.second < b.second);
    }
}

and it work for me
UPD:
We can define own type for safeness:
class MyOwnPair: public std::pair<int,int>{};
typedef MyOwnPair P;


text:
Q: Capture and play voice with Asterisk ARI There are Channel ARI Demo in wich we can control channel state: ring, answer, play silence, play some tone or audio-file (https://github.com/asterisk/ari-examples/tree/master/channel-state, https://wiki.asterisk.org/wiki/display/AST/ARI+and+Channels%3A+Manipulating+Channel+State)
Is it possible to receive some chunks (parts, buffers, etc.) of call voice (which are created by remote subscriber) or write chunks of voice, for example like a some array of bytes (not from file) in some audio format (alaw, ulow etc).

A: You can use asterisk EAGI interface to get voice data.
Other option is use Record or Mixmonitor app for record channel(channel have be put to Stasis to allow dialplan control by ARI)
"Write chunks of voice" can be done by application Playback
Also you can create your own application using c/c++, compile it into asterisk and get result you want.
No, you can't redirect voice directly using ARI.


text:
Q: Configuring grouped summing behavior on Pandas Dataframe Python/Pandas here. I have a DataFrame (input_df) with the following columns/data:
Id | Name | Amount | Term | NumDays
-----------------------------------
1  | Joe  | 5.50   | 6    | 20
2  | Jon  | 7.85   | 10   | 11
3  | Mac  | 2.18   | 4    | 19
1  | Joe  | 15.40  | 12   | 154
2  | Jon  | 1.95   | 70   | 2019
1  | Joe  | 8.24   | 55   | 8
2  | Jon  | 11.10  | 32   | 29
...

I need to collapse/condense/aggregate/sum this DataFrame by Name, in such a way that:

*

*Amounts get summed

*Terms get summed

*NumDays get summed

*I don't care about any other columns

Hence after the aggregation the DataFrame would look like:
Id | Name | Amount | Term | NumDays
-----------------------------------
1  | Joe  | 29.14  | 73   | 182
2  | Jon  | 20.90  | 112  | 2059
3  | Mac  | 2.18   | 4    | 19

I know there is an input_df.sum() available to me, but I'm not understanding how to configure it such that the aggregation is based on or grouped by Name and that the only columns I care about are Amount, Term and NumDays. Can anyone point me in the right direction?


text:
Q: How to customize validation messages in Django I would like to know how to customize the Validation message when using UniqueConstraint to create unique constraints on multiple columns (including foreign keys) of Model in Django.
In Django, I am creating a system for parents to apply for school lunches for their children. An account exists for each parent, and one or more children are associated with one parent. When parents log in to the school lunch application screen, select their child and date, and press the school lunch application button to complete the application. The validation of this application form did not go well.
We use UniqueConstraints for multiple columns (child, date) in the Lunch model to avoid duplicate lunch requests for the same child on the same date. By default, the error message is confusing, so I tried to change the validation message, but it didn't work.
Specifically, I created check_duplicate as a class method in the Lunch model and called it from the clean method of the form (ModelForm). At this time, both the validation message that I created and the default message are displayed on the actual screen.
・Message I created (child has already applied for yyyy/mm/dd school lunch.)
・Default message (Lunch with this child and date already exists.)
I want the validation message displayed on the screen below to be only the message I created.
source code
# models.py
from django.db import models
from django.utils.timezone import now
from django.contrib.auth import get_user_model
User = get_user_model()

class Child(models.Model):
    name = models.CharField(max_length=128)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

class Lunch(models.Model):
    child = models.ForeignKey(Child, on_delete=models.CASCADE)
    date = models.DateField(default=now)

    class Meta:
       constraints = [
           models.UniqueConstraint(fields=['child', 'date'],
           name='unique_lunch_application',
           )
       ]

    @classmethod
    def check_duplicate(cls, child, date):
        return cls.objects.filter(child=child, date=date).exists()

# forms.py
from django import forms
from .models import Child, Lunch
from django.core.exceptions import ValidationError
from django.utils.translation import gettext as _
from django.contrib.auth import get_user_model
User = get_user_model()

class LunchForm(forms.ModelForm):
    class Meta:
        model = Lunch
        fields = ('child', 'date',)

    def __init__(self, user, *args, **kwargs):
        super(LunchForm, self).__init__(*args, **kwargs)
        self.fields['child'].queryset = Child.objects.filter(user=user)

    def clean(self):
        cleaned_data = super().clean()
        child = cleaned_data.get('child')
        date = cleaned_data.get('date')
        if Lunch.check_duplicate(child=child, date=date):
            _validation_messsage = f'{child} has already applied for {date} school lunch.'
            raise ValidationError(
                _(_validation_messsage), code="duplicated_lunch_application"
                )
        return cleaned_data

# views.py
from django.shortcuts import render, redirect
from .models import Child, Lunch
from .forms import LunchForm
from django.contrib.auth import get_user_model
User = get_user_model()
def lunch(request):
    if request.method == 'POST':
        form = LunchForm(request.user, request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('another view name')
    else:
        form = LunchForm(user=request.user)
    return render(request, 'members/lunch.html', {'form': form})  # Urls are defined in urls.py.

<form action="" method="POST">
    {{ form.non_field_errors }}
    {% for field in form %}

            {{ field.label_tag }}
            {{ field }}
            {% if field.help_text %}
                {{ field.help_text }}
            {% endif %}
            {{ field.errors }}

    {% endfor %}

        <button type="submit">apply lunch</button>

    {% csrf_token %}
</form>

tried
I found that the following implementation using Form instead of ModelForm works fine with other parts as is. (default validation message is not displayed)
However, this time, the child column has to work as a foreign key, so it has not been resolved.
It seems necessary to solve it in another way while using ModelForm, or to incorporate foreign keys in Form.
# forms.py
from django import forms
from .models import Child, Lunch
from django.core.exceptions import ValidationError
from django.utils.translation import gettext as _
from django.contrib.auth import get_user_model
User = get_user_model()

class LunchForm(forms.Form):
    child = forms.CharField(max_length=16)  # ←Actually, this part is a foreign key, so I can't write it like this.
    date = forms.DateField()

    def __init__(self, user, *args, **kwargs):
        super(LunchForm, self).__init__(*args, **kwargs)
        self.fields['child'].queryset = Child.objects.filter(user=user)

    def clean(self):
        cleaned_data = super().clean()
        child = cleaned_data.get('child')
        date = cleaned_data.get('date')
        if Lunch.check_duplicate(child=child, date=date):
            _validation_messsage = f'{child} has already applied for {date} school lunch.'
            raise ValidationError(
                _(_validation_messsage), code="duplicated_lunch_application"
                )
        return cleaned_data

version information
python 3.9.13
Django 4.1

A: Use forms.validationerror instead of plain validationerror
like this...
raise forms.ValidationError(f"{child} has already applied for {date} school lunch.")

i think it's should be work...


text:
Q: Cannot execute binary file on Linux server I'm currently trying to run Knime (a Java-based program) on a Linux server, and every time I try to execute the file (knime) it gives me a "cannot execute binary file" error. I've posted the relevant information below.
  uname -a
     Linux safar 2.6.32-5-amd64 #1 SMP Sun Sep 23 10:07:46 UTC 2012 x86_64 GNU/Linux

  ls -al knime_2.6.3
     drwxrwxr-x 10 **** **** 4096 Nov 28 23:18 knime_2.6.3

  ls -al /knime_2.6.3/knime
     -rwxrwxrwx 1 **** ***** 71162 Oct 15 15:11 knime

For reference, the file's name is "knime" and it's within the "knime_2.6.3" folder. There are other files within that folder pertinent to Knime (which I can post information about if necessary) but the Readme simply says to execute knime. Here's the error:
  . knime
       -bash: .: knime: cannot execute binary file

I'm not really experienced with Linux, so any help would be appreciated. Thank you!

A: May be this file belong to different architecture like you are trying to run a x86 binary on a ppc system.
You can check this by using 'ldd' command for e.g.
ldd /knime_2.6.3/knime


text:
Q: Repeating steps based on different field using ModelBuilder? I have built a model to interpolate air pollution from 40 recording stations using IDW.
The results are then exported to an average for census divisions.
I need to repeat this process hundreds of times for every month for 15 years for five different types of air pollution.
I have all of the data by year as a new field in the recording stations' file.
Table:
Recording_Station 03jan 03feb 03mar 03apr 03may 03jun 03jul ....
1                  26.5 27.5  22.2  32.3  34.5  45.4  55.4
2                  19.1 12.2  45.3  33.3  36.6  55.4  65.5
3                  11.1 15.6  44.4  34.4  66.6  55.4  44.6

etc.
How can I re-run the model for every field without manually changing them each time?

A: There is not an Iterate Fields tool in ModelBuilder.
I can think of two possible workarounds:

*

*Modify the model to run as a Python script. Define a list of the fields you want to use, and define a loop to go through each one and execute the IDW/export functions.
I would go with this one personally, but it would be (much) easier with some Python knowledge.
An example of iterating through the fields list:
fields = ['03jan', '03feb', '03mar'] # etc.
for field in fields:
    # your existing IDW Python code here
    # replace any instances of specific field name e.g. "03jan"
    # with the variable *field*

Once you're satisfied that works, you can automatically generate a list of all fields in a feature class using the arcpy ListFields function. Make sure that you're not including Recording_Station in the fields you iterate over (which would cause weird results, and potentially crashing):
fields = ListFields(yourFeatureClass)
fields.remove('Recording_Station') # repeat for any other fields you don't need
for field in fields:
    # your existing IDE Python code here [etc.]

*Set the field name as a model parameter within your ModelBuilder. Use batch processing to execute the tool hundreds of times automatically.
This is more tedious, since you will have to manually enter (hundreds of times...!) the field names in the batch parameters, but it does allow you to run the analysis multiple times without significantly altering the model or needing to know any Python.

A: Seems like you need to nest iterators; this can only be done by placing one model within another. It is kind of pain to do, but can be done. Your inner model will run the IDW and summarize. Your outer model will feed which columns to base the IDW on. The outer model will do so by selecting column names from a list you will create, and then iterating over that list. You create the list by opening the dbf of the shapefile, copying the column labels from it, copy-paste (transpose) into Excel. Then, use 'eliminate duplicates' in Excel to make sure the names are all unique. Then save that excel as a CSV. Add that CSV to the out model. Add an iterator-(iterate by list). Call the output of that list 'fieldname' or the like.

A: You could explore using the batch processing function on the model. Right click (see image below) the model in your toolbox and select 'Batch'. From there you can add multiple instances and each will run through the model. Unfortunately, I am not aware of any way to easily enter the content into 'Add Row'. Thus, you would be required to enter the hundreds of records for each month.

A: Maybe try to iterate through all the fields using the "Iterate Field" tool in Model Builder.
It will do all the fields in a feature clase.


text:
Q: NestJS - TypeORM - Unable to track the Entity Not Found in TypeOrm & Nest.JS No repository for "UserEntity" was found. Looks like
this entity is not registered in current "default" connection? +114ms
RepositoryNotFoundError: No repository for "UserEntity" was found. Looks like this entity is not registered in current "default" connection?
    at RepositoryNotFoundError.TypeORMError [as constructor] (E:\Projects\...\src\error\TypeORMError.ts:7:9)

This is a Seed Method. It runs fine and add the data in the database, after adding data, I just get the error.
import { MediaEntity } from '../entities/media.entity';
import { Connection, Equal } from 'typeorm';
import { UserEntity } from '../entities/user.entity';
import { Helper } from '../services/helper';

export default async function UsersSeed(connection: Connection) {
  const repository = connection.getRepository(UserEntity);

  const data: Partial<UserEntity> = {
    firstName: 'tesFName',
    lastName: 'testLNsmr',
    password: 'fafafa',
    email: 'testmail@mail.com',
    createdAt: Helper.dateToUTC(new Date())
  };

  let user = await repository.findOne({ email: data.email });

  console.log("19");
  console.log(user);

  if (!user) {
    const entity = Helper.createEntity(UserEntity, data);
    console.log("23");
    user = await repository.save(entity);
    console.log("25");
  } else {
    console.log("27");
    await repository.update(user.id, {
      firstName: data.firstName,
      lastName: data.lastName
    });

    console.log("33");
  }

  console.log("36");

  const mediaRepository = connection.getRepository(MediaEntity);
  await mediaRepository.update({ user: Equal(null) }, { user: user });

  return user;
}

A bit more context:
It is being imported in app.module.ts as this.
@Module({
  imports: [
    ServeStaticModule.forRoot({
      rootPath: join(__dirname, 'uploads')
    }),
    TypeOrmModule.forRootAsync({
      useFactory: async (optionsService: OptionsService) =>
        optionsService.typeOrmOptions(),
      imports: [OptionsModule],
      inject: [OptionsService]
    }),
    OptionsModule,
    MediaModule,
    AuthModule,
    PlaceModule,
    RepositoryModule,
    ServicesModule
  ],
  controllers: [],
  providers: []
})

And then there is src/entities/entities.module.ts as:
const entities = [
  UserEntity,
  MediaEntity,
  PlaceEntity,
  DownloadRestrictionEntity,
  MediaInfoEntity
];

@Module({
  imports: [TypeOrmModule.forFeature(entities)],
  exports: [TypeOrmModule.forFeature(entities)]
})
export class EntitiesModule {
}

Then src/options/options.service.ts as
@Injectable()
export class OptionsService {
  constructor(
    private service: ConfigService<IEnvironmentVariables>
  ) {
  }
 public typeOrmOptions(): TypeOrmModuleOptions {
    const environment = process.env.NODE_ENV ? process.env.NODE_ENV : '';
    const directory = this.directory();
    return {
      type: 'postgres',

      host: this.service.get('POSTGRES_HOST'),
      port: this.service.get('POSTGRES_PORT'),
      username: this.service.get('POSTGRES_USER'),
      password: this.service.get('POSTGRES_PASSWORD'),
      database: this.service.get('POSTGRES_DATABASE'),
      synchronize: false,
      migrationsRun: this.service.get('RUN_MIGRATIONS'),
      keepConnectionAlive: this.isTest(),

      entities: [`${directory}/**/*.entity${environment ? '{.ts,.js}' : '{.js, .ts}'}`],

      migrationsTableName: 'migrations',
      migrations: [`${directory}/migrations/*.ts`],

      cli: {
        migrationsDir: 'src/migrations'
      }
    }
  }
}

A: please create UserRepository typeorm-repository-pattern
Method 1:
@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {}
}

Method 2: use BaseRepository from typeorm-transactional-cls-hooked
@EntityRepository(UserAdminEntity)
export class UserAdminRepository extends BaseRepository<UserAdminEntity> {}


text:
Q: Constructing a Complex SQL Query with Joins Sorry for the nondescript title but I'm not sure how to phrase the question. Say we have the following tables:
    people
    id|created_at|updated_at|name             |
    --|----------|----------|-----------------|
     1|          |          |Quentin Tarantino|
     2|          |          |Terry O'Quinn    |
     3|          |          |Sam Jackson      |
     4|          |          |Michael Madsen   |
     5|          |          |Bryan Cranston   |

    crew_members
    id|created_at|updated_at|type    |
    --|----------|----------|--------|
     1|          |          |Actor   |
     2|          |          |Director|
     3|          |          |Writer  |

    movies
    id|created_at|updated_at|title         |
    --|----------|----------|--------------|
     1|          |          |Pulp Fiction  |
     2|          |          |Reservoir Dogs|

    series
    id|created_at|updated_at|title             |
    --|----------|----------|------------------|
     1|          |          |Lost              |
     2|          |          |Breaking Bad      |
     3|          |          |The Tarantino Show|

    credits
    id|created_at|updated_at|person_id|character   |crew_member_id|
    --|----------|----------|---------|------------|--------------|
     1|          |          |        1|            |             2|
     2|          |          |        1|Jimmy       |             1|
     3|          |          |        1|            |             3|
     4|          |          |        2|John Locke  |             1|
     5|          |          |        3|Jules       |             1|
     6|          |          |        4|Mr Blonde   |             1|
     7|          |          |        5|Walter White|             1|
     8|          |          |        1|Mr Brown    |             1|
     9|          |          |        1|Himself       |             1|

    credit_feature_person
    id|created_at|updated_at|person_id|credit_id|movie_id|series_id|
    --|----------|----------|---------|---------|--------|---------|
     1|          |          |        1|        1|       1|        0|
     2|          |          |        1|        2|       1|        0|
     3|          |          |        1|        3|       1|        0|
     4|          |          |        1|        1|       2|        0|
     5|          |          |        1|        8|       2|        0|
     6|          |          |        1|        3|       2|        0|
     7|          |          |        2|        4|       0|        1|
     8|          |          |        3|        5|       1|        0|
     9|          |          |        4|        6|       2|        0|
    10|          |          |        5|        7|       0|        2|
    11|          |          |        1|        9|       0|        3|

If I want to show all movies a person (say, Tarantino with id 1) was involved in, plus what they did in that movie, I can do this:
    select m.title as movie, coalesce(character,type) as role
    from "credits"
    inner join "credit_feature_person" on "credits"."id" = "credit_id"
    inner join "people" on "credit_feature_person"."person_id" = "people"."id"
    inner join "movies" m on "credit_feature_person"."movie_id" = "m"."id"
    inner join "crew_members" on "credits"."crew_member_id" = "crew_members"."id"
    where "credits"."person_id" = 1;

    //result
         movie      |   role
    ----------------+----------
     Pulp Fiction   | Director
     Pulp Fiction   | Jimmy
     Pulp Fiction   | Writer
     Reservoir Dogs | Director
     Reservoir Dogs | Mr Brown
     Reservoir Dogs | Writer
    (6 rows)

But I also want to include the series they worked on too, and the result to look like

         title      |   role
    ----------------+----------
     Pulp Fiction   | Director
     Pulp Fiction   | Jimmy
     Pulp Fiction   | Writer
     Reservoir Dogs | Director
     Reservoir Dogs | Mr Brown
     Reservoir Dogs | Writer
    The Tarantino Show | Himself
    (7 rows)

I keep trying different things and either get syntax errors or 0 results. Any ideas? I expected to at least be able to do this:
    select coalesce(m.title, s.title) as title, coalesce(character,type) as role
    from "credits"
    inner join "credit_feature_person" on "credits"."id" = "credit_id"
    inner join "people" on "credit_feature_person"."person_id" = "people"."id"
    inner join "movies" m on "credit_feature_person"."movie_id" = "m"."id"
    inner join "series" s on "credit_feature_person"."series_id" = "s"."id"
    inner join "crew_members" on "credits"."crew_member_id" = "crew_members"."id"
    where "credits"."person_id" = 1;

But this doesn't work either, it returns zero results for some reason.
Edit:
Solution is to use left joins on movies and series
select coalesce(m.title,s.title) as title, coalesce(character,type) as role
from "credits"
inner join "credit_feature_person" on "credits"."id" = "credit_id"
inner join "people" on "credit_feature_person"."person_id" = "people"."id"
left join "movies" m on "credit_feature_person"."movie_id" = "m"."id"
left join "series" s on "credit_feature_person"."series_id" = "s"."id"
inner join "crew_members" on "credits"."crew_member_id" = "crew_members"."id"
where "credits"."person_id" = 1;

A: The problem is that the links to movies and series are mutually exclusive. When you attempt an inner join to the one side that's missing each of the rows is eliminated from the results. Those two joins need to be left outer joins.
select coalesce(m.title, s.title) as title, coalesce(character,type) as role
from "credits"
    inner join "credit_feature_person" on "credits"."id" = "credit_id"
    inner join "people" on "credit_feature_person"."person_id" = "people"."id"
    inner join "crew_members" on "credits"."crew_member_id" = "crew_members"."id"
    left outer join "movies" m on "credit_feature_person"."movie_id" = "m"."id"
    left outer join "series" s on "credit_feature_person"."series_id" = "s"."id"
    where "credits"."person_id" = 1
order by title, role;

http://sqlfiddle.com/#!15/45440/5


text:
Q: Getting Blob ID from files If I have a repository  given at  commit ffded2bb9b398af20fbc2f3e11c74b546f4c9764
I would like to get the blob ID of all the files in a given folder (and possible sub-folder) using bash. But I don't understand how.
As I am new with blob, I didn't understand the online manual.

A: Few options:
git ls-tree

git-ls-tree - List the contents of a tree object

git ls-tree ffded2bb9b398af20fbc2f3e11c74b546f4c9764

git log
# get the tree (%T) object of the given commit
git log ffded2bb9b398af20fbc2f3e11c74b546f4c9764 -1 --pretty=%T

git diff-tree

git-diff-tree - Compares the content and mode of blobs found via two tree objects

# Get the SHA-1 of the files in the given commit
git diff-tree ffded2bb9b398af20fbc2f3e11c74b546f4c9764


text:
Q: How do I flip a bit using bitwise operator for an int in TSQL? I have a flags column in sql which is an int.
I need to set a bit in the flag with a SQL statement. The corresponding C++ statement looks something like flags &= ~(unsigned long) (0x10000000).
I tried to do
update [Databases]
 set flags = flags & ~0x10000000

but i get a
Operand data type varbinary is invalid for '~' operator.

Then I tried to see what the convert function would yeild
select flagInt = CONVERT(int , 0x10000000)

gives me 268435456.
select flagIntInvert = ~CONVERT(int , 0x10000000)

gives me  -268435457
which is the same as the signed int
flag    268435456   int
        ~flag   -268435457  int

However I need the unsigned versions
(uint32)flag    268435456   unsigned long
~(uint32)flag   4026531839  unsigned long

Is there a way to set the flag to be the inversion of 0x10000000?
Thanks.

A: Setting the inversion of the flag can be used but applying the bitwise NOT operator ~.
The int in SQL Server is an signed int.
From what I can see you want to active a bit in an integer and that can be done using the following statements.
Assume you are having an integer with value 1, i.e. the first bit is active.
DECLARE @Value int = 1;

And you want to active the third bit you use the or-operator (|) as below:
SET @Value = @Value | 4;

This will render the value 5 of the int variable.
SELECT @Value;

If you then want to check if the third bit is set in use the following, which will filter of all other active bits:
SELECT @Value & 4

And if you want to use it in comparing use the following statement:
IF @Value & 4 = 4 ...

Hope this helps.


text:
Q: What do these symbols mean in Season 2 of The Witcher? In the second season of The Witcher each episode has a symbol what does these symbols represent?

A: Note: as with the nature of explaining the symbols there is going to be a lot of spoilers and they are unmarked. Read at your own risk.
1. A Grain of Truth

Click image to enlarge.
This symbol shows a hooded winged creature. Undoubtedly this is referring to Vereena, the bruxa that features with Nivellen as a major part of episode involving Geralt and Ciri. The wings/claws refer to her being a bruxa (a type of vampire) and the hooded part because Nivellen keeps her hidden and tells the two that she's a cat.
Similarly, in the story it was adapted from with the same name in The Last Wish Nivellen tells Geralt that Vereena is rusalka to hide her true nature from him.
2. Kaer Morhen

Click image to enlarge.
This symbol shows a Witcher's medallion, which looks to be the one belonging to Eskel. In the episode Eskel is infected by a Leshy and eventually all but turns into one before being killed. The roots sprouting from the Witcher medallion in the logo symbolise this.

Click image to enlarge.
3. What is Lost

Click image to enlarge.
I'm not really overly sure what this symbol is referring to. In the books the Swallow is Ciri's symbol though that's yet to be shown in the Netflix series. We do have a large focus on Ciri's training here and how she keeps getting knocked down and powers through to better herself. We also see her focusing on her power a bit more to hunt down the Leshy.
The title of the episode though presumably focuses on a few other things. Yennefer has lost her powers and we see Tiss spot this. We also see those at Aretuza having a memorial for the sorceresses that were lost in the Battle of Sodden. And of course at Kaer Morhen there is some focus on losing Eskel to the Leshy and putting him to rest.
4. Redanian Intelligence

Click image to enlarge.
The symbol being a cloak and dagger along with the title are referring to Sigismund Dijkstra the head of the Redanian Intelligence. He is introduced in this episode and promptly sets about doing spy stuff.
We also meet the Sandpiper who turns out to be Jaskier who is doing cloak and dagger actions as well.
It's also worth noting that the dagger looks like the one that Voleth Meir used to kill Klef before the other Witchers imprisoned her. I'm not sure what this means other than her constant presence in the background in this episode.
5. Turn Your Back

Click image to enlarge.
Again I'm not quite sure what this refers to in this particular episode. However, a major theme in this season is that everything should be in balance and it's hard to keep it that way. Towards the end of the episode this tips out of favour with a monster coming through a portal in the monolith at Cintra.
6. Dear Friend

Click image to enlarge.
This symbol shows a hand turning into flames and is clearly referring to Rience who is quite the accomplished fire mage and causes quite a stir in this episode. First he attacks Vesemir and Triss in Kaer Morhen and then Geralt, Yennefer and Ciri at the Temple of Melitele.
7. Voleth Meir

Click image to enlarge.
This shows a skull, blindfolded and mouth open, and appears to reference Voleth Meir herself. The episode is pretty heavily focused on her behind the scene and ends with her being set loose.
8. Family

Click image to enlarge.
This episode is focused quite heavily around family, losing and gaining, so the title is pretty apt. The symbol appears to be the Medallion Tree at Kaer Morhen which plays a pretty pivotal role when Voleth Meir cracks it in half revealing a monolith underneath. Pretty much the whole episode involving Geralt and Ciri takes place at the base of the tree.


text:
Q: Copy array to struct array as fast as possible in C# I am working with Unity 4.5, grabbing images as bytes arrays (each byte represent a channel, taking 4 bytes per pixel (rgba) and displaying them on a texture converting the array to a Color32 array, using this loop:
   img = new Color32[byteArray.Length / nChannels]; //nChannels being 4
   for (int i=0; i< img.Length; i++) {
        img[i].r = byteArray[i*nChannels];
        img[i].g = byteArray[i*nChannels+1];
        img[i].b = byteArray[i*nChannels+2];
        img[i].a = byteArray[i*nChannels+3];
    }

Then, it is applied to the texture using:
tex.SetPixels32(img);

However, this slows down the application significantly (this loop is executed on every single frame), and I would like to know if there is any other way to speed up the copying process. I've found some people (Fast copy of Color32[] array to byte[] array) using the Marshal.Copy functions in order to do the reverse process (Color32 to byte array), but I have not been able to make it work to copy a byte array to a Color32 array. Does anybody know a faster way?
Thank you in advance!

A: This code requires unsafe switch but should be fast. I think you should benchmark these answers...
var bytes = new byte[] { 1, 2, 3, 4 };

var colors = MemCopyUtils.ByteArrayToColor32Array(bytes);

public class MemCopyUtils
{
    unsafe delegate void MemCpyDelegate(byte* dst, byte* src, int len);
    static MemCpyDelegate MemCpy;

    static MemCopyUtils()
    {
        InitMemCpy();
    }

    static void InitMemCpy()
    {
        var mi = typeof(Buffer).GetMethod(
            name: "Memcpy",
            bindingAttr: BindingFlags.NonPublic | BindingFlags.Static,
            binder:  null,
            types: new Type[] { typeof(byte*), typeof(byte*), typeof(int) },
            modifiers: null);
        MemCpy = (MemCpyDelegate)Delegate.CreateDelegate(typeof(MemCpyDelegate), mi);
    }

    public unsafe static Color32[] ByteArrayToColor32Array(byte[] bytes)
    {
        Color32[] colors = new Color32[bytes.Length / sizeof(Color32)];

        fixed (void* tempC = &colors[0])
        fixed (byte* pBytes = bytes)
        {
            byte* pColors = (byte*)tempC;
            MemCpy(pColors, pBytes, bytes.Length);
        }
        return colors;
    }
}

A: Yes, Marshal.Copy is the way to go. I've answered a similar question here.
Here's a generic method to copy from struct[] to byte[] and vice versa
private static byte[] ToByteArray<T>(T[] source) where T : struct
{
    GCHandle handle = GCHandle.Alloc(source, GCHandleType.Pinned);
    try
    {
        IntPtr pointer = handle.AddrOfPinnedObject();
        byte[] destination = new byte[source.Length * Marshal.SizeOf(typeof(T))];
        Marshal.Copy(pointer, destination, 0, destination.Length);
        return destination;
    }
    finally
    {
        if (handle.IsAllocated)
            handle.Free();
    }
}

private static T[] FromByteArray<T>(byte[] source) where T : struct
{
    T[] destination = new T[source.Length / Marshal.SizeOf(typeof(T))];
    GCHandle handle = GCHandle.Alloc(destination, GCHandleType.Pinned);
    try
    {
        IntPtr pointer = handle.AddrOfPinnedObject();
        Marshal.Copy(source, 0, pointer, source.Length);
        return destination;
    }
    finally
    {
        if (handle.IsAllocated)
            handle.Free();
    }
}

Use it as:
[StructLayout(LayoutKind.Sequential)]
public struct Demo
{
    public double X;
    public double Y;
}

private static void Main()
{
    Demo[] array = new Demo[2];
    array[0] = new Demo { X = 5.6, Y = 6.6 };
    array[1] = new Demo { X = 7.6, Y = 8.6 };

    byte[] bytes = ToByteArray(array);
    Demo[] array2 = FromByteArray<Demo>(bytes);
}

A: Using Parallel.For may give you a significant performance increase.
img = new Color32[byteArray.Length / nChannels]; //nChannels being 4
Parallel.For(0, img.Length, i =>
{
    img[i].r = byteArray[i*nChannels];
    img[i].g = byteArray[i*nChannels+1];
    img[i].b = byteArray[i*nChannels+2];
    img[i].a = byteArray[i*nChannels+3];
});

Example on MSDN

A: public Color32[] GetColorArray(byte[] myByte)
{
    if (myByte.Length % 1 != 0)
       throw new Exception("Must have an even length");

    var colors = new Color32[myByte.Length / nChannels];

    for (var i = 0; i < myByte.Length; i += nChannels)
    {
       colors[i / nChannels] = new Color32(
           (byte)(myByte[i] & 0xF8),
           (byte)(((myByte[i] & 7) << 5) | ((myByte[i + 1] & 0xE0) >> 3)),
           (byte)((myByte[i + 1] & 0x1F) << 3),
           (byte)1);
    }

    return colors;
}

Worked about 30-50 times faster than just i++. The "extras" is just styling. This code is doing, in one "line", in the for loop, what you're declaring in 4 lines plus it is much quicker. Cheers :)
Referenced + Referenced code: Here

A: I haven't profiled it, but using fixed to ensure your memory doesn't get moved around and to remove bounds checks on array accesses might provide some benefit:
img = new Color32[byteArray.Length / nChannels]; //nChannels being 4
fixed (byte* ba = byteArray)
{
    fixed (Color32* c = img)
    {
        byte* byteArrayPtr = ba;
        Color32* colorPtr = c;
        for (int i = 0; i < img.Length; i++)
        {
            (*colorPtr).r = *byteArrayPtr++;
            (*colorPtr).g = *byteArrayPtr++;
            (*colorPtr).b = *byteArrayPtr++;
            (*colorPtr).a = *byteArrayPtr++;
            colorPtr++;
        }
    }
}

It might not provide much more benefit on 64-bit systems - I believe that the bounds checking is is more highly optimized. Also, this is an unsafe operation, so take care.


text:
Q: how to use AsyncTask in android 4.2 i am using AsyncTask class in my first activity its work fine
and call second and i am call another AsyncTask call object in onCreate
and call the webservice in doInBackground
then its give exception
android.os.networkmainthread.
i am not getting any idea as
i am new to android development
so please show me some sample or i show you my code
this is my code
public class panel extends Activity {

@Override
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.panel);
   User_Balance_Load Balance_load=new User_Balance_Load();
   Balance_load.execute();
   Toast.makeText(getBaseContext(),Cls_Constant.username, Toast.LENGTH_LONG).show();

}
class User_Balance_Load extends AsyncTask<Void, Void, Void>
{
    private final ProgressDialog dialog = new ProgressDialog(panel.this);
    protected void onPreExecute() {

        this.dialog.setMessage("Loding Diet type...");
        this.dialog.show();
                                    }

    protected Void doInBackground(final Void... unused) {
        // TODO Auto-generated method stub
        panel.this.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                Update_balance();
            }
        });
        return null;
    }
    protected void onPostExecute(Void result)
    {

            if (this.dialog.isShowing())
            {
            this.dialog.dismiss();
            }

     }

}
void Update_balance()
{

    Vector result;
    result=Cls_webservice.User_Balance(Cls_Constant.Guid);
    if(result.size()>0)
    {
        String UserBalance=result.elementAt(2).toString();
        TextView Tv_User_balacne=(TextView)findViewById(R.id.tv_point_balance);
        Tv_User_balacne.setText(UserBalance);
    }
}

And this is my class of webservice
public class Cls_webservice {

 public static Vector User_Balance(String id)
    {
        Vector _vector = new Vector();
        final String userid = id;

        final String METHOD_NAME = "WCFDatatableRes";
        final String SOAP_ACTION = "http://tempuri.org/WCFDatatableRes";
        final String NAMESPACE = "http://tempuri.org/";
        final String URL = "http://xxxxxxxx.com/GameRoom/ANDROIDLOTT/WebService.asmx";
        String return_val="";
        SoapObject newob;
        try
        {
            Object response;
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            envelope.encodingStyle = SoapEnvelope.ENC;
            SoapObject Request = new SoapObject(NAMESPACE , METHOD_NAME);
            Request.addProperty("Params", userid+",3");
            Request.addProperty("Do", "Balance");
            envelope.dotNet = true;
            envelope.setOutputSoapObject(Request);
            AndroidHttpTransport httptransport ;
            httptransport = new AndroidHttpTransport(URL);

            httptransport.debug=true;
            try
            {

                httptransport.call(SOAP_ACTION,envelope);
                response = envelope.getResponse();
                newob = (SoapObject)envelope.bodyIn;
                return_val = newob.toString();
                SoapObject diettype_listResult = (SoapObject) newob.getProperty("WCFDatatableRes ") ;
                SoapObject diffgram = (SoapObject) diettype_listResult.getProperty("diffgram") ;

            }
            catch (Exception e) {
                System.out.println("error:" + e);
            }

        }
        catch (Exception e) {
        }
        return _vector;
    }

}
The exception come in this line -> "httptransport.call(SOAP_ACTION,envelope);
so please help me
and this same code work in
my first activity
i don't know why in second come error
thanks

A: NetworkOnMainThread Exception occurs because you are running a network related operation on the UI Thread. This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged. See the document Designing for Responsiveness.
Your are running Update_balance() by using runonUithread.
You are attempting to update ui on in doInBackground() by calling Update_balance() which sets the text in textview as below. You should not update ui in doInBackground().
TextView Tv_User_balacne=(TextView)findViewById(R.id.tv_point_balance);
    Tv_User_balacne.setText(UserBalance);TextView Tv_User_balacne=(TextView)findViewById(R.id.tv_point_balance);
    Tv_User_balacne.setText(UserBalance);

All your network related operations should be done in doInBackground(). Make your webservice call in doInBackground().
You can return value from doInBackground() retrieve it in onPostExecute() and update ui accordingly.
class TheTask extends AsyncTask<Void,Void,Void>
{
 protected void onPreExecute()
 {           super.onPreExecute();
        //display progressdialog.
 }

protected void doInBackground(Void ...params)//return result here
{
    //http request. do not update ui here
    //call webservice
    //return result here
    return null;
}

protected void onPostExecute(Void result)//result of doInBackground is passed a parameter
{
        super.onPostExecute(result);
        //dismiss progressdialog.
        //update ui using the result returned form doInbackground()

}

}

The 4 steps
When an asynchronous task is executed, the task goes through 4 steps:

*

*onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.

*doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.

*onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.

*onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
For more details please check the link below
http://developer.android.com/reference/android/os/AsyncTask.html

A: You're using an asynctask and then in your asynctask you're running code under the UI thread. That is nonsense, since the result is the same as executing the code on the OnCreate() method.
protected Void doInBackground(final Void... unused)
{
    Vector result = Update_balance();
    panel.this.runOnUiThread(new Runnable()
    {
        @Override
        public void run()
        {
            if(result.size()>0)
            {
                String UserBalance=result.elementAt(2).toString();
                TextView Tv_User_balacne=(TextView)findViewById(R.id.tv_point_balance);
                Tv_User_balacne.setText(UserBalance);
            }
        }
    });
    return null;
}

Vector Update_balance()
{
    Vector result;
    result=Cls_webservice.User_Balance(Cls_Constant.Guid);
    return result;
}


text:
Q: Magento 2.3 - Need detail about some newly introduced feature I need to know about some of the newly introduced featured of Magento 2.3

*

*GraphQL

*Declarative DB Schema

*Asynchronous and Bulk Web API

There are few blogs information but not elaborating properly. I need short and to the point answer not full articles on this.
Any help would be appreciated

A: GraphQL:
GraphQL is a new concept from Magento 2.3 version in Magento eCommerce. Using Graphql we can get sales order data. There are many default core module uses GraphQl for getting data like, Product, CMS Page, and Block, Customer module uses Graphql for getting data of a specific entity.
Declarative DB Schema:
Magento 2.3 introduces a new approach – declarative database schema, allowing developers to define database structures and changes in XML files, instead of defining with install scripts. Magento 2.3 will convert the XML schema files into SQL statements and perform them.
Asynchronous web API:
An asynchronous web endpoint intercepts messages to a Web API and writes them to the message queue. Each time the system accepts such an API request, it generates a UUID identifier. Magento includes this UUID when it adds the message to the queue. Then, a consumer reads the messages from the queue and executes them one-by-one.
Magento supports the following types of asynchronous requests:

*

*POST

*PUT

*PATCH

I hope this will help though this is not the best possible description but I tried


text:
Q: Woocommerce products not showing after a product with many variations in the catalog I have a curious problem.
When I've a product with a lot of variations (for example 15 colors variations), in the catalog page, the next products are not displayed.
But if the product has for example 5 variations, works nice.
Has it happened to someone?
Any idea?
Thank you very much to all!
The page is: https://www.covertea.shop/shop
enter image description here

A: Yesterday I can fix my problem.
The problem was in the loop product of catalog, when have more than "x" number of variations the product variation can't load all.
How to fix this problem?
I was change the array that return small images on the loop and now return 3 variations.
Thanks you very much to all!


text:
Q: Change Order of Tuple Values within a List of a list I have a list of tuples inside a list like this:
[[('2375', 'AddressNumber'),
  ('Second', 'StreetName'),
  ('Street', 'StreetNamePostType')],
 [('401', 'AddressNumber'),
  ('Wilmington', 'StreetName'),
  ('Drive', 'StreetNamePostType')],
   ... ],
 ...]

And need to change the order of the values like this:
[[('AddressNumber', '2375'),
  ('StreetName', 'Second'),
  ('StreetNamePostType', 'Street')],
 [('AddressNumber', '401'),
  ('StreetName', 'Wilmington'),
  ('StreetNamePostType', 'Drive')],
   ... ],
 ...]

I realize that it's immutable and I think I need to change this to a list but the list within a list is throwing me off in my python script. Any help is appreciated. Thanks

A: xxx = [[('2375', 'AddressNumber'),
        ('Second', 'StreetName'),
        ('Street', 'StreetNamePostType')],
       [('401', 'AddressNumber'),
        ('Wilmington', 'StreetName'),
        ('Drive', 'StreetNamePostType')]]

[[(x[1],x[0]) for x in tt] for tt in xxx]

Output
[[('AddressNumber', '2375'),
  ('StreetName', 'Second'),
  ('StreetNamePostType', 'Street')],
 [('AddressNumber', '401'),
  ('StreetName', 'Wilmington'),
  ('StreetNamePostType', 'Drive')]]

A:
I realize that it's immutable and I think I need to change this to a list

No; you just need to create a new tuple instead of trying to mutate the existing one.

but the list within a list is throwing me off in my python script.

So, take it a step at a time, and work from the inside out.
First, let's define something that can create the reversed version of one of the tuples:
def flip_address_data(data): # 1A
    value, label = data
    return label, value

Or, without naming the values:
def flip_address_data(data): # 1B
    return data[::-1]

Then we can write the code to replace each item in the inner list:
def flip_inner_list(l): # 2A
    l[:] = [flip_address_data(d) for d in l]

(Or, if you prefer, the procedural way using enumerate to get the indices to write back:)
def flip_inner_list(l): # 2B
    for i, d in enumerate(l):
        l[i] = flip_address_data(d)

Finally the same for the outer list:
def flip_outer_list(l): # 3A
    l[:] = [flip_inner_list(i) for i in l]

(or similarly:)
def flip_outer_list(l): # 3B
    for i, x in enumerate(l):
        l[i] = flip_inner_list(x)

Once you're comfortable with it, you can condense the process. For example, it's easy to just substitute 1B into 2A:
def flip_inner_list(l): # 2C
    l[:] = [d[::-1] for d in l]

Rather than assigning back into the original lists, it will be easier to just create new data:
def flip_inner_list(l): # modify 2C to return the value
    return [d[::-1] for d in l]

def flip_outer_list(l): # similarly modifying 3A
    return [flip_inner_list(i) for i in l]

Once we have the mindset of creating new values instead of modifying old ones, the substitution step becomes easy again:
def flip_outer_list(l): # using full-sized names for clarity
    return [[item[::-1] for item in inner] for inner in l]

A: Another possibly way is this:
outerList = [[('2375', 'AddressNumber'),('Second', 'StreetName'),('Street', 'StreetNamePostType')], [('401', 'AddressNumber'),('Wilmington', 'StreetName'),('Drive', 'StreetNamePostType')]]

print([[swapVals[::-1] for swapVals in element] for element in outerList])
### use the slice approach to reverse the elements within each set of the nested list.

Output:
[[('AddressNumber', '2375'), ('StreetName', 'Second'), ('StreetNamePostType', 'Street')], [('AddressNumber', '401'), ('StreetName', 'Wilmington'), ('StreetNamePostType', 'Drive')]]