id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23536300
|
Experience = soup.find_all(id='background-experience-container')
Exp = {}
for element in Experience:
Exp['Experience'] = {}
for element in Experience:
role = element.find(href=re.compile("title").get_text()
Exp['Experience']["Role"] = role
for element in Experience:
company = element.find(href=re.compile("exp-company-name").get_text()
Exp['Experience']['Company'] = company
It doesn't like the syntax for how I've defined the Exp['outer_key']['inner_key'] = value it is returning SyntaxError.
I'm trying to buld a Dict.dict which contains info on role and company, will also look to include dates for each but haven't got that far yet.
Can anyone spot any glaringly obvious mistakes in my code?
Really appreciate any help with this!
A: find_all can return many values (even if you search by id) so better use list to keep all values - Exp = [].
Experience = soup.find_all(id='background-experience-container')
# create empty list
Exp = []
for element in Experience:
# create empty dictionary
dic = {}
# add elements to dictionary
dic['Role'] = element.find(href=re.compile("title")).get_text()
dic['Company'] = element.find(href=re.compile("exp-company-name")).get_text()
# add dictionary to list
Exp.append(dic)
# display
print(Exp[0]['Role'])
print(Exp[0]['Company'])
print(Exp[1]['Role'])
print(Exp[1]['Company'])
# or
for x in Exp:
print(x['Role'])
print(x['Company'])
if you sure that find_all gives you only one element (and you need key 'Experience') then you can do
Experience = soup.find_all(id='background-experience-container')
# create main dictionary
Exp = {}
for element in Experience:
# create empty dictionary
dic = {}
# add elements to dictionary
dic['Role'] = element.find(href=re.compile("title")).get_text()
dic['Company'] = element.find(href=re.compile("exp-company-name")).get_text()
# add dictionary to main dictionary
Exp['Experience'] = dic
# display
print(Exp['Experience']['Role'])
print(Exp['Experience']['Company'])
or
Experience = soup.find_all(id='background-experience-container')
# create main dictionary
Exp = {}
for element in Experience:
Exp['Experience'] = {
'Role': element.find(href=re.compile("title")).get_text()
'Company': element.find(href=re.compile("exp-company-name")).get_text()
}
# display
print(Exp['Experience']['Role'])
print(Exp['Experience']['Company'])
| |
doc_23536301
|
My project configuration :
ASP.Net core 2.0,
Vs2017 Preview2,
c#
i have installed Microsoft.SqlServer.Scripting using nuget package , then i tried to restore data base using below code
try
{
string DatabaseName = "TestDB";
String ConnectionString = "Data Source=(local);Initial Catalog= " + DatabaseName + ";Integrated Security=SSPI;";
SqlConnection sqlConnection = new SqlConnection(ConnectionString);
// Error on the line below
Microsoft.SqlServer.Management.Common.ServerConnection conn = new Microsoft.SqlServer.Management.Common.ServerConnection(sqlConnection);
Server srv = new Server(conn);
Console.WriteLine(srv.Information.Version);
}
catch (Exception ex)
{
string exepe = ex.Message.ToString();
}
Error is :
Could not load type 'Microsoft.SqlServer.Server.SqlContext' from
assembly 'System.Data, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089'.
Did i miss anything? can you please any body help me out this .
A: I had the same problem today. I solved it by referencing Microsoft.SqlServer.SqlManagementObjects.
| |
doc_23536302
|
My second question is when searching in certain columns I have dates in I need to find rows that fit the criteria of '21 days or closer to the current date'. How can I specify the script to look at the dates and copy and paste all rows that are no further out than 21 days from the current date?
Thanks in advance!
A: There are two ways to automate the manipulation of spreadsheet (Excel?) data: Both start with specifying your tasks in plain/natural language (e.g. 'copy all rows with ??-date 21 days greater/greater equal/smaller/smaller equal than the current date from sheet ?? (row/col?) to sheet ?? (row/col?)' and then
*
*use the macro recorder to get the VBA code to solve the task and 'port' it to VBScript
*translate the task decriptions to SQL statements and execute them on an ADO connection to the spreadsheet
Whether the first or the second way is better for you depends on your knowledge and skills.
A: Are you interested in creating a custom macro using VBS? Adding VB file under Development/Visual Basic, You can process rows and columns.
Sub CountX(pRowStart As Integer, pRowStop As Integer, pColStart As Integer, pColStop As Integer, pObjGrp As String)
Dim x As Integer
Dim xRow As Integer
Dim xCol As Integer
Dim wSht As Worksheet
x = 0
'**** create object reference to worksheet object.
Set wSht = Worksheets("Sheet1")
'**** set cell control values
xRow = 1
xCol = 3
Do While xRow < pRowStop + 1
Do While xCol < pColStop + 1
If UCase(ActiveSheet.Cells(xRow, xCol)) = "X" Then
x = x + 1
End If
xCol = xCol + 1
Loop
xCol = pColStart
xRow = xRow + 1
Loop
End Sub
You can also add this to your code to activate another sheet and set the value to row 1 column 3
Sheets(psSheetName).Activate
ActiveSheet.Cells(1, 3).Value = "value"
| |
doc_23536303
|
I have a feeling it's because the character is being connected twice hence counting the while loop twice?
local Players = game.Players
Players.PlayerAdded:Connect(function(Player)
local leaderstats = Instance.new("Folder", Player)
leaderstats.Name = "leaderstats"
local WalkS = Instance.new("IntValue", leaderstats)
WalkS.Name = "Walkspeed"
WalkS.Value = 0
Player.CharacterAdded:Connect(function(Char)
local Humanoid = Char:FindFirstChild("Humanoid")
Humanoid.WalkSpeed = WalkS.Value
while Humanoid do
Humanoid.WalkSpeed = WalkS.Value
wait(1)
WalkS.Value = WalkS.Value + 1
end
end)
end)
I don't know how to fix this and have been trying, I just don't know anything else to use other than CharacterAdded
A: When any instance gets destroyed its references (in code) don't necessarily become nil. It's important to understand that all destroy does is remove the object from workspace, remove any connections associated object has, and then lock the object from being re-added to workspace.
Eg:
local baseplate = workspace.Baseplate;
baseplate:Destroy(); -- removes it from workspace, and removes all connections
print(baseplate.Name); -- still prints "baseplate"
baseplate.Name = "test" -- works
baseplate.Parent = workspace -- errors, since it's locked
So to fix your issue, you should also make sure that the Humanoid exists in workspace
Player.CharacterAdded:Connect(function(Char)
local Humanoid = Char:WaitForChild("Humanoid") -- also would recommend WaitForChild
-- as humanoid may not be loaded on character added
Humanoid.WalkSpeed = WalkS.Value
while Humanoid:IsDescendantOf(workspace) do -- check to make sure it's in the workspace
Humanoid.WalkSpeed = WalkS.Value
wait(1)
WalkS.Value = WalkS.Value + 1
end
end)
| |
doc_23536304
|
The task I want to accomplish is simple:
Read the daily step count from the server.
Ideally I want the step count retrieved to match what is displayed on https://fit.google.com/ but I have not been able to do so.
Here is my set up:
Request access:
val fitnessOptions = FitnessOptions.builder()
.addDataType(DataType.TYPE_STEP_COUNT_DELTA, FitnessOptions.ACCESS_READ)
.addDataType(DataType.AGGREGATE_STEP_COUNT_DELTA, FitnessOptions.ACCESS_READ)
.build()
if (GoogleSignIn.hasPermissions(GoogleSignIn.getLastSignedInAccount(this), fitnessOptions)) {
Toast.makeText(this, "Already Has permission", Toast.LENGTH_SHORT).show()
} else {
GoogleSignIn.requestPermissions(
this, // your activity
FIT_REQUEST_CODE,
GoogleSignIn.getLastSignedInAccount(this),
fitnessOptions)
}
To my understanding the method below should reach out to the server and retrieve the step count.
According to the documentation there is readDailyTotalFromLocalDevice(...) method so if I wanted to get the data from the device I would just use that method. But both of these methods seem to return the same exact values.
Query Data
Fitness.getHistoryClient(this, GoogleSignIn.getLastSignedInAccount(this))
.readDailyTotal(DataType.TYPE_STEP_COUNT_DELTA)
.addOnSuccessListener {
tvResult.text = "Steps: ${it.dataPoints[0].getValue(Field.FIELD_STEPS)}"
}
.addOnFailureListener {
tvResult.text = "Error"
}
For context: the step count (at the time of writing this) on https://fit.google.com is 6000 and the value I am getting back from the method above is 4 Furthermore I do not see any traffic being generated on the GoogleAPI console for fitness api which confirms the hypothesis that the request is never going out to the server.
What I have tried (without success):
*
*Manually constructing the request and explicitly adding enable server
query
*Adding subscription for the same data type that I am trying to read
How can I read the daily step count data that is stored on the cloud fitness data store?
| |
doc_23536305
|
I think it is because client 1 does not have authority to request client 2 to activate their UI panel. I thought the Command and ClientRpc would have fixed this issue?
Short story: So, for simplicity, say when client 1 presses the Input for “Submit”, I would like all client’s textContainer GameObjects to go active.
I am hoping someone might be able to point me in the right direction. Cheers.
This script would be attached to the player prefab.
public GameObject textContainer;
[Client]
void Update()
{
if (Input.GetAxisRaw("Submit") == 1)
{
CmdActivateChatClientRPC();
textContainer.SetActive(true);
}
}
[Command]
private void CmdActivateChatClientRPC()
{
ActivateChatClientRPC();
}
[ClientRpc]
private void ActivateChatClientRPC()
{
textContainer.SetActive(true);
}
A: How about
client->server: request to activate
and then
server->client: singal
[SyncVar(hook = nameof(AcivateText))]
bool textActivated = false;
[Command]
private void CmdActivateChatClientRPC()
{
ActivateChatClientRPC();
}
void AcivateText(bool oldval, bool newval)
{
textContainer.SetActive(newval);
}
A: You are not checking whether you have the authority over this object.
void Update()
{
// Does your device have the authority over this object?
// only then you can invoke a Cmd
if(!hasAuthority) return;
if (Input.GetAxisRaw("Submit") == 1)
{
CmdActivateChatClientRPC();
textContainer.SetActive(true);
}
}
[Command]
private void CmdActivateChatClientRPC()
{
ActivateChatClientRPC();
}
// This will be executed on ALL clients!
// BUT only for this one instance of this class
[ClientRpc]
private void ActivateChatClientRPC()
{
textContainer.SetActive(true);
}
If it is rather about only you trying to invoke a command on an object that belongs to the server it gets tricky ;)
You will have to relay the command through your local player object and then on the server forward the call to the according object e.g. referencing the actual target via it's Network identity.
To me it sounds a bit like you are having each player prefab has this class and you want to invoke the RPC on all of them.
This is something that can only be done by the server like e.g.
void Update()
{
// Does your device have the authority over this object?
// only then you can invoke a Cmd
if(!hasAuthority) return;
if (Input.GetAxisRaw("Submit") == 1)
{
CmdActivateChatClientRPC();
textContainer.SetActive(true);
}
}
[Command]
private void CmdActivateChatClientRPC()
{
foreach (var player in NetworkManager.singleton.client.connection.playerControllers)
{
if (player.IsValid)
{
player.gameObject.GetComponent<YourScriptName>().ActivateChatClientRPC();
}
}
}
Seems that .client.connection.playerControllers was removed.
I guess in that case you would need a custom NetworkManager and keep track of them yourself via OnServerConnect and OnServerDisconnect somewhat like
public CustomNetworkManager : NetworkManager
{
public static readonly HashSet<NetworkConnection> players = new HashSet<NetworkConnection>();
public override void OnServerConnect(NetworkConnection conn)
{
base.OnServerConnect(conn);
players.Add(conn);
}
public override void OnServerDisconnect(NetworkConnection conn)
{
base.OnServerDisconnect(conn);
players.Remove(conn);
}
}
and then instead access
foreach (var player in CustomNetworkManager.players)
{
player.identity.GetComponent<YourScriptName>().ActivateChatClientRPC();
}
| |
doc_23536306
|
For example:
http://example.com/3000
No need to update the db and display value 3000
If i use
http://example.com/3000/update
than need to update my db...
However my .htaccess and php script working fine... But my CSS and images file not working while update URL and i got 404 error on CSS/JS files.
I checked the URL for css, it can be rewrite like this
http://example.com/3000/theme.css
Actual URL is
http://example.com/theme.css
My .HTACCESS file
Options +FollowSymLinks
RewriteEngine on
RewriteBase /
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/update$ index.php?result=$1&update=true [L]
</IfModule>
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ db.php?result=$1 [L]
</IfModule>
How to fix this problem.. What mistake done on htaccess file..
| |
doc_23536307
|
I would like to know if I close the webview, does session data in webview's server remains, or gets closed.
| |
doc_23536308
|
I know that the orders of the messages are in any order (because i explicitly did not use semaphores)
How does the flow of my program look and why?
The parent is executed so "baz" is printed once. Can somebody explain why "bar" is not printed? Why do I get "foo" (the if statement is true) two times and not one or three times(not that i want this but i want to understand the logic)(because a colleague says that i should get three times foo out of it)?
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
int p;
p = fork();
if (fork()==0) {
if (execl("/bin/echo", "/bin/echo", "foo", 0) == -1) {
fork();
}
printf("bar\n");
}
else {
if (p!=0) execl("/bin/echo", "/bin/echo", "baz", 0);
}
}
A: execl does not return, it replaces the entire process image with /bin/echo.
There are therefore zero "bar"s.
if (execl("/bin/echo", "/bin/echo", "foo", 0) == -1) {
fork();
}
/* Not reached if execl succeeded.
Because the exec family of functions replace the process image with
another executable. Flow will never return, unless there is an
error. */
printf("bar\n");
There are two "foo"s.
int p;
p = fork();
/* Two processes now */
if (fork()==0) {
/* Two child processes here. */
execl("/bin/echo", "/bin/echo", "foo", 0); /* (Simplification) */
/* Two (/bin/echo foo) here, flow will never return back */
}
There is one "baz".
int p;
p = fork();
/* if block removed for simplicity */
if (p != 0)
{
/* Only the initial parent process. */
execl("/bin/echo", "/bin/echo", "baz", 0);
}
A: First you need to understand that the exec family of system calls replaces the entire program with some other program. In your case, the "echo" program. Anything beyond an execl call is not executed.
Here is what is happening:
*
*Your parent process (call it p0) executes p=fork() that forks a clone process p1.
*Again p0 executes if (fork()==0) that forks another clone process p2.
*p0 then executes the body of the else statement that prints the "baz".
*After being forked, p1 executes the if (fork()==0) statement that forks another process p3. Like p0, p1 will enter the else statement but will not print "baz" because p which was set when p0 forked p1 is actually equal to 0 (since p1 is the child of p0).
*p2 enters the if-statement body and executes the execl function which replace the current program with the echo program that prints "foo".
*Like p2, p3 enters the if-statement body and executes the execl function which replace the current program with the echo program that prints "foo".
A: The first fork creates two processes,
which then both do a second fork.
p0 (p=$pid) //first fork
p1 (p==0)
p01 p11 //second fork
exec exec
In the leaf children (p01 and p11), this second fork is followed by an exec, which if successful, ends the old process image. This should give you two foos on stdout.
The parents (p0 and p1) then do the:
if (p!=0) execl("/bin/echo", "/bin/echo", "baz", 0);
p!=0 test which may only succeed in p0 (the original process).
This should give you a single baz on stdout.
(In real code you should also check for fork errors).
| |
doc_23536309
|
A: As suggested by Farinha, but using HashSet
Some importang points: we are using a HashSet because in the end the letters can have two states: discovered (present in the HS) or not discovered (not present). We initialize the HashSet passing as a parameter StringComparer.InvariantCultureIgnoreCase because we consider L and l to be the same thing. To use the StringComparer.InvariantCultureIgnoreCase we have to use an HashSet<string> (an HS of strings) instead of an HashSet<char> (an HS of chars). So when using the discovered.Contains() we have to convert the c char in a string with a ToString
static string ConvertWord(string word, HashSet<string> discovered)
{
StringBuilder sb = new StringBuilder(word.Length);
foreach (char c in word)
{
if (discovered.Contains(c.ToString()))
{
sb.Append(c);
}
else
{
sb.Append('_');
}
}
return sb.ToString();
}
HashSet<string> discovered = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
// The "secret" word
string word = "Hello world";
// How to add letters to the ones discovered
discovered.Add("l");
// The word ready to be shown
string convertWord = ConvertWord(word, discovered);
We could have done the ConvertWord in much less characters, but for today it's enough :-)
Ok... I'll give you an example, in C# 4.0:
static string ConvertWord(string word, HashSet<string> discovered)
{
return string.Concat(word.Select(p => discovered.Contains(p.ToString()) ? p : '_'));
}
A: Using a Regex doesn't seem like a good approach. I would instead grab the word, break it down into characters, and build a Dictionary<char,bool> where the bool indicates if the letter has been discovered yet. Then you an look through the Dictionary and for each item display the char if the letter has been discovered, or an underscore if not.
// build the Dictionary
string originalWord = "Stack Overflow";
Dictionary<char, bool> dict = new Dictionary<char, bool>();
for(int i = 0; i < originalWord.Length; i++)
dict.Add(originalWord[i], false);
// output the current state
string current = "";
foreach(KeyValuePair<char, bool> pair in dict)
{
current += pair.Value ? pair.Key.ToString() : "_";
}
A: I am not sure if this is exactly what you want, but you can take a look if it is helpful.
The game was simulated by sed and echo. of course, you can use variable for the secret word, not echo as plain text.
say, my secret word is "memory"
#user gives a letter "a"
kent$ echo "memory"|sed 's/[^a]/_/g'
______
#user gives a letter "r"
kent$ echo "memory"|sed 's/[^ar]/_/g'
____r_
#user gives a letter "m"
kent$ echo "memory"|sed 's/[^arm]/_/g'
m_m_r_
#user gives a letter "o"
kent$ echo "memory"|sed 's/[^armo]/_/g'
m_mor_
#user gives a letter "x"
kent$ echo "memory"|sed 's/[^armox]/_/g'
m_mor_
#user gives a letter "y" then "e"
kent$ echo "memory"|sed 's/[^armoxy]/_/g'
m_mory
kent$ echo "memory"|sed 's/[^armoxye]/_/g'
memory
A: Why not using a textbox and having its entry type as password, then set his password character as 'underscore'
A: I wouldn't bother with regex - you can write a fairly simple function to take an array of characters which represent the guesses made and return the representation of the word as required:
string word = "AMBULANCE";
public string Hangman(char[] guesses)
{
char[] output = new char[word.Length];
for (int i = 0; i < word.Length; i++)
{
if (guesses.Contains(word[i]))
{
output[i] = word[i];
}
}
return new String(output).Replace('\0','_');
}
and then call it using something like:
char[] guesses = new char[] { 'A', 'E' };
Console.WriteLine(Hangman(guesses));
Console.ReadLine();
| |
doc_23536310
|
window.connect_show(clone!(@weak window => move |_| {
// std::thread::sleep(std::time::Duration::from_secs(1)); // add a delay of 1 second
let command = format!("xdotool search --onlyvisible --name {}", WINDOW_NAME);
let window_id = Command::new("sh").arg("-c").arg(command).output();
println!("window_id: {:?}", window_id);
}));
However, I can't get the window id:
window_id: Ok(Output { status: ExitStatus(unix_wait_status(256)), stdout: "", stderr: "" })
I can't get it even if I use window.connect_realize (after the window has been mapped to the screen).
I do get the window id if I uncomment std::thread::sleep(std::time::Duration::from_secs(1));
Why is this? And how can I get the window id without relying on std::thread::sleep(std::time::Duration::from_secs(1));?
The full code of the file is here.
| |
doc_23536311
|
word Frequency
Gone 60
Goes 10
Go 30
So far the system returns words eg starting with 'g' as go30, goes10, gone60 as a list.
(alphabetically). I want to increase the accuracy of the system so that the search result is based on frequency. Words with high frequencies appear first. kindly help.
Here is the Text midlet class that reads the dictionary line by line.
public class Text extends MIDlet {
// Fields
private static final String[] DEFAULT_KEY_CODES = {
// 1
".,?!'\"1-()@/:_",
// 2
"ABC2",
// 3
"DEF3",
// 4
"GHI4",
// 5
"JKL5",
// 6
"MNO6",
// 7
"PQRS7",
// 8
"TUV8",
// 9
"WXYZ9",
};
//Initializing inner Classes
public ComposeText() {
cmdHandler = new CommandHandler();
lineVector = new Vector();
}
//Calling All InitMethods, setting Theme, Show MainForm
public void startApp() {
Display.init(this);
setTheme();
initCmd();
initMainGui();
mainFrm.show();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
//Initializing all the Commands
public void initCmd() {
exitCmd = new Command("Exit");
selectCmd = new Command("Ok");
cancelCmd = new Command("Cancel");
predCmd = new Command("Prediction");
sendCmd = new Command("Send");
tfPredArea = new TextField();
//check dictionary
try {
readFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}
//Initiating MainScreen
public void initMainGui() {
mainFrm = new Form("Compose Text");
mainFrm.setLayout(new BorderLayout());
mainFrm.setLayout(new CoordinateLayout(150, 150));
mainFrm.addCommand(exitCmd);
mainFrm.addCommand(predCmd);
mainFrm.addCommand(sendCmd);
mainFrm.addCommandListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == predCmd){
initPredGui();
} else if(ae.getSource() == exitCmd){
destroyApp(true);
notifyDestroyed();
}
}
});
// To : 07xxxxxxxxxx
Dimension d1 = new Dimension(130, 20);
lbTo = new Label("To:");
lbTo.setX(10);
lbTo.setY(10);
tfTo = new TextField();
tfTo.setReplaceMenu(false);
tfTo.setConstraint(TextField.NUMERIC);
tfTo.setInputModeOrder(new String[]{"123"});
tfTo.setMaxSize(13);
tfTo.setX(40);
tfTo.setY(10);
tfTo.setPreferredSize(d1);
//Message : Compose Text
Dimension d2 = new Dimension(135, 135);
lbSms = new Label("Message:");
lbSms.setX(5);
lbSms.setY(40);
tfSms = new TextField();
tfSms.setReplaceMenu(false);
tfSms.setX(40);
tfSms.setY(40);
tfSms.setPreferredSize(d2);
//add stuff
mainFrm.addComponent(lbTo);
mainFrm.addComponent(lbSms);
mainFrm.addComponent(tfTo);
mainFrm.addComponent(tfSms);
}
//Initiating FilterSelection Screen
public void initPredGui() {
predForm = new Form("Prediction on");
predForm.setLayout(new CoordinateLayout(150, 150));
predForm.addCommand(cancelCmd);
predForm.addCommand(selectCmd);
//textfied in prediction form
final Dimension d5 = new Dimension(200, 200);
tfPredArea = new TextField();
tfPredArea.setReplaceMenu(false);
tfPredArea.setX(10);
tfPredArea.setY(10);
tfPredArea.setPreferredSize(d5);
predForm.addComponent(tfPredArea);
final ListModel underlyingModel = new DefaultListModel(lineVector);
// final ListModel underlyingModel = new
DefaultListModel(tree.getAllPrefixMatches(avail));
// this is a list model that can narrow down the underlying model
final SortListModel proxyModel = new SortListModel(underlyingModel);
final List suggestion = new List(proxyModel);
tfPredArea.addDataChangeListener(new DataChangedListener() {
public void dataChanged(int type, int index) {
int len = 0;
int i = 0;
String input = tfPredArea.getText();
len = tfPredArea.getText().length();
//ensure start search character is set for each word
if (!(len == 0)) {
for (i = 0; i < len; i++) {
if (input.charAt(i) == ' ') {
k = i;
}
}
String currentInput = input.substring(k + 1, len);
proxyModel.filter(currentInput);
}
}
});
Dimension d3 = new Dimension(110, 120);
suggestion.setX(80);
suggestion.setY(80);
suggestion.setPreferredSize(d3);
predForm.addComponent(suggestion);
suggestion.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String string = suggestion.getSelectedItem().toString();
if (tfPredArea.getText().charAt(0) == 0) {
tfPredArea.setText(string);
}
else if (tfPredArea.getText().length() == 0) {
tfPredArea.setText(string);
} else {
tfPredArea.setText(tfPredArea.getText() + string);
}
}
});
predForm.addCommandListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == addCmd) {
newDictionaryFrm.show();
} else {
mainFrm.show();
}
}
});
predForm.show();
}
//Setting Theme for All Forms
public void setTheme() {
try {
Resources r = Resources.open("/theme.res");
UIManager.getInstance().setThemeProps(r.getTheme(
r.getThemeResourceNames()[0]));
} catch (java.io.IOException e) {
System.err.println("Couldn't load the theme");
}
}
//Inner class CommandHandler
public class CommandHandler implements ActionListener {
public void actionPerformed(ActionEvent ae) {
//cancelCommand from predictionForm
if (ae.getSource() == cancelCmd) {
if (edit) {
mainFrm.show();
// clearFields();
} else if (ae.getSource() == selectCmd){
tfPredList.addDataChangeListener(model);
predForm.show();
}
else{}
}
}
}
// method that reads dictionary line by line
public void readFile() throws IOException {
tree = new Trie();
InputStreamReader reader = new InputStreamReader(
getClass().getResourceAsStream("/Maa Corpus.txt-01-ngrams-Alpha.txt"));
String line = null;
// Read a single line from the file. null represents the EOF.
while ((line = readLine(reader)) != null) {
// Append to a vector to be used as a list
lineVector.addElement(line);
}
}
public String readLine(InputStreamReader reader) throws IOException {
// Test whether the end of file has been reached. If so, return null.
int readChar = reader.read();
if (readChar == -1) {
return null;
}
StringBuffer string = new StringBuffer("");
// Read until end of file or new line
while (readChar != -1 && readChar != '\n') {
// Append the read character to the string.
// This is part of the newline character
if (readChar != '\r') {
string.append((char) readChar);
}
// Read the next character
readChar = reader.read();
}
return string.toString();
}
}
}
The SortListModel Class has a filter method that gets prefix from the textfield datachangeLister
class SortListModel implements ListModel, DataChangedListener {
private ListModel underlying;
private Vector filter;
private Vector listeners = new Vector();
public SortListModel(ListModel underlying) {
this.underlying = underlying;
underlying.addDataChangedListener(this);
}
private int getFilterOffset(int index) {
if(filter == null) {
return index;
}
if(filter.size() > index) {
return ((Integer)filter.elementAt(index)).intValue();
}
return -1;
}
private int getUnderlyingOffset(int index) {
if(filter == null) {
return index;
}
return filter.indexOf(new Integer(index));
}
public void filter(String str) {
filter = new Vector();
str = str.toUpperCase();
for(int iter = 0 ; iter < underlying.getSize() ; iter++) {
String element = (String)underlying.getItemAt(iter);
if(element.toUpperCase().startsWith(str)) // suggest only if smthing
{
filter.addElement(new Integer(iter));
}
}
dataChanged(DataChangedListener.CHANGED, -1);
}
public Object getItemAt(int index) {
return underlying.getItemAt(getFilterOffset(index));
}
public int getSize() {
if(filter == null) {
return underlying.getSize();
}
return filter.size();
}
public int getSelectedIndex() {
return Math.max(0, getUnderlyingOffset(underlying.getSelectedIndex()));
}
public void setSelectedIndex(int index) {
underlying.setSelectedIndex(getFilterOffset(index));
}
public void addDataChangedListener(DataChangedListener l) {
listeners.addElement(l);
}
public void removeDataChangedListener(DataChangedListener l) {
listeners.removeElement(l);
}
public void addSelectionListener(SelectionListener l) {
underlying.addSelectionListener(l);
}
public void removeSelectionListener(SelectionListener l) {
underlying.removeSelectionListener(l);
}
public void addItem(Object item) {
underlying.addItem(item);
}
public void removeItem(int index) {
underlying.removeItem(index);
}
public void dataChanged(int type, int index) {
if(index > -1) {
index = getUnderlyingOffset(index);
if(index < 0) {
return;
}
}
for(int iter = 0 ; iter < listeners.size() ; iter++) {
((DataChangedListener)listeners.elementAt(iter)).dataChanged(type, index);
}
}
}
| |
doc_23536312
| ||
doc_23536313
|
import jericho-html-3.1.src.java.net.htmlparser.jericho.*;
even though I added the zip file Libraries folder.
A: You probably want to add library to your project so you could call it in your code.
From the line import jericho-html-3.1.src.java.net.htmlparser.jericho.*; I assume that you try to add source code to the project. This will not work.
You need to add a library library and not source code. The library file has .jar extension.
When you download a zip file from http://sourceforge.net/projects/jerichohtml/files/jericho-html/3.1/ The library is in /jericho-html-3.1/dist/ folder of the zip.
For library usage take a look on Sample Programs.
A: In the Projects window right-click on the name of the project that lacks library -> Properties -> The Project Properties window opens. In Categories tree select "Libraries" node -> On the right side of the Project Properties window press button "Add JAR/Folder" -> Select jars you need.
You also can see MockerTim's short Video How-To.
| |
doc_23536314
|
Said person suggested that I avoid custom actions at all costs though, stating that the moment you need to use custom actions you need to come up with your own solution and said that this is something that is recognised by many people and has been for a long time.
I have had a search around and can't find a single forum in which anyone has expressed concerns about this, and I just want to know if anyone knows of any reason why custom actions should not be used?
I want to ensure I'm using the most reliable solution possible in my new project, and this has given me some concerns about my current approach, however the person I was discussing it with couldn't give me an example of why it's a bad idea, so I just want confirmation as to whether what they said holds water or not.
A: I have a lot of reasons but it's a long and subjective conversation. Here are a couple links to get you started. In summary the thing to keep in mind is to maintain the declarative native of MSI ( author table data driven, transactional custom actions ) and work really, really hard to not introduce fragiltiy to your installer. Because of the design of InstallUtil / Installer class custom actions, they are simply a non-starter. Use WiX's DTF ( Deployment Tools Foundation ) managed custom action project types ( C# / VB.NET ) instead.
Managed Code CustomActions, no support on the way and here's why
Custom actions are (generally) an admission of failure
Note, for the first link, the "technical" portion is OBE due to the release of DTF. The strategic portion is somewhat optimistic IMO and discussed more in the second link. Here's also some background from my own blog:
MSI vs .NET
The Price of Ideology and a Great New Hope
Deployment Tools Foundation (DTF) Managed Custom Actions
| |
doc_23536315
|
But configured rest delivery points, consumer, queue-binding status are down
:( (Note: Admin status is up)
Http listener link: http://hostname:port/ws/simple/getDefaultRDP
added the screen shots Please let me know any changes need to be done
rest delivery point status screen shot
rest consumer screenshot
queue binding screen shot
screenshot for (a)show message-vpn sol-vpn rest rest-delivery-point * detail
show message-vpn sol-vpn rest rest-delivery-point * detail
screenshot for (b) show message-vpn sol-vpn rest rest-consumer * rest-delivery-point * detail
show message-vpn sol-vpn rest rest-consumer * rest-delivery-point * detail
screenshot for (c) show message-vpn sol-vpn rest rest-delivery-point * queue-binding * detail
show message-vpn sol-vpn rest rest-delivery-point * queue-binding * detail
Note: Http listener is a Dellboomi process and listner working fine when i did test with soap ui test tool
A: The operational status of a Rest Delivery Point (RDP) depends on the operational statuses of its Rest Consumers and Queue bindings.
In this case, the command:
show message-vpn <vpn_name> rest rest-consumer * rest-delivery-point <rdp_name> detail
shows the last failure reason as:
Host Name Resolution Failure
This means the Solace router is unable to resolve the remote hostname to an IP address and thus cannot connect to your http listener.
You'll need to put in a resolvable FQDN as the remote, or an IP address as the remote host.
| |
doc_23536316
|
import plotly.express as px
input_df = px.data.tips()
fig = px.scatter(input_df,
x = 'total_bill',
y = 'tip',
color = 'day',
facet_row = 'smoker',
facet_col = 'sex',
)
fig.layout.width = 800
fig.show()
I would like to convert the above so each trace (or color) has its own secondary y-axis. So in this case, I would like 3 additional y-axes for each facet. This is my attempt but it doesn't work. There must be a better way. I would appreciate any ideas.
import plotly.graph_objects as go
yaxes = []
for trace in fig.data:
yaxisLabel = trace['yaxis']
if trace['yaxis'] in yaxes:
if yaxisLabel == 'y':
axisnumber = 0
else:
axisnumber = int(trace['yaxis'][1:])
newAxis_num = axisnumber + 100 * yaxes.count(yaxisLabel)
exec(f"fig.layout.update(yaxis{newAxis_num} = go.layout.YAxis(overlaying='y', side='right'))")
trace.update({'yaxis': f'y{newAxis_num}'})
yaxes.append(yaxisLabel)
| |
doc_23536317
|
Thank you I appreciate any info.
| |
doc_23536318
|
I have this code:
if ($request->hasfile('profilePhoto')) {
$this->validate($request, [
'profilePhoto' => 'required',
'profilePhoto.*' => 'mimetypes:image/jpg'
]);
$image = $request->file('profilePhoto');
$extension = strtolower($image->getClientOriginalExtension());
$path = 'upload/images/UserImage/';
$uniqueName = md5($image . time());
$image->move(public_path($path), $uniqueName . '.' . $extension);
}
This function uploads files to public/upload/images/UserImage/.
I need it to store it in storage/app/upload/images/UserImage/ instead
How can I rewrite my code?
A: You have to use storage_path function ("storage/app/upload" folder must exist):
$image->move(storage_path("app/upload"), $uniqueName . '.' . $extension);
A: if ($request->hasfile('profilePhoto')) {
$this->validate($request, [
'profilePhoto' => 'required',
'profilePhoto.*' => 'mimetypes:image/jpg'
]);
$image = $request->file('profilePhoto');
$extension = strtolower($image->getClientOriginalExtension());
$path = storage_path('app/public/upload/images/UserImage');
$uniqueName = md5($image . time());
$image->move(public_path($path), $uniqueName . '.' . $extension);
}
A: A common way in Laravel to upload to storage/app is through the local disk driver.
$file = $path . $uniqueName . '.' . $extension;
\Storage::disk('local')->put($file, $request->file('profilePhoto'));
Storage::disk('local') points to storage/app/.
A: As your $path variable is already declared like this $path = 'upload/images/UserImage/' .So instead of storing data to public_path you can store to storage_path().
$image->move(storage_path($path), $uniqueName . '.' . $extension);
| |
doc_23536319
|
I'm trying to localize a website, so i converted it to a web application and generated resx file for each aspx and ascx file i have ( pagename.en.resx ..etc)
however the localization never worked with me. one thing to mention that when i open the resx files in the designer mode i find "Access Modifier" dropdown enabled on the upper right, on sample projects that works successfully i find the "Access Modifier" dropdown disable ?
Your suggestions are very much appreciated !
A: Resolved ! the issue was as follows :
I defined resources files with language prefix : resourcefile.en.resx , resourcefile.jp.resx
however ASP.NET requires a generic resource file like resourcefile.resx
Thank you all !
A: *
*Try also declaring the culture:
*Make sure that your browser settings include English as a language.
If that doesn't help, can you post some of the code of your aspx/ascx file in which you use localization?
| |
doc_23536320
|
Old: http://old-website.com/index4.php?show=1590
New: http://new-website.com/performance/1590
Notice the variable "1590" is carried to the new URLs. I'm still learning regex and htaccess but can get this working right. Here is where I left off...
RewriteEngine On
RewriteCond %{QUERY_STRING} page=/index4.php?show=([0-9]+)
RewriteRule ^/?(index4.php)?$ http://showfile.fm/performance/%1? [L,R=301]
I also need to get the homepage and other pages without variables to redirect to specific pages. I'm not sure how you would stack those other rules - if there is a necessary order.
| |
doc_23536321
|
<style>
#content{ margin:25px;}
</style>
<div id='wrapper' title='example'>
<div id='content'>
</div>
</div>
(I only want the tool-tip to show up between the edges of the 'content' and 'wrapper' elements, instead of in both)
A: I don't think this is possible with pure CSS or HTML.
One way to hack this is using client side code.. basic plain JavaScript example:
window.onload = function() {
var oDiv = document.getElementById("content");
oDiv.onmouseover = function() {
this.parentNode.setAttribute("old_title", this.parentNode.title);
this.parentNode.title = "";
};
oDiv.onmouseout = function() {
this.parentNode.title = this.parentNode.getAttribute("old_title");
};
};
This will "clear" the parent div title upon mouse over of the contents, and restore the title when the mouse leave the contents.
Live test case: http://jsfiddle.net/UASPZ/
A: I had the same problem. I found out that you can prevent this by giving the child elements a dummy title title=" ".
A: Same problem here.
Found out that specifying title=' ' works for Chrome and FireFox but shows annoying tool-tip with one space in IE. title='' works for IE but completely ignored by Chrome and FireFox thus showing parent's tool-tip.
Didn't figured out how to make in cross-browser :(
A: This is now possible, as explained on MDN
Title attribute inheritance
If an element has no title attribute, then it inherits it from its
parent node, which in turn may inherit it from its parent, and so on.
If this attribute is set to the empty string, it means its ancestors'
titles are irrelevant and shouldn't be used in the tooltip for this
element.
This creates the following solution for your problem:
<div id='wrapper' title='example'>
<div id='content' title=''>
</div>
</div>
I have confirmed that this works in Firefox and Chrome.
| |
doc_23536322
|
GCGGCTCCTCTGGGGCGTTCCC
GCGGCTCCTCTGGGGGGCGTTC
The first can be converted to the second with an insertion of 2 characters like so:
GCGGCTCCTCTGGGGGGCGTTCCC
GCGGCTCCTCTGGGGGGCGTTC
The lengths of the original two strings were 22. The first 22 characters in these two strings are now identical. The levenshtein distance between these two strings is 4, and I'd like a way of reporting an edit distance of 2 for these two strings.
Is there a way to do this with the python package Levenshtein_distance function or Levenshtein python package I'm already using?
More details:
I'm applying this to Next Generation Sequencing data. I'd like to compare 2 sequences generated from a portion of each sequencing read. The sequences are obtained from the start of the full length sequencing read and should be a unique sequence per sequencing read.
Example:
Read A: ATCGAACCGGTT
Read B: ATGAACCGGTT
Where the first four bases of the strings will be used as the unique identifier of each read. Sequence ATCG is the unique identifier for Read A and ATGA is the unique identifier for Read B. Both reads contain the identical sequence "AACCGGTT". When comparing the unique identifiers (ATCG and ATGA), I'd like a metric that returns an edit distance of 1 between the two sequences.
Read A unique identifier: ATCG
Read B unique id after insertion: AT_GA
The reasons I think the overhanging bases on the right side of the string (end of the sequencing) should not be penalized, but they should be penalized on the left side of the sequence, are as follows:
*
*The first and most important reason is that just because there are overhanging characters on the right side of the string (AKA the end of the sequence), that doesn't mean the characters don't align between the two sequences being compared. It only means we don't have the corresponding characters from the other sequence to compare them to. The same is not true for the left side of the string.
*Usually, the characters at the left side of the string (AKA the start of the sequencing read) are more confidently identified (have higher quality scores) than those on the right side.
A: Although it is not difficult to write a customized function to calculate the 'distance', you can try edlib first. Cause it is a very efficient tool to do this job.
Input Read A:
ATCGAACCGGTT
Input Read B:
ATGAACCGGTTATG
After Alignment:
ATCGAACCGGTT--- # these tailing gap will be ignored
AT-GAACCGGTTATG # the internal gap is meaningful
There is python tag in your question, so I post a solution using edlib python wrapper.
>>> import edlib
>>> edlib.align("ATCGAACCGGTT","ATGAACCGGTTATG", mode="SHW")['editDistance']
1
SHW mode: gap at query end is not penalized
| |
doc_23536323
|
the second for infinity loops although there is a condition that j is less than the input value(col). i tried with values of [ row = 5 columns = 5] but still get infinite loop.
function addtable(){
var row = document.getElementById('row1').value;
var col = document.getElementById('col1').value;
if( row === "" || col === ""){alert("Please Enter Row & Column values");}
//console.log(row*col);
table = document.createElement('table');
//table.id='Ntables';
console.log(table);
var i = 0;
for( i; i <(row+1) ; i++)
{
var tr = document.createElement('tr');
//tr.id='Ntablerows';
console.log(tr);
table.appendChild(tr);
var j = 0;
for(j; j < (col+1); j++)
{
var td = document.createElement('td');
console.log(td);
tr.appendChild(td);
//td.id='Ntablecols'
var input = document.createElement('input');
input.type = 'text';
//input.id = 'Ntableinput';
td.appendChild(input);
}
}
return (0);
}
Edit: it was not an infinite loop, it was a number being concatenated to the loop variable. making it bigger than expected.
A: try this:
var row = document.getElementById('row1').value;
var col = document.getElementById('col1').value;
if( row === "" || col === ""){alert("Please Enter Row & Column values");}
row = parseInt( row )
col = parseInt( col )
| |
doc_23536324
|
There is a method called .slideUp(), however, it is used to hide the element, not to show it, as it looks.
Is it possible to "slide down" (=> show element) from bottom to top (instead from top to bottom)?
Best Answer
The selected answer from the similar question jQuery UI blind effect - reveal from bottom is actually not really satisfying. But there is also an answer further below from Prof. Desty Nova which answers this question perfectly in my opinion:
$("div").hide("blind", {"direction": "down"});
$("div").show("blind", {"direction": "down"});
JSFiddle (updated)
| |
doc_23536325
|
If anyone has any examples they could share it would be appreciated.
A: I was able to create the UserService.
User Model
import play.db.ebean.Model;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Entity
@Table(name = "users")
public class User extends Model {
@Id
@GeneratedValue
public Long id;
public Date lastLogin;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
public List<Profile> identities;
public User(Profile profile){
identities = new ArrayList<Profile>();
this.identities.add(profile);
lastLogin = new Date();
}
public static Finder<String ,User> find = new Finder<String, User>(String.class, User.class);
}
Profile Model
import play.db.ebean.Model;
import securesocial.core.BasicProfile;
import javax.persistence.*;
@Entity
@Table(name = "profiles")
public class Profile extends Model {
@Id
@GeneratedValue
public Long id;
public String providerId;
public String authUserId;
public String firstName;
public String lastName;
public String fullName;
public String email;
public String avatarUrl;
@ManyToOne
@JoinColumn(name = "user_id")
public User user;
public Profile(BasicProfile profile){
this.providerId = profile.providerId();
this.authUserId = profile.userId();
if(profile.firstName().isDefined())
firstName = profile.firstName().get();
if(profile.lastName().isDefined())
lastName = profile.lastName().get();
if(profile.fullName().isDefined())
fullName = profile.fullName().get();
if(profile.email().isDefined())
email = profile.email().get();
if(profile.avatarUrl().isDefined())
avatarUrl = profile.avatarUrl().get();
}
}
And the User Service
package services;
import models.Profile;
import models.User;
import play.libs.F;
import securesocial.core.BasicProfile;
import securesocial.core.PasswordInfo;
import securesocial.core.java.BaseUserService;
import securesocial.core.java.Token;
import securesocial.core.services.SaveMode;
import java.util.Date;
import java.util.List;
public class DemoUserService extends BaseUserService<User> {
@Override
public F.Promise<User> doSave(BasicProfile basicProfile, SaveMode saveMode) {
User result = null;
if(saveMode == SaveMode.SignUp()){
Profile profile = new Profile(basicProfile);
result = new User(profile);
profile.user = result;
result.save();
}else if(saveMode == SaveMode.LoggedIn()){
List<User> users = User.find.all();
for(User user: users){
for(Profile p : user.identities) {
if (p.authUserId.equals(basicProfile.userId()) && p.providerId.equals(basicProfile.providerId())) {
result = user;
result.lastLogin = new Date();
result.update();
}
}
}
}else{
throw new RuntimeException("Unknown mode");
}
return F.Promise.pure(result);
}
@Override
public F.Promise<User> doLink(User user, BasicProfile basicProfile) {
User target;
User u = User.find.byId(user.id.toString());
if(u == null) {
throw new RuntimeException("Cant find user");
}
target = u;
boolean linked = false;
for(Profile p : target.identities){
if(p.authUserId.equals(basicProfile.userId()) && p.providerId.equals(basicProfile.providerId())){
linked = true;
}
}
if(!linked) {
target.identities.add(new Profile(basicProfile));
target.update();
}
return F.Promise.pure(target);
}
@Override
public F.Promise<BasicProfile> doFind(String providerId, String userId) {
BasicProfile found = null;
List<User> users = User.find.all();
for(User u: users){
for(Profile i : u.identities){
if(i.providerId.equals(providerId) && i.authUserId.equals(userId)){
found = new BasicProfile(providerId , userId , null , null , null , null , null , null , null , null , null);
break;
}
}
}
return F.Promise.pure(found);
}
@Override
public F.Promise<BasicProfile> doFindByEmailAndProvider(String s, String s1) {
return null;
}
@Override
public F.Promise<Token> doSaveToken(Token token) {
return null;
}
@Override
public F.Promise<Token> doDeleteToken(String s) {
return null;
}
@Override
public void doDeleteExpiredTokens() {
}
@Override
public F.Promise<Token> doFindToken(String s) {
return null;
}
@Override
public F.Promise<PasswordInfo> doPasswordInfoFor(User user) {
return null;
}
@Override
public F.Promise<BasicProfile> doUpdatePasswordInfo(User user, PasswordInfo passwordInfo) {
return null;
}
}
| |
doc_23536326
|
[MyUILib makePathForRectWithEdges:UIRectEdgeLeft|UIRectEdgeRight]
In which the argument is an NSInteger, which I later compare to UIRectEdge enum values to see which sides I want to include in the path:
if(edges & UIRectEdgeTop)
{
// Draw Stuff
}
In Swift, Apple defines UIRectEdge as:
struct UIRectEdge : OptionSetType {
init(rawValue rawValue: UInt)
static var None: UIRectEdge { get }
static var Top: UIRectEdge { get }
static var Left: UIRectEdge { get }
static var Bottom: UIRectEdge { get }
static var Right: UIRectEdge { get }
static var All: UIRectEdge { get }
}
I can still use UIRectEdge.Top.rawValue to get a UInt, but calling a function like: makePathForRectWithEdges(UIRectEdge.Left.rawValue|UIRectEdge.Right.rawValue) is ugly and hard to read compared to how I used to do it. Is there a better pattern for using flags, or is this just how it has to be in Swift?
A: Instead of or-ing the raw value, you send a set to the functions:
MyUILib.makePathForRectWithEdges([.Left, .Right])
Hence the name OptionSetType. When you need to check if an option is included in the set:
if edges.contains(.Top) { ... }
| |
doc_23536327
|
Console.WriteLine("Enter an number: ");
int x = int.Parse(Console.ReadLine());
for (int i = 0; i < x; i++ )
{
Console.WriteLine("Ange tal {0}: ",i );
double numbers= double.Parse(Console.ReadLine());
}
Console.WriteLine("Sum of the entered numbers are: {0} ",x);
Console.ReadLine();
But the the result only gives me the last entered number. What am I doing wrong?
A: You need to make a variable where you will store the sum of the numbers (sum).
Then after you read the next number, you should add it to your sum.
Console.WriteLine("Enter a number: ");
int x = int.Parse(Console.ReadLine());
double sum = 0;
for (int i = 0; i < x; i++ )
{
Console.WriteLine("Ange tal {0}: ", i);
double number = double.Parse(Console.ReadLine());
sum += number;
}
Console.WriteLine("Sum of the entered numbers is: {0}", sum);
Console.ReadLine();
A: Console.Write("Enter N number: ");
double numberN = double.Parse(Console.ReadLine());
double sum = 0;
for (double i = 0; i < numberN; i++)
{
Console.Write("Enter number: ");
double number = double.Parse(Console.ReadLine());
sum += number;
}
Console.WriteLine("The sum is: {0}", sum);
A: This way the sum of the inputed number will be shown
Console.WriteLine("Enter an number: ");
int x = int.Parse(Console.ReadLine());
double sum = 0
for (int i = 0; i < x; i++ )
{
Console.WriteLine("Ange tal {0}: ",i );
sum = sum + double.Parse(Console.ReadLine());
}
Console.WriteLine("Sum of the entered numbers are: {0} ",sum);
Console.ReadLine();
A: You never actually do any summation in your code.
double sum = 0;
for (int i = 0; i < x; i++ )
{
Console.WriteLine("Ange tal {0}: ",i );
double numbers= double.Parse(Console.ReadLine());
sum += numbers;
}
Console.WriteLine("Sum of the entered numbers are: {0} ",sum);
A: You can do it like this
Console.WriteLine("Enter an number: ");
int x = int.Parse(Console.ReadLine());
List<double> allNumbers = new List<double>();
for (int i = 0; i < x; i++ )
{
Console.WriteLine("Ange tal {0}: ",i );
double temp;
if(double.TryParse(Console.ReadLine(), out temp))
allNumbers.Add(temp);
else
Console.WriteLine("Enter a valid number");
}
Console.WriteLine("Sum of the entered numbers are: {0} ",allNumbers.Sum());
Console.ReadLine();
A: Here there is the code, with the Write and WriteLine correctly formatted.
Console.Write("Enter an number: ");
int x = int.Parse(Console.ReadLine());
double sum = 0;
for (int i = 0; i < x; i++)
{
Console.Write("Ange tal {0}: ", i);
double number = double.Parse(Console.ReadLine());
sum = sum + number;
}
Console.WriteLine("Sum of the entered numbers are: {0:R} ", sum);
Console.Write("Press a key to exit");
Console.ReadKey();
But now we want to go a step forward: try inserting:
2
0.1
0.2
(or 0,1 and 0,2 if you use , as the decimal separator)
I always think that OMG Ponies!!! (Aka Humanity: Epic Fail) is the best reading possible...
A: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace add
{
class Program
{
static void Main(string[] args)
{
int a,b,c;
Console.WriteLine("Enter the first number");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter second number");
b = Convert.ToInt32(Console.ReadLine());
c = a + b;
Console.WriteLine("The addition of two number is {0}", c);
Console.ReadLine();
}
}
}
| |
doc_23536328
|
@NgModule({
declarations:[LoginComponent, LogoutComponent, HomeComponent],
exports:[LoginComponent,LogoutComponent, HomeComponent]
})
export class AuthModule {
}
import { AuthModule } from './auth.module'
@Injectable({
providedIn: AuthModule
}
)
export class LogoutService{
constructor(){
}
isLogout(){
console.log("Is logout successful");
}
}
@NgModule({
declarations: [
AppComponent,
DemoDynamicComponent,
TestComponent
],
imports: [
BrowserModule,
AppRoutingModule,
AuthModule //Uncaught ReferenceError: Cannot access 'AuthModule' before initialization
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
A: Option providedIn?: Type<any> is deprecated. Anyway this option was not usable because of problems with component lifecycle and possible circular references.
You can provide service trough module injector by adding it to the NgModule providers array:
@NgModule({
providers: [LogoutService]
}) export class AuthModule {}
| |
doc_23536329
|
This works great:
Get-ADUser -Filter * -Properties * | Select-Object -Property Name,SamAccountName,Description,EmailAddress,LastLogonDate,Manager,Title,Department,whenCreated,Enabled,Organization | Sort-Object -Property Name | ConvertTo-CSV
However, that does not include the groups the user is a member of.
Attempts at something like this have failed:
Get-ADUser -Filter * -Properties * | Select-Object -Property Name,SamAccountName,Description,EmailAddress,LastLogonDate,Manager,Title,Department,whenCreated,Enabled,Organization, @{$_.MemberOf |Get-Group|ForEach-Object {$_.Name}} | Sort-Object -Property Name | ConvertTo-CSV
This also failed:
Get-ADUser -Filter * -Properties * | Sort-Object -Property Name | ForEach-Object {
$_ | Format-List -Property Name,SamAccountName,Description,EmailAddress,LastLogonDate,Manager,Title,Department,whenCreated,Enabled
$_.MemberOf | Get-ADGroup | ForEach-Object {$_.Name} | Sort-Object
} | ConvertTo-CSV
I'm probably missing something simple.
Any help would be greatly appreciated.
Thanks!
A: From a Windows Server OS execute the following command for a dump of the entire Active Director:
csvde -f test.csv
This command is very broad and will give you more than necessary information. To constrain the records to only user records, you would instead want:
csvde -f test.csv -r objectClass=user
You can further restrict the command to give you only the fields you need relevant to the search requested such as:
csvde -f test.csv -r objectClass=user -l DN, sAMAccountName, department, memberOf
If you have an Exchange server and each user associated with a live person has a mailbox (as opposed to generic accounts for kiosk / lab workstations) you can use mailNickname in place of sAMAccountName.
A: For posterity....I figured out how to get what I needed. Here it is in case it might be useful to somebody else.
$alist = "Name`tAccountName`tDescription`tEmailAddress`tLastLogonDate`tManager`tTitle`tDepartment`tCompany`twhenCreated`tAcctEnabled`tGroups`n"
$userlist = Get-ADUser -Filter * -Properties * | Select-Object -Property Name,SamAccountName,Description,EmailAddress,LastLogonDate,Manager,Title,Department,Company,whenCreated,Enabled,MemberOf | Sort-Object -Property Name
$userlist | ForEach-Object {
$grps = $_.MemberOf | Get-ADGroup | ForEach-Object {$_.Name} | Sort-Object
$arec = $_.Name,$_.SamAccountName,$_.Description,$_.EmailAddress,$_LastLogonDate,$_.Manager,$_.Title,$_.Department,$_.Company,$_.whenCreated,$_.Enabled
$aline = ($arec -join "`t") + "`t" + ($grps -join "`t") + "`n"
$alist += $aline
}
$alist | Out-File D:\Temp\ADUsers.csv
A: csvde -f test.csv
This command will perform a CSV dump of every entry in your Active Directory server. You should be able to see the full DN's of users and groups.
You will have to go through that output file and get rid off the unnecessary content.
A: HI you can try this...
Try..
$Ad = Get-ADUser -SearchBase "OU=OUi,DC=company,DC=com" -Filter * -Properties employeeNumber | ? {$_.employeenumber -eq ""}
$Ad | Sort-Object -Property sn, givenName | Select * | Export-Csv c:\scripts\ceridian\NoClockNumber_2013_02_12.csv -NoTypeInformation
Or
$Ad = Get-ADUser -SearchBase "OU=OUi,DC=company,DC=com" -Filter * -Properties employeeNumber | ? {$_.employeenumber -eq $null}
$Ad | Sort-Object -Property sn, givenName | Select * | Export-Csv c:\scripts\cer
Hope it works for you.
A: the first command is correct but change from convert to export to csv, as below,
Get-ADUser -Filter * -Properties * `
| Select-Object -Property Name,SamAccountName,Description,EmailAddress,LastLogonDate,Manager,Title,Department,whenCreated,Enabled,Organization `
| Sort-Object -Property Name `
| Export-Csv -path C:\Users\*\Desktop\file1.csv
| |
doc_23536330
|
<sj:tabbedpanel id="remotetabs" selectedTab="%{selectedTab}" useSelectedTabCookie="true">
<sj:tab id="div1" target="pendingDiv" loadingText="Loading..." indicator="indicator" >
</sj:tab>
<sj:tabbedpanel>
Thanks
| |
doc_23536331
|
Here is the fiddle to check out: https://jsfiddle.net/mfj1ub8c/
I'm pretty sure it has something to do with the delays/fadein/hide methods on each append, but they need to be there to give a certain effect that is needed.
Any ideas on how to solve this?
A: Call scrollDown only when fadeIn is complete. You can use the complete callback parameter of fadeIn.
e.g.
.fadeIn(500, scrollDown))
Fixed fiddle: https://jsfiddle.net/mfj1ub8c/1/
A: The problem is scrollDown is being called before the element is actually shown (display: block) by fadeIn, so the scroll height hasn't changed yet. If you call scrollDown after fadeIn is complete, you'd miss the animation when the new content is off-screen. What you want to do is scroll when the element is displayed, but still transparent (opacity: 0). If you are on jQuery 1.8+ you can use the start option.
Here is a working fiddle https://jsfiddle.net/mfj1ub8c/2/
Also you are overshooting your scrollTop, which won't cause you problems here, but it should be the whole height minus the visible height.
$('#chat').prop("scrollHeight") - $('#chat').height()
| |
doc_23536332
|
#update.sh
#!/bin/bash
/usr/bin/freshclam
maldet -b -a /home
Another Script
#doandmail.sh
./update.sh > mail.txt
SUBJECT="Shell Script"
EMAIL="myemail@gmail.com"
EMAILMESSAGE="mail.txt"
/bin/mail -s "$SUBJECT" "$EMAIL" < $EMAILMESSAGE
When I run doandmail.sh using ./doandmail.sh an email with result was sent. I've added this line in cron @hourly /custom/doandmail.sh and I got blank email every hour.
I'm fully novice, need your advice to solve.
A: I'm going to say that the problem is in ./update.sh > mail.txt
Cron can be funny with paths - make these be absolute paths and try again.
A: The line before the interpreter directive - before the #! line - is wrong but may not be your problem. The #! is only special as the first two characters of a executable file, and identifies what program should open it (/bin/bash in this case). The shells will tend to try to interpret scripts by defaulting to themselves, but this isn't reliable - especially for non-sh scripts.
Secondly, http://www.talisman.org/~erlkonig/documents/commandname-extensions-considered-harmful
So in /custom/update
#!/bin/bash
# update
/usr/bin/freshclam
maldet -b -a /home
then run: chmod +x /custom/update
In ./doandmail:
#!/bin/bash
# doandmail
SUBJECT="Shell Script" # these don't need to be uppercase
EMAIL="myemail@gmail.com" # ...though it doesn't hurt anything
EMAILMESSAGE="mail.txt" # usually only exported variable are upper.
/custom/update | /bin/mail -s "$SUBJECT" "$EMAIL" # no need for a tmp file.
Then: chmod +x doandmail
When your crontab runs, it won't have the same directory you're thinking, or even the same environment you might expect, unless you set them explicitly. It's most likely breaking on the ./update... line in doandmail. Hence the /custom/update above.
In your crontab:
@hourly /custom/doandmail
| |
doc_23536333
|
string svg = GetSvg();
byte[] bytes = Encoding.UTF8.GetBytes(svg);
Clipboard.SetData("image/svg+xml", svg); // idea 1
Clipboard.SetData("image/svg+xml", bytes); // idea 2
Based on my clipboard viewer tool, both techniques produce (almost) the same result--The XML text is there as expected under image/svg+xml, but it is prefixed with 43 bytes that are definitely not present in svg or bytes:
These bytes differ slightly depending on whether I write the text as a string or a byte array, so I suspect they are some sort of description of the data format. However, no SVG editor I have will accept the result for pasting. Is there more I need to do?
A: Those extra bytes looked an awful lot like a serialization header, so I hunted around and eventually found this note in the MSDN documentation for the Clipboard class (bolding mine):
An object must be serializable for it to be put on the Clipboard. If
you pass a non-serializable object to a Clipboard method, the method
will fail without throwing an exception. See
System.Runtime.Serialization for more information on serialization. If
your target application requires a very specific data format, the
headers added to the data in the serialization process may prevent the
application from recognizing your data. To preserve your data format,
add your data as a Byte array to a MemoryStream and pass the
MemoryStream to the SetData method.
That suggested an obvious course of action:
string svg = GetSvg();
byte[] bytes = Encoding.UTF8.GetBytes(svg);
MemorySteam stream = new MemoryStream(bytes);
Clipboard.SetData("image/svg+xml", stream);
That worked! Further, I can confirm that DataObject.SetData() will also accept a MemoryStream in case you are looking to push the image to the clipboard in both svg and bitmap form at the same time.
| |
doc_23536334
|
This is my JS Code
document.getElementById('mainnav-up').innerHTML =
"<div class='banner'>" +
"<a href='..\index.html'><div class='button'></div></a>" +
"</div>";
Which places a button on my HTML page under :
home/products/product1.html
<div id="mainnav-up"></div>
but instead of being taken to
home/index.html
I am instead taken to
home/products/..index.html
Which is non-existent.
If I then hard code the link into the home/products/product1.html page it takes me to the index page correctly, but I'd like to be able to just edit one piece of code for the whole website.
A: Change
<a href='..\index.html'>
to
<a href='../product1.html'>
| |
doc_23536335
|
Basically, find ./ -iname "*jar*" shows:
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/log4j-1.2.15.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/antlr-2.7.7.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/aopalliance-1.0.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/aspectjrt-1.6.10.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/commons-dbcp-20030825.184428.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/commons-fileupload-1.3.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/commons-io-2.2.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/commons-lang3-3.1.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/dom4j-1.6.1.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/hibernate-commons-annotations-4.0.1.Final.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/hibernate-core-4.2.1.Final.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/hibernate-entitymanager-4.2.1.Final.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/hibernate-jpa-2.0-api-1.0.1.Final.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/jackson-core-asl-1.9.13.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/jackson-mapper-asl-1.9.13.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/javassist-3.15.0-GA.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/javax.inject-1.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/jboss-logging-3.1.0.GA.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/jboss-transaction-api_1.1_spec-1.0.1.Final.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/jcl-over-slf4j-1.6.6.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/json-path-0.9.1.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/json-smart-1.2.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/jstl-1.2.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/ognl-3.0.6.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/opencsv-2.3.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/postgresql-9.3-1100-jdbc41.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/slf4j-api-1.6.6.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/slf4j-log4j12-1.6.6.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/spring-aop-3.1.1.RELEASE.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/spring-asm-3.1.1.RELEASE.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/spring-beans-3.1.1.RELEASE.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/spring-context-3.1.1.RELEASE.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/spring-context-support-3.1.1.RELEASE.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/spring-core-3.1.1.RELEASE.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/spring-expression-3.1.1.RELEASE.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/spring-jdbc-3.1.1.RELEASE.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/spring-security-config-3.2.0.RELEASE.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/spring-security-core-3.2.0.RELEASE.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/spring-security-web-3.2.0.RELEASE.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/spring-tx-3.1.1.RELEASE.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/spring-web-3.2.6.RELEASE.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/spring-webmvc-3.1.1.RELEASE.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/thymeleaf-2.1.2.RELEASE.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/thymeleaf-spring3-2.1.2.RELEASE.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/tomcat-jdbc-7.0.47.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/tomcat-juli-7.0.47.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/xpp3_min-1.1.3.4.O.jar
./target/hp-dsat-1.0.0-BUILD-SNAPSHOT/WEB-INF/lib/xstream-1.2.jar
I don't see a specific jar file for my project though. Should I see something like hp-dsat.jar?
A: there should be a WAR or JAR file in the target folder named hp-dsat-1.0.0-BUILD-SNAPSHOT. That would be the one you put into the webapps folder.
You have 2 choices, either copy the entire hp-dsat-1.0.0-BUILD-SNAPSHOT folder or the WAR file.
| |
doc_23536336
|
import requests
from bs4 import BeautifulSoup
import csv
class ZiwiScraper:
results = []
headers = {
'authority': '99petshops.com.au',
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'accept-language': 'en,ru;q=0.9',
'cache-control': 'max-age=0',
# Requests sorts cookies= alphabetically
# 'cookie': 'TrackerGuid=f5419f8d-632a-46b1-aa04-eed027d03e89; _ga=GA1.3.1385392550.1666770065; _gid=GA1.3.1560927430.1666770065',
'referer': 'https://www.upwork.com/',
'sec-ch-ua': '"Chromium";v="104", " Not A;Brand";v="99", "Yandex";v="22"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"Linux"',
'sec-fetch-dest': 'document',
'sec-fetch-mode': 'navigate',
'sec-fetch-site': 'cross-site',
'sec-fetch-user': '?1',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.114 YaBrowser/22.9.1.1110 (beta) Yowser/2.5 Safari/537.36',
}
def fetch(self, url):
print(f'HTTP GET request to URL: {url}', end='')
res = requests.get(url, headers=self.headers)
print(f' | Status Code: {res.status_code}')
return res
def parse(self, html):
soup = BeautifulSoup(html, 'lxml')
titles = [title.text.strip() for title in soup.find_all('h2')]
low_prices = [low_price.text.split(' ')[-1] for low_price in soup.find_all('span', {'class': 'hilighted'})]
store_names = []
stores = soup.find_all('p')
for store in stores:
store_name = store.find('img')
if store_name:
store_names.append(store_name['alt'])
shipping_prices = [shipping.text.strip() for shipping in soup.find_all('p', {'class': 'shipping'})]
price_per_hundered_kg = [unit_per_kg.text.strip() for unit_per_kg in soup.find_all('p', {'class': 'unit-price'})]
other_details = soup.find_all('div', {'class': 'pd-details'})
for index in range(0, len(titles)):
try:
price_per_100_kg = price_per_hundered_kg[index]
except:
price_per_100_kg = ''
try:
lowest_prices = low_prices[index]
except:
lowest_prices = ''
for detail in other_details:
detail_1 = [pr.text.strip() for pr in detail.find_all('span', {'class': 'sp-price'})]
for idx, price in enumerate(detail_1):
self.results.append({
'title': titles[index],
'lowest_prices': lowest_prices,
f'lowest_price_{idx}': detail_1[idx],
'store_names': store_names[index],
'shipping_prices': shipping_prices[index],
'price_per_100_kg': price_per_100_kg,
})
# json_object = json.dumps(self.results, indent=4)
# with open("ziwi_pets_2.json", "w") as outfile:
# outfile.write(json_object)
def to_csv(self):
with open('ziwi_pets_2.csv', 'w') as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=self.results[0].keys())
writer.writeheader()
for row in self.results:
writer.writerow(row)
print('Stored results to "ziwi_pets_2.csv"')
def run(self):
for page in range(1):
url = f'https://99petshops.com.au/Search?brandName=Ziwi%20Peak&animalCode=DOG&storeId=89%2F&page={page}'
response = self.fetch(url)
self.parse(response.text)
self.to_csv()
if __name__ == '__main__':
scraper = ZiwiScraper()
scraper.run()
Every time I run the script it gives me the above code I got ValueError: dict contains fields not in fieldnames: 'lowest_price_1'. csv file however generating with one entry only.
title,lowest_prices,lowest_price_0,store_names,shipping_prices,price_per_100_kg
Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg,$57.75,$64.60,Woofers World,+$9.95 shipping,$5.78 per 100g
I tried to output it as json just to see the data formation and it was also not as I expected.
[
{
"title": "Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg",
"lowest_prices": "$57.75",
"lowest_price_0": "$64.60",
"store_names": "Woofers World",
"shipping_prices": "+$9.95 shipping",
"price_per_100_kg": "$5.78 per 100g"
},
{
"title": "Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg",
"lowest_prices": "$57.75",
"lowest_price_1": "$64.60",
"store_names": "Woofers World",
"shipping_prices": "+$9.95 shipping",
"price_per_100_kg": "$5.78 per 100g"
},
{
"title": "Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg",
"lowest_prices": "$57.75",
"lowest_price_2": "$64.95",
"store_names": "Woofers World",
"shipping_prices": "+$9.95 shipping",
"price_per_100_kg": "$5.78 per 100g"
},
]
I expected something like this:
[
{
"title": "Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg",
"lowest_prices": "$57.75",
"lowest_price_0": "$64.60",
"lowest_price_1": "$64.60",
"lowest_price_2": "$64.95",
"store_names": "Woofers World",
"shipping_prices": "+$9.95 shipping",
"price_per_100_kg": "$5.78 per 100g"
},
]
Can anyone please help me out here? Thanks.
A: You were creating csv header based only upon the first result, which didn't contained whole set of unique keys.
Change to_csv function to this to resolve your problem:
def to_csv(self):
key_list = list()
for key_list_for_one_element in [list(x.keys()) for x in self.results]:
key_list.extend(key_list_for_one_element)
key_list = set(key_list)
with open('ziwi_pets_2.csv', 'w') as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=key_list)
writer.writeheader()
for row in self.results:
writer.writerow(row)
print('Stored results to "ziwi_pets_2.csv"')
A: You need to pass as fieldnames all the keys any item in self.results might have. The error should go away if you just add that into your to_csv function
def to_csv(self):
fNames = list(set([k for r in self.results for k in r.keys()]))
fNames.sort(key=lambda r: (
-1*(int(r.replace('lowest_price_', ''))+1) if 'lowest_price_' in r else 0, r
), reverse=True)
with open('ziwi_pets_2.csv', 'w') as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=fNames)
writer.writeheader()
for row in self.results:
writer.writerow(row)
print('Stored results to "ziwi_pets_2.csv"')
(The sort statement is optional - it's just to make sure the columns are in a certain order.)
As for this bit
I expected something like this
the for idx, price in enumerate(detail_1) in the parse function is appending a new line for every lowest_price_idx value of each detail. To get get them all in one line, change the outer loop to
for detail in other_details:
result_i = {
'title': titles[index],
'lowest_prices': lowest_prices,
'store_names': store_names[index],
'shipping_prices': shipping_prices[index],
'price_per_100_kg': price_per_100_kg,
}
detail_1 = [pr.text.strip() for pr in detail.find_all('span', {'class': 'sp-price'})]
for idx, price in enumerate(detail_1):
result_i[f'lowest_price_{idx}'] = detail_1[idx]
self.results.append(result_i)
Then, your csv output will go from
to
and you json would look, as expected
{
"title": "Ziwi Peak Dog Air-Dried Free Range Chicken Recipe 1Kg",
"lowest_prices": "$57.75",
"store_names": "Woofers World",
"shipping_prices": "+$9.95 shipping",
"price_per_100_kg": "$5.78 per 100g",
"lowest_price_0": "$3.87",
"lowest_price_1": "$4.49",
"lowest_price_2": "$5.09",
"lowest_price_3": "$5.95",
"lowest_price_4": "$5.99"
}
(printed using print(json.dumps([r for r in scraper.results if len(r) == 10][0], indent=4)))
| |
doc_23536337
|
org.springframework.mail.MailSendException: Failed messages: com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. b10sm22671312wmi.34 - gsmtp
Here is the code that I'm using for sending email:
MailRequest mailRequest = new MailRequest();
mailRequest.setSubject(messageByLocale.getMessage("mail.subject.forgetpassword"));
mailRequest.setTemplateName(messageByLocale.getMessage("mail.template.forgetpassword"));
mailRequest.setToEmail(tbNstyleloyalty.getEmail());
Map<String, Object> map = new HashMap<>();
map.put("tbNstyleloyalty", tbNstyleloyalty);
mailingConfig.sendEmail(mailRequest, map);
And my sendEmail method is:
@Async
public void sendEmail(MailRequest mailRequest, Map<String, Object> model) {
MimeMessagePreparator preparator = new MimeMessagePreparator()
{
@Override
public void prepare(MimeMessage mimeMessage) throws Exception {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
message.setTo(mailRequest.getToEmail());
message.setSubject(mailRequest.getSubject());
message.setText(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,templatePath + mailRequest.getTemplateName() + ".vm", ApplicationConstants.CHARSET_UTF8, model),true);
}
};
this.javaMailSender.send(preparator);
}
Please, help me to overcome from this issue.
Thank you!
A: Thank you guys for your answers. All answers given by you were correct but I was unable to understand where I should add this property.
Finally I add:
spring.mail.properties.mail.smtp.starttls.enable = true
to my property file and then I got success.
A: Probably you are missing either of the 2 points:
*
*Set the following property in your email request.
props.put("mail.smtp.starttls.enable", "true");
*You are probably attempting to use mail server on port 25 to deliver mail to a third party over an unauthenticated connection.You will need to ask your SMTP client to connect to an authenticated connection. (look if your port number is for TLS connection)
A: I guess that your mail server uses STARTSSL for authentication (as the exception message implies).
Maybe this post helps:
JavaMail smtp properties (for STARTTLS)
A: i think below code is simple enough to be used for mailing functionality
//headers
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
//code
Session mailSession = new SmtpImpl().getSession();
Message simpleMessage = new MimeMessage(mailSession);
MimeMultipart multipart = new MimeMultipart("related");
BodyPart messageBodyPart = new MimeBodyPart();
try {
simpleMessage.setFrom(new InternetAddress("from address")));
simpleMessage.addRecipient(RecipientType.TO, new InternetAddress("to address"));
String SENDCC_GET = "person1@gmail.com,person2.gmail.com";
String [] SENDCC = SENDCC_GET.split(",");
InternetAddress[] addressCC = new InternetAddress[SENDCC.length];
for (int i = 0; i < SENDCC.length; i++) {
addressCC[i] = new InternetAddress(SENDCC[i]);
}
//for bcc
simpleMessage.setRecipients(Message.RecipientType.BCC, addressCC);
//for cc
//simpleMessage.setRecipients(Message.RecipientType.CC, addressCC);
String message = null;
String subject = null;
subject = "email subject";
simpleMessage.setSubject(subject);
message = "message body";
messageBodyPart.setContent(message, "text/html; charset=utf-8");
multipart.addBodyPart(messageBodyPart);
simpleMessage.setContent(multipart);
Transport.send(simpleMessage);
} catch (AddressException e) {
LOGGER.error("******Error while sending - Email: Address Exception::: " + e);
} catch (MessagingException e) {
LOGGER.error("******Error while sending - Email: Messaging Exception::: " + e);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
//SmtpImpl.java
public Session getSession(){
Properties props = new Properties();
props.put("mail.smtp.host", EmailUtilityParam.getSmtpHostName());
props.put("mail.smtp.port", EmailUtilityParam.getSmtpPort());
props.put("mail.smtp.user", EmailUtilityParam.getAuthenticationId());
props.put("mail.smtp.password", EmailUtilityParam.getAuthenticationPassword());
props.put("mail.debug", "false");
Session mailSession = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(EmailUtilityParam
.getAuthenticationId(), EmailUtilityParam
.getAuthenticationPassword());
}
});
return mailSession;
}
SMTP dev tool can be used for development and keep it in default values for testing whether it works
HOST = localhost
PORT = 25
USER(authentication id) = //empty string
PASSWORD(authentication password) = //empty string
| |
doc_23536338
|
But when running the application on a device with iOS 8, I am running into problems. I am unable to get the Alert View where the user can select to "Allow Notifications from App X".
But, the device token registration call is being called successfully when the user opts in to push notifications and the device is successfully registering an Installation object with a valid device token. Notifications are also being sent to the device.
If I go into Settings->Notifications->My App and turn the Notifications On or Off, it doesnt make a difference the notifications are still being sent through.
This is the code I am using to register for notifications:
let settings = UIUserNotificationSettings(forTypes: UIUserNotificationType([.Alert, .Badge, .Sound]), categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
A: Found the solution here on stackoverflow... Registration for notifications are sent only once on devices running versions older than iOS 9.
As answered by another user here...
"The first time a push-enabled app registers for push notifications, iOS asks the user if they wish to receive notifications for that app. Once the user has responded to this alert it is not presented again unless the device is restored or the app has been uninstalled for at least a day."
OR
"If you want to simulate a first-time run of your app, you can leave the app uninstalled for a day. You can achieve the latter without actually waiting a day by setting the system clock forward a day or more, turning the device off completely, then turning the device back on."
Reference Links:
Push Notification ON or OFF Checking in iOS
https://developer.apple.com/library/ios/technotes/tn2265/_index.html#//apple_ref/doc/uid/DTS40010376-CH1-TNTAG42
| |
doc_23536339
|
Is there any way to repeat a block of HTML code using only Ruby / ERB?
In Rails I would do this:
<% content_for :mycontent do %>
some html code
that I want to capture
etc
<% end %>
Then, here, in the same template, I can reuse the block...
<%= content_for :mycontent %>
Multiple times...
<%= content_for :mycontent %>
Is there any equivalent without Rails?
| |
doc_23536340
|
The below code is generated by default:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
A: Web Api is design to be a restful Api and when creating a restful Api one of the most important things is to have a correct relationship between the URL and the HTTP methods.
For each entity (controller) there should be a GET, POST, PUT and DELETE method which all are operating on the entity level.
If we create a controller named UserController, this should then expose the entity User on the http level.
To fullfill the restful principle the controller should be able to handle most of these request
GET api/user
GET api/user/id
POST api/user
PUT api/user
PUT api/user/id
DELETE api/user
DELETE api/user/id
By default, Web API is designed to support these restful requests and that's most likely why the default route is set to only be "api/{controller}/{id}" as that is the minimum requirement to support a restful implementation of an api
A: as indicated in official doc, In Web API, the usual convention is to omit "{action}".
https://learn.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/routing-and-action-selection
| |
doc_23536341
|
New question how I can add and remove from the image adapter... I need the behavior to be like one pic with a and I add same pic with text ab so there should be 2 pics and then i can remove the one with a..
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class AlbumAdapter extends BaseAdapter {
private Context mContext;
private ArrayList albNames;
public AlbumAdapter(Context c, ArrayList albNames) {
mContext = c;
this.albNames = albNames;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
/* public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(10, 10, 10, 3);
}
else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
*/
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.album_image, null);
}
else {
view = convertView;
}
ImageView imgView = (ImageView) view.findViewById(R.id.icon_image);
imgView.setLayoutParams(new LinearLayout.LayoutParams(50, 50));
imgView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imgView.setPadding(10, 10, 10, 3);
TextView albNameView = (TextView) view.findViewById(R.id.icon_text);
if (albNames.size() > 0) {
for (int i = 0; i < albNames.size(); i++) {
imgView.setBackgroundResource(R.drawable.folder);
albNameView.setText((String)albNames.get(i));
}
}
return view;
}
// references to our images
public Integer[] mThumbIds = { R.drawable.folder};
}
A: Try
imgView.setLayoutParams(new LinearLayout.LayoutParams(85, 85));
EDIT
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class AlbumAdapter extends BaseAdapter {
private Context mContext;
public AlbumAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
/* public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(10, 10, 10, 3);
}
else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
*/
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.album_image, null);
}
else {
view = convertView;
}
ImageView imgView = (ImageView) view.findViewById(R.id.icon_image);
imgView.setLayoutParams(new LinearLayout.LayoutParams(85, 85));
imgView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imgView.setBackgroundResource(R.drawable.a);
TextView albNameView = (TextView) view.findViewById(R.id.icon_text);
albNameView.setText("as");
return view;
}
// references to our images
public Integer[] mThumbIds = { R.drawable.a };
}
A: 'imgView' is the child of ConvertView which is inflated from R.layout.album_image which is nothing but a LinearLayout. So while setting layout params it needs to be parents ViewGroup type. So LinearLayout.LayoutParams works fine.
Suppose you wanted to set the size of 'ConvertView' then in that case it needs to be GridView.LayoutParams, becoz 'ConvertView' is being added to parent which is GridView.
Hope u got it..!!
| |
doc_23536342
|
I noticed that it was changing the line endings from the default Windows line ending. Specifically, when I was doing git diffs, I would see stuff like this:
Notice the ^M
So I read an article about how to fix this and it suggested the following git config change:
git config --global core.autocrlf true
But I'm still seeing these line endings being used when I update my code.
A: The only thing you would read from me is: "What is the correct core.autocrlf setting I should use?"
Meaning:
git config --global core.autocrlf false
Then, as mentioned in "Disable git EOL Conversions":
git add --renormalize .
Using .gitattributes core.eol directive is the right approach to fix eol.
And you can check what is applied to which file with:
git ls-files --eol
| |
doc_23536343
|
var model = new { reportid = rid, refno = refernumber};
return View(model );
but when i try to access it in view like this:
@Model.reportid
I get, object doesn't contain property reportid
How can I pass multiple values without using viewbag ?
A: Another way to accomplish this task - is to use ExpandoObject.
dynamic model = new System.Dynamic.ExpandoObject();
model.reportid = 123
model.refno = 456;
Set the view model type to dynamic:
@model dynamic
@Model.reportid
@Model.refno
A: Well, i strongly recommend you to use ViewModel class. But if for some reason you have phobia of extra viewmodel classes, you can use C# feature called Tuple
var model = Tuple.Create(firstObject, secondObject)
and then your view will be of type Tuple, for example
@model Tuple<int, string>
and you can access them like this
@Model.Item1
And then you can congratulate yourself, you have achieved nice mess with hidden meaning :)
| |
doc_23536344
|
I have been using the method:
componentWillReceiveProps(nextProps){
this.setState({key:nextProps});
console.log(this.state);
}
The console shows me that nextProps is the defined value, but this.state.key remains undefined.
Thanks!
A: The console log this.state shows undefined because setState is asynchronous. Hence when you perform setState it does not update state immediately and that's why console log doesn't show updated state.
You should do as follows:
componentWillReceiveProps(nextProps){
this.setState({key:nextProps}, () => {
console.log(this.state);
});
}
Here when setState will take place the callback defined as a second parameter gets called and then we have updated state.
| |
doc_23536345
|
window.addEventListener('load', function(){
function interva15(){
var submitorder = document.getElementById("orderSubmit");
submitorder.click();
}
var id5 = interva15();
The website I'm trying to use the script on elements:
<input alt="Submit Order" src="https://www.websitename.com/checkout/ckout_submit_order.gif" type="image" id="orderSubmit" name="orderSubmit" width="150" height="28" />
it was to my understand that you must correlate an action with the correct element on the page to create an action? Again, I do apologize, pretty new to this.
A: in Html
<form action="desired url" type="POST" id="submitform">
<input alt="Submit Order" src="https://www.websitename.com/checkout/ckout_submit_order.gif" type="image" id="orderSubmit" name="orderSubmit" width="150" height="28" />
</form>
in js
window.addEventListener('load', function(){
function interva15(){
var submitorder = document.getElementById("submitform");
submitorder.submit();
}
var id5 = interva15();
A: *
*window.addEventListener('load', function() { means "when the window has loaded, do whatever is in the function.
*var submitorder = document.getElementbyId("orderSubmit"); finds an element in the DOM that has the id, orderSubmit and stores it in the variable submitorder.
*submitorder.click() calls the function that would be called when that element is clicked.
| |
doc_23536346
|
The html page uses an ajax request to get the data and echos it back to the html page - but it is returned as text (xmlhttp.responseText), which I can display, but can't easily manipulate.
I would like to return the data as an array that I can process in JavaScript.
Is there a way for an ajax request to include the response as a variable, instead of as raw text?
If I can provide more information to make it easier to answer, let me know!
thanks!
A: Check PHP, JSON and JavaScript usage
| |
doc_23536347
|
tell application "Mail"
my cleanup(mailbox "Archives")
end tell
on cleanup(box)
tell application "Mail"
if (count of mailboxes of box) > 0 then
repeat with mbx in mailboxes of box
my cleanup(mbx)
end repeat
else
if (count of messages of box) = 0 then delete box
end if
end tell
end cleanup
The "delete box" causes error:
error "Mail got an error: Can’t get item 1 of every mailbox of item 1 of every mailbox of mailbox \"Archives\"." number -1728 from item 1 of every mailbox of item 1 of every mailbox of mailbox "Archives"
A: There are two issues:
• The index variable mbx in the line
repeat with mbx in mailboxes of box
is a reference like item 1 of every mailbox of box rather than mailbox "something" of box. You have to dereference the variable before passing it to the handler with contents of.
• In the same line you'll get an error if for example item 1 has been deleted, item 2 is now item 1 and there is no item 2 anymore. To avoid this use the keyword get to retrieve a copied reference which isn't affected by deletions during the loops.
tell application "Mail"
my cleanup(mailbox "Archives")
end tell
on cleanup(box)
tell application "Mail"
if (count of mailboxes of box) > 0 then
repeat with mbx in (get mailboxes of box)
my cleanup(contents of mbx)
end repeat
else
if (count of messages of box) = 0 then delete box
end if
end tell
end cleanup
| |
doc_23536348
|
*
*I only have one version of python
*I'm not using a virtual environment
*C:\Python27 and C:\Python27\Scripts are included in my path
*I can import django in python and get the version number
*I can import management from django.core in python
*my manage.py was created using pydev and begins with "#!/usr/bin/env python" as seems appropriate according to other answers
*I have already uninstalled and reinstalled django via pip
It is possible I might have messed something up when trying to change from 32 bit to 64 bit python in order to interface with Matlab.
A: Start python from shell, the same way you did when the import works:
>>> import os
>>> os.environ['PYTHONPATH']
'/the/python/path'
Copy this path, and in your manage.py add:
sys.path.append('/the/python/path')
from django.core.management import execute_from_command_line
| |
doc_23536349
|
Using netbeans debug mode I can pause application and get some information at any time, but when the application hangs mouse no longer works (there is no cursor). Is it possible to get the mouse back without stopping the application or debug using only keyboard?
A: So far I have found 5 solutions to this problem:
*
*This may or may not work depending on your IDE and operating system - if you are able to switch into the IDE window you can try to use keyboard shortcuts to pause execution and then evaluate expression to ungrab the mouse. The expression you need to evaluate in that case is Mouse.setGrabbed(false). This is also useful when breakpoint hits and your mouse is stuck within LWJGL window. Since I first asked this question I switched to IntelliJ IDEA so here is how to do it in that IDE: alt+u to open "run" menu, then select "pause", then step through the code one line further using F7 or F8, and then press alt+u again and select "evaluate expression".
*Configure breakpoint to evaluate Mouse.setGrabbed(false).
Alternatively you can set a breakpoint and apply a condition with code that ungrabs the mouse, for example:
package com.acne;
import org.lwjgl.input.Mouse;
public class DebugHelper {
public static boolean restoreMouse() {
Mouse.setGrabbed(false);
return true;
}
}
Then set your breakpoint condition to com.acne.DebugHelper.restoreMouse()
*Remote debugging - good solution if you have access to a second machine and know that you will need remote debugging before starting your program.
On the first computer start it in debug mode and attach the debugger on the second computer.
*[linux only] By starting second X session
Switch to tty1/2/... using ctrl+alt+Fn (for example ctr+alt+F1 for tty1), login and run command startx. This should start new X session, eighter in the tty you are in or in tty8. The you can switch between graphical environments using ctrl+alt+Fn (usially F7 and F8).
Unfortunately this is not a good solution if your application takes so much memory that you can't run second X session.
*[linux only] You can add a second mouse pointer. Your LWJGL (or OpenGL) application will grab only one mouse pointer and you will have the second one for you.
Unfortunately most window managers don't officially support multiple mouse pointers, but it doesn't mean that it doesn't work. It does work, but there are some annoying glitches.
You can add a second mouse pointer using xinput:
*
*Run xinput create-master pointer-name. A second mouse pointer should appear on the screen. This creates keyboard/pointer pair, you don't need to do anything with the second added keyboard. It won't be attached to any physical device.
*Run xinput list to list all your devices
On my laptop it looks like this:
⎡ Virtual core pointer id=2 [master pointer (3)]
⎜ ↳ Virtual core XTEST pointer id=4 [slave pointer (2)]
⎜ ↳ ETPS/2 Elantech Touchpad id=14 [slave pointer (2)]
⎜ ↳ A4Tech USB Mouse id=11 [slave pointer (2)]
⎣ Virtual core keyboard id=3 [master keyboard (2)]
↳ Virtual core XTEST keyboard id=5 [slave keyboard (3)]
↳ Power Button id=6 [slave keyboard (3)]
↳ Video Bus id=7 [slave keyboard (3)]
↳ Video Bus id=8 [slave keyboard (3)]
↳ Power Button id=9 [slave keyboard (3)]
↳ Lenovo EasyCamera id=10 [slave keyboard (3)]
↳ Ideapad extra buttons id=12 [slave keyboard (3)]
↳ AT Translated Set 2 keyboard id=13 [slave keyboard (3)]
⎡ new-mouse pointer id=15 [master pointer (16)]
⎜ ↳ new-mouse XTEST pointer id=17 [slave pointer (15)]
⎣ new-mouse keyboard id=16 [master keyboard (15)]
↳ new-mouse XTEST keyboard id=18 [slave keyboard (16)]
The newly added mouse pointer (master device) has id=15. I have a touchpad and an external mouse so I can attach one of them to the new cursor and leave the other attached to the old cursor. If you don't have 2 physical devices - you can leave the old pointer with no physical device attached.
*Now run xinput reattach slave-device-id master-device-id. For example if I want to attach my touchpad to the new pointer: xinput reattach 14 15
After this you should be able to control the newly added pointer.
*When you no longer want the second mouse pointer use xinput remove-master master-device-id, in my case it would be xinput remove-master 15
*sometimes you may need to reattach the device to the previous master device.
Note: It's better to add the new pointer before you start debugging.
I also noticed that some window managers have some issues with multiple cursors that cause all kinds of unexpected bugs - for example "typing stops working", or typing works but in the wrong window. So leaving multiple cursors enabled normally may not be a good option.
A: For completeness' sake:
If you find yourself stuck and desperately don't want to stop debugging, you can add this snippet somewhere in your code:
org.lwjgl.input.Mouse.setGrabbed(false);
then execute it via Debug commands.
For example in Eclipse:
Use Run>Execute (Default shortcut: Ctrl+U) or Run>Display (Default shortcut: Ctrl+Shift+D)
It might not work always, but it might save you a debug session.
[Don't forget to remove it from your code again ;)]
| |
doc_23536350
|
Here is a snippet of the part of the code that I think may be generating the issue:
int BIN_SIZE=(2*width)/bins;
//binCounts and binCounts2 store the fragment counts in each bin. mask=1 flags histone modification site
float **binVals;
binVals = (float **)malloc(chromNum*sizeof(int *));
//Initialize the arrays
totalBinNum = 0;
for (i=0;i<chromNum;i++)
{
totalBinNum += chromInfo[i].chromSize/BIN_SIZE+1;
binVals[i] = (float *)malloc((chromInfo[i].chromSize/BIN_SIZE+1)*sizeof(float));
memset(binVals[i], 0, (chromInfo[i].chromSize/BIN_SIZE+1)*sizeof(float));
}
If you know some easy catch on what may be causing the error please let me know? Otherwise it could also be in some other part of the code leading to not a smart Q :(
A: It would be more precise to do so:
binVals = malloc(chromNum*sizeof(float *));
But it is not likely that this is the cause of the error, as you can expect that 2 pointers, even if to different types int* and float*, will have the same size. In short, the source of the error is probably somewhere else in your code.
Some other suggestions:
*
*I would suggest removing the other type cast in the other malloc.
*I would use some temporary variable to store chromInfo[i].chromSize/BIN_SIZE+1, so that you do not have to repeat the expression 3 times with very likely cut and past errors.
*You can compact the malloc and the memset to zero in one calloc call.
| |
doc_23536351
|
In my example use case I want to generate some random numbers and use these as the input to a function. I would like to save the the random numbers as they key and the function output given these numbers as the value.
Something like the following, however this implementation would generate different arrays of random numbers for the key and value.
{
tuple(sorted(rng.choice(1000, size=10, replace=False))): my_function(sorted(rng.choice(1000, size=10, replace=False)))
for i in range(sample_size)
}
Reproducable example:
import numpy as np
rng = np.random.default_rng()
sample_size = 3
def my_function(x: np.array) -> int:
return sum(x)
dictionary = {
tuple(sorted(rng.choice(1000, size=3, replace=False))): my_function(sorted(rng.choice(1000, size=3, replace=False)))
for i in range(sample_size)
}
An example output would be:
{(43, 70, 788): 2386, (56, 151, 613): 1074, (486, 645, 647): 2038}
The sum of the keys is not equal to the value because different random numbers were used. My desire is that the same random numbers are stored as the key and used in the function call. In this example it would mean that the sum of the keys was equal to the value.
A: If you are using Python3.8 or newer you can use Assignment Expressions
{tuple((arr := sorted(rng.choice(1000, size=10, replace=False)))): my_function(arr) for i in range(sample_size)}
A: In python 3.8+, you can use the := operator:
{(n:=tuple(sorted(rng.choice(1000, size=10, replace=False)))):my_function(n) for _ in range(sample_size)}
A: Just re-write your code to use a generator expression:
dictionary = {tuple(v): my_function(v) for v in (sorted(rng.choice(1000, size=3, replace=False)) for _ in range(sample_size))}
Output (of a single run)
{(92, 325, 573): 990, (361, 840, 913): 2114, (470, 669, 891): 2030}
As an alternative, is to use map:
dictionary = {tuple(v): my_function(v) for v in
map(lambda _: sorted(rng.choice(1000, size=3, replace=False)), range(sample_size))}
print(dictionary)
Output (of a single run)
{(45, 157, 889): 1091, (73, 353, 779): 1205, (275, 282, 633): 1190}
Both solutions will work in Python regardless of the version.
| |
doc_23536352
|
The current implementation we had with the old DatePickerDialog
val calendar = Calendar.getInstance()
val year = calendar[Calendar.YEAR]
val month = calendar[Calendar.MONTH]
val day = calendar[Calendar.DAY_OF_MONTH]
val datePickerDialog = DatePickerDialog(appContext,
R.style.AppDatePicker,
dateSetListener,
year,
month,
day)
//Oldest date will be 2009
calendar.add(Calendar.YEAR, 2009 - year)
datePickerDialog.datePicker.minDate = calendar.timeInMillis
//Latest date will be the current date
datePickerDialog.datePicker.maxDate = System.currentTimeMillis()
// datePickerDialog.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
//Pop up the DatePicker dialog
datePickerDialog.show()
Additional possible improvement is to limit the supported date by specifying the date statically.
Something like
val startDate = "01/01/2009"
val endDate = "03/27/2022"
calendarPicker.minDate = Date(startDate)
calendarPicker.maxDate = Date(endDate)
Currently looking on CalendarConstraints.DateValidator and CalendarConstraints.Builder() but do not know how to work with it base on my requirements.
A: I don't know if you still need it, but maybe it will help others too.
I had a similar problem where I needed only dates in the range from the previous day to 45 days behind the current date to be enabled. That is, today, January 18th, the calendar would only be enabled from 12-05-2022 to 01-17-2023.
I did it like this:
val dateValidatorMin: DateValidator =
DateValidatorPointForward.from(
Calendar.getInstance().timeInMillis - 45.days.toLong(DurationUnit.MILLISECONDS))
val dateValidatorMax: DateValidator =
DateValidatorPointBackward.before(
Calendar.getInstance().timeInMillis - 1.days.toLong(DurationUnit.MILLISECONDS))
enter code here
val dateValidator: DateValidator = CompositeDateValidator.allOf(listOf(dateValidatorMin, dateValidatorMax))
val constraints: CalendarConstraints =
CalendarConstraints.Builder()
.setValidator(dateValidator)
.build()
val builder = MaterialDatePicker.Builder.dateRangePicker()
.setCalendarConstraints(constraints)
.setTitleText(getString(R.string.label_select_date_range))
val picker = builder.build()
And the result was like this:
Hope this helps.
| |
doc_23536353
|
private async Task<bool> myTask0() {
var val2 = await myTask2();
var val3 = await myTask3();
return true;
}
where:
private async Task<bool> myTask1() {
//run some tasks in paralell
var myParallel= arrayValues.Select(fileBEanListItem => manageSrcFilesDownload().ToList();
return true;
}
private async Task<bool> myTask2() {
return await myTask3();
}
So I'd like to gave the option to cancel myTask0 with all tasks in it - just abort it! Is there a solution:
I am trying:
var ts = new CancellationTokenSource();
CancellationToken ct = ts.Token;
await Task.Factory.StartNew(async () => {
await myTask0();
},ct);
and when I need to close it, I use ts.Cancel(true); but no effect, tasks are running anyway.
A: Cancellation is cooperative. So, you should pass the CancellationToken down through your methods:
private async Task<bool> myTask0(CancellationToken token) {
var val2 = await myTask2(token);
var val3 = await myTask3(token);
return true;
}
private async Task<bool> myTask1(CancellationToken token) {
//run some tasks in paralell
var myParallel= arrayValues.Select(fileBEanListItem => manageSrcFilesDownload(token).ToList();
return true;
}
private async Task<bool> myTask2(CancellationToken token) {
return await myTask3(token);
}
And so on, until you either pass the token to APIs that can take it (e.g., file download), or until you have your own code that uses CancellationToken.ThrowIfCancellationRequested or CancellationToken.Register to respond to cancellation.
On a side note, StartNew is an anti-pattern. As I explain on my blog, you should use Task.Run instead. In particular, the CancellationToken parameter (for both StartNew and Run) only cancels the scheduling of the delegate; they won't abort your code. For proper cancellation support, you have to write code that responds to a CancellationToken.
A: In addition to Stephen Cleary
MSDN states:
In the Task classes, cancellation involves cooperation between the user delegate, which represents a cancelable operation and the code that requested the cancellation. A successful cancellation involves the requesting code calling the CancellationTokenSource.Cancel method, and the user delegate terminating the operation in a timely manner.
| |
doc_23536354
|
def calculateSum(a, x, y):
s = 0;
for i in range(0,x+1):
for j in range(0,y+1):
s = s + a[i][j];
print(s)
return s
def check(a):
arr = []
x = 0
y = 0
for i in range(len(a)):
row = []
y = 0
for j in range(len(a[i])):
row.append(calculateSum(a, x, y))
y = y + 1
x = x + 1
print(row)
check([[1, 2], [3, 4]])
calculateSum is the function that calculates sum of elements.
Now my question is, if the matrix size is huge then is there is a way to improve performance of the above program?
Update:
import numpy as np
def calculateSum(a, x, y):
return np.sum(a[x:,y:])
After using numpy I am getting error as TypeError: list indices must be integers or slices, not tuple if I use numpy
A: As the matrix dimensions increases, Efficiency will fall, the efficient way to deal with this is to parallelize the task of summing the values, this is possible because addition follows Associative property.
Luckily for you this parallelization is already implemented in a library known as numpy.
To get started with numpy, use pip install numpy To get an overview of the library visit: https://www.geeksforgeeks.org/numpy-in-python-set-1-introduction/
And for your question you will need to use function numpy.sum()
Edit:
Also as @Mad Physicist pointed out Numpy also has packed memory layout and the routines are implemented in C which boost its speed even further.
| |
doc_23536355
|
CloudChecker Gold;#System Administration;#NOC Monitoring;#ACDaaS
I'm trying to create a formula that finds each ;# and then does a carriage return (Alt+Enter).
I tried doing this, but it blanks out the whole cell. And the FIND formula just returns the index number of ; (which is 16 in the string above).
IF(FIND(";#", A1), CHAR(10), A1)
Any other ideas? The end goal should look like this in one cell:
CloudChecker Gold
System Administration
NOC Monitoring
ACDaaS
A: You can use Substitute function along with CHAR(10) like this:
=SUBSTITUTE(A1,";#",CHAR(10))
Note: You need to have "Wrap Text" enabled on the cell to actually see it being split in multiple lines. If wrap text is not enabled, you will see it in one line
| |
doc_23536356
|
A: To measure the time some code has taken, you either use time or clock.
The time command will run its script argument and return a description of how long the script took, in milliseconds (plus some descriptive text, which is trivial to chop off with lindex). If you're really doing performance analysis work, you can supply an optional count argument that makes the script be run repeatedly, but for just general monitoring you can ignore that.
The clock command lets you get various sorts of timestamps (as well as doing formatting, parsing and arithmetic with times). The coarsest is got with clock seconds, which returns the amount of time since the beginning of the Unix epoch (in seconds computed with civil time; that's what you want unless you're doing something specialized). If you need more detail, you should use clock milliseconds or clock microseconds. There's also clock clicks, but it's not typically defined what unit that's counting in (unless you pass the -milliseconds or -microseconds option). It's up to you to turn the timestamps into something useful to you.
If you're timing things on Tcl 8.4 (or before!) then you're constrained to using time, clock seconds or clock clicks (and even the -microseconds option is absent; there's no microsecond-resolution timer exposed in 8.4). In that case, you should consider upgrading to 8.5, as it's generally faster. Faster is Good! (If you're using pre-8.4, definitely upgrade as you're enormously behind on the support front.)
A: a very crude example would be something like:
set TIME_start [clock clicks -milliseconds]
...do something...
set TIME_taken [expr [clock clicks -milliseconds] - $TIME_start]
Using the time proc, you can do the following:
% set tt [time {set x [expr 23 * 34]}]
38 microseconds per iteration
A: To tell how long a function has taken, you can either use the time command (wrapped around the function call) or use clock clicks to get the current time before and then during the function. The time option is simple but can only time a whole function (and will only give you a time when the function returns). Using clock clicks can be done several times, but you will need to subtract the current time from the starting time yourself.
A: In case your really looking for some kind of profiler, have a look at the profiler package in Tcllib:
http://tcllib.sourceforge.net/doc/profiler.html
| |
doc_23536357
|
I tried as the following:
$(function(){
$('#logout-link').click(function(event){
event.preventDefault();
$.ajax({
url : $(this).attr('href'),
success : function(data){
$('#login-loader').hide();
location.reload(true);
},
error : function(){
$('#error-login').replaceWith('<div id="error-login" class="msg fail"><p>Une erreur a été rencontrée lors du deconnexion!</p></div>');
}
});
});
});
But it stills redirect me tho the other page.
How can prevent a link from redirecting to another page ?
A: Try with return false; instead of event.preventDefault(); But use it after ajax call.
A: You can modify hyperlink href like below. This method doesn't need any code in JQuery.
<a id="logout-link" href="javascript:void(0);">Logout</a>
A: Use
$(document).on("click", '#logout-link', function(event){
event.preventDefault();
// your ajax call here
});
| |
doc_23536358
|
Say below are the records and column A is customer number, column be is customer name and column C is country
CNumber CName CCountry
-----------------------------
0001 CustomerA USA
0002 CustomerB Japan
0003 CustomerC France
0004 CustomerD Hoss
In the SQL server database, there is already a tabled name COUNTRY which has all the countries there is listed there. What would be the query to compare that all the customers have a valid country name in column C. Like we can see customer 0004 has the country Hoss which is not a country. I need the query to tell me its an invalid country for the 0004 customer.
Thanks for any help.
A: if you want to list all the records with invalid country
SELECT *
FROM customer
WHERE CCountry NOT IN (SELECT CCountry
FROM country)
A: Basically you just want to know what customers have a country which is not in the country table. this tells you that:
SELECT *
FROM CUSTOMER
WHERE CUSTOMER.COUNTRY NOT IN (SELECT NAME FROM COUNTRY)
You could edit this to only return the ids of customers with invalid countries:
SELECT CUSTOMER.ID
FROM CUSTOMER
WHERE CUSTOMER.COUNTRY NOT IN (SELECT NAME FROM COUNTRY)
Or perhaps the country and id they customer has used. Then you could give a custom error message: "John unfortunately the country you specified: "asdf" is invalid."
| |
doc_23536359
|
Structure of Pi;
do{
wait(mutex);
Critical Section
signal(mutex);
Remainder section
}
while(1);
Considering N processes, does the above algorithm provides a good solution to the Critical Section problem?
My observation is that the first two conditions, i.e Mutual exclusion and Progress are being satisfied but not the bounded buffer. Is that correct?
A: Mutual exclusion is being satisfied if the semaphore maximum count is 1. Typically you would use a lock if you want mutual exclusion.
Progress isn't necessarily being satisfied. It depends on if the semaphore implementation guarantees fairness. On some operating systems, given two high priority threads and one with lower priority, it's possible for the low priority thread to be starved.
The bounded buffer problem is not being satisfied, but then what you show is not a producer-consumer program.
| |
doc_23536360
|
The documentation explains:
Action bar navigation modes are deprecated and not supported by inline
toolbar action bars. Consider using other common navigation patterns
instead.
What is the supposed replacement?
Also, is "inline toolbar action bars" a new concept? I don't think I've heard of it before.
A: The new Toolbar cannot be used for inflating multiple line objects, so it is impossible to add Tabs to it.
If you want to use a Toolbar like a TabWidget you can insert some Tab Objects to it, but only with the old Holo style.
Here there is a custom Library that uses v7 Toolbar like TabWidget with the new Material Design animations, but it uses the same methods from the old ActionBar Tabs, so you can attach your ViewPager to it.
A: For 'replacement' of deprecated ActionBar, I changed the type of my ActionBar-type variables to PagerTabStrip, as per (old code in comment):
// ActionBar bigActionBar;
PagerTabStrip bigActionBar;
A 'replacement' for ~actionBar's .selectTab(tabindex) was to use my associated ViewPager's .setCurrentItem(int) method, like this (old code in comment):
/*
ActionBar.Tab eventTab = bigActionBar.getTabAt(2);
bigActionBar.selectTab(eventTab);
*/
mViewPager.setCurrentItem(2);
Hope this is helpful.
A: Now that the Android 5.0 docs are available, we have the official documentation for the Toolbar widget:
A standard toolbar for use within application content.
A Toolbar is a generalization of action bars for use within
application layouts. While an action bar is traditionally part of an
Activity's opaque window decor controlled by the framework, a Toolbar
may be placed at any arbitrary level of nesting within a view
hierarchy.
A Toolbar widget can also be used to replace the action bar:
An application may choose to designate a Toolbar as the action bar for
an Activity using the setActionBar() method.
The deprecation of tabs in the action bar is most probably due to this, since toolbars cannot contain tab themselves.
Also, it's available for previous Android verions via the appcompat library. See this post by Chris Banes for more information. An excerpt:
Android 5.0 introduces a new Toolbar widget. This is a generalization
of the ActionBar pattern but gives you much more control and
flexibility in using it. Toolbar is a view in your hierarchy just like
any other, making it easier to interleave with the rest of your views,
animate, react to scroll events.
A: The new Android Design Support Library adds TabLayout, providing a tab implementation that matches the material design guidelines for tabs. A complete walkthrough of how to implement Tabs and ViewPager can be found in this video
Now deprecated: The PagerTabStrip is part of the support library (and has been for some time) and serves as a direct replacement. If you prefer the newer Google Play style tabs, you can use the PagerSlidingTabStrip library or modify either of the Google provided examples SlidingTabsBasic or SlidingTabsColors as explained in this Dev Bytes video.
A: It seems like they added a new Class named android.widget.Toolbar that extends ViewGroup. Also they added a new method setActionBar(Toolbar) in Activity. I haven't tested it yet, but it looks like you can wrap all kinds of TabWidgets, Spinners or custom views into a Toolbar and use it as your Actionbar.
A: I had the same problem and this solution suited me quite nicely:
In the layout xml file that contains the viewpager, add the a PagerTabStrip as shown:
<android.support.v4.view.PagerTabStrip
android:id="@+id/pager_tab_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#996633"
android:textColor="#CCCCCC"
android:paddingTop="5dp"
android:paddingBottom="5dp" />
To control page titles, add a switch statement to your ViewPager file:
@Override
public CharSequence getPageTitle(int position)
{
switch (position)
{
case 0:
return "Page 1";
case 1:
return "Page 2";
case 2:
return "Page 3";
}
return null;
}
A: FragmentTabHost is also an option.
This code is from Android developer's site:
/**
* This demonstrates how you can implement switching between the tabs of a
* TabHost through fragments, using FragmentTabHost.
*/
public class FragmentTabs extends FragmentActivity {
private FragmentTabHost mTabHost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_tabs);
mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"),
FragmentStackSupport.CountingFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Contacts"),
LoaderCursorSupport.CursorLoaderListFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("custom").setIndicator("Custom"),
LoaderCustomSupport.AppListFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("throttle").setIndicator("Throttle"),
LoaderThrottleSupport.ThrottledLoaderListFragment.class, null);
}
}
A: I found these tutorials helpful while putting together an action bar (now the 'tool bar' - argh) that supports sliding tabs with Material Design:
https://www.youtube.com/watch?v=Fl0xMuo10yA
http://www.exoguru.com/android/material-design/navigation/android-sliding-tabs-with-material-design.html
You sort of have to synthesize these resources to match your particular situation. For example, you may not want to manually create the tabs in the same style that the exoguru.com tutorial did.
A: Well for me to handle the deprecated navigation toolbar by using toolbar v7 widget appcompat.
setSupportActionBar(toolbar);
getSupportActionBar().setSubtitle("Feed Detail");
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//goToWhere
}
});
A: I think a suitable replacement for when you have three to five screens of equal importance is the BottomNavigationActivity,this can be used to switch fragments.
You will notice a wizard exists for this in Android Studio, take care however as Android Studio has a tendency to produce overly complex boiler plate code.
A tutorial can be found here:
https://android.jlelse.eu/ultimate-guide-to-bottom-navigation-on-android-75e4efb8105f
Another quality tutorial can be found at Android Hive here:
https://www.androidhive.info/2017/12/android-working-with-bottom-navigation/
| |
doc_23536361
|
$ ./adb devices
List of devices attached
S5830c10eb068 device
Also, Eclipse allows me to run project directly on physical device, but Idea is just able to see that device - S5830c10eb068(Samsung gt-s5830, android 2.3.6) in some windows:
but even when I choose 'USB device' in 'Run Configuration' - nothing happens:
What should I do?
Also, there is errors in logcat after device plugged in:
02-20 03:59:35.419: ERROR/RingtoneManager(158): getActualDefaultRingtoneUri : content://media/internal/audio/media/9
02-20 03:59:35.419: ERROR/RingtoneManager(158): Uri.parse(uriString) : content://media/internal/audio/media/9
02-20 03:59:35.439: ERROR/RingtoneManager(158): getActualDefaultRingtoneUri : content://media/internal/audio/media/9
02-20 03:59:35.439: ERROR/RingtoneManager(158): Uri.parse(uriString) : content://media/internal/audio/media/9
02-20 03:59:35.539: ERROR/MountService(158): ### notifyShareAvailabilityChange :: method = ums, avail = false
02-20 03:59:35.549: ERROR/MountService(158): notifyShareAvailabilityChange :: send ACTION_UMS_CONNECTED
02-20 03:59:38.609: ERROR/MountService(158): ### notifyShareAvailabilityChange :: method = ums, avail = true
02-20 03:59:38.619: ERROR/MountService(158): notifyShareAvailabilityChange :: send ACTION_UMS_CONNECTED
02-20 03:59:39.639: ERROR/RingtoneManager(158): getActualDefaultRingtoneUri : content://media/internal/audio/media/42
02-20 03:59:39.639: ERROR/RingtoneManager(158): Uri.parse(uriString) : content://media/internal/audio/media/42
02-20 03:59:39.919: ERROR/RingtoneManager(158): getActualDefaultRingtoneUri : content://media/internal/audio/media/42
02-20 03:59:39.919: ERROR/RingtoneManager(158): Uri.parse(uriString) : content://media/internal/audio/media/42
02-20 03:59:40.219: ERROR/RingtoneManager(158): getActualDefaultRingtoneUri : content://media/internal/audio/media/42
02-20 03:59:40.219: ERROR/RingtoneManager(158): Uri.parse(uriString) : content://media/internal/audio/media/42
02-20 04:00:12.689: ERROR/RingtoneManager(158): getActualDefaultRingtoneUri : content://media/internal/audio/media/9
02-20 04:00:12.689: ERROR/RingtoneManager(158): Uri.parse(uriString) : content://media/internal/audio/media/9
02-20 04:00:12.699: ERROR/RingtoneManager(158): getActualDefaultRingtoneUri : content://media/internal/audio/media/9
02-20 04:00:12.699: ERROR/RingtoneManager(158): Uri.parse(uriString) : content://media/internal/audio/media/9
02-20 04:00:12.809: ERROR/MountService(158): ### notifyShareAvailabilityChange :: method = ums, avail = false
02-20 04:00:12.819: ERROR/MountService(158): notifyShareAvailabilityChange :: send ACTION_UMS_CONNECTED
02-20 04:00:22.859: ERROR/MountService(158): ### notifyShareAvailabilityChange :: method = ums, avail = true
02-20 04:00:22.889: ERROR/MountService(158): notifyShareAvailabilityChange :: send ACTION_UMS_CONNECTED
02-20 04:03:52.719: ERROR/MountService(158): ### notifyShareAvailabilityChange :: method = ums, avail = false
02-20 04:03:52.729: ERROR/MountService(158): notifyShareAvailabilityChange :: send ACTION_UMS_CONNECTED
02-20 04:04:25.659: ERROR/MountService(158): ### notifyShareAvailabilityChange :: method = ums, avail = true
02-20 04:04:25.669: ERROR/MountService(158): notifyShareAvailabilityChange :: send ACTION_UMS_CONNECTED
02-20 04:59:09.369: ERROR/RingtoneManager(158): getActualDefaultRingtoneUri : content://media/internal/audio/media/9
02-20 04:59:09.369: ERROR/RingtoneManager(158): Uri.parse(uriString) : content://media/internal/audio/media/9
02-20 04:59:09.389: ERROR/RingtoneManager(158): getActualDefaultRingtoneUri : content://media/internal/audio/media/9
02-20 04:59:09.399: ERROR/RingtoneManager(158): Uri.parse(uriString) : content://media/internal/audio/media/9
Also, if I chose 'Show chooser dialog' and then select 'run' from 'Run' menu - there is the same window as on the second picture opens.
A: You are trying to edit Defaults, but you need to create a new run configuration instead.
Refer to this documentation section for details.
Once configuration is created, you will be able to select it in the drop-down on the toolbar and Run/Debug buttons will become available.
A: Run --> Edit Configurations... --> General --> Show Chooser Dialog --> OK
Then run it again.
A: Select "show choice dialog" and you show dialog with device ID
A: On idea 13,in run configuration -> General -> target device -> USB devices
A: Maybe related to seeing the device in the chooser: On my machine the device is only in the list after I killed the ADB process manually (Task Manager -> "adb.exe *32"). Before that, there were no device in list or OK button grayed out.
(IntelliJ IDEA 13.0.2 Community)
| |
doc_23536362
|
InputStream inputStream = openFileInput("settings.xml");
XmlPullParser parser;
parser.setInput(inputStream, null);
Have no idea, how to repair it. I use Intellij IDEA12 and Android 2.3 SDK.
A:
I use Eclipse and the below code has worked for me:
You might be missing the below first line:
XmlPullParserFactory xppf = XmlPullParserFactory.newInstance();
xppf.setNamespaceAware(true);
XmlPullParser xpp = xppf.newPullParser();
File myXML = new File("myXML.xml"); // give proper path
FileInputStream fis = new FileInputStream(myXML);
xpp.setInput(fis, null);
A: Its working code in eclipes but dont know about Intellij IDEA12
write this code to open and get xml from assets
or modify according to your need
try {
XmlPullParserFactory xppf = XmlPullParserFactory.newInstance();
XmlPullParser = xppf.newPullParser();
AssetManager manager = context.getResources().getAssets();
InputStream input = manager.open("createDb.xml");
xpp.setInput(input, null);
int type = xpp.getEventType();
while(type != XmlPullParser.END_DOCUMENT) {
if(type == XmlPullParser.START_DOCUMENT) {
Log.d(Tag, "In start document");
}
else if(type == XmlPullParser.START_TAG) {
Log.d(Tag, "In start tag = "+xpp.getName());
}
else if(type == XmlPullParser.END_TAG) {
Log.d(Tag, "In end tag = "+xpp.getName());
}
else if(type == XmlPullParser.TEXT) {
Log.d(Tag, "Have text = "+xpp.getText());
if(xpp.isWhitespace())
{
}
else
{
String strquery = xpp.getText();
db.execSQL(strquery);
}
}
type = xpp.next();
}
}
catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
A: You are not instantiating an instance of XmlPullParser. Try:
XmlPullParser parser = Xml.newPullParser();
Also, you need to call:
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
From the docs:
Use this call to change the general behaviour of the parser, such as namespace processing >or doctype declaration handling. This method must be called before the first call to >next or nextToken. Otherwise, an exception is thrown.
Example: call setFeature(FEATURE_PROCESS_NAMESPACES, true) in order to switch on namespace >processing. The initial settings correspond to the properties requested from the XML Pull >Parser factory. If none were requested, all features are deactivated by default.
| |
doc_23536363
|
That timer triggers a mouse click.
Problem is that if I keep Z pressed more than 5 seconds, it gets stuck and on KeyUp it doesn't fire, variable doesn't change to false and loop is endless, so it continues firing timer's callback when key is not pressed anymore. Only way to stop it is via ALT+F4
My code is at http://pastebin.com/rbCgY1rb
I use globalKeyboardHook from here
Critical part of code is:
private void keyDownCallback(object sender, KeyEventArgs e) {
if (e.KeyCode.ToString() == "Z") {
timer1.Enabled = true;
this.forceNoLoop = false;
} else if(e.KeyCode.ToString() == "X") {
timer1.Enabled = false;
this.forceNoLoop = true;
}
}
private void keyUpCallback(object sender, KeyEventArgs e) {
timer1.Enabled = false;
this.forceNoLoop = true;
}
private void timer1_Tick(object sender, EventArgs e) {
if (forceNoLoop) return;
mouse_event(MOUSEEVENTF_LEFTDOWN, (uint)Cursor.Position.X, (uint)Cursor.Position.Y, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, (uint)Cursor.Position.X, (uint)Cursor.Position.Y, 0, 0);
lblClickStatus.Text = "clicked " + (this.clickTimes++) + " times";
}
So question is: how to fix the freeze problem?
A: Can you try checking the state of the timer before enabling/disabling it?
private void keyDownCallback(object sender, KeyEventArgs e) {
if (e.KeyCode.ToString() == "Z") {
if (!timer1.Enabled)
timer1.Enabled = true;
} else if (e.KeyCode.ToString() == "X") {
if (timer1.Enabled)
timer1.Enabled = false;
}
}
| |
doc_23536364
|
HTML
<div id="grid" class="grid">
<div id="t1" class="tile"></div>
<div id="t2" class="tile">
<img class="Extractor" title="Extractor" src="images/buildings/Extractor.png">
</div>
<div id="t3" class="tile"></div>
<div id="t4" class="tile"></div>
<div id="t5" class="tile active"></div>
</div>
JS
function saveGame() {
// Format like: "[['t2','Extractor']['t8','Forge']]"
saveData.buildings = $('.tile').children().stuff(?);
localStorage.saveData = JSON.stringify(saveData);
}
Fiddle
A: The .map() method is used to build a new Array. Here we're selecting the child images, and using map against that collection.
The return values from the .map() callback becomes the members of the new Array. Because jQuery's .map() is... odd... we need to double up the returned Array because any outer Array gets flattened into the resulting Array.
$('.tile').children("img").map(function(i, el) {
return [[el.parentNode.id, el.className]];
}).toArray();
The reason for the .toArray() at the end is that this version of .map() in jQuery actually returns a jQuery object, which is Array-like, but not an actual Array. So we need to convert it.
A: use .each to loop over each tile, and then .each on the children to loop over those, there might be a quicker algorithm someone maybe someone will comment if there is.
saveData.buildings = "[['t2','Extractor']['t8','Forge']]";
$('.tile').each(function(){
var parent = $(this);
parent.children().each(function(){
saveData.buildings.push([parent.id,$(this).attr("class")]);
});
});
saveData.resources = 'resources';
A: I haven't tested it, but something with this logic should work fine:
results = [];
// iterate over every element with class 'tile'
$('.tile').each(function() {
var $$ = $(this);
// does this instance of class tile have a child?
if ($$.children().length > 0) {
// store data
var parent = $$.attr('id');
var child = $$.children().first().attr('class');
results.append([parent, child]);
}
});
| |
doc_23536365
|
A: You could try putting an image inside the <noscript> tag, which would point to a php file of yours, which in turn it should return an image. This could allow you to know in the server that the user has Javascript disabled.
How to identify the user: you could rely on the session, or set an ID to the url of the image.
You could use the answer on this question as an example on how to server image files from a php script where you could add your logic to detect if the user has js disabled:
Return a PHP page as an image
A: Here is an idea I got from a book long time ago
<script>
document.cookie= "js_enabled=true";
</script>
Use the above on some first page that you see. Then check for that cookie on the next request to see if javascript is enabled. Of course this has the same flaw if cookies are disabled.
A: no... any kind of such detection after the page is loaded would have to be detected with js, and if it's disabled, it can't even do anything if it is.
A: Why not just render the NOSCRIPT tags all the time? That's the point of that tag, to provide content when JS is disabled. If the user is seeing what's in the NOSCRIPT's then they clearly don't have JavaScript enabled.
You could also have a JavaScript AJAX call fire at page load. If your server recieves a request for the page, but then does not receive the AJAX call by the client within the standard loading time frame, then the server can assume the client doesn't accept JS. Not perfect mind you, but you are dealing with client-side JS here.
A: I don't think there is really a good way to do server-side JS detection. <noscript> is the semantic way to specify non-javascript content - so I suppose rather then detect if JS is disabled, you should detect if it is enabled. You can hide the detection by default, and put a <style> block inside the <noscript> to unhide.
| |
doc_23536366
|
+---------+------------+------------+----+----+----+----+----+----+----+
| user_id | project_id | date | d1 | d2 | d3 | d4 | d5 | d6 | d7 |
+---------+------------+------------+----+----+----+----+----+----+----+
| 1 | 2 | 2015-06-07 | 3 | 4 | 5 | 6 | 2 | 1 | 3 |
| 2 | 2 | 2015-06-14 | 3 | 4 | 5 | 6 | 2 | 1 | 3 |
| 1 | 1 | 2015-06-21 | 3 | 4 | 5 | 6 | 2 | 1 | 3 |
| 3 | 2 | 2015-06-28 | 3 | 4 | 5 | 6 | 2 | 1 | 3 |
| 2 | 3 | 2015-07-05 | 3 | 4 | 5 | 6 | 2 | 1 | 3 |
| 1 | 2 | 2015-07-12 | 3 | 4 | 5 | 6 | 2 | 1 | 3 |
| 2 | 4 | 2015-07-19 | 3 | 4 | 5 | 6 | 2 | 1 | 3 |
+---------+------------+------------+----+----+----+----+----+----+----+
Here Date field is always sunday. d1, d2,d3 are hours. I want to generate a report between two dates which gives output like this:
+---------+------------+-------+-------+-------+-------+-------+-------+-------+
| user_id | project_id | week1 | week2 | week3 | week4 | week5 | week6 | total |
+---------+------------+-------+-------+-------+-------+-------+-------+-------+
| 1 | 1 | 2 | 2 | 2 | 2 | 2 | 3 | 13 |
| 1 | 2 | 2 | 3 | 3 | 2 | 2 | 3 | 15 |
+---------+------------+-------+-------+-------+-------+-------+-------+-------+
here weeks are sum of 7days hours i.e.(d1+d2+d3+d4+d5+d6+d7). Week fields will vary depending on how many weeks are there between the date range. How do I build a MySQL query to achieve this result without writing much,or any, php?
| |
doc_23536367
|
I'm wondering why the outputs only have properties of Child, but no Human property.
I guess it's because the property descriptors, specifically the enumerable, but I can't figure it out. Can anyone help me?
const Child = function() {
this.name = "child"
}
const Human = function() {
this.move = "walking";
}
Child.prototype = new Human();
Child.prototype.constructor = Child;
const child = new Child();
console.log(child);
After running above code I only see {name: "child"}, though console.log(child.move) gives 'walking'.
A: The short answer, is that move is not found on the Child instance, but on the prototype it inherits from Human.
Let's analyze your code.
const Child = function() {
this.name = "child"
}
const Human = function() {
this.move = "walking";
}
These are self explanatory, you make two constructor functions. They are unrelated (yet).
Child.prototype = new Human();
Child.prototype.constructor = Child;
This is the inheritance part. Child.prototype = new Human(); will create an instance of of Human, and assign it to Child.prototype, because the instance has a member move, that gets assigned to Child.prototype and you get what's essentially Child.prototype = { move: 'walking' } or Child.prototype.move = 'walking' (those aren't accurate, but close enough)
Then you assign Child itself as the prototype.constructor.
The reason you're seeing the weird behavior is that you expect move to be an instance member, but it's a prototype member instead. A more significant drawback of this effect is that altering child.move will alter it for all child instances at once, which is not what you'd expect from an instance member.
For this reason, it is not recommended to do inheritance by actually creating an instance, like you did, but using Object.create() instead, like so:
Child.prototype = Object.create(Human.prototype);
Child.prototype.constructor = Child;
Additionally, your Child function should be calling the parent constructor, to maintain the parent's logic and members. Like so:
const Child = function() {
Human.call(this); // call to parent constructor
this.name = "child";
}
Full code:
const Human = function() {
this.move = "walking";
}
const Child = function() {
Human.call(this);
this.name = "child"
}
Child.prototype = Object.create(Human.prototype);
Child.prototype.constructor = Child;
const child = new Child();
console.log(child);
Once you understand how prototype chains work, remember that ES6 classes were created to handle these situations more gracefully and with more readable code:
class Human {
constructor() {
this.move = "walking";
}
}
class Child extends Human {
constructor() {
super();
this.name = "child";
}
}
| |
doc_23536368
|
PeriodIndex Value
2017Q1 1.156355
2017Q2 0.815639
2017Q3 0.798100
2017Q4 1.027752
How do I get duration of each of the indeces? I could do end_time - start_time, but that gets it slightly wrong like Timedelta('30 days 23:59:59.999999') for January and you have to round that somehow. As I need to multiply the value by amount of days, I can also resample the data to days, ffil, then resample back to Q with sum, but that doesn't seem very efficient.
EDIT: Of course in my example I can just multiply with timedelta/timedelta('1 day'), but in general if duration of period is needed, is there no built in function?
| |
doc_23536369
|
When the number of series is known everything work OK but I can't get it work correctly for unknown number of series.
Here is my code for 4 series - 1 line and 3 columns.
<script type="text/javascript">
$(function () {
var DivName1 = '<%= DivName(1)%>'
var DivName2 = '<%= DivName(2)%>'
var DivName3 = '<%= DivName(3)%>'
var DivName4 = '<%= DivName(4)%>'
var DivN1 = parseInt('<%= DivN(1)%>')
var DivN2 = parseInt('<%= DivN(2)%>')
var DivN3 = parseInt('<%= DivN(3)%>')
var DivN4 = parseInt('<%= DivN(4)%>')
var DivTotal1 = parseFloat('<%= DivTotal(1)%>')
var DivTotal2 = parseFloat('<%= DivTotal(2)%>')
var DivTotal3 = parseFloat('<%= DivTotal(3)%>')
var DivTotal4 = parseFloat('<%= DivTotal(4)%>')
$('#DivCompTotalA').highcharts({
chart: {
type: 'column'
},
title: {
text: ''
},
credits: {
enabled: false
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
itemWidth: 180,
useHTML: true,
x: 0,
y: 40,
borderWidth: 0
},
xAxis: {
categories: ['']
},
yAxis: {
max: 7.01,
labels: {
enabled: false
},
gridLineColor: 'transparent',
plotLines: [{
value: DivTotal1,
color: '#333333',
width: 2,
label: {
text: 'Org.=' + DivTotal1 + '<br>N=' + DivN1,
align: 'right',
y: -5,
x: 0,
style: {
fontSize: '13px'
}
},
zIndex: 2
}],
title: {
text: ''
}
},
plotOptions: {
column: {
pointPadding: 0.2,
groupPadding: 0.10,
borderWidth: 0
},
series: {
dataLabels: {
enabled: true,
y: 5,
style: {
fontSize: '14px'
}
},
enableMouseTracking: false,
events: {
legendItemClick: function () {
return false;
}
}
}
},
series: [{
name: DivName2 + ' [' + DivN2 + ']',
color: '#c9e7ff',
data: [DivTotal2]
}, {
name: DivName3 + ' [' + DivN3 + ']',
color: '#4898a4',
data: [DivTotal3]
}, {
name: DivName4 + ' [' + DivN4 + ']',
color: '#ffd949',
data: [DivTotal4]
}]
});
});
My first question is How to replace these lines:
var DivName1 = '<%= DivName(1)%>'
var DivName2 = '<%= DivName(2)%>'
var DivName3 = '<%= DivName(3)%>'
var DivName4 = '<%= DivName(4)%>'
with a loop I tried this loop but with no success
var N = '<%=N %>'
var DivName = []
for (var i = 0; i <= N; i++) {
DivName[i] = '<%= DivName(i)%>';
}
How to write the "i" inside the '<%= DivName(i)%>' so it will be a variant
A: Try something like this:
Set series to nothing:
series: []
Fill it by script (where seriesData is array of prepared data. For format check documentation
$.each(Div, function(i){
var chart = $('#container').highcharts();
if (chart.series.length === 1) {
chart.addSeries({
name: Div[i].Name + i + ' [' + Div[i].N + ']',
color: '#c9e7ff',
data: Div[i].Total
});
}
});
Here an example how to add 1 series. You can add as many as you like with each loop.
$(function () {
$('#container').highcharts({
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
}]
});
// the button handler
$('#button').click(function () {
var chart = $('#container').highcharts();
if (chart.series.length === 1) {
chart.addSeries({
data: [194.1, 95.6, 54.4, 29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4]
});
}
});
});
| |
doc_23536370
|
This is what the txt file looks like:
A20000to22000.7z, A20000to22000/rows/A21673.Lo1sign.jpg
B20000to22000.7z, B20000to22000/rows/B21673.Lo1sign.jpg
I currently am able to extract files with Python but only from one 7z at a time. I use this command to do that:
7zz e A0000to22000.7z @f1.txt
This is taking way too long though. Is there anyway to edit the command or use another approach so I can extract many different files from many different 7z files at once?
A: Updated Answer
With the new information that there are lots of files to retrieve from each archive, a modified approach is needed.
First we must generate a list of the files needed from each 7z archive, then process that list in parallel. So this code should do that:
awk -F, '{sub("7z","txt",$1); print $2 > $1}' joblist.txt
That should make a file called A20000to22000.txt that contains all the files to be extracted from the archive A20000to22000.7z and similarly for B20000to22000.7z it should produce B20000to22000.txt.
Don't proceed past here till the files ending in .txt look correct.
Now we need to process the .txt files in parallel with GNU Parallel. That should look something like this:
parallel --dry-run 7zz e {.}.7z @{} ::: *to*.txt
I used *to*.txt in order to avoid processing the original joblist.txt.
If that command looks correct, remove --dry-run and run for real.
Original Answer
Assuming joblist.txt looks like this:
A20000to22000.7z, A20000to22000/rows/A21673.Lo1sign.jpg
B20000to22000.7z, B20000to22000/rows/B21673.Lo1sign.jpg
and that corresponds to needing to run a command like:
7zz e A20000to22000.7z A20000to22000/rows/A21673.Lo1sign.jpg
you can do that in parallel with GNU Parallel like this:
parallel --dry-run --colsep , 7zz e {1} {2} :::: joblist.txt
If it looks right, remove --dry-run and run for real.
Note that this is done in the terminal/shell and without Python, so it falls under the "another approach" you mentioned.
| |
doc_23536371
|
template <typename... Ts>
struct foo : Ts...
{
template <typename... Us>
foo(Us&&... us) : Ts{us}... { }
};
template <typename... Us>
foo(Us&&... us) -> foo<Us...>;
If I try to instantiate foo with explicit template arguments, the code compiles correctly:
foo<bar> a{bar{}}; // ok
If I try to instantiate foo through the deduction guide...
foo b{bar{}};
*
*g++7 produces a compiler error:
prog.cc: In instantiation of 'foo<Ts>::foo(Us ...) [with Us = {bar}; Ts = {}]':
prog.cc:15:16: required from here
prog.cc:5:27: error: mismatched argument pack lengths while expanding 'Ts'
foo(Us... us) : Ts{us}... { }
^~~
*clang++5 explodes:
#0 0x0000000001944af4 PrintStackTraceSignalHandler(void*) (/opt/wandbox/clang-head/bin/clang-5.0+0x1944af4)
#1 0x0000000001944dc6 SignalHandler(int) (/opt/wandbox/clang-head/bin/clang-5.0+0x1944dc6)
#2 0x00007fafb639a390 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x11390)
#3 0x0000000003015b30 clang::Decl::setDeclContext(clang::DeclContext*) (/opt/wandbox/clang-head/bin/clang-5.0+0x3015b30)
...
clang-5.0: error: unable to execute command: Segmentation fault
live example on wandbox
While clang++ is definitely bugged (reported as issue #32673), is g++ correct in rejecting my code? Is my code ill-formed?
A: To simplify your example further, it appears that GCC does not implement variadic template arguments in deduction guides:
https://wandbox.org/permlink/4YsacnW9wYcoceDH
I didn't see any explicit mention of variadic templates in the wording for deduction guides in the standard or on cppreference.com. I see no interpretation of the standard that disallows this. Therefore I think this is a bug.
A: Since foo has a constructor the compiler generates an implicit deduction guide based on the constructor:
// implicitly generated from foo<T...>::foo<U...>(U...)
template<class... T, class... U> foo(U...) -> foo<T...>;
template<class... T> foo(T...) -> foo<T...>; // explicit
The problem then is that gcc is preferring the implicit guide, and thus deducing T to {} and U to {bar}; clang (since 5.0.0 according to godbolt) prefers the explicit guide. This is an overload resolution problem; when two deduction guides are found to be ambiguous, explicit deduction guides are preferred over implicit deduction guides. But clang and gcc disagree over whether the deduction guides are ambiguous:
template<class... T, class... U> int f(U...) { return 1; }
template<class... T> int f(T...) { return 2; }
int i = f(1, 2);
This program (not involving deduction guides at all) is accepted by gcc (selecting #1) and rejected by clang (as ambiguous). Retracing our steps, this means that going back to deduction guides clang gets to tie-break the ambiguity by selecting the explicit deduction guide over the implicit deduction guide (generated from the constructor template), while gcc cannot do this as it has already selected the implicit deduction guide as a preferred candidate.
We can construct an even simpler example:
template<class... T, int = 0> int f(T...); // #1
template<class... T> int f(T...); // #2
int i = f(1, 2);
Again, gcc (incorrectly) selects #1 while clang rejects as ambiguous.
Importantly, we can workaround this issue by adding another explicit deduction guide that gcc will nevertheless prefer to the implicit deduction guide generated from the constructor:
template <typename U, typename... Us>
foo(U&& u, Us&&... us) -> foo<U, Us...>;
This is preferred (when more than 0 arguments are supplied) since it is binding the first argument to a singular parameter as opposed to a pack. In the 0-argument case it does not matter which deduction guide (between the original explicit guide and the implicitly generated guide) is selected since both come up with the same result, foo<>. It is safe to add this for all compilers, since it is preferred in the 1+-argument case and is not a candidate in the 0-argument case.
Example.
| |
doc_23536372
|
How to allow remote connection to mysql
However, by commenting out
"bind-address = XXX.XXX.XXX.XXX" in /etc/my.cnf
, it does not work at all.
the mariadb cannot be restarted.
systemctl restart mariadb
Should I work on firewall setting or somewhere else?
A: You have to check the sql user permission. Each SQL user has a "scope". By default, all user are authorized from "localhost". You have to create a new SQL user with "%" as client.
A: This is due to the firewall problem.
I have tick the service mysql in the public zone in firewall setting.
However, I don't know if this is a "safe" practice.
Thanks.
| |
doc_23536373
|
The problem is that each of them requires a unique setup in Xcode project's AppDelegate.
Both of them need jsCodeLocation:
NSURL *jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
RNN setup:
[ReactNativeNavigation bootstrap:jsCodeLocation launchOptions:launchOptions];
RNCK setup:
RNCallKit *rncallkit = [[RNCallKit alloc] init];
RCTBridge *bridge = [[RCTBridge alloc] initWithBundleURL:jsCodeLocation
moduleProvider:^{ return @[rncallkit]; }
launchOptions:launchOptions];
RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
moduleName:@"MyApp"
initialProperties:nil];
I see this (outdated) issue in RNCK repo, which leads to this (also outdated) issue and both talk about RNN 1, while in RNN 2 this setup is simplified and I don't see a proper way to integrate both frameworks in one project except forking the RNN and adding a separate initialiser that will receive moduleProvider...
A: RNN has an additional bootstrap method that takes a delegate object parameter (which implements RNNBridgeManagerDelegate) that allows you to inject extra modules.
Here's an example of how you can bootstrap RNN with the app delegate itself set as the delegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSURL *jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
[ReactNativeNavigation bootstrap:jsCodeLocation launchOptions:launchOptions bridgeManagerDelegate:self];
return YES;
}
You can then implement the delegate method and return the RNCallKit object:
- (NSArray<id<RCTBridgeModule>> *)extraModulesForBridge:(RCTBridge *)bridge {
RNCallKit *rncallkit = [[RNCallKit alloc] init];
return @[rncallkit];
}
| |
doc_23536374
|
Private Sub cmdSendEmail_Click()
Dim EmailApp, NameSpace, EmailSend As Object
Set EmailApp = CreateObject("Outlook.Application")
Set NameSpace = EmailApp.GetNamespace("MAPI")
Set EmailSend = EmailApp.CreateItem(0)
EmailSend.To = [emailadd] '[emailadd] is the field on the form where the button is located
EmailSend.Subject = [Forms]![WorkordersVR]![Project] & " - " & [Forms]![WorkordersVR]![JobNumber]
EmailSend.Body = "Hello," & vbCrLf & vbCrLf & _
"The project" & " " & [Forms]![WorkordersVR]![Project] & " " & "is ready for pickup." & vbCrLf & vbCrLf & _
"Thank you!" & vbCrLf & vbCrLf & _
"Person sending email here" & vbCrLf & _
EmailSend.Display
Set EmailApp = Nothing
Set NameSpace = Nothing
Set EmailSend = Nothing
End Sub
What ends up in the displayed email To is:
"fred@aplace.com#fred@aplace.com#"
How do I get fred@aplace.com?
A: You can use string functions available in VBA to get a substring until the # symbol in the string. For example, the InStr function returns a number specifying the position of the first occurrence of one string within another.
Also I'd suggest using the Recipients property of the MailItem class which returns a Recipients collection that represents all the recipients for the Outlook item. Then I'd suggest using the Recipient.Resolve method which attempts to resolve a Recipient object against the Address Book.
For example:
Sub CreateStatusReportToBoss()
Dim myItem As Outlook.MailItem
Dim myRecipient As Outlook.Recipient
Set myItem = Application.CreateItem(olMailItem)
Set myRecipient = myItem.Recipients.Add("email")
myRecipient.Resolve
If(myRecipient.Resolved) Then
myItem.Subject = "Status Report"
myItem.Display
End If
End Sub
| |
doc_23536375
|
Arrays.stream(sequence.split(" "))
.mapToInt(Integer::parseInt)
.boxed()
.sorted((a, b) -> a.compareTo(b))
.forEach(a -> System.out.print(a + " "));
Now I have two different sorts of course - ascending and descending and the sort I need to use is specified in the user input. So what I want to do is having something like switch with 2 cases: "ascending" and "descending" and a variable to store the lambda expression respectively:
switch(command) {
case "ascending": var = a.compareTo(b);
case "descending": var = b.compareTo(a);
}
Then I my sorted looks like:
.sorted((a, b) -> var)
I got the idea in a python course I attended. There it was available to store an object in variable, thus making the variable "executable". I realize that this lambda is not an object, but an expression, but I'm asking is there any clever way that can achieve such result, or should I just have
if(var)
and two diferent streams for each sort order.
A: You can switch between using Comparator.reverseOrder() and Comparator.naturalOrder:
Comparator<Integer> comparator = youWantToHaveItReversed ? Comparator.reverseOrder(): Comparator.naturalOrder();
Arrays.stream(sequence.split(" "))
.map(Integer::valueOf)
.sorted(comparator)
.forEach(a -> System.out.print(a + " "));
A: The question is not stupid at all. Answering it in a broader sense: Unfortunately, there is no generic solution for that. This is due to the type inference, which determines one particular type for the lambda expression, based on the target type. (The section about type inference may be helpful here, but does not cover all details regarding lambdas).
Particularly, a lambda like x -> y does not have any type. So there is no way of writing
GenericLambdaTypefunction = x -> y;
and later use function as a drop-in replacement for the actual lambda x -> y.
For example, when you have two functions like
static void useF(Function<Integer, Boolean> f) { ... }
static void useP(Predicate<Integer> p) { ... }
you can call them both with the same lambda
useF(x -> true);
useP(x -> true);
but there is no way of "storing" the x -> true lambda in a way so that it later may be passed to both functions - you can only store it in a reference with the type that it will be needed in later:
Function<Integer, Boolean> f = x -> true;
Predicate<Integer> p = x -> true;
useF(f);
useP(p);
For your particular case, the answer by Konstantin Yovkov already showed the solution: You have to store it as a Comparator<Integer> (ignoring the fact that you wouldn't have needed a lambda here in the first place...)
A: In Lambdas you can use a functionblock
(a,b) -> { if(anything) return 0; else return -1;}
| |
doc_23536376
|
m_textPane.addHyperlinkListener(new HyperlinkListener()
{
@Override
public void hyperlinkUpdate(HyperlinkEvent hyperlinkevent)
{
EventType eventType = hyperlinkevent.getEventType();
if (eventType == HyperlinkEvent.EventType.ACTIVATED)
{
URL url = hyperlinkevent.getURL();
hyperLinkClicked(hyperlinkevent);
}
}
});
The JTextPant is created with HTML and in this HTML file I have two Links.
<tr>
<td valign="top" class="label">Telefon:</td>
<td class="value">
<a href="telnet:[PhoneNumber.primary.number]">
[PhoneNumber.primary.number]
</a>
</td>
</tr>
<tr>
<td valign="top" class="label">Mobil:</td>
<td class="value">[PhoneNumber:Mobil.number]</td>
</tr>
<tr>
<td valign="top" class="label">Arbete:</td>
<td class="value">[PhoneNumber:Arbete.number]</td>
</tr>
<tr>
<td valign="top" class="label">E-post:</td>
<td class="value">
<a href="mailto:[Email.primary.address|]">
[Email.primary.address|]
</a>
</td>
</tr>
</table>
There is no problem getting the mailto protocol, returns "mailto" but the url for the telnet returns null
Any ideas? If any more information is needed tell me :)
A: Try to use hyperlinkevent.getDescription(); instead of hyperlinkevent.getURL();
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
String description = e.getDescription();
...
}
}
| |
doc_23536377
|
<input id="x" type="text" name="x"
oninput="lotsofgeneratedcocde...."/>
I want to add another handler that simply calls that one. My initial though was that this would work:
<input id="x" type="text" name="x"
oninput="lotsofgeneratedcocde...." onfocus="this.oninput"/>
But it doesn't. What should I be doing? Thanks.
Edit: I thought that onfocus="this.oninput" would copy the reference to the function, that's why I left off the parentheses for a call.
A: this.oninput() (note parentheticals) should work:
<input id="x" type="text" name="x"
oninput="console.log('test');" onfocus="this.oninput();"/>
http://jsfiddle.net/9kNrW/
A: This could work?
... onfocus="this.oninput()"
I assume there's no way to have the generated code be outsourced as proper functions that you could call from both event handlers...
A: Short answer:
Use parens: onfocus="this.oninput();"
If oninput references this or the event object, you need to add a little more:
onfocus="this.oninput.call(this, event);"
Explanation:
If you were attaching the event handlers in code, your syntax is correct. Because you are setting a function reference. Ie,
myInput.onfocus = myInput.oninput;
But, when attached in the markup, the code between the quotes actually is itself a function. Eg,
<span id="foo" onclick="alert('hello world');" />
Is equivalent to:
document.getElementById("foo").onclick = function () {
alert('hello world');
};
So your code as written is the equivalent of:
document.getElementById("x").onfocus = function () {
this.oninput; // returns a function reference. Does not call the function.
};
| |
doc_23536378
|
A user will manually fill out the form in Access, I would like to capture the data that the user inputs.
A: Bind the table to the form and then bind the controls to the fields of the table.
Or, the easy route: Mark the table in the navigation pane, then click in the band: Create and then Form, and it will do the dirty work.
| |
doc_23536379
|
Focus on the 3 slides in the middle with the 3 links beneath "99% Satisfaction, New, Studio10" and 2 blue arrow butons
In IE7, 8, 9, when you click the 3 links or the 2 arrows, a little icon pops up in top left of the container. If you keep clicking, more icons appear from left to right. When you click the icons you see that they are the onclick links from that javascript event.
What is this icon anyway? In the other browsers these icons do not show up. I need these icons NOT to show up in IE7, 8, 9.
function imageSwap(action){
var state = $('#features-image').attr("src");
if (action == 'previous')
{
switch(state)
{
case '/themes/default/images/HPSlide-NinetyNine-Percent-Satisfaction.jpg':
$("#features-image").ImageSwitch({Type:"FadeIn", NewImage:"/themes/default/images/HPSlide-Studio10.jpg"});
$("#features-link").attr("href",'/our-features/studio10/');
$('#features-text').html('<p><a href="#" onclick="imageSwap(\'next\');">99% Satisfaction</a> <a href="#" onclick="imageSwap(\'previous\');">New</a> <span class=\"features-selected\"><a href="/our-features/studio10/">Studio10</a></span></p>');
break;
case '/themes/default/images/HPSlide-New-Headquarters-Aerial.jpg':
$("#features-image").ImageSwitch({Type:"FadeIn", NewImage:"/themes/default/images/HPSlide-NinetyNine-Percent-Satisfaction.jpg"});
$("#features-link").attr("href",'/our-features/99-satisfaction/');
$('#features-text').html('<p><span class=\"features-selected\"><a href="/our-features/99-satisfaction/">99% Satisfaction</a></span> <a href="#" onclick="imageSwap(\'next\');">New</a> <a href="#" onclick="imageSwap(\'previous\');">Studio10</a></p>');
break;
case '/themes/default/images/HPSlide-Studio10.jpg':
$("#features-image").ImageSwitch({Type:"FadeIn", NewImage:"/themes/default/images/HPSlide-New-Headquarters-Aerial.jpg"});
$("#features-link").attr("href",'/our-features/new-administration-building/');
$('#features-text').html('<p><a href="#" onclick="imageSwap(\'previous\');">99% Satisfaction</a> <span class=\"features-selected\"><a href="/our-features/new-administration-building/">New</a></span> <a href="#" onclick="imageSwap(\'next\');">Studio10</a></p>');
break;
}
}
A: That "icon" that is popping up is an image tag without a valid source attribute or valid height/width attributes.
It appears as though you have a click event handler on the links you describe in your question that adds an image to the page that is not functioning properly.
The most probable reason you only see the "icon" in Internet Explorer is because the other browsers don't show an "icon" when an image cannot be found unless you specify width and height attributes for the image.
UPDATE
You most likely have some JavaScript code that is creating these images and there is an error when doing so. Here is a sample image I copied from my developer tools:
<img class="GrpEffectImg" id="GrpEffectImg-[object Object]"/>
You probably need to specify a property of the object that you are adding to the ID of the image. Instead of:
var img = '<img class="GrpEffectImg" id="GrpEffectImg-' + someObject + '"/>';
Use:
var img = '<img class="GrpEffectImg" id="GrpEffectImg-' + someObject.someProperty + '"/>';
I cannot be sure what syntax to use with your object but the above example should demonstrate what to do.
| |
doc_23536380
|
$phonegap platform remove android
$phonegap platform add android@^6.3.0 (previously i was using 6.3.0, this moved it to 6.4.0)
$brew update && brew install gradle
now when I build the project locally everything is happy and no errors
when I go to phonegap build and build it remotely i get a failure:
* What went wrong:
A problem occurred configuring root project 'www_android'.
> Could not resolve all dependencies for configuration ':_debugApkCopy'.
> Could not find any version that matches com.google.android.gms:play-services-gcm:12+.
Versions that do not match:
11.0.4
11.0.2
11.0.1
11.0.0
10.2.6
+ 18 more
Searched in the following locations:
file:/opt/android-sdk/extras/google/m2repository/com/google/android/gms/play-services-gcm /maven-metadata.xml
file:/sdk-manager/com/google/android/gms/play-services-gcm/maven-metadata.xml
file:/sdk-manager/com/google/android/gms/play-services-gcm/
file:/opt/android-sdk/extras/android/m2repository/com/google/android/gms/play-services-gc m/maven-metadata.xml
file:/opt/android-sdk/extras/android/m2repository/com/google/android/gms/play-services-gc m/
file:/sdk-manager/com/google/android/gms/play-services-gcm/maven-metadata.xml
file:/sdk-manager/com/google/android/gms/play-services-gcm/
Required by:
project :
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
at ChildProcess.whenDone (/cordova/node_modules/cordova-common/src/superspawn.js:169:23)
at emitTwo (events.js:106:13)
at ChildProcess.emit (events.js:191:7)
at maybeClose (internal/child_process.js:877:16)
at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
some more context:
*
*using cli-7.0.1
*engine name="android" spec="6.4.0" (AS MENTIONED ABOVE THIS WAS: 6.3.0)
project.properties:
target=android-26
android.library.reference.1=CordovaLib
cordova.gradle.include.1=bidwrangler-opentok-plugin/stevechuppauctions-build-extras.gradle
cordova.gradle.include.2=cordova-plugin-safariviewcontroller/stevechuppauctions-SafariView Controller-java18.gradle
cordova.system.library.1=com.android.support:customtabs:23.2.0
cordova.gradle.include.3=phonegap-plugin-push/stevechuppauctions-push.gradle
cordova.system.library.2=com.android.support:support-v13:23+
cordova.system.library.3=com.google.android.gms:play-services-gcm:11+
cordova.system.library.4=me.leolin:ShortcutBadger:1.1.14@aar
I tried updating packages through Android Studio but this not seem to help at all.
A: cordova.system.library.3=com.google.android.gms:play-services-gcm:12.0.1
Have you tried updating your project.properties with this?
I have found two things are usually needed. All of the google and firebase stuff must be set at the same version in the project.properties, and this needs to be added to it as well:
cordova.system.library.7=com.android.support:appcompat-v7:27.1.0
| |
doc_23536381
|
foreach (string itemm in Request.Params)
{
Response.Write(itemm.Substring(itemm.LastIndexOf("$") + 1) + "<br/>");
}
This retrieves all the values , but I have 2 different form I only want the values from the form1 for example. Is it possible? I have already performed a search but I cant find any answer.
A: It seems is Asp.Net you only get to have one form element running server side. This means we can have more than one form tags in our ASP.Net HTML but only one of them can be server side. Rest of the forms have to be client side HTML forms
So all server-controls and user controls must be nested inside that main form in order to work. So server control name-value pairs would always come from input elements inside the main <form runat="server"> when inspecting a postback.
UPDATE
To answer your original question in order to distinguish a post you could always put a hidden input in each form with the same name and switch/case on the expected value. Further more you can use naming conventions on input fields
aspx
<!DOCTYPE html>
<html lang="en">
<head runat="server">
</head>
<body>
<form id="form1" runat="server">
<input type="hidden" name="form.origin" value="first" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
<form id="form2" method="POST">
<input type="hidden" name="form.origin" value="seccond" />
<input type="submit" value="Post Second" />
</form>
</body>
</html>
code behind
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e) {
switch (Request.Form["form.origin"]) {
case "first":
// first for has asp.net spesifics. Because its the main runat server form
foreach (var key in Request.Form.AllKeys) {
Response.Write(string.Format("{0}: {1}", key, Request.Form[key]) + "<br/>");
} break;
case "second":
//seccond form contains only values from the post.
foreach (var key in Request.Form.AllKeys) {
Response.Write(string.Format("{0}: {1}", key, Request.Form[key]) + "<br/>");
} break;
default:
break;
}
}
protected void Button1_Click(object sender, EventArgs e) {
}
}
| |
doc_23536382
|
def columnMatch(self):
with open(self.file_path) as csvfile:
readcsv = csv.reader(csvfile, delimiter=';')
line_count = 0
row_list = []
for row in readcsv:
if line_count < 5:
row_list.append(row)
line_count += 1
return row_list
A: You can use enumerate function to do it easier like:-
...
readcsv = csv.reader(csvfile, delimiter=';')
row_list = []
for i, row in enumerate(readcsv):
if i < 5:
row_list.append(row)
else:
break
...
| |
doc_23536383
|
Here, I want to filter Flatlist data as per top categories and button should be multi-selected.
FlatList data is HotelData array and above categories is also one array that is used inside scrollview using map function.
so by selecting multiple categories i want to filter Flatlist data, so if anyone has done this task, please help me for the same.
const HotelData = [
{
id: '1',
img: require('../Assets/UIPracticeImage/H1.jpg'),
name: 'Chef Vincent',
desc: 'Lorem ipsum dolor sit amet aliquon sciscilant',
tag: 'Toutes possibilities',
compareKey: 1,
},
{
id: '2',
img: require('../Assets/UIPracticeImage/H2.jpg'),
name: 'Pine hill green caben',
desc: 'Lorem ipsum dolor sit amet aliquon sciscilant',
tag: 'Restaurants',
compareKey: 2,
},
{
id: '3',
img: require('../Assets/UIPracticeImage/H3.jpg'),
name: 'Sky Palace',
desc: 'Lorem ipsum dolor sit amet aliquon sciscilant',
tag: 'Restaurants',
compareKey: 2,
},
{
id: '4',
img: require('../Assets/UIPracticeImage/H4.jpg'),
name: 'Green leaf',
desc: 'Lorem ipsum dolor sit amet aliquon sciscilant',
tag: 'Toutes possibilities',
compareKey: 1,
},
{
id: '5',
img: require('../Assets/UIPracticeImage/H1.jpg'),
name: 'Pine green leaf',
desc: 'Lorem ipsum dolor sit amet aliquon sciscilant',
tag: 'Bars',
compareKey: 3,
},
];
const [categories, setCategories] = useState([
{name: 'Toutes possibilités', key: 1, isCheck: false, compareKey: 1},
{name: 'Restaurantes', key: 2, isCheck: false, compareKey: 2},
{name: 'Bars', key: 3, isCheck: false, compareKey: 3},
]);
A: You can use this:
const HotelData = [
{
id: '1',
img: require('../Assets/UIPracticeImage/H1.jpg'),
name: 'Chef Vincent',
desc: 'Lorem ipsum dolor sit amet aliquon sciscilant',
tag: 'Toutes possibilities',
compareKey: 1,
},
{
id: '2',
img: require('../Assets/UIPracticeImage/H2.jpg'),
name: 'Pine hill green caben',
desc: 'Lorem ipsum dolor sit amet aliquon sciscilant',
tag: 'Restaurants',
compareKey: 2,
},
{
id: '3',
img: require('../Assets/UIPracticeImage/H3.jpg'),
name: 'Sky Palace',
desc: 'Lorem ipsum dolor sit amet aliquon sciscilant',
tag: 'Restaurants',
compareKey: 2,
},
{
id: '4',
img: require('../Assets/UIPracticeImage/H4.jpg'),
name: 'Green leaf',
desc: 'Lorem ipsum dolor sit amet aliquon sciscilant',
tag: 'Toutes possibilities',
compareKey: 1,
},
{
id: '5',
img: require('../Assets/UIPracticeImage/H1.jpg'),
name: 'Pine green leaf',
desc: 'Lorem ipsum dolor sit amet aliquon sciscilant',
tag: 'Bars',
compareKey: 3,
},
];
const [filterHotels, setFilterHotels] = useState(HotelData);
const [categories, setCategories] = useState([
{name: 'Toutes possibilités', key: 1, isCheck: false, compareKey: 1},
{name: 'Restaurantes', key: 2, isCheck: false, compareKey: 2},
{name: 'Bars', key: 3, isCheck: false, compareKey: 3},
]);
const [selectedCategories, setSelectedCategories] = useState([]);
const toggleCategory = (category) => {
const idx = selectedCategories.findIndex(item => item.key === category.key);
const temp = [...selectedCategories];
if (idx > -1) {
temp.splice(idx, 1);
} else {
temp.push(category);
}
setSelectedCategories(temp);
}
useEffect(() => {
HotelData.filter((el) => {
return setSelectedCategories.some((f) => {
return f.name === el.tag && f.compareKey === el.compareKey;
});
});
}, [selectedCategories]
return (
<FlatList data={filterHotels} renderItem={renderItem} />
);
| |
doc_23536384
|
[HttpPost]
ViewResult Edit([modeltype] editedModel){
... }
method calculates and sets a new value for the calculated field before saving the new dates and calculated value to the database, and then returns the View with the updated model. The problem I have is that the view does not show the new calculated value (instead it shows the original calculated value as per the initial page load). Until I navigate away from and back to that view - then it shows the calculated value correctly. Any idea what I'm missing? Is the browser perhaps showing a cached version of the page after my HttpPost? If so, can I disable that behavior?
A: The Html helpers prefers the ModelStateCollection over the actual Model. This means they will display the posted values instead of the ones you've update in the controller.
So if you want to return the same model that you got in your action and you have changed some of the values you need to clear the ModelState before returning your model:
[HttpPost]
public ViewResult Edit(MyModel editedModel)
{
//set some properties on editedModel
ModelState.Clear();
return View(editedModel);
}
| |
doc_23536385
|
So I'm following this tutorial, which guides users through assembling the API service with rxjs. The problem is, it's written for version 5.
Here is a sample API route written in version 5:
public getAllTodos(): Observable<Todo[]> {
return this.http
.get(API_URL + '/todos')
.map(response => {
const todos = response.json();
return todos.map((todo) => new Todo(todo));
})
.catch(this.handleError);
}
After reading the documentation, I've gotten the version 6 route re-written to this point:
public getAllTodos(): Observable<Todo[]> {
return this.http
.get(API_URL + '/todos')
.pipe(
map(response => {
return response.map((todo) => new Todo(todo));
}),
catchError(this.handleError)
);
}
The problem is, I'm getting:
Property 'map' does not exist on type 'Object'.
I am guessing this has to do with the response not being in json format, although the response does not seem to have a .json() method.
A: The reason you have an error is that if you don't specify the type of your response variable, it is assumed to be an Object. As map is an array function, you need to specify the type of your response to be an array:
this.http.get<any[]>(...).pipe(...); // Preferred
or:
this.http.get(...).pipe(map((response: any[]) => ...)...);
Note that you should replace any in the above with the actual type that is being returned from your API (string, object, etc.).
| |
doc_23536386
|
Endpoint class:
package org.madbit.rest;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.madbit.rest.ws.SumRequest;
import org.madbit.rest.ws.SumResponse;
@Path("/services")
public class SumEndpoint {
@POST
@Path("sum")
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_XML)
public SumResponse getSum(SumRequest request) {
SumResponse response = new SumResponse();
List<Integer> elements = request.getElement();
int sum = 0;
for (Integer element: elements)
sum += element;
response.setSum(sum);
return response;
}
}
XSD:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.madbit.org/SumService" xmlns:tns="http://www.madbit.org/SumService" elementFormDefault="qualified">
<xs:element name="SumRequest">
<xs:complexType>
<xs:sequence>
<xs:element name="element" type="xs:int" minOccurs="1" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="SumResponse">
<xs:complexType>
<xs:sequence>
<xs:element name="sum" type="xs:int" minOccurs="1" maxOccurs="1"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
I have generated POJOs from above xsd using Maven JAXB plugin. now i have SumRequest and SumResponse POJOs.
Now how can i write a Jersey client to get the response by passing below input?
<?xml version="1.0" encoding="ISO-8859-1"?>
<SumRequest xmlns="http://www.madbit.org/SumService">
<element>1</element>
<element>4</element>
</SumRequest>
Thanks!
A: This should work for you:
public static void testWS(){
try{
SumRequest sumRequest = new SumRequest(1,4); //here you have to create your input object
Client client = Client.create();
WebResource service = client.resource("http://www.madbit.org/SumService");
/*
* here you are calling the post method with your input object attached
*/
ClientResponse response = service.type(MediaType.APPLICATION_XML).post(ClientResponse.class, sumRequest);
SumResponse res = response.getEntity(SumResponse.class);
System.out.println("output JaxbWS:\n " + res.toString());
}
catch(Exception e){
System.out.println(e.getMessage());
}
I must add that your object SumRequest that you are passing will be automatically converted in XML because you method specifies that consumes XML.
| |
doc_23536387
|
I am using this document as my guideline.
It specifies that byte 22 of the header is the number of channels of the wave files, and byte 24 of the header is the sample rate.
I am using a test file that was output by Ableton as 2 channel 16 bit 44100hz. I have confirmed that the format of the test wave file is audacity to be sure it is indeed 44100hz samplerate.
When I read in the wave file, I get a sample rate value of -21436. I am quite certain that my code that reads in a little endian integer is correct. And I am certain that my test wavfile is correct. So now I am out of idea's as to why the read samplerate is incorrect....
my int reading code is as follows.
int ReadInt(char* bytes , int start) { return (bytes[start+3] << 24) + (bytes[start+2] << 16) + (bytes[start+1] << 8) + bytes[start]; }
The function that reads the wave file is as follows...
WavFile::WavFile(std::string filename)
{
std::ifstream ifs;
ifs.open( filename, std::ios::binary | std::ios::in );
LogStream(LOG_DEBUG) << "WavFile::WavFile - - - - BEGIN READING WAV - - - -";
if(ifs.fail())
throw std::invalid_argument("WavFile::WavFile : Failed to open wavFile "+filename);
char hbytes[HEADER_SIZE];
ifs.read(hbytes , HEADER_SIZE);
// check that this is actually a wave file
bool valid_riff = hbytes[0]=='R' && hbytes[1]=='I' && hbytes[2]=='F' && hbytes[3]=='F';
bool valid_wave = hbytes[8]=='W' && hbytes[9]=='A' && hbytes[10]=='V' && hbytes[11]=='E';
bool valid_ftm = (hbytes[12]=='f' && hbytes[13]=='m' && hbytes[14]=='t' && hbytes[15]==' ');
bool valid_data = (hbytes[36]=='d' && hbytes[37]=='a' && hbytes[38]=='t' && hbytes[39]=='a');
LogStream(LOG_DEBUG) << "WavFile::WavFile - valid_riff="<<valid_riff<<" valid_wave="<<valid_wave<<" valid_ftm="<<valid_ftm<<" valid_data="<<valid_data;
if(!(valid_data && valid_ftm && valid_riff))
throw std::invalid_argument("WavFile::WavFile : Invalid argument - unable to open wavfile "+filename);
int audioFormat = ReadShort(hbytes , 20);
int SubChunk1Size = ReadInt(hbytes , 16);
if(audioFormat != 1 || SubChunk1Size != 16)
throw std::invalid_argument("WavFile::WavFile : Only uncompressed PCM wave format supported."+filename);
int subChunk2size = ReadInt(hbytes , 40);
m_header.num_channels = ReadShort(hbytes , 22);
m_header.sample_rate = ReadInt(hbytes , 24);
m_header.bits_per_sample = ReadShort(hbytes , 34);
LogStream(LOG_DEBUG) << "WavFile::WavFile num_channels="<<m_header.num_channels << " sample_rate="<<m_header.sample_rate<<" bits_per_sample="<<m_header.bits_per_sample;
m_pcm_data.resize( subChunk2size / sizeof(int16_t) );
LogStream(LOG_DEBUG) << "WavFile::WavFile - subChunk2size = "<<subChunk2size;
LogStream(LOG_DEBUG) << "WavFile::WavFile - m_pcm_data.size() = "<<m_pcm_data.size();
ifs.read((char*)m_pcm_data.data() , subChunk2size);
LogStream(LOG_DEBUG) << "WavFile: ifstream failbit="<<ifs.fail()<<" badbit="<<ifs.bad()<<" goodbit="<<ifs.good();
ifs.close();
LogStream(LOG_DEBUG) << "WavFile::WavFile - - - - END READING WAV - - - -\n";
LogStream(LOG_DEBUG) << "WavFile::WavFile";
}
A: 44100 has hex value 44ac (unsigned int16) and -21436 also has hex value 44ac (signed int16) - the problem is with the way the compiler is implicitly casting each signed char to a signed integer before shifting. You can avoid that either by casting as follows (which outputs 44100):
int main()
{
char bytes[4] = { 0x44, 0xac, 0x00, 0x00 };
printf("%i\n", (((unsigned char)bytes[3]) << 24) | (((unsigned char)bytes[2]) << 16) | (((unsigned char)bytes[1]) << 8) | ((unsigned char)bytes[0]));
return 0;
}
or simply reading as unsigned bytes - this will avoid the same problem for other fields:
int main()
{
unsigned char bytes[4] = { 0x44, 0xac, 0x00, 0x00 };
printf("%i\n", (bytes[3] << 24) | (bytes[2] << 16) | (bytes[1] << 8) | bytes[0]);
return 0;
}
| |
doc_23536388
|
robocopy.exe "%location%" "%destination%" /E /tee /LOG+:C:\Users\etc\Log.txt
EDIT 2:
OK thanks to the comments bellow and a bunch of trail and error I figured that it was a quotation issue. Now after a bunch of trial and error found a combination of quotes and no quotes that worked, I have no idea why though. If some one is able to explain why this works and other combinations didn't I would appreciate it haha...batch is so weird.
Input -> Test.bat "C:\etc\etc\" - Path in quotes
set location=%1 - No Quotes
set type="%~2" - Quotes
set destination="C:\Users\xxxx\Desktop\Destination" - Quotes
set logfile="C:\Users\xxxx\Desktop\robolog.txt" - Quotes
robocopy.exe %location% "%destination%" /E /tee /LOG+:%logfile% - Source with no quotes but destination in quotes???
Do quotes cancel each other out? I'm confused why adding quotes would make it not work, but only work in some cases?
Also having %~1 vs %1 vs "%1" vs "%~1" produced different results.
A: I tested this:
@ECHO OFF &SETLOCAL
SET "location=this & that"
SET "destination=more & more"
robocopy.exe "%location%" "%destination%" /E /tee /LOG+:"%destination%\Log.txt"
And I got no error:
-------------------------------------------------------------------------------
ROBOCOPY :: Robust File Copy for Windows :: Version XP010
-------------------------------------------------------------------------------
Started : Wed Jul 31 09:59:55 2013
Source : C:\TEST\this & that\
Dest : C:\TEST\more & more\
Files : *.*
Options : *.* /TEE /S /E /COPY:DAT /R:1000000 /W:30
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Total Copied Skipped Mismatch FAILED Extras
Dirs : 1 0 1 0 0 0
Files : 81 81 0 0 0 1
Bytes : 28.3 k 28.3 k 0 0 0 0
Times : 0:00:00 0:00:00 0:00:00 0:00:00
Speed : 184585 Bytes/sec.
Speed : 10.562 MegaBytes/min.
Ended : Wed Jul 31 09:59:55 2013
| |
doc_23536389
|
Expression: header->_block_use == block_use || header->_block_use ==
_CRT_BLOCK && block_use == _NORMAL_BLOCK
What does this mean? It has something to do with a header?
I found in my code where after I step over it returns the debug assertion failure, just this one line of code works in other projects.
Is there a linker setting or c/c++ setting that I have to remove?
A: The assertion that you are hitting is part of the Microsoft Visual C/C++ runtime libraries, specifically related to the debug heap. Calling malloc/free and using the new/delete operators leads to calls to the CRT heap functions, which perform internal consistency checks using these assertions.
It's very likely that the assertion is hit as a result of a memory safety bug, for example trying to delete a garbage pointer, double-free, etc. If you are unable to find it, the ASAN tool can help by keeping closer track of memory operations and raising errors when your code does invalid things. Without these close checks, mistakes in your code can corrupt a data structure, and the crash could occur much, much later in unrelated code.
For Visual Studio, it involves a few steps: the "C++ AddressSanitizer" feature must be installed using the Visual Studio installer, and the address sanitizer must be enabled in the project properties under C/C++ -> General.
A: Languages such as C and C++ offer an assert(...expression...) facility that is typically used during debugging ... and omitted from the final delivered product. The ..expression... being "something that should always be False."
If the expression turns out not to be False, then it throws a runtime exception containing the exact text of expression. Which is exactly what a developer would like to see, because: "the whole idea is that this should never, ever, ever happen!"
Ordinarily, published versions of applications are compiled in such a way that all of the assert() statements are ignored: they are "no-ops."
| |
doc_23536390
|
So instead of checking if form.is_valid() I could just check the field instead?
def some_ajax_view(request):
form = Form(request.POST):
if form.is_valid():
....
| |
doc_23536391
|
Edit: This is a 2d game but the unity2d tag is showing med unity3d
A: You can create gridManager class that has 2d array of type gridCell class
public class GridManager : MonoBehaviour
{
GridCell[,] grid = new grid[5,5];
void Start()
{
grid[1,2] = new GridCell();
grid[1,2].example = true;
bool boo = grid[1,2].example;
}
}
public class GridCell
{
public bool example;
}
Here we create 5x5 empty grid of type GridCell, then on cords x=1 y=2 we add new GridCell to that place in grid. We add true value to our example value in that cell, and then we read what that value is.
Now you can change that bool variable to array that stores all game object you want. When you adding game object to that array, add reference to GridCell inside game object you storing. To get other stored objects inside that cell, create method inside cell that returns other objects stored inside that array cell. With that, your game object can request a list of other game objects inside same cell
| |
doc_23536392
|
In order to better understand Purescript, and partly to challenge Purescript on a procedural task, I want to rewrite a very simple Node script written in Typescript.
The script reads some input from the command line, calls an async function that hydrates a (server-side) redux store, and then prints some data to the console.
import { store } from '../server/store'
import { deep, log, red } from '../src/io'
import { isRehydrated } from './isRehydrated'
async function readRecord(dbName: string, tableName: string, recordId: string) {
try {
await isRehydrated()
const result = store.getState().databases[dbName][tableName][recordId]
deep(result)
return 'DONE!'
} catch (e) {
return e
}
}
readRecord(process.argv[2], process.argv[3], process.argv[4]).then(
m => {
log(m)
process.exit()
},
e => {
red(e)
process.exit()
}
)
Is there a simple way to rewrite the above script in Purescript using Purescript's FFI to call the Javascript imports and the do syntax to handle the async procedures?
A: This answer is a work in progress.
Main.js
"use strict";
exports.store = require('../../../build_server/server/store/index').store
exports.red = require('../../../build_server/src/io/console').red
exports.deep = require('../../../build_server/src/io/console').deep
exports.isRehydrated = require('../../../build_server/scripts/isRehydrated').isRehydrated
exports.path = require('ramda').path
exports.argv = process.argv
exports.exit = process.exit
Main.purs
module Main where
import Prelude
import Control.Promise (toAff, Promise)
import Data.Array (slice)
import Effect (Effect)
import Effect.Aff (Aff, launchAff_)
import Effect.Class (liftEffect)
import Effect.Console (log)
import Foreign (Foreign)
foreign import isRehydrated :: Unit -> Promise Unit
foreign import red :: ∀ a. a -> Effect Unit
foreign import deep :: ∀ a. a -> Effect Unit
foreign import store :: { getState :: Unit -> { databases :: Foreign } }
foreign import path :: Array String -> Foreign -> Foreign
foreign import argv :: Array String
foreign import exit :: Unit -> Effect Unit
recordPath :: Array String
recordPath = slice 2 5 argv
affLog :: String -> Aff Unit
affLog msg = liftEffect $ log msg
affDeep :: ∀ a. a -> Aff Unit
affDeep m = liftEffect $ deep m
affExit :: Unit -> Aff Unit
affExit unit = liftEffect $ exit unit
isRehydratedAff :: Unit -> Aff Unit
isRehydratedAff unit = toAff (isRehydrated unit)
main :: Effect Unit
main = do
log "BEGIN EFF"
launchAff_ do
affLog "BEGIN AFF"
isRehydratedAff unit
affLog "HYDRATED"
affDeep $ path recordPath (store.getState unit).databases
affLog "END AFF"
affExit unit
main.js
require('./src/pursOut/Main/index').main()
At the terminal:
node main.js
| |
doc_23536393
|
RewriteEngine on
RewriteRule \.svn/ - [F]
# rewrite traffic to HTTPS
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# otherwise forward it to index.php
RewriteRule . index.php
A: Did you mean to omit the [L] after your https rewriterule? Without it, if I request "http://myserver.com/something" it will first rewrite as "https://myserver.com/something" but then (I believe) continue on in the .htaccess file, subsequently using the internal rewrite to serve up "index.php" without actually redirecting the client. Though if the file requested does exist I'm not sure how Apache would handle that.
| |
doc_23536394
|
How can I change the DB from MSSQL to MySQL?
A: This is the steps:
*
*Install MySQL DB and Run MySQL DB service.
*Install mysql-connector-odbc-5.1.10-win32.msi <-- must use this version of odbc
*Stop the Biostar Server Service at services.msc
*Stop MSSQL Service
*Next, Go to folder --> C:\Program Files\BioStar\server\
and run file DBSetup.exe
*The system will ask "Do you want to install MSSQL?" Choose "No"
*Then a window will pop-up. Choose Database MySQL and Insert Host, Port, ID and Password.
*Startup the Biostar Server Service.
*Open Client Login and try to Login.
Hopefully this answer will be beneficial to everyone.
p/s: The most important is the odbc version (refer above step 2)
A: *
*Insert the BioStar installation CD into a compatible media drive.
*Locate the installation directory and run BioStar 1.8 Setup.
*Follow the on-screen prompts to begin the installation.
*During the installation, you will be asked to select the language of your preference.
*Select a language, then click Next to proceed.
*Follow the instructions on the screen to finish the installation.
*During the installation, you will be required to accept the OpenSSL license agreement
and select a destination folder for the OpenSSL program files.
*You will also be asked whether or not you wish to install the MS SQL Server Express
edition. If you will use a pre-installed version of MS SQL Server, MySQL or Oracle, you
may click No when this message appears. If you decide to use the express edition in this step, you can skip to step 10. The database setup process will be automated when you install the express edition.
*When the Create Database [BioStar] dialog box appears, select a database type (MS
SQL Server, MySQL or Oracle). The database server address and port numbers will be
automatically populated, but you should verify that they are correct.
Configure the MySQL Database
BioStar cannot use the MySQL database if the maximum packet size is less than 16MB. To configure the maximum packet size n MySQL server, locate and open a configuration file for the MySQL server (“my.ini” for a Windows system or “my.cnf” for a Linux system).
Under [mysqld], add or edit the packet size to 16M or bigger (for example: max_allowed_packet=16M). After you have changed and saved the file, restart the BioStar Server for the changes to take effect.
Complete Manual PDF
| |
doc_23536395
|
Something like in this pic
| |
doc_23536396
|
In my application I have a class called Album:
public class Album
{
public int Id { get; set; }
public string AlbumName { get; set; }
public int YearReleased { get; set; }
public string AlbumInfo { get; set; }
public string imgAlbumCover { get; set; }
}
My database contains a table of several Album objects
I created an API controller to return this list of Albums in Json format.
I added the following code to WebApiConfig.cs to get JSON back instead of XML:
using System.Net.Http.Headers;
GlobalConfiguration.Configuration.Formatters
.JsonFormatter.MediaTypeMappings.Add
(new System.Net.Http.Formatting.RequestHeaderMapping("Accept",
"text/html",
StringComparison.InvariantCultureIgnoreCase,
true,
"application/json"));
When I do an Albums API call in the browser, returned is a list of Album objects in JSON format.
Instead of returning the list of Albums, I'd like to retun a RootObject that has 1 property called Albums, where Albums is a list of Album objects. Is there a way of doing this in the controller? I don't want to have to create a new RootObject class.
Below is the code for my API controller:
namespace Music.Controllers.API
{
public class AlbumsController : ApiController
{
private MusicContext db;
public AlbumsController()
{
db = new MusicContext();
}
public IEnumerable<Album> GetAlbums()
{
return (db.Albums.ToList());
}
}
}
A: Then create a viewmodel as such and return the same like
public class AlbumListResponseModel
{
public IEnumerable<Album> Albums { get; set; }
}
public async Task<IActionResult> GetAlbums()
{
AlbumListResponseModel model = new AlbumListResponseModel
{
Albums = db.Albums;
}
return OK(model);
}
If you are using WEB API 2.0 then consider using IActionResult rather
A: Change the GetAlbums return type to HttpResponseMessage and change the return statement as
return Request.CreateResponse(HttpStatusCode.OK, new {Albums = db.Albums.ToList() });
That's way you don't need to create a new class.
Full Code :
namespace Music.Controllers.API
{
public class AlbumsController : ApiController
{
private MusicContext db;
public AlbumsController()
{
db = new MusicContext();
}
public HttpResponseMessage GetAlbums()
{
return Request.CreateResponse(HttpStatusCode.OK, new {Albums = db.Albums.ToList() });
}
}
}
| |
doc_23536397
|
//div[@class='itudeBox floatDiv']/div[1]/div/text()[2]
This returns the correct value in Selenium.
But when I try the same in Eclipse → TestNG:
selenium.getAttribute("xpath=//div[@class='itudeBox floatDiv']/div[1]/div/text()[2]");
It shows an error "Element not found".
How can I fix this?
A: Try out the below one to locate the element:
//div[text()='AD- Advice']
css=div:contains(“AD- Advice”)
//div[contains(text(),'AD- Advice')]
A: Try this:
selenium.getText("xpath=//div[@class='itudeBox floatDiv']/div[1]/div");
Or:
selenium.getText("xpath=//div[@class='itudeBox floatDiv']/div[1]/div[2]");
The getText() method works on the element and I believe your XPath expression returns the text within an element.
| |
doc_23536398
|
here is my image download function that using url
extension UIImageView {
func downloadImage(from url : String){
let urlRequest = URLRequest(url: URL(string: url)!)
let task = URLSession.shared.dataTask(with: urlRequest){(data,response,error)in
if error != nil {
print("error...")
}
DispatchQueue.main.async {
self.image = UIImage(data:data!)
}
}
task.resume()
}
My question is how can i do this ? ( sorry my bad english )
A: You can pass a closure in your method which will be executed after downloading the image
extension UIImageView {
func downloadImage(from url : String, completion: ((_ errorMessage: String?) -> Void)?){
let urlRequest = URLRequest(url: URL(string: url)!)
let task = URLSession.shared.dataTask(with: urlRequest){ (data,response,error) in
if error != nil {
completion?("error...")
}
DispatchQueue.main.async {
self.image = UIImage(data:data!)
completion?(nil)
}
}
task.resume()
}
}
and in your ViewController
activityIndicator.startAnimating()
imageView.downloadImage(from: "...") { (err) in
if err != nil {
// error handler
}
self.activityIndicator.stopAnimating()
}
A: You can try the following approach
extension UIImageView {
func downloadImage(from url : String){
self.activityIndicator.startAnimating()
let urlRequest = URLRequest(url: URL(string: url)!)
let task = URLSession.shared.dataTask(with: urlRequest){(data,response,error)in
if error != nil {
DispatchQueue.main.async {
self.activityIndicator.stopAnimating()
}
print("error...")
}
else {
DispatchQueue.main.async {
self.activityIndicator.stopAnimating()
self.image = UIImage(data:data!)
}
}
}
task.resume()
}
fileprivate var activityIndicator: UIActivityIndicatorView {
get {
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
activityIndicator.hidesWhenStopped = true
activityIndicator.center = CGPoint(x:self.frame.width/2,
y: self.frame.height/2)
activityIndicator.stopAnimating()
self.addSubview(activityIndicator)
return activityIndicator
}
}
}
A: It's an improved of @Idindu 's answer, since I use his answer and found some problems with activityIndicator.
The major problem is that activityIndicator won't stop even if the image is already displayed, I have been searched and found that it's because any time when you call it, you get completely new instance, that's why activityIndicator.stopAnimating() didn't work.
Next thing is that the position of activityIndicator not always be center of imageView, and I found a better way here.
So here is the final version that I use:
fileprivate var activityIndicator: UIActivityIndicatorView {
get {
if let indicator = self.subviews.first(where: { $0 is UIActivityIndicatorView }) as? UIActivityIndicatorView {
print("image view already contains activity indicator")
return indicator
}
let activityIndicator = UIActivityIndicatorView(style: .whiteLarge)
activityIndicator.hidesWhenStopped = true
self.addSubview(activityIndicator)
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
let centerX = NSLayoutConstraint(item: self,
attribute: .centerX,
relatedBy: .equal,
toItem: activityIndicator,
attribute: .centerX,
multiplier: 1,
constant: 0)
let centerY = NSLayoutConstraint(item: self,
attribute: .centerY,
relatedBy: .equal,
toItem: activityIndicator,
attribute: .centerY,
multiplier: 1,
constant: 0)
self.addConstraints([centerX, centerY])
return activityIndicator
}
}
A: here is the way I load the images
if(activityList.banner != ""){
dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), {
let fileManager = NSFileManager.defaultManager()
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let pathSplit = activityList.banner.characters.split{$0 == "/"}.map(String.init)
let getImagePath = (paths as NSString).stringByAppendingPathComponent("\(pathSplit[pathSplit.count-1])")
if (fileManager.fileExistsAtPath(getImagePath)){ // if I already download the image before I opened from the folder
func display_image2(){
activityImageView.image = UIImage(contentsOfFile: getImagePath)
activityImageView.image = activityImageView.image?.alpha(0.7)
activityIndicator.hidden = true
//iconImageView.hidden = true
}
dispatch_async(dispatch_get_main_queue(), display_image2)
}else{ //in another case I download the image from server
let url:String = "\(Constants().mainURL)/imagecache/activity_preview/" + activityList.banner
let imgURL: NSURL = NSURL(string: url)!
let request: NSURLRequest = NSURLRequest(URL: imgURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request){
(data, response, error) -> Void in
if (error == nil && data != nil){
func display_image(){
activityImageView.image = UIImage(data: data!)
if let data = UIImageJPEGRepresentation(UIImage(data: data!)!, 0.8) {
data.writeToFile(getImagePath, atomically: true)
}
activityIndicator.hidden = true
//iconImageView.hidden = true
activityImageView.image = activityImageView.image?.alpha(0.7)
}
dispatch_async(dispatch_get_main_queue(), display_image)
}
}
task.resume()
}
})
}
| |
doc_23536399
|
code
<?php
include 'dbinc.php';
mysql_connect($mysql_hostname,$mysql_user,$mysql_password);//database connection
mysql_select_db($mysql_database);
$order = "SELECT * FROM quanta
ORDER BY ID DESC
LIMIT 1
";
//order to search data
//declare in the order variable
$result = mysql_query($order);
//order executes the result is saved
//in the variable of $result
$data = mysql_fetch_row($result);
$data_id = $data[0]; //Unique Id
$data_timestamp = $data[1]; //Time Stamp by Server
$data_validated = $data[2]; //Validated by Server
$data_type = $data[3]; //Type 0 - Periodic / 1 - Fault
$data_type_str = "Unknown";
if ($data[3] == 0) $data_type_str = "Periodic";
if ($data[3] == 1) $data_type_str = "Fault";
$data_site_id = $data[4]; //String Site Id
$data_datetime = $data[5]; //Date Time by Device
$data_device_id = $data[6]; //Device Id/ Only 1 known for now
$data_status = $data[7]; //Status Bits - To Expand
$data_status_hex= bin2hex($data_status);
$data_raw = $data[8]; //Raw Data, for device specific information
echo ("<table class='table table-striped'>");
echo("
<tr><td>Site Id</td><td>$data[4]</td></tr>
<tr><td>Date Time</td><td>$data_datetime</td></tr>
<tr><td>Device Id</td><td>$data_device_id</td></tr>");
//echo ("Status: <b>$data_status</b><br>");
//echo ("Status: <b>$data_status_hex</b></tr>");
//$tmp = gettype($data_status);
//echo "Var: $tmp<br>";
$stats = unpack ( "C*" , $data_status );
//var_dump($stats);
//for table
echo "<tr><td>Smoke Fire Alarm</td><td";
//0x0000000000 Smoke fire 0 means No alarm, 1 means Alarm
if (($stats[5] & 0x01) == false)
echo " >no Smoke alarm";
else
echo " >smoke alarm";
echo "</td></tr>" ;
echo "<tr><td>Door</td><td";
//$FLAG_01_DOOR = 0x0000000002; //Door Open 0 means Door Close , 1 Means Door open
if (($stats[5] & 0x02) == false)
echo " >door closed";
else
echo " >door open";
echo "</td></tr>";
echo "<tr><td>Mode</td><td";
//$FLAG_02_AUTO = 0x0000000004; //Auto/Man Mode 0 Means Auto Mode, 1 Means Man Mode
if (($stats[5] & 0x04) == false)
echo " >Auto";
else
echo " >Manual";
echo "</td></tr>";
echo "<tr><td>Load</td><td>";
//$FLAG_034_LOAD = 0x0000000018; //00 :Load on EB,01: Load on DG, 10: Load on site Battery 11: Not used
if (($stats[5] & 0x08) == false)
{
if (($stats[5] & 0x10) == false)
echo "[- Load on EB -]<br>"; //00
else
echo "[- Load on site Battery -]<br>"; //10
}
else
{
if (($stats[5] & 0x10) == false)
echo "[- Load on DG -]<br>"; //01
else
echo "[- Not Used -]<br>"; //11
}
echo "</td></tr>";
echo "<tr><td>Alternate Fault</td><td";
//$FLAG_10_ALT = 0x0000000400; //Alternate Fault
if (($stats[4] & 0x04) == false)
echo " >no fault";
else
echo " >fault";
echo "</td></tr>";
?>
A: It's only showing 1 item because you only do 1 mysql_fetch_row($result).
Maybe try this
while($data = mysql_fetch_row($result)) {
//The code you have after to generate the table
}
Documentation: https://www.php.net/manual/en/function.mysql-fetch-row.php
A: If you want all your item to show then you need to use a while loop
while($data = mysql_fetch_row($result)){
//input your code here
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.