text:
Q: Cómo insertar un array dentro de un JSON en PHP? Buen día estoy haciendo un merge en mi base de datos, donde uno un objeto con otro que retorna una galería y alfinal debo regresar un JSON, Aquí mi código en PHP usando Eloquent/Laravel:
public function getProperty($prop){
        $property = Property::where("code", $prop)->first();

        $images = Photo::where("property_id", $property['company_id'])->get();

        $decodedImages = json_decode($images, true);
        $decodedProperty = json_decode($property, true);

        $merged = array_merge($decodedProperty, $decodedImages);

        return $merged;
    }

Y la respuesta de la peticion GET en POSTMAN es esta:
{
    "id": 1,
    "country": 1,
    "city": 729,
    "zone": 4,
    "neighborhood": "at",
    "type": 9,
    "biz": 2,
    "status": 1,
    "area": 214,
    "area_built": 368,
    "area_private": 207,
    "floor": 2,
    "floor_quantity": 3,
    "bedrooms": 4,
    "bathrooms": 3,
    "parking": 0,
    "stratum": 1,
    "rent": "247.29",
    "sale": "261.91",
    "administration": "278.28",
    "description_demo": "Quo quidem autem ducimus harum animi est reprehenderit.",
    "built_at": 1994,
    "photo": "https://via.placeholder.com/640x480.png/007733?text=animals+voluptatibus",
    "published_date": "2022-08-22",
    "latitude": 63.3599999999999994315658113919198513031005859375,
    "longitude": 5.37000000000000010658141036401502788066864013671875,
    "featured": 0,
    "video": "https://via.placeholder.com/640x480.png/000022?text=animals+occaecati",
    "destination": 7,
    "score": 84,
    "0": {
        "id": 1,
        "property_id": 1,
        "url": "https://via.placeholder.com/640x480.png/0099ee?text=animals+numquam",
        "created_at": "2022-08-22T16:44:34.000000Z",
        "updated_at": "2022-08-22T16:44:34.000000Z"
    },
    "1": {
        "id": 2,
        "property_id": 1,
        "url": "https://via.placeholder.com/640x480.png/009988?text=animals+qui",
        "created_at": "2022-08-22T16:44:34.000000Z",
        "updated_at": "2022-08-22T16:44:34.000000Z"
    },
    "2": {
        "id": 3,
        "property_id": 1,
        "url": "https://via.placeholder.com/640x480.png/000055?text=animals+explicabo",
        "created_at": "2022-08-22T16:44:34.000000Z",
        "updated_at": "2022-08-22T16:44:34.000000Z"
    },
    "3": {
        "id": 4,
        "property_id": 1,
        "url": "https://via.placeholder.com/640x480.png/002277?text=animals+sint",
        "created_at": "2022-08-22T16:44:34.000000Z",
        "updated_at": "2022-08-22T16:44:34.000000Z"
    }
}

Pero quisiera que al final quedara una propiedad llamada gallery con una array de objetos dentro del mismo json tal como este ejemplo que pongo ahora, he intentado convertirlos primero en array y hacer el merge para posteriormente retornar un JSON pero no logro conseguir que quedé así:
{
    "id": 1,
    "country": 1,
    "city": 729,
    "zone": 4,
    "neighborhood": "at",
    "type": 9,
    "biz": 2,
    "status": 1,
    "area": 214,
    "area_built": 368,
    "area_private": 207,
    "floor": 2,
    "floor_quantity": 3,
    "bedrooms": 4,
    "bathrooms": 3,
    "parking": 0,
    "stratum": 1,
    "rent": "247.29",
    "sale": "261.91",
    "administration": "278.28",
    "description_demo": "Quo quidem autem ducimus harum animi est reprehenderit.",
    "built_at": 1994,
    "photo": "https://via.placeholder.com/640x480.png/007733?text=animals+voluptatibus",
    "published_date": "2022-08-22",
    "latitude": 63.3599999999999994315658113919198513031005859375,
    "longitude": 5.37000000000000010658141036401502788066864013671875,
    "featured": 0,
    "video": "https://via.placeholder.com/640x480.png/000022?text=animals+occaecati",
    "destination": 7,
    "score": 84,
    "gallery": [
    {
        "id": 1,
        "property_id": 1,
        "url": "https://via.placeholder.com/640x480.png/0099ee?text=animals+numquam",
        "created_at": "2022-08-22T16:44:34.000000Z",
        "updated_at": "2022-08-22T16:44:34.000000Z"
    },
    {
        "id": 2,
        "property_id": 1,
        "url": "https://via.placeholder.com/640x480.png/009988?text=animals+qui",
        "created_at": "2022-08-22T16:44:34.000000Z",
        "updated_at": "2022-08-22T16:44:34.000000Z"
    },
    {
        "id": 3,
        "property_id": 1,
        "url": "https://via.placeholder.com/640x480.png/000055?text=animals+explicabo",
        "created_at": "2022-08-22T16:44:34.000000Z",
        "updated_at": "2022-08-22T16:44:34.000000Z"
    },
    {
        "id": 4,
        "property_id": 1,
        "url": "https://via.placeholder.com/640x480.png/002277?text=animals+sint",
        "created_at": "2022-08-22T16:44:34.000000Z",
        "updated_at": "2022-08-22T16:44:34.000000Z"
    }
}

A: Tienes que codificar en formato JSON. Reemplazar por $merged:
$decodedProperty['galeria'] = $decodedImages;

return json_encode($decodedProperty);


text:
Q: SVN improvement suggestions for my work environment Yet another SVN guideline question, I know.
I recently joined a new company which maintains a few websites. We have a few developers and a graphics designer and all of us use SVN. Each of us has individual working copies and sandboxes to work with, and commits everything to the trunk.
Here are the problem we are facing:

*

*Sometimes, multiple ppl work on the same feature/bug (eg. me and the graphics guy). In order for us sync our work(eg for me to see the new picture/css), the graphics guy needs to commit his changes and I have to update my working copy. Therefore at the end of the day we have a lot of revisions to merge from trunk to the RC branch.

*Often we were asked to implement a feature, ok, finished, commit the code to trunk. Then we were asked to fix a bug(to fix this bug it somehow uses some of the code written for the feature, and no body remembered it) Ok, bug fixed, tested, commit bug fix to trunk. The screw up part is later we got told that we would not release the feature but needed to release the bug fix.
There are a few more scenarios but I can't remember now. What changes do you guys reckon that will improve our processes?
Regards
James

A: That is probably a good time to change svn to some distributed svc(like mercurial or git). I haven't used them, but according to what I've read about it they have less friction when it comes to merging and branching and this seems to be the problem here.

A: Our shop goes like this ...
The trunk is only what is in production.
If a developer needs to create a change he creates a branch from the trunk. performs his changes in the branch, etc ...
Right before the branch is to get deployed, a merge is done from the trunk into the branch. That way you have trunk + newest changes in branch.
Once the branch has been deployed to production and some testing has been done then the branch that just got put into production is reintegrated into the truck.
Nobody touches the trunk, it is always a working snapshot of production, except for a small window after a deployment.

A: You can have feature branches that yourself and the graphics guy work toegther on. Make sure you have the tasks written out that both of you will do and when as there undoubtably be some dependencies between both of you (as you seem to be experiencing).
One good way our team used a designer was that we sat down and quickly drew up an 'API' or basic code contract that he can design against at the same time the devs would code against.
Try to integrate often both to your branch and trunk. If there are large gaps in check ins then merging becomes more difficult (code drift). The merge tools can only get you so far.
Bugs do happen after a feature is done, no one is perfect but make sure you have a proper bug tracking system and assign the bugs to the best person for the job (ususally the one who knows most about the feature).
If you have one person knowing the feature and he goes on holiday you can get the situation where no one else in the team would know how it worked. In this situation I have found that it is best to share the knowledge around the team as much as possible. If you use Agile peer(pair) programming can work, perhaps code reviews.
Remember communication is key for larger projects and simply takling to the next person about the tasks at hand goes a long way to share knowledge and understanding.
HTH

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a tool for remotely monitoring resource usage on OS X workstations? We have a bunch of OS X workstations and some users have complained that there isn't enough memory on them.  We'd like to monitor some resource usage stats over time to see if we should upgrade memory on all the machines or not - is there a good tool that does this?

A: 1 word... SNMP.  After SNMP is installed, there are hundreds of tools that can monitor your machines and create all sorts of pretty graphs of whatever you wish to monitor.  (cpu/ram/processes running/etc...)  I recommend something like Cacti.  It's pretty simple to get going.

A: You can try Ganglia it's a great open source software, and you see all the bottlenecks per workstations. Ganglia create graphs per user, and per resource (cpu/ram/disk/etc)


text:
Q: Some requests time out with no clear reason I encountered a bug I can't understand and for now it happens only on a specific device. It happens on an iPhone 5 with iOS 6 but unfortunately I don't have access to another one to check if it's related to the fact that it's an iPhone 5.
The problem is that some specific network requests made to our server API time out although the connection is fast and there seems to be no server-side problem as the server acts normally responding to the same request from other devices.
I use AFNetworking to make my http requests.
I have subclassed AFHTTPClient and for that specific request I use it like this
[[MyClient sharedInstance] putPath:@"myPath"
                        parameters:[NSDictionary dictionaryWithObject:@"y" forKey:@"set"]
                           success:^(AFHTTPRequestOperation *operation, id responseObject){
                                     // do something with response
                           }
                           failure:^(AFHTTPRequestOperation *operation, NSError *error){
                                     // tell user there an error occurred
                           }];

I would appreciate if someone points me to some possible reasons this is happening or things to analyze to understand what is happening.

A: There is a near-zero chance that the issue relates to the interaction between AFNetworking and a specific device - it's likely one or the other.
Testing AFNetworking
AFNetworking does provide build-in detection of connectivity changes.  Set a block using AFHTTPClient's -setReachabilityStatusChangeBlock: method.  This will let you know when an Internet connection is lost, and will allow you to adjust your app's behavior as needed.
This Stack Overflow question provides sample code and setup instructions.
Here are the values for the status variable, for your reference:
AFNetworkReachabilityStatusUnknown          = -1,
AFNetworkReachabilityStatusNotReachable     = 0,
AFNetworkReachabilityStatusReachableViaWWAN = 1,
AFNetworkReachabilityStatusReachableViaWiFi = 2,

Testing the Device
Here are something you can try to isolate the issue to your device:
• Download Fing and compare network performance on different devices
• Do a data speed test on testmyiphone.com
• Check the device's parental controls to see if anything would conflict with your app's behavior
• Restore the device, without restoring from backup, in iTunes

A: I would suggest you start by monitoring the actual HTTP request/responses that you are sending by using a tool such as Charles
You can use Charles as a proxy for your actual device, check out the instructions here.
Hope this helps.

A: My suggestion is to check your iphone wifi network. This happen to me in the past when i am connected to my company's corporate network and i tried to connect to my server and there is a request timeout. This may be due to some proxy issues.
Firstly is your server intranet? If it is not, try using 3G to connect to the server instead.
If it is intranet try to find an alternative company network or use VPN if your company has one


text:
Q: How to "runAction" forever with completion block parameter included I declared a method in a SpriteKit game I have been working on that runs an action where a SpriteNode moves up and on competition, moves down.
func yFluctuation(node: SKSpriteNode) {
  let flucUp = SKAction.moveToY(node.position.y + 9, duration: 2.0)
  let flucDown = SKAction.moveToY(node.position.y - 9, duration: 2.0)
    node.runAction(flucUp, completion: {node.runAction(flucDown)})
}

I have tried SKAction.repeatActionForver(), however it only works on flucUp and gives an error if I include the completion block in it. If anyone has a solution of any kind, even if it means changing the structure of the function, I would be very grateful.
Thanks in advance.

A: I don't have a way to test it, but will repeating a sequence forever work? I confess to it being something of a shot in the dark though.
SKAction.repeatActionForever(SKAction.sequence([flucUp, flucDown]))


text:
Q: How do I get the signature design from embedded app? When I checked the document in the email, I was able to select the Signature design registered in the sand box account. But there is no Signature information in embedded app, so how can I get it?
enter image description here

A: https://developers.docusign.com/esign-rest-api/reference/Users/UserSignatures/getImage
GET /restapi/v2.1/accounts/{accountId}/users/{userId}/signatures/{signatureId}/{imageType}

You need to know the SignatureId
for that you make first this call:
GET /restapi/v2.1/accounts/{accountId}/users/{userId}/signatures

A: Thank you for your answer.
I don't know how to get the signatureId. How can i bring my signatureId?
OAuth.OAuthToken oAuthToken = apiClient.requestJWTUserToken(integratorKey, userId, scopes, privateKeyBytes, 3600);
        log.info("getAccessToken : " + oAuthToken.getAccessToken());
        log.info("getExpiresIn : " + oAuthToken.getExpiresIn());

        apiClient.setAccessToken(oAuthToken.getAccessToken(), oAuthToken.getExpiresIn());
        //UserInfo userInfo = apiClient.getUserInfo(oAuthToken.getAccessToken());
        userInfo = apiClient.getUserInfo(oAuthToken.getAccessToken());
        List<Account> accountList = userInfo.getAccounts();
        Account account = accountList.get(0);

        UsersApi userApi = new UsersApi(apiClient);
        userApi.getSignature(accountId, userId, signatureId); // I don't know signatureId


text:
Q: ASP.NET web site builds locally, but throws MSB3268 on the build server I added a project to my web site solution. Everything built fine locally and on the build server.
I added a line in web code to call a method in the new project. Everything built and worked fine locally, but it broke the build on the build server.
I got a pile of errors going something like this:

warning MSB3268: The primary reference "C:...\ProjectName.dll" could not be resolved because it has an indirect dependency on the framework assembly "Assembly.Name (e.g. System.Runtime)", Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" which could not be resolved in the currently targeted framework. ".NETFramework,Version=v4.5". To resolve this problem, either remove the reference "C:...\ProjectName.dll" or retarget your application to a framework version which contains "System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a".

After all the warnings, the build failed with an error indicating the namespace ProjectName could not be found. Makes sense considering the project's dependencies couldn't be resolved.
At first I wondered if there was an issue with targeting the wrong framework. But there was a mix of 4.0 and 4.5 projects referenced by the 4.5 website. This was the first one that had failed.
The only difference between this and the other projects was that it referenced third-party DLLs. So apparently their dependencies are the ones that couldn't be resolved.

A: This post held the key: http://devsilos.blogspot.com/2014/10/msb3268-while-targeting-aspnet-web-site.html
The author suggests:

aspnet_compiler for some reason does not take into account the .dll-s that reside under the Facade directory of 4.5 assemblies (C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5\Facades).
  It looks only under
  C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5

My extrapolation on that idea is that maybe the compiler doesn't take into account DDLs in the Facades directory if they're referenced by a third-party DLL rather than directly from your project.
The solution, as suggested by the author, was to find the DLLs matching assemblies mentioned in the MSB3268 warnings and copy them from Facades to its parent directory.
I think my problem/solution differed from the blog's in that it had nothing to do with the .NET Framework version targeted. It had only to do with whether the build server's compiler looked in the right places to resolve third-party DLLs' dependencies.
The problem caused about ten hours of frustration. I hope this helps someone else avoid that!


text:
Q: Plotting logistic regression with multiple predictors? I ran the following logistic regression:
model<-glm(Choice~Cat+Dog+Rabbit+Cow,data=database,family=binomial(link="logit"))
summary(model)

Now, I'd like to visualize this regression with all four predictors. Thank you!!

A: You have a multivariate regression, so you need to vary one variable and hold others constant, this is called marginal effect. You can code it from scratch to visualize it, and I think there are some useful packages like ggeffects or sjplot. Before I use an example dataset and plot the effects:
library(ggeffects)
dat = iris
dat$Species = as.numeric(dat$Species=="versicolor")
mdl = glm(Species ~ .,data=dat,family="binomial")

summary(mdl)

Call:
glm(formula = Species ~ ., family = "binomial", data = dat)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-2.1280  -0.7668  -0.3818   0.7866   2.1202

Coefficients:
             Estimate Std. Error z value Pr(>|z|)
(Intercept)    7.3785     2.4993   2.952 0.003155 **
Sepal.Length  -0.2454     0.6496  -0.378 0.705634
Sepal.Width   -2.7966     0.7835  -3.569 0.000358 ***
Petal.Length   1.3136     0.6838   1.921 0.054713 .
Petal.Width   -2.7783     1.1731  -2.368 0.017868 *

To visualize one:
plot(ggpredict(mdl,"Petal.Width"))

To make these plots for all variables:
library(patchwork)

plts = lapply(names(coefficients(mdl))[-1],function(i){
       return(plot(ggpredict(mdl,i)))
       })

wrap_plots(plts)

As mentioned before, those plots are obtained via the marginal effects, that is keeping others at their mean values. You can also explore it by keep another variable at different value, for example:
plot(ggpredict(mdl,c("Petal.Width","Petal.Length")))


text:
Q: How to avoid the users from seeing the webviews resize to match content? I have an activity with a number of WebViews. Local html is loaded to them on onCreate() of the activity. How to avoid the users from seeing the webviews resize?
The WebViews are placed in a linearlayout (which is in a scrollview). There are more than 100 of them
As the app starts webviews are loaded with local html.
However heres what the users see.

*

*A list of empty webviews appear as the app starts. They are small in height as they are empty.

*Then (within milliseconds) the webviews get content and they expand in size to wrapcontent.

I want to avoid the users from seeing this transition. I want them to see (step2) as the first thing they see without seeing the step1.
I tried the onPageFinished of webview with no luck. Therefore I think this problem is not unique to webview.


text:
Q: Shell script check if file exists? I wrote a simple backup script which back ups my stuff on a remote server, everything is working great but I'd like to have some sort of report like "backup successful or not".
this is my script
# backup CHECK
date1=`date +"%d.%m.%y - %H.%M"`
host=`hostname`
twdate=`date +"%d.%m"`
performtw=`ls -la|grep "tw"|grep "$twdate" > tmp1.txt`
echo $performtw
if
cat tmp1.txt|grep "tw"
then
echo backup successfull
printf "tw backup success!" | mail -s "tw backup check $date1 repor$
rm tmp1.txt
else
echo backup failure
printf "sitename backup failure!" | mail -s "site backup check $date1 repor$
rm tmp1.txt
fi
exit

But this isn't working really well and I ask you if there's some simpler and more powerful way to do it? Basically it just needs to check if file exists with the name starting xyz and was created at date xyz.

A: You could use a nice bash conditional execution to see whether the file exists or not...
[ -f tmp1.txt ] && echo "Found" || echo "Not found"

Alternatively you could use the find command with the -newer flag...
find /some/dir -type f -newer $startdate -not -newer $enddate


text:
Q: How can I give the elements of the following set?
Well, in this case i is equal to true and h for false.
$ \underline{4} = \{ 1,2,3,4\}$
The statements are the following:
$ \{a \in \underline{4}:(\exists x \in \underline{4})(Q(a,x) \land Q(x,x)$
Well I think that I have to check the pairs:$(1,x) \land (x,x)$,$(2,x) \land (x,x)$,$(3,x) \land (x,x)$,$(4,x) \land (x,x)$ and these $(x,x)$pairs are in the diagonal, and in the diagonal these are always i so true. But how can I give the elements of the set? I still can see what would be the difference if I would use $\forall$ instead of $\exists$.
The other statement is:
$ \{a \in \underline{4}:(\forall x \in \underline{4})(\exists y \in \underline{4})(Q(a,x) \implies Q(x,y) \land Q(y,a)))\}$
I'm a little bit perplexed again


text:
Q: How to solve Error:apache shutdown unexceptedly? I have tried every thing in that stack overflow,even after it is showing the same error. Please can anyone provide an answer for this problem?

A: There could be many reasons for that output but here's the way you can know for sure

*

*Open cmd by pressing, Win + R and typing cmd

*cd into apache / bin directory eg. "C:/xampp/apache/bin"

*Now type httpd.exe to start apache

If there's a problem, it would output the error in the console and then you can correct it.


text:
Q: Inter-Domain iframe Content Access How to communicate between iframes on different domains?
<!DOCTYPE html>

<button onclick="tcget();">Click me</button>
<button onclick="tfget();">Click me</button>

I would like to be able to share content, from each iframe loaded into the same page.
I have looked into window.postMessage but this does not appear to be able to do it either. My app will be pulling statistics from each iframe for a Neural Net - I hope that it can be done, security wise it seems that its not something that can be done.


text:
Q: Decorator - viewpoint mapping assertion error I have a flask app with several end points and I have written a decorator to log the end points for audit purpose. The decorator works fine when I tried with one end point but when I add the decorator to a second end point, I am facing assertion error
For Example, I have two end points to edit and delete
@route('/owners/<ownerid>/delete',methods=['DELETE'])
@logtrail()
def deleteOwner(ownerid):
     if request.method == 'DELETE':
         return jsonify({})

@route('/owners/<ownerid>/edit',methods=['PUT'])
@logtrail()
def editOwner(ownerid):
     if request.method == 'PUT':
         return jsonify({})

The decorator @logtrail works fine either for edit or delete edit point but the app fails to start if add the decorator to both end points
Decorator code is as below
def logtrail(usermsg=None):
    def decorator(func):
        def wrap(*args, **kwargs):
            print "Audit code goes here"
            return func(**kwargs)
        return wrap
    return decorator

Exact error which I get when I start the application is
AssertionError: View function mapping is overwriting an existing endpoint function: wrap

From error message, I get the name has to be unique like method names but how can I do that in a decorator?
Any suggestion will be helpful

A: Using a decorator without the wrap will rename the function, which will cause the issue you mentioned - since there will be more than one function with the same name.

(...) A decorator is a function that returns a function. The only thing you have to keep in mind when implementing something like this is to update the __name__, __module__ and some other attributes of a function. This is often forgotten, but you don't have to do that by hand, there is a function for that that is used like a decorator (functools.wraps()).

(http://flask.pocoo.org/docs/0.11/patterns/viewdecorators/).
Try to change your decorator to the following:
from functools import wraps

def logtrail(usermsg=None):
    def decorator(func):
        @wraps(func)
        def wrap(*args, **kwargs):
            print "Audit code goes here"
            return func(**kwargs)
        return wrap
    return decorator


text:
Q: Does MongoDB support Upsert to an Array Field I have a document structured as follows:
{
    "_id" : 1000001,
    "ListMembers" : [
            {
                    "MemberID" : 1000,
                    "Notes" : "Test Notes for 1000"
            },
            {
                    "MemberID" : 1001,
                    "Notes" : "Test Notes for 1002"
            }
    ]

}
The application generates a unique Id.
I need to achieve following:

*

*If the document doesn't exist then Insert a new document with Array
Field.

*If the document exits in the collection and Member record
exists in the array then Update the Member Notes

*If the document exits in the collection and Member record doesn't
exist in the array then Insert Member Record in the array.

Here #1 and #2 work fine but the {upsert:true} option doesn't work for #3 above; if the document exists but the Member Record doesn't exist, it tries to Insert a new document with the same Id which obviously gives me a Duplicate key error. Does MongoDB support UPSERT operation in this scenario OR do I need to check the existence of the document and then do INSERT for #1 and ($pull and $push) to achieve #2 and #3 on the array field.

A: Currently this isn't supported as the $ positional operator doesn't support upserting:

Do not use the positional operator $ with upsert operations because, inserts will use the $ as a field name in the inserted document.

The positional operator is required to update the notes for the member record but wont work for an upsert.
The logic I would recommend is to do an update query to cover #2 and #3 - I'd make sure the writeconcern is 1 - so it returns the number of documents updated.  If it returns none do an insert to $push the item onto the ListMembers - this covers #1*
*There is a potential race condition here - for extra points you should ensure when you try and do the $push it checks that it doesn't match the ListMembers aspect and set the writeconcern.  If the $push operation returns 0 - that means the document was updated inbetween the first operation and this one, so you can now proceed back with the $update as theres is now a match and it will update it.


text:
Q: docker: invalid reference format with -it option I get the below error with docker run command
docker run --rm  -it -v /home/pycharm/project/test_project:/temp docker-image:/latest /bin/bash

It returns an
docker: invalid reference format.
See 'docker run --help'.

Any thoughts on what I might be missing?
Thanks!


text:
Q: Computer doesn't remain in power-off state I can't hibernate my computer. After finishing hibernate and powering off, it powers on again and boot.
All options in BIOS known to me are disabled:

Motherboard is Gigabyte GA-B85M-D3H
How to fix?
UPDATE
Powercfg gives the following answer:
C:\Windows\System32>powercfg /lastwake
Wake History Count - 1
Wake History [0]
  Wake Source Count - 0

Computer wakes only from within hibernate mode. It doesn't autowake if in poweroff mode.
UPDATE 2
Disabling mouse wake up didn't help.
I emphasize, that I am speaking not about sleep mode, but about hibernate mode. This is different mode. When mouse wake up was on, I still was unable to turn computer on by mouse. Because in hibernate mode mouse is powered of and can't send any signals to anywhere.
UPDATE 3
I have set network card to this:

Previously "Only allow a magic..." checkbox was unchecked. Now my computer "survives" whole night in hibernate mode!
But when I am coming to it in the morning and touching mouse, it is immediately waking up! This is despite the fact I have disabled mouse wake up during research.
Microsoft never does what it told to :)

A: Gigabyte UEFI seems to have an issue with Wake On Lan, which is known to cause reboots after a shutdown in some conditions. Since "hibernation" is a glorified name for "dump your RAM on the disk and shut down", you may have experienced exactly that.
Try to find an option in your UEFI settings which reads like "Wake on Lan" or "Wake on PCI" and disable it. Another thing to try is to modify your network adapter settings in Windows:

*

*Device manager -> right click on your network adapter -> Properties -> Advanced -> Wake on magic packet = Disabled

*Device manager -> right click on your network adapter -> Properties -> Power Management -> Allow this device to wake up the computer = Unchecked

A: I've been experiencing similar issues and suddenly autoboots with and HP ProDesk 600 G2. After being mad trying different BIOS configs, the problem was Windows 10 "Fast Startup" option.
After unchecking it, my problem was solved.

A: Method 1
Laptops will wake-up if mouse or keyboard is pressed.
Go to Control Panel and open MOUSE > Hardware > Properties > General > Change Settings > Power Management > and uncheck "Allow this device to wake up pc".

(do the same for Keyboard, Network Devices..... You can do it from ControlPanel or Device manager too).
Method 2
To see the last devices, which WOKE UP computer, type this in CMD:
powercfg –lastwake

To find out which devices are enabled to wake up the PC, enter this command
powercfg -devicequery wake_armed

If not helps, try this Source 1.
(source 2: Why does my Windows computer immediately turn back on after sleep/hibernate?)

A: You could try looking in the Task Scheduler for tasks that wake the computer up to do updates, scans or maintenance routines.


text:
Q: Export JPanel to vector graphics I would like to export the image in my JPanel to a vector graphics file so it can be edited and printed at a higher-than-screen resolution.  Essentially I want its paint() function to be called with a destination Graphics that saves the drawing commands into a vector graphic file.
What is a good, simple way to do this?  What libraries are recommended?  Which vector format would be best, and why?

A: Have a look at The Java EPS Graphics2D package.

Many Java programs use Graphics2D to draw stuff on the screen, and while it is easy to save the output as a png or jpeg file, it is a little harder to export it as an EPS for including in a document or paper.
This package makes the whole process extremely easy, because you can use the EpsGraphics2D object as if it's a Graphics2D object. The only difference is that all of the implemented methods create EPS output, which means the diagrams you draw can be resized without leading to any of the jagged edges you may see when resizing pixel-based images, such as JEPG and PNG files.

A: Apache Batik will let you paint to a specialised implementation of a Graphics2D object and then export as an scalable vector graphics (.svg) file. You can then view/process/print it using an SVG-enabled browser (Firefox will handle it nativly, ISTR, IE and others can use plugins).
See the SVGGraphics2D object (process documented here)

A: The Java EPS mentioned by Pierre looks good, but if it isn't you might also like to look at FreeHEP Vector Graphics. Written to allow Java reuse in the High Energy Physics field it includes a vector graphics package, done through an implementation of Graphics2D. We've used it to export EPS very successfull for a number of years.

A: I can recommend the VectorGraphics2D library (LGPL). Although it does not support all the features of Graphics2D, I used it successfully for my project. It provides implementations of java.awt.Graphics2D for various vector file formats. It simply exports all paint operations to EPS, SVG, or PDF files.

A: Additional libraries for people with the same requirement:

*

*for SVG, JFreeSVG at http://www.jfree.org/jfreesvg/

*for PDF, OrsonPDF at http://object-refinery.com/orsonpdf/index.html
Both of these GPLv3 and well tested via extensive usage in JFreeChart and Orson Charts.

A: FreeHEP seems to work quite well although it does not appear to be maintained anymore and its bug and forum pages are gone. With just a handful of lines you get a popup dialog that can save any component to a variety of scalable and regular image formats. We have some challenging images, using alpha channel, rotated text, areas bounded by curves, and they saved perfectly, much better with with VectorGraphics2D.
The only problem I've seen so far is in jpeg save, which comes out black for all my images. This isn't very important for us given that png works, plus all the vector modes, but I'm sure it would be an issue for some.
I had to add exactly this much code to save in all these modes:
public static void showImage(Component comp)
{
    try
    {
        ExportDialog export = new ExportDialog();
        export.showExportDialog( null, "Export view as ...", comp, "export" );
        System.err.println("Image save complete");

    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}

There are a bunch of library jars that must be added as well.

A: this is basically not possible directly, as the low level java api works in terms of raster (pixels) and is never stored in vector format.
(Check the API of java.awt.Graphics to see what I mean).
there are some general purpose program that convert raster to vector formats, this is one I found on a quick search:
http://autotrace.sourceforge.net/index.html
so, using such a program you can divide your problem into two smaller problems:

*

*convert your JPanel into a bitmap or file (http://www.jguru.com/faq/view.jsp?EID=242020)

*run autotrace on the file.


text:
Q: Moving a screenshot from Persistent Data Path to Gallery - Android I've been using the script below to take a screenshot, save it to the persistent data path, then move it to the gallery and refresh the gallery.
When testing on Samsung Gallery S8 and Samsung Tab S5e, this works perfectly; I take a screenshot then I can view it in the devices gallery.
However, I've now tested it on Samsung Galaxy A50, and it doesn't work (I've also had reports from other people who have the same issue). It saves to the Persistent Data Path but is unable to move it to the DCIM/Camera folder, giving the error:
2020-12-04 10:51:56.345 6166-6251/? E/Unity: UnauthorizedAccessException: Access to the path is denied.
      at System.IO.File.Move (System.String sourceFileName, System.String destFileName) [0x00000] in <00000000000000000000000000000000>:0
      at SaveGallery+<CRSaveScreenshot>d__2.MoveNext () [0x00000] in <00000000000000000000000000000000>:0
      at UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) [0x00000] in <00000000000000000000000000000000>:0

    (Filename: currently not available on il2cpp Line: -1)

myDefaultLocation returns a pathway of:
/storage/emulated/0/Android/data/BUNDLEIDENTIFIER/files/Screenshot104958.jpg

myScreenshotLocation returns a pathway of:
/storage/emulated/0/DCIM/Camera/Screenshot104958.jpg

Here's the script I'm using:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Android;

public class SaveGallery : MonoBehaviour
{
    void Start()
    {
        if (Permission.HasUserAuthorizedPermission(Permission.ExternalStorageWrite))
        {
            // The user authorized use of the External Storage.
        }
        else
        {
            // We do not have permission to use the External Storage.
            // Ask for permission or proceed without the functionality enabled.
            Permission.RequestUserPermission(Permission.ExternalStorageWrite);
        }
    }
    public void TakePhoto(){
        StartCoroutine(CRSaveScreenshot());
    }
   IEnumerator CRSaveScreenshot()
 {
     yield return new WaitForEndOfFrame();

      string myFileName = "Screenshot" + System.DateTime.Now.Hour + System.DateTime.Now.Minute + System.DateTime.Now.Second + ".jpg";
      string myDefaultLocation = Application.persistentDataPath + "/" + myFileName;
      string myFolderLocation = "/storage/emulated/0/DCIM/Camera/";  //EXAMPLE OF DIRECTLY ACCESSING A CUSTOM FOLDER OF THE GALLERY
      string myScreenshotLocation = myFolderLocation + myFileName;
      Debug.Log("I WANT TO SAVE TO " + myScreenshotLocation);

      //ENSURE THAT FOLDER LOCATION EXISTS
      if (!System.IO.Directory.Exists(myFolderLocation))
      {
          System.IO.Directory.CreateDirectory(myFolderLocation);
      }

      ScreenCapture.CaptureScreenshot(myFileName);
      //MOVE THE SCREENSHOT WHERE WE WANT IT TO BE STORED

      yield return new WaitForSeconds(3);

      System.IO.File.Move(myDefaultLocation, myScreenshotLocation);

        using (AndroidJavaClass jcUnityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
        using (AndroidJavaObject joActivity = jcUnityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
        using (AndroidJavaObject joContext = joActivity.Call<AndroidJavaObject>("getApplicationContext"))
        using (AndroidJavaClass jcMediaScannerConnection = new AndroidJavaClass("android.media.MediaScannerConnection"))
        using (AndroidJavaClass jcEnvironment = new AndroidJavaClass("android.os.Environment"))
        using (AndroidJavaObject joExDir = jcEnvironment.CallStatic<AndroidJavaObject>("getExternalStorageDirectory"))
        {
            jcMediaScannerConnection.CallStatic("scanFile", joContext, new string[] { myScreenshotLocation }, null, null);
        }
 }
}

Why does this seem to work on some Samsung devices but not other ones?


text:
Q: opendaylight: what is the purpose of InstructionKey? I am programming an SDN application using opendaylight. I see that an InstructionKey is required to create an instruction but I don't know where it is used. Any idea what it's use is?
I am always setting it to new InstructionKey(0) but I am not sure if this is correct. Thanks.

A: The InstructionKey is not necessary. This is part of code I have created :
Instruction applyActionsInstruction = new InstructionBuilder()
        .setOrder(0).setInstruction(new ApplyActionsCaseBuilder()
                .setApplyActions(applyActions)
                .build())
        .build();

instructions.add(applyActionsInstruction);

Instructions allInstructions = new InstructionsBuilder()
        .setInstruction(instructions)
        .build();

and it works fine, the Instruction is created even without the key specified.


text:
Q: Linked List Search not working (SIGBUS error and memory leak) i made a C program implementing linked lists but it won't work... everything i implemented was taken from websites or stackoverflow and it seems to be working for everyone, still does not work for me.
Everytime i run the program (which has an input of a series of word in STDIN, one for row) it gives me Process finished with exit code 138 (interrupted by signal 10: SIGBUS) and debugging it it seems to be stuck at if (strcmp(var->word, searched) == 0) line in the Search function... where am i wrong? I suppose there's something related to pointers but i do not understand what.
The programs starts working and prints something, then breaks and the temp value gets no word as it says read memory from 0x6c62430000600000 failed (0 of 1 bytes read).
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct node{
    char* word;
    struct node* next;
};

int search(struct node** head, char* searched);
void Print(struct node* head);
void Free_All(struct node* head);
void Insert(struct node** head, char* word);
void Delete(struct node* head, char* to_delete);
int Count(struct node* head);

int main() {
    static struct node *head = NULL;

    int temp;
    char word[20];

    for (;;) {
        temp = scanf("%s", word);

        if (strcmp(word, "Print") == 0) {
            Print(head);
        }
        else if (strcmp(word, "Stop") == 0) {
            break;
        }
        else if (temp == EOF) {
            Free_All(head);
            return 0;
        }
        else {
            Insert(&head, word);
        }
    }

    scanf("%s", word);
    int found = search(&head, word);

    if (found == 0) {
        printf("!! ERROR !!");
        return 1;
    }

    else {
        char to_delete[15];
        scanf("%s", to_delete);
        Delete(head,to_delete);

        // DO OTHER STUFF
    }

    int count = Count(head);
    printf("Remaining nodes: %d",count);
    Free_All(head);
}

int search(struct node** head, char* searched) {
    struct node* var = *head;

    while (var != NULL) {
        if (strcmp(var->word, searched) == 0)
            return 1;
        var = var->next;
    }
    return 0;
}

void Print(struct node* head){
    struct node* temp = head;
    while (temp) {
        printf("%s \n", temp->word);
        temp = temp->next;
    }
}

void Free_All(struct node* head){
    struct node* temp;
    temp = head;

    while( temp != NULL ){
        head= head->next;
        free(temp);
        temp = head;
    }
}

void Insert(struct node** head, char* word)
{
    // Create new node
    struct node* new_node = (struct node*)malloc(sizeof(struct node));
    new_node->word = malloc(strlen(word)+1);
    new_node->word = strcpy(new_node->word,word);
    new_node->next = NULL;

    if (*head== NULL || strcmp((*head)->word, new_node->word) >= 0) {
        new_node->next = *head;
        *head= new_node;
    }
    else {
        struct node* temp = *head;
        temp = *head;
        while (temp->next != NULL && strcmp(temp->next->word, new_node->word) < 0) {
            temp = temp->next;
        }
        new_node->next = temp->next;
        temp->next = new_node;
    }
}

void Delete(struct node* head, char* to_delete) {
    struct node *temp = head;
    struct node *prev = NULL;
    while(temp != NULL){
        if(strcmp(temp->word, to_delete) == 0)
        {
            if(prev == NULL){
                head = head->next;
                free(temp);
                return;
            }
            else{
                prev->next = temp->next;
                free(temp);
                return;
            }
        }
        prev = temp;
        temp = temp->next;
    }
}

int Count(struct node* head){
    int counter = 0;
    struct node* var = head;
    while (var != NULL)
    {
        counter++;
        var = var->next;
    }
    return counter;
}

EDIT: Solved typo in main

A: The function Delete accepts the pointer to the head node by value
void Delete(struct node* head, char* to_delete);

So the function deals with a copy of the value of the pointer head declared in main
static struct node *head = NULL;

Changing the copy of the value of the pointer head declared in main leaves the value of the original pointer unchanged.
You need to pass the pointer by reference through a pointer to it.
For example the function can be declared and defined the following way.
int Delete( struct node **head, const char *to_delete )
{
    while ( *head != NULL && strcmp( ( *head )->word, to_delete ) != 0 )
    {
        head = &( *head )->next;
    }

    int success = *head != NULL;

    if ( success )
    {
        struct node *tmp = *head;
        *head = ( *head )->next;
        free( tmp );
    }

    return success;
}

Pay attention to that this for loop
for (;;) {
    temp = scanf("%s", word);

    if (strcmp(word, "Print") == 0) {
        Print(head);
    }

    if (strcmp(word, "Stop") == 0) {
        break;
    } else if (temp == EOF) {
        Free_All(head);
        return 0;
    } else {
        Insert(&head, word);
    }
}

has a wrong logic. For example if the user will enter the string "Print" then apart from calling the function Print there will be called the function
Insert(&head, word);

And the function Free_All actually does not free all. It does not free character arrays pointed to by the data member word.
void Free_All(struct node* head){
    struct node* temp;
    temp = head;

    while( temp != NULL ){
        head= head->next;
        free(temp);
        temp = head;
    }
}

The function also shall accept the pointer to the head node by reference. It can look the following way
void Free_All( struct node **head )
{
    while ( *head != NULL )
    {
        free( ( *head )->word );
        struct node *tmp = *head;
        *head = ( *head )->next;
        free( tmp );
    }
}

A: I don't have the time or patience to go through line-by-line what's wrong with your code. Right now, Delete of first item on the list does NOT affect the 'head' pointer in 'main()', so using that pointer to Count() or FreeAll() is undefined behaviour.
Here's a bit of code. Use pencil & paper to keep track of the very few variables in use, and where pointers are pointing.
void Print( struct node *p ) {
    for( ; p; p = p->next )
        printf( "%s ", p->word );
    putchar( '\n' );
}

void Insert( struct node **head, char *word ) {
    // assemble new node
    struct node *nn = (struct node*)malloc( sizeof node );
    nn->word = (char*)malloc( strlen( word ) + 1 );
    nn->word = strcpy( nn->word, word );
    nn->next = NULL;

    // find insertion point
    struct node *pPrev = NULL;
    struct node *pThis = *head;
    while( pThis && strcmp( word, pThis->word ) >= 0 )
        pPrev = pThis, pThis = pThis->next;

    // insert into (possibly empty) list
    if( pThis ) nn->next = pThis;
    if( pPrev ) pPrev->next = nn;
    if( pThis == *head ) *head = nn; // new head?
}

void Delete( struct node **head, char *word ) {
    struct node *pPrev = NULL;

    for( struct node *pThis = *head; pThis; pPrev = pThis, pThis = pThis->next ) {
        int res = strcmp( pThis->word, word );

        if( res < 0 ) // not found yet
            continue;
        if( res > 0 ) // gone beyond, so not present
            break;

        // Found!
        if( pPrev ) pPrev->next = pThis->next; // excise from list
        if( pThis == *head ) *head = pThis->next; // change head??
        free( pThis->word ); // release memory
        free( pThis ); // release memory
        break;
    }
}

int main() {
    struct node *head = NULL;

    char word[20];

    printf( "Entry phase:\n" );
    for( ;; ) {
        Print( head );

        scanf( "%s", word );

        if( strcmp( word, "Stop" ) == 0 )
            break;

        Insert( &head, word );
    }

    printf( "Delete phase:\n" );
    while( head ) {
        Print( head );

        scanf( "%s", word );

        if( strcmp( word, "Stop" ) == 0 )
            break;

        Delete( &head, word );
    }

    return 0;
}

Output:
Entry phase:

baker
baker
delta
baker delta
able
able baker delta
epsilon
able baker delta epsilon
charlie
able baker charlie delta epsilon
Stop
Delete phase:
able baker charlie delta epsilon
able
baker charlie delta epsilon
epsilon
baker charlie delta
charlie
baker delta
baker
delta
delta
{ program halts }


text:
Q: Qt signals & inheritance question I am relatively new to programming with Qt and had a question.  Short version:
How do I inherit signals defined in superclasses?
I am trying to subclass someone else's nicely made QTWidgets to change some of the default behavior:

//Plot3D is a QWidget that defines a signal "rotationChanged"
class matLinePlot : public QObject, public Plot3D {

    Q_OBJECT;
        //etc...
public:
       //etc...

        //Catch Plot3D's signal "rotationChanged" and do some magic with it:
    void initPlot(){
              QObject::connect(this, SIGNAL(rotationChanged( double , double , double )),
            this, SLOT(myRotationChanged(double, double, double)));
    }
};

The problem is in the QObject::connect line.  What I would like to do is connect the rotationChanged SIGNAL (from qwt3D_plot.h) to a local function/SLOT - "myRotationChanged".  However whenever I do this, at run time I get:

Object::connect: No such signal matLinePlot::rotationChanged(double, double, double)

in C:...\matrixVisualization.h.   Of course, I know that rotationChanged isn't in matrixVisualization.h - it's in qwt_plot3D.h, but I thought that since I inherit from Plot3D everything should be fine.  But, now that I think about it, since SIGNAL and SLOT are macros, I assume MOC doesn't know/care about inheritance.
Which leads me to my question - since MOC and SIGNALS / SLOTS don't seem to know about inheritance etc: how can I subclass a widget defined somewhere else and get access to the widget's signals?
I have a lot of examples of how to use encapsulation to accomplish something like this, but I'm afraid I don't understand how to do this with inheritance.
Sorry if this is a ridiculous question - I feel like I'm missing something obvious.

A: SIGNAL(x) and SLOT(x) are macros that generate string literals.  At runtime, slots and signals are matched up using string compares of those generated literals.
(I would have added a comment to mdec's comment, but I don't have enough rep)

A: I guess the problem is the multiple inheritance:
class matLinePlot : public QObject, public Plot3D
...

I assume that Plot3D is a subclass of QObject? In this case, you should do
class matLinePlot : public Plot3D
...

instead.

A: I believe that will work if the Plot3D::rotationChanged signal is public or protected. Are you sure the signal is not private?
Edit:
Although I could not find a specific reference, I'll have to conclude that signals are always public. At least a test I did here seemed to indicate that I could connect to a signal even if it was declared in the private section of a class.
I also verified that a signal declared in QObject could be connected using a subclass of QObject in the connect statement so signals are definitely inheritable. As I see in other answers and comments here, the issue must be elsewhere.

A: Incorrect -> see comments.
I'm using Qtopia at Uni and I believe I recall someone saying something about spacing in the SIGNAL and SLOT parameters for connect.
Try using
QObject::connect(this, SIGNAL(rotationChanged(double,double,double)),
            this, SLOT(myRotationChanged(double,double,double)));

I know it doesn't seem intuitive, as C++ isn't sensitive to whitespace, however I believe it has something to do with some of the magic that Qtopia/QT uses when connecting signals and slots. This may only apply to Qtopia, or I may have heard wrong, but give it a try. Additionally are the signals public or protected and have you included the appropriate header files?


text:
Q: Accessing host computer's etc/hosts file inside of Docker not working I added an alias hostname to etc/hosts... something like 127.0.0.1 test.site and want to view it on the browser. I'm currently using Docker Desktop for Windows with a WSL2 environment setup.
I've tried running:
docker run -it --add-host=test.site:127.0.0.1 ubuntu and docker run --add-host wrapper.local:127.0.0.1 -p 4000:80 -ti ubuntu /bin/bash
... and when I run it on the browser I get the error This site can't be reached
I've also tried writing in a Dockerfile something like this:
FROM ubuntu:latest

ENTRYPOINT umount /etc/hosts && echo '127.0.0.1 test.site' > /etc/hosts && bash

... and then running:
docker run --privileged -it -p 3000:80 sample-site
In that case, I was trying to connect the computer's /etc/hosts to the container but I still got the same error.
What am I doing wrong?


text:
Q: golang - mysql panic: runtime error: invalid memory address or nil pointer dereference i trying to make a simple connection and getting data from database with golang, here the program that contain my API trial:
package main

import (
    // "encoding/json"
    "log"
    "net/http"
    "fmt"
    // "math/rand"
    // "strconv"
    "github.com/gorilla/mux"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)

// Book Struct(Model)
// type Book struct {
//  ID      string  `json:"id"`
//  Isbn    string  `json:"isbn"`
//  Title   string  `json:"title"`
//  // Author   *Author `json:"author"`
// }

// Article Struct(Model)
type Article struct {
    Author  string  `json:"author"`
    Title   string  `json:"title"`
    Body    string  `json:"body"`
    Created string  `json:"created"`
}

// //Author struct
// type Author struct {
//  Firstname   string  `json:"firstname"`
//  Lastname    string  `json:"lastname"`
// }

// Init books var as a slice book struct
// var books []Book

//get All Books
func getBooks(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    // json.NewEncoder(w).Encode(books)
}
//get single book
func getBook(w http.ResponseWriter, r *http.Request) {
    //
}
//create new book
func createBook(w http.ResponseWriter, r *http.Request) {
    //
}
//get All Books
func updateBook(w http.ResponseWriter, r *http.Request) {
    //
}
//get All Books
func deleteBook(w http.ResponseWriter, r *http.Request) {
    //
}

func main() {
    //init router
    r:= mux.NewRouter()

    //mock Data - @todo - implement DB
    // books = append(books, Book{ID: "1", Isbn: "436455", Title: "Book One", Author: &Author{Firstname: "John", Lastname: "Doe"}})
    // books = append(books, Book{ID: "2", Isbn: "436444", Title: "Book two", Author: &Author{Firstname: "Samuel", Lastname: "Etoo"}})

    db, err := sql.Open("mysql", "root:@tcp(127.0.0.1:3306)/api_golang")
    if err != nil {
        panic(err.Error())
    }

    defer db.Close()

    getarticle, err := db.Query("SELECT * FROM article")

    for getarticle.Next() {
        var article Article

        err = getarticle.Scan(&article.Author)
        if err != nil {
            panic(err.Error())
        }
        fmt.Println(article.Author)
    }
    //Route Handlers
    r.HandleFunc("/api/books", getBooks).Methods("GET")
    r.HandleFunc("/api/books/{id}", getBook).Methods("GET")
    r.HandleFunc("/api/books", createBook).Methods("POST")
    r.HandleFunc("/api/books{id}", updateBook).Methods("PUT")
    r.HandleFunc("/api/books{id}", deleteBook).Methods("DELETE")

    log.Fatal(http.ListenAndServe(":8000", r))
}

and here's the error report after build and run the program inside docker container:
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x618087]

goroutine 1 [running]:
database/sql.(*Rows).Next(0x0)
    /usr/local/go/src/database/sql/sql.go:2944 +0x27
main.main()
    /app/app.go:83 +0x165

i'm already make sure that the program is running fine just when trying to connect mysql database.
[UPDATE]
for the database connection, i use xampp for linux that contains apache and mysql. So, the database is not installed from docker.

A: 1.try with password
db, err := sql.Open("mysql",
    "user:password@tcp(127.0.0.1:3306)/test")
if err != nil {
    log.Fatal(err)
}
defer db.Close()

*the struct: Article has 4 param,so when use "scan",the param also need 4 param when "select * from ...".
"select author from article"


text:
Q: Python sorted order of files I have written the following code for a program to display the image path names in a folder. However, as seen in the output, the pictures' paths are not being displayed in the correct order despite me using sorted. How can I display them in their sorted order?
Code:
import os
import sys
from PIL import Image
import PIL.ImageOps
import glob

path="/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/"
print(path)
files=sorted(glob.glob(path+"*.JPG"))
#print(files)
file_index=0
for f in files:
    file_index=file_index+1
    print(f,file_index)

Output:
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/1.JPG 1
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/10.JPG 2
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/11.JPG 3
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/12.JPG 4
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/13.JPG 5
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/14.JPG 6
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/2.JPG 7
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/3.JPG 8
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/4.JPG 9
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/5.JPG 10
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/6.JPG 11
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/7.JPG 12
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/8.JPG 13
/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/9.JPG 14

A: This should work, assuming the file names are numbers.
import os
import sys
from PIL import Image
import PIL.ImageOps
import glob

path = "/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/"
print(path)
files = glob.glob(path+"*.JPG")
n = [int(i) for i in map(lambda x: x.split('/')[-1].split('.jpg')[0], files)]
files = [x for (y, x) in sorted(zip(n, files))]
print(files)

Essentially, your code isn't working because you sorted the files as strings.

A: As others have stated, you are comparing strings.
You could create a custom comparator for this:
files = glob.glob(path+"*.JPG")
sortedfiles = sorted(files, key=lambda filepath: int(filepath.split('/')[-1].split('.jpg')))

Whole snippet:
import os
import sys
from PIL import Image
import PIL.ImageOps
import glob

path="/home/srilatha/Desktop/Research_intern/Data_sets/Expanded_data_set/1/"
print(path)
files=glob.glob(path+"*.JPG")
sortedfiles = sorted(files, key=lambda filepath: int(filepath.split('/')[-1].split('.jpg')[0]))

for f in sortedfiles:
    file_index=file_index+1
    print(f,file_index)


text:
Q: Rails, path_names and nested resources My routes:
resources :events, :path_names => { :new => "organize" } do
    resources :forums
end

With these routes, I'll get urls like /events/:event_id/forums/organize. I don't want the path_names to propagate to my nested routes... Do I have to redefine path_names for them? Or use scope?
resources :events, :path_names => { :new => "organize" } do
    scope :path_names => { :new => "new" } do
        resources :forums
        # other nested resources...
    end
end

Or (my favorite, until you find a better solution ;))
resources :events, :path_names => { :new => "organize" }
resources :events, :only => [] do
    #nested resources...
end

Is there a more elegant way to do this? if you don't think so, you can also tell me which one is the best in your opinion.

A: I went for the last option:
resources :events, :path_names => { :new => "organize" }
resources :events, :only => [] do
    #nested resources...
end


text:
Q: Putting down axioms for some symbols. Playing with their consequences qualitatively and symbolically. Building theories. The book? I am interested in the design and building of theories. By building theories, I mean putting down axioms of various kinds, over various fields, exploring their perhaps interesting, or probably boring, consequences.
I would like to know if there are books:

*

*perhaps with a historical bent, characterizing the thoughts that went behind the design of a particular system of axioms for a catalogue of theories;

*perhaps with a non-historical bent, just exploring axiomatization in general;

*perhaps with a "fun" bent, attempting to recreate a well established mathematical theory from scratch;

*perhaps that are clearly a text on abstract algebra, but one that explores qualitatively the various consequences of choosing particular axioms?
Does such a book exist, or am I dreaming?

A: I'm not sure that there's a single book that fits your varied desiderata. But, just addressing the first of the bullet points, the history of the axiomatization of geometry (and then geometries, plural) is surely an obvious place to start. There is a rich but very readable article by Marvin Greenberg here. And then, for a lot more, there is Greenberg's book mentioned in his biblio.

A: I suggest you :

Robin Hartshorne, Geometry: Euclid and Beyond (2005)

and

Ian Mueller, Philosophy of Mathematics and Deductive Structure in Euclid's Elements (1st ed 1981).

Both deal with geometry and have an historical bent (no "fun").
You can see also :

Howard Eves, Foundations and Fundamental Concepts of Mathematics (1st ed 1990), with a nice Chapter 6 on Formal Axiomatics; it deals also with algebra and number systems (no "fun").

Regarding the development of modern algebra and axiomatics, see :

Leo Corry, Modern Algebra and the Rise of Mathematical Structures (2004).

With a different point of view, can be interesting also :

PhilipJ Davis & Reuben Hersh, The Mathematical Experience (1st ed 1981).

In conclusion, I think that it will be not easy to find references "helping" with the "design of a particular system of axioms for a catalogue of theories".


text:
Q: Setting notifications at different times in android I have an android app.I want to produce five notifications at five different times which are setted by the user.The notifications should produced if my app will not be running...How can I do this?
In the below class I am comparing the db notification values with the devices time in an infinite while loop in oncreate().res1,res2...res5 are the five notification times stored in the db.day4 is the system time...
MyService.java
ppublic class MyService extends Service {
              private static final String DATABASE_NAME = "MYPRAYER.db";
              private static final String DATABASE_TABLE = "notification";
              String tag="TestService";
                String a="hello";
                String res1,res2,res3,res4,res5;
                int hour,minute;
                String day3,day4,minute1,hour1;
                MediaPlayer mMediaPlayer;
                   /* Service creation */
               @Override
               public void onCreate() {
             super.onCreate();
               Toast.makeText(this, "Service created...", Toast.LENGTH_LONG).show();
               Log.i(tag, "Service created...");

                  /* Rereive notification times from the databse notificaion */
              SQLiteDatabase myDB;
            myDB = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
            String[] resultColumns = new String[] {"fajr","zuhr","asr","magrib","isha"};
            Cursor allRows = myDB.query(DATABASE_TABLE, resultColumns, null, null, null, null, null, null);

            Integer cindex = allRows.getColumnIndex("fajr");
            Integer cindex1 = allRows.getColumnIndex("zuhr");
            Integer cindex2 = allRows.getColumnIndex("asr");
            Integer cindex3 = allRows.getColumnIndex("magrib");
            Integer cindex4 = allRows.getColumnIndex("isha");
            allRows.moveToFirst();
            res1=allRows.getString(cindex);
            res2=allRows.getString(cindex1);
            res3=allRows.getString(cindex2);
            res4=allRows.getString(cindex3);
            res5=allRows.getString(cindex4);

            myDB.close();

            while(!Thread.currentThread().isInterrupted())
            {
            try
            {

                Calendar cal = Calendar.getInstance(); // Rereive calender date
                hour = cal.get(Calendar.HOUR_OF_DAY); // Take hour from the calender
                minute = cal.get(Calendar.MINUTE);    // Take minute from the calender
                minute1=minute + "";  // Convert minute to dtring
                if(minute1.equals("1"))
                {
                minute1="01";
                }
                else if(minute1.equals("2"))
                {
                minute1="02";
                }
                else if(minute1.equals("3"))
                {
                minute1="03";
                }
                else if(minute1.equals("4"))
                {
                minute1="04";
                }
                else if(minute1.equals("5"))
                {
                minute1="05";
                }
                else if(minute1.equals("6"))
                {
                minute1="06";
                }
                else if(minute1.equals("7"))
                {
                minute1="07";
                }
                else if(minute1.equals("8"))
                {
                minute1="08";
                }
                else if(minute1.equals("9"))
                {
                minute1="09";
                }
                     /* Converting to 12 hour format */
                if ( hour < 12 )
                {
                     hour=hour;
                     day3=hour + "" + ":" + minute1;
                     day4=day3 + " " + "AM"; // DAY4 Contains the system time
                }
                else
                {
                    hour=hour-12;
                    day3=hour + "" + ":" + minute1;
                    day4=day3 + " " + "PM";
                }

                if(day4.equals(res1))
              {
                     Notification("Notification Title","Notification Message");

              }

                 if(day4.equals(res2))
                  {
                         Notification("Notification Title","Notification Message");

                  }

                 if(day4.equals(res3))
                  {
                         Notification("Notification Title","Notification Message");

                  }
                 if(day4.equals(res4))
                  {
                         Notification("Notification Title","Notification Message");

                  }
                 if(day4.equals(res5))
                  {
                         Notification("Notification Title","Notification Message");

                  }

               Thread.sleep(1000);
       }
       catch (InterruptedException e)
       {
               Thread.currentThread().interrupt();
               //System.out.println("New 1 Exception here");

       }

       catch (Exception e)
      {
               //Thread.currentThread().interrupt();
           System.out.println("nEW Exception here");
      }
       }

       }
          @Override
          public void onStart(Intent intent, int startId) {
          super.onStart(intent, startId);
          Log.i(tag, "Service started...");
       }
         @Override
         public void onDestroy() {
         super.onDestroy();
         Toast.makeText(this, "Service destroyed...", Toast.LENGTH_LONG).show();
       }

         @Override
         public IBinder onBind(Intent intent) {
         return null;
        }

         private  void Notification(String notificationTitle, String notificationMessage)
       {
         NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
         Notification notification = new Notification(R.drawable.ic_launcher, "A New Message!", System.currentTimeMillis());

         Intent notificationIntent = new Intent(this,MyService.class);
         PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

         notification.setLatestEventInfo(MyService.this, notificationTitle, notificationMessage, pendingIntent);
         notificationManager.notify(10001, notification);
   //HELLO_ID++;
         Uri alert = RingtoneManager.getDefaultUri(
        RingtoneManager.TYPE_NOTIFICATION);

        mMediaPlayer = new MediaPlayer();
      try
      {
      mMediaPlayer.setDataSource(this, alert);

      AudioManager audioManager = (AudioManager)getSystemService(
                                  Context.AUDIO_SERVICE);
      int volumen = audioManager.getStreamVolume(
                    AudioManager.STREAM_NOTIFICATION);

      if (volumen != 0) {
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
        mMediaPlayer.setLooping(true);
        mMediaPlayer.prepare();
        mMediaPlayer.start();
      }
      }
      catch(IOException e)
      {
          System.out.println("Exception here");
          //System.out.println("Exception 1 here");
      }
      }
          }

Logcat:
07-27 16:25:00.542: I/TestService(363): Service created...
07-27 16:25:20.752: I/dalvikvm(363): threadid=7: reacting to signal 3
07-27 16:25:20.803: I/dalvikvm(363): Wrote stack trace to '/data/anr/traces.txt'

A: What I did was use AlarmManager that triggers a BroadcastReceiver to set the notification. So search that on the Android docs. There are also a lot of resources on that stuff. Others might also tell you not to use BroadcastReceiver, but rather use a Service. To be honest it can go both ways, so whatever choice you make should be fine. As for notification, you can easily google notifications to find resources on that. Search Status Notifications.


text:
Q: Trying to add the Information emoji to webpage I'm trying to add the white i on blue button information emoji to a webpage and I'm only seeing the i on a white background. Hoping someone can help.
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="UTF-8">

For more information ℹ

A: You missed the meta charset on the top. Don't forget to include that. Also from your question it seems like you missed the color style. Here's the full code

a {
  color: #ffffff;
  text-decoration: none;
  font-weight: bold;
  background-color: #00a6ed;
  width: 2.5rem;
  height: 2.5rem;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-size: 1.8rem;
  border-radius: .5rem;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="../css/global_styles.css" rel="stylesheet" />
  <meta charset="UTF-8">

i


text:
Q: SAN failover with Solaris 11 express Is there a good solution to provide failover between two identical servers based on Solaris 11 Express? We replicate data between the two SANs now, but want to setup a failover solution.
I have looked at IPMP as a alternative, but is not sure if it is a good solution when it is between two hosts? As the SAN2 is identical to SAN1 and communicates through iSCSI, a IP address change should be a working solution? It's most likely that the clients lose any active sessions, but it would be a minimal impact and downtime(?)

A: If you are looking for HA solutions based on Solaris then you probably don't want to go Solaris 11 Express. Even Oracle Solaris Cluster doesn't support Solaris 11 Express.
Stick with 10 unless there is a compelling, overriding need to go with 11.


text:
Q: Customise hover of parcats plotly.js chart I've used a plotly.js parcats chart to make a sequential sankey (eg https://github.com/EE2dev/sequence-explorer). Here are the example parcats that shows changes in grades between quizzes:
var trace1 = {
  type: 'parcats',
  hoveron: 'color',
  dimensions: [
    {
      label: 'Quiz 1',
      values: ['Black', 'Black', 'Black', 'Brown', 'Brown', 'Brown', 'Red', 'Brown'],
    },
    {
      label: 'Quiz 2',
      values: ['Brown', 'Brown', 'Brown', 'Brown', 'Brown', 'Blue', 'Blue', 'Blue'],
    },
    {
      label: 'Quiz 3',
      values: ['Female', 'Female', 'Female', 'Male', 'Female', 'Male', 'Male', 'Male'],
    },
  ],
};

var data = [ trace1 ];

var layout = {width: 600};

Plotly.newPlot('myDiv', data, layout);

When I hover over a path the full path from 'Quiz 1' to 'Quiz 3' highlights but what I'd like is for only the path between 'Quiz 1' to 'Quiz 2' to highlight. I tried hover on but nothing changed.
This is the fiddle

var trace1 = {
  type: 'parcats',
  hoveron: 'color',
  dimensions: [
    {
      label: 'Quiz 1',
      values: ['Black', 'Black', 'Black', 'Brown', 'Brown', 'Brown', 'Red', 'Brown'],
    },
    {
      label: 'Quiz 2',
      values: ['Brown', 'Brown', 'Brown', 'Brown', 'Brown', 'Blue', 'Blue', 'Blue'],
    },
    {
      label: 'Quiz 3',
      values: ['Female', 'Female', 'Female', 'Male', 'Female', 'Male', 'Male', 'Male'],
    },
  ],
};

var data = [ trace1 ];

var layout = {width: 600};

Plotly.newPlot('myDiv', data, layout);

Is there a way to customize the hover functionality?

A: Unfortunately, I believe that's not possible on this specific parcats ploty chart.
When this parcats chart is created, its generate an svg path for each "ROW", and when i say "ROW" you can understand it being like this:

*

*Row 1: Black   - Brown - Female

*Row 2: Brown - Brown - Female

*Row 3: Brown - Brown - Male

*Row 4: Brown - Blue  - Male

*Row 5: Red   - Blue  - Male

This way, we can say that your chart has 5 "ROWS".
And as I said before, each of this "ROW" is a SVG path, like this:
<path class="path" stroke-opacity="1" fill="#1f77b4" fill-opacity="0.6"
stroke="lightgray" stroke-width="0.2" d="M 40,0l16,0 C56,0 544,4 544,
4l16,0 C560,4 1048,4 1048,4l16,0 l0,95.25 l -16,0 C1048,99.25 560,
99.25 560,99.25l-16,0 C544,99.25 56,95.25 56,95.25l-16,0 Z"></path>

So, when you hover this path, it changes fill-opacity, stroke and stroke-width, like this:
<path class="path" stroke-opacity="1" fill="#1f77b4" fill-opacity="0.8"
stroke="white" stroke-width="0.3" d="M 40,0l16,0 C56,0 544,4 544,
4l16,0 C560,4 1048,4 1048,4l16,0 l0,95.25 l -16,0 C1048,99.25 560,
99.25 560,99.25l-16,0 C544,99.25 56,95.25 56,95.25l-16,0 Z"></path>

Therefore, its not possible to highlight only paths 'Quiz 1' to 'Quiz 2' when you hover it.
What you can do here, is use the sankey chart type instead:

var trace1 = {
  type: "sankey",
  orientation: "h",
  node: {
   groups: ["Quiz 1", "Quiz 2", "Quiz 3"],
   label: ["Black", "Brown", "Red", "Brown", "Blue", "Female", "Male"],
   color: ["blue", "blue", "blue", "blue", "blue", "blue", "blue"]
  },
  link: {
    source: [0,1,1,1,2,3,3,3,4,4],
    target: [3,3,3,4,4,5,5,6,6,6],
    value:  [3,1,1,2,1,3,1,1,2,1]
  }
};

var data = [ trace1 ];

var layout = {
   title: {
      text:'SANKEY Title',
      font: {
         family: 'Courier New, monospace',
         size: 24
      },
   },
   annotations: [{
      text: 'QUIZ 1',
      x: 0.0,
      y: 1.1,
      showarrow: false,
      font: {size: 12}
    },
    {
      text: 'QUIZ 2',
      x: 0.5,
      y: 1.1,
      showarrow: false,
      font: {size: 12}
    },
    {
      text: 'QUIZ 3',
      x: 1.0,
      y: 1.1,
      showarrow: false,
      font: {size: 12}
    }],
   width: 600,
};

Plotly.newPlot('myDiv', data, layout);

As you can see, isn't exactly like the parcats chart, but it does the job.
Some infos about this chart:

*

*Unlike parcats, it creates an svg path for each part of the chart, so the highlight hover is separated for each path.

Just to be clear, the Row 1: Black - Brown - Female has now TWO svg paths, like:

<path class="sankey-link" d="M30,1.9895196601282805e-13C603.5,
1.9895196601282805e-13 603.5,15.000000000000114 1177, 15.000000000000114L1177,
105.00000000000011C603.5,105.00000000000011 603.5,90.0000000000002 30,90.0000000000002Z"
style="stroke: rgb(68, 68, 68); stroke-opacity: 1; fill: rgb(0, 0, 0); fill-opacity: 0.2;
stroke-width: 0; opacity: 1;"></path>

<path class="sankey-link" d="M1207,15.000000000000114C1780.5,
15.000000000000114 1780.5,15.000000000000142 2354,15.000000000000142L2354,
105.00000000000014C1780.5,105.00000000000014 1780.5,
105.00000000000011 1207,105.00000000000011Z" style="stroke: rgb(68, 68, 68);
stroke-opacity: 1; fill: rgb(0, 0, 0); fill-opacity: 0.2; stroke-width: 0; opacity: 1;"></path>

*

*This chart need to have the Link field, with the specific values (source, target and value). You can check more about this option here.

*You can edit and customize the labels in this chart. You can check more about it here and here.

A: As far as I understand, the Parallel Categories Diagram is aimed at working with whole lines and it does not have the ability to select individual line segments.
However, there is another diagram that looks similar and yet focuses on individual segments. This is the Sankey Diagram. But it requires rearranging the original data to indicate exactly how the individual values change on each segment.

*

*Set the type parameter as sankey.

*In the label parameter, we sequentially list all the values that occur in our diagram.
First for the first quiz (Black, Brown, Red), then for the second (Brown, Blue) and finally for the third (Female, Male).

*Thus, we turn all the values into array elements, and thanks to this we can access them by their indecies.
For example, Brown from the first quiz has index 1, and Brown from the second quiz has index 3
(the indices in the array start from zero).
Then we use these indices in the source and target parameters.

*The values in link describe all the segments in the diagram.
For convenience, I have arranged them in columns.
For example, the first column 0, 3, 3 means that Black in the Quiz 1 (index 0 in source) and Black in the Quiz 2 (index 3 in the target) have 3 participants (3 in value).

For example: https://jsfiddle.net/glebkema/subnqp8v/

var trace1 = {
  type: 'sankey',
  node: {
    pad: 15,
    thickness: 20,
    line: {
      color: "black",
      width: 0.5
    },
    label: [
      'Black', 'Brown', 'Red',  // Quiz 1
      'Brown', 'Blue',          // Quiz 2
      'Female', 'Male'          // Quiz 3
    ],
    color: "blue",
  },
  link: {
    //        Quiz 1 -> Quiz 2                  Quiz 2 -> Quiz 3
    //        Quiz 1: Black Brown Red  Brown    Quiz 2: Brown  Brown Blue
    source: [         0,    1,    1,   2,               3,     3,    4   ],
    //        Quiz 2: Brown Brown Blue Blue     Quiz 3: Female Male  Male
    target: [         3,    3,    4,   4,               5,     6,    6   ],
    value:  [         3,    2,    2,   1,               4,     1,    3   ],
  },
};

var data = [ trace1 ];

var layout = {width: 600};

Plotly.newPlot('myDiv', data, layout);


text:
Q: Why are most consumer electronics power supply boards single sided and made of FR2 (Phenolic resin) Most consumer appliances/power adapters that I open up have an SMPS providing the power. This SMPS is layed out on a phenolic resin (FR2) board and is usually a one-sided layout. Can anyone explain why power supply boards are designed as such?
My guess is that this board mostly contains through hole components, and is easier to wave solder when laid out on a single side. Since FR4 is used for multilayer boards/through hole plating and vias, it is cheaper to lay the power supply out on this type of board.

A: FR2 can be punched instead of drilled.  FR4 has to be drilled.  When you're making 100's of thousands, it's worthwhile to make one big punch and do a ton of boards in one pass.  Drilling is expensive and takes time.   So it's "cost"  ;)
It's because of the materials they're made of.  FR2 is paper phenolic resin.  FR4 is fiberglass
Single sided boards are a lot cheaper to work with 'cuz you only have to process one side of them.

A: Cost. It is cheap, and it is good enough.
"The best is the enemy of the good enough"

A:
Why are most consumer electronics power supply boards single sided and made of FR2 (Phenolic resin)?

Cost. The FR2 will be a bit cheaper than glass fibre boards and may be a little easier to machine meaning less tooling cost. Single-sided board will be cheaper than double-sided due to reduced copper cost and processing steps.

Figure 1. XT PC Power Supply PCB - Component Side. Source.

Figure 2. XT PC Power Supply PCB - Solder Side. Source.
Note that some of the traces are rather circuitous to avoid crossover connections on the other side of the board.

Can anyone explain why power supply boards are designed as such?

The circuits aren't so complex and the board can be laid out without the need for wire jumper links. There are none visible in Figure 1.

My guess is that this board mostly contains through hole components, and is easier to wave solder when laid out on a single side.

Double-sided boards are generally wave-soldered in the same way. The traces on top facilitate jumping over other traces and the through hole vias connect the the two layers.

Since FR4 is used for multilayer boards/through hole plating and vias, it is cheaper to lay the power supply out on this type of board.

Yes. You could get a feel for the cost saving by trying to price, say, 1000 PCBs on one of the online PCB manufacturing companies.

A: You will find most PCBs are are made with the copper pre bonded to both sides and it is etched away to make the spaces for the traces. While the designer of the board could specify traces/pad/etc only on the bottom, which will require all of the copper to be removed from one side and hence have little difference in cost to a 2 layer board. I doubt most manufacturers would keep any stock of 1 sided pcb cores. It would be most likely a custom order and if the quality was high enough would maybe justify the saving. 1 sided boards are terrible at containing the return currents for every trace and can lead to crosstalk and high interferance issues. There would be a cost saving not having to plate vias in 2 sided boards, but it is a minimal cost for a better design. If you make millions of units it might be worth the cost saving using a single sided core.

A: One reason for single sided boards in consumer electroniss is they are easily serviceable, and it is easy to service them during the warranty period instead of repairing the whole board.

A: The power supply boards having higher voltage, have higher risk of arcing, static and carbon formation making the circuit in-efficient and higher power losses and pose risk of short circuit damaging the psu and could be harmful.


text:
Q: Use NodeJS to run YUI compressor for output file I tried to use YUI Compressor to compress my js file through NodeJS according to the document.
I require the module, successfully output the compressed string. Then I tried to  output any file, but failed. The document says the option -o is used for output file.
Is it possible to use -o in NodeJS as well ? How ?
P.S., I know how to output file in java command (YUI Compressor is based on java).

A: Nope you can't pass -o in the options sent from your node program (these are the valid options if you use the compressor in a node program) however you can write the file on your own
var compressor = require('yuicompressor');
var fs = require('fs');

compressor.compress('/path/to/file or String of JS', {
    //Compressor Options:
    charset: 'utf8',
    type: 'js',
    nomunge: true,
    'line-break': 80
}, function(err, data, extra) {
    //err   If compressor encounters an error, it's stderr will be here
    //data  The compressed string, you write it out where you want it
    //extra The stderr (warnings are printed here in case you want to echo them
    if (err) throw err
    fs.writeFileSync('./output.js', data)
});


text:
Q: JHipster, AngularJS- After login, based on user authority how to take user to different pages new to both AngularJS & JHipster and appreciate any help.
I currently have two user authorities, ROLE_ADMIN, and ROLE_USER. After logging in I would like to be able to direct the user to different pages (that they have access to). I believe I have been able to narrow down the issue to my sign in controller:
function login (event) {
event.preventDefault();
Auth.login({
    email: vm.email,
    password: vm.password,
    rememberMe: vm.rememberMe
}).then(function () {
    vm.authenticationError = false;
    $state.go('home', {}, {reload: true});

    $rootScope.$broadcast('authenticationSuccess');

    // previousState was set in the authExpiredInterceptor before being redirected to login modal.
    // since login is successful, go to stored previousState and clear previousState
    if (Auth.getPreviousState()) {
        var previousState = Auth.getPreviousState();
        Auth.resetPreviousState();
        $state.go(previousState.name, previousState.params);
    }
}).catch(function () {
    vm.authenticationError = true;
});}

If I change $state.go('home', {}, {reload: true}); to $state.go('trips', {}, {reload: true}); ('home' -> 'trips'), or change that to another page it works fine, so long as that user has the proper privileges, if not it goes to an error page.
Intuitively, I would like to add something like:
if (authority === 'ROLE_ADMIN') {
    $state.go('home', {}, {reload: true});
} else if (authority === 'ROLE_USER') {
    $state.go('trips', {}, {reload: true});
}

But I cannot find a way to access what authority I am in/using. I have also looked in auth.service.js and logged about everything I could think of to see if it is lurking in there somewhere.
If anyone has any suggestions or can point me in the right direction that would be very helpful! Thanks!

A: stumbled across a solution with the help of a friend and wanted to share in case anyone else had the same issue... or, even better, a more elegant solution.
Looking into what Principal was doing in some of the other controllers found that result will return true or false
Principal.hasAuthority('ROLE_XYZ').then( function(result) {
    if(result) {
        $state.go('trips', {}, {reload: true});
    }
Principal.hasAuthority('ROLE_QWEQWE').then( function(result) {
    if(result) {
        $state.go('home', {}, {reload: true});
    }

As a result I just repeated and replaced ROLE_XYZ with the authority in question and that routes me to the page I am looking to get to.


text:
Q: CoronaSDK - clip the listview using tableview library I have a navbar at the top of a screen with a listview.  The problem is that, even in the sample code for the listview samples, you can click on the navbar, and the capture phase will not end at the navbar, but instead continues all the way to the listview.  This makes it so that, as soon as you scroll the list underneath the navbar, any click on the navbar captures the click on the list item instead of on the navbar buttons.  I've tried to add the navbar group back to the maingroup on the handler, but that doesn't seem to work (visually, it's still on top, anyway).  I also tried returning true when the navbar button was clicked to end the capture phase, but that didn't work, either.
I want to be able to go from one listview to another (drill-down type), but that's a problem right now as you can't scroll the list and then access the navbar.

A: OK, I was close to the answer the first time, but misstepped just enough to throw myself off.  The key is to put the "return true" statement during the "began" phase.  That did the trick.


text:
Q: Sencha Theming with Compass and Sass not working I am trying to build a custom theme. I added the $base-color and $base_gradient properties to my resources/sass/app.scss and compiled it by issuing compass compile from the folder. The compilation worked and replaced the css/app.csss. However I am not seeing the changes reflected in my application. How do I change the theme with sass and compass?

A: Base gradient takes a - not a _
Then check that your var are defined after the line (should not matter for base-color but better to put them after)
@import 'sencha-touch/default/all';

Your vars should be defined like this :
$base-color: #7A1E08;
$base-gradient: 'glossy';

Check that you are in the [app-folder]/resources/sass/app.css and not in the sdk folder
When compiling you should see the following line
overwrite ../css/app.css

Empty your browser cache then reload your app.


text:
Q: KSQL stream from Kafka Topic Maintain same partition values I am creating a ksql stream from kafka topic. Source topic has 50 partitions, and target stream also has 50 partitions, But the issue is  source partition 1 is going to random partition in the target stream ( example partition 10).
Schema:
CREATE STREAM SCHEMA_BASE (
ID VARCHAR,
Timestamp VARCHAR,
CITY VARCHAR,
Partition INTEGER) WITH (
KAFKA_TOPIC = 'SPARK_EVENTS',
VALUE_FORMAT = 'JSON',
TIMESTAMP_FORMAT = 'yyyy-MM-dd''T''HH:mm:ss.SSSSSSS''Z''',
TIMESTAMP = 'Timestamp'
);
Stream : CREATE STREAM spark_event_streams as
SELECT
ID,
Timestamp,
CITY,
Partition
FROM
SCHEMA_BASE
PARTITION BY Partition;
Is there a way I can force the target stream to use exact partitioning??

A: Custom partitioning is not supported in ksqlDB, and ksqlDB always uses the default partitioner, that implement a round-robin strategy if the message key is null.
I filed https://github.com/confluentinc/ksql/issues/7984 to maybe extend ksqlDB with a new feature.


text:
Q: How to import StreamingResponseBody in spring mvc project? I am trying to import it from "org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody". But it is showing me an error that the import cannot be resolved.
Actually I am using it as the equivalent class of StreamingOutput Class in java to loop through very large set of data using hibernate.
For further reference u can see the below link:
http://mitchdickinson.com/exporting-very-large-data-sets-with-hibernate-jax-rs/

A: You need to add spring-mvc as dependency:
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>

The class StreamingResponseBody is introduced in Spring 4.2
You can use the version - 4.3.7.RELEASE in maven pom.xml file


text:
Q: IF Statement simplification How does one achieve multiple checks against one value? I think I'm being a little bit stupid...
What I want to achieve is this:
if(basename($_SERVER['SCRIPT_NAME']) != ("1.php" || "2.php" || "3.php"){
    header('Location: elsewhere.php');
}

rather than:
if(basename($_SERVER['SCRIPT_NAME']) != "1.php" && basename($_SERVER['SCRIPT_NAME']) != "2.php" && basename($_SERVER['SCRIPT_NAME']) != "3.php" && basename($_SERVER['SCRIPT_NAME']) != "4.php"){
    header('Location: elsewhere.php');
}

I've written it out a few times but I'm clearly licking windows.
Thanks in advance!

A: you can write
$files = array("1.php", "2.php", "3.php", "4.php");//so on

if(!in_array(basename($_SERVER['SCRIPT_NAME']), $files)){
    header('Location: elsewhere.php');
}

yes another method is (little bit faster than above one)
if(array_diff((array)(basename($_SERVER['SCRIPT_NAME'])),array("1.php", "2.php", "3.php", "4.php")))
{
 header('Location: elsewhere.php');
}


text:
Q: how to order result by displaying each job type by order I have a search query which search for all jobs in the database and than displays them in accordance to the most recent ones filtering the data by date as follows:
  result = db.AllJobModel.Where(a => a.JobTitle.Contains(searchTitle) && a.locationName.Contains(searchLocation)).ToList());

      result = (from app in result orderby DateTime.ParseExact(app.PostedDate, "dd/MM/yyyy", null) descending select app).ToList();

result = GetAllJobModelsOrder(result);

after that I have a method GetAllJobModelsOrder which displays jobs in order which seems to be work fine but in my case its not ordering jobs so I need to understand where I am wrong:
 private List<AllJobModel> GetAllJobModelsOrder(List<AllJobModel> result)
    {
        var list = result.OrderBy(m => m.JobImage.Contains("job1") ? 1 :
                       m.JobImage.Contains("job2") ? 2 :
                       m.JobImage.Contains("job3") ? 3 :
                       m.JobImage.Contains("job4") ? 4 :
                       m.JobImage.Contains("job5") ? 5 :
                       6)
         .ToList();
        return list;
    }

The result I get is about 10 jobs from job1 and than followed by other jobs in the same order what I would like to achieve is to filter the most recent jobs than display one job from each type of a job.
An example of the input would be as follows:
    AllJobModel allJobModel = new AllJobModel
    {

        JobDescription = "Description",
        JobImage = "Job1",
        JobTitle = "title",
        locationName = "UK",
        datePosted = "15/06/2020",
    }

The output that I get is as follows:

In where result should be mixed from different jobs.
Excepted resulta as follows a specific order of job source--1. TotalJob[0] :: 2. MonsterJob[0] :: 3. Redd[0] :: 4. TotalJob[ 1 ] :: 5. MonsterJob[ 1 ] ::6. Redd[ 1 ]:

I have tried the following solution but list data structure seems to be not stroing data in order:
     private List<AllJobModel> GetAllJobModelsOrder(List<AllJobModel> result)
    {

        string lastItem = "";
        List<AllJobModel> list = new List<AllJobModel>();
        int pos = -1;
        while(result.Count != 0)
        {
            for(int i  = 0; i < result.Count; i++)
            {
                if(result[i].JobImage.Contains("reed") && (lastItem == "" || lastItem == "total" || lastItem == "monster"))
                {
                    pos++;
                    list.Insert(pos,result[i]);
                    lastItem = "reed";
                    result.Remove(result[i]);
                    break;
                }else if (result[i].JobImage.Contains("total") && (lastItem == "reed" || lastItem == "monster" || lastItem == ""  ))
                {
                    pos++;
                    list.Insert(pos, result[i]);
                    lastItem = "total";
                    result.Remove(result[i]);
                    break;
                }else if(result[i].JobImage.Contains("monster.png") && (lastItem =="total" || lastItem == "reed" || lastItem == ""  ))
                {
                    pos++;
                    list.Insert(pos, result[i]);
                    lastItem = "monster";
                    result.Remove(result[i]);
                    break;
                }else if(result[i].JobImage.Contains("reed") &&( lastItem == "reed"))
                {
                    if(result.FirstOrDefault(a=>a.JobImage.Contains("total") || a.JobImage.Contains("monster")) != null)
                    {
                        lastItem = "total";
                        break;
                    }
                    else
                    {
                        pos++;
                        list.Insert(pos, result[i]);
                        lastItem = "reed";
                        result.Remove(result[i]);
                        break;
                    }

                }
                else if (result[i].JobImage.Contains("total") && (lastItem == "total"))
                {
                    if (result.FirstOrDefault(a => a.JobImage.Contains("reed") || a.JobImage.Contains("monster")) != null)
                    {
                        lastItem = "monster";
                        break;
                    }
                    else
                    {
                        pos++;
                        list.Insert(pos, result[i]);
                        lastItem = "total";
                        result.Remove(result[i]);
                        break;
                    }
                }
                else if (result[i].JobImage.Contains("monster") && (lastItem == "monster"))
                {
                    if (result.FirstOrDefault(a => a.JobImage.Contains("total") || a.JobImage.Contains("reed")) != null)
                    {
                        lastItem = "reed";
                        break;
                    }
                    else
                    {
                        pos++;
                        list.Insert(pos, result[i]);
                        lastItem = "monster";
                        result.Remove(result[i]);
                        break;
                    }
                }

            }
        }

        return list;

    }

also what I found is that the value of the elements in the list is different from what its actual value. So I am not sure if this is an error with my code or with visual studio:

A: you can use the below concept here. I am sorting a list based on the numeric value at the end of each string value using Regex.
List<string> ls = new List<string>() { "job2", "job1", "job4", "job3" };
ls = ls.OrderBy(x => Regex.Match(x, @"\d+$").Value).ToList();

A: Certainly the requirement was not as straight forward as initially thought. Which is why I am offering a second solution.
Having order by and rotate the offering "Firm" in a type of priority list for a set number of times and then just display whatever comes after that requires a custom solution. If the one algorithm you have works and you are happy then great. Otherwise, I have come up with this algorithm.
    private static List<AllJobModel> ProcessJobs(List<AllJobModel> l)
    {
        var noPriorityFirst = 2;
        var orderedList = new List<AllJobModel>();
        var priorityImage = new string[] { "TotalJob", "MonsterJob", "Redd" };

        var gl = l.OrderBy(o => o.datePosted).GroupBy(g => g.datePosted).ToList();

        foreach (var g in gl)
        {
            var key = g.Key;
            for (int i = 0; i < noPriorityFirst; i++)
            {
                foreach (var j in priorityImage)
                {
                    var a = l.Where(w => w.datePosted.Equals(key) && w.JobImage.Equals(j)).FirstOrDefault();
                    if (a != null)
                    {
                        orderedList.Add(a);
                        var ra = l.Remove(a);
                    }
                }
            }
            foreach (var j in l.ToList())
            {
                var a = l.Where(w => w.datePosted.Equals(key)).FirstOrDefault();
                if (a != null)
                {
                    orderedList.Add(a);
                    var ra = l.Remove(a);
                }
            }
        }

        return orderedList;
    }

To test this process I have created this Console app:
static void Main(string[] args)
{
    Console.WriteLine("Start");
    var l = CreateTestList();
    var lJobs = ProcessJobs(l);
    lJobs.ForEach(x => Console.WriteLine($"{x.datePosted} : {x.JobImage}"));
}

private static List<AllJobModel> CreateTestList()
{
    var orderedList = new List<AllJobModel>();
    var l = new List<AllJobModel>();
    var priorityImage = new string[] { "TotalJob", "MonsterJob", "Redd" };
    var rand = new Random();

    var startTime = DateTime.Now;
    for (int i = 0; i < 20; i++)
    {
        var j = rand.Next(0, priorityImage.Length);
        var h = rand.Next(0, 4);
        var a = new AllJobModel();
        a.JobDescription = "Desc " + i;
        a.JobImage = priorityImage[j];
        a.JobTitle = "Title" + i;
        a.locationName = "UK";
        a.datePosted = startTime.AddDays(h);
        l.Add(a);
    }

    for (int i = 0; i < 20; i++)
    {
        var j = rand.Next(0, priorityImage.Length);
        var h = rand.Next(0, 4);
        var a = new AllJobModel();
        a.JobDescription = "Desc " + i;
        a.JobImage = "Job " + i;
        a.JobTitle = "Title" + i;
        a.locationName = "UK";
        a.datePosted = startTime.AddDays(h);
        l.Add(a);
    }

    return l;
}