text
stringlengths 14
21.4M
|
---|
Q: Creating relationships between posts in WordPress Is there a way to create an exlicit relationship between two posts in WordPress regarless of what categories those posts might be in?
The idea is that within the post template it would be obtain and list the related posts for the current post.
I'm guessing you could achieve this using tags to group posts together, but that seems to be a hi-jacking of the tag system for a purpose for which is wasn't designed.
Any ideas?
A: Would adding post IDs as meta data help? I had written a quick hack to display the Digg box for posts that were submitted to Digg. I was manually adding a digg_url meta field with the Digg URL. Perhaps you could add multiple related__post fields and add some code to iterate through all and render post links? Are you looking for a more automated solution?
A: Maybe I didn't catch the point, but Categories are not just there for that purpose?
A: I may have miss understood the question. But tags, archives and categories are there to "connect" posts, on the basis of that common connection.
Other than that, I can only see ...
*
*Manually linking posts from with the text of a blog post or
*Using plugins. Two I user are similar posts (http://rmarsh.com/plugins/similar-posts/) and SEO Smart Links (http://www.prelovac.com/vladimir/wordpress-plugins/seo-smart-links)
Similar posts if highly configurable and allows the blog to automatically suggest "related posts" and SEO Smart Links, links (in post) words or phrases to related posts.
All the best
stephen
|
Q: iOS 9.3.5 no internet access through my app after adding a url scheme After making an update to an app that only added a url scheme, all 9.3.5 devices fail to connect. The app opens but no intent access. If they upgrade to iOS 10 then it works fine. However, that is not an option for my iPhone 4 customers.
Is there something that needs to be done in addition to support this iOS version?
I Added URL Types with the scheme and identifier to my Plist.
Edit: The problem is there whether they open the app normally or through a link.
A: After finally getting my hands on an iPhone 4, The actual error was "the resource could not be loaded because the app transport security policy"
iOS 9 was the version that added this.
I assume since the last update of the app was prior to iOS 9 that new updates to that version from older versions weren't affected.
I had to add a key to my Plist retrieved from this answer
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
|
Q: Best way to emulate hardware input? I used AutoIt because of its
versatility and semplicity to solve repetitive problems on Windows. Now I want to try to improve the way my code works.
The major problem that I have encountered is to work with hardware input on a non-software level.
I want to use a "pure" input as I'm pressing a key on my keyboard or clicking on my mouse instead of emulating mouse-clicking or key-pressing with AutoIt.
I searched for a solution for several days on Google before asking here, and I had two ideas. Maybe they even work, but I'm sure that they aren't the best methods to solve the problem.
1: Use C++ Keyboard/Mouse APIs - But would it make a perfect emulation of a "hardware" signal or it could be seen as a virtual signal anyway?
2: Use Arduino - I have found APIs also for this for the same result. I thought this would have been good because it is about an input from an USB source. I can request the sending of a certain key as a keyboard could press a key by itself. Is it too intricate and exaggerated?
However I'm probably wrong and you are laughing at these ideas because they are stupid and insane :P
I have really a little knowledge of C++. If it is the best way to reach this target, would it be hard to learn only to solve the problem?
But the most important question is: are those solutions good, or there are much easier ways?
Thanks in advance!
A: I do not think I fully understand the problem you are trying to solve here but I do have experience with using Arduino as a Keyboard/Mouse emulator. There is documentation for the built in Mouse and Keyboard Library here: https://www.arduino.cc/en/Reference/MouseKeyboard. I will note that these functions will only work on certain Arduino models so be sure to check if it is compatible before purchasing an Arduino board. In my experience, it's easy to program and works quite well.
A: I am not really sure what you are trying to do, but i think you are trying to make your computer to think you are moving the mouse, i have been looking for an answer to this problem for a few months, and finally i was able to move the mouse even in Fortnite (not easy at all).
I used a module i found in sendtex gihub's page (he says the author there), i leave you the the url to it.
https://github.com/Sentdex/pygta5/blob/master/keys.py
The module uses a library called ctypes, that provides C compatible data types, and gives you the the capability to call functions in DLLs or shared libraries.
you can find more information about ctypes here:
https://docs.python.org/2/library/ctypes.html
As i am not an advanced programmer, i dont exactly know how it works, but i know what it does and how to use it. The module has a Keys class that contains all the functions, (only two of them really care, directMouse and directkey, the other ones are used to make the main ones work), and a few more classes that i dont know what the really do.
As you want to move the mouse, you might only care about the directMouse function, this fuction makes an instant movement of the mouse but not to the specified coordinates, it sums the current mouse position the given numbers.
This fuction also allows you to right and left click by giving the argument:
buttons=keys.mouse_lb_press for pressing the left button
buttons=keys.mouse_lb_release for releasing the left button
buttons=keys.mouse_rb_press for pressing the right button
buttons=keys.mouse_rb_release for releasing the right button
and you can combine a movement with a button action
for example:
keys.directMouse(20, 20, buttons=keys.mouse_rb_press)
This will sum to the current mouse position 20 pixels left and 20 pixels low and it will press (and hold) the right click button.
If you have not understood my explanation, i suggest you to see the code, at the end, you will find a sample code that will make a demonstration of the program working, you will see what it does and easily recognize how it works.
Hope i helped you.
|
Q: Using MSAL.js in SPA for Azure B2C Authentication - Pop up window an issue? So I was thinking of using MSAL for authentication against the AZURE B2C Identity Provider, but from what I can see by looking at the code, MSAL is dependent on pop up windows for logins. (Please correct me if I'm wrong).
My question is, given that B2C sites are consumer facing, isn't the use of pop up windows highly discouraged, given that many of your potential site users may have pop up disabled? I'm having difficulty finding a good example of how to plug Azure B2C into an angular2 app without pop up windows.
A: You can actually use loginRedirect() instead of loginPopup(); however, Azure B2C does not yet support custom domains for the login page, so your users will be redirected to a variant of https://login.microsoftonline.com. This isn't terrible if you setup branding on your Azure AD tenant, but there is a bug where users may get a 400 error. ( http 400: size of header request is too long when signing in user using Multifactor authentication )
A: You can use hello.js for your spa application. This does not have any popup, 100% consistent and very light weight, so you don't have to deal with any popup's. It is very flexible too. We are using that in our current project. You can find the sample for angular 2 app. https://github.com/karthikeyanVK/ng2AzureAdB2C
|
Q: Kubernetes, how to work with multiple Instance of the same Service?
I'm pretty new to K8. I wonder, what is the best practices for working with CoreDNS and multiple Instances of the same Service. Does it make Sense to register a Load Balancer to CoreDNS, which then handles the distribution of requests? Or is the default random ordering of the Response from CoreDNS enough?
Sorry if im asking a stupid question, I just haven't found anything in the Docs.
A: Kubernetes has a service resource that points to a set of pods and directs traffic to them
The service can be either internal (ClusterIP) or have external interface (NodePort / LoadBalancer) according to your needs
|
Q: View server response string and all hidden newline characters I'm dealing with an LMS (Learning Management System) in which I have NO access to the server-side code. All I can view is the response the server gives me. It returns a response in a string with newline characters, but I would like to see the string in it's raw form... showing all hidden characters. I'm not sure if this can be done, but if someone knows a way that would be great.
$.get(_url,{command:"GetParam",version:"2.2",session_id:_sid},function(response)
{
console.log(response);
});
The code above gives me this response:
ERROR=0
ERROR_TEXT=Successful
VERSION=2.2
AICC_DATA=[CORE]
STUDENT_ID=0123456
STUDENT_NAME=Doe, JohnR
SCORE=
TIME=00:00:00
CREDIT=C
LESSON_LOCATION=1_5
LESSON_STATUS=NULL
[Core_Lesson]
[Objectives_Status]
|
Q: Add hyphen between 2 spans, but only when left span is a single line Sorry about the title, can't think of a better way of describing this issue.
I have a container, that includes 2 spans, the content of each span can differ so can't solely rely on media queries here. Sometimes the text on the left span can be 20 characters, sometimes 100 for example.
I want it that when the left span is on a single line it adds a hyphen between the left and right span elements and when the left span breaks onto a new line, it removes the hyphen.
Component
import React from "react";
import styled from "styled-components";
const Container = styled.div`
display: flex;
height: 44px;
align-items: center;
justify-content: center;
cursor: pointer;
`;
const Wrapper = styled.div`
display: flex;
flex-direction: row;
align-items: center;
cursor: pointer;
overflow: hidden;
padding: 0 10px;
`;
const Text = styled.p`
font-weight: normal;
color: #ffffff;
font-size: 14px;
display: flex;
`;
const Left = styled.span`
white-space: pre-line;
overflow: hidden;
text-overflow: ellipsis;
margin-right: 5px;
background: green;
&::after {
content: " - ";
}
`;
const Right = styled.span`
background: blue;
`;
const Content = ({ rightText, leftText }) => {
return (
<Container>
<Wrapper>
<Text>
<Left>{leftText}</Left>
<Right>{rightText}</Right>
</Text>
</Wrapper>
</Container>
);
};
export default Content;
You can see here, one the 1st instance it has a hyphen to the right of the text, but I don't want the hyphen there, but I do on the other 2.
Is there a way via CSS or JS to only add the hyphen when the left text is on a single line
A: You could try something like comparing the paragraph's innerheight with the fontsize.
say para.clientHeight > (computed fontSize of paragraph) + padding then that means the paragraph is now multiline, remove psudo class if its the case.
|
Q: how to find out how many nonzero elements in a matrix in matlab? as the title shows,
for instance,
A=[ 1 2 3
0 0 0
0 1 2]
the number of nonzero elements is four. what is the function in matlab to find this?
A: To find the number of non-zero elements you can use the following function: nnz(A). In the vector above, A=[ 1 2 3 0 0 0 0 1 2] you have 5 non-zero elements.
A: You can simply convert it to a logical array using ~ which will turn 0 values to 1 and non-zero values to 0 and sum the result
sum(~A);
|
Q: Mysql, order by "pattern"? I want to order by type, by a pattern. Records now:
type name
1 a
2 b
1 c
4 d
4 e
3 f
2 g
3 h
my pattern is 2,4,3,1 so I would like to get:
2 b
2 g
4 d
4 e
3 f
3 h
1 a
1 c
A: use order by field (type,2,4,3,1). This will give you the correct result.
|
Q: NodeJS Express: json not being included in response I've written a super simple server that takes POST requests with a name, and writes the name to a file, GETs return all the names, and DELETEs delete the name file. My problem is in the DELETE method. When I send a 205 to indicate that the names file was deleted, the JSON is being included in the response, but when I send the 204, indicating that no file exists to delete, the response comes back empty.
Here's the method defining the behavior:
function clearNames(req, res) {
fs.unlink('names.txt', function(err){
if (err) {
res.status(204).json({'success': true});
} else {
res.status(205).json({'success': true});
}
});
}
and here's the result. The first request is sent when a name file exists, and deletes the file. The second is sent after the file is deleted, so no file exists to delete:
$ curl -X DELETE -w ' %{http_code}' http://localhost:18080/api/names
{"success":true} 205
$ curl -X DELETE -w ' %{http_code}' http://localhost:18080/api/names
204
$
A: In the error-case you're sending a status 204, which means "No content", and thus the client doesn't expect any content after that. Change the status to something that would include a response body and it should work.
Quote from the specs:
The 204 response MUST NOT include a message-body, and thus is always
terminated by the first empty line after the header fields.
A 205 status shouldn't also include a body, so I suggest you change it as well.
|
Q: Whats the derivative of $\sqrt{4+|x|}$ using first principle Here is my attempt:
$$f(x)=\sqrt{4+|x|}$$
$$f`(x) = \lim_{h\to0} \frac{\sqrt{4+|x-h|}-\sqrt{4+|x|}}{h}$$
multiplying by the conjugate:
$$\lim_{h\to0} \frac{4+|x-h|-4-|x|}{h[\sqrt{4+|x-h|}+\sqrt{4+|x|}]}$$
$$\lim_{h\to0} \frac{|x-h|-|x|}{h[\sqrt{4+|x-h|}+\sqrt{4+|x|}]}$$
What is the next step? how can I deal with absloute value of |x|?
A: The graph of the function looks like this: it isn't differentiable at x = 0.
As noted in the comments, Split the domain of the function into
x>0 $f(x)=\sqrt{4+x}$ and
x≤0 f(x)= $\sqrt{4-x}$.
Both halves are easily differentiable, but have different values at x = 0 (or to be more precise, the limiting value for x > 0 differs from the value for x = 0).
(P.S - this is quite an interesting web site: http://fooplot.com/
A: First note that if $f(x)=\sqrt{4+|x|}$, then
$$ \frac{d}{dx}f(0) = \lim_{h\to0} \frac{\sqrt{4+|0+h|}-\sqrt{4+|0|}}{h}= \lim_{h\to0} \frac{\sqrt{4+|h|}-\sqrt{4}}{h}
$$
$$= \lim_{h\to0} \frac{\left(\sqrt{4+|h|}-\sqrt{4}\right)\left(\sqrt{4+|h|}+\sqrt{4}\right)}{h\left(\sqrt{4+|h|}+\sqrt{4}\right)}
$$
$$= \lim_{h\to0} \frac{4+|h|-4}{h\left(\sqrt{4+|h|}+2\right)}= \lim_{h\to0} \frac{|h|}{h\left(\sqrt{4+|h|}+2\right)} $$
From the left of zero, we have
$$
\lim_{h\to0^-} \frac{|h|}{h\left(\sqrt{4+|h|}+2\right)}= \lim_{h\to0^-} \frac{-h}{h\left(\sqrt{4-h}+2\right)}
$$
$$= \lim_{h\to0^-} \frac{-1}{\left(\sqrt{4-h}+2\right)}=-\frac{1}{\left(\sqrt{4}+2\right)}=-\frac14
$$
From the right of zero, we have
$$
\lim_{h\to0^+} \frac{|h|}{h\left(\sqrt{4+|h|}+2\right)}= \lim_{h\to0^+} \frac{h}{h\left(\sqrt{4+h}+2\right)}
$$
$$= \lim_{h\to0^+} \frac{1}{\left(\sqrt{4+h}+2\right)}=\frac{1}{\left(\sqrt{4}+2\right)}=\frac14
$$
Therefore, $f(x)$ is not differentiable at $x=0$.
|
Q: Why serial code is faster than concurrent.futures in this case? I am using the following code to process some pictures for my ML project and I would like to parallelize it.
import multiprocessing as mp
import concurrent.futures
def track_ids(seq):
'''The func is so big I can not put it here'''
ood = {}
for i in seq:
# I load around 500 images and process them
ood[i] = some Value
return ood
seqs = []
for seq in range(1, 10):# len(seqs)+1):
seq = txt+str(seq)
seqs.append(seq)
# serial call of the function
track_ids(seq)
#parallel call of the function
with concurrent.futures.ProcessPoolExecutor(max_workers=mp.cpu_count()) as ex:
ood_id = ex.map(track_ids, seqs)
if I run the code serially it takes 3.0 minutes but for parallel with concurrent, it takes 3.5 minutes.
can someone please explain why is that? and present a way to solve the problem.
btw, I have 12 cores.
Thanks
A: Here's a brief example of how one might go about profiling multiprocessing code vs serial execution:
from multiprocessing import Pool
from cProfile import Profile
from pstats import Stats
import concurrent.futures
def track_ids(seq):
'''The func is so big I can not put it here'''
ood = {}
for i in seq:
# I load around 500 images and process them
ood[i] = some Value
return ood
def profile_seq():
p = Profile() #one and only profiler instance
p.enable()
seqs = []
for seq in range(1, 10):# len(seqs)+1):
seq = txt+str(seq)
seqs.append(seq)
# serial call of the function
track_ids(seq)
p.disable()
return Stats(p), seqs
def track_ids_pr(seq):
p = Profile() #profile the child tasks
p.enable()
retval = track_ids(seq)
p.disable()
return (Stats(p, stream="dummy"), retval)
def profile_parallel():
p = Profile() #profile stuff in the main process
p.enable()
with concurrent.futures.ProcessPoolExecutor(max_workers=mp.cpu_count()) as ex:
retvals = ex.map(track_ids_pr, seqs)
p.disable()
s = Stats(p)
out = []
for ret in retvals:
s.add(ret[0])
out.append(ret[1])
return s, out
if __name__ == "__main__":
stat, retval = profile_parallel()
stat.print_stats()
EDIT: Unfortunately I found out that pstat.Stats objects cannot be used normally with multiprocessing.Queue because it is not pickleable (which is needed for the operation of concurrent.futures). Evidently it normally will store a reference to a file for the purpose of writing statistics to that file, and if none is given, it will by default grab a reference to sys.stdout. We don't actually need that reference however until we actually want to print out the statistics, so we can just give it a temporary value to prevent the pickle error, and then restore an appropriate value later. The following example should be copy-paste-able and run just fine rather than the pseudocode-ish example above.
from multiprocessing import Queue, Process
from cProfile import Profile
from pstats import Stats
import sys
def isprime(x):
for d in range(2, int(x**.5)):
if x % d == 0:
return False
return True
def foo(retq):
p = Profile()
p.enable()
primes = []
max_n = 2**20
for n in range(3, max_n):
if isprime(n):
primes.append(n)
p.disable()
retq.put(Stats(p, stream="dummy")) #Dirty hack: set `stream` to something picklable then override later
if __name__ == "__main__":
q = Queue()
p1 = Process(target=foo, args=(q,))
p1.start()
p2 = Process(target=foo, args=(q,))
p2.start()
s1 = q.get()
s1.stream = sys.stdout #restore original file
s2 = q.get()
# s2.stream #if we are just adding this `Stats` object to another the `stream` just gets thrown away anyway.
s1.add(s2) #add up the stats from both child processes.
s1.print_stats() #s1.stream gets used here, but not before. If you provide a file to write to instead of sys.stdout, it will write to that file)
p1.join()
p2.join()
|
Q: Как можно оптимизировать SQL запрос? Существует запрос к таблице bonuses, в котором исходя из содержимого полей referrer_id_vk и promo_code_id (одно из них равно NULL) делаются подзапросы в таблицы referrers (referral_settings) либо promo_codes
SELECT *,
IF
(
referrer_id_vk,
IF
(
(SELECT referral_first_deposit_bonus FROM `referrers` WHERE id_vk = '$id_vk'),
(SELECT referral_first_deposit_bonus FROM `referrers` WHERE id_vk = '$id_vk'),
(SELECT referral_first_deposit_bonus FROM `referral_settings` WHERE id = 1)
),
(SELECT value FROM `promo_codes` WHERE id = promo_code_id)
) AS value
FROM `bonuses` WHERE id_vk = '$id_vk"
Как видите, в коде дублируется этот подзапрос
SELECT referral_first_deposit_bonus FROM referrers WHERE id_vk = '$id_vk'
сначала он производится чтобы проверить есть ли значение в таблице referrers , если есть, то снова делает этот же запрос, чтобы уже вернуть результат, иначе делает запрос в таблицу referral_settings . Можно ли избежать дублирование подзапроса в этом моменте?
A: Я бы использовал соединение таблиц, что-то вроде этого:
SELECT b.*,
IF
(
referrer_id_vk,
COALESCE(r.referral_first_deposit_bonus, rs.referral_first_deposit_bonus),
pc.value
) AS value
FROM `bonuses` b
LEFT JOIN `referrers` r on b.id_vk = r.id_vk
INNER JOIN `referral_settings` rs ON rs.id = 1
LEFT JOIN `promo_codes` pc ON pc.id = b.promo_code_id
WHERE b.id_vk = '$id_vk"
|
Q: Operator '&' is not defined for types 'Object' and '1-dimensional array of byte' Good day/night!
I'm making an .Net application using Mysql as my database and currently stuck in a problem on my query. I'm allowing the user to upload images, however I'm getting this error on the 'ImageData' variable which is a Byte datatype
Operator '&' is not defined for types 'Object' and '1-dimensional array of byte'
on my console as I click the button for saving it to the database.
Here's my code on the click event
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'DECLARE THE STRING VARIABLE THAT YOU'RE GOING TO USE.
Dim sqlQUERY As String
'FORMAT IMAGE TO BE ABLE TO SAVE TO DATABASE
Dim fs As FileStream
Dim br As BinaryReader
Try
If txtbox_image.Text.Length > 0 Then
Dim FileName As String = txtbox_image.Text
Dim ImageData() As Byte
fs = New FileStream(FileName, FileMode.Open, FileAccess.Read)
br = New BinaryReader(fs)
ImageData = br.ReadBytes(CType(fs.Length, Integer))
br.Close()
fs.Close()
'STORE YOUR QUERY TO A VARIABLE THAT YOU HAVE DECLARED.
sqlQUERY = "INSERT INTO vids.vehicles " & _
"VALUES (" & _
" NULL, " & _
" '" & txtbox_plateno.Text.ToString() & "', " & _
" '" & txtbox_model.Text.ToString() & "', " & _
" '" & txtbox_manufacturer.Text.ToString() & "', " & _
" '" & Format(dtp_year.Value, "yyyy").ToString() & "', " & _
" '" & Format(dtp_dateacq.Value, "yyyy-MM-dd").ToString() & "', " & _
" (SELECT vehicle_type_id from vehicle_types where type_name='" & DirectCast(cb_vehicletype.SelectedItem, DataRowView).Item("type_name") & "'), " & _
" '" & Format(dtp_reg.Value, "yyyy-MM-dd").ToString() & "', " & _
" '" & Format(dtp_regexpire.Value, "yyyy-MM-dd").ToString() & "', " & _
ImageData & ", now(), now());"
'CALL THE METHOD THAT YOU HAVE CREATED AND PUT YOUR SQLQUERY IN THE PARAMETERS' LIST
SAVING(sqlQUERY)
RELOAD(Form1.dgv_vehicles)
Me.Close()
Else
MsgBox("Incomplete data!", MsgBoxStyle.Critical, "")
End If
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Sub
The 'SAVING' subroutine is placed in a Module so that it would be reusable.
'CREATE A SUB PROCEDURE IN SAVING THE DATA WITH THE PARAMETER TYPE OF STRING
Public Sub SAVING(ByVal sqlQuery As String)
Try
'OPENING THE CONNECTION
strcon.Open()
'INITIALIZE YOUR COMMANDS
'IT HOLDS THE DATA TO BE EXECUTED
With cmd
'PASS ON THE VALUE OF STRCON TO THE MYSQL COMMANND WHICH IS THE CONNECTION
.Connection = strcon
'THE FUNCTION OF THIS IS TO RETURN THE TEXT REPRESENTED BY A COMMAND OBJECT
.CommandText = sqlQuery
End With
'IT EXECUTES THE DATA THAT HAS TO BE SAVE IN THE DATABASE.
res = cmd.ExecuteNonQuery
'DATA WILL NOT BE SAVED IF IT EXECUTES LESS THAN 0
'BUT IF IT EXECUTES GREATER THAN 0, THE DATA WILL BE SAVED.
If res = 0 Then
MsgBox("Error in saving!", MsgBoxStyle.Exclamation)
Else
MsgBox("The data has been saved.")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
'CLOSING THE CONNECTION
strcon.Close()
End Sub
I tried using DirectCast(ImageData, Byte) but it returns an
Value of type '1-dimensional array of Byte' cannot be converted to 'Byte'.
I'm currently new to VB.Net so I don't have extensive knowledge about Datatypes and its conversions
Thanks!
A: I won't get into the the debate of best practices/using parameterized queries etc. You need to read on that stuff yourself.
In the code you posted, I would avoid string concatenation the way you do and use String.Format instead, which results in cleaner code and also avoids problems similar to what you are facing.
See the difference for yourself.
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'DECLARE THE STRING VARIABLE THAT YOU'RE GOING TO USE.
Dim sqlQUERY As String
'FORMAT IMAGE TO BE ABLE TO SAVE TO DATABASE
Dim fs As FileStream
Dim br As BinaryReader
Try
If txtbox_image.Text.Length > 0 Then
Dim FileName As String = txtbox_image.Text
Dim ImageData() As Byte
fs = New FileStream(FileName, FileMode.Open, FileAccess.Read)
br = New BinaryReader(fs)
ImageData = br.ReadBytes(CType(fs.Length, Integer))
br.Close()
fs.Close()
'STORE YOUR QUERY TO A VARIABLE THAT YOU HAVE DECLARED.
sqlQUERY = String.Format("INSERT INTO vids.vehicles VALUES ( NULL, '{0}', '{1}', '{2}', '{3:yyyy}', '{4:yyyy-MM-dd}', (SELECT vehicle_type_id from vehicle_types where type_name='{5}'), '{6:yyyy-MM-dd}', '{7:yyyy-MM-dd}', {8}, now(), now());", _
txtbox_plateno.Text, txtbox_model.Text, txtbox_manufacturer, dtp_year.Value, dtp_dateacq.Value, DirectCast(cb_vehicletype.SelectedItem, DataRowView).Item("type_name"), dtp_reg.Value, dtp_regexpire.Value, ImageData)
'CALL THE METHOD THAT YOU HAVE CREATED AND PUT YOUR SQLQUERY IN THE PARAMETERS' LIST
SAVING(sqlQUERY)
RELOAD(Form1.dgv_vehicles)
Me.Close()
Else
MsgBox("Incomplete data!", MsgBoxStyle.Critical, "")
End If
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Sub
A: Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim colours(9) As String
Dim totals(9) As Integer
End Sub
Private Sub populatelists(ByRef colours() As String, ByRef totals() As Integer)
For row = 0 To 9
colours = InputBox("please enter the colour of car you saw?")
totals = InputBox("please enter how many times you saw this colour")
Next
End Sub
Private Sub findmostpopular(ByVal colours() As String, ByVal totals() As Integer, ByRef highest As Integer, ByRef mostpopcolour As String)
mostpopcolour = colours(0)
highest = totals(0)
For row = 1 To 9
If totals > highest Then
highest = totals(row)
colours = colours(row)
End If
Next
End Sub
Private Sub findleastpopular(ByVal colours() As String, ByVal totals() As Integer, ByRef lowest As Integer, ByRef leastpopcolour As String)
leastpopcolour = colours(0)
lowest = totals(0)
For row = 1 To 9
If totals < lowest Then
lowest = totals(row)
colours = colours(row)
End If
Next
End Sub
Private Sub displayresults(ByVal highest As Integer, ByVal mostpopcolour As String, ByVal lowest As Integer, ByVal leastpopcolour As String)
output.Items.Add("the highest amount of cars seen were " & highest & " " & mostpopcolour & " cars")
output.Items.Add(" ")
output.Items.Add("the lowest amount of cars seen were " & lowest & " " & leastpopcolour & " cars")
End Sub
End Class
|
Q: Transpose multiple columns to rows in R I have a data set as following, in which each ID has multiple rows for different attributes.
ID<-c(1,1, 2,2,3,3)
Score<-c(4,5, 5,7,8,9)
Attribute<-c("Att_1","Att_2", "Att_1","Att_2", "Att_1","Att_2")
T<-data.frame(ID, Score, Attribute)
Need to transform it to following format so each ID has one row:
ID Att_1 Att_2
1 4 5
2 5 7
3 8 9
There are threads on how to do this in excel, just wondering is there is any neat way to do in R? Thanks a lot!
A: You could try this:
library(reshape2)
dcast(T, ID ~ Attribute, value.var="Score")
# ID Att_1 Att_2
#1 1 4 5
#2 2 5 7
#3 3 8 9
A: This can be done with reshape():
reshape(data.frame(ID,Score,Attribute),idvar='ID',timevar='Attribute',dir='w');
## ID Score.Att_1 Score.Att_2
## 1 1 4 5
## 3 2 5 7
## 5 3 8 9
|
Q: How do I show that the fermion creation operator creates a particle with spin 1/2? Consider the mode expansion of the Dirac spinor:
\begin{equation}
\psi(x) = \int\frac{d^3 k}{(2\pi)^3\omega_k}\sum_\lambda \bigg[b(k, \lambda)u(k, \lambda)\exp(-ikx)+d^\dagger(k, \lambda)v(k, \lambda)\exp(ikx)\bigg]
\end{equation}
I need to show that the state $b^\dagger(k, \lambda)|0>$ has charge -1, 4-momentum $k$, and spin $1/2$ and the state $d^\dagger(k, \lambda)|0>$ has charge $+1$, 4-momentum $k$ and spin $1/2$. For this I have to use the transformation properties of the Dirac fermion under Poincare symmetry and the $U(1)$ internal symmetry. Note that $\lambda$ is the helicity eigenvalue.
I was able to show that the states have charge $\mp 1$ using the charge operator which can be found out by exploiting the $U(1)$ internal symmetry which gave the following commutation relation:
\begin{equation}
[b(k, \lambda), Q] = -b(k, \lambda)
\end{equation}
And similarly for the antifermion creation operator
\begin{equation}
[d(k, \lambda), Q] = d(k, \lambda)
\end{equation}
For the momentum part, we can do this by considering the commutation relation with $P_\mu$ which are the generators of Poincare transformations (along with $J_{\mu\nu}$), identified with the 4-momentum operator. These satisfy the commutation relation
\begin{equation}
[b^\dagger(k, \lambda), P_\mu] = k_\mu b^\dagger(k, \lambda)
\end{equation}
And the exact same relation for $d^\dagger(k, \lambda)$. Therefore they both create particles with 4-momentum $k_\mu$. But I am unable to prove the spin part of the problem as I am not sure which commutator I should find. Can someone please help me? Thank you for your time.
|
Q: npm project behind a corporate proxy global I found already a lot of helpful tutorials to set the proxy locally and global to install packages and so on.
Now I started a new project and I figured out how to reuse the proxy settings:
#! /usr/bin/env node
var http = require("http");
var shell = require('shelljs');
var request = require('request');
var iplocation = require('iplocation')
// setup proxy
var proxyUrl = shell.exec('npm config get proxy', {silent:true}).stdout;
var proxiedRequest = request.defaults({
'proxy': proxyUrl,
'https-proxy' : proxyUrl,
'strict-ssl' : false
});
// get location (works)
proxiedRequest('http://ipinfo.io/216.58.194.46', function (error, response, body) {
console.log('error:', error);
console.log('statusCode:', response && response.statusCode);
console.log('body:', body);
});
// doesn't work
iplocation('56.70.97.8').then(res => {
console.log(res.iplocation)
})
.catch(err => {
console.error(err);
})
Is there a way to set it someway global for the project so other npm packages could use it too?
I tried a local .npmrc file in the projects folder but it doesn't affect the environment at all.
Any hints are welcome. Thanks
A: This SO answer1, SO answer2 explains different ways to set npm proxy. See if it helps you.
You could add functions like proxy_on and proxy_off to your bashrc which will let you set global npm config and toggle it from your command line.
Refer to this gist for the code.
|
Q: css file status 403 I am importing some css files in another css document like so, however the foundation.css file is getting a 403 for the stylesheet when I visit the location, my ftp says it is there and it all works locally. The site is live here username:anders pass:reading61 I am not sure what is going on.
/*
Theme Name: git.Austin.Kitson.org
Theme URI: http://austin.kitson.org
Description: A Wordpress version of Austin.kitson.org
Author: springmethod
Author URI: http://springmethod.com
Version: 1.0
*/
/*import styles for zurbs foundation*/
@import url("stylesheets/foundation.css");
@import url("stylesheets/app.css");
[if lt IE 9] @import url("stylesheets/ie.css");
here is my functions.php css register and enqueue if that helps
//LOAD CSS
function load_css_styles(){
if (!is_admin()){
wp_register_style('css_main', get_template_directory_uri() . '/style.css');
wp_enqueue_style('css_main');
}// if not admin ends
}// css_styles ends
add_action('wp_enqueue_scripts', 'load_css_styles');
A: 403 Forbidden is a permissions error, check that the file has proper permissions for public access on your server.
|
Q: Safe Area increase itself after hide tab bar, but dont decrease if i show tab bar again i have a view controllers in a tab bar controller with constraints to bottom safe area, but one of them i must hide tab bar i use this
self.tabBarController?.tabBar.isHidden = true
this increase the safe area
But if i need to move to another i show back tab bar
self.tabBarController?.tabBar.isHidden = false
But safe area don't decrease by itself, making view contents behind tab bar
To make it clear i put a red view pinned to bottom safe area, next i go to view and hide tab bar
this is when it come back to this view and show tab bar again, safe area increased below tab bar, that's why red square are more below
A: It appears to be a bug in iOS. SafeArea doesn't change to account for tabBar, after hiding / showing it.
You can work around it by anchoring your view to superview and adjusting for tabBar manually. For example, if you want to anchor a tableView to a tabBar it would look like this
if let tabBar = tabBarController?.tabBar {
tabBar.isHidden = true
tableViewBottomConstraint.constant = tabBar.frame.height
}
|
Q: Changing the timezone in libc time at compile time We have firmware that will be deployed on devices all over the world and that will be synced to UTC by a host device. To track time, we end up converting between struct tm and time_t (Unix time) because we use a hardware RTC whose registers closely mirror struct tm, but any time-based operations are done on Unix time. However, when we use mktime it attempts to put everything into localtime, which is not UTC on the build system. We could just add an offset, but it would be easier to just tell time.h that our local time should be UTC, since the device is otherwise agnostic to the local time.
Is there a (non-invasive) way to do this other than changing the local time on the build system to UTC? Like, can we somehow use tzset to inject this data? Or just set TZ to something? I'm having difficulty understanding how I would set TZ if I just wanted UTC.
A:
However, when we use mktime it attempts to put everything into localtime ...
The compiler's time zone setting at compile time is irrelevant to how code handles time at run time.
The easiest way to avoid local time in conversions is to hope your compiler offers struct_tm (UTC) to time_t, instead of using mktime() (time zone dependent) as an extension like time_t timegm(struct tm *tm).
There is no simple standard solution. Tricks with divining the offset via locatime(), gmtime() fail corner cases.
IMO, to convert struct_tm (UTC) to UNIX time time_t, simply write that code and get it reviewed. It is not that hard as there are few corner cases (aside from overflow).
Some sample code to change int year, int month, int day (0:00:00) to MJD to get OP started.
#include <stdint.h>
static const short DaysMarch1ToBeginingOfMonth[12] = { //
0, 31, 61, 92, 122, 153, 184, 214, 245, 275, 306, 337};
#ifndef INT32_C
#define INT32_C(x) ((int_least32_t)1*(x))
#endif
#define DaysPer400Years (INT32_C(365)*400 + 97)
#define DaysPer100Years (INT32_C(365)*100 + 24)
#define DaysPer4Years (365*4 + 1)
#define DaysPer1Year 365
#define MonthsPerYear 12
#define MonthsPer400Years (12*400)
#define MonthMarch 3
#define mjdOffset 0xA5BE1
#define mjd1900Jan1 15020
// November 17, 1858
// Example: 2015 December 31 --> ymd_to_mjd(2015, 12, 31)
int2x ymd_to_mjd(int year, int month, int day) {
// int2x is a type twice as wide as int to handle extreme int values.
// Use int (at least 32-bit) to handle common values.
int2x year2x = year;
year2x += month / MonthsPerYear;
month %= MonthsPerYear;
// Adjust for month/year to Mar ... Feb
while (month < MonthMarch) {
month += MonthsPerYear;
year2x--;
}
int2x d = (year2x / 400) * DaysPer400Years;
int y400 = (int) (year2x % 400);
d += (y400 / 100) * DaysPer100Years;
int y100 = y400 % 100;
d += (y100 / 4) * DaysPer4Years;
int y4 = y100 % 4;
d += y4 * DaysPer1Year;
d += DaysMarch1ToBeginingOfMonth[month - MonthMarch];
d += day;
// November 17, 1858 == MJD 0
d--;
d -= mjdOffset;
return d;
}
|
Q: What is a modern approach to similarity search? Given is a list of text files. Each text file describes a topic. Input is a mental concept that I describe with a few sentences.
The text files contain umlauts.
The algorithm should output the files and probability for each that the concept described is being dealt with.
My Pseudocode:
split the concept by the space literal and put words into an array, while omitting stopwords
iterate over each text file
split by the space literal and put words into an array, while omitting stopwords
i = 0
iterate over vector
if vectorword in concept
i++
determine percentage by using i/vectorcount * 100
save the percentage in a dictionary filename - percentage
sort dictionary by percentage descendingly
output
Drawbacks I see in this approach:
*
*The output would not include similar words but only the words used.
*The code is redundant, iterating over each text file should only be done once and then one should work with a faster approach, like a database
A: TL;DR
From https://colab.research.google.com/drive/1wXmqj3LAL6juxvQY_IHTtZAMuN46YZdV
import itertools
import torch
import tensorflow as tf
import tensorflow_hub as hub
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
def cos(a, b):
return cosine_similarity(torch.tensor(a).view(1, -1), torch.tensor(b).view(1, -1))[0][0]
# Printing candies, make sure that arrays
# are ellipsis and humanly readable.
np.set_printoptions(precision=4, threshold=10)
# The URL that hosts the DAN model for Universal Sentence Encoder
module_url = "https://tfhub.dev/google/universal-sentence-encoder/2"
embed = hub.Module(module_url)
bulbasaur = """A strange seed was planted on its back at birth. The plant sprouts and grows with this POKéMON."""
ivysaur = """When the bulb on its back grows large, it appears to lose the ability to stand on its hind legs."""
venusaur = """The plant blooms when it is absorbing solar energy. It stays on the move to seek sunlight."""
charmander = """Obviously prefers hot places. When it rains, steam is said to spout from the tip of its tail."""
charmeleon = """When it swings its burning tail, it elevates the temperature to unbearably high levels."""
charizard = """Spits fire that is hot enough to melt boulders. Known to cause forest fires unintentionally."""
input_texts = [bulbasaur, ivysaur, venusaur,
charmander, charmeleon, charizard]
with tf.Session() as session:
session.run([tf.global_variables_initializer(), tf.tables_initializer()])
sentence_embeddings = session.run(embed(input_texts))
names = ['bulbasaur', 'ivysaur ', 'venusaur',
'charmander', 'charmeleon', 'charizard']
for (mon1, vec1), (mon2, vec2) in itertools.product(zip(names, sentence_embeddings), repeat=2):
print('\t'.join(map(str, [mon1, mon2, cos(vec1, vec2)])))
[out]:
bulbasaur bulbasaur 1.0000002
bulbasaur ivysaur 0.5978951
bulbasaur venusaur 0.57630616
bulbasaur charmander 0.27358365
bulbasaur charmeleon 0.36671823
bulbasaur charizard 0.3608557
ivysaur bulbasaur 0.5978951
ivysaur ivysaur 1.0
ivysaur venusaur 0.5274135
ivysaur charmander 0.34133852
ivysaur charmeleon 0.54503417
ivysaur charizard 0.26368174
venusaur bulbasaur 0.57630616
venusaur ivysaur 0.5274135
venusaur venusaur 0.99999994
venusaur charmander 0.37098676
venusaur charmeleon 0.50332355
venusaur charizard 0.50058115
charmander bulbasaur 0.27358365
charmander ivysaur 0.34133852
charmander venusaur 0.37098676
charmander charmander 1.0000001
charmander charmeleon 0.58522964
charmander charizard 0.4640133
charmeleon bulbasaur 0.36671823
charmeleon ivysaur 0.54503417
charmeleon venusaur 0.50332355
charmeleon charmander 0.58522964
charmeleon charmeleon 1.0000001
charmeleon charizard 0.59804976
charizard bulbasaur 0.3608557
charizard ivysaur 0.26368174
charizard venusaur 0.50058115
charizard charmander 0.4640133
charizard charmeleon 0.59804976
charizard charizard 1.0000001
See https://tfhub.dev/google/universal-sentence-encoder/2 for details
A: Generally speaking I would use word embedding --> some variations of doc2vec and apply it on your text files, store these vectors. For the mental concept input I would do the same and then search for the most similar vectors. I kinda like spacy tools
https://spacy.io/api/doc and https://spacy.io/usage/vectors-similarity should point you to the right way.
PS: https://stackoverflow.com/help/how-to-ask
|
Q: I can´t add an Excel button to my table and my form is not working when using DataTables I'm using DataTables library from https://datatables.net/ and I want to have an Excel Button to download all the table, but everything I'm trying is not working:
I tried adding
buttons: [ {
extend: 'excelHtml5',
autoFilter: true,
sheetName: 'Exported data'
} ]
Or
buttons: [
'excel'
]
Or
buttons: [
{
extend: 'excel',
text: 'Save current page',
exportOptions: {
modifier: {
page: 'current'
}
}
}
]
And this is my DataTable Js:
$(document).ready(function () {
$.noConflict();
$('#myTable').DataTable({
buttons: [{
extend: 'excelHtml5',
autoFilter: true,
sheetName: 'Exported data'
}],
order: [[3, 'desc']],
}
But doesn't work.
I know my Js works because it's not the only customization I'm doing, so I don't know where I'm wrong.
And my form whas working fine but when I added DataTable is stopped working don't know why. Just that, what it suppose to send the value from the button to another View, but it doesn't work now and only added the Library, I didn't touch code behind
<table class="table table-striped table-hover text-center" id="myTable">
<thead>
<tr>
<th>Column1</th>
<th>Column2</th>
<th>Column3</th>
</tr>
</thead>
<tbody id="tbData">
<form action="~/Home/ReadOption" method="post">
<input hidden value="entrega" name="seleccion"/>
@{
string delivery = "";
}
@foreach (var item in Model)
{
if (entrega != item.DeliveryNumber)
{
<tr>
<td><button type="submit" class="btn btn-link" value="@item.NumeroEntrega" name="identi">@item.DeliveryNumber</button></td>
<td>@item.TaskNumber</td>
<td>@item.RandomNumber</td>
</tr>
}
delivery = item.DeliveryNumber;
}
</form>
</tbody>
</table>
A: As @GrafiCode told me, to fix the form, I put it outside the <table>
<table class="table table-striped table-hover text-center" id="myTable">
<thead>
<tr>
<th>Column1</th>
<th>Column2</th>
<th>Column3</th>
</tr>
</thead>
<tbody id="tbData">
<form action="~/Home/ReadOption" method="post">
<input hidden value="entrega" name="seleccion"/>
@{
string delivery = "";
}
@foreach (var item in Model)
{
if (entrega != item.DeliveryNumber)
{
<tr>
<td><button type="submit" class="btn btn-link" value="@item.NumeroEntrega" name="identi">@item.DeliveryNumber</button></td>
<td>@item.TaskNumber</td>
<td>@item.RandomNumber</td>
</tr>
}
delivery = item.DeliveryNumber;
}
</form>
</tbody>
</table>
And also for Button of the atatable, I read the documentation and concluded I was missing something for the DOM so this is the final dataTable code:
dom: "Blfrtip",
buttons: {
dom: {
button: {
className: 'btn'
}
},
buttons: [{
extend: "excel",
text: 'Exportar Excel',
className: 'btn btn-primary',
excelStyles: {
template:'header_blue'
}
}
]
}
|
Q: Why my stream is unlocked before I do it myself? I have a text file. Several processes can simultaneously try to read and edit this file. I have a problem with FileStream.Unlock() method:
using System;
using System.IO;
using System.Text;
static class Program
{
static void Main()
{
var fileName = @"c:\temp\data.txt";
// Content of the 'c:\temp\data.txt' file:
// Hello!
// The magic number is 000. :)))
// Good luck...
using (var stream = new FileStream(fileName, FileMode.Open,
FileAccess.ReadWrite, FileShare.ReadWrite))
{
using(var reader = new StreamReader(stream))
{
var value = 0;
Console.Write("New value [0-999]: ");
while(int.TryParse(Console.ReadLine(), out value))
{
var prevPosition = stream.Position;
stream.Position = 28;
var data = Encoding.UTF8.GetBytes(value.ToString());
try
{
stream.Lock(stream.Position, data.LongLength);
Console.WriteLine("Data locked. Press any key for continuation...");
Console.ReadKey();
stream.Write(data, 0, data.Length);
stream.Flush();
// I get the Exception here: The segment already unlocked.
stream.Unlock(stream.Position, data.LongLength);
}
catch(Exception ex)
{
Console.WriteLine("Error: {0}", ex.Message);
}
stream.Position = prevPosition;
Console.Write("New value: ");
}
}
}
}
}
Why my stream is unlocked before I do it myself?
A: The reason is stream.Position is advanced after you locked the file (because you write to it), and you use stream.Position (which is now different) to unlock a file. In result - you are trying to unlock not the same range you locked. Instead, save stream.Position:
var position = stream.Position; // < save
stream.Lock(position, data.LongLength);
Console.WriteLine("Data locked. Press any key for continuation...");
stream.Write(data, 0, data.Length); // < this changes stream.Position, breaking your old logic
stream.Flush();
// I get the Exception here:
// The blocking of the segment already taken off.
stream.Unlock(position, data.LongLength); // < now you unlock the same range
A: Not sure, but maybe when you Write, the Stream.Position changes.
|
Q: Error al mostrar valores en un bucle Ando haciendo un programa que me haga números sucesivos del 10 al 1 pares, impares y múltiplos de cinco, pero no me arroja nada y no entiendo cómo hace que el resultado se vea hacia abajo de forma de columnas:
10 2 3 1
9 4 5 5
8 6 10
7 8 11 15
Éste es el código:
<?php
$sucesivo=11-$i;
$pares=$i * 2;
$impares=$i * 2 - 1;
$quintos=$i * 5 -5;
for($i=1; $i<=10; $i++){
echo $sucesivo,$pares,$impares,$quintos;
}
?>
A: Solucionado.
$i no existe cuando estás usándolo en la primera línea de tu código.
<?php
$i=1;
$sucesivo=11-$i;
$pares=$i * 2;
$impares=$i * 2 - 1;
$quintos=$i * 5 -5;
for($i; $i<=10; $i++){
echo $sucesivo,$pares,$impares,$quintos;
}
?>
De hecho, te pasó lo mismo en una pregunta que te resolví ayer: Link
Intenta entender la solución y buscar por tí mismo el error antes de preguntar cada ejercicio que tengas que realizar en este foro.
|
Q: TransformException duplicate entry for GoogleCloudMessaging After a re-install of Android Studio following a disk failure, I have updated the dependencies for my project to reflect API 21. This introduced the use of multiDex, so my build.gradle now contains:
compileSdkVersion 21
buildToolsVersion '21.1.2'
defaultConfig {
minSdkVersion 17
targetSdkVersion 21
multiDexEnabled true
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile ('com.android.support:support-v4:21.0.3') {
exclude group: 'com.google.android.gms'
}
compile ('com.android.support:appcompat-v7:21.0.3') {
exclude group: 'com.google.android.gms'
}
compile ('com.android.support:multidex:1.0.0') {
exclude group: 'com.google.android.gms'
}
compile 'com.google.android.gms:play-services-gcm:7.+'
compile files('libs/android-async-http-1.4.4.jar')
}
Please note I don't want to update to API 23 at this stage for consistency with a sister application.
I keep getting the following error when I try to build:
Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/google/android/gms/gcm/GoogleCloudMessaging$1.class
I added the 'exclude group' lines to the dependencies only when trying to resolve the duplication.
Cleaning the project makes no difference (I've tried from both the terminal and the Studio menu).
The output from ./gradlew app:dependencies is as follows:
+--- com.android.support:multidex:1.0.1
+--- com.android.support:support-v4:21.0.3 -> 22.2.0
| \--- com.android.support:support-annotations:22.2.0
+--- com.android.support:appcompat-v7:21.0.3
| \--- com.android.support:support-v4:21.0.3 -> 22.2.0 (*)
+--- com.android.support:multidex:1.0.0 -> 1.0.1
\--- com.google.android.gms:play-services-gcm:7.+ -> 7.8.0
\--- com.google.android.gms:play-services-base:7.8.0
\--- com.android.support:support-v4:22.2.0 (*)
Apologies if this is a duplication of another SO question, but I've looked at other questions and they haven't helped, as I can't see where the duplication is introduced. Can anyone tell me the source of the duplication?
A: Found it, and just to try to help if anyone else sees something similar...
This was a project which had been imported into Studio from Eclipse and there was still a Google Play Services jar in the libs folder, hence the clash with the gradle dependency.
I couldn't tell the jar was there from the Studio interface though, I had to look directly in the folder, and it was only the introduction of multiDex which produced an error.
|
Q: How to add space in grouping of multiple JButtons? import java.awt.*;
import javax.swing.*;
class Grid extends JFrame {
public Grid() {
JPanel pnl = new JPanel(new GridLayout(5,2));
pnl.add(new JButton("One"));
pnl.add(new JButton("Two"));
pnl.add(new JButton("Three"));
pnl.add(new JButton("Four"));
pnl.add(new JButton("Five"));
pnl.add(new JButton("1"));
pnl.add(new JButton("2"));
pnl.add(new JButton("3"));
pnl.add(new JButton("4"));
pnl.add(new JButton("5"));
this.add(pnl);
this.setTitle("Grid");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400, 75);
this.setLocation(200, 200);
this.setVisible(true);
}
public static void main(String[] args) {
Grid app = new Grid();
}
}
how to add space between five and 1
like this picts:
I'm already trying to resolve this with GridLayout or GridBagLayout but nothing happend, its will be give space every button
A: The below code is the same as the code in the question but uses the GridLayout constructor that declares four parameters, namely:
*
*number of rows
*number of columns
*horizontal gap between columns (in pixels)
*vertical gap between rows (in pixels)
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Grid extends JFrame {
public Grid() {
JPanel pnl = new JPanel(new GridLayout(5, 2, 10, 10));
pnl.add(new JButton("One"));
pnl.add(new JButton("Two"));
pnl.add(new JButton("Three"));
pnl.add(new JButton("Four"));
pnl.add(new JButton("Five"));
pnl.add(new JButton("1"));
pnl.add(new JButton("2"));
pnl.add(new JButton("3"));
pnl.add(new JButton("4"));
pnl.add(new JButton("5"));
this.add(pnl);
this.setTitle("Grid");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400, 75);
this.setLocation(200, 200);
this.setVisible(true);
}
public static void main(String[] args) {
Grid grid = new Grid();
}
}
Here is a screen capture of the running app.
A: i think you can add border to every jcomponent with the setBorder-method
https://docs.oracle.com/javase/tutorial/uiswing/components/border.html
A: You add space to group JButtons by adding dummy JLabels.
Here's an example GUI.
*
*You should start all Swing applications with a call to the SwingUtilities invokeLater method. This method ensures that all Swing components are created and executed on the Event Dispatch Thread.
*I separated the JFrame code from the JPanel code. This allows me to focus on one part of the GUI at a time.
*I set the location of the JFrame based on the platform.
*I set the preferred size of the JPanel. The JFrame will size itself based on the JPanel size.
Here's the minimum, runnable, example code.
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class GridLayoutExample implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new GridLayoutExample());
}
@Override
public void run() {
JFrame frame = new JFrame("Grid Layout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createControlPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createControlPanel() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 2));
panel.setPreferredSize(new Dimension(400, 200));
panel.add(new JButton("One"));
panel.add(new JButton("Two"));
panel.add(new JButton("Three"));
panel.add(new JButton("Four"));
panel.add(new JButton("Five"));
panel.add(new JLabel(" "));
panel.add(new JLabel(" "));
panel.add(new JLabel(" "));
panel.add(new JButton("1"));
panel.add(new JButton("2"));
panel.add(new JButton("3"));
panel.add(new JButton("4"));
panel.add(new JButton("5"));
return panel;
}
}
A: you can use 2 panel and 2 FlowLayout for each one of panels, if you want something like your images
|
Q: Add consume filter to batch consumer I code service with MassTransit and RabbitMQ.
I have endpoint configuration with few filters:
cfg.ReceiveEndpoint("BillingTransaction",
e =>
{
e.UseMessageRetry(r => r.Interval(defaultRetryCount, defaultRetryPeriod));
e.UseConsumeFilter(typeof(CacheTransactionFilter<>), context);
e.UseConsumeFilter(typeof(TransactionValidationFilter<>), context);
e.UseConsumeFilter(typeof(TransactionDispatchingFilter<>), context);
e.ConfigureConsumer<TransactionEventConsumer>(context);
EndpointConvention.Map<ITransactionEvent>(e.InputAddress);
});
And i have TransactionEventConsumer what consume ITransactionEvent.
For now i recieve ITransactionEvent and filtering it by Filters.
But i need change TransactionEventConsumer from IFilter<ConsumeContext<ITransactionEvent>> to IFilter<ConsumeContext<Batch<ITransactionEvent>>> and still filtering ITranscationEvent by one, not by batch.
As i know, i can use .UseFilter in RecieveEndpoint configuration method, but with it i can't access DI container with service's. context.GetPayload<IServiceProvider>() always return null.
How can i use filter for one ITransactionEvent and then consume thay by batch consumer?
|
Q: how to convert externalXML to arraylist in FLEX only those xml tag having data need to be placed in an arraylist ,which will act as a dataprovider for a datagroup.
Can anyone pls help in achieving this task...Thanks in advance
A: for each (var x:XML in myXML.item) {
if (x.children().length() > 0)
myList.push(x);
}
|
Q: real-time database in firebase, rules I have the following problem: I have my app in development, this allows the authenticated user to add data from a crud, in the rules of firebase real-time database, when they are in "true" read and write, they are saved and visualized, but when I try to add the following rule it does not save the data
{
// Allow anyone to read data, but only authenticated content owners can
// make changes to their data
"rules": {
"some_path": {
"$uid": {
".read": true,
// or ".read": "auth.uid != null" for only authenticated users
".write": "auth.uid == $uid"
}
}
It is supposed to be so that the authenticated users can read and write their data, but that the other users can only see the published data. I cannot let users modify the data of others.
A: Change some_path with your refrence name
{
// Allow anyone to read data, but only authenticated content owners can
// make changes to their data
"rules": {
"some_path": {//change this with your ref_name
"$uid": {
".read": true,
// or ".read": "auth.uid != null" for only authenticated users
".write": "auth.uid == $uid"
}
}
}
}
|
Q: Linkbutton onclick not working in a Visual Webpart I am having issues with the onClick event on LinkButtons (possibly all controls). These are not working in a Visual web-part. I am writing for SharePoint 2010.
Simple example of what I am doing:
public partial class MyUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "load";
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
Label1.Text = "click";
}
}
<asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click">LinkButton</asp:LinkButton>
<asp:Label ID="Label1" runat="server"></asp:Label>
Web-part loads fine with Label1 text being set to "load", but clicking on the button has no effect.
An ideas?
A: Add AutoPostBack="true" to LinkButton and it will work fine.
<asp:LinkButton ID="LinkButton1" runat="server" AutoPostBack="true" onclick="LinkButton1_Click">LinkButton</asp:LinkButton>
[Update]
Sorry for the missleading answer. Checked out the LinkButton - no AutoPostBack property, but there is PostBackUrl property - assign it the url of page that contains your web part and it will work - tested. For other controls like Buttons, DropDownList it's AutoPostBack to use.
A: Couldn't reproduce this problem. Are you sure the controls are inside a form? This can happen if you have a mishap when editing the master page. Another possibility is if you change the attributes on the page or in the control, e.g. AutoEventWireup.
A: Add it in the CreateChildControls() event in the webpart, like:
protected override void CreateChildControls()
{
LinkButton linkbutton = new LinkButton();
linkbutton.Click += ClickButton;
this.Controls.Add(linkbutton);
}
protected void ClickButton(object sender, EventArgs e)
{
// handle event
}
|
Q: Sorting array of strings such that substrings of any other string will comes later I want to find an algorithm which can sort (or arrange) array of the strings such that if any string (say B) is sub-string of any other string (say ABAC) than that B should come after ABAC.
e.g. :
suppose the string are :
abc
bc
zef
abcde
then order will be :
abcde,
abc,
bc
and zef can come anywhere in the order.
A: Sort algorithms are based on comparing pairs of values. Often programming languages allow to provide the built-in sort-method with a comparator function, which should take two arguments, and return an integer value indicating their relative order (-1, 0 or 1).
So define the comparator as follows:
compare(a, b):
if a is substring of b then return 1
if b is substring of a then return -1
if a < b then return -1
if a > b then return 1
return 0
This substring-test should first check the length of the two strings to potentially avoid a scan of the strings. Because when a.length > b.length, then a cannot be a substring of b. Or you could also explicitly write:
compare(a, b):
if a.length <= b.length and a is substring of b then return 1
if a.length >= b.length and b is substring of a then return -1
if a < b then return -1
if a > b then return 1
return 0
If the target programming language does not offer this possibility, then you should write your own sorting function (like QuickSort), and make sure it can use such a comparator, so that (starting from a standard implementation) you would replace:
if a < b
with:
if compare(a, b) < 0
...etc.
Transitivity of the relationship
Let's assume for a moment that the relationship that is encoded in the compare function is not transitive, so that we could find three strings a, b and c for which:
*
*compare(a, b) < 0
*compare(b, c) < 0
*but also: compare(c, a) <= 0
First, note what this says about the lengths of the three strings:
*
*compare(a, b) < 0 implies that a.length >= b.length
*compare(b, c) < 0 implies that b.length >= c.length
*compare(c, a) <= 0 implies that c.length >= a.length
From the first two we conclude that a.length >= c.length, and combining that with the third, we can conclude all three strings have the same length.
So now we have:
*
*compare(a, b) < 0 implies that a is alphabetically ordered before b
*compare(b, c) < 0 implies that b is alphabetically ordered before c
*compare(c, a) <= 0 implies that c is alphabetically ordered before a, or is equal to a.
This leads to a contradiction. And so we must conclude that the relationship is transitive.
|
Q: Data Source Name not found? I'm working on vb.net and trying to connect to a Informix database.
Both the system and the server are in 64-bit mode and the file DSN is from the 64-bit ODBC Data Sources.
The string is something like this: DRIVER={IBM INFORMIX ODBC DRIVER (64-bit)};UID=userid;PWD=password;DATABASE=database;HOST=host;SERVER=server;SERVICE=9088;PROTOCOL=onsoctcp;CLIENT_LOCALE=en_US.CP1252;DB_LOCALE=en_US.819
It returns this error:
ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified.
I've already checked the name of the driver and it's correct, and the driver is installed correctly, as I have used it before with no problems.
Here's the code I'm trying to run, it's just a connection to the database which has worked for me before:
Imports System.Data.Odbc
Public Class Form1
Dim x As New OdbcConnection
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim constr As String = "DRIVER={IBM INFORMIX ODBC DRIVER (64-bit)};UID=uid;PWD=passwd;DATABASE=database;HOST=host;SERVER=server;SERVICE=9088;PROTOCOL=onsoctcp;CLIENT_LOCALE=en_US.CP1252;DB_LOCALE=en_US.819"
Try
x.ConnectionString = constr
x.Open()
x.Close()
Console.WriteLine("Connection Succesful")
Catch ex As Exception
Console.WriteLine("Connection Unsuccesful: " & ex.Message & Environment.NewLine & "Check input data")
End Try
End Sub
End Class
A: I think your application is 64 bit where you installed and configured 32 bit ODBC driver, or vice versa.
If you have Informix driver installed then in ODBC Driver Manager configure DSN (of course with successful connection testing) and try to use DSN with much simpler ConnectionString like:
test_odbc('DSN=ifx_test; Uid=username; Pwd=password;')
You can also see my Python recipes that show available ODBC sources: https://code.activestate.com/recipes/578782-printing-list-of-odbc-data-sources/?in=user-186902
You can run it with 32 bit and 64 bit Python interpreter (I prefer ActiveState which comes with odbc module) and see what DSN are available for each environment.
A: Just solved it. The debugger chose to work on X86 for some reason
|
Q: How to start and stop jupyter notebook on dl VMs I want to make changes to the VM environment (e.g. install a new conda package, or activate a new conda env) and then restart jupyter notebook - but I can't work out how to do that within the jupyter user of the Google Cloud DL Images. Is it possible?
A: If you want to run some code on a running DLVM and restart Jupyter, ssh to the machine from the compute section of the gcp web console. Then:
sudo service jupyter restart
If you want to do some steps automatically before Jupyter is started at the time you create the VM, create the DLVM using gcloud and specify a startup script as follows:
STARTUP_SCRIPT="conda install something"
gcloud compute instances create ${INSTANCE_NAME} \
--machine-type=n1-standard-8 \
--scopes=https://www.googleapis.com/auth/cloud-platform \
--min-cpu-platform="Intel Skylake" \
${IMAGE} \
--image-project=deeplearning-platform-release \
--boot-disk-size=100GB \
--boot-disk-type=pd-ssd \
--accelerator=type=nvidia-tesla-p100,count=1 \
--boot-disk-device-name=${INSTANCE_NAME} \
--maintenance-policy=TERMINATE --restart-on-failure \
--metadata="install-nvidia-driver=True,startup-script=${STARTUP_SCRIPT}"
|
Q: How to Run Ktor Embedded Server from Code I've written a simple Ktor server that processes a JSON payload from an incoming POST request. Now, I want to spawn this server from another application, and after processing the request, shut it down.
So the first problem I need to solve is: how do I spawn the Ktor server from some other 'driver' Kotlin code? All the tutorials I've found online are 1-2 years old, and are apparently using an older version of Ktor, where the main class looks like this:
fun main(args: Array<String>) {
embeddedServer(Netty, 8080) {
routing {
get("/") {
call.respondText("Hello from Kotlin Backend", ContentType.Text.Html)
}
}
}.start(wait = true)
}
It's easy to see that one can just run the embeddedServer(Netty, 8080) { ... }.start(wait = true) from wherever they want, to spawn the server. But I downloaded the Ktor plugin for IntelliJ IDEA yesterday, and it seems things have changed lately. This is what the new main class looks like:
fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)
@Suppress("unused") // Referenced in application.conf
@kotlin.jvm.JvmOverloads
fun Application.module(testing: Boolean = false) {
install(ContentNegotiation) {
gson {
}
}
routing {
get("/") {
call.respondText("HELLO WORLD!", contentType = ContentType.Text.Plain)
}
get("/json/gson") {
call.respond(mapOf("hello" to "world"))
}
}
}
Now, the Application.module(...) function takes care of setting up the routing and stuff, while the actual running of the server is done internally by io.ktor.server.netty.EngineMain.main(args). Also, properties like the port number are referenced from the application.conf file, and I'm not quite sure how it figures out where to find that application.conf file.
I have been able to run this Ktor server using gradlew. I also understand that it is possible to export it as an executable jar and run it (as explained here). But I can't find out how to run it from code. Any suggestions?
Edit: And it would be nice if I could set the port number from the driver code.
|
Q: mongoid TTL option doesn't work class Event
include Mongoid::Document
field :status, type: Integer
index({ status: 1 }, { expire_after_seconds: 3600 })
end
I knew TTL option for MongoDB and Mongoid.
https://github.com/mongoid/mongoid/commit/ac3c4bbe43c8756daff844c808c99b84f10834bc
But its ttl option doesn't work since I update and upgrade ruby gems and brew packages.
Do you have any suggestions?
A: Your :status field must be a date BSON type. http://docs.mongodb.org/manual/tutorial/expire-data/#constraints
|
Q: Find named elements in WinRT XAML page I'm trying to add notes represented by icons into a RichTextBlock and then add Tapped event handlers to all of them. I found out that I can't add handlers into XAML before I insert it programmatically into the page, so I need to find each element with a certain naming pattern and add a handler to each one.
Here's my code:
private void assignNoteHandlers()
{
//For each note expected on screen
for ( int i = 0; i < currentTextFile.noteCount; i++ ){
try
{
string noteName = String.Format("note{0}", i);
Image noteIcon = (Image)pageRoot.FindName(noteName);
noteIcon.Tapped += noteIcon_Tapped;
}
catch
{
Debug.WriteLine("The Image note{0} was not found", i);
continue;
}
}
}
When I look at the screen, I can see the note icon inserted into the text as it should be.
The text on screen comes from an HTML file, into which I programmatically insert this string for each note:
string noteXML = string.Format("<note name=\"note{0}\" src=\"Assets/TEMPNoteIcon.png\" />", i);
That psuedo-HTML gets converted into XAML with this xslt template:
<xsl:template match="NOTE | note">
<Span>
<InlineUIContainer>
<Image Stretch="None" >
<xsl:attribute name="x:Name">
<xsl:value-of select="@name"/>
</xsl:attribute>
<!-- DISABLED
<xsl:attribute name="Name">
<xsl:value-of select="@name"/>
</xsl:attribute>
-->
<xsl:attribute name="Source">
<xsl:value-of select="@src"/>
</xsl:attribute>
<xsl:apply-templates />
</Image>
</InlineUIContainer>
</Span>
</xsl:template>
I have tried using both "Name" and "x:Name" above (but I can't do both at once).
So, my problem is that in the first block of code (which runs last), Image noteIcon is always null.
I know this is a very complicated question, but can anyone help me figure this out?
EDIT: Here's the code that fills the RichTextBlock (I downloaded it from the web),
private static async void HtmlChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// Get the target RichTextBlock
RichTextBlock richText = d as RichTextBlock;
if (richText == null) return;
// Wrap the value of the Html property in a div and convert it to a new RichTextBlock
string xhtml = string.Format("<div>{0}</div>", e.NewValue as string);
RichTextBlock newRichText = null;
if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
{
// In design mode we swallow all exceptions to make editing more friendly
string xaml = "";
try {
xaml = await ConvertHtmlToXamlRichTextBlock(xhtml);
newRichText = (RichTextBlock)XamlReader.Load(xaml);
}
catch (Exception ex) {
string errorxaml = string.Format(@"
<RichTextBlock
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
>
<Paragraph>An exception occurred while converting HTML to XAML: {0}</Paragraph>
<Paragraph />
<Paragraph>HTML:</Paragraph>
<Paragraph>{1}</Paragraph>
<Paragraph />
<Paragraph>XAML:</Paragraph>
<Paragraph>{2}</Paragraph>
</RichTextBlock>",
ex.Message,
EncodeXml(xhtml),
EncodeXml(xaml)
);
newRichText = (RichTextBlock)XamlReader.Load(errorxaml);
} // Display a friendly error in design mode.
}
else
{
// When not in design mode, we let the application handle any exceptions
string xaml = await ConvertHtmlToXamlRichTextBlock(xhtml);
newRichText = (RichTextBlock)XamlReader.Load(xaml);
}
// Move the blocks in the new RichTextBlock to the target RichTextBlock
richText.Blocks.Clear();
if (newRichText != null)
{
for (int i = newRichText.Blocks.Count - 1; i >= 0; i--)
{
Block b = newRichText.Blocks[i];
newRichText.Blocks.RemoveAt(i);
richText.Blocks.Insert(0, b);
}
}
}
A: You don't need to create your RichTextBlock through XAML. You can do it like this:
var rtb = new RichTextBlock();
var paragraph = new Paragraph();
paragraph.Inlines.Add(new Run { Text = "Hello" });
paragraph.Inlines.Add(new InlineUIContainer { Child = new Button { Content = "World" } });
rtb.Blocks.Add(paragraph);
((Grid)this.Content).Children.Add(rtb);
A: It turns out my code wasn't waiting for the RichTextBlock to be filled before trying to attach the note handlers to the images. Odd, but simple.
|
Q: $0–1$ incidence matrix is totally unimodular then $G$ is bipartite. I know the result incidence matrix of a bipartite graph is totally unimodular.
But I am stuck with a converse statement:
Let $Q$ be the $0–1$ incidence matrix of the graph $G$, if $Q$ is totally
unimodular then $G$ is bipartite.
Require some hints to do the problem.
A: Hint: Show that the incidence matrix of an odd cycle is not totally unimodular.
|
Q: Word for "stating the obvious?" Is there a word or term commonly used to describe the act of stating the obvious (or a person who continually does so)?
He constantly states the obvious, he is such a __.
She is always ___ing.
A: Redundant is the word that you're looking for, according to Merriam-Webster.
Redundant means
*
*exceeding what is necessary or normal
*superfluous
So you can say:
Please could you be less redundant and get straight to the point?
A: Stating the obvious is perhaps best stated as "self-evident." For example, "A street is better than a little trail to connect those two large neighborhoods." "That's self-evident."
A: As a somewhat insulting noun, "Captain obvious" can be used for someone who is always stating the obvious.
Prolixity can be used to describe someone who says too much. This may be applicable in some cases.
In addition, Logorrhoea is a term with a similar meaning to prolixity although again the primary meaning is simply too much vs. stating the obvious.
A: I don't believe there's a single word that has the exact meaning you want, but the phrase "belaboring the obvious" is a classic idiom for your second case.
A: I believe you're looking for belabor, which means to redundantly or excessively state the obvious.
A: I think a bromide would be apt for your query.
Instead of offering an umbrella to her, the cheeky stranger offered
the bromide: "It's raining", much to her dismay.
A: Platitude, as in "He is full of platitudes"?
|
Q: Show and edit escaped character in QLineEdit Is there a way to show escaped characters like carriage return line feed "\r\n" characters in a QLineEdit in a human readable (escaped) way automatically?
Alternatively is there an easy method to automatically generate an escaped string.
Also I need to allow the user to edit the escaped string and when reading back the current text from the QLineEdit, storing it in a std::string it has to be non-escaped.
Use case.
I want the user to set a termination string (for example \r\n) for a communication object. Passing \r\n to a QLineEdit without any manual escaping, results in two unvisible characters in the QLineEdit input box.
A: "\\r\\n" ? You can create an inline stub the calls qstring::replace and return std with .toStdString
|
Q: Using StringEntity to send POST Request in Android? I'm using the exact same code in 2 programs, except for the storing of the POST data. In the first method (the one that works) I use NameValuePair, and in the other, I use StringEntity (doesn't work, but I also don't use any encoding). The reason I don't use encoding is because it completely messes up my String. The code with the StringEntity won't work though... Here's the code:
public static String sendNamePostRequest(String urlString, String nameField) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
StringBuffer sb = new StringBuffer();
try {
post.setEntity(new StringEntity(
"__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwULLTE3NDM5MzMwMzRkZA%3D%3D&__EVENTVALIDATION=%2FwEWBAL%2B%2B4CfBgK52%2BLYCQK1gpH7BAL0w%2FPHAQ%3D%3D&_nameTextBox=John&_zoekButton=Zoek&numberOfLettersField=3"));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(
entity.getContent()));
String in = "";
while ((in = br.readLine()) != null) {
sb.append(in + "\n");
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
This code does send the request (sniffed with wireshark to check), but doesn't return the appropriate HTML data. Any reason why this might be?
A: Instead of using:
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(
entity.getContent()));
Remove HttpEntity entity = response.getEntity(); and do this:
HttpResponse response = client.execute(post);
BufferedReader br = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
For NameValuePair, check this link
|
Q: XPage not syncing properly with backend data on partial refresh I have an XPage that displays fields in a document. I also have the ability to pop out a new window that displays those same fields. I'm implementing a document locking scheme so that the two instances can't cause conflicts (and this is how I'm testing it).
A problem I've run into is that when the user edits the document in the pop out and saves it, a partial refresh of the panel containing those same fields in the original page doesn't show the updated data.
The save in the pop out was successful, and I can see in the Notes client that the document does indeed have the new value, but the original page simply won't show the new value. A complete page refresh using the reload button in the browser works, but I'd like to trigger this programmatically and as quickly as possible, hence the partial refresh.
Does anyone know what is going wrong? Is the NotesXspDocument in the original page getting out of sync with the backend document? I read about document1.getDocument(true), but that doesn't seem to do anything.
(As usual, I can't supply source code unfortunately....)
A: Once the NotesXspDocument is loaded with the XPage, a partial refresh does not update the xspDoc from the back-end DB, but from the in-memory DataSource.
You will need to refresh the XPage:
Reload the url from browser or in ssjs with a context.reloadPage()
|
Q: Subsetting a pairwise matrix with wlidcard I would like to subset part of a large pairwise matrix into smaller matrices.
e.g.
TF1 TF2 TF3 TG1 TG2 TG3
TF1 0 2 1 450 460 450
TF2 2 0 1 452 462 462
TF3 1 2 0 451 461 451
TG1 450 452 450 0 2 0
TG2 460 462 462 2 0 1
TG3 450 452 451 1 2 0
I can subset if I input the exact column and row name "TF1" etc but I want e.g. all of the TFs.
I reckon it may be a grep but I cant put grep anywhere in my forumula:
TF <-T_PW[c("TF1","TF2","TF3"),c("TF1","TF2","TF3")]
This is the expected output matrix:
TF2 TF3 TF1
TF1 0 2 1
TF2 2 0 1
TF3 1 2 0
Is it because since it is a pairwise then the columns and rows have names??
Thank you
A: grep returns the indices of the input that match the regex provided:
> grep('^TF', rownames(T_PW))
[1] 1 2 3
> grep('^TF', colnames(T_PW))
[1] 1 2 3
You can therefore place grep inside [] to subset the rownames and colnames of the matrix:
TF = T_PW[grep('^TF', rownames(T_PW)), grep('^TF', colnames(T_PW))]
Since the rownames are symmetric to the colnames, you can also do something like this:
TF_names = grep('^TF', colnames(T_PW))
T_PW[TF_names, TF_names]
Result:
TF1 TF2 TF3
TF1 0 2 1
TF2 2 0 1
TF3 1 2 0
Data:
T_PW = read.table(text=" TF1 TF2 TF3 TG1 TG2 TG3
TF1 0 2 1 450 460 450
TF2 2 0 1 452 462 462
TF3 1 2 0 451 461 451
TG1 450 452 450 0 2 0
TG2 460 462 462 2 0 1
TG3 450 452 451 1 2 0", header = TRUE, row.names=1)
T_PW = as.matrix(T_PW)
|
Q: When to use this.prop when passing down props? I'm a beginner in JS/React and I am trying to wrap my head around the concept of when to use this.prop or just passing props down without this in React.
In some sources, the coder always uses this.prop while in others this seems to be unnecessary. Could anyone please clarify?
*
*In this example, we are passing props username, authed, logout, and header from apps to hello. To do so, we use this.props. everytime we import.
*However, in this example (React Native), we pass down term, onTermChange, and onTermSubmit from searchscreen to searchbar, without using this.props. Then I believe we re-defined our props in the TextInput of Search bar so its onEndEditing is the same as the onTermSubmit from the searchscreen.
*I thought this.props may be a react syntax which became streamlined in React Native. However, I came across yet another example in React which does not use this.props:
A: You will use "this" when you have a class component. When you have a functional component there is no need , because you're not creating an instance of a class. All arguments passed to a class are stored into "this.props".
So in your second example and third example , you have functional components, which take the consts passed to them not as props, but as actual constants with their own names.
Hope this helps.
A: props is being used in both scenarios. You are just accessing props values differently. First example uses Class component. That means props is passed to children as this.props, where as second example uses stateless/ functional component, which means no this. And
const FunctionalComponent = (props) => {
const {name, onLogin} = props
......
}
is equivalent to
const FunctionalComponent = ({name, onLogin}) => {
.....
}
due to Object Destructuring, hence you are not seeing explicit use of props in second example.
A: It's not a React thing but a JavaScript thing.
Classes - Here you need to access the state and props using the this keyword.
Functions - Here you don't need to use this in React. The argument to your function component here are props so you can directly use props.something and not this.props.something.
In your Searchbar component:-
const Searchbar = ({term,onTermSubmit,onTermChange}) means that the properties
term,onTermSubmit and onTermChange are being destructured from the props object and so can now be used directly. You don't need to access them like props.term anymore. They can directly be accessed like term wherever you want them to be.
|
Q: multithread task, Threads in ViewController? I have to make a simple task - singleview app with two buttons and three treads -
Start Button :
*
*create a thread T1 - the GPS location of the device is collected repeatedly every 3.0 seconds, and the results (as a string) are handed over to T3.
*create w thread T2 - the percentage usage of the device's battery is collected repeatedly every B seconds, and the results (as a string) are handed over to T3.
*In Thread T3 data from T1 and T2 should be stored in array and do sth when there is more then x data.
STOP button - just stop all three threads
I am a total noob in iOS threading. Unfortunately, App MUST use threads even if it is not necessary. Where should i create threads? Can i create them in ViewController class? Or maybe i should create a kind of singleton class to create and run threads (in a model part) ?
|
Q: "Attempted to read or write protected memory.." error when CrViewer print button is clicked I am getting the error "Attempted to read or write protected memory.." on print button click of the Crystal Report Viewer. This error is random and sometimes the report prints without any errors. Sometimes it gives error as "Handle is invalid". I have tried 2-3 solutions provided on internet like un-checking the "Suppress JIT optimization.."option , but nothing has worked for me. Please help!! (Other details : Crystal Reports 2011, Crystal Reports for VS2010 version 13.0.2, C# 2010 winforms application)
A: I faced this problem on Windows7 64-bit only, and the Windows6.1-KB2695321-v2-x64 hotfix solved the problem.
I used Windows Hotfix Downloader to download the hotfix.
I hope this helps.
A: I used this way to avoid this problem :
*
*set show print button to false in crystal report viewer
*add a custom button to toolstrip look the link below :
http://www.manjuke.com/2011/08/invoke-custom-method-when-crystal.html
*set Eventhandler to new customized button and inside it set code to print directly to printer
cr1.PrintToPrinter(1, false, 0, 0);
when you print directly to printer the problem does not appear.
or you can create a printdialog and use it to print your report
I did that and it all work fine
|
Q: Audio unit instrument + sampler now i'm working on a project for creating audio unit instrument that provide the basic waveform and also provide the audio sampler. i have a problem with how to implement the audio unit instrument base to support the audio file browsing and also wonder about the Audio unit SDK that support this situation to making a sampler.
the sampler can combine with wave form then generate the new sound
This is not an IOS audio unit. and i have not much knowledge about this sampler structure
i have been search a lot, but their are no related knowledge and some source code that i can understand. pls help me for at least browsing the audio file from Au Instrument and slicing the audio data in a time domain. so i can use DSP to work with it.
regard.
A: I suggest taking a look at the FilterDemo source code. It illustrates the most important aspects of the relationship between parameters, properties, UI, and the underlying DSP code. I have had some success with using the FilterDemo source code as a basis for converting raw DSP code, as well as AU plugins with only generic parameters (and therefore no UI), into fully integrated AU plugins with customized UI.
Also, pay close attention to the warnings, embedded in some of the source code, about renaming your UI elements, as there is a flat namespace to contend with.
|
Q: Why is sscanf behaving like this when converting hex strings to number? I have written a piece of code that I am using to research the behavior of different libraries and functions. And doing so, I stumbled upon some strange behavior with sscanf.
I have a piece of code that reads an input into a buffer, then tries to put that value into a numeric variable.
When I call sscanf from main using the input buffer, and the format specifier %x yields a garbage value if the input string is shorter than the buffer. Let's say I enter 0xff, I get an arbitrarily large random number every time. But when I pass that buffer to a function, all calls to scanf result in 255 (0xff) like I expect, regardless of type and format specifier mismatch.
My question is, why does this happen in the function main but not in the function test?
This is the code:
#include <stdio.h>
int test(char *buf){
unsigned short num;
unsigned int num2;
unsigned long long num3;
sscanf(buf, "%x", &num);
sscanf(buf, "%x", &num2);
sscanf(buf, "%x", &num3);
printf("%x", num);
printf("%x", num2);
printf("%x", num3);
return 0;
}
void main(){
char buf[16];
unsigned long long num;
printf("%s","Please enter the magic number:");
fgets(buf, sizeof(buf),stdin);
sscanf(buf, "%x", &num);
printf("%x\n", num);
test(&buf);
}
I expect the behavior to be cohesive; all calls should fail, or all calls should succeed, but this is not the case.
I have tried to read the documentation and do experiments with different types, format specifiers, and so on. This behavior is present across all numeric types.
I have tried compiling on different platforms; gcc and Linux behave the same, as do Windows and msvc.
I also disassembled the binary to see if the call to sscanf differs between main() and test(), but that assembly is identical. It loads the pointer to the buffer into a register and pushes that register onto the stack, and calls sscanf.
Now just to be clear:
This happens consistently, and num in main is never equal to num, num2 or num3 in test, but num, num2 and num3 are always equal to each other.
I would expect this to cause undefined behavior and not be consistent.
Output when run - every time
./main
Please enter the magic number: 0xff
0xaf23af23423 <--- different every time
0xff <--- never different
0xff <--- never different
0xff <--- never different
The current reasoning I have is in one instance sscanf is interpreting more bytes than in the other. It seems to keep evaluating the entire buffer, getting impacted by residual data in memory.
I know I can make it behave correctly by either filling the buffer, with that last byte being a new line or using the correct format specifier to match the pointer type. "%llx" for main in this case. So that is not what I am wondering; I have made that error on purpose.
I am wondering why using the wrong format specifier works in one case but not in the other consistently when the code runs.
A: sscanf with %x should be used only with the address of an unsigned int. When an address of another object is passed, the behavior is not defined by the C standard.
With a pointer to a wider object, the additional bytes in the object may hold other values (possibly leftover from when the startup code prepared the process and called main). With a pointer to a narrower object, sscanf may write bytes outside of the object. With compiler optimization, a variety of additional behaviors are possible. These various possibilities may manifest as large numbers, corruption in data, program crashes, or other behaviors.
Additionally, printing with incorrect conversion specifiers is not defined by the C standard, and can cause errors in printf attempting to process the arguments passed to it.
Use %hx to scan into an unsigned short. Use %lx to scan into an unsigned long. Use %llx to scan into an unsigned long long. Also use those conversion specifiers when printing their corresponding types.
My question is, why does this happen in the function main but not in the function test?
One possibility is the startup code used a little stack space while setting up the process, and this left some non-zero data in the bytes that were later used for num in main. The bytes lower on the stack held zero values, and these bytes were later used for num3 in test.
A: The argument expression in this call
test(&buf);
has the type char ( * )[16] but the function expects an argument of the type char *
int test(char *buf){
There is no implicit conversion between these pointer types.
You need to call the function like
test( buf );
Also it seems there is a typo
printf("%s","Please enter the magic number:");
printf("%x\n", num);
The variable num is not initialized.
In this call
unsigned long long num;
//...
sscanf(buf, "%x", &num);
you are using the third argument of the type unsigned long long int * but the conversion specification "%x" expects an argument of the type unsigned int *. So the call has undefined behavior.
You need to write
sscanf(buf, "%llx", &num);
The same problem exists for the used variable num that has the type unsigned short
unsigned short num;
//...
sscanf(buf, "%x", &num);
You have to write
sscanf(buf, "%hx", &num);
The same length modifiers you need to use in calls of printf
printf("%hx", num);
printf("%x", num2);
printf("%llx", num3);
Here is a demonstration program.
#include <stdio.h>
int main( void )
{
char buf[] = "0xff\n";
unsigned short num;
unsigned int num2;
unsigned long long num3;
sscanf( buf, "%hx", &num );
sscanf( buf, "%x", &num2 );
sscanf( buf, "%llx", &num3 );
printf( "%hx\n", num );
printf( "%x\n", num2 );
printf( "%llx\n", num3 );
}
The program output is
ff
ff
ff
|
Q: How to get the stats of memory and process consumption of a .net assembly I need to capture the statistics of windows service in terms of memory and process usage.
I tried exploring Perfmon, it has options for capturing the system performance. Probably this will have option for monitoring individual process also.
Please let me know how can i monitor windows service.
A: i quickly pulled up the pages which helped me a lot when i started with performance counters
Your reference:
http://msdn.microsoft.com/de-de/library/system.diagnostics.performancecounter.aspx
Simple Example
How can I use Performance Counters in C# to monitor 4 processes with the same name?
Special ASP.Net Counters:
http://msdn.microsoft.com/en-us/library/fxk122b4(v=vs.100).aspx
When you run intro problems read these:
Performance Counter by Process ID instead of name?
and
With Process PerformanceCounters how do I know what process an instance is associated with?
and
http://openrent.blogspot.de/2008/01/multiple-clr-performance-counters.html
|
Q: Not able to pull changes from Source tree When I am trying to pull the changes of my iOS app from SourceTree to my local computer. It is cloned with Bitbucket. I am getting the following error, on trying to Pull the recent changes or checking out a new branch:
error: Your local changes to the following files would be overwritten by
merge:
test.xcodeproj/project.pbxproj
Please commit your changes or stash them before you merge.
Aborting
A: You have local changes in your working directory. You need either commit those changes or discard or stash those local changes. Then pull latest from remote repo
|
Q: Why the generating function of $\frac{2^K}{k!}$ is $e^{2x}$ instead of $e^{2^{x}}$? I'm trying to find the generating function of $\frac{2^k}{k!}$, as there is a $k!$ in the denominator, it must be related to $e^x$, then perhaps, just a simple substitution is needed.
The sequence given by $a_k=\frac{2^k}{k!}$ is $\left\{1,2,2,\frac{4}{3},\frac{2}{3},\frac{4}{15},\frac{4}{45},\frac{8}{315},\frac{2}{315},\frac{4}{2835},\frac{4}{14175}\right\}$, the generating functions I proposed are:
$$e^{2x}=\ldots + \frac{4 x^6}{45}+\frac{4 x^5}{15}+\frac{2 x^4}{3}+\frac{4 x^3}{3}+2 x^2+2 x+1$$
$$e^{2^{x}}=\ldots + 2^x+2^{2 x-1}+\frac{1}{3} 2^{3 x-1}+\frac{1}{3} 2^{4 x-3}+\frac{1}{15} 2^{5
x-3}+\frac{1}{45} 2^{6 x-4}+1$$
I know that the coefficients of $e^{2x}$ are exactly the ones in the sequence of $a_k$ and this would show the answer. The problem is that I spent some time thinking about it, I looked at the answers in the back of the book and the generating function was actually $e^{2x}$. I have the answer, but I don't fully understand what's happening.
EDIT: My problem is that using $2x$ is just like a lucky guess. It could be anything, is there any systematic method that shows precisely that $y$ must be $2x$?
A: I may be pointing out the obvious, but...
Set $y=2x$. Then
$$
1+y+\frac{y^2}{2!}+\frac{y^3}{3!}+\dots = 1+2x+\frac{(2x)^2}{2!}+\frac{2x^3}{3!}+\dots = 1+2x+\frac{2^2}{2!}x^2+\frac{2^3}{3!}x^3+\dots
$$
Set $z=2^x$. Then,
$$
1+z+\frac{z^2}{2}+\frac{z^3}{3!}+\dots = 1+2^x+\frac{2^{2x}}{2!}+\frac{2^{3x}}{3!}+\dots
$$
It is possible to use $2^x=e^{x\log 2}$ to transform this further into an ordinary power series, but I think that from these substitutions you can already see why things aren't turning out as you expected.
|
Q: C# ASP.NET Core : I am able to update data for only one table but the others are not updating Am I doing something wrong?
I am not able to update data in my LsstoreDetails table but the Lsstores table is the only table that is updating the data in the database.
Whenever I debug, I can see that model.StoreDetail.StoreDetailsEn is not null and has registered my input but it doesn't save it.
I am not sure what to do as I tried so many different methods and the same issue kept persisting.
I am not getting any errors.
It would be much appreciated if I could receive some help/guidance to resolve this issue.
Thank you!
Model class:
public class Manage
{
public Lsstore Store { get; set; }
public List<Lscity> Cities { get; set; }
public List<Lscountry> Countries { get; set; }
public List<LsstoreStatus> Status { get; set; }
public List<LsstoreType> Types { get; set; }
public List<Lsprovince> Provinces { get; set; }
public List<LsstoreMall> Malls { get; set; }
public List<Lsregion> Regions { get; set; }
public List<LssubBrand> SubBrands { get; set; }
public List <LsstoreBusinessHour> StoreBusinessHours { get; set; }
public List<Lslanguage> Languages { get; set; }
public List<Lsbanner> Banners { get; set; }
public VwLsstoreMgmtInfo LsstoreMgmt { get; set; }
public VwStoreKiboInfo StoreKiboInfo { get; set; }
public LsstoreDetail StoreDetail { get; set; }
}
A part of the view (it is in a form):
<div class="mb-1">
@Html.LabelFor(model => model.Store.StoreDescription, "Store Name",
htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.Store.StoreDescription, new { htmlAttributes
= new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Store.StoreDescription, "", new {
@class = "text-danger" })
</div>
<div class="form-group input-group-lg mb-1">
@Html.LabelFor(model => model.StoreDetail.StoreDetailsEn, "Store Description", htmlAttributes: new { @class = "control-label" })
<ul class="nav nav-tabs" id="myTab">
<li class="nav-item">
<a href="#english" class="nav-link active" data-bs-toggle="tab">EN</a>
</li>
<li class="nav-item">
<a href="#french" class="nav-link" data-bs-toggle="tab">FR</a>
</li>
</ul>
<div class="tab-content">
<div class="tab-pane fade show active" id="english">
@Html.TextAreaFor(model => model.StoreDetail.StoreDetailsEn, new { htmlAttributes = new { @class = "form-control" }, rows = 10, cols = 60 })
@Html.ValidationMessageFor(model => model.StoreDetail.StoreDetailsEn, "", new { @class = "text-danger" })
</div>
<div class="tab-pane fade" id="french">
@Html.TextAreaFor(model => model.StoreDetail.StoreDetailsFr, new { htmlAttributes = new { @class = "form-control" }, rows = 10, cols = 60 })
@Html.ValidationMessageFor(model => model.StoreDetail.StoreDetailsFr, "", new { @class = "text-danger" })
</div>
</div>
</div>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int? id, Manage model)
{
if (id == null)
{
return NotFound();
}
// This part doesn't work
var storeDetail = db.LsstoreDetails.Where(x => x.StoreId.Equals(id)).FirstOrDefault();
if (storeDetail != null)
{
storeDetail.StoreDetailsEn = model.StoreDetail.StoreDetailsEn;
db.SaveChanges();
}
//-------------------------
// This part works
var data = db.Lsstores.Find(id);
if (data != null)
{
data.StoreDescription = model.Store.StoreDescription;
data.Address = model.Store.Address;
data.Local = model.Store.Local;
data.Zip = model.Store.Zip;
data.Sqft = model.Store.Sqft;
data.Fax2 = model.Store.Fax2;
data.Phone1 = model.Store.Phone1;
data.Fax1 = model.Store.Fax1;
data.RegisterCount = model.Store.RegisterCount;
data.PosVersion = model.Store.PosVersion;
data.Latitude = model.Store.Latitude;
data.Longitude = model.Store.Longitude;
data.OpenDate = model.Store.OpenDate;
data.CloseDate = model.Store.CloseDate;
data.ModifiedDate = model.Store.ModifiedDate;
data.ModifiedBy = model.Store.ModifiedBy;
db.SaveChanges();
}
//------------------------------------------
return RedirectToAction("index", "Home");
}
}
A: I think this is what you wanted to accomplish, but got confused along the way, i would suggest you read about auto mapper it would help clean up your code.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int? id, Manage model)
{
if (id == null)
{
return NotFound();
}
// This part doesn't work
var storeDetail = db.LsstoreDetails.Where(x => x.StoreId.Equals(id)).FirstOrDefault();
if (storeDetail != null)
{
storeDetail.StoreDetailsEn = model.StoreDetail.StoreDetailsEn;
db.LsstoreDetails.update(storeDetail);
}
//-------------------------
// This part works
var data = db.Lsstores.Find(id);
if (data != null)
{
data.StoreDescription = model.Store.StoreDescription;
data.Address = model.Store.Address;
data.Local = model.Store.Local;
data.Zip = model.Store.Zip;
data.Sqft = model.Store.Sqft;
data.Fax2 = model.Store.Fax2;
data.Phone1 = model.Store.Phone1;
data.Fax1 = model.Store.Fax1;
data.RegisterCount = model.Store.RegisterCount;
data.PosVersion = model.Store.PosVersion;
data.Latitude = model.Store.Latitude;
data.Longitude = model.Store.Longitude;
data.OpenDate = model.Store.OpenDate;
data.CloseDate = model.Store.CloseDate;
data.ModifiedDate = model.Store.ModifiedDate;
data.ModifiedBy = model.Store.ModifiedBy;
db.Lsstores.update(data);
}
db.SaveChanges();
//------------------------------------------
return RedirectToAction("index", "Home");
}}
|
Q: Redirect based on the ?id= parameter in the url I have a login system that I build in PHP and MySQL.
if any of my users log in they get directed to the user.php page
I have an authenticate.php page that redirects the user based on their ID to a page. This is the code that adds the id to the URL: header("Location: user.php?id=".$id); )
<?php
session_start();
// Change this to your connection info.
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = 'root';
$DATABASE_NAME = 'phplogin';
// Try and connect using the info above.
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if ( mysqli_connect_errno() ) {
// If there is an error with the connection, stop the script and display the error.
exit('Failed to connect to MySQL: ' . mysqli_connect_error());
}
// Now we check if the data from the login form was submitted, isset() will check if the data exists.
if ( !isset($_POST['username'], $_POST['password']) ) {
// Could not get the data that should have been sent.
exit('Please fill both the username and password fields!');
}
// Prepare our SQL, preparing the SQL statement will prevent SQL injection.
if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE username = ?')) {
// Bind parameters (s = string, i = int, b = blob, etc), in our case the username is a string so we use "s"
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
// Store the result so we can check if the account exists in the database.
$stmt->store_result();
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $password);
$stmt->fetch();
// Account exists, now we verify the password.
// Note: remember to use password_hash in your registration file to store the hashed passwords.
if ($_POST['password'] === $password) {
// Verification success! User has logged-in!
// Create sessions, so we know the user is logged in, they basically act like cookies but remember the data on the server.
session_regenerate_id();
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $_POST['username'];
$_SESSION['id'] = $id;
header("Location: user.php?id=".$id);
} else {
// Incorrect password
echo 'Incorrect username and/or password!';
}
} else {
// Incorrect username
echo 'Incorrect username and/or password!';
}
$stmt->close();
}
?>
Can I write a javascript function on the original user.php file that will read the user ID in the URL and redirect to a specific page on my site?
Example:
User 1 needs to go
from: http://www.mysite/user.php?id=1
To: http://www.mysite/dashboard/clientA/home.php
User 2 needs to go
from: http://www.mysite/user.php?id=2
To: http://www.mysite/dashboard/clientB/home.php
A: Hi you can do the following:
//function redirect to page
function redirect(){
var id= <?php echo $_GET['id'];?>;
if(id==1){
window.location.href = "url1";
}
if(id==2){
window.location.href = "url2";
}
}
redirect();
|
Q: Experience with AMCC 3ware 9650se raid cards? Ours seems dead We have a 8-port 3ware 9650se raid card for our main disk array. We had to bring the server down for a pending power outage, and when we turned the machine back on, the raid card never started.
This card has been in service for a couple years without problems, and was working up until the shutdown.
Now, when we turn the machine on, the bios option rom that normally kicks in before the bootloader doesn't show up, none of the drives start, and when the OS tries to access the device, it just times out.
The firmware on it has been upgraded in the past, so it's possible we've hit some sort of firmware bug.
We're using it in a Silicon Mechanics R272 machine with gentoo for the OS. The OS eventually boots, but alas, without the card.
We've ordered a new one, but I'm worried that if we replace the card it won't recognize the existing array. Has anybody performed a card swap before?
Any help would be greatly appreciated.
Edit: These are the kernel errors we see:
3ware 9000 Storage Controller device driver for Linux v2.26.02.012.
3w-9xxx 0000:09:00.0: PCI INT A -> GSI 18 (level, low) -> IRQ 18
3w-9xxx 0000:09:00.0: setting latency timer to 64
3w-9xxx: scsi0: ERROR: (0x06:0x000D): PCI Abort: clearing.
3w-9xxx: scsi0: ERROR: (0x06:0x001F): Microcontroller not ready during reset sequence.
3w-9xxx: scsi0: ERROR: (0x06:0x0036): Response queue (large) empty failed during reset sequence.
3w-9xxx 0000:09:00.0: PCI INT A disabled
A: It's quite painless to swap 3ware cards.
Just make sure it's the same or newer model and that the firmware versions are the same. If the firmware versions are different, the disks won't import to the controller. (been there, done that)
Does the old card show up in lspci at all? I've had problems where the BIOS settings would get scrambled and cause the card to not show up at all. I had to reenable the PCI slot and also enable MSI for the 3Ware cards to appear again.
A: This is Dan who posted previously, this time I've created an account :)
Anyway, now that my data was pulled.. I decided to screw around with the card and success!!
*
*Downloaded LiveCD version of Ubuntu 10.04.3 LTS
*Booted Live and ensured the card was detected ('tail /var/log/messages | grep 3w-')
*Installed tw_cli from the following guy's repo: http://jonas.genannt.name
*Downloaded the latest firmware (2.08.00.009) from CodeSet 9.3.0.8 for the 9500S-8 from http://www.3ware.com/support/downloadpageprod.asp?pcode=9&path=Escalade9500SSeries&prodname=3ware%209500S%20Series
*Used tw_cli to flash the firmware (stock tw_cli from 3ware doesn't support this). I did not use the force flag, and flashed despite already having the same version.
*Rebooted when it told me so.
BIOS now comes up as expected!
RMA my !@#. Perhaps I should share this with 3Ware. Big thanks to everyone for listening.
A: Some info on using 3ware 9650 raid cards in modern, common motherboards:
*
*Avoid full size 9650 cards as they don't work with newer motherboards, bios fails to kick in after soft reset. In older motherboards they work fine (tested in core2 motherboards).
*The low profile 9650SE cards are later made and they work fine in modern uefi, etc. motherboards.
*They are still working (most of them made around 2007 perhaps?)
*Did not see a failing battery yet, after 8-9 years (using them in ideal conditions, batteries always checked, charged).
*You can switch cards, but use the same firmware (or newer if same version is not available). When building raids use the lower ports first, because you can also switch to a 9650 card with fewer ports easily as long as the higher ports are not used on the original card.
*avoid the first x16 pci express port on the motherboard, some motherboards are expecting video cards there, causing strange behavior.
*installing 3dm2 and cli is working out of the box in ubuntu (tested: 14.04LTS, 16.04LTS), just run the shell script from the install.
*It's a pity that 3ware is no more, these are great products
*if you use them still, sadly its time to swicth to something new. I'm afraid there is only LSI (now Broadband) to consider.
*after Broadcom bought Avago they made changes to Avago website, drivers/downloads are harder to find for 3ware.
A: You should be good, i haven't done it with that particular card, but with many other Hardware raid cards. The only thing i would suggest you do is to toss the card in another machine, make sure it works, and is at the same BIOS level as your old card - downgrade if you have to.
A: 3ware cards are excellent at array compatibility. Do ensure the firmware is no older then the old card (as far as you can determine), and you probably want to try and keep within the same series if possible.
Keep those two in mind and it just works.
A: I happened to do some repetitive booting in a machine that had a 9500S-8 and it appears to have suffered the same fate. I came across an article for the 9650 from 3ware saying how to fix it. I couldn't believe 3Ware's solution of the only option being to RMA the card.
Anyway, I haven't been successful in applying any of the said magic to revive the BIOS. Thankfully after a couple of reboots in a different machine, it's detected properly after booting (BIOS still not coming up), detected the raid array and I'm able to mount it and pull my data.
Both Ubuntu and Fedora distros show all card info except one: BIOS string not found. I'm going to pull my data before I start screwing with firmware updates, in the meantime, antiduh, if you're still around and reading this, do you have any additional info about the Redhat version or drivers or other procedure I can try? I'm not convinced a firmware update will solve this..
A: I have swapped an 8 port card for a 12 port card ( edit thinking about it was a 9500 not a 9650 ) and the other card has detected the array so I would have every expectation that it would work based on my experience.
A: We managed to bring the card back to life, magically. We took the card out of the machine and stuck it in a completely different machine running something redhat with very new drivers. The story goes that the first time it booted, the raid bios did not kick in during the boot (like we'd been seeing), but the kernel reported a lot of different errors. Eventually it was able to actually bring it up and then the next reboot the raid bios started working again and it booted cleanly. We put it back in the machine and everything came back to life.
To me, this sounds like a problem with microcode - i've seen some drivers for things like sound cards, soft raids, video cards, etc download some sort of microcode to the card when turning it on. If the last time that happened things went bad, or if it got corrupted due to the power blip from the UPSes kicking in when we lost power (walls down the hall turned into a waterfall), then that would certainly explain what happened.
Figured I'd post an update for all future googlers.
Edit 3-Jan-2012:
@rakslice made the point that these cards often have battery back-ups attached. We hadn't tried to remove the battery (didn't think of it), but it's a great idea. Anybody else having this problem may want to try the same. We're still not sure if we fixed it because the Fedora kernel did some magic handshake to recover the card, or if we happened to leave it unpowered long enough for something to reset.
A: I've got a stable of 3Ware 9650SE cards and swapping is easy. I tested that before deploying as I have 4 and 8 port cards.
However, recently my experience with 3ware soured badly.
It started with a hang on the backup box with 5 x 1.5TB drives. The controller was unstable, when heavily loaded (just untaring a large tgz file), and would crash within a day of burn-in testing.
A spare controller worked fine.
Then a 2nd controller failed and I've sent the past 4 replacements back. They all fail within 48 hours of burn-in testing on the provided firmware or the latest. A raid 5 array of 5 to 7 drives will at times crash the system so badly that the card is not detected unless the system is powered down. A raid 5 array of 4 HDs will also fail - but it takes a few days instead of hours. The QA people will not talk to me as I don't use their approved motherboards - but I've got 3 different motherboards (all Asus, 2 AMD, one Intel) which I use for testing - and a failing card fails on all of them. The failures are basically a flurry of parity errors. Typically one will see messages about the card being unresponsive and being reset and then it just does an outright hang and corruption of the data being manipulated.
Right now I can't trust the cards. Only a burn-in test for a few days reveals if a card will be stable under load. Sending them in for warranty replacement seems to be a method to just swap a flaky card for a different flaky card!
A: Ive had excellent results with the 3ware 9650se. I have owned several of them: a few 2 port cards, a pair of 4 port cards, and one 12 port that I got used for a great price. I usually plug them into the PCI-e slot that is used for a video card, and they just work.
Although, I have found a bios setting that causes them to crash. Its called the PCI Latency Timer. I use a lot of AMD mainboards, and those that have this bios option will default to 64. Unless I set it to 32, nothing is stable.
Anyway, I'm about to upgrade one array to 5 x 2TB drives and I'll have to swap controllers, so your answers have given me hope.
Is the information about the array written to the drives? Is that how a different controller can import the array? (I need to see how thats done)
|
Q: How to preserve transparency in PHP GD on a PNG I am using this code:
<?php
list($width, $height, $type, $attr) = getimagesize("terrain.png");
$canvas = imagecreatetruecolor($width, $height);
$src = imagecreatefrompng("terrain.png");
if($_GET['glass'] == 1){
$src2 = imagecreatefrompng("rock.png");
}
imagecopymerge($canvas, $src, 0, 0, 0, 0, $width, $height, 100);
if($_GET['glass'] == 1){
imagecopy($canvas, $src2, 0, 0, 0, 0, 16, 16);
}
imagealphablending($canvas, true);
imagesavealpha($canvas, true);
header("Content-type: image/png");
imagepng($canvas);
imagedestroy($dest);
imagedestroy($src);
?>
Terrain.png is at http://hogofwar.co.uk/experiment/mc/terrain.png (which is transparent)
How do I preserve the transparency when using GD?
A: You can try
Parameters:
$new_image = image resource identifier such as returned by imagecreatetruecolor(). must be passed by reference
$image_source = image resource identifier returned by imagecreatefromjpeg, imagecreatefromgif and imagecreatefrompng. must be passed by reference
<?php
function setTransparency($new_image,$image_source)
{
$transparencyIndex = imagecolortransparent($image_source);
$transparencyColor = array('red' => 255, 'green' => 255, 'blue' => 255);
if ($transparencyIndex >= 0) {
$transparencyColor = imagecolorsforindex($image_source, $transparencyIndex);
}
$transparencyIndex = imagecolorallocate($new_image, $transparencyColor['red'], $transparencyColor['green'], $transparencyColor['blue']);
imagefill($new_image, 0, 0, $transparencyIndex);
imagecolortransparent($new_image, $transparencyIndex);
}
?>
You can check for more details,
http://www.php.net/manual/en/function.imagecolortransparent.php
A: Try this:
$img = imagecreatefrompng("yourimage.png");
$width = imagesx($img);
$height = imagesy($img);
$new_width=500;//this is the new width of the output image
$newheight=($height/$width)*$new_width;
$target=imagecreatetruecolor($new_width,$newheight);
$transparent=imagecolorallocatealpha($target,0,0,0,127);
imagefill($target,0,0,$transparent);
imagecopyresampled($target,$img,0,0,0,0,$new_width,$newheight,$width,$height);
imagealphablending($target,false);
imagesavealpa($target,true);
imagepng($target,"your_target_filename.png");
Done...
|
Q: sequences and subsequences Let $(x_n)_{n\geq1}\subseteq \mathcal{H}$ and $(y_n)_{n\geq1}\subseteq \mathcal{H}$ such that $\|x_n\|=\|y_n\|=1$. I see in a paper the following statements: We claim that there exists a constant $\theta\in \mathbb{R}$ such that $|\langle x_n\; |\;y_n\rangle|\leq \theta< 1$ for all $n$ sufficiently large. To see this, suppose otherwise. By replacing $(x_n)_{n\geq1}\subseteq \mathcal{H}$ and $(y_n)_{n\geq1}\subseteq \mathcal{H}$ with subsequences, we may assume that $\lim_{n\longrightarrow\infty}|\langle x_n\; |\;y_n\rangle|=1$. I don't understand how to prove that
$$\lim_{n\longrightarrow\infty}|\langle x_n\; |\;y_n\rangle|=1.$$
Where $\mathcal{H}$ stands for a Hilbert space over $\mathbb{K}=\mathbb{R}$ or $\mathbb{C}$, with inner product $\langle\cdot\;| \;\cdot\rangle$.
And thank you.
A: Suppose that it is not true that there is a constant $\theta<1$ such that
$|\langle x_n|y_n\rangle|\leq\theta <1 $ for all $n$ sufficiently large. Therfore, for every positive integer $k$, the number $\theta=1-1/k$ does not satisfy
$|\langle x_n|y_n\rangle|\leq 1-1/k $ for all $n$ sufficiently large, which means that it is not true that there exists an $N$ such that for all $n>N$ this inequality is valid. Therefore, there exists some $n_k$ such that
$1\geq |\langle x_{n_k}|y_{n_k}\rangle|> 1-1/k $ where the l.h.s inequality from from the fact that $x_n,y_n$ are unit vectors, and in fact we can always choose $n_{k+1}>n_k$ (why?). It follows that
$$\lim_{k\to\infty}|\langle x_{n_k}|y_{n_k}\rangle|=1$$
as was declared.
|
Q: Getting information from an object selected using Mouse Listeners So basically I am trying to make the Set card game the idea is to select 3 cards from a 4x3 board of cards determine if they are all a match or all opposite and display a message. I have build the cards and they all have a value for shade, shape, color, and number. What I am having trouble with is when I click on the card I am able to remove it. What I want to do is click on a card that is 2 red dashed squiggles and have it return 2,1,2,3 and add it onto a sum for each. Then after the three cards are selected determine if they are a match. I do not even know how to go about doing this. The only thing I have really tried was saving the card I clicked on to a new object.
package assignment3;
import acm.program.GraphicsProgram;
import acm.graphics.*;
import java.awt.event.MouseEvent;
import java.util.Random;
public class SetGame extends GraphicsProgram
{
private int APP_WIDTH = 470;
private int APP_HEIGHT = 300;
GObject Card[][];
public void run()
{
setSize(APP_WIDTH,APP_HEIGHT);
for(int row = 0;row < 3; row++)
{
for(int col = 0; col < 4; col++)
{
Card[][] setCard = new Card[4][3];
setCard[col][row] = new Card(col*60, row*60, getRandomNum()+1,getRandomNum()+1,getRandomNum()+1,getRandomNum()+1);
add(setCard[col][row]);
}
println();
}
addMouseListeners();
}
public int getPigment(int num)
{
int pigment = num;
String[] color = new String[3];
color[0] = "red";
color[1] = "green";
color[2] = "purple";
return pigment;
}
//gets a random shape
public int getShape(int num)
{
int shape = num;
String[] Shape = new String[3];
Shape[0] = "circle";
Shape[1] = "diamond";
Shape[2] = "squiggle";
return shape;
}
public int getShade(int num)
{
int shade = num;
String[] Shade = new String[3];
Shade[0] = "solid";
Shade[1] = "dashed";
Shade[2] = "hollow";
return shade;
}
public int getRandomNum()
{
Random number = new Random();
int num = number.nextInt(3);
return num;
}
public void mouseClicked(MouseEvent e)
{
GObject whichCard = getElementAt(e.getX(), e.getY());
if(whichCard == null)return;
remove(whichCard);
}
}
And here is the constructor on the other class
package assignment3;
import java.awt.Image;
import java.awt.Toolkit;
import java.util.Random;
import acm.program.GraphicsProgram;
import acm.graphics.*;
//Written by Dan Mattwig
//This program is built to display properties for cards
public class Card extends GCompound
{
private int color;
private int shape;
private int shading;
private int number;
public Card(int X,int Y,int color,int shape, int shading, int number)
{
setLocation(X,Y);
this.color = color;
this.shape = shape;
this.shading = shading;
this.number = number;
int image = (color * 3) + (shape * 9) + (shading * 27) + (number - 39);
GImage card = new GImage("images/"+image+".gif");
add(card,X,Y);
}
}
A: When clicked, you're going to need to determine if the source of the event represents a Card, for example...
if (whichCard instanceof Card) {
...
}
You will then need to determine the properties of Card, but you've provided no means by which to do this. You will need to provide a series of getters so you can obtain the information you need, for example...
public int getColor() {
return color;
}
public int getShape() {
return shape;
}
public int getShading() {
return shading;
}
public int getNumber() {
return number;
}
At this point, you need to start making decisions. You could add each Card to a List of some kind as it is clicked and process it at a later stage or make comparisons when they click, that's up to you.
At any rate, I be tempted to use the Comparable interface...
|
Q: Error when adding Role to my user in a scratch org I came across this issue when trying to add a role to my own user, in order to have the account serve as a community account for community user provisioning. I also tried creating another admin with the role set from the get-go but same issue. Anybody else seen this?
A: This is a pretty common issue with scratch orgs, particularly if your org is generated with hasSampleData: false. It comes up any time you assign one of the built-in Roles to any User and it's always a gack.
I typically begin scratch org builds that use hasSampleData: false with a little Anonymous Apex:
delete [SELECT Id FROM UserRole];
UserRole ur = new UserRole(Name = 'CEO');
insert ur;
update new User(Id = UserInfo.getUserId(), UserRoleId = ur.Id);
|
Q: How to divide string in php How can I add divider ; in the following variable which contains string
I have string like this:
$filename = "a.jpg3c.pngyes.jpg";
I would like to have something like
a.jpg;3c.png;yes.jpg
This string is created when I select multiple files to upload.
Is regex only solution in here?
A: Regex is not the only solution! Perhaps you can use str_replace() instead of regex.
$filenames = "a.jpg3c.pngyes.jpg";
$img_extensions = array(".png", ".jpg", ".gif");
$semicolon_additions = array(".png;", ".jpg;", ".gif;");
$newfilenames = str_replace($img_extensions, $semicolon_additions, $filenames);
http://php.net/manual/en/function.str-replace.php
Edit: In your particular case, I would add in the semicolon at the end of the filename inside of your loop.
A: Here is one option using regular expressions:
$filename = "a.jpg3c.pngyes.jpg";
$regex = '/\.(jpg|png|gif)(?!$)/';
$filename = preg_replace($regex, ".$1;", $filename);
|
Q: What is the best Docker tagging strategy? It is certain, that "latest" tag is not enough (i.e. if you want to rollback/debug).
What is the best docker tagging practice? Is it better to tag it with build number or commit number? Or some other option?
A: We don't use tagging for development environment, because we have pretty nice test coverage, but I suggest, you can easily tag container with your CI tool build number (Teamcity, Jenkins), something like
docker build -t {yourserviceName}:{JENKINS BUILD NUMBER}
However, production deployments - is a little bit different story.
We use two tags for that - previous and latest
1.Build production container on teh build server
2.Push it to shared repo
3.Pull to production server.
The latest tag is always contained at shared repository.
Before step 3, just re-tag existing running container to
previous.
What's the benefit?
If you have your latest container with critical failure, you just rollback to previous one. It's extremely rare case, when you have to do a rapid rollback, let's say, 4 deployments back, so no need to maintain versions there
A: I would say go with an older one cause they might look more stable. But you can refer to this:
https://hub.docker.com/_/node/tags
To get an idea of which one is suitable for you.
|
Q: When to use the user Java keyword Throw on a user-defined Exception? Is it possible to create a user-defined exception and only catch it in a try-catch or does the user-defined exception have to be thrown with the throw statement.
Question: I am somewhat confused on whether when to use the throw keyword? I think that the throw is used with user-defined Exceptions.
Code: (Java)
public genericPanel() {
try {
if (i.length == size) {
throw new MyOwnDefinedError("Error - Size is 1 integer
to large");
}
for (int index=0;index<=i.length;index++) {
System.out.println(i[index]);
}
} catch (MyOwnDefinedError o) {
o.getMessage();
} catch (Exception e) {
e.getMessage();
}
}
class MyOwnDefinedError extends Exception {
MyOwnDefinedError(String myNewString) {
super( myNewString);
}
A: throw is used whenever you want to throw any Exception, whether user-defined or not. There is no difference between "pre-defined" exceptions (like IOException) or self-defined one, as in your MyOwnDefinedError.
A: The throw keyword in java is used for user defined exceptions you are right. For example you are doing a banking application and you want to withdraw money from a customer's account. As is normal, the amount cannot go negative so you would throw a InvalidAmountException or something similar.
The keyword itself is used every time when an exceptional situation needs to be underlined, hence you will use throw for throwing any kind of exception, that exists in the API already or one that an user implemented.
As it goes for the handling of the exception - if one extends the Exception class from java, the Exception should be specifically placed on the method definition by using the throws keyword. If you want the exception to pop-up at runtime and maybe interrupt the execution of your program you can extend the RuntimeException. In this case, the exception handling it is optional - you don't have to specify it with throws or you don't have to wrap the execution of the method with try/catch block.
A complete tutorial on exception can be found here.
A: You can read the answer in the java documentation on throwing excepions:
http://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html
Before you can catch an exception, some code somewhere must throw one.
Any code can throw an exception: your code, code from a package
written by someone else such as the packages that come with the Java
platform, or the Java runtime environment. Regardless of what throws
the exception, it's always thrown with the throw statement.
As you have probably noticed, the Java platform provides numerous
exception classes. All the classes are descendants of the Throwable
class, and all allow programs to differentiate among the various types
of exceptions that can occur during the execution of a program.
You can also create your own exception classes to represent problems
that can occur within the classes you write. In fact, if you are a
package developer, you might have to create your own set of exception
classes to allow users to differentiate an error that can occur in
your package from errors that occur in the Java platform or other
packages
A: *
*Throw is used to throw an exception.
*Throw is a part of method definition.
*At a given point of time, a throw statement can only throw one exception.
*A throw statement is post fixed by an instance of exception.
A: class Test
{
void testDivision(float a,float b)
{
if(b=0.0)
{
try
{
throw new MathematicalException("Please, do not divide by zero");
}
catch (MathematicalException ae)
{
System.out.println(ae);
}
}
else
{
float result=a/b;
System.out.println("Result:" + result);
}
}
public static void main(String args[])
{
float f1 = Float.parsefloat(args[0]);
float f2 = Float.parsefloat(args[1]);
Test t1 = new Test();
t1.testDivision(f1,f2);
}
class MathematicalException extends Exception
{
MathematicalException();
MathematicalException(String msg)
{
super(msg);
}
}
}
|
Q: KOA - Passport with Password Grant strategy Hi I am trying to implement password grant strategy with Koa-passport. I configured a strategy as below
passport.use(new PasswordGrantStrategy({
tokenURL: "http://localhost:3001/api/v1/oauth/token",
clientID: "democlient1",
clientSecret: "democlientsecret1",
scope: "profile",
grant_type: "password",
customHeaders: {Authorization: "Basic ZGVtb2NsaWVudDE6ZGVtb2NsaWVudHNlY3JldDE=", scope: "profile" }
},
async (accessToken: string, refreshToken: string, profile: any,
done: (error: any, user?: any, options?: IVerifyOptions) => void) => {
console.log("Details ", accessToken, profile);
done(null, profile);
}));
And this is how i try to authenticate,
return passport.authenticate("password-grant", {
username: "test",
password: "test"
}, (err: any, user: any, info: any, status: any) => {
console.log("Inside Callback method");
})(ctx, next);
Could anyone please help me. The above code does not call the token URL. But the control come inside to the callback method defined in passport.authenticate.
Thanks in advance.
|
Q: Subtle bugs in implementing circular queue i am trying to implement a simple circular queue operation as below
void push(int theElement)
{
//Check if the push causes queue to overflow
if (((queueBack + 1 ) % arrayLength) == queueFront) {
std::cout<<"Queue is full."<<std::endl;
return ;
}
queueBack = (queueBack + 1) % arrayLength;
inputArray[queueBack] = theElement;
}
int pop()
{
//Check if queue is already empty
if ( queueFront == queueBack ) {
std::cout<<"Queue is empty."<<std::endl;
return;
}
queueFront = (queueFront + 1 ) % arrayLength;
return inputArray[queueFront];
}
Considering initially queueFront = 0 and queueBack = 0,
The above code results in a full queue even though actually it isn't. How do i correct this? Is my implementation correct in the first case?
Test cases
Initially arrayLength = 3, queueFront = 0, queueBack = 0;
*
*At the end of first call to push(1) ; queueFront = 0 , queueBack = 1 , 1 gets added to inputArray[1] rather than 0;
*At the end of second call to push(2), queueFront = 0, queueBack = 2, , 2 gets added to inputArray[2],
*Now , (queueBack + 1) % arrayLength == queueFront is true, whereas there is one more empty space left i.e., inputArray[0] .
Thanks
A: It's not a bug, it's a feature of circular queues. If you don't leave one empty slot, then there's no way to distinguish between the full and empty cases. Of course, the pop function should return the int that it read from the queue, and there's no need to set the value to -1.
|
Q: How to run dotnet restore using dotnet sdk linux docker image and mounted volume from Windows 10? I'm setting up a very simple build of a .NET Standard project using latest microsoft/dotnet sdk image (microsoft/dotnet:2.2.104-sdk-alpine3.8).
This is for a migration of existing code and existing build infrastructure into a new repository and build infrastructure (GitLab (not really important here)).
The new build infrastructure is of course leveraging Docker. But I also need to be able to build on my local Windows 10 using Docker (need this to prove that the SW can be built also without GitLab, without being dependent on a certain build computer).
What I have tried is to simply mount my project folder to the docker image and then run dotnet restore. I'm doing it interactively to understand what is going on:
docker run -it --rm --volume c:\projects\test-project`:/project microsoft/dotnet:2.2.104-sdk-alpine3.8
And then inside the container:
cd project
dotnet restore TestProject.sln
My solution is very basic. Looks like this:
test-project/
src/
ClassLibrary1/
ClassLibrary1.csproj
TestProject.sln
where ClassLibrary1.csproj looks like this (just referencing json.net):
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="12.0.1" />
</ItemGroup>
</Project>
That's it.
I'm using:
*
*Windows 10 Enterprise Version 1709
*Docker Desktop Community Version 2.0.0.3 (31259)
The expected result is that the dotnet restore should work without issues.
The actual result is surprising to me:
/project # dotnet restore TestProject.sln
Restoring packages for /project/src/ClassLibrary1/ClassLibrary1.csproj...
Installing Newtonsoft.Json 12.0.1.
Generating MSBuild file /project/src/ClassLibrary1/obj/ClassLibrary1.csproj.nuget.g.props.
/usr/share/dotnet/sdk/2.2.104/NuGet.targets(114,5): error : Access to the path '/project/src/ClassLibrary1/obj/8a35f086-c8be-4d31-93df-14c254b9be6c.tmp' is denied. [/project/TestProject.sln]
/usr/share/dotnet/sdk/2.2.104/NuGet.targets(114,5): error : Permission denied [/project/TestProject.sln]
Does anybody have an idea why this is not working as I expect it to? Am I not supposed to be able to make a restore on my mounted volume like this?
Note: If I run the same dotnet restore command directly from my Windows 10 computer everything works as expected.
UPDATE
The issue only appears when running the Linux container in Docker using "Windows Container mode (experimental features enabled)". Confusing to me is that I can still create and write to new files, append to existing files, etc. in the mounted folder from within the container. How can that be?
A: That's simply because the security context running the container isn't allowed to write into your project folder. That's not you, it's the user used to run docker!
Great explanation: https://jtreminio.com/blog/running-docker-containers-as-current-host-user/ (there's a section about Windows at the end of the article).
You can try this:
Click "Reset credentials" at the bottom of Docker Settings / Shared Drives in Docker. You will be asked for your user & password. This will be the user used to access your files!
|
Q: How to correctly put function in object Javascript by method? I want to make an object by function method because of lots of object I have to put in. I do step by step from instruction but this method do not work for me. I think the main problem is in function in function. I want to have all object have their its value of the second function so I name "A", "B", "C", "D" fields.
function pol () {
this.name = name;
this.moc = moc;
this.square = square;
this.A = A;
this.B = B;
this.C = C;
this.D = D;
this.price = function(){
if(wynik1 >18000){ return A;}
if(wynik1 >10000){ return B;}
if(wynik1 >5000){ return C;}
if(wynik1>3000){ return D;}
})();
}
var Bingo = new pol ("Psyche", 370, 1.7, 4000, 4200, 4600, 5000);
var Ringo = new pol("Psyche Myche", 370, 1.7, 4000, 4200, 4600, 5000);
var Zingo = new pol("Psyche Ryche", 370, 1.7, 4000, 4200, 4600, 5000);
var moc = pol.Ringo.moc
var pow = pol.Ringo.square
var prices = pol.Ringo.price();
I have problem in this step but my next step is
var moc = function (){
if(k =="A"){return: pol.Ringo.moc}
if(k =="A"){return: pol.Bingo.moc}
if(k =="A"){return: pol.Zingo.moc}
}();
Is this possible?
A: Notice that when you run:
var Ringo = new pol("Psyche Myche", 370, 1.7, 4000, 4200, 4600, 5000);
you have added inputs into this pol constructor. By that logic, you also need to have parameters defined in the pol constructor like:
function pol (name, moc, square, A, B, C, D) {...}
As a side note, be careful about the line: var prices = pol.Ringo.price(); You define this.price as:
function(){
if(wynik1 >18000){ return A;}
if(wynik1 >10000){ return B;}
if(wynik1 >5000){ return C;}
if(wynik1>3000){ return D;}
})();
Those final parentheses are making this function return a value instead of setting this.price to a function. You'll notice I copied the syntax error (the single parenthesis after the close of the function) because that decides whether this will return a value or not. If you remove that one parenthesis, you also need to remove the () as well. Decide if this.price is supposed to be a function or a value. Based on the fact that you tried pol.Ringo.price(), you probably want it to instead be a function like (also note the added parameter of wynik1 (assuming you then call Ringo.price(some number)):
this.price = function(wynik1) {
if(wynik1 >18000){ return A;}
if(wynik1 >10000){ return B;}
if(wynik1 >5000){ return C;}
if(wynik1>3000){ return D;}
}; // no additional parentheses
The this.price function should also not be using A, B, C, and D. It should instead be accessing the specific values that are connected with a specific pol constructor: this.A, this.B, this.C, and this.D.
The final note is that the use of pol.Ringo.moc (or any of your other parameters will not work. Since pol is a constructor, when you create a new pol, there is no connection to the variable pol. Ringo will now point to different storage that has all of the information copied over, then set based on the parameters you get to new pol(...). You instead can access any of your new pol constructs just by using the variable name and doing something like:
var moc = Ringo.moc
var pow = Ringo.square
var prices = Ringo.price();
A: finally, with your help, I managed to fix it but I don't understand why it works.
var Ringo = new pol("Psyche", 370, 1.7, 4000, 4200, 4600, 5000);
var prices = Ringo.price(4000, 4200, 4600, 5000);
in Ringo.price(); I can put any numbers and it works just like 1, 2, 3, 4 but if I put "a", "b", "c', "d" or empty do not. Why i can not just put there noting.
|
Q: Using JSON files in Google Maps styling I'm having a bit of a nightmare with this Google Maps custom styling wizard.
Ok, I have my map and it loads fine, but I am trying to add my JSON file to custom style the thing and I get an error.
Uncaught InvalidValueError: not a Feature or FeatureCollection
Also the error seems to come from a file called main.js - but I have a file called main.js and it doesn't have this code in it.
Here is my code in the head of my document.
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
var map;
function initialize() {
// Create a simple map.
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 16,
center: {lat: 53.668398, lng: -2.167713}
});
// Load a GeoJSON from the same server as our demo.
map.data.loadGeoJson('http://pixelsandcode.local:5757/map.json');
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
My JSON code:
{
"type": "FeatureCollection",
"features": [
{
"featureType": "landscape",
"elementType": "geometry.fill",
"stylers": [
{ "color": "#ffffff" }
]
},{
"featureType": "poi",
"elementType": "geometry",
"stylers": [
{ "color": "#efefef" }
]
},{
"featureType": "water",
"stylers": [
{ "visibility": "off" }
]
},{
"featureType": "road",
"elementType": "geometry.stroke",
"stylers": [
{ "visibility": "on" },
{ "color": "#dedddd" }
]
},{
"featureType": "road",
"elementType": "geometry.fill",
"stylers": [
{ "visibility": "on" },
{ "color": "#efefef" }
]
},{
"featureType": "poi",
"elementType": "labels.icon",
"stylers": [
{ "visibility": "on" }
]
}
]
}
Any ideas what I'm doing wrong here? This is my first go at doing maps.
A: You are confusing the JSON to style a map which is what you get out of the Map Styling Wizard and the GeoJSON used by the data layer
They go in different places and do different things. To style the map, put the "style" data in the MapOptions styles property.
The data layer is used for displaying geographic information on the map (markers, polygons, polylines,...), not styling the map tiles.
Working code snippet with your map styles (if you want to load them from an external file, you can, but you wouldn't use the data layer, you would just assign the styling data to a global variable and use that for the styles property):
var map;
function initialize() {
// Create a simple map.
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 16,
center: {
lat: 53.668398,
lng: -2.167713
},
styles: [{
"featureType": "landscape",
"elementType": "geometry.fill",
"stylers": [{
"color": "#ffffff"
}]
}, {
"featureType": "poi",
"elementType": "geometry",
"stylers": [{
"color": "#efefef"
}]
}, {
"featureType": "water",
"stylers": [{
"visibility": "off"
}]
}, {
"featureType": "road",
"elementType": "geometry.stroke",
"stylers": [{
"visibility": "on"
}, {
"color": "#dedddd"
}]
}, {
"featureType": "road",
"elementType": "geometry.fill",
"stylers": [{
"visibility": "on"
}, {
"color": "#efefef"
}]
}, {
"featureType": "poi",
"elementType": "labels.icon",
"stylers": [{
"visibility": "on"
}]
}]
});
// Load a GeoJSON from the same server as our demo.
//map.data.loadGeoJson('http://pixelsandcode.local:5757/map.json');
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map-canvas"></div>
A: you need to something like this:
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 16,
center: {lat: 53.668398, lng: -2.167713},
styles: [
{
"featureType": "landscape",
"elementType": "geometry.fill",
"stylers": [
{ "color": "#ffffff" }
]
},{
"featureType": "poi",
"elementType": "geometry",
"stylers": [
{ "color": "#efefef" }
]
},{
"featureType": "water",
"stylers": [
{ "visibility": "off" }
]
},{
"featureType": "road",
"elementType": "geometry.stroke",
"stylers": [
{ "visibility": "on" },
{ "color": "#dedddd" }
]
},{
"featureType": "road",
"elementType": "geometry.fill",
"stylers": [
{ "visibility": "on" },
{ "color": "#efefef" }
]
},{
"featureType": "poi",
"elementType": "labels.icon",
"stylers": [
{ "visibility": "on" }
]
}
]
})
|
Q: Android Eclipse dev enviroment not building dependent libraries I've got a project which has a dependency on a library. I added the library to the main project successfully in the "Android" project properties of the main project.
Once everything is compiled everything works fine. The problem is that if I make a change to the library I would expect that when I build project referencing that library it would detect that the library has changed source files and build it too. It doesn't. I have to manually build the library, then the main project. Is there something I need to do to get this to work?
A: A couple of things you could try:
1) Open the properties of the library project, select Android property and ensure that the Is Library checkbox is ticked.
2) Open the properties of your main project, select Java Build Path, click the Order and Export tab, then ensure that the Android Private Libraries checkbox is ticked.
3) Build your main project again to see if the changes in the library project are refreshed.
|
Q: Is kinetic energy formula tightly related to Pythagoras theorem? Consider 2 balls of mass $M$ traveling on the plain at speed $V$. One ball goes up and the other goes right. Let's associate them with the vectors $(V, 0)$ and $(0, V)$ to express their velocity and direction.
If one ball hits the other, we'll end up with one stationary ball and another one traveling by the vector $(V, V)$. From Pythagoras we know that $(V, V$) has a velocity of $\sqrt{2}V$. That means that one ball of mass $M$ and velocity $\sqrt{2} V$ has the same energy as 2 balls of mass $M$ and velocity $V$ each. This fits the $E = \frac{1}{2}MV^2$ formula. So, is this formula true only in geometries that comply to Pythagoras theorem?
A: In this case you assume that the collision is elastic. This means that there is no net loss of energy throughout the course of events, meaning
E=const.
Moreover, it is not necessary that one of the masses remain stationary, which you have assumed in this case (a basic introduction into this concept and a few examples are available here, on Wikipedia, CREDIT: https://en.wikipedia.org/wiki/Elastic_collision)
Also, when it comes to classical mechanics (not talking about Lagrangian or more complex systems), energy is not a vector, so work and energy are "seldom" linked with directions. In contrast to this, the momentum of an object IS a vector, that we link with a certain direction.
In your question it is important to ask what you mean by geometries that comply with the Pythagoras theorem - is it for non-curved spaces? Generally speaking when it comes to some problems you can select certain points of reference, which will help you describe the motion more easily (https://ocw.mit.edu/courses/physics/8-01sc-classical-mechanics-fall-2016/week-2-newtons-laws/4.3-reference-frames credit; MIT OpenCourseWare). You are describing a motion based around a certain reference frame. You can choose how you want to describe the motion of said object by selecting other points of reference. MIT OpenCourseWare, the channel which I've linked in the section link has great videos which will help introduce you to mechanics.
|
Q: Data design in marketing cloud I have to create an attribute group where I have two Data extension, below is the criteria for the same:
DE1 field name "Email"
DE2 fields name "EamilA" and "EmailP"
i have to create a data relationship between
Issue am not able to join same field(email from DE1) to different fields(emailA and emailP to DE2)
can you please help me find a solution around this attribute group.
Regards,
Joey
A: I believe the only way you can do this is via SQL.
Something like below should get you there:
SELECT a.email as email,
a.otherAttributes
FROM [de1] a
WHERE EXISTS (SELECT TOP 1 emailA FROM [de2] b WHERE a.email = b.emailA)
OR EXISTS (SELECT TOP 1 emailP FROM [de2] b WHERE a.email = b.emailP)
You could also do this with left joins instead if you wanted:
SELECT a.email as email,
a.otherAttributes
FROM [de1] a
LEFT JOIN [de2] b ON a.email = b.emailA
LEFT JOIN [de2] c ON a.email = c.emailP
WHERE b.emailA IS NOT NULL
OR c.emailP IS NOT NULL
In attributes and data relationships or via the UI at all, you cannot do this as honestly, It is not exactly a best practice approach. Utilizing SQL or a Script (not recommended as less efficient) is the only options to do this.
|
Q: Receiving multiple multicast feeds on the same port - C, Linux I have an application that is receiving data from multiple multicast sources on the same port. I am able to receive the data. However, I am trying to account for statistics of each group (i.e. msgs received, bytes received) and all the data is getting mixed up. Does anyone know how to solved this problem? If I try to look at the sender's address, it is not the multicast address, but rather the IP of the sending machine.
I am using the following socket options:
struct ip_mreq mreq;
mreq.imr_multiaddr.s_addr = inet_addr("224.1.2.3");
mreq.imr_interface.s_addr = INADDR_ANY;
setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
and also:
setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &reuse, sizeof(reuse));
A: Use setsockopt() and IP_PKTINFO or IP_RECVDSTADDR depending on your platform, assuming IPv4. This combined with recvmsg() or WSARecvMsg() allows you to find the source and destination address of every packet.
Unix/Linux, note FreeBSD uses IP_RECVDSTADDR whilst both support IP6_PKTINFO for IPv6.
*
*http://www.kernel.org/doc/man-pages/online/pages/man7/ip.7.html
Windows, also has IP_ORIGINAL_ARRIVAL_IF
*
*http://msdn.microsoft.com/en-us/library/ms741645(v=VS.85).aspx
A: Replace
mc_addr.sin_addr.s_addr = htonl(INADDR_ANY);
with
mc_addr.sin_addr.s_addr = inet_addr (mc_addr_str);
it's help for me (linux), for each application i receive separate mcast stream from separate mcast group on one port.
Also you can look into VLC player source, it show many mcast iptv channel from different mcast group on one port, but i dont know, how it separetes channel.
A: After some years facing this linux strange behaviour, and using the bind workaround describe in previous answers, I realize that the ip(7) manpage describe a possible solution :
IP_MULTICAST_ALL (since Linux 2.6.31)
This option can be used to modify the delivery policy of
multicast messages to sockets bound to the wildcard INADDR_ANY
address. The argument is a boolean integer (defaults to 1).
If set to 1, the socket will receive messages from all the
groups that have been joined globally on the whole system.
Otherwise, it will deliver messages only from the groups that
have been explicitly joined (for example via the
IP_ADD_MEMBERSHIP option) on this particular socket.
Then you can activate the filter to receive messages of joined groups using :
int mc_all = 0;
if ((setsockopt(sock, IPPROTO_IP, IP_MULTICAST_ALL, (void*) &mc_all, sizeof(mc_all))) < 0) {
perror("setsockopt() failed");
}
This problem and the way to solve it enabling IP_MULTICAST_ALL is discussed in Redhat Bug 231899, this discussion contains test programs to reproduce the problem and to solve it.
A: [Edited to clarify that bind() may in fact include a multicast address.]
So the application is joining several multicast groups, and receiving messages sent to any of them, to the same port. SO_REUSEPORT allows you to bind several sockets to the same port. Besides the port, bind() needs an IP address. INADDR_ANY is a catch-all address, but an IP address may also be used, including a multicast one. In that case, only packets sent to that IP will be delivered to the socket. I.e. you can create several sockets, one for each multicast group. bind() each socket to the (group_addr, port), AND join group_addr. Then data addressed to different groups will show up on different sockets, and you'll be able to distinguish it that way.
I tested that the following works on FreeBSD:
#include <sys/socket.h>
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/param.h>
#include <unistd.h>
#include <errno.h>
int main(int argc, const char *argv[])
{
const char *group = argv[1];
int s = socket(AF_INET, SOCK_DGRAM, 0);
int reuse = 1;
if (setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &reuse, sizeof(reuse)) == -1) {
fprintf(stderr, "setsockopt: %d\n", errno);
return 1;
}
/* construct a multicast address structure */
struct sockaddr_in mc_addr;
memset(&mc_addr, 0, sizeof(mc_addr));
mc_addr.sin_family = AF_INET;
mc_addr.sin_addr.s_addr = inet_addr(group);
mc_addr.sin_port = htons(19283);
if (bind(s, (struct sockaddr*) &mc_addr, sizeof(mc_addr)) == -1) {
fprintf(stderr, "bind: %d\n", errno);
return 1;
}
struct ip_mreq mreq;
mreq.imr_multiaddr.s_addr = inet_addr(group);
mreq.imr_interface.s_addr = INADDR_ANY;
setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
char buf[1024];
int n = 0;
while ((n = read(s, buf, 1024)) > 0) {
printf("group %s fd %d len %d: %.*s\n", group, s, n, n, buf);
}
}
If you run several such processes, for different multicast addresses, and send a message to one of the addresses, only the relevant process will receive it. Of course, in your case, you probably will want to have all the sockets in one process, and you'll have to use select or poll or equivalent to read them all.
A: I have had to use multiple sockets each looking at different multicast group addresses, and then count statistics on each socket individually.
If there is a way to see the "receiver's address" as mentioned in the answer above, I can't figure it out.
One important point that also took me awhile - when I bound each of my individual sockets to a blank address like most python examples do:
sock[i].bind(('', MC_PORT[i])
I got all the multicast packets (from all multicast groups) on each socket, which didn't help. To fix this, I bound each socket to it's own multicast group
sock[i].bind((MC_GROUP[i], MC_PORT[i]))
And it then worked.
A: IIRC recvfrom() gives you a different read address/port for each sender.
You can also put a header in each packet identifying the source sender.
A: The Multicast address will be the receiver's address not sender's address in the packet. Look at the receiver's IP address.
A: You can separate the multicast streams by looking at the destination IP addresses of the received packets (which will always be the multicast addresses). It is somewhat involved to do this:
Bind to INADDR_ANY and set the IP_PKTINFO socket option. You then have to use recvmsg() to receive your multicast UDP packets and to scan for the IP_PKTINFO control message. This gives you some side band information of the received UDP packet:
struct in_pktinfo {
unsigned int ipi_ifindex; /* Interface index */
struct in_addr ipi_spec_dst; /* Local address */
struct in_addr ipi_addr; /* Header Destination address */
};
Look at ipi_addr: This will be the multicast address of the UDP packet you just received. You can now handle the received packets specific for each multicast stream (multicast address) you are receiving.
|
Q: Luhn formula implementation in Java I'm trying to implement a luhn formula in my java servlet application. I tried other 'valid' credit cards numbers scattering in the internet and didn't work. I just want to know if I got it correctly. Any help would be appreaciate!
public static boolean luhn(String input){
char[] creditCard = input.toCharArray();
int checkSum = 0;
boolean alternate = false;
for (int i = creditCard.length - 1; i >= 0; i --){
int m = (int)Integer.parseInt(Character.toString(creditCard[i]));
if (alternate){
m *= 2;
if (m > 9){
m = (m & 10) + 1;
}
}
checkSum += m;
alternate = true;
}
if ( (checkSum % 10) == 0){
return true;
}else{
return false;
}
}
A: here the working code
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean repeat;
List<Integer> digits = new ArrayList<Integer>();
do {
repeat = false;
System.out.print("Enter your Credit Card Number : ");
String input = in.next();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c < '0' || c > '9') {
repeat = true;
digits.clear();
break;
} else {
digits.add(Integer.valueOf(c - '0'));
}
}
} while (repeat);
int[] array = new int[digits.size()];
for (int i = 0; i < array.length; i++) {
array[i] = Integer.valueOf(digits.get(i));
}
boolean valid = check(array);
System.out.println("Valid: " + valid);
}
to check for luhn algo
public static boolean check(int[] digits) {
int sum = 0;
int length = digits.length;
for (int i = 0; i < length; i++) {
// get digits in reverse order
int digit = digits[length - i - 1];
// every 2nd number multiply with 2
if (i % 2 == 1) {
digit *= 2;
}
sum += digit > 9 ? digit - 9 : digit;
}
return sum % 10 == 0;
}
or a more refracted program might be as below
import java.util.Scanner;
public class Luhn {
private static Scanner input;
public static void main(String... args) {
input = new Scanner(System.in);
System.out.print("Enter number to validate:\n");
String pnr = input.nextLine();
boolean result = luhn(pnr);
printMessage(result);
input.close();
}
static boolean luhn(String pnr){
// this only works if you are certain all input will be at least 10 characters
int extraChars = pnr.length() - 10;
if (extraChars < 0) {
throw new IllegalArgumentException("Number length must be at least 10 characters!");
}
pnr = pnr.substring(extraChars, 10 + extraChars);
int sum = 0;
for (int i = 0; i < pnr.length(); i++){
char tmp = pnr.charAt(i);
int num = tmp - '0';
int product;
if (i % 2 != 0){
product = num * 1;
}
else{
product = num * 2;
}
if (product > 9)
product -= 9;
sum+= product;
}
return (sum % 10 == 0);
}
private static void printMessage(boolean valid) {
if (valid){
System.out.print("Valid!\r");
}
else{
System.out.print("Invalid!");
}
}
}
|
Q: java.lang.NullPointerException in my JDBC app - Do I need to use resultSet or something? I am attempting to create a database connection and update using a prepared statement with JDBC to MYSQL.
I have tried changing the connection a bit and had to change the preparedStatement class to static in order to not get errors. However, when running the app I got a NullPointerException error and I can't see where exactly I need to create a new object.
Currently, I get an error:
Exception in thread "main" java.lang.NullPointerException
at Alter.main(Alter.java:12)
import java.sql.PreparedStatement;
import java.sql.SQLException;
public abstract class Alter {
public static void main(String[] args) throws SQLException {
String query = "INSERT INTO school.students (First_Name, Last_Name, Gender, Grade_Level, IEP, Disruptive_1to5_LowtoHigh, OffTask_1to5_LowtoHigh, Not_Responsible_1to5_LowtoHigh, Not_GetAlong_1to5_LowtoHigh) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement myStmt = Connection.prepareStatement(query);
myStmt.setString(1, "Chris");
myStmt.setString(2, "Johnson");
myStmt.setString(3, "Male");
myStmt.setString(4, "K");
myStmt.setString(5, "N");
myStmt.setInt(6, 1);
myStmt.setInt(7, 3);
myStmt.setInt(8, 5);
myStmt.setInt(9, 2);
myStmt.addBatch();
int[] result = myStmt.executeBatch();
System.out.println(result + " were added to the database.");
}
}
import java.sql.*;
public class Connection extends Alter {
{
try {
Class.forName("com.mysql.cj.jdbc.Driver").getDeclaredConstructor().newInstance();
}
catch (Exception ex) {
}
try {
batchInsertRecordsIntoTable();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
final static void batchInsertRecordsIntoTable() throws SQLException {
{
try {
DriverManager.getConnection(
"jdbc:mysql://localhost:3306/school?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC",
"root", "");
System.out.println("Connection Successful");
}
catch (SQLException ex) {
ex.printStackTrace();
}
}
}
public Statement createStatement() {
return null;
}
public static PreparedStatement prepareStatement(String query) {
return null;
}
}
A: Your method prepareStatement returns null.Thats why you get a NPE when calling myStmt.setString(1, "Chris")
you have to store the return value of DriverManager.getConnection( in a private property and return the result of prepareStatement
public static PreparedStatement prepareStatement(String query) {
return myConnection.prepareStatement(query);
}
Never use catch (Exception ex) { } atleast log exception
|
Q: Best way to handle multiple conditions for conditional compilation I have a template class that has a method where the template parameters dictate the inputs and outputs of that method like so:
template <typename In, typename Out>
class Foo
{
Out fn(const In& in)
{
Out out;
return out;
}
}
So I tried this, but then (probably obvious) errors arise when trying to use void for either In or Out. So I tried to add multiple methods that are variations on this theme hoping that their substitutions would enable the relevant functions and disable the invalid ones:
template <std::enable_if_t<std::is_void<InputType>::value>* = nullptr>
OutputType fn()
{
OutputType out;
return out;
}
template <std::enable_if<(!std::is_void<OutputType>::value) && (!std::is_void<InputType>::value)>* = nullptr>
OutputType fn(InputType& t)
{
OutputType out;
return out;
}
template <std::enable_if<std::is_void<OutputType>::value>* = nullptr>
void fn(InputType& t)
{}
Which lands me back in "invalid reference to void" territory, or with colliding signatures.
How should I go about gracefully handling these conditions so that only one of the following signatures was created from the template:
/*In == void && Out != void*/
Out fn(/* no input here to keep compiler happy*/) { return Out; }
/*In != void && Out != void, standard case*/
Out fn(const In& in) { return Out; }
/*In != void && Out == void*/
void fn(const In& in) { /* No returns here to keep compiler happy*/; }
A: You can use partial specialisation to provide implementations of Foo for when either of In and Out are void, and explicit specialisation for when both are void.
The syntax is as follows (note the angle brackets after Foo denoting this is a specialisation of the primary Foo class template)
template<typename Out>
struct Foo<void, Out> // specialisation for only In = void
{ ... };
template<typename In>
struct Foo<In, void> // specialisation for only Out = void
{ ... };
template<>
struct Foo<void, void> // specialisation for both In and Out = void
{ ... };
Here is an example:
#include <iostream>
// primary class template
template <typename In, typename Out>
struct Foo {
Out fn(const In& in) { return Out{}; }
};
// partial specialisation for when In=void
template<typename Out>
struct Foo<void, Out> {
Out fn() { return Out{}; }
};
// partial specialisation for when Out=void
template<typename In>
struct Foo<In, void> {
void fn(const In& in) { }
};
// explicit specialisation for when both In=void and Out=void
template<>
struct Foo<void, void> {
void fn() { }
};
int main() {
Foo<int, double> f;
f.fn(5);
Foo<void, void> g;
g.fn();
Foo<void, int> h;
h.fn();
Foo<int, void> i;
i.fn(5);
return 0;
}
A: The return value and the input value are different problem and you can solve they independently.
First of all, I suggest you to switch the order of the template types: first Out, next In.
This is because if you transform In in a variadic list of input types
template <typename Out, typename ... Ins>
struct Foo { /* ... */ };
you automatically solve the void input type (you simply don't express it).
Not a great solution because can be difficult to use the input value; just to show you how to create a struct/method that works in all cases.
For the return void type, you can simply do
return (Out)someVal;
where someVal is of type Out, when Out isn't void, and of another type (by example: int) if Out is void.
So if you define a type traits deVoid as follows
template <typename T>
struct deVoid
{ using type = T; };
template <>
struct deVoid<void>
{ using type = int; }; // a fake not-void type
template <typename T>
using deVoid_t = typename deVoid<T>::type;
you can define the out variable as follows
deVoid_t<Out> out {};
and return this way
return (Out)out;
that works also when Out is void.
So you can write Foo as follows
template <typename Out, typename ... Ins>
struct Foo
{
Out fn (Ins const & ... ins)
{
deVoid_t<Out> out {};
return (Out)out;
}
};
that works with zero input types (ex void input type) and with a void return type.
The following is a full working example
template <typename T>
struct deVoid
{ using type = T; };
template <>
struct deVoid<void>
{ using type = int; }; // a fake not-void type
template <typename T>
using deVoid_t = typename deVoid<T>::type;
template <typename Out, typename ... Ins>
struct Foo
{
Out fn (Ins const & ... ins)
{
deVoid_t<Out> out {};
return (Out)out;
}
};
int main ()
{
Foo<int, int> f; f.fn(42);
Foo<void> g; g.fn();
Foo<int> h; h.fn();
Foo<void, int> i; i.fn(42);
Foo<void, int, long> j; j.fn(42, 84L);
}
|
Q: Access bash associate array via variable indirection I wish to access an associative array using a variable. The example in the accepted answer to this post is exactly what I want:
$ declare -A FIRST=( [hello]=world [foo]=bar )
$ alias=FIRST
$ echo "${!alias[foo]}"
however this does not work for me when using bash 4.3.48 or bash 3.2.57.
It does however work if I don't declare ("declare -A") the array i.e. this works:
$ FIRST[hello]=world
$ FIRST[foo]=bar
$ alias=FIRST
$ echo "${!alias[foo]}"
Is there any problem with not declaring the array?
A: It works just as expected, you just missed out defining one more level of indirection to access the value,
declare -A first=()
first[hello]=world
first[foo]=bar
alias=first
echo "${!alias[foo]}"
The above result would obviously be empty as the other answer points out as there is no reference created yet to the array key. Now define an item to introduce a second level of indirect reference to point out to the actual key value.
item=${alias}[foo]
echo "${!item}"
foo
Now point item to the next key hello
item=${alias}[hello]
echo "${!item}"
world
Or a more detailed example would be, to run a loop over the keys of the associative array
# Loop over the keys of the array, 'item' would contain 'hello', 'foo'
for item in "${!first[@]}"; do
# Create a second-level indirect reference to point to the key value
# "$item" contains the key name
iref=${alias}["$item"]
# Access the value from the reference created
echo "${!iref}"
done
|
Q: выгрузка фото на onedrive такой вопрос: Есть скрипт(не мой), который должен выгружать фото на onedrive, значение scope пустое и скрипт не работает. Что может быть не так?
import requests
import json
import urllib
import os
#from getpass import getpass
import time
from datetime import datetime
URL = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"
client_id = "ТУТ КЛИЕНТ ID, я его убрал"
permissions = ["offline_access", "files.readwrite", "User.Read"]
response_type = "code"
redirect_uri = "http://localhost:8080/"
scope = ""
for items in range(len(permissions)):
scope = scope + permissions[items]
if items < len(permissions) - 1:
scope = scope + "+"
print("Click over this link " + URL + "?client_id=" + client_id + "&scope=" + scope + "&response_type=" + response_type + "&redirect_uri=" + urllib.parse.quote(redirect_uri))
print("Sign in to your account, copy the whole redirected URL.")
code = input("Paste the URL here :")
code = code[(code.find("?code") + len("?code") + 1) :]
URL = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
response = requests.post(URL + "?client_id=" + client_id + "&scope=" + scope + "&grant_type=authorization_code" + "&redirect_uri=" + urllib.parse.quote(redirect_uri) + "&code=" + code)
data = {
"client_id": client_id,
"scope": permissions,
"code": code,
"redirect_uri": redirect_uri,
"grant_type": 'authorization_code',
"client_secret": ''
}
response = requests.post(URL, data=data)
print(response.text)
token = json.loads(response.text)["access_token"]
refresh_token = json.loads(response.text)["refresh_token"]
def get_refresh_token():
data = {
"client_id": client_id,
"scope": permissions,
"refresh_token": refresh_token,
"redirect_uri": redirect_uri,
"grant_type": "",
"client_secret": "",
}
response = requests.post(URL, data=data)
token = json.loads(response.text)["access_token"]
refresh_token = json.loads(response.text)["refresh_token"]
last_updated = time.mktime(datetime.today().timetuple())
return token, refresh_token, last_updated
token, refresh_token, last_updated = get_refresh_token()
url = 'https://graph.microsoft.com/v1.0/'
HEADERS = {'Authorization': 'Bearer ' + token}
content = open("pidor.png", "rb")
response = json.loads(requests.put(url, headers=HEADERS, data=content).text)
print("Файл загружен!")
|
Q: How to create a grid like ui in android? I would like to implement the following ui
The screen will divide into 8 parts which is equal size, each of them contain a imageview
I would perfer not to use grid view as it is not a gallery . Thanks for helping
I tried the following code , but left and right column are not equals
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/share_bg">
<LinearLayout
android:id="@+id/s_leftColumn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_toLeftOf="@+id/s_rightColumn"
android:orientation="vertical" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="@drawable/title" />
<ImageView
android:id="@+id/s_sixMates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="@drawable/leaderboard_a" />
<ImageView
android:id="@+id/s_player"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="@drawable/leaderboard_b" />
<ImageView
android:id="@+id/s_party"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="@drawable/leaderboard_c" />
</LinearLayout>
<LinearLayout
android:id="@+id/s_rightColumn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:orientation="vertical" >
<ImageView
android:id="@+id/s_food"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="@drawable/leaderboard_d" />
<ImageView
android:id="@+id/s_dress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="@drawable/leaderboard_e" />
<ImageView
android:id="@+id/s_attendant"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="@drawable/leaderboard_f" />
<ImageView
android:id="@+id/s_ball"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="@drawable/leaderboard_g" />
</LinearLayout>
</RelativeLayout>
!!!!!!!!!!!!!!Update:!!!!!!!!!!!!!!!!!!!!!!
After I implement gridview , the images size is too large and out of screen , how to fix that? thanks
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/share_bg"
android:columnCount="2"
android:orientation="vertical"
android:rowCount="4" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/title" />
<ImageView
android:id="@+id/s_sixMates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/leaderboard_a" />
<ImageView
android:id="@+id/s_player"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/leaderboard_b" />
<ImageView
android:id="@+id/s_party"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/leaderboard_c" />
<ImageView
android:id="@+id/s_food"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/leaderboard_d" />
<ImageView
android:id="@+id/s_dress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/leaderboard_e" />
<ImageView
android:id="@+id/s_attendant"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/leaderboard_f" />
<ImageView
android:id="@+id/s_ball"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/leaderboard_g" />
</GridLayout>
Updated: with using Ankit solution . Unfortunately the left right is not equal , please refer to the screenshot
A: Use this code for your reference and replaced with your drawable. Its working fine for me :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="2" >
<LinearLayout
android:id="@+id/s_leftColumn"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:src="@drawable/ic_launcher" />
<ImageView
android:id="@+id/s_sixMates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:src="@drawable/ic_launcher" />
<ImageView
android:id="@+id/s_player"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:src="@drawable/ic_launcher" />
<ImageView
android:id="@+id/s_party"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:src="@drawable/ic_launcher" />
</LinearLayout>
<LinearLayout
android:id="@+id/s_rightColumn"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical" >
<ImageView
android:id="@+id/s_food"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:src="@drawable/ic_launcher" />
<ImageView
android:id="@+id/s_dress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:src="@drawable/ic_launcher" />
<ImageView
android:id="@+id/s_attendant"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:src="@drawable/ic_launcher" />
<ImageView
android:id="@+id/s_ball"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:src="@drawable/ic_launcher" />
</LinearLayout>
</LinearLayout>
|
Q: Is there a way to do fine grained access control in ASPNET 5 MVC 6 The new authorize attribute in ASPNET 5 seems to cover simple apps with course access control fine. But how would one go about using it with 10+ controllers with CRUD operations?
Is it correct to add policies for all calls, since there is no way to pass required claims to the policies?
It seems this list would be impossible to manage and clutter the ConfigureService method.
A: You can write policies which require claims and their values;
services.AddAuthorization(options =>
{
options.AddPolicy("RequireRead",
policy => policy.RequireClaim("DocumentPermission", "Read"));
}
It depends how you model your claim values. If you have a claim value of, for example, "CRUD" to indicate a user has create, read, update and delete for that particular claim then you're going to have to write your own requirement and handler.
|
Q: Fish equivalent to for loop with evaluation How would you write the equivalent script in fish
#!/bin/bash
for i in `ls`
do
echo $i
done
Thank you
A: fish uses ( parens ) rather than backticks for capturing shell output:
for i in (ls)
echo $i
end
|
Q: How can I send the key ENTER to the page setup dialog in IE7 I have the following code that changes the page orientation. it works in IE6 but not in IE7. it gets as far as %a and does not send the enter or tab keys so that i can hit 'OK'
var shell;
function SetPrintProperties() {
shell = new ActiveXObject("WScript.Shell");
shell.SendKeys("%fu"); // %=alt f= file u= page setup
window.setTimeout("javascript:SetPaperSize();", 1500);
}
function SetPaperSize() {
shell.sendKeys("%a{ENTER}");
}
A: Try to run this
shell.SendKeys("%~");
From here
|
Q: Keyboard hooks in C#: Side-effects I have seen a number of questions on this topic on SO and elsewhere, but I've now taken it a step further and am facing some weird behavior.
My application (an Excel add-in) installs a keyboard hook to monitor for ENTER key to perform some actions. The hook appears to works, as it executes the procedure I have wired with it when user presses ENTER. However, I see 2 strange behaviors:
*
*The NumLock status turns off automatically after my hooked procedure has executed.
*A library that my add-in is using throws SEHException (with message "External component threw an exception"). If I do not install the hook, the library works fine.
So I'm wondering if there's something wrong with the hook itself. I have downloaded it from a CodeProject article, but looking at some other implementations, most of these have the same basic code.
|
Q: What is the order in which the bootup tasks are run? I have a Debian 10 server and I'm running a systemctl service on it. I am using systemctl enable myservice to run it at startup. Also, I have a few lines of bash script, which help set up networking/port forwarding etc. for the service. I want that bash script run at startup. I'll be using this answer to run it at startup. My question is, what is the order the things will be executed in? Will the bash script run first or the systemctl service? I have to make sure that the bash script runs first and then the service. Is it so by default? If not, how do I achieve that?
A: There is no order. In general, always assume that everything may happen in parallel and that there is no guaranteed order until you request one. (Although systemd has several bootup stages, both things you mentioned happen within the same stage.)
The rc.local script itself is run as a normal service. It requests to be run "after networking", but other than that, doesn't try to be placed in any specific position – so it will run parallel to other normal services.
Also, avoid rc.local. It always ends up being a dumping ground for bunch of different tasks that often have contradictory ordering requirements. Create separate services for all tasks that don't have a generic service yet. (You don't need a new service for /proc/sys – systemd-sysctl can handle that. You don't need a new service for iptables – iptables-persistent can handle that.)
The answer you found was written in 2010 and the Debian boot process has changed quite a bit since then. What made sense with the mostly-linear LSB/sysv init may no longer make sense with systemd, and vice versa.
So there are two ways to ensure that your script runs before your (existing) service:
Separate services
Whenever you create new a service, you can use Before= or After= to explicitly ask for it to be sorted before or after something else, whenever both things are queued at once:
[Unit]
Description=Custom port forwarding configuration
Before=myservice.service
[Service]
Type=oneshot
ExecStart=/etc/enable-port-forwarding.sh
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
Part of an existing service
In case the task is 1) quick and 2) very specific to just one service, it can be run as an ExecStartPre= command within that service itself:
[Service]
...
ExecStartPre=/etc/enable-port-forwarding.sh
ExecStart=/usr/bin/myservice
...
|
Q: In GNOME-Wayland shell, How I map an touchscreen USB input to a specific video display output? I use Ubuntu 22.04 with GNOME-Wayland is default (It also happened on Ubuntu 20.x with GNOME-Wayland shell). Two touchscreens connect to system. I face a problem:
Two USB (touchscreen) touch inputs are always mapping to one touch monitor.
From X11, I can use "xinput map-to-output {device_id} {display_name}", and it works well.)
to map the touch USB input to a specific video display output, and it works well.
But xinput under Wayland cannot not detected for an touch USB devices, so cannot obtain an device ID to use in xinput command.
Anyone know how to map touch USB input to video output?
Please help.
Thank you so much.
|
Q: Finding the least double greater than in Java Is there a built-in method to find the next greatest double number in Java?
When writing a test, I sometimes want to verify that an operation succeeds for x but fails for values greater than x. One way to do this is to show that the operations fails for x + eps. But eps must be chosen taking into account the value of x to avoid problems like 180 + 1e-15 == 180.
To automatically select eps, I'd like to find the smallest representable number greater than x. I was surprised that I didn't find a standard library method, so I wrote the following:
public static double nextDouble(double d) {
if (d < 0) {
return -prevDouble(Math.abs(d));
} else {
return Double.longBitsToDouble(Double.doubleToLongBits(d) + 1);
}
}
public static double prevDouble(double d) {
if (d < 0) {
return -nextDouble(-d);
} else {
return Double.longBitsToDouble(Double.doubleToLongBits(d) - 1);
}
}
Should I use these custom functions, or is there a built-in approach available?
A: There is the Math.nextUp method.
Returns the floating-point value adjacent to d in the direction of positive infinity.
There are overloads to take double and float. There are also corresponding Math.nextDown methods.
|
Q: buildnumber-maven-plugin exposes SVN password plaintext After scanning the build logs for exposes passwords, I've noticed that buildnumber-maven-plugin (version 1.4) prints SVN passwords plaintext on [INFO]:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>buildnumber-maven-plugin</artifactId>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>create</goal>
</goals>
</execution>
</executions>
<configuration>
<doCheck>false</doCheck>
<doUpdate>true</doUpdate>
</configuration>
</plugin>
[INFO] --- buildnumber-maven-plugin:1.4:create (default) @ project ---
[INFO] Executing: /bin/sh -c cd '/home/build/tmp/project' && 'svn' '--username' 'svn-user' '--password''*****' '<svn-pass-plaintext>' '--no-auth-cache' '--non-interactive' 'update' '/home/build/tmp/project'
I've looked on https://www.mojohaus.org/buildnumber-maven-plugin/create-mojo.html for hints how to disable that 'feature' but found no clue.
How to disable printing passwords in logs without disabling [INFO] logging in maven? Or the plugin is broken and should not be used?
|
Q: Which OpenLayers.Protocol should I prefer which design patterns provided at? At our scenario, there is a server which stores the feature info (coordinates, properties, etc) into a SQL database. Google Maps are used for a layer. The geoJSON data format are used for communication between our server and web mapping client. We want to create/use a WCF (Windows Communication Foundation) service as a communication protocol. Should I implement OpenLayers.Protocol.WFS as a WCF protocol because OpenLayers supports HTTP or WFS as protocol? Or which OpenLayers.Protocol (HTTP or WFS) should I prefer which design patterns provided at?
Thanks a lot for your helps and clarifications,
Yasemin
A: Sorry, I never work with WCS, but I can clarify you a bit how to work with OL.
The OpenLayers.Protocol determines the way OL comunicates with the server, for example, using HTTP (OpenLayers.Protocol.HTTP) or using WFS (OpenLayers.Protocol.WFS).
The protocol class allows you to set a "format" property, which determines the way we can read/write from/to a specific data format, for example: OpenLayers.Format.KML, OpenLayers.Format.GeoJSON, etc.
You can create a OpenLayers.Protocol.HTTP instance by hand and set its format as OpenLayers.Format.GeoJSON.
At book OpenLayers Cookbook you have a recipe on "how to use protocols":
var geojsonReq = new OpenLayers.Protocol.HTTP({
url: "URL_TO_YOUR_GeoJSON_FILE",
format: new OpenLayers.Format.GeoJSON(),
callback: addFeaturesFromResponse // Some function to manage features
});
geojsonReq.read();
Cheers.
|
Q: REMOTE_ADDR not working I have a wierd problem. Whatever i do, the IP is the server's IP, not the client / the visitor. What to do?
if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARTDED_FOR'] != '') {
$ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip_address = $_SERVER['REMOTE_ADDR'];
}
return $ip_address;
}
A: You may need to switch to another server software (depending on what you're using now)
From the PHP docs:
$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here. That said, a large number of these variables are accounted for in the » CGI/1.1 specification, so you should be able to expect those.
REMOTE_ADDR is in the CGI/1.1 specification though so it's odd that whatever server you're using wouldn't be returning it.
A: If your server is on the same network as your server, behind a router with NAT, then you might see your private IP.
If you are behind a reverse proxy $_SERVER['REMOTE_ADDR']; will always be the IP of the proxy server.
A: Your webserver is not configured properly (once I've had this issue on buying alias domains at my webhost provider).
However if you're unable to fix this problem, I HIGLY recommend you to check if $_SERVER['HTTP_X_FORWARDED_FOR'] is valid IP address and then just assing it to $_SERVER['REMOTE_ADDR'] for simply usage, because It is easy to fake $_SERVER['HTTP_X_FORWARDED_FOR'] and to throw there your own values (I had this problem).
|
Q: cmake & Qt Creator's project tree: .ui-files missing I'm using a cmake-project with Qt Creator. Everything works and builds fine except Qt Creator does not show any .ui files in the project tree. If I want to edit a .ui file in the designer, I have to switch to the file system view and locate it manually.
Is there a way to tell Qt Creator / cmake to add the .ui-files to the project tree (or .cbp-file) as well?
A: QtCreator shows only files that are used as sources for some target. You can add your .ui files to some target to see them in the IDE, for example:
add_executable(some_target <sources> file1.ui file2.ui)
|
Q: How to change Panel Border Color In the properties of a Panel I have set the border style to Fixed Single.
When I am running my application it has the color gray. I don't know how to change the border color.
I have tried this in the Paint event handler of the panel:
private void HCp_Paint(object sender, PaintEventArgs e)
{
Panel p = sender as Panel;
ControlPaint.DrawBorder(e.Graphics, p.DisplayRectangle, Color.Yellow, ButtonBorderStyle.Inset);
}
This displays the border like this:
but I want a fixed single border like this:
How I make the border in yellow?
A: If you don't want to go to the trouble of sub-classing a panel, you can just create another panel 2 pixels bigger in each dimension, make it the border color and sit it directly behind the panel that needs a border.
This is just a few clicks in the IDE ...
A: I found this post useful
I also set the padding of the panel to the thickness of the border so that controls inside the panel don't overlap the border and hide it. In my case, I wasn't using the padding otherwise so it was a good solution, but things might get more tricky if you also plan on using the padding for more than just showing the border...
A: If you don't want to make a custom panel as suggested in @Sinatr's answer you can draw the border yourself:
private void panel1_Paint(object sender, PaintEventArgs e)
{
ControlPaint.DrawBorder(e.Graphics, this.panel1.ClientRectangle, Color.DarkBlue, ButtonBorderStyle.Solid);
}
A: You can create own Panel class and draw border in the client area:
[System.ComponentModel.DesignerCategory("Code")]
public class MyPanel : Panel
{
public MyPanel()
{
SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
}
protected override void OnPaint(PaintEventArgs e)
{
using (SolidBrush brush = new SolidBrush(BackColor))
e.Graphics.FillRectangle(brush, ClientRectangle);
e.Graphics.DrawRectangle(Pens.Yellow, 0, 0, ClientSize.Width - 1, ClientSize.Height - 1);
}
}
A: This also worked for me:
private void HCp_Paint(object sender, PaintEventArgs e)
{
Panel p = sender as Panel;
ControlPaint.DrawBorder(e.Graphics, p.DisplayRectangle, Color.Yellow, ButtonBorderStyle.Solid);
}
The problem of the border style is due to the ButtomBorderStyle option "Inset". By selecting "ButtonBorderStyle.Solid" you get a single line (also dotted, dashed... are available).
For many panels, I agree that the best solution is to create your own class that inherits from Panel and overwrite the Paint method...
A: After a workaround when creating my custom panel. I was forced to apply another tweak to solve the border overlapping when the size of the child control(s) > size of the panel.
In the tweak, instead of the panel drawing its border, its drawn by the parent control.
Public Class SharpPanel : Inherits Panel
Sub New()
Padding = New Padding(2)
SetStyle(ControlStyles.SupportsTransparentBackColor, True)
SetStyle(ControlStyles.ResizeRedraw, True)
SetStyle(ControlStyles.UserPaint, True)
SetStyle(ControlStyles.AllPaintingInWmPaint, True)
SetStyle(ControlStyles.ContainerControl, True)
SetStyle(ControlStyles.OptimizedDoubleBuffer, True)
SetStyle(ControlStyles.ContainerControl, True)
Width = 100
Height = 100
TabStop = False
End Sub
Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
MyBase.OnPaint(e)
Dim p As Control = Me.Parent
Dim gr As Graphics = p.CreateGraphics
Dim rec As Rectangle = Me.ClientRectangle
If Me.VerticalScroll.Visible Then
rec.Width = rec.Width + SystemInformation.VerticalScrollBarWidth
End If
If Me.HorizontalScroll.Visible Then
rec.Height = rec.Height + SystemInformation.HorizontalScrollBarHeight
End If
rec.Location = Me.Location
rec.Inflate(1, 1)
gr.DrawRectangle(New Pen(Color.Pink), rec)
End sub
End Class
|
Q: Biopython MMCIF2Dict return error when reading x,y,z coordinate I am trying to load atom coordinates of protein with PDB_ID 5itp using
mmcif_dict = MMCIF2Dict.MMCIF2Dict("5itp.cif")
for i in range(0,len(mmcif_dict["_atom_site.auth_atom_id"])):
print(mmcif_dict["_atom_site.Cartn_x"][i])
It returns an error: IndexError: string index out of range.
Same error pop up for protein 4y7l.
I look at the cif files for these two proteins and find there are two entries for Cartn_x. The first one appears before ATOM coordinates at
...
_atom_site.pdbx_PDB_ins_code
_atom_site.Cartn_x
_atom_site.Cartn_y
_atom_site.Cartn_z
_atom_site.occupancy
...
and the second one appears much later at
2 2 'Structure model' '_atom_site.Cartn_x'
3 2 'Structure model' '_atom_site.Cartn_y'
4 2 'Structure model' '_atom_site.Cartn_z'
If I delete the second one, MMCIF2Dict.MMCIF2Dict works properly. But the problem is it is not practical to modified every such cif files for reading atom coordinate. Does anyone have a solution for this issue ?
|
Q: What is causing Apache2 to display PHP as plain text in this config file? I am trying to run PHP and Rails in the same virtual host, however, PHP is being displayed as plain/text. When I create a test host without all the rewrites and proxy-ing, Apache2 will process the PHP as desired. Where in my config file have I gone wrong?
<VirtualHost *:80>
#ServerName staging.domain.com
#ServerAlias www.domain.com
DocumentRoot /home/demo/vhosts/domain/public
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /home/demo/vhosts/domain/public>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
RewriteEngine On
<Proxy balancer://thinservers>
BalancerMember http://127.0.0.1:5000
BalancerMember http://127.0.0.1:5001
BalancerMember http://127.0.0.1:5002
</Proxy>
# Redirect all non-static requests to thin
RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f
RewriteRule ^/(.*)$ balancer://thinservers%{REQUEST_URI} [P,QSA,L]
ProxyPass / balancer://thinservers/
ProxyPassReverse / balancer://thinservers/
ProxyPreserveHost on
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
# Custom log file locations
ErrorLog /home/demo/vhosts/domain/log/error.log
CustomLog /home/demo/vhosts/domain/log/access.log combined
</VirtualHost>
A: Check your httpd.conf file and make sure it is loading the php5 module or if you use mod_suphp, make sure youre not loading both.
<Directory "/var/www/myrailsapp/public/">
Options Indexes +ExecCGI FollowSymLinks
Order allow,deny
Allow from all
</Directory>
This is more of a http://www.serverfault.com question ...
|
Q: VSCode how to change size of explorer scrollbar? Using VSCode 1.58.2 on Ubuntu 20.04.2.
VSCode 1.58 allows Editor scroll bar customization which is great. However, this has no effect on the vertical scrollbar in the Explorer pane. Is there a setting to change the size of that scrollbar?
|
Q: iOS Storyboarding segue action changes orientation incorrectly Okay so I'm new to the whole storyboarding functionality in iOS 5. I have an application for iPad that is locked into landscape mode. Just to test out the seguing functionality, I took my initial view controller, added a button, dragged a new view controller next to it (which shows up in landscape mode visually on the designer), then tied the segue action to the button. I left everything defaulted.
Hitting the button on the initial view controller initiates the segue with no problems, and the new screen loads up, but ALWAYS in portrait mode.
What am I doing wrong? Is there some toggle I'm missing? I figured that if via the summary of the project, I have it locked into landscape left and right, it would assume I always want that orientation unless otherwise noted? Please help!
A: I had the same problem and managed it by adding a new own ViewControllerClass to the new scene.
Within the following auto created method, you can restrict the orientation to landscape only. This is also helpful for the Main Scene ViewController:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (UIInterfaceOrientationIsLandscape(interfaceOrientation));
}
Cheers,
Daniel
A:
I have an application for iPad that is locked into landscape mode.
How are you locking it app-wide? Just want to make sure you are doing it correctly.
To lock an orientation in Storyboard mode, select your ViewController and on the Attributes inspector change the Orientation from Inferred to whatever you want it to be locked to.
A: What have you put in the orientation delegate method?
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft);
}
A: In the properties file for your app (YOURAPPNAME-Info.plist), located in the "supporting files" group, there is an array called "Supported interface orientations". Remove both landscape values from the array and your app will be locked in portrait orientation.
|
Q: how to compute norm.ppf() in tensorflow/Keras? I want to use inverse of cumulative distribution function (cdf) which can be done using norm.ppf() from scipy https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.norm.html#scipy.stats.norm
inside a layer of a tf/keras model architecture.
A: As per documentation, tfp.distribution.Normal does have a method for calculating ppf (percent point function). It's called quantile:
scipy.stats.norm(loc=0, scale=1).ppf(0.95)
Output:
1.6448536269514722
Tensorflow:
tfp.distributions.Normal(loc=0, scale=1).quantile(0.95)
Output:
<tf.Tensor: shape=(), dtype=float32, numpy=1.6448536>
|
Q: Proof with symmetric matrix (Direct and Contraposition) $S$ is a symmetric matrix. If $Sx=\lambda x$ and $Sy = \mu y$, where $x$ and $y$ are non-zero vectors and $\lambda , \mu \in \mathbb{R}$. Prove the following:
(a) If $\mu \neq \lambda$, then $x^{t}y=0$. Prove by contraposition.
(b) $(S^4 + S^2 + S)$ has an eigenvalue $\lambda^4+\lambda^2+\lambda$. Give a direct proof.
Help on this would be much appreciated - I'm very new to proofs!
A: Part a
$$\begin{array}{rcl}
\lambda x^T y
&=& (x^T S^T) y \\
&=& (x^T S) y \\
&=& x^T (S y) \\
&=& x^T (\mu y) \\
\end{array}$$
Therefore $(\lambda-\mu)(x^T y) = 0$
Part b
$$\begin{array}{rcl}
S x &=& \lambda x \\
S^2 x &=& \lambda^2 x \\
S^3 x &=& \lambda^3 x \\
S^4 x &=& \lambda^4 x \\
S^4 x + S^2 x + S x &=& \lambda^4 x + \lambda^2 x + \lambda x \\
(S^4 + S^2 + S) x &=& (\lambda^4 + \lambda^2 + \lambda) x \\
\end{array}$$
|
Q: Rails.cache.read in sidekiq process In my Ruby on Rails application I have model that looks like this:
class Schema < ActiveRecord::Base
has_many :schema_items
def self.from_cache(schema_id)
schema = Rails.cache.read("schema_#{schema_id}")
unless schema
schema = Schema.where(id: schema_id).includes(:schema_items).first
Rails.cache.write("schema_#{schema_id}", schema) if schema
end
schema
end
end
I'm using this class method in other class which is called by Sidekiq worker. From time to time it returns the following error:
NotImplementedError
Using google I found this issue in redis_store gem: https://github.com/redis-store/redis-store/issues/74
But they fix this bug. My app is hosted on Heroku and I'm using the RedisCloud. Any ideas how can I solve this?
EDIT:
Here is the full backtrace:
NotImplementedError: NotImplementedError
from celluloid/tasks/task_fiber.rb:15:in `block in create'
from celluloid/tasks.rb:57:in `block in initialize'
from celluloid/actor.rb:357:in `block in task'
from celluloid/cell.rb:71:in `block in task'
from celluloid/cell.rb:60:in `block in invoke'
from celluloid/calls.rb:122:in `dispatch'
from celluloid/calls.rb:26:in `dispatch'
from celluloid/calls.rb:26:in `public_send'
from sidekiq/processor.rb:50:in `process'
from sidekiq/processor.rb:98:in `stats'
from sidekiq/processor.rb:51:in `block in process'
from sidekiq/middleware/chain.rb:132:in `invoke'
from sidekiq/middleware/chain.rb:132:in `call'
from sidekiq/middleware/chain.rb:129:in `block in invoke'
from sidekiq/middleware/server/logging.rb:11:in `call'
from sidekiq/logging.rb:30:in `with_context'
from sidekiq/middleware/server/logging.rb:15:in `block in call'
from sidekiq/middleware/chain.rb:129:in `block in invoke'
from sidekiq/failures/middleware.rb:9:in `call'
from sidekiq/middleware/chain.rb:129:in `block in invoke'
from sidekiq/middleware/server/retry_jobs.rb:74:in `call'
from sidekiq/middleware/chain.rb:129:in `block in invoke'
from sidekiq/middleware/server/active_record.rb:6:in `call'
from sidekiq/middleware/chain.rb:129:in `block in invoke'
from sidekiq/batch/middleware.rb:25:in `call'
from sidekiq/middleware/chain.rb:129:in `block in invoke'
from sidekiq_unique_jobs/middleware/server/unique_jobs.rb:16:in `call'
from sidekiq/middleware/chain.rb:129:in `block in invoke'
from sidetiq/middleware/history.rb:8:in `call'
from sidekiq/middleware/chain.rb:129:in `block in invoke'
from new_relic/agent/instrumentation/sidekiq.rb:29:in `call'
from new_relic/agent/instrumentation/controller_instrumentation.rb:352:in `perform_action_with_newrelic_trace'
from new_relic/agent/instrumentation/sidekiq.rb:33:in `block in call'
from sidekiq/middleware/chain.rb:127:in `block in invoke'
from sidekiq/processor.rb:52:in `block (2 levels) in process'
from sidekiq/processor.rb:75:in `execute_job'
from app/workers/response_processor_worker.rb:8:in `perform'
from app/services/import/response_processor.rb:28:in `process'
from app/models/import/importer/raw_response_validator.rb:17:in `validate'
from app/models/survey_schema.rb:51:in `from_cache'
from active_record/relation/finder_methods.rb:127:in `first'
from active_record/relation/finder_methods.rb:484:in `find_nth'
from active_record/relation/finder_methods.rb:500:in `find_nth_with_limit'
from active_record/relation.rb:243:in `to_a'
from active_record/relation.rb:514:in `load'
from active_record/relation.rb:643:in `exec_queries'
from active_record/relation.rb:643:in `each'
from active_record/relation.rb:644:in `block in exec_queries'
from active_record/associations/preloader.rb:102:in `preload'
from active_record/associations/preloader.rb:102:in `flat_map'
from active_record/associations/preloader.rb:102:in `each'
from active_record/associations/preloader.rb:103:in `block in preload'
from active_record/associations/preloader.rb:115:in `preloaders_on'
from active_record/associations/preloader.rb:143:in `preloaders_for_one'
from active_record/associations/preloader.rb:143:in `flat_map'
from active_record/associations/preloader.rb:143:in `each'
from active_record/associations/preloader.rb:144:in `block in preloaders_for_one'
from active_record/associations/preloader.rb:144:in `map'
from active_record/associations/preloader.rb:144:in `each'
from active_record/associations/preloader.rb:146:in `block (2 levels) in preloaders_for_one'
from active_record/associations/preloader/association.rb:20:in `run'
from active_record/associations/preloader/collection_association.rb:13:in `preload'
from active_record/associations/preloader/association.rb:78:in `associated_records_by_owner'
from active_record/associations/preloader/association.rb:60:in `owners_by_key'
from active_record/associations/preloader/association.rb:103:in `key_conversion_required?'
from active_record/associations/preloader/association.rb:107:in `association_key_type'
from active_record/associations/preloader/association.rb:45:in `association_key_name'
and my worker looks like this:
class ResponseCreatorWorker
include Sidekiq::Worker
sidekiq_options queue: :response_processing
def perform(schema_id)
# some not important code
schema = Schema.from_cache(schema_id) # this line throws the error
Response.create(schema: schema)
end
end
A: A couple options without being able to go into the Pro code:
Error you found is redis-store related, try memcached
Try moving the cache to memcached, it should be a simple and non-disruptive action, cost-free on simple plans, and see if the problem goes away, or changes, could be useful for hunting the core bug down
memcache is a better caching service anyway for simple key-value stuff,
The worker you linked is not a part of the stack trace
You showed the ResponseCreatorWorker, but that does not appear in the stack trace. What appears is ResponseProcessorWorker, maybe link that worker instead?
Are you sure you are running the code you are running?
Mike Perham says that the Sidekiq backtrace doesn't match the version you have given him, and the wrong worker is in the stack trace? Are you really sure the server is updating? Review the deployment log and log in to the worker with heroku run bash and inspect a couple of key files, make sure nothing is off with the platform.
Can you rescue it? :D
It should be pretty safe to put in a rescue that catches NotImplementedError, tries once again, and logs a record of it into the logs. Update gems when appropriate and when warnings disappear open a whiskey and celebrate.
Put something like this in your model:
def wrap_me_scotty
yield
rescue NotImplementedError => e
warn "#{e} :-("
yield # try once more, let it explode if no joy
end
and then wrap Rails.cache calls
def self.from_cache(schema_id)
schema = wrap_me_scotty{ Rails.cache.read("schema_#{schema_id}") }
unless schema
schema = Schema.where(id: schema_id).includes(:schema_items).first
wrap_me_scotty{ Rails.cache.write("schema_#{schema_id}", schema) } if schema
end
schema
end
|
Q: Make my internal employees app updated all the time automatically Im having issues getting my users to install updates of my app.
I need to say that my users are internal company employees, our app is for us internally and we need them to have the latest app always.
*
*Is there a way to launch Android InAppUpdates (https://developer.android.com/guide/playcore/in-app-updates) from the background so I show them all the time "UPDATE ME".
*Is there a way through G-Suite admin to force this? I can force them to have it installed, but not to be updated all the time.
|
Q: access variable from inner function var urihost;
var result = page.evaluate(function () {
............
"set urihost value from here"
............
});
How can I access urihost from the inner functions, Making it global does not work either
Fiddle: http://jsfiddle.net/KGLzj/
A: It should work just fine but I see that you have something that looks like a callback function. It is possible that urihost does not yet have a value after assigning result - because the callback function hasn't been called, and urihost hasn't been assigned a value.
Can you post more of the code?
A: I might be misunderstanding your question...
But your code should work the way it is, see this fiddle
// Setup page object:
var page = {
evaluate: function(func) {
// Don't forget to call the function...
func();
}
};
// The variable you want to change:
var urihost = 1;
// Execute now...
var result = page.evaluate(function () {
urihost = 2;
});
// The alerted result will be 2
alert(urihost);
|
Q: MATLAB Compiler getting stuck during build process I built a GUI in MATLAB that makes use of the Instrument Control Toolbox, among other things. I tried to compile this GUI with deploytool but it's getting stuck during the compile:
ant:
<mkdir dir="Z:\My Path\MyApp\distrib" />
<mkdir dir="Z:\My Path\MyApp\src" />
mcc -o MyApp -W WinMain:MyApp -T link:exe -d 'Z:\My Path\MyApp\src' -N -p instrument -w enable:specified_file_mismatch -w enable:repeated_file -w enable:switch_ignored -w enable:missing_lib_sentinel -w enable:demo_license -v 'Z:\My Path\MyApp.m'
Compiler version: 4.18.1 (R2013a)
Processing C:\Program Files\MATLAB\R2013a\toolbox\matlab\mcc.enc
Processing C:\Program Files\MATLAB\R2013a\toolbox\instrument\mcc.enc
Processing C:\Program Files\MATLAB\R2013a\toolbox\shared\instrument\mcc.enc
Processing include files...
2 item(s) added.
Processing directories installed with MCR...
The file Z:\My Path\MyApp\src\mccExcludedFiles.log contains a list of functions excluded from the CTF archive.
0 item(s) added.
Generating MATLAB path for the compiled application...
Created 54 path items.
And that's all she wrote. Of note, the final statement of "Created 54 path items" to me doesn't make a whole lot of sense, since I don't have 54 dependencies.
I changed the path that the code is on to Z:\My Path\MyApp to be generic. It may or may not be important but there are spaces in the path. I mentioned this because maybe that's my problem. Z:\ is a network drive instead of a local drive. Some dependencies live on R:\, which is also a network drive. All dependencies are on the MATLAB path or in my local folder.
I'm using MATLAB R2013a x64 and the Windows SDK 7.1 (used mbuild -setup to set this).
The deploytool and MATLAB are both responsive - I can cancel the build process with no problem. I ran the mcc code verbatim as above and it's still stuck in the same place with no indication that it's working. Hitting CTRL-C to interrupt it gives no error messages or anything.
Does anyone know what's going on? It must be something to do with the mcc call, I'm sure of it.
A: It looks like this problem is due to my license file being located on a network server rather than locally. Working with MathWorks tech support really helped out here.
When using mcc, specify a local license file with the -Y flag. The compile then goes from 20 minutes or so to about 2. An example call:
mcc -m -v -N -Y alpha.lic myApp.m
|
Q: Unable to rotate image in windows store app I'm attempting to take a photo with my device camera, but images taken with the device held in "portrait" mode come out sideways. I'd like to rotate them before saving them, but the solution that I keep coming across isn't working for me.
Windows.Storage.Streams.InMemoryRandomAccessStream stream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
imagePreview.Source = null;
await stream.WriteAsync(currentImage.AsBuffer());
stream.Seek(0);
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(stream, decoder);
encoder.BitmapTransform.Rotation = BitmapRotation.Clockwise90Degrees;
encoder.IsThumbnailGenerated = false;
await encoder.FlushAsync();
//save the image
StorageFolder folder = KnownFolders.SavedPictures;
StorageFile capturefile = await folder.CreateFileAsync("photo_" + DateTime.Now.Ticks.ToString() + ".bmp", CreationCollisionOption.ReplaceExisting);
string captureFileName = capturefile.Name;
//store stream in file
using (var fileStream = await capturefile.OpenStreamForWriteAsync())
{
try
{
//because of using statement stream will be closed automatically after copying finished
await Windows.Storage.Streams.RandomAccessStream.CopyAsync(stream, fileStream.AsOutputStream());
}
catch
{
}
}
this produces the original image with no rotation applied to it. I've looked at a lot of samples, and can't figure out what I'm doing wrong.
|
Q: How can I get duplicated values from ArrayList? There is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class CompareFile {
CompareFile() {}
boolean check = false;
int count = 0;
/*
* this method return a File type variable
* variable path - this parameter takes a path in specified root
* also it's a private method and he should be called with help by class object
*/
public File find(File path) throws FileNotFoundException {
PrintWriter writer = new PrintWriter("D:/Photos/name.txt");
ArrayList<String> buffer = new ArrayList<String>();
/*
* let's create array of files
* where must be all found files
* We use File[], and named 'files'
* variable files takes on list of found files
* with help by listFiles method, that
* return list of files and directories
*/
File[] files = path.listFiles();
//System.out.println(files.toString());
try {
/*
* we'll ought use the for each loop
* in this loop we'll create File type variable 'file'
* then we'll do iterating for each expression from variable files
*/
for (File file : files) {
//print all found files and directories
//if file or directory exists
if (file.isDirectory()) {
//recursively return file and directory
find(file);
}
else {
buffer.add(file.getName());
System.out.println(file);
}
}
}
catch (Exception e) {
System.out.print("Error");
}
finally{
if ( writer != null )
writer.close();
}
/*
Iterator<String> i = buffer.iterator();
while(i.hasNext()) {
System.out.println(i.next());
}*/
return path;
}
public static void main(String[] args) throws FileNotFoundException {
File mainFile = new File("D:/Photos/");
CompareFile main = new CompareFile();
main.find(mainFile);
}
}
If I use sort, after sorting, the result bad, because first row from dir "Photos",
and second row from directory in directory "Photos/sub" Let's look at
the screen: I think you understand)
http://s10.postimg.org/7hcw83z9x/image.png
A: You'll need to keep track of where you are in the tree, change the find method to take a path:
public File find(File path, string path="") throws FileNotFoundException
When you call the find method recursively:
find(file, path + file.getName() + "/")
Then when you add to the list, use
buffer.add(path + file.getName());
|
Q: How would I programmatically send the same request to different methods in Dropwizard and Jersey? Right now, I have some endpoints in a resource. These endpoints access some data and return it:
@Path("/v1/event")
@Produces({MediaType.APPLICATION_JSON})
public class EventResource {
private final DataStore dataStore;
// constructor stuff
@Timed
@GET
@Path("/all/total")
public String getAll(@Bind({Bind.Params.QUERY}) Params params) throws Exception {
return dataStore.getEventTotals(params);
}
}
We completely revamped how our data is stored so now I have a resource that accesses this new data store:
@Path("/v2/event")
@Produces({MediaType.APPLICATION_JSON})
public class NewEventResource {
private final NewDataStore newDataStore;
// constructor stuff
@Timed
@GET
@Path("/all/total")
public MyDataPojo getAll(@Bind({Bind.Params.QUERY}) Params params) throws Exception {
return newDataStore.getEventTotals(params);
}
}
What I would like to do now is somehow have the v1 endpoint use both these resources. Some object would decide which getAll method to use based on some parameters in the Params object that is passed in.
The reason is we have some customers that have data in the old data store, and other customers have data in the new data store. We also have a bunch of other projects that are using our endpoints. It's not feasible or realistic to go change all the other projects to use the v2 endpoint instead of the v1 endpoint.
A couple thoughts. I could do something like this:
@Path("/v1/event")
@Produces({MediaType.APPLICATION_JSON})
public class EventResource {
private final DataStore dataStore;
private final NewDataStore newDataStore;
// constructor stuff
@Timed
@GET
@Path("/all/total")
public String getAllEndpoint(@Bind({Bind.Params.QUERY}) Params params) throws Exception {
if (customerInNewDataStore(params.getCustomer())) {
return getEventTotalsNew(params);
} else {
return getEventTotalsOld(params);
}
}
private MyDataPojo getEventTotalsNew(Params params) throws Exception {
return newDataStore.getEventTotals(params);
}
private String getEventTotalsOld(Params params) throws Exception {
return dataStore.getEventTotals(params);
}
}
The problem with this is that getEvenTotalsNew and getEventTotalsOld return different types. How would I be able to merge this? Also, doing this would be sort of a pain to do for every endpoint as there are quite a few endpoints in our codebase.
I've been reading about filters and intercepters in Jersey: https://jersey.java.net/documentation/latest/filters-and-interceptors.html.
Would a ContainerRequestFilter be able to accomplish what I want to do? Would I be able to access my Params params object in the filter?
Any other better ways to do this? I'm open to all ideas.
Thanks!
A: I think I might have what you are looking for. You can use a pre-matching filter to modify the request.
This is based on your example stating that you have a v1 and v2 API, both of which are equal (apart from the versioning). I am using a custom header for routing.
Consider these two resources:
@Path("v1")
@Produces(MediaType.APPLICATION_JSON)
public class TestResource1 {
@GET
@Path("test")
public String get() {
return "Hello v1";
}
}
@Path("v2")
@Produces(MediaType.APPLICATION_JSON)
public class TestResource2 {
@GET
@Path("test")
public MyResultObj get() {
MyResultObj o = new MyResultObj();
o.name = "pandaa";
o.message = "Hello V2";
return o;
}
public static class MyResultObj {
@JsonProperty
String name;
@JsonProperty
String message;
}
}
These are both equal with the exception for the version type in the context and the return type. Note, the return type does not matter in this case. What ends up in the response is a json string regardless. In your case, you could also do something like:
Response.ok(myResultObject).build();
At that point all of your return types would just be Response.
Anyhow, Version 1 prints something, and version 2 returns an object.
The pre-matching (important, otherwise you can not change the URI) filter will look like this:
@PreMatching
public class RoutingFilter implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
String headerString = requestContext.getHeaderString("IS_V2");
boolean v2 = headerString != null && headerString.equals("yes");
URI absolutePath = requestContext.getUriInfo().getAbsolutePath();
if(v2) {
URI v2Redirect = URI.create(absolutePath.toString().replace("v1", "v2"));
requestContext.setRequestUri(v2Redirect);
}
}
}
It simply evaluates the header and replaces the version in the URI. There is probably a better way to do this, but then again this is just an example of how to approach this.
Finally, the test:
artur@pandaadb:~/dev/vpn$ curl "localhost:9085/api/v1/test" --header "IS_V2: yes"
{"name":"pandaa","message":"Hello V2"}
artur@pandaadb:~/dev/vpn$ curl "localhost:9085/api/v1/test" --header "IS_V2: no"
Hello v1
Note how both are doing a request for V1. The first request though gets rerouted internally to v2.
You can write a more generic version (since you might need to be backwards compatible e.g. v1 -> v2 and v2 -> v1) so that it doesn't matter if people call v1 or v2.
Finally - I am not at all sure if this is a good solution :) Personally I would probably write a delegate as seen in your example.
I hope that helps!
Edit: finally - you should be able to use your params object. However this may result in you consuming the requests's input stream. I believe this can only be done once, so you may need to set a new stream after reading it as well.
Artur
|