text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Create Social Graph Dataset From Facebook I am doing a project at my college and I want to build a social graph from Facebook.
I want only the connections between users (friendship) so I can build a Graph.
I read the Facebook API documentation, from my understanding it doesn't allow to fetch my friends' friends, meaning that I'm stuck at first depth.
Does anyone have any suggestions on how to overcome this?
A: Without using a crawler, which is most likely against the TOS, this is not possible.
You could use the first depth to make only a first degree connection graph based on mutual friends within your friend network.
/userid1/friends/userid2
It would be easier to center your project around Twitter's data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11373506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: What is a function signature? I was studying python and I ran into the concept of 'signature'. I looked things up but signature of a function seems to have different meaning for different languages. So, what does signature of a function refer to in python?
A: The signature indicates the names and types of the input arguments, and (with type annotations) the type of the returned result(s) of a function or method.
This is not particular to Python, though the concept is more central in some other languages (like C++, where the same method name can exist with multiple signatures, and the types of the input arguments determine which one will be called).
A: In general the signature of a function is defined by the number and type of input arguments the function takes and the type of the result the function returns.
As an example in C++ consider the following function:
int multiply(int x, int y){
return x*y;
}
The signature of that function, described in an abstract way would be the set {int, int, int}.
As Python is a weakly typed language in general the signature is only given by the amount of parameters. But in newer Python versions type hints were introduced which clarify the signature:
def multiply(x: int, y: int) -> int:
return x*y
A: A function signature is its declaration, parameters, and return type.
def func(params):
#some stuff
return modified_params
When you call it is an instance of that function.
var = func(parameters)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72788932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: T-SQL and MSBUILD - xml indents and line breaks i'm using msbuild for some automation. One of the task is sql query to get xml representation of table and write it to file. So i'm using
<MSBuild.ExtensionPack.SqlServer.SqlExecute
ConnectionString="$(AdminConnectionString)"
Sql="SELECT '%(ReaderResult.Identity)' as XmlFileName,
(SELECT * FROM %(ReaderResult.Identity) FOR XML AUTO, TYPE, ELEMENTS,
XMLSCHEMA('%(ReaderResult.Identity)'), ROOT('DataSet')) as FileContent"
ContinueOnError="false" TaskAction="ExecuteReader">
<Output ItemName="ExportResult" TaskParameter="ReaderResult"/>
</MSBuild.ExtensionPack.SqlServer.SqlExecute>
<WriteLinesToFile File="%(ExportResult.XmlFileName).xml"
Lines="<?xml version="1.0" standalone="yes"?>;
%(ExportResult.FileContent)" Overwrite="true"/>
The problem is - i get the xml data in single line which is not readable, hard to edit etc.
How can i get the human readable xml with line breaks and indents?
Thanks.
A: Did the following, instead of WriteLinesToFile Task
<SaveFormattedXml XmlString="%(ExportResult.FileContent)" FilePath="%(ExportResult.XmlFileName).xml"/>
<UsingTask TaskName="SaveFormattedXml" TaskFactory="CodeTaskFactory" AssemblyFile="c:\Program Files (x86)\MSBuild\12.0\Bin\amd64\Microsoft.Build.Tasks.v12.0.dll">
<ParameterGroup>
<XmlString ParameterType="System.String" Required="true" />
<FilePath ParameterType="System.String" Required="true" />
</ParameterGroup>
<Task>
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq"/>
<Using Namespace="System" />
<Using Namespace="System.IO" />
<Using Namespace="System.Xml" />
<Using Namespace="System.Xml.Linq" />
<Code Type="Fragment" Language="cs">
<![CDATA[
XDocument doc = XDocument.Parse(XmlString);
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = " ";
settings.NewLineChars = "\r\n";
settings.NewLineHandling = NewLineHandling.Replace;
using (Stream fileStream = new FileStream(FilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
{
using (XmlWriter writer = XmlWriter.Create(fileStream, settings))
{
doc.Save(writer);
}
}
]]>
</Code>
</Task>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26655382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Create GString from String We're using groovy in a type-safe way. At some point I want to invoke a method with signature
void foo(GString baa)
As long the String I enter contains some ${baz} everything is fine, but when I use a pure String I get a compile error
foo("Hello, ${baz}") // fine
foo("Hello, world") // Cannot assign value of type java.lang.String to variable of type groovy.lang.GString
foo("Hello, world${""}") // fine but ugly
Is there a nice way to create a GString out of String?
EDIT
Guess I've oversimplicated my problem. I'm using named constructor parameters to initialize objects. Since some of the Strings are evaluated lazily, I need to store them as GString.
class SomeClass {
GString foo
}
new SomeClass(
foo: "Hello, world" // fails
)
So method-overloading is no option.
The solution is as mentioned by willyjoker to use CharSequence instead of String
class SomeClass {
CharSequence foo
}
new SomeClass(
foo: "Hello, world" // works
)
new SomeClass(
foo: "Hello, ${baa}" // also works lazily
)
A: There is probably no good reason to have a method accepting only GString as input or output. GString is meant to be used interchangeably as a regular String, but with embedded values which are evaluated lazily.
Consider redefining the method as:
void foo (String baa)
void foo (CharSequence baa) //more flexible
This way the method accepts both String and GString (GString parameter is automagically converted to String as needed). The second version even accepts StringBuffer/Builder/etc.
If you absolutely need to keep the GString signature (because it's a third party API, etc.), consider creating a wrapper method which accepts String and does the conversion internally. Something like this:
void fooWrapper (String baa) {
foo(baa + "${''}")
}
A: You can create overloaded methods or you can use generics; something as below:
foo("Hello from foo GString ${X}")
foo("Hello from foo")
MyClass.foo("Hello from foo GString ${X}")
MyClass.foo("Hello from foo")
// method with GString as parameter
void foo(GString g) {
println("GString: " + g)
}
// overloading method with String as parameter
void foo(String s) {
println("String: " + s)
}
// using generics
class MyClass<T> {
static void foo(T t) {
println(t.class.name + ": " + t)
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70593174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how can the bash script kill self if it received ctrl z pseudo code in my xxx.sh
a large loop {
python xxx.py
}
when I run this script ./xxx.sh and some bugs in python, then exception info will be raised to stdout repeatedly.
if I press ctrl+c, the signal will be catched by python, and if I press ctrl+z, the xxx.sh will be sleep in the background.
So, I am trying to add some trap code to catch ctrl+z,
the trap code in my xxx.sh
function stop_ctrl_z() {
echo $$
pkill -9 $$
}
trap stop_ctrl_z SIGTSTP
But xxx.sh cannot stop itself when met ctrl+z as my expected.
It hangs up, sadly I must open another terminal and use pkill -9 xxx.sh to stop this script.
^Z^Z^Z^Z^Z^Z^Z^Z^Z^Z
Does someone has solution to solve my problem?
A: Just force an exit when the Python call fails:
python xxx.py || exit 1
You could use break instead of exit to just leave the loop. More advanced error handling can be achieved by evaluating $?; here's an example how to store the return value and reuse it:
python xxx.py
result=$?
if [ ${result} -ne 0 ]; then
# Error
echo "xxx.py exited with ${result}"
...
else
# Success
...
fi
As a general rule, not only regarding Bash scripting but programming in general, always check return codes of commands for errors and handle them. It makes debugging and your working life in general easier in the long run.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48515428",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Does Perl 6 have an equivalent to Python's bytearray method? I can't find bytearray method or similar in Raku doc as in Python. In Python, the bytearray defined as this:
class bytearray([source[, encoding[, errors]]])
Return a new array of bytes. The bytearray class is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the str type has, see String Methods.
Does Raku should provide this method or some module?
A: brian d foy answer is essentially correct. You can pretty much translate this code into Perl6
my $frame = Buf.new;
$frame.append(0xA2);
$frame.append(0x01);
say $frame; # OUTPUT: «Buf:0x<a2 01>»
However, the declaration is not the same:
bu = bytearray( 'þor', encoding='utf8',errors='replace')
in Python would be equivalent to this in Perl 6
my $bú = Buf.new('þor'.encode('utf-8'));
say $bú; # OUTPUT: «Buf:0x<c3 be 6f 72>»
And to use something equivalent to the error transformation, the approach is different due to the way Perl 6 approaches Unicode normalization; you would probably have to use UTF8 Clean 8 encoding.
For most uses, however, I guess Buf, as indicated by brian d foy, is correct.
A: I think you're looking for Buf - a mutable sequence of (usually unsigned) integers. Opening a file with :bin returns a Buf.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51009154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Programmatically convert WAV I'm writing a file compressor utility in C++ that I want support for PCM WAV files, however I want to keep it in PCM encoding and just convert it to a lower sample rate and change it from stereo to mono if applicable to yield a lower file size.
I understand the WAV file header, however I have no experience or knowledge of how the actual sound data works. So my question is, would it be relatively easy to programmatically manipulate the "data" sub-chunk in a WAV file to convert it to another sample rate and change the channel number, or would I be much better off using an existing library for it? If it is, then how would it be done? Thanks in advance.
A: PCM merely means that the value of the original signal is sampled at equidistant points in time.
For stereo, there are two sequences of these values. To convert them to mono, you merely take piecewise average of the two sequences.
Resampling the signal at lower sampling rate is a little bit more tricky -- you have to filter out high frequencies from the signal so as to prevent alias (spurious low-frequency signal) from being created.
A: I agree with avakar and nico, but I'd like to add a little more explanation. Lowering the sample rate of PCM audio is not trivial unless two things are true:
*
*Your signal only contains significant frequencies lower than 1/2 the new sampling rate (Nyquist rate). In this case you do not need an anti-aliasing filter.
*You are downsampling by an integer value. In this case, downampling by N just requires keeping every Nth sample and dropping the rest.
If these are true, you can just drop samples at a regular interval to downsample. However, they are both probably not true if you're dealing with anything other than a synthetic signal.
To address problem one, you will have to filter the audio samples with a low-pass filter to make sure the resulting signal only contains frequency content up to 1/2 the new sampling rate. If this is not done, high frequencies will not be accurately represented and will alias back into the frequencies that can be properly represented, causing major distortion. Check out the critical frequency section of this wikipedia article for an explanation of aliasing. Specifically, see figure 7 that shows 3 different signals that are indistinguishable by just the samples because the sampling rate is too low.
Addressing problem two can be done in multiple ways. Sometimes it is performed in two steps: an upsample followed by a downsample, therefore achieving rational change in the sampling rate. It may also be done using interpolation or other techniques. Basically the problem that must be solved is that the samples of the new signal do not line up in time with samples of the original signal.
As you can see, resampling audio can be quite involved, so I would take nico's advice and use an existing library. Getting the filter step right will require you to learn a lot about signal processing and frequency analysis. You won't have to be an expert, but it will take some time.
A: I don't think there's really the need of reinventing the wheel (unless you want to do it for your personal learning).
For instance you can try to use libsnd
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2861435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Odd behavior with Ruby defined? I am a newbie at Ruby and have a question with the defined? keyword.
Here's a snippet of code that I've written to load a yaml file to initialize settings in my Ruby script:
# Read settings file
require 'YAML'
settingsFile = File.join(File.dirname(__FILE__), "settings.yml").tr('\\', '/')
Settings = YAML.load_file(settingsFile) unless defined? Settings
puts Settings
The yaml file looks like this:
Hello: World
This outputs correctly with:
{"Hello"=>"world"}
Now if I use a variable instead of a constant to store the settings, such as the following:
# Read settings file
require 'YAML'
settingsFile = File.join(File.dirname(__FILE__), "settings.yml").tr('\\', '/')
settings = YAML.load_file(settingsFile) unless defined? settings
puts settings
settings returns empty.
What gives? Why would using a constant make this work?
A: This is a quirk in the way Ruby handles trailing if/unless conditions and how variables come into existence and get "defined".
In the first case the constant is not "defined" until it's assigned a value. The only way to create a constant is to say:
CONSTANT = :value
Variables behave differently and some would argue a lot more strangely. They come into existence if they're used anywhere in a scope, even in blocks of code that get skipped by logical conditions.
In the case of your line of the form:
variable = :value unless defined?(variable)
The variable gets "defined" since it exists on the very line that's being executed, it's going to be conditionally assigned to. For that to happen it must be a local variable.
If you rework it like this:
unless defined?(variable)
variable = :value
end
Then the behaviour goes away, the assignment proceeds because the variable was not defined prior to that line.
What's strange is this:
if defined?(variable)
variable = :value
end
Now obviously it's not defined, it doesn't get assigned, but then this happens:
defined?(variable)
# => "local-variable"
Now it's defined anyway because Ruby's certain it's a variable. It doesn't have a value yet, it's nil, but it's "defined" as far as Ruby's concerned.
It gets even stranger:
defined?(variable)
# => false
if (false)
variable = :value
end
defined?(variable)
# => "local-variable"
Where that block of code didn't even run, it can't even run, and yet, behold, variable is now defined. From that assignment line on forward that variable exists as far as Ruby is concerned.
Since you're doing an attempted assignment and defined? on the same line the variable exists and your assignment won't happen. It's like a tiny paradox.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54446159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: When is disk cache cleared on iOS? I'm using the cache to store a bunch of rendered thumbnails for my game. It can easily go up to 60MB if the user has all the content in the game.
I wonder if I need to clear this out myself? Does the OS do this for me, and if so when?
Thanks!
A: When I had an issue with the documents directory on IOS5 I found this article which discusses the cache amongst other subjects.
As I understand it; yes the OS handles the cache and it will clear it when disk space is low. What low actually means in size I do not know.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9566018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I iterate through nested hash of hash without knowing its key? I have a hash of hashes, that is, hash and hash references in my data structure. Can I iterate through the deepest hash when I only have the main hash name and no key of the deepest hash?
my %gates_info=(
'order' => {
'nand' => {
'nand2_1' =>2,
'nand2_5' =>-1,
'nand2_4' =>2,
'nand2_6' =>-1,
'nand2_2' =>2,
'nand2_3' =>3
},
'and' => {
'and2'=>1,
'and3'=>2,
},
}
);
sub max_gate_order {
print values (%{$gates_info{'order'}});
my @arr = (sort {$a <=> $b} values %{$gates_info{'order'}});
return $arr[-1];
}
I want to iterate over the whole hash when I have just its name %gates_info and no keys such as "nand" or "and". What I am trying to achieve is to get the highest numeric value in each of the gates by sorting. Such as 3 in nand case and 2 in and case. Sub max_gate_order is used for sorting and returning highest value. Thanks
A: keys will give you those keys.
sub max_gate_order {
my ($gates_info) = @_;
my $max_order;
my @gates;
for my $gate_type (keys %{ $gates_info->{order} }) {
for my $gate_id (keys %{ $gates_info->{order}{$gate_type} }) {
my $order = $gates_info->{order}{$gate_type}{$gate_id};
$max_order //= $order;
if ($order >= $max_order) {
if ($order > $max_order) {
$max_order = $order;
@gates = ();
}
push @gates, $gate_id;
}
}
}
return @gates;
}
my @gates = max_gate_order(\%gates_info);
The above returns all the gates with the highest order.
If you want both the gate type and the gate id, replace
push @gates, $gate_id;
with
push @gates, [ $gate_type, $gate_id ];
or
push @gates, [ $gate_type, $gate_id, $order ];
A: This is a longer, more redundant solution, more of an exercise really. But you might find it interesting to examine the structure of the hash iteration this way. (I know I do!) This could be useful if you only have the main hash name (%gates_info), and none of the keys under that. Which is what your question implies is the case. This pulls out all the key and value names as deep as the hash goes, in case any of those might be useful. (Note this does require knowing how many levels deep your hash is.)
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my %gates_info=(
'order' => {
'nand' => {
'nand2_1' =>2,
'nand2_5' =>-1,
'nand2_4' =>2,
'nand2_6' =>-1,
'nand2_2' =>2,
'nand2_3' =>3
},
'and' => {
'and2'=>1,
'and3'=>2,
},
}
);
print Dumper %gates_info;
print "\n\n";
my @gate;
my $hival;
foreach my $gate (sort keys %gates_info) {
foreach my $gatekey (sort keys %{$gates_info{$gate}}) {
foreach my $deepkey (sort keys %{$gates_info{$gate}{$gatekey}}) {
my $deepvalue = $gates_info{$gate}->{$gatekey}->{$deepkey};
push @gate, $deepvalue;
@gate = sort @gate;
$hival = $gate[@gate - 1];
print "Gate is $gate, gatekey is $gatekey, deepkey is $deepkey, deepvalue is $deepvalue\n";
}
print "\nGatekey is $gatekey, highest value is $hival\n\n";
@gate = (); #empty gate array
}
}
exit 0;
The output of the code is:
$VAR1 = 'order';
$VAR2 = {
'and' => {
'and2' => 1,
'and3' => 2
},
'nand' => {
'nand2_3' => 3,
'nand2_6' => -1,
'nand2_4' => 2,
'nand2_5' => -1,
'nand2_2' => 2,
'nand2_1' => 2
}
};
Gate is order, gatekey is and, deepkey is and2, deepvalue is 1
Gate is order, gatekey is and, deepkey is and3, deepvalue is 2
Gatekey is and, highest value is 2
Gate is order, gatekey is nand, deepkey is nand2_1, deepvalue is 2
Gate is order, gatekey is nand, deepkey is nand2_2, deepvalue is 2
Gate is order, gatekey is nand, deepkey is nand2_3, deepvalue is 3
Gate is order, gatekey is nand, deepkey is nand2_4, deepvalue is 2
Gate is order, gatekey is nand, deepkey is nand2_5, deepvalue is -1
Gate is order, gatekey is nand, deepkey is nand2_6, deepvalue is -1
Gatekey is nand, highest value is 3
A: sub max_gate_order {
my %hash =();
foreach my $k (keys %{$gates_info{'order'}}) {
my @arr = (sort {$a <=> $b} values %{$gates_info{'order'}->{$k}});
$hash{$k} = $arr[-1];
}
return \%hash;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55744057",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can't add std_logic to unsigned I'm making a program to count all the 1's from a std_logic_vector, the out from the program should be a std_logic_vector too. The vector size is based on a generic number. To do the count, i'm using a for generate and adding the 1's to an unsigned signal, but it's not working. Here is the error from the ide:
Line 27. unsigned can not have such operands with returned type UNSIGNED.
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use ieee.std_logic_arith.all;
use IEEE.NUMERIC_STD.ALL;
entity proj2_1 is
GENERIC (N: INTEGER := 8); -- SIZE OF THE VECTOR
Port ( VTIN : in STD_LOGIC_VECTOR (N-1 downto 0);
VTOUT : out STD_LOGIC_VECTOR (N-1 downto 0);
cont: buffer unsigned (N-1 downto 0) );
end proj2_1;
architecture Behavioral of proj2_1 is
begin
gen: FOR i IN VTIN' RANGE GENERATE
BEGIN
cont <= cont + ( unsigned (VTIN(i)));
END GENERATE;
VTOUT <= std_logic_vector(cont);
end Behavioral;
A: First there should be no declaration of unsigned visible due to conflicts between packages std_logic_arith and numeric_std. Use one or the other (numeric_std is part of the VHDL standard).
Second the element type of VTIN is std_logic or std_ulogic depending on the VHDL revision which isn't compatible with the array type/subtype std_logic_vector. That means type conversion isn't legal.
Next a concurrent signal assignment is elaborated into a process which implies a driver for the longest static prefix (here cont). Having VTIN'LENGTH processes with generate 'X's, the values will be resolved, the driver outputs are shorted.
Instead of a generate statement use a process with a variable used to count '1's in a sequential loop statement with a for iteration scheme. The variable is used because the value of signal cont isn't updated until the process suspends. You assign the variable value to cont after the loop statement. After the process suspends, the value of cont will be available to use in the assignment to VTOUT. std_logic_arith can added a std_logic value to a std_logic_vector as can numeric_std in -2008 (otherwise unsigned(""& VTIN(i)) converts std_logic to unsigned. You could also implement a subprogram.
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
-- use ieee.std_logic_arith.all;
use IEEE.NUMERIC_STD.ALL;
entity proj2_1 is
GENERIC (N: INTEGER := 8); -- SIZE OF THE VECTOR
Port ( VTIN : in STD_LOGIC_VECTOR (N-1 downto 0);
VTOUT : out STD_LOGIC_VECTOR (N-1 downto 0);
cont: buffer unsigned (N-1 downto 0) );
end entity proj2_1;
architecture behavioral of proj2_1 is
begin
-- gen: FOR i IN VTIN' RANGE GENERATE
-- BEGIN
-- cont <= cont + ( unsigned (VTIN(i)));
-- END GENERATE;
SEQUENTIAL_LOOP_NOT_GENERATE_STATEMENT:
process (VTIN)
variable ones: unsigned(VTOUT'RANGE);
begin
ones := (others => '0'); -- zero
for i in VTIN'RANGE loop
ones := ones + unsigned'("" & VTIN(i));
end loop;
VTOUT <= std_logic_vector (cont + ones);
end process;
end architecture behavioral;
A generate statement is a concurrent statement which elaborates to a block statement for every value of the generate parameter containing the concurrent statement which has a process statement equivalent. A process statement has a driver for each signal assigned in it's sequence of statements. One driver versus lots of drivers.
With package numeric std you could also declare the variable (here ones) as an integer (natural). numeric_std supports the addition of natural range integers to unsigned values.
Notice there's nothing that defines an initial value for port cont which has a mode of buffer, essentially an output that be read internally. The default initial value will be (others => 'U')from the left most value of the enumerated type std_ulogic. Either the original intent is wrong (count all the 1's from a std_logic_vector" or more likely you actually one the population count of '1's in VTIN.
The latter requires a change:
architecture behavioral of proj2_1 is
begin
SEQUENTIAL_LOOP_NOT_GENERATE_STATEMENT:
process (VTIN)
variable ones: unsigned(VTOUT'RANGE);
begin
ones := (others => '0'); -- zero
for i in VTIN'RANGE loop
ones := ones + unsigned'("" & VTIN(i));
end loop;
-- VTOUT <= std_logic_vector (cont + ones);
VTOUT <= std_logic_vector (ones);
cont <= ones;
end process;
end architecture behavioral;
that doesn't reflect the original code but doesn't accumulate across new values of VTIN and is synthesis eligible.
The integer variable version of the population count of '1's could look like
architecture integer_variable of proj2_1 is
begin
SEQUENTIAL_LOOP_NOT_GENERATE_STATEMENT:
process (VTIN)
variable ones: natural;
begin
ones := 0;
for i in VTIN'RANGE loop
if TO_BIT(VTIN(i)) = '1' then
ones := ones + 1;
end if;
end loop;
VTOUT <= std_logic_vector (to_unsigned(ones, VTOUT'length));
cont <= to_unsigned(ones, VTOUT'length); -- and both outputs don't make sense
end process;
end architecture integer_variable;
where adding an integer value doesn't propagate meta values from VTIN during addition.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57845113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Array to string in JavaScript I get an array of numbers as a response from remote command execution (using ssh2). How do I convert it to a string?
[97,112,112,46,106,115,10,110,111,100,101,46,106,115,10]
A: var result = String.fromCharCode.apply(null, arrayOfValues);
JSFiddle
Explanations:
String.fromCharCode can take a list of char codes as argument, each char code as a separate argument (for example: String.fromCharCode(97,98,99)).
apply allows to call a function with a custom this, and arguments provided as an array (in contrary to call which take arguments as is). So, as we don't care what this is, we set it to null (but anything could work).
In conclusion, String.fromCharCode.apply(null, [97,98,99]) is equivalent to String.fromCharCode(97,98,99) and returns 'abc', which is what we expect.
A: It depends on what you want and what you mean.
Option One: If you want to convert the text to ASCII, do this:
var theArray = [97,112,112,46,106,115,10,110,111,100,101,46,106,115,10];
theString = String.fromCharCode.apply(0, theArray);
(Edited based on helpful comments.)
Produces:
app.js
node.js
Option Two: If you just want a list separated by commas, you can do .join(','):
var theArray = [97,112,112,46,106,115,10,110,111,100,101,46,106,115,10];
var theString = theArray.join(',');
You can put whatever you want as a separator in .join(), like a comma and a space, hyphens, or even words.
A: In node.js it's usually done with buffers:
> new Buffer([97,112,112,46,106,115,10,110,111,100,101,46,106,115,10]).toString()
'app.js\nnode.js\n'
It'll be faster than fromCharCode, and what's most important, it'll preserve utf-8 sequences correctly.
A: just use the toString() function:
var yourArray = [97,112,112,46,106,115,10,110,111,100,101,46,106,115,10];
var strng = yourArray.toString();
A: The ssh2 module passes a Buffer (not an actual javascript array) to 'data' event handlers for streams you get from exec() or shell(). Unless of course you called setEncoding() on the stream, in which case you'd get a string with the encoding you specified.
If you want the string representation instead of the raw binary data, then call chunk.toString() for example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21918048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Google Sheet - Calculate a cost I'm trying to reproduce that lovely website that helps you calculate the cost of something you bought into my personnal google sheet so it's easier for me to use it.
I'm seeking here for help since I don't really know how to adapt the math when you change the value of year/month/day.
As you may see, it's able to calculate the cost by year, but when you change the value to month for example, I don't know how to make it adjust the results.
I've tried =SUMIF, =IF, but I can't seem to find a clear way to do it.
here is the doc
Thanks a lot!
A: I think what you are looking for is the SWITCH function:
You can in the cell D6 use the following formula:
=SWITCH(F2; I2; E1/E2; I3; E1*12/E2; I4; E1*52/E2; I5; E1*365/E2)
The logic is:
*
*check the cell F2 (where you have the dropdown)
*if the value of F2 equals I2 (Year) then, just divide the cost by the number of years
*if the value of F2 equals I3 (Month), then make E1*12 and divide it by the the E2 (same as (E1/E2)/12
*if the value of F2 equals I4 (Week), then calculate E1*52/E2 (same as above but with 52 weeks)
*if the value of F2 equals I5 (Day), then calculate E1*365/E2 (same as above but with 365 days)
And so on on the other cells, just change the differences between the formulas, between day, week, month and year.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64207482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get number apps running in background I am working on an app which needs the information of how many application running in background at the system,
I want to get number of them.
Any idea please ?
A: This Below lines give the list of Apps which are in background,
ActivityManager actvityManager = (ActivityManager)
this.getSystemService( ACTIVITY_SERVICE );
List<RunningAppProcessInfo> procInfos = actvityManager.getRunningAppProcesses();
procInfos.size() gives you number of apps
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43419672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do i fix this Nested if command in excel? I have a excel doc in which I record the crashes of a certain application.
Inside one of the rows is the following
3/27/2016 | (Cell B39) | null | mins | null | secs | (Command)
... the command is,
=IF(ERROR.TYPE(B39) =3,"Hasn't Crashed Yet",IF(B39 =0, "No Crash", "Crashed"))
*
*when B39 = 0, i want it to output "No Crash".
*when B39 is any number greater than 0, i want it to output "Crashed".
*when B39 has an error, i want it to output "Hasn't Crashed Yet".
The current command outputs "Hasn't Crashed Yet" when B39 is an error, but when B39 is 0 or higher, it outputs #N/A.
A: Try,
=if(isnumber(B39), if(b39>0, "crashed", "no crash"), if(iserror(b39), "hasn't crashed yet", "how'd I get here?"))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36252154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why is rust-analyzer not finding dependencies in workspace member? I have a cargo workspace with one library "./raytracing" and one binary "./cli". The two workspace members have different dependencies.
./raytracing/Cargo.toml:
[package]
name = "raytracer"
version = "0.1.0"
edition = "2021"
[dependencies]
rand = "0.8.5"
./cli/Cargo.toml:
[package]
name = "cli"
version = "0.1.0"
edition = "2021"
[dependencies]
raytracer = {path = "../raytracer"}
rand = "0.8.5"
rand_xorshift = "0.3.0"
Parent directory Cargo.toml (./Cargo.toml)
[package]
edition = "2021"
name = "raytracing"
version = "0.1.0"
[workspace]
members = [
"raytracer",
"cli",
]
[[bin]]
path = "cli/src/main.rs"
name = "cli"
Compiling both the raytracer and cli packages using cargo build -p works, however in VSCode rust-analyzer complains about my dependencies in the ./cli package when I import them in main.rs:
Error
A: With your current setup you actually have two binaries compiled from the same source file: cli and raytracing. raytracing doesn't declare any [dependencies] so of course you're getting an error when trying to compile that. You haven't explained what you're trying to achieve, so I can't tell you the correct way to fix this problem. Generally, there's two things you can do:
*
*Make the root package virtual by deleting everything from ./Cargo.toml except the [workspace] section. (normal)
*Ditch the ./cli/Cargo.toml and move its [dependencies] section to ./Cargo.toml. (bit weird)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72121176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: multiple file upload jquery asp.net add, remove then add again I am currently experiencing the exact same problem as here: Multiple File Upload with jQuery [removing file then adding it again].
So far I have managed this:
function UploadFile(ajaxUrl, event)
{
if ($("p[id=alertFileCount]").is(":visible"))
$("p[id=alertFileCount]").hide();
if (ajaxUrl == '' || ajaxUrl === undefined)
{
ShowErrorAlertUploadFiles();
return;
}
var fileList = [];
var files = event.target.files;
var $elem = $("a.attachMessageBtn");
if (ValidateFilesCount(files) === false)
{
ShowErrorAlertUploadFiles();
return;
}
for (var i = 0; i < files.length; i++)
{
var file = files[i];
var ext = $("#fileAttach").val().split('.').pop().toLowerCase();
event.stopPropagation();
event.preventDefault();
if (ValidateFiles(file, ext) === false)
return;
else
{
var finalData = [];
var evtOnClick = $elem.attr('onclick');
var postData = new FormData();
postData.append("file", file);
// contentType: false _> Set content type to false as jQuery will tell the server its a query string request.
// enctype: "multipart/form-data" _> Compatibility with IE.
$.ajax({
url: ajaxUrl + "?a=setUploadFile",
type: "POST",
data: postData,
cache: false,
processData: false,
contentType: false,
forceSync: false,
enctype: "multipart/form-data",
beforeSend: function (jqXHR, settings)
{
$elem.attr('onclick', null);
},
success: function (data, textStatus, jqHXR)
{
fileList.push(file);
finalData = data.split('|');
UpdateFileUploadUI(finalData);
},
error: function (jqHXR, textStatus, errorThrown)
{
ShowErrorAlertUploadFiles();
if (jqXHR.getAllResponseHeaders() !== '')
LogError(errorThrown, this.url, 0, 0, this.type + ': ' + this.data);
},
complete: function (jqXHR, textStatus)
{
$elem.attr('onclick', evtOnClick);
}
});
}
}
}
function ValidateFilesCount(files)
{
var currFiles = files.length;
var currAttachFilesAddRemove = $("#attachFilesAddRemove > div.attached").length;
var currFileTempNames = $("#fileTempNames").val().split('?').length;
if (currFiles > 3
|| currAttachFilesAddRemove > 3
|| currFileTempNames > 3
|| currFiles + currAttachFilesAddRemove > 3)
{
ShowNoContentUploadFiles('{ERROR MESSAGE HERE}');
return false;
}
return true;
}
function ValidateEmptyFile(file)
{
if (file.size == 0)
return false;
return true;
}
function ValidateFileMaxSize(file)
{
var maxFileSize = 4 * 1024 * 1024;
if (file != null && file.size > maxFileSize)
return false;
return true;
}
function ValidateFileExt(ext)
{
if ($.inArray(ext, ['exe']) > -1)
return false;
return true;
}
function ShowNoContentUploadFiles(text)
{
var $pNoContent = $("p[id=alertFileCount]");
$pNoContent.html(text);
$pNoContent.show().css({ opacity: 1, display: "block" });
}
function ValidateFiles(file, ext)
{
var text = '';
var isInvalid = false;
if (ValidateEmptyFile(file) === false)
{
text = 'You may only upload files with over 0bytes.';
isInvalid = true;
}
if (ValidateFileMaxSize(file) === false)
{
text = 'You may only upload files with up to 4MB.';
isInvalid = true;
}
if (ValidateFileExt(ext) === false)
{
text = 'Files with extension \'.exe\' will not be uploaded.';
isInvalid = true;
}
if (isInvalid === true)
{
ShowNoContentUploadFiles(text);
return false;
}
return true;
}
function UpdateFileUploadUI(finalData)
{
UpdateFilesAddRemove(finalData);
UpdateFileDataMediaUID();
}
function UpdateFilesAddRemove(finalData)
{
var fileData = finalData[0] + '|' + finalData[1];
$("div[id=attachFilesAddRemove]").append("<div class='attached' data-mediauid='"
+ fileData
+ "'><a class='file' style='cursor: pointer;'>"
+ finalData[0]
+ "</a><a onclick=\"RemoveAttachedFile(\'"
+ fileData
+ "\');\" style='cursor: pointer;' class='close'></a></div>");
}
function UpdateFileDataMediaUID()
{
var listData = '';
$("div[id=attachFilesAddRemove] > .attached").each(function (i, obj)
{
listData += $(obj).attr("data-mediauid") + '?';
});
listData = listData.slice(0, -1);
$("input[id=fileTempNames]").val(listData);
}
function RemoveAttachedFile(fileData)
{
if (fileData == '' || fileData === undefined)
return;
// Update the names in fileTempNames.
var result = '';
var $iElem = $("input[id=fileTempNames]");
var names = $iElem.val().split('?');
for (var i = 0; i < names.length; i++)
{
if (names[i] != '' && names[i] != fileData)
{
result += names[i] + '?';
}
}
$iElem.val(result);
$("div[data-mediauid='" + fileData + "']").remove();
}
function ShowErrorAlertUploadFiles()
{
SetAlertBoxTitleAndText('', 'At the moment it was not possible to proceed with the upload, please try again later.', true);
ShowAlertBox();
}
Also have this for file upload in html:
<a class="attachMessageBtn" style="cursor: pointer; position: relative; overflow: hidden; direction: ltr;">Adicionar ficheiro
<input id="fileAttach" type="file" name="file" multiple="multiple" title="Adicionar ficheiro" style="position: absolute; right: 0px; top: 0px; font-family: Arial; font-size: 118px; margin: 0px; padding: 0px; cursor: pointer; opacity: 0;" onchange="UploadFile('<%=VirtualPathUtility.ToAbsolute({SERVER ADDRESS HERE})%>', event);" accept="*">
</a>
<input id="fileTempNames" type="hidden" value="">
<div class="attachFiles" id="attachFilesAddRemove"></div>
<p id="alertFileCount" style="display: none;"></p>
Both the error message and the server address, between {}, are actually properly coded, just not displayed here.
My apologies for the length of code.
I need a simple way of adding up to 3 files as attachments, then if the user wishes to add one, remove it and add it again, it must be working. My code works fine on Firefox, but of course this sort of excuse does not work in a company.
Most teams here use plugins, but I am out of such option, as I have already tryed it, and was 20 times harder to put it working, due to the enormous ammount of changes the code would have to suffer (changes I have neither time nor authorization to proceed with).
Any help, please? One of the comments in the post I linked says the fiddle made was working fine, but I tested it, and same issue, on chrome and IE nothing, on firefox it works fine.
Furthermore I must add that I have only one year of experience in programming in general, most of it for mobile platform Android, which does not equip me with the required skills to understand most of the working engine behind browsers or even web browsing in general.
Thank you so much in advance.
A: ended up giving up the idea of uploading to a temporary folder, and them move the files when the message is sent. rather, now, I send everything on the same FormData object (using a mixture of both here http://www.c-sharpcorner.com/UploadFile/manas1/upload-files-through-jquery-ajax-in-Asp-Net-mvc/ and here JQuery ajax file upload to ASP.NET with all form data, and for now it is working (which is actually enough for me)...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37488549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can the S3 SDK figure out a bucket's region on its own? I'm writing an Amazon S3 client that might potentially access buckets in different regions. Our IT department is fairly strict about outgoing HTTP, and I want to use path-style access for this client to avoid having to make firewall changes for each new bucket.
My client uses the java SDK v1.4.4.2. As a test, I created a bucket in Singapore, then took a working S3 unit test that lists objects, and changed it to use path-style access:
AmazonS3 client = new AmazonS3Client(environ);
client.setS3ClientOptions(new S3ClientOptions().withPathStyleAccess(true));
When I run the unit test with this version of the client, all S3 accesses fail with the error that I have to set the right endpoint.
My question is, do I have to add the logic to look up the bucket's region and set that for the client? Or can the SDK be set to do that on its own? It seems the SDK should be able to do this automatically, since the function to look up a bucket's location is in there.
As a side issue, are there any particular performance issues with using path-style access? I presume it's just an extra round trip to query the bucket's location if I don't already know it.
A: As stated in the documentation, The path-style syntax, however, requires that you use the region-specific endpoint when attempting to access a bucket. In other words, with path style access, you've to tell to the SDK in which region is the bucket, it doesn't try to determine it on its own.
Performance wise, there should not be a difference.
A: If you need the client to access objects in different region, you probably want to use the option:
AmazonS3ClientBuilder builder.withForceGlobalBucketAccessEnabled(true)
to build your client... See the s3 client builder documentation
this with ensure successful requests even if the client default region is not the same as the bucket/object targeted.
Also, if you need to get the bucket "mybucketname" exact end-point, you can use (headBucketResult ref page):
s3client.headBucket(HeadBucketRequest("mybucketname")).getBucketRegion()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17117648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: undefined reference to function when compiling using makefiles C I am trying to run some experiments using a set of functions inside a file called coco.c (from the coco optimisation platform which can be found at https://github.com/numbbo/coco). This file also comes with a header file coco.h. I have been trying to test if the calling functions from the coco.c file works by writing my own file called testing.c.
The full testing.c file can be seen below
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include "coco.h"
#define max(a,b) ((a) > (b) ? (a) : (b))
int main(void){
coco_suite_t *suite;
suite = coco_suite("bbob-biobj", "", "");
return 0;
}
I have placed placed both coco.h and coco.c in the same folder as testing.c along with my Makefile.in. coco_suite is a function inside coco.c.
The makefile that I have been using can be seen below (most of which I have copied from the example makefile).
## Makefile
LDFLAGS += -lm
CCFLAGS ?= -g -ggdb --std+c89 -pedantic -Wall -Wextra -Wstrict-prototypes -Wshadow -Wno-sign-compare -Wconversion
all: testing
clean:
rm -f coco.o
rm -f testing.o testing
testing: testing.o coco.o
gcc ${CCFLAGS} -o testing coco.o testing.o ${LDFLAGS}
coco.o: coco.h coco.c
gcc -c ${CCFLAGS} -o coco.o coco.c
testing.o: coco.h coco.c testing.c
gcc -c ${CCFLAGS} -o testing.o testing.c
However, when attempting to build the executable I get an error saying undefined reference to coco_suite. I know that the function prototype is in the header file and the full code is in the source file as I have successfully run the example provided by the authors of the coco platform. I have doublechecked the whitespace (tabs vs spaces etc) and it matches exactly with the working example provided. However even when I copy and paste the example code into the testing.c file I get the same error.
This leads me to believe that the issue is in the makefile but I cant see what it is.
Does anyone know what the issue could be?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71765694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: getchar not taken in consideration after scanf I'm learning programmation in C and tried to create a program that asks the user his age. When the user writes his age (for example 18) he gets the message "So you're 18 years old". When I execute the .exe file it automatically closes after you see the message, so fast that you don't see it. Then I added getchar so that the user reads the message and then presses Enter to quite. Here's the program I wrote:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int age=0;
printf("How old are you?\n");
scanf("%d",&age);
printf("So you're %d years old", age);
getchar();
return 0;
}
Unfortunately, when I execute the .exe file, it still closes automatically like if the getchar() doesn't exist and I don't know why.
A: scanf("%d",&age);
When the execution of the program reaches the above line,you type an integer and press enter.
The integer is taken up by scanf and the \n( newline character or Enter )which you have pressed remains in the stdin which is taken up by the getchar().To get rid of it,replace your scanf with
scanf("%d%*c",&age);
The %*c tells scanf to scan a character and then discard it.In your case,%*c reads the newline character and discards it.
Another way would be to flush the stdin by using the following after the scanf in your code:
while ( (c = getchar()) != '\n' && c != EOF );
Note that c is an int in the above line
A: You're only having trouble seeing the result because you're starting the program from a windowing environment, and the window closes as soon as its internal tasks are completed. If you run the compiled program from a command line in a pre-existing shell window (Linux, Mac, or Windows), the results will stay on the screen after you're returned to the prompt (unless you've ended by executing a clear-screen of some sort). Even better, in that case, you don't need the extraneous getchar() call.
For Windows, after opening the command prompt window, you'd issue a "cd" command to change to the directory that contains the compiled program, and then type its name. For Linux (and, I presume, Mac, since Mac is UNIX under the hood), you'd need to type ./ ahead of the program name after changing to the appropriate directory with "cd".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26828370",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Qpid Erlang Module I am newbie to erlang but managed to get the ActiveMQ talking to my erlang shell using qpid pronton c library as, which is working well and i am getting messages from queue itself on my erlang shell and vice versa.
qpidpn:subscribe("amqp://localhost/topic://xxx").
qpidpn:publish(#{address => "amqp://127.0.0.1/topic://xxx", body => "hello"}).
Now, i want to implement the same above stated code using .erl file with some function getting invoked everytime we have new message on the queue and i can take further action of returning the same to origin.
A: You can implement gen_server, as seems the messages are coming from some MQ. So, you can get the messages in handle_info. Once there you can do whatever you want to do with them.
A: Well, it all depends on how your subscriber is implemented (is it another process, TCP listener, do you use gen_event behaviour, does it decode any data for you .... ).
Since you are using AMQP protocol for communication, you could use RabbitMQ as client. You would get whole AMQP implementation (with all responses to your broker), and some model for getting messages or subscribing to channels. Code-base is mature, whole project is stable, and most of logic is written for you, so I would strongly recommend using this approach.
The "invoked everytime we have new message on the queue" is somewhat explained in subscibe to que section.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24484494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Swift: TableViewController in NavigationController - Change distance between first static cell and top Ive created just a new xcode project without any coding. I just worked in the storyboard. There I have a Navigation Controller. My RootViewController has a TableView with Static cells in 3 sections (Grouped). The Section headers I deleted. My next step was to change the distances between the sections. For top I said 4 and for bottom 4, too. It looks now like this:
Now my problem: The size between the first section and the top is really big (I think 32 because thats the automatic distance between the sections). THe only place I found something was the size inspector - Content Insets. This is set to automatic. With no option I can put some values in myself. If I choose never there, the section got displayed under the Root View Controller header. My size inspector looks like this:
Can anyone tell me how I can reduce the size between viewController top and first section? Exactly I want to have a size of 16 between first section and the header of the Root View Controller.
And is there a way to do a change for the complete project so that also upcoming navigation controllers will have their tableview with a size of 16 between first section and the header?
What Ive tried: I found this question Why is there extra padding at the top of my UITableView with style UITableViewStyleGrouped in iOS7 Here someone asked for tableViews in general. The solutions I readed there which didnt worked for me:
*
*Turn Adjust scroll view insets off. I tried this for the root as well as the navigation controller. I also tried to solve the problem in code.
*Set edgesForExtendedLayout to none in viewDidLoad - nothing changed.
*Set the header just for first section to 1.
*self.navigationController?.navigationBar.isTranslucent = true changed nothing
Half correct: One solution was changing the contenInset manually in code. I dont like this because I would have to type the 16 points hard in my code. I dont know there the header of 32 comes from. So I dont know if the 16 points will stay forever. So I want a safer solution for future as well. THis was the hard solution:
self.tableView.contentInset = UIEdgeInsetsMake(-16, 0, 0, 0)
A: That top space comes from grouped style tableView header. You can add your own table header view at top of the table, set its color to "Group Table View Background Color", and set its height to what you want (16).
A: iOS11 Pure code Solution
Anyone looking to do this in pure code and remove the 35px empty space needs to add a tableHeaderView to their tableView - it appears having it as nil just sets it as default sizing of 35px
i.e.
tableView.tableHeaderView = tableHeaderView
var tableHeaderView:UIView = {
let view = UIView()
view.frame = CGRect(x: 0, y: 0, width: tableView.bounds.width, height: CGFloat.leastNormalMagnitude)
return view
}()
Note device width would be your bounds/view width and height is NOT 0 - but CGFloat.leastNormalMagnitude
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48022360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Flutter Exception caught by gesture: a ticker was started twice I have a Flutter application that communicates with the android native code through EventChannel and MethodChannel in order to start or stop an SDK and listen and display in the Flutter Ui the event generated by the SDK.
Everything work fine until I decide to stop and re-start the SDK through a floatingActionButton.
After pressing it the UI freezes and in the Console of Android studio I get the following Exception:
======== Exception caught by gesture ===============================================================
The following assertion was thrown while handling a gesture:
A ticker was started twice.
A ticker that is already active cannot be started again without first stopping it.
The affected ticker was: _WidgetTicker(created by _GlowingOverscrollIndicatorState#d8a61)
The stack trace when the _WidgetTicker was actually created was:
#0 new Ticker.<anonymous closure> (package:flutter/src/scheduler/ticker.dart:67:40)
#1 new Ticker (package:flutter/src/scheduler/ticker.dart:69:6)
#2 new _WidgetTicker (package:flutter/src/widgets/ticker_provider.dart:271:81)
#3 TickerProviderStateMixin.createTicker (package:flutter/src/widgets/ticker_provider.dart:202:34)
#4 new _GlowController (package:flutter/src/widgets/overscroll_indicator.dart:333:33)
#5 _GlowingOverscrollIndicatorState.initState (package:flutter/src/widgets/overscroll_indicator.dart:187:27)
#6 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4728:57)
#7 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4561:5)
... Normal element mounting (27 frames)
#34 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3631:14)
#35 MultiChildRenderObjectElement.inflateWidget (package:flutter/src/widgets/framework.dart:6261:36)
#36 MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6272:32)
... Normal element mounting (22 frames)
#58 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3631:14)
#59 MultiChildRenderObjectElement.inflateWidget (package:flutter/src/widgets/framework.dart:6261:36)
#60 MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6272:32)
... Normal element mounting (261 frames)
#321 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3631:14)
#322 MultiChildRenderObjectElement.inflateWidget (package:flutter/src/widgets/framework.dart:6261:36)
#323 Element.updateChild (package:flutter/src/widgets/framework.dart:3383:18)
#324 RenderObjectElement.updateChildren (package:flutter/src/widgets/framework.dart:5684:32)
#325 MultiChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6284:17)
#326 Element.updateChild (package:flutter/src/widgets/framework.dart:3370:15)
#327 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4613:16)
#328 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4763:11)
#329 Element.rebuild (package:flutter/src/widgets/framework.dart:4311:5)
#330 StatefulElement.update (package:flutter/src/widgets/framework.dart:4795:5)
#331 Element.updateChild (package:flutter/src/widgets/framework.dart:3370:15)
#332 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4613:16)
#333 Element.rebuild (package:flutter/src/widgets/framework.dart:4311:5)
#334 ProxyElement.update (package:flutter/src/widgets/framework.dart:4943:5)
#335 Element.updateChild (package:flutter/src/widgets/framework.dart:3370:15)
#336 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4613:16)
#337 Element.rebuild (package:flutter/src/widgets/framework.dart:4311:5)
#338 ProxyElement.update (package:flutter/src/widgets/framework.dart:4943:5)
#339 _InheritedNotifierElement.update (package:flutter/src/widgets/inherited_notifier.dart:111:11)
#340 Element.updateChild (package:flutter/src/widgets/framework.dart:3370:15)
#341 SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6130:14)
#342 Element.updateChild (package:flutter/src/widgets/framework.dart:3370:15)
#343 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4613:16)
#344 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4763:11)
#345 Element.rebuild (package:flutter/src/widgets/framework.dart:4311:5)
#346 StatefulElement.update (package:flutter/src/widgets/framework.dart:4795:5)
#347 Element.updateChild (package:flutter/src/widgets/framework.dart:3370:15)
#348 SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6130:14)
#349 Element.updateChild (package:flutter/src/widgets/framework.dart:3370:15)
#350 SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6130:14)
#351 Element.updateChild (package:flutter/src/widgets/framework.dart:3370:15)
#352 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4613:16)
#353 Element.rebuild (package:flutter/src/widgets/framework.dart:4311:5)
#354 ProxyElement.update (package:flutter/src/widgets/framework.dart:4943:5)
#355 Element.updateChild (package:flutter/src/widgets/framework.dart:3370:15)
#356 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4613:16)
#357 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4763:11)
#358 Element.rebuild (package:flutter/src/widgets/framework.dart:4311:5)
#359 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2578:33)
#360 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:882:21)
#361 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:363:5)
#362 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1145:15)
#363 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1082:9)
#364 SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:996:5)
#368 _invoke (dart:ui/hooks.dart:150:10)
#369 PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:270:5)
#370 _drawFrame (dart:ui/hooks.dart:114:31)
(elided 3 frames from dart:async)
When the exception was thrown, this was the stack:
#0 Ticker.start.<anonymous closure> (package:flutter/src/scheduler/ticker.dart:151:9)
#1 Ticker.start (package:flutter/src/scheduler/ticker.dart:158:6)
#2 _GlowController.pull (package:flutter/src/widgets/overscroll_indicator.dart:443:29)
#3 _GlowingOverscrollIndicatorState._handleScrollNotification (package:flutter/src/widgets/overscroll_indicator.dart:262:29)
#4 Element.visitAncestorElements (package:flutter/src/widgets/framework.dart:4091:39)
#5 Notification.dispatch (package:flutter/src/widgets/notification_listener.dart:83:13)
#6 DragScrollActivity.dispatchOverscrollNotification (package:flutter/src/widgets/scroll_activity.dart:472:135)
#7 ScrollPosition.didOverscrollBy (package:flutter/src/widgets/scroll_position.dart:918:15)
#8 ScrollPosition.setPixels (package:flutter/src/widgets/scroll_position.dart:282:9)
#9 ScrollPositionWithSingleContext.setPixels (package:flutter/src/widgets/scroll_position_with_single_context.dart:82:18)
#10 ScrollPositionWithSingleContext.applyUserOffset (package:flutter/src/widgets/scroll_position_with_single_context.dart:124:5)
#11 ScrollDragController.update (package:flutter/src/widgets/scroll_activity.dart:387:14)
#12 ScrollableState._handleDragUpdate (package:flutter/src/widgets/scrollable.dart:646:12)
#13 DragGestureRecognizer._checkUpdate.<anonymous closure> (package:flutter/src/gestures/monodrag.dart:449:55)
#14 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:198:24)
#15 DragGestureRecognizer._checkUpdate (package:flutter/src/gestures/monodrag.dart:449:7)
#16 DragGestureRecognizer.handleEvent (package:flutter/src/gestures/monodrag.dart:298:9)
#17 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:94:12)
#18 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:139:9)
#19 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:539:8)
#20 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:137:18)
#21 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:123:7)
#22 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:439:19)
#23 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:419:22)
#24 RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:322:11)
#25 GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:374:7)
#26 GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:338:5)
#27 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:296:7)
#28 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:279:7)
#32 _invoke1 (dart:ui/hooks.dart:169:10)
#33 PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:293:7)
#34 _dispatchPointerDataPacket (dart:ui/hooks.dart:88:31)
(elided 3 frames from dart:async)
Handler: "onUpdate"
Recognizer: VerticalDragGestureRecognizer#72195
start behavior: start
====================================================================================================
This is my java code in the Android folder (MainActivity.java):
public class MainActivity extends FlutterActivity implements ILogListener, IPositionEventListener {
private static final int PERMISSIONS_REQUEST_LOCATION = 2;
public static String authkey = "authkey";
public static String deviceID = "deviceID";
private MySDK mySDK;
private static final String channel = "channel_events_positions_updates";
private static final String channel1 = "mySDK";
private EventChannel.EventSink eventSink = null;
private Handler handler;
@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine);
EventChannel event = new EventChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), channel);
event.setStreamHandler(new EventChannel.StreamHandler() {
@Override
public void onListen(Object listener, EventChannel.EventSink eventSink) {
startListening(listener, eventSink);
}
@Override
public void onCancel(Object listener) {
cancelListening(listener);
}
});
new MethodChannel(flutterEngine.getDartExecutor(), channel1).setMethodCallHandler(
(call, result) -> {
if (call.method.equals("setAuthekyAndDeviceID")) {
if (call.argument("authkey") != null && call.argument("deviceID") != null) {
authkey = call.argument("authkey").toString();
deviceID = call.argument("deviceID").toString();
}
} else if (call.method.equals("stopService")) {
onStop();
} else {
result.notImplemented();
}
});
}
@Override
protected void onStop() {
if(mySDK!=null){
handler.removeCallbacksAndMessages(null);
eventSink = null;
mySDK.Stop();
super.onStop();
}
}
protected void startSDK() {
Set<String> missingPermissions = new HashSet<>();
ArrayList<String> perms = new ArrayList<>();
perms.add(Manifest.permission.ACCESS_FINE_LOCATION);
perms.add(Manifest.permission.ACCESS_COARSE_LOCATION);
perms.add(Manifest.permission.INTERNET);
perms.add(Manifest.permission.ACCESS_NETWORK_STATE);
perms.add(Manifest.permission.RECEIVE_BOOT_COMPLETED);
perms.add(Manifest.permission.WAKE_LOCK);
perms.add(Manifest.permission.VIBRATE);
perms.add(Manifest.permission.BLUETOOTH);
perms.add(Manifest.permission.BLUETOOTH_ADMIN);
perms.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
perms.add(Manifest.permission.READ_EXTERNAL_STORAGE);
checkPerms(missingPermissions, perms);
if (!missingPermissions.isEmpty()) {
// ask for permissions
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(missingPermissions.toArray(new String[0]),
missingPermissions.size());
}
if (!missingPermissions.isEmpty()) {
return;
// will try again after onRequestPermissionsResult
}
}
buildSdk();
mySDK.Start();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSIONS_REQUEST_LOCATION) {
for (int result : grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
break;
}
}
this.getApplicationContext();
buildSdk();
mySDK.Start();
}
}
private void checkPerms(Set<String> missingPermissions, ArrayList<String> perms) {
for (String perm : perms) {
if (ContextCompat.checkSelfPermission(this, perm) != PackageManager.PERMISSION_GRANTED) {
missingPermissions.add(perm);
}
}
}
private ConnectionConfig generateConnectionConfig() {
ConnectionConfig result = new ConnectionConfig();
result.setDeviceId(deviceID);
result.setAuthkey(authkey);
return result;
}
private void buildSdk() {
mySDK.Builder builder = new mySDK.Builder(this);
builder.setConnectionConfig(generateConnectionConfig());
builder.addLogListener(this);
builder.setPositionEventListener(this);
builder.setNotification(demo);
mySDK = builder.build();
mySDK.Start();
log("SDK Started");
}
public void log(String _message) {
log(_message, false, false);
}
@Override
public void log(String _message, boolean _vibrate, boolean _sound) {
sendMessageToEventChannel("[LOG]" +_message);
}
private void sendMessageToEventChannel(String _message) {
Runnable runnable = () -> {
if (eventSink != null) {
eventSink.success(_message);
}
};
handler.post(runnable);
}
@Override
public void onPositionEntry(Iterable<? extends BasicPosition> positions) {
if (positions != null) {
String position = positions.iterator().next().getName() + "\n" + positions.iterator().next().getAttributes();
sendMessageToEventChannel(position);
}
}
public void startListening(Object listener, EventChannel.EventSink event) {
handler = new Handler(Looper.getMainLooper());
eventSink = event;
startSDK();
}
public void cancelListening(Object listener) {
onStop();
}
}
And this is my dart class in which I manage the SDK:
class StateScreen extends StatefulWidget {
const StateScreen({Key? key, required this.authkey, required this.deviceID})
: super(key: key);
final String authkey;
final String deviceID;
State<StateScreen> createState() => _StateScreenState();
}
class _StateScreenState extends State<StateScreen> {
static const platform = MethodChannel('mySDK');
static const channel = const EventChannel('channel_events_positions_updates');
bool serviceStarted = false;
late StreamSubscription _positionEventSubscription;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My App'),
),
backgroundColor: Colors.white,
body: Center(
child: Column(
children: <Widget>[
PositionsView(logs: logs),
Padding(
padding: const EdgeInsets.only(top: 20.0),
child: ConstrainedBox(
constraints: new BoxConstraints(
maxHeight: 230.0,
),
child: new ListView.separated(
itemCount: names.length,
scrollDirection: Axis.vertical,
shrinkWrap: true,
separatorBuilder: (BuildContext context, int index) =>
const Divider(),
itemBuilder: (BuildContext context, int index) {
return Container(
margin: EdgeInsets.all(6),
child: Text(
'${names[index]}',
style: TextStyle(fontSize: 10),
),
);
},
),
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
if (serviceStarted) {
serviceStarted = false;
stopSDK();
} else {
serviceStarted = true;
startSDK();
}
});
},
child: Icon(serviceStarted ? Icons.stop : Icons.play_arrow),
),
);
}
String logs = "";
List<String> names = <String>[];
void startSDK() async {
_setAuthkeyAndDeviceID(widget.authkey, widget.deviceID);
_positionEventSubscription = channel.receiveBroadcastStream().listen((msg) {
setState(() {
print(msg);
if (msg.toString().contains("[LOG]")) {
var log = msg.toString().replaceAll("[LOG]", "");
print(log);
names.add(log);
} else {
logs = msg;
}
});
});
}
void _disablePositionEventSubscription() {
_positionEventSubscription.cancel();
}
void stopSDK() async {
try {
await platform.invokeMethod('stopService');
_disablePositionEventSubscription();
super.dispose();
} on PlatformException catch (e) {
print("Failed to get: '${e.message}'.");
}
}
Future<void> _setAuthkeyAndDeviceID(String authkey, String deviceID) async {
try {
await platform.invokeMethod(
'setAuthekyAndDeviceID', {"authkey": authkey, "deviceID": deviceID});
} on PlatformException catch (e) {
print("Failed to get: '${e.message}'.");
}
}
}
Anyone know how can I fix this exception?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72232153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: benchmarking PHP vs Pylons I want to benchmark PHP vs Pylons. I want my comparison of both to be as even as possible, so here is what I came up with:
*
*PHP 5.1.6 with APC, using a smarty template connecting to a MySQL database
*Python 2.6.1, using Pylons with a mako template connecting the the same MySQL database
Is there anything that I should change in that setup to make it a more fair comparison?
I'm going to run it on a spare server that has almost no activity, 2G of ram and 4 cores.
Any suggestions of how I should or shouldn't benchmark them? I plan on using ab to do the actual benchmarking.
Related
*
*Which is faster, python webpages or php webpages?
A: If you're not using an ORM in PHP you should not use the SQLAlchemy ORM or SQL-Expression language either but use raw SQL commands. If you're using APC you should make sure that Python has write privileges to the folder your application is in, or that the .py files are precompiled.
Also if you're using the smarty cache consider enabling the Mako cache as well for fairness sake.
However there is a catch: the Python MySQL adapter is incredible bad. For the database connections you will probably notice either slow performance (if SQLAlchemy performs the unicode decoding for itself) or it leaks memory (if the MySQL adapter does that).
Both issues you don't have with PHP because there is no unicode support. So for total fairness you would have to disable unicode in the database connection (which however is an incredible bad idea).
So: there doesn't seem to be a fair way to compare PHP and Pylons :)
A: *
*your PHP version is out of date, PHP has been in the 5.2.x area for awhile and while there are not massive improvements, there are enough changes that I would say to test anything older is an unfair comparison.
*PHP 5.3 is on the verge of becomming final and you should include that in your benchmarks as there are massive improvements to PHP 5.x as well as being the last version of 5.x, if you really want to split hairs PHP 6 is also in alpha/beta and that's a heavy overhaul also.
*Comparing totally different languages can be interesting but don't forget you are comparing apples to oranges, and the biggest bottleneck in any 2/3/N-Tier app is waiting on I/O. So the biggest factor is your database speed, comparing PHP vs Python VS ASP.Net purely on speed is pointless as all 3 of them will execute in less than 1 second but yet you can easily wait 2-3 seconds on your database query, depending on your hardware and what you are doing.
*If you are worried what is faster, you're taking the absolute wrong approach to choosing a platform. There are more important issues, such as (not in order):
a. How easily can I find skilled devs in that platform
b. How much do those skilled devs cost
c. How much ROI does the language offer
d. How feature rich is the language
| {
"language": "en",
"url": "https://stackoverflow.com/questions/674739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Passing same value of method to multiple forms In my window application I have orderNumber that need to be passed to another form. This order number is generated by the code which I will put below. I am trying to pass only 1 identical order number to two locations but unfortunately, two different order number passed to both location. How can I make that only one order number is passed to both location.
Code that generates the order number:
public string orderNumber()
{
string ord = "ORD" + get_next_id() + DateTime.Now.Year;
return ord;
}
public int get_next_id()
{
OleDbConnection objConnection = null;
OleDbCommand objCmd = null;
String sql;
int res;
// Create and open the connection object
objConnection = new OleDbConnection(connString);
objConnection.Open();
sql = "SELECT IIF(MAX(Customer.NumGenerate) IS NULL,100,MAX(Customer.NumGenerate)) as v_max FROM Customer;";
objCmd = new OleDbCommand(sql, objConnection);
res = (int)objCmd.ExecuteScalar();
++res;
objConnection.Close();
return res;
}
In the first form the following insert method uses the order number:
private void SaveAllListItems()
{
string listItems = string.Empty;
foreach (var listBoxItem in listBox1.Items)
{
listItems += listBoxItem.ToString();
if (listBox1.Items.IndexOf(listBoxItem) < listBox1.Items.Count - 1)
{
listItems += ", ";
}
}
InsertUser(maskedTextBox1.Text, comboBox1.Text, maskedTextBox2.Text, maskedTextBox3.Text, maskedTextBox4.Text, maskedTextBox5.Text,
maskedTextBox6.Text, maskedTextBox7.Text, maskedTextBox8.Text, maskedTextBox9.Text, listItems, DateTime.Now, maskedTextBox10.Text, orderNumber(), get_next_id());
;
}
In second form I want to use the same order number which is being used to insert user. right now I have the following code which is not working as form1 has different order number and form 2 has different.
private void FindOrder()
{
Form1 m = new Form1();
string number = m.orderNumber();
// string number = "ORD1012013";
string InvSql = "SELECT (Customer.[Title] + SPACE(2) + Customer.[Customer's Name]) as CustomerName, Customer.[Customer's Ebayname], Customer.[Email Address], Customer.[Phone Number], (Customer.[Address 1] + SPACE(2) +Customer.[Address 2] + SPACE(2) + Customer.[City] + SPACE(2) + Customer.[Post Code]+ SPACE(2) + Customer.[Country]) as Address, Customer.[Item Purchased], Customer.[Purchased Date], Customer.[Total Price], Customer.[OrderNumber] FROM Customer WHERE Customer.[OrderNumber]= '" + number + "'";
OleDbConnection cnn = new OleDbConnection(connString);
OleDbCommand cmdOrder = new OleDbCommand(InvSql, cnn);
cnn.Open();
OleDbDataReader rdrOrder = cmdOrder.ExecuteReader();
rdrOrder.Read();
custName.Text = rdrOrder["CustomerName"].ToString();
ebayName.Text = rdrOrder["Customer's Ebayname"].ToString();
email.Text = rdrOrder["Email Address"].ToString();
phone.Text = rdrOrder["Phone Number"].ToString();
address.Text = rdrOrder["Address"].ToString();
item.Text = rdrOrder["Item Purchased"].ToString();
date.Text = Convert.ToString(Convert.ToDateTime(rdrOrder["Purchased Date"]));
price.Text = rdrOrder["Total Price"].ToString();
order.Text = rdrOrder["OrderNumber"].ToString();
rdrOrder.Close();
cnn.Close();
}
How can I pass same order number to both location?
A: Data can be passed between forms in different ways.
Here's a good tutorial on how to do that.The Constructor and Property approach is easier to implement.
You dont seem to be saving the orderid on the form1 class
Declare a variable for the OrderID on Form1 class
string OrderId;
Modify your exisiting Method
public string orderNumber()
{
OrderId = "ORD" + OrderId + DateTime.Now.Year;
}
And then follow the Constructor Approach to pass over the value to PrintForm
Again declare a variable for orderID inside the PrintForm class
string OrderId;
Change your PrintForm Constructor to this
public PrintForm(string value)
{
InitializeComponent();
OrderId=value;
}
on Form1 Button click event
private void button1_Click(object sender, System.EventArgs e)
{
PrintForm frm=new PrintForm(OrderId);
PrintForm.Show();
}
A: Create a container class with a static property in the same namespace:
class clsDummy
{
internal static string ptyValue { get; set; }
}
you can assign this property where you are getting order id:
public string orderNumber()
{
string ord = "ORD" + get_next_id() + DateTime.Now.Year;
clsDummy.ptyValue =ord ;
return ord;
}
after that where ever you want to access just check value inside : clsDummy.ptyValue
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15041479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Parsing twilio transcription GET request within studio flow? EDIT: My question is similar to Twilio - Studio - HTTP Request except that the response I get is in xml rather than JSON. So is there a way i can specify a particular xml tag using liquid?
I have designed a studio flow which is as follows
*
*On Incoming call:
*Plays message telling caller to leave a voicemail
*Records voicemail
*Upon hangup, retrieves the transcription of the voicemail using the 'Make HTTP Request' widget using "GET https://user:[email protected]/2010-04-01/Accounts/{AccountSid}/Recordings/{RecordingSid}/Transcriptions/ "
*Sends that response to a phone number via SMS by putting "{{widget.http_request.body}}" in the message box of the "send_message" widget.
Now I'm so close to that goal however I am having trouble on step 4. I need the response to be turned into just the tag within the xml response. Instead I get the entirety of it which looks like this:
<?xml version='1.0' encoding='UTF-8'?>
<TwilioResponse>
<Transcriptions end="0" firstpageuri="/2010-04-01/Accounts/AC8275ec8e6fb8c37d6b2a5eca99f0dae6/Recordings/RE1595c7b8bc2b8850401ba44fba0dd24d/Transcriptions?PageSize=50&Page=0" nextpageuri="" page="0" pagesize="50" previouspageuri="" start="0" uri="/2010-04-01/Accounts/AC8275ec8e6fb8c37d6b2a5eca99f0dae6/Recordings/RE1595c7b8bc2b8850401ba44fba0dd24d/Transcriptions?PageSize=50&Page=0">
<Transcription>
<Sid>TRbcdfd8fb2fe226ed741b14a05a46cfef</Sid>
<DateCreated>Wed, 17 Aug 2022 19:27:18 +0000</DateCreated>
<DateUpdated>Wed, 17 Aug 2022 19:27:42 +0000</DateUpdated>
<AccountSid>AC8275ec8e6fb8c37d6b2a5eca99f0dae6</AccountSid>
<Status>completed</Status><Type>fast</Type>
<RecordingSid>RE1595c7b8bc2b8850401ba44fba0dd24d</RecordingSid>
<Duration>7</Duration>
<TranscriptionText>Hello. Hello, Hello, Hello, Hello. Hello.</TranscriptionText>
<ApiVersion>2010-04-01</ApiVersion>
<Price/>
<PriceUnit>USD</PriceUnit>
<Uri>/2010-04-01/Accounts/AC8275ec8e6fb8c37d6b2a5eca99f0dae6/Transcriptions/TRbcdfd8fb2fe226ed741b14a05a46cfef</Uri>
</Transcription>
</Transcriptions>
</TwilioResponse>
As you can see, I only need the content between the "TranscriptionText" tags, but currently my HTTP_Request widget returns all of the above. How can I do this within studio? I am trying to keep everything contained in Twilio so any solutions involving outside servers are not desired.
Thank you!
A: Try adding .json to the end, like below, to get a JSON response Studio can parse.
/2010-04-01/Accounts/{YourAccountSid}/Recordings/{RecordingSid}/Transcriptions.json
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73394803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: adding the user to a many to many field upon creating a model Good day, I am trying to create a viewset whereby when a showcase is created, the user gets added as one of the administrators in the many to many fields, but my code doesn't seem to work. Below is what I have tried, which doesn't work.
models.py
class Showcase(models.Model):
title = models.CharField(max_length=50)
description = models.TextField(null=True)
skill_type = models.ForeignKey(Skill, on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name="Showcases")
content = models.TextField(null=True)
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
voters = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="upvotes")
slug = models.SlugField(max_length=255, unique=True)
administrator = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="administrators", blank=True)
def __str__(self):
return self.title
views.py
class showcaseCreateViewSet(generics.CreateAPIView):
queryset = Showcase.objects.all()
serializer_class = ShowcaseSerializer
permission_classes = [IsAuthenticatedOrReadOnly]
def perform_create(self, serializer):
serializer.save(user=self.request.user, administrator=self.request.user)
serializers.py
class ShowcaseSerializer(serializers.ModelSerializer):
user = serializers.SlugRelatedField(read_only=True, slug_field='slug')
created_on = serializers.SerializerMethodField(read_only=True)
likes_count = serializers.SerializerMethodField(read_only=True)
user_has_voted = serializers.SerializerMethodField(read_only=True)
slug = serializers.SlugField(read_only=True)
comment_count = serializers.SerializerMethodField(read_only=True)
class Meta:
model = Showcase
exclude = ['voters', 'updated_on', 'id', 'administrator']
def get_likes_count(self, instance):
return instance.voters.count()
def get_user_has_voted(self, instance):
request = self.context.get("request")
return instance.voters.filter(pk=request.user.pk).exists()
def get_comment_count(self, instance):
return instance.comments.count()
A: I think this could be an alternative, instead of overwriting perform_create, overwrite create
class showcaseCreateViewSet(generics.CreateAPIView):
queryset = Showcase.objects.all()
serializer_class = ShowcaseSerializer
permission_classes = [IsAuthenticatedOrReadOnly]
def create(self, request):
serializer = self.serializer_class(
data=request.data
)
if serializer.is_valid():
showcase = serializer.save(user=request.user)
if showcase:
showcase.administrator.add(request.user)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Another possibility is passing in the view the request (or just the user) to the context of the serializer by implementing get_serializer_context,
def get_serializer_context(self):
return {
'request': self.request
}
and then, implement the create method of the serializer,
def create(self, validated_data):
showcase = Showcase(**validated_data)
showcase.administrator.add(self.context['request'].user)
showcase.save()
return showcase
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60105340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to reveal multiple html? Suppose that, i got this pseudocode:
itemset1[apple,orange]
itemset2[banana,potato]
<div>
<header>
<h3>Mylist</h3>
</header>
<ul>
<li>itemset1[]</li>
</ul>
</div>
<div>
<header>
<h3>Mylist</h3>
</header>
<ul>
<li>itemset2[]</li>
</ul>
</div>
Is there any way that letting me write only once the html code? like
<div>
<header>
<h3>Mylist</h3>
</header>
<ul>
<li>items</li>
</ul>
</div>
and reveals twice like the first example(one for itemset1 and one for itemset2) i can use evrything javascript or php but prefer javascript
A: There're two ways (or more?). Rendering with PHP or JavaScript.
With PHP at view
For example, using foreach ($itemset1 as $item) probably what you want.
<div>
<header>
<h3>Mylist</h3>
</header>
<ul>
<?php foreach ( $itemset1 as $item ) { ?>
<li><?php echo $item ?></li>
<?php } ?>
</ul>
</div>
With JavaScript
In this case, I'm using AngularJS for rendering data. Assuming you have known what AngularJS is and have been prepared for that.
<div>
<header>
<h3>Mylist</h3>
</header>
<ul>
<li ng-repeat="item in itemset1">{{ item }}</li>
</ul>
</div>
Of course, If you like, jQuery is also a good choice for you. But hate the jQuery append expression. And it's inconvenient.
See that reference:
PHP: foreach - Manaual
AngularJS: API: ngRepeat
A: Sure but now i have to write
<div>
<header>
<h3>Mylist</h3>
</header>
<ul>
<li ng-repeat="item in itemset1">{{ item }}</li>
</ul>
</div>
<div>
<header>
<h3>Mylist</h3>
</header>
<ul>
<li ng-repeat="item in itemset2">{{ item }}</li>
</ul>
</div>
Any way that i can avoid writing twice all of this div,header,ul,li elements?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40483188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Facebook comment plugin im trying to add facebook comment plugin to each picture of a simple photo gallery but it doesnt seem to work when i add it to the loop, here's the code of the page:
`
Affichages
</head>
<body>
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/fr_FR/sdk.js#xfbml=1&appId="id"&version=v2.0";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<?php
$folder = 'img/';
$filetype = '*.*';
$files = glob($folder.$filetype);
$count = count($files);
$sortedArray = array();
for ($i = 0; $i < $count; $i++) {
$sortedArray[date ('YmdHis', filemtime($files[$i]))] = $files[$i];
}
krsort($sortedArray);
echo '<table>';
foreach ($sortedArray as &$filename) {
#echo '<br>' . $filename;
echo '<tr><td>';
echo '<a name="'.$filename.'" href="#'.$filename.'"><img src="'.$filename.'" /></a>';
echo substr($filename,strlen($folder),strpos($filename, '.')-strlen($folder));
echo '</td></tr>';
}
echo '</table>';
?>
</body>
</html>`
thanks for your time ! :)
A: I dont see any code for adding the like buttons in your loop. So there is nothing to render.
Firstly you should configure your Javascript SDK and link it to your Facebook page / application.
To configure the Javascript SDK you will need to add something like
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'your-app-id',
xfbml : true,
version : 'v2.1'
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
This code is detailed here but links your website to your application and configures the SDK to look for Facebook social plugins on the page.
Then you need to add placeholder elements for the Javscript SDK to parse and render, like the below:
foreach ($sortedArray as &$filename) {
#echo '<br>' . $filename;
echo '<tr><td>';
echo '<a name="'.$filename.'" href="#'.$filename.'"><img src="'.$filename.'" /></a>';
?>
<div class="fb-like" data-href="<?php echo $imageUrl; ?>" data-layout="button" data-action="like" data-show-faces="true" data-share="false"></div>
<?php
echo substr($filename,strlen($folder),strpos($filename, '.')-strlen($folder));
echo '</td></tr>';
}
These divs have special attributes that the SDK will recognise and use to render the like buttons in the correct place.
You should read the documentation here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27804992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: awk append with /32 not working in MS Windows I am trying to append /32 to public IP that is in a file using awk
ip.txt has IP address 4.14.XX.XXX
the issue is with the command in script file
awk "{print $0 "/32"}" < ip.txt
result=0.129375
if I remove / than the result is 4.14.XX.XXX32
I want 4.14.XX.XXX/32.
The complete bat file
curl v4.ifconfig.co > ip.txt
awk "{ print $0 "/32" }" < ip.txt > ipnew.txt
@REM set stuff=type ipnew.txt
for /f %%i in ('type ipnew.txt') do set stuff=%%i
echo %stuff%
====================
awk -f changeipaddress.bat
error
awk: changeipaddress.bat:1: curl v4.ifconfig.co > ip.txt
awk: changeipaddress.bat:1: ^ syntax error
awk: changeipaddress.bat:1: curl v4.ifconfig.co > ip.txt
awk: changeipaddress.bat:1: ^ syntax error
awk: changeipaddress.bat:2: awk "{ print $0 "/32" }" < ip.txt > ipnew.txt
awk: changeipaddress.bat:2: ^ syntax error
awk: changeipaddress.bat:2: awk "{ print $0 "/32" }" < ip.txt > ipnew.txt
awk: changeipaddress.bat:2: ^ syntax error
awk: changeipaddress.bat:3: @REM set stuff=type ipnew.txt
awk: changeipaddress.bat:3: ^ invalid char '@' in expression
Please suggest where I am going wrong?
Regards,
TJ.
A: Create a file named foo.awk with content { print $0 "/32" } (i.e. the awk script) then change line 2 of your bat file from awk "{ print $0 "/32" }" < ip.txt > ipnew.txt to awk -f foo.awk < ip.txt > ipnew.txt. Now run your bat file however you normally do.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51139245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Multiple IF statements showing image when input are completed I cant seem to get multiple IF statements to work on my script. I want an image to appear when three input fields have text in, and not when only one or two have text in. Any help would be much appreciated.
HTML:
<form method="post" action="email-case-study-checker.php" onsubmit="return submitToHighslide(this)">
Full Name <span class="required">*</span><br />
<input name="your_name" type="text" id="name" title="Enter your full name" size="36" maxlength="50"><br /><br />
Company <span class="required">*</span><br />
<input name="your_company" type="text" id="company" title="Enter your company name" size="36" maxlength="50"><br /><br />
Email Address <span class="required">*</span><br />
<input name="your_email" type="text" id="email" title="Enter your email address" size="36" maxlength="50"><br /><br />
<div id="hiddenpdf"> <a href="pdfs/Southend-On-Sea-Council-Case-Study.pdf"> Right click and save link as to download pdf</a></div>
Javascript:
<script>
function hiddenpdf()
{
if(document.getElementById('name').value == "") {
if(document.getElementById('company').value == "") {
if(document.getElementById('email').value == "");}
{
document.getElementById('hiddenpdf').style.display = 'none';
}
}
else
{
document.getElementById('hiddenpdf').style.display = 'block';
}
}
</script>
A: if (document.getElementById('name').value != "" && document.getElementById('company').value != "" && document.getElementById('email').value != ""){
document.getElementById('hiddenpdf').style.display = 'block';
}else{
document.getElementById('hiddenpdf').style.display = 'none';
}
Hope this helps.
You have a syntax error in your code. Above solution checks with "and" logic and will only execute 'block' statement if all three conditions are met otherwise it will move over to else statement.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24870157",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
} |
Q: SCC compliant version control I'm new to version control and reading about some of the ones available out there. I noticed the term SCC-Compliant (used with clearcase), and the definition from wikipedia is:
SCC compliant as applied to revision control software, means that a
program uses a particular interface defined by Microsoft for Visual
SourceSafe.[1] The SCC denotes Source Code Control
Is this concept of SCC-compliance huge or not that meaningful? Do most version control systems have it?
A: Regarding ClearCase, as mentioned in this IBM technote:
The SCC API is an interface specification, defined by Microsoft® that defines hooks for a number of common source control operations.
An application (typically an "integrated" development environment (IDE) of any kind) can provide source control functions without implementing the functions itself.
If an SCC compliant code control system is installed, the application dispatches code control operations to the source control tool (e.g. Visual Studio > ClearCase).
That being said:
*
*if you are new to version control, try and stay away from ClearCase: it isn't the more practical one by far ;)
*IBM Jazz protocol is a much more recent standard, that other SCM tools can use to integrate into other environments.
So while the concept of tool integration is important, the SCC concept is quite old, and limited to version control.
As opposed to Application Hub communication protocol, for integrating any two applications together, like Jazz.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8015121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Question on creating SPF record for the first time and trying not to disrupt mail delivery I'm creating an SPF record for our domain. We never had one before. I've been collecting DMARC reports so I have a good idea what IPs we are using to send email and I have a good idea what additional "includes" we need. Since we don't have an SPF record at the moment, some ISPs are flagging our mail but it's still being delivered. My question is this: If I terminate my SPF record with ~all and I missed some IPs or includes, will we be any worse off than we were when we had no SPF record?
My goal here is to minimize any email delivery disruptions as we work through the implementation of SPF DMARC and DKIM. At some point we will change the ~all to -all but for now I have to be cautious as to not disrupt email delivery. From what I have read, using ~all should be a safeguard against missing a network or a host. Just wanted to be sure about this before I activate the SPF record.
A: When you're using SPF with DMARC, you should only go as far as ~all anyway; you can configure DMARC to report everything that does not obtain a pass status, including softfails. The way to phase it in is to configure your services to sign everything with DKIM, set your DMARC to pct=100, saying that receivers should expect everything to be signed, configure your ruf and rua parameters so that you get to hear about any delivery problems, and then set p=none. This will allow you to see any problems. Leave it like tat for a while and see if anything is reported, then when you're ready set p=quarantine, and ultimately p=reject. You do need to be absolutely sure of all your mail sources before you can get to that point though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58493506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cloudera VM Insufficient space for shared memory file I am getting below error while starting the Hive in cloudera VM CDH 5.10:
Java HotSpot(TM) 64-Bit Server VM warning: Insufficient space for shared memory file: /tmp/hsperfdata_cloudera/26270 Try using the -Djava.io.tmpdir= option to select an alternate temp location.
How to clear tmp drives or what are all the solution for this?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45001995",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Display field in MySQL as a link in PHP? I have a submission script set up where people can submit their details and upload an attachment. It is all recorded in a database in a table called Submissions with the following fields: fname, lname, snumber and upload.
The upload field is currently the location of the file on the server, for example one entry says uploads/123456.zip (uploads is the directory, 123456.zip is the file name).
I also have a back end administration system where all the submissions are displayed. The code used for that is as follows:
<html>
<head>
<title>Internal Database Listing</title>
<style type="text/css">
/**** Start page styles ****/
body {
background: #DFA01B;
font-family: arial, sans-serif;
font-size: 14px;
}
#wrap {
max-width: 900px;
margin: 30px auto;
background: #fff;
border: 4px solid #FFD16F;
-moz-border-radius: 15px;
-webkit-border-radius: 15px;
border-radius: 15px;
padding: 20px;
}
table.subs {
text-align: center;
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif ;
font-weight: normal;
font-size: 11px;
color: #fff;
width: 800px;
background-color: #666;
border: 0px;
border-collapse: collapse;
border-spacing: 0px;
}
table.subs td
{background-color: #CCC;
color: #000;
padding: 4px;
text-align: left;
border: 1px #fff solid;}
table.subs td.hed
{background-color: #666;
color: #fff;
padding: 4px;
text-align: left;
border-bottom: 2px #fff solid;
font-size: 12px;
font-weight: bold;}
</style>
</head>
<body>
<?php
$username="dbuser";
$password="dbuserpass";
$database="dbsub";
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$query="SELECT * FROM Submissions";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
?>
<div id="wrap">
<div align="left">
<img src="logo.png" width="208" height="87" />
</div>
<div align="center">
<h1 style="font-family:arial">Total submissions</h1>
</div>
<div align="center">
<table class="subs" border="1" cellspacing="1" cellpadding="3">
<tr>
<th><font face="Arial, Helvetica, sans-serif">First name</font></th>
<th><font face="Arial, Helvetica, sans-serif">Last name</font></th>
<th><font face="Arial, Helvetica, sans-serif">Student #</font></th>
<th><font face="Arial, Helvetica, sans-serif">Grade</font></th>
<th><font face="Arial, Helvetica, sans-serif">Submission</font></th>
</tr>
</div>
</div>
<?php
$i=0;
while ($i < $num) {
$f1=mysql_result($result,$i,"fname");
$f2=mysql_result($result,$i,"lname");
$f3=mysql_result($result,$i,"snumber");
$f4=mysql_result($result,$i,"grade");
$f5=mysql_result($result,$i,"upload");
?>
<tr>
<td><font face="Arial, Helvetica, sans-serif"><?php echo $f1; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><?php echo $f2; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><?php echo $f3; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><?php echo $f4; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif"><?php echo $f5; ?></font></td>
</tr>
<?php
$i++;
}
?>
</body>
</html>
This code works perfectly except under the upload field it displays upload/123456.ppt. How do I get it to display http://sitename.com/uploads/123456.ppt AND make it a hyper link to that file?
A: Simply wrap the output in an <a> tag
<td><font face="Arial, Helvetica, sans-serif"><a href="http://sitename.com/<?php echo $f5; ?>"><?php echo $f5; ?></a></font></td>
A: The following will print a link containing the fixed URL.
<?php
$url = 'http://www.' . $_SERVER['SERVER_NAME'] . '/' . $f1;
echo '<a href="' . $url . '">Click here to download the file!</a>';
On the off-chance that $_SERVER['SERVER_NAME'] is not correct for your website, you can simply replace it with the correct domain name.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7747894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Pass multiple list of parameters from python to java program and get back return code using subprocess.communicate Need some help with following code - I want to pass string elements of three list as input to java program that I am calling in my python script. Here is what I have done so far -
import subprocess
from subprocess import PIPE
from subprocess import Popen
amount = ['23.5', '12.5', '56.0', '176.1']
invoice_no = ['11290', '12892', '12802', '23489']
date = ['2/3/19', '12/30/17', '04/21/2018', '8/12/17', '12/21/18']
## problem is proc.communicate(). I am currently passing only invoice_no[i] as input.
for i in range (0, len(invoice_no)):
proc = subprocess.Popen(['java', '-jar', '/data/python/xyz.jar'],stdin=PIPE,stdout=PIPE, stderr=STDOUT)
q = proc.communicate(input = invoice_no[i])
print(q)
## But I want to pass amount and date as input as well.
## I dont know the syntax for that. I also want output as 1 or 0 i.e success or failure. Does anyone know syntax for this?
Most of the questions which I have seen are passing single string as input.But that's not what I am looking for. Even official document of subprocess is not helpful in finding out how to pass multiple inputs syntax. Links are - running java program from python script
How to execute java program using python considering inputs and outputs both
A: Since I have found answer. I thought I will post it here. May be someone will find it useful -
import subprocess
from subprocess import PIPE
from subprocess import Popen
amount = ['23.5', '12.5', '56.0', '176.1']
invoice_no = ['11290', '12892', '12802', '23489']
date = ['2/3/19', '12/30/17', '04/21/2018', '8/12/17', '12/21/18']
for i in range (0, len(invoice_no)):
proc = subprocess.Popen(['java', '-jar', '/data/python/xyz.jar', invoice_no[i], date[i], amount[i]],stdin=PIPE,stdout=PIPE, stderr=PIPE)
output = proc.communicate()[0] ## this will capture the output of script called in the parent script.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54308381",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Back button of device not working with webView I am using wix's react-native-navigation V2 library for navigation and in one of my bottom tab i have webView. In webview i am showing website of company. following is my webview code with activity indicator.
render() {
return (
<View style={styles.container}>
<WebView
onLoad={() => this.hideSpinner()}
source={{uri: 'url'}}
style={{marginTop: 0}}
/>
{this.state.visible && (
<ActivityIndicator
style={{ position: "absolute", top: height / 2, left: width / 2 }}
size="large"
color="#212B51"
/>
)}
</View>
)
}
}
Now the problem is when i am clicking on any link on website it going to that page but after clicking back button the app gets close not comming to previous page. i want after pressing the back button the user should go to the previous page of website.
if anyone have solution please share. Thanks in advance
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54250528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: RxJava2 : How to test an observable is subscribed with TestObserver Using Observable.test() to get a test observer seems to be a bit messed up ... as .test() creates a subscription to the observable giving the following erroneous tests.
// fixme: test passes but TestObservable is always true even if disp= .. is commented out
@Test
fun `with subscription`() {
val observable = Observable.never<String>()
val test = observable.test()
val disp = observable.subscribe()
test.assertSubscribed()
}
// fixme: this test should not pass
@Test
fun `without subscription`() {
val observable = Observable.never<String>()
val test = observable.test()
test.assertSubscribed()
}
It seems the only way to test an observable is subscribed - is to use a PublishSubject as below, which both pass as expected (taken from this for rx-java1 (no TestSubject in rx2) Unit Test - Verify Observable is subscribed)
@Test
fun `with subscription subject`() {
val observable = PublishSubject.create<String>()
val disp = observable.subscribe()
assertTrue(observable.hasObservers())
}
@Test
fun `without subscription subject`() {
val observable = PublishSubject.create<String>()
assertFalse(observable.hasObservers())
}
Is there a way to make a proper test for subscription using Observable.test()?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59054018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Why more than one "using system" namespace?
I don't get why, when I start a new console solution in C#, it has more than one "using system" lines. Shouldn't Using System cover using system.text and the rest?
A: If using System; were recursive, then, in just the "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" assembly, this would be list of type collisions you would get:
__Filters, __HResults, <>c, <>c__DisplayClass11_0, <>c__DisplayClass4_0, AsyncCausalityStatus, AsyncReplySink, BIND_OPTS, BINDPTR, CALLCONV, CausalityRelation, CausalitySynchronousWork, CausalityTraceLevel, ChannelInfo, ConfiguredTaskAwaiter, CONNECTDATA, ContractHelper, DebugView, Decoder, DESCKIND, DESCUNION, DictionaryEnumerator, Disposition, DISPPARAMS, ELEMDESC, Encoder, Entry, Enumerator, Environment, EventData, EXCEPINFO, ExplicitlySet, FILETIME, FUNCDESC, FUNCFLAGS, FUNCKIND, Getter, IDLDESC, IDLFLAG, IEnumerable, IEnumerator, IExpando, IMPLTYPEFLAGS, InternalPartitionEnumerable, InternalPartitionEnumerator, INVOKEKIND, IReflect, KeyCollection, Keywords, LIBFLAGS, MdSigCallingConvention, NameInfo, Node, NodeEnumerator, OpFlags, PARAMDESC, PARAMFLAG, ParseFailureKind, Reader, RemoteAppEntry, Segment, SerializationMask, SinkStack, State, STATSTG, SYSKIND, Tasks, TokenType, TYPEATTR, TYPEDESC, TypeEntry, TYPEFLAGS, TypeInfo, TypeKind, TYPEKIND, TYPELIBATTR, UnsafeNativeMethods, ValueCollection, VARDESC, VARFLAGS, Variant, Win32
And in the current project I have open, with 14 assemblies loaded I would have 792 type collisions (of the 14,251 types defined).
That's why it's not recursive.
Here's how to run this yourself:
var typeCollisions = String.Join(", ",
System
.AppDomain
.CurrentDomain
.GetAssemblies()
.SelectMany(a => a.GetTypes())
.GroupBy(x => x.Name)
.Where(x => x.Skip(1).Any())
.Select(x => x.Key)
.OrderBy(x => x));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34984845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: MongoDB Custom Serializer to avoid _t being added collection, throws ReadEndArray Error? Situation:
Language: C# using the C# Driver
I have a model that contains a List as a property. That List can contain one of 3 different models that all inherit the BaseModelClass. To assist in serialization of this situation Mongo adds _t to identify which of the models is actually being used. For us this is a problem due to the amount of space that _t is taking up. I am a lowly dev, I have asked for more space and ram and they have told me to solve it without the additional space. So I sat down to writing a custom serializer that handled the different types without writing a _t to the BSONDocument. I thought all was great until I started doing my unit testing of the serialization. I started getting "ReadEndArray can only be called when ContextType is Array, not when ContextType is Document."
Any advice or suggestions are greatly appreciated.
Here is the code I have thus far...
<---------Collection Model--------------------->
[BsonCollectionName("calls")]
[BsonIgnoreExtraElements]
public class Call
{
[BsonId]
public CallId _id { get; set; }
[BsonElement("responses")]
[BsonIgnoreIfNull]
public IList<DataRecord> Responses { get; set; }
}
<----------Base Data Record------------------>
[BsonSerializer(typeof(DataRecordSerializer))]
public abstract class DataRecord
{
[BsonElement("key")]
public string Key { get; set; }
}
<-----------Examples of actual Data Records----------------->
[BsonSerializer(typeof(DataRecordSerializer))]
public class DataRecordInt : DataRecord
{
[BsonElement("value")]
public int Value { get; set; }
}
[BsonSerializer(typeof(DataRecordSerializer))]
public class DataRecordDateTime : DataRecord
{
[BsonElement("value")]
public DateTime? Value { get; set; }
}
<---------------Unit Test to trigger Deserializer----------------->
//Arrange
var bsonDocument = TestResources.SampleCallJson;
//Act
var result = BsonSerializer.Deserialize<Call>(bsonDocument);
//Assert
Assert.IsTrue(true);
<----------------Serializer----------------->
public class DataRecordSerializer : IBsonSerializer
{
public object Deserialize(BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options)
{
//Entrance Criteria
if(nominalType != typeof(DataRecord)) throw new BsonSerializationException("Must be of base type DataRecord.");
if(bsonReader.GetCurrentBsonType() != BsonType.Document) throw new BsonSerializationException("Must be of type Document.");
bsonReader.ReadStartDocument();
var key = bsonReader.ReadString("key");
bsonReader.FindElement("value");
var bsonType = bsonReader.CurrentBsonType;
if (bsonType == BsonType.DateTime)
{
return DeserializeDataRecordDateTime(bsonReader, key);
}
return bsonType == BsonType.Int32 ? DeserializeDataRecordInt(bsonReader, key) : DeserializeDataRecordString(bsonReader, key);
}
public object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
{
//Entrance Criteria
if (nominalType != typeof (DataRecord)) throw new BsonSerializationException("Must be of base type DataRecord.");
if (bsonReader.GetCurrentBsonType() != BsonType.Document) throw new BsonSerializationException("Must be of type Document.");
bsonReader.ReadStartDocument(); // Starts Reading and is able to pull data fine through this and the next few lines of code.
var key = bsonReader.ReadString("key");
if (actualType == typeof(DataRecordDateTime))
{
return DeserializeDataRecordDateTime(bsonReader, key);
}
return actualType == typeof(DataRecordInt) ? DeserializeDataRecordInt(bsonReader, key) : DeserializeDataRecordString(bsonReader, key); // Once it tries to return I am getting the following Error: ReadEndArray can only be called when ContextType is Array, not when ContextType is Document.
}
public IBsonSerializationOptions GetDefaultSerializationOptions()
{
return new DocumentSerializationOptions
{
AllowDuplicateNames = false,
SerializeIdFirst = false
};
}
public void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
{
var currentType = value.GetType();
if (currentType == typeof (DataRecordInt))
{
SerializeDataRecordInt(bsonWriter, value);
return;
}
if (currentType == typeof(DataRecordDateTime))
{
SerializeDataRecordDateTime(bsonWriter, value);
return;
}
if (currentType == typeof(DataRecordString))
{
SerializeDataRecordString(bsonWriter, value);
}
}
private static object DeserializeDataRecordString(BsonReader bsonReader, string key)
{
var stringValue = bsonReader.ReadString();
var isCommentValue = false;
if (bsonReader.FindElement("iscomment"))
{
isCommentValue = bsonReader.ReadBoolean();
}
return new DataRecordString
{
Key = key,
Value = stringValue,
IsComment = isCommentValue
};
}
private static object DeserializeDataRecordInt(BsonReader bsonReader, string key)
{
var intValue = bsonReader.ReadInt32();
return new DataRecordInt
{
Key = key,
Value = intValue
};
}
private static object DeserializeDataRecordDateTime(BsonReader bsonReader, string key)
{
var dtValue = bsonReader.ReadDateTime();
var dateTimeValue = new BsonDateTime(dtValue).ToUniversalTime();
return new DataRecordDateTime
{
Key = key,
Value = dateTimeValue
};
}
private static void SerializeDataRecordString(BsonWriter bsonWriter, object value)
{
var stringRecord = (DataRecordString) value;
bsonWriter.WriteStartDocument();
var keyValue = stringRecord.Key;
bsonWriter.WriteString("key", string.IsNullOrEmpty(keyValue) ? string.Empty : keyValue);
var valueValue = stringRecord.Value;
bsonWriter.WriteString("value", string.IsNullOrEmpty(valueValue) ? string.Empty : valueValue);
bsonWriter.WriteBoolean("iscomment", stringRecord.IsComment);
bsonWriter.WriteEndDocument();
}
private static void SerializeDataRecordDateTime(BsonWriter bsonWriter, object value)
{
var dateRecord = (DataRecordDateTime) value;
var millisecondsSinceEpoch = dateRecord.Value.HasValue
? BsonUtils.ToMillisecondsSinceEpoch(new DateTime(dateRecord.Value.Value.Ticks, DateTimeKind.Utc))
: 0;
bsonWriter.WriteStartDocument();
var keyValue = dateRecord.Key;
bsonWriter.WriteString("key", string.IsNullOrEmpty(keyValue) ? string.Empty : keyValue);
if (millisecondsSinceEpoch != 0)
{
bsonWriter.WriteDateTime("value", millisecondsSinceEpoch);
}
else
{
bsonWriter.WriteString("value", string.Empty);
}
bsonWriter.WriteEndDocument();
}
private static void SerializeDataRecordInt(BsonWriter bsonWriter, object value)
{
var intRecord = (DataRecordInt) value;
bsonWriter.WriteStartDocument();
var keyValue = intRecord.Key;
bsonWriter.WriteString("key", string.IsNullOrEmpty(keyValue) ? string.Empty : keyValue);
bsonWriter.WriteInt32("value", intRecord.Value);
bsonWriter.WriteEndDocument();
}
}
A: Also asked here: https://groups.google.com/forum/#!topic/mongodb-user/iOeEXbUYbo4
I think your better bet in this situation is to use a custom discriminator convention. You can see an example of this here: https://github.com/mongodb/mongo-csharp-driver/blob/v1.x/MongoDB.DriverUnitTests/Samples/MagicDiscriminatorTests.cs. While this example is based on whether a field exists in the document, you could easily base it on what type the field is (BsonType.Int32, BsonType.Date, etc...).
A: Basing on @Craig Wilson answer, to get rid off all discriminators, you can:
public class NoDiscriminatorConvention : IDiscriminatorConvention
{
public string ElementName => null;
public Type GetActualType(IBsonReader bsonReader, Type nominalType) => nominalType;
public BsonValue GetDiscriminator(Type nominalType, Type actualType) => null;
}
and register it:
BsonSerializer.RegisterDiscriminatorConvention(typeof(BaseEntity), new NoDiscriminatorConvention());
A: This problem occurred in my case when I was adding a Dictionary<string, object> and List entities to database. The following link helped me in this regard: C# MongoDB complex class serialization. For your case, I would suggest, following the link given above, as follows:
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
[JsonConverter(typeof(DataRecordConverter))]
public abstract class DataRecord
{
public string Key { get; set; }
public string DataRecordType {get;}
}
public class DataRecordInt : DataRecord
{
public int Value { get; set; }
public override string DataRecordType => "Int"
}
public class DataRecordDateTime : DataRecord
{
public DateTime? Value { get; set; }
public override string DataRecordType => "DateTime"
}
public class DataRecordConverter: JsonConverter
{
public override bool CanWrite => false;
public override bool CanRead => true;
public override bool CanConvert(Type objectType)
{
return objectType == typeof(DataRecord);
}
public override void WriteJson(
JsonWriter writer,
object value,
JsonSerializer serializer)
{}
public override object ReadJson(
JsonReader reader,
Type objectType,
object existingValue,
JsonSerializer serializer)
{
var jsonObject = JObject.Load(reader);
var dataRecord = default(DataRecord);
switch (jsonObject["DataRecordType"].Value<string>())
{
case "Int":
dataRecord = new DataRecordInt();
break;
case "DateTime":
dataRecord = new DataRecordDataTime();
break;
}
serializer.Populate(jsonObject.CreateReader, dataRecord);
return dataRecord;
}
}
[BsonCollectionName("calls")]
[BsonIgnoreExtraElements]
public class Call
{
[BsonId]
public CallId _id { get; set; }
[JsonIgnore]
[BsonElement("responses")]
[BsonIgnoreIfNull]
public BsonArray Responses { get; set; }
}
You can add populate the BsonArray using:
var jsonDoc = JsonConvert.SerializeObject(source);
var bsonArray = BsonSerializer.Deserialize<BsonArray>(jsonDoc);
Now, you can get deserialized List from Mongo using:
var bsonDoc = BsonExtensionMethods.ToJson(source);
var dataRecordList = JsonConvert.DeserializeObject<List<DataRecord>>(bsonDoc, new DataRecordConverter())
Hope this helps, again, thanks to C# MongoDB complex class serialization for this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28637135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: extract on various lines with logstash so I just discovered logstash and I managed to extract data from log files.
This time, I have to extract information on MULTIlines, I show you an example:
2016-03-07 14:09:11,613 INFO [][com.ole.ecom.jms.crm.JmsCrmSender] Envoi du message ...<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root xmlns="http://wlsosb.gjkjdhdfhkllmld.crm/">
<entry>
<clients>
<code>8800356499460</code>
<raisonsociale>Ole</raisonsociale>
<siret>51770313800088</siret>
<civilite>M.</civilite>
<nom>Aurius</nom>
<prenom>Gerard</prenom>
<telephone>0614666644</telephone>
<email>[email protected]</email>
</clients>
I have to recover, information on the first line and I must also be able to extract the number in between <code> 8800356499460 </ code> and email between the <email> [email protected] </ email >
if you see how I can do, help me I would be very grateful
A: The first step is to join those lines together, either on the shipper side (filebeat can do this), or with the multiline codec in logstash.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36327964",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to enlarge image while hover over an image? I want to show the thumbnail image large when hover over it, similar to the one in
http://www.freelayouts.com/websites/html-templates Plz help. Any help will be appreciated.
A: What you need is a tooltip plugin. There are plenty of them.
Check out this list: https://cssauthor.com/jquery-css3-hover-effects/
A: <img class="enlarge-onhover" src="img.jpg">
...
And on the css:
.enlarge-onhover {
width: 30px;
height: 30px;
}
.enlarge-onhover:hover {
width: 70px;
height: 70px;
}
A: Take a look at http://fancybox.net/blog
Fancybox looks nice, uses JQuery and is highly configurable with various show/hide effects. Tutorial number 3 on this page shows you how to use it OnHover rather than OnClick
The home page http://fancybox.net/home shows some examples of the visual effect
A: <script>
function bigImg(x) {
x.style.height = "64px";
x.style.width = "64px";
}
function normalImg(x) {
x.style.height = "32px";
x.style.width = "32px";
}
</script>
<img onmouseover="bigImg(this)" onmouseout="normalImg(this)" border="0" src="smiley.gif" alt="Smiley" width="32" height="32">
The function bigImg() is triggered when the user mouse over the image. This function enlarges the image.
The function normalImg() is triggered when the mouse pointer is moved out of the image. That function sets the height and width of the image back to normal.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2252324",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL Server linux forwarding I'm wondering if I could forward SQL queries from localhost to another local IP address?
I don't want to install SQL Server on Linux, but I need to connect to it on another PC through localhost.
Thanks
A: You can use iptables:
iptables -A FORWARD -p tcp -i eth0 -s localhost -d x.x.x.x --dport 3306 -j ACCEPT
where x.x.x.x is the mysql server ip address, and eth0 is the interface you use.
A: It seems like you are asking if you are on a Linux machine you want to query to localhost and have that query forwarded to a SQL Server. In this case the above answer is partially correct and will allow packets to be forwarded but doesn't actually perform the forward/redirect. You also say "SQL Server" which I take to mean MS SQL Server. The default port in this case is listed as 1433. You would actually need (2) rules:
# iptables -t nat -A PREROUTING -p tcp -i lo -d localhost --dport 1433 -j DNAT --to-destination x.x.x.x # where x.x.x.x is the SQL Server IP address
# iptables -A FORWARD -i lo -p tcp --dport -j ACCEPT # only if your default FORWARD policy is DROP. Otherwise you just need the prerouting rule.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44759378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can we compare two plots? Suppose we have two similar plots.
*
*Plot1 (already published in a paper)
*Plot2 (calculated by using any software)
My question is: How can I compare my calculated plot (pdf, png, jpeg, etc) with the plot in the paper.
Thank You
A: To the best of my knowledge, there is currently no software that would enable you to re-convert images into their nominal data.
However, it's not that hard to write a piece of code that does it.
Here are the steps (at a high level):
*
*extract the images from the pdf document (use iText)
*separate out those images that look like a plot. You can train a neural network to do this, or you can simply look for images that contain a lot of white (assuming that's the background) and have some straight lines in black (assuming that's the foreground). Or do this step manually.
*Once you have the image(s), extract axis information. I'll assume a simple lineplot. Extract the minimal x and y value, and the maximum x and y value.
*separate out the colors of the lines in your lineplot, and get their exact pixel coordinates. Then, using the axis information, scale them back to their original datapoint.
*apply some kind of smoothing algorithm. E.g. Savitzky-Golay
*If you ever use this data in another paper, please mention that you gathered this data by approximation of their graph. Make it clear you did not use the original source data.
Reading material:
*
*https://developers.itextpdf.com/examples
*https://en.wikipedia.org/wiki/Savitzky%E2%80%93Golay_filter
*https://docs.oracle.com/javase/tutorial/2d/images/index.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46172469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Using command-line arguments in J I know that ARGV represents the arguments. Can I type arguments after the filename in jqt.exe or does that only work in jconsole.exe. Executing the code regarding ARGV given in the J docs crashes J on my Win 10. An example would be welcome.
I tried out 0 ". > ,. 2 }. ARGV from an earlier question on SO, but am not sure how to make it work.
A: Both jqt and jconsole read the command line arguments and box them:
jqt script.ijs arg1 arg2
ARGV
┌───┬──────────┬────┬────┐
│jqt│script.ijs│arg1│arg2│
└───┴──────────┴────┴────┘
2}. ARGV
┌────┬────┐
│arg1│arg2│
└────┴────┘
] x =: > 3 { ARGV
arg2
example script:
$ cat script.ijs
x =: ". every 2 }. ARGV
echo +/ x
$ jqt script.ijs 1 2 3
6
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61284555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: jasmine + karma - Firefox does not calculate element.height and element.width properly I have a strange problem using jasmine and karma frameworks.
Basically I just want to make a resize using plain javascript of some img's.
I have the following test :
it('Should set both the height and width style for the one applicable as being the maximum allowed', function () {
var images = '<img class="resizableImage" src="" alt="" style="height: 1200px; width: 1000px; visibility: hidden;">' +
'<img class="resizableImage" src="" alt="" style="height: 1100px; width: 199px; visibility: visible;">' +
'<img class="resizableImage" src="" alt="" style="height: 1990px; width: 200px; visibility: visible;">';
setFixtures(images);
var allResizableImages = $('img.resizableImage');
resizeImagesWidthHeightIfBiggerThan(allResizableImages, 199, 199);
$.each(allResizableImages, function () {
expect($(this).css('width')).toBe('199px');
expect($(this).css('height')).toBe('199px');
});
});
and the function :
function resizeImagesWidthHeightIfBiggerThan(imagesToBeResized, maxWidth, maxHeight) {
var UNIT = "px";
var VISIBILITY_SETTINGS = "visible";
for (var i = 0, len = imagesToBeResized.length; i < len; i++) {
var imgCandidate = imagesToBeResized[i];
if (imgCandidate && imgCandidate.tagName.toLowerCase() == 'img') {
if (imgCandidate.width > maxWidth) {
imgCandidate.style.width = maxWidth + UNIT;
}
if (imgCandidate.height > maxHeight) {
imgCandidate.style.height = maxHeight + UNIT;
}
}
imgCandidate.style.visibility = VISIBILITY_SETTINGS;
}
}
With Chrome, everythings goes well.
However, with Firefox, the test doesn't pass.
Though, live (doing testing manually on Firefox), everything goes well.
What could be wrong ?
I am using Firefox 29.0
Thanks a lot.
A: We had the same problem. FF does not report correct image sizes if src is empty. Try and set src to a valid image to see if it works.
In our project we use ng-src; not src. We created a mock of ng-src that kicks-in in all our tests. The mock replaces the ng-src value (empty or not) with a single fake image stored in /tests/image. This is useful if you unit test directives that include images in their html template. See also How do you mock directives to enable unit testing of higher level directive?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23519621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python type as a string I'm attempting to display a string that provides the type of a given variable.
When I try the following:
'This is a '+str(type(somevariable))
the output is "This is a <type 'float'>", instead of "This is a float".
How do I get the output I want?
A: 'This is a ' + type(somevariable).__name__
A: somevariable.__class__.__name__
is one way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10014160",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Set relative location header with Restlet When trying to set a relative location header using something like the following code:
setLocationRef(getReference().addSegment(MyItem.getId()).getPath());
Restlet seems to always make the Location header an absolute URL no matter what I do. It there a way to override this behavior and set a relative URL in the Location header? Besides creating a filter to edit the raw headers, that is.
A: After having a look at the http RFC, I read that the Location header is an absolute URI:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.30
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21207690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to iterate over the elements in lists in the values of a dictionary I want to assert if all values in lists in the values of a dict are integer.
My dictionary is very long and I don't know an efficient way to do this.
My dictionary looks like this:
{'chr7': [[127471196, 127472363], [127472363, 127473530], [127473530, 127474697], [127474697, 127475864], [127475864, 127477031], [127477031, 127478198], [127478198, 127479365], [127479365, 127480532]], 'chr8': [[127480532, 127481699], [127471196, 127472363], [127472363, 127473530], [127473530, 127474697], [127474697, 127475864]], 'chr9': [[127475864, 127477031], [127477031, 127478198], [127478198, 127479365], [127479365, 127480532], [127480532, 127481699]], 'chrX': [[127480532, 127481699]], 'chr1': [[127471196, 127472363], [127472363, 127473530], [127473530, 127474697], [127474697, 127475864], [127475864, 127477031], [127477031, 127478198], [127478198, 127479365], [127479365, 127480532]], 'chr2': [[127480532, 127481699], [127471196, 127472363], [127472363, 127473530], [127473530, 127474697], [127474697, 127475864]], 'chr3': [[127475864, 127477031], [127477031, 127478198]], 'chr4': [[127478198, 127479365], [127479365, 127480532], [127480532, 127481699]], 'chrY': [[127480532, 127481699]]}
I have been trying something like this
assert all(isinstance(value, list) and all(isinstance(el, int)
for el in value)for value in bed_data.values()), "Values of the dictionnary aren't lists of integers"
(Code copy from here Assert data type of the values of a dict when they are in a list)
A: You could use a generator:
assert all(isinstance(e, int)
for l1 in bed_data.values()
for l2 in l1 for e in l2)
It will raise an AssertionError for the first invalid value. If all values are correct, there is no choice but to test them all.
A: You don't need to try all items. Stop at the first failed test (not an instance of int) and prefer use TypeError rather than AssertionError:
import itertools
for l in bed_data.values():
for v in itertools.chain.from_iterable(l):
if not isinstance(v, int):
raise TypeError(f"Values of the dictionnary aren't lists of integers '{v}'")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69392339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Handling static files when when upgrading an application My application has a number of static files (SQLite DB, User settings file) that are deployed with the application.
When publishing a new version, I'd like to replace the DLL's, but retain the users static files. I'm intending to use InstallShield LE, but open to other suggestions to create the installer.
How can this be achieved?
Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37860949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Are there any differences between using StringTokenizer and concatenating Strings together? I am using Java to make an Uno game. I have a method called findCard(String cardname) whose function is to find the card in a hand of cards when the user writes in the name of the card (e.g: “Red 6”) and to return null if it can’t find the card. It works fine when I tried something like:
String card = "Red" + " " + "6";
pHand.findCard(card); // return the card Red 6
However, in the game, I will need the user to write a full command such as “deal Red 6”. Thus, I use StringTokenizer to separate the card’s name from the command:
StringTokenizer scan = new StringTokenizer(input);
String cmd = scan.nextToken(); // = "deal"
String color = scan.nextToken(); // = "Red"
String card = color + " " + scan.nextToken(); // = "Red 6"
What is wrong is when I try pHand.findCard(card); in this scenario, it only returns null no matter what was typed in.
All I know about StringTokenizer is that it can split words in a string so I don't see how these are different. Thus, it would be great if anyone can point out the reason and the solution for this.
A: The comments already have the solutions really... but to wrap some more advice around it:
Your Problem
You're just missing a space between the color and number.
General Advice
*
*Make sure everything is the same case before comparing (e.g. all lower/upper).
*Get rid of white space when handling tokens.
*Keep variables separate; card value and card color are both unique and useful, putting them back in one string makes them less useful and harder to use and can introduce errors like yours.
Recommendation
Modify findCard() to take 2 strings, one with the card value and one with the color. Also, if you're using "red 6" as a key in a map or something, either:
*
*Make sure you build "red 6" from "red" and "6" using a function that you use everywhere you do this. That way you can unit test the function and you're sure that you don't add a space in one spot and forget it in another spot. Generally anywhere where you duplicate code, you might mess up - so don't duplicate.
*Make "card" a class and override equals and hash code to use both of these values when determining equality. Then you can use card as the key in a map fine.
Also, I kind of agree with the person who said that string spit() would be easier (just because you see it more often in code). But both should work if you're comfortable; so do it your way if you're happy :).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59042003",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can I send sms to multiple number using Twilio by passing the recipient number array? I am building an application for ios, android, and for web. The application is using REST api to send sms via Twilio api gateway. Now there is a requirement to send bulk sms to customers. Is there any way to pass the recipient mobile number array to twilio using their api, because I don't want to send to individual customer the same message using foreach loop in my code.
Thanks
A: Twilio developer evangelist here.
I'm afraid there is no bulk SMS message endpoint. For each message you send you need to make a new request to the API.
I'd recommend doing this using a background process so that it doesn't tie up server processes as that can take quite a long time if you are trying to send a lot of messages.
Edit
This answer was correct at the time, however recently the Passthrough API was announced in which you can send messages to up to 10,000 numbers at the same time. Check out the details in this blog post here: https://www.twilio.com/blog/2017/08/bulk-sms-with-one-api-request.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33079475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do i downgrade a meteor installation on windows? I tried reading the official manual and two books, but the chage in versions is too large, even the directory sturcture is off.
I tried running meteor bundle --release 1.0.0
no luck
what is the first windows version of meteor, i shold downgrade to?
A: According to this: http://info.meteor.com/blog/meteor-11-microsoft-windows-mongodb-30
Meteor supports development on windows as of version 1.1
You have to have at least windows 7 installed. I would recommend that you upgrade your version of meteor to 1.1 or greater by running npm update meteor. If you want to use the first version of meteor that supports windows you can run npm install [email protected]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38619829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cascading drop down list with ajax in php I have a cascading dropdown list which is fetched from the database through ajax.
The list loads but its not posting to the database nor is the code seen behind.
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getCity(stateid)
{
//alert(stateid);
var strURL="findCity.php?state="+stateid;
var req = getXMLHTTP();
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4) // only if "OK"
{
if (req.status == 200)
{
document.getElementById('citydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
and the php file
<? $state=$_GET['state'];
$link = mysql_connect('localhost', '', ''); //change the configuration if required
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('a'); //change this if required
$query="select FOR_CODE,FOR_DESC from maruti_city where FOR_STAT_CODE='{$state}' order by FOR_DESC";
$result=mysql_query($query);?>
<select name="city" onchange="getDealer(this.value)" class="sel" >
<option value="0">Select City</option>
<? while($row=mysql_fetch_array($result)) { ?>
<option value><?=$row['FOR_DESC']?></option>
<?} ?>
</select>
The DDL's Load but these values are not getting posted to the database.
form
<div class="container">
<table width="528" border="0" cellpadding=1 class="formTable" style="width: 515px;font-family:arial;font-size:12px;" >
<form action="form_submit.php" method="POST" name="alto800" id="alto800" onsubmit="return validate();">
<tbody>
<tr>
<td width="52%">Name</td>
<td width="48%" >Mobile/Phone No.</td>
</tr>
<tr>
<td>
<select name="title" id="mr" class="sel">
<option value="mr">Mr.</option>
<option value="mrs">Mrs.</option>
</select>
<input type="text" name="name" id="name" class="formName" />
</td>
<td>
<input type="text" name="mobile" id="mobile"/>
</td>
</tr>
<tr>
<td >State</td>
<td >City</td>
</tr>
<tr>
<td>
<select name="state" id="state" class="sel" onchange="getCity(this.value)">
<option value="0">Select state</option>
<option value="AN">ANDAMAN</option>
<option value="AP">ANDHRA PRADESH</option>
<option value="AR">ARUNANCHAL PRADESH</option>
<option value="AS">ASSAM</option>
<option value="BH">BIHAR</option>
<option value="CG">CHATTISGARH</option>
<option value="CH">CHANDIGARH</option>
<option value="DL">DELHI</option>
<option value="DM">DAMAN</option>
<option value="DN">DADRA & NAGAR HAVELI</option>
<option value="GJ">GUJRAT</option>
<option value="GO">GOA</option>
<option value="HN">HARYANA</option>
<option value="HP">HIMACHAL PRADESH</option>
<option value="JH">JHARKHAND</option>
<option value="JK">JAMMU & KASHMIR</option>
<option value="KL">KERALA</option>
<option value="KT">KARNATAKA</option>
<option value="MH">MAHARASHTRA</option>
<option value="ML">MEGHALAYA</option>
<option value="MN">MANIPUR</option>
<option value="MP">MADHYA PRADESH</option>
<option value="MZ">MIZORAM</option>
<option value="NG">NAGALAND</option>
<option value="OS">ORISSA</option>
<option value="PJ">PUNJAB</option>
<option value="PY">PONDICHERRY</option>
<option value="RJ">RAJASTHAN</option>
<option value="SK">SIKKIM</option>
<option value="TN">TAMIL NADU</option>
<option value="TR">TRIPURA</option>
<option value="UP">UTTAR PRADESH</option>
<option value="UT">UTTARANCHAL</option>
<option value="WB">WEST BENGAL</option>
</select>
</td>
<td><div id="citydiv">
<select name="city" id="city" class="sel" onChange="getDealer(this.value)" >
<option value="0">Select state first</option>
</select>
</div>
</td>
</tr>
<tr>
<td >Preffered Dealer</td>
<td > </td>
</tr>
<tr>
<td colspan="2"><div id="dealerdiv"><select name="dealer" style="width:500px;height:25px;" >
<option value="0">Select city first</option>
</select> </div> </td>
</tr>
<tr>
<td>Email Address</td>
<td> </td>
</tr>
<tr>
<td><input type="text" name="email" id="email" /></td>
<td> </td>
</tr>
<tr>
<td >Your Query</td>
<td rowspan="2" ><br />
<br /> </td>
</tr>
<tr>
<td>
<textarea name="query" id="query"></textarea>
</td>
</tr>
<tr>
<td >
<div style="height:10px"></div>
<input type="image" name="submit" value="submit" src="images/submit.png" />
</td>
<td ></td>
</tr>
</tbody>
</form>
</table>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12955999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Should you create a reference the main class in every class in Java? I have a big program and I use my main class in almost every class. I usually access by a getInstance method but I do that every time I need it. For example:
OITCPlugin.getInstance().get....
Now I wonder if that is very efficient and if it was better if I declare a variable for it and access the variable instead:
private OITCPlugin plugin = OITCPlugin.getInstance();
...
plugin.get...
And if I only need it in one method is it more efficient and ram saving if I only declare it in the method itself?
Thanks in advance!
A: Singleton pattern is a common approach if you only want one instance of the object. A lot of people regard it as an anti-pattern, yet it is still very popular. Spring beans are singletons, and redux store is a singleton!
If you are only using it in one method, you might as well free up the heap and store it locally in the method, as described here. Freeing up the heap will technically give better performance, but Java is not exactly a super-efficient language anyway, and it also manages the memory for you. Memory generally isn't a problem though, because it's quite cheap and we have lots of it (maybe I should be more careful about my memory management!)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71709254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: add #define when a specific flag is used I want to add a #define FOO code in an header file with autotools when I used a specific flag.
The project I have creates a static library using header to use inline functions for example. If I use the -D option, It will be used at the creation time but I'll have to add it at each compilation using this library which is what I want to avoid.
How can I perform this?
A: I think your best bet is to generate the required header file from the pre-existing file. The following shell command would do the trick:
(echo "#define FOO" ; cat myheader_pregen.hpp) > myheader.hpp
You can incorporate the above as a script into autotools with this
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37110991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Joomla 3.2 working with css files I am testing Joomla 3.2 and trying to customize css files off custom and default templates but I can't get any changes to actualy display online.
First of all I thought it was a cache problem although it usualy is disabled on installation. I enabled and disabled it, cleared cache several times...
Tried several browsers clearing and disabling cache each time but still, my changes don't apear...
The wierdest thing is that I don't have that problem on joomla 3.1 and changes I make to index.php files apear.
If you have had that problem or have an idea where it comes from I would be greatfull for help.
A: Ok, I found out what the pb was...
My hosting service (a french company : OVH) is caching static files and I have to ask them to stop it while I am working on the css. Sorry for bothering, it is not a joomla problem.
A: Check the default template of your site and then go to:
root_of_your_site/templates/default_template_named_folder/index.php
and try to edit here, this will work.
A: I had this problem too. spent hours trying to work it out. i solved it in the end.am sure someone else may do the same. i had checked JOOMLA cache was off, and my cache was cleared.
In my situation i had forgotten i have set to domain up to use a CDN (cloudflare) This was caching the CSS files. so maybe check this and tick it off the list just in case.
hope it helps someone
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20192908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: A way to list each called function along with its parameters and return value for debugging c++ Is there a way to ease the debugging process by getting each function call along with the parameter and return values automatically output, as the program execution is progressing?
Maybe a tool that adds that outputting code before and after each function, which I can use while debugging and then cancel afterwards?
I'm writing the code in Eclipse on Windows and compiling with GNU C++ on a Linux server without a graphical interface — so no KCachegrind available. Valgrind + callgrind alone produces a mass of text that does not seems very usable to me…
The GDB debugger is somewhat an option, but it's slow and too detailed if I want data per (my) function call, not each statement.
When searched for this, I remember reading that there are two special functions that can be defined that would automatically execute upon starting and ending of each function, which could then be defined to output the variables. However, it was for some other programming language or specific C++ IDE.
A: I would say valgrind + callgrind, you can control the output while the program is running and you can use kcachegrind to check the output in kde.
A: You can use valgrind for this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4397020",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Update trigger MySQL giving syntax error I want to create trigger to make update on table when inserting rows to other table, but I get a syntax error for this:
CREATE TRIGGER quantity AFTER INSERT ON sale_items
FOR EACH ROW
BEGIN
update products set quantity = quantity -1 where id =(
SELECT product_id
FROM sale_items
ORDER BY id desc
LIMIT 1)
END;
Error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
near 'END' at line 7
A: This seems like a silly trigger. Why are you fetching the last update id using a subquery? It should be available through new:
DELIMITER //
CREATE TRIGGER quantity AFTER INSERT ON sale_items
FOR EACH ROW
BEGIN
update products
set quantity = quantity - 1
where id = new.product_id
END//
DELIMITER ;
A: Use proper Delimiter in your trigger , the correct code is:
DELIMITER //
CREATE TRIGGER quantity AFTER INSERT ON sale_items
FOR EACH ROW
BEGIN
update products set quantity = quantity - 1
where id = new.product_id ;
END//
DELIMITER ;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23838064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Button not displaying properly when converting from ui to py file PyQt5 I am fairly new to pyqt5, so still learning. I am creating a Home page for a small desktop app I am creating. I am using Qt designer to help me with the code.
My home-page looks like this in Qt designer:
Here, the Launch Tool button is being properly displayed, but when I convert this to py file and run it in spyder, this is how it becomes:
This is the full code for the HomePage generated by Qt designer:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_HomeWindow(object):
def setupUi(self, HomeWindow):
HomeWindow.setObjectName("HomeWindow")
HomeWindow.resize(492, 380)
HomeWindow.setStyleSheet("background-color: rgb(70, 70, 70);")
self.centralwidget = QtWidgets.QWidget(HomeWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName("gridLayout")
self.frame = QtWidgets.QFrame(self.centralwidget)
self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame.setObjectName("frame")
self.verticalLayout = QtWidgets.QVBoxLayout(self.frame)
self.verticalLayout.setObjectName("verticalLayout")
self.frame_2 = QtWidgets.QFrame(self.frame)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.frame_2.sizePolicy().hasHeightForWidth())
self.frame_2.setSizePolicy(sizePolicy)
self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_2.setObjectName("frame_2")
self.gridLayout_4 = QtWidgets.QGridLayout(self.frame_2)
self.gridLayout_4.setObjectName("gridLayout_4")
self.label = QtWidgets.QLabel(self.frame_2)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
self.label.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(24)
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setStyleSheet("color: rgb(85, 170, 255);\n"
"color: rgb(255, 255, 0);\n"
"")
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName("label")
self.gridLayout_4.addWidget(self.label, 0, 0, 1, 1)
self.verticalLayout.addWidget(self.frame_2)
self.frame_3 = QtWidgets.QFrame(self.frame)
self.frame_3.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_3.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_3.setObjectName("frame_3")
self.gridLayout_3 = QtWidgets.QGridLayout(self.frame_3)
self.gridLayout_3.setObjectName("gridLayout_3")
self.textBrowser = QtWidgets.QTextBrowser(self.frame_3)
self.textBrowser.setStyleSheet("background-color: rgb(255, 255, 255);")
self.textBrowser.setObjectName("textBrowser")
self.gridLayout_3.addWidget(self.textBrowser, 0, 0, 1, 1)
self.verticalLayout.addWidget(self.frame_3)
self.frame_4 = QtWidgets.QFrame(self.frame)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.frame_4.sizePolicy().hasHeightForWidth())
self.frame_4.setSizePolicy(sizePolicy)
self.frame_4.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_4.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_4.setObjectName("frame_4")
self.gridLayout_2 = QtWidgets.QGridLayout(self.frame_4)
self.gridLayout_2.setObjectName("gridLayout_2")
self.pushButton = QtWidgets.QPushButton(self.frame_4)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().hasHeightForWidth())
self.pushButton.setSizePolicy(sizePolicy)
self.pushButton.setMinimumSize(QtCore.QSize(100, 30))
self.pushButton.setMaximumSize(QtCore.QSize(100, 30))
font = QtGui.QFont()
font.setPointSize(10)
font.setBold(False)
font.setWeight(50)
self.pushButton.setFont(font)
self.pushButton.setStyleSheet("background-color: rgb(255, 220, 20);")
self.pushButton.setObjectName("pushButton")
self.gridLayout_2.addWidget(self.pushButton, 0, 0, 1, 1)
self.verticalLayout.addWidget(self.frame_4)
self.gridLayout.addWidget(self.frame, 0, 0, 1, 1)
HomeWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(HomeWindow)
QtCore.QMetaObject.connectSlotsByName(HomeWindow)
def retranslateUi(self, HomeWindow):
_translate = QtCore.QCoreApplication.translate
HomeWindow.setWindowTitle(_translate("HomeWindow", "MainWindow"))
self.label.setText(_translate("HomeWindow", "Arrhenius Solver"))
self.textBrowser.setHtml(_translate("HomeWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8pt; font-weight:400; font-style:normal;\">\n"
"<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:16pt; font-weight:600; text-decoration: underline;\">Instructions</span></p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:10pt; text-decoration: underline;\">For calculations without Humidity:</span></p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:10pt;\">1. Please leave all the Humidity fields empty</span></p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:10pt;\">2. Atleast 2 values each of Temperature, Degradation, and Time are required to calculate the parameters.</span></p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:10pt;\">3. More than 2 (upto 7) inputs can be provided to increase accuracy.</span></p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:10pt; text-decoration: underline;\">For calculations with Humidity:</span></p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:10pt;\">1. Please fill the Humidity text fields as well</span></p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:10pt;\">2. Atleast 3 values each of Temperature, Degradation, Time and Humidity are required to calculate the parameters</span></p>\n"
"<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:10pt;\">3. More than 3 (upto 7) inputs can be provided to increase accuracy<br /></span></p></body></html>"))
self.pushButton.setText(_translate("HomeWindow", "Launch Tool"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
HomeWindow = QtWidgets.QMainWindow()
ui = Ui_HomeWindow()
ui.setupUi(HomeWindow)
HomeWindow.show()
sys.exit(app.exec_())
Please help me fix this, I want it like it's being displayed in Qt designer
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64010136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Woocommerce product attribute value as an icon I am using woocommerce and on shop product page I am showing a product with attributes.
I need to change the value of the attribute for an icon (tick icon)
i.e. My attribute is called Sugar Free the value is "yes". Instead of displaying the word "yes" I would like to display a tick icon.
Please, Does anyone know how to achieve this?
Thanks for your attention. I’m looking forward to your reply.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75535238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How vanishing points can help in restoring proper camera perspective? I'm trying to insert 3D object into a photo, that was not taken by me. Meta info is erased, so I can only guess camera parameters and dimensions of the objects in the scene. How can I set proper campoints in such case, is there any methodology?
I've seen that people are drawing helper lines, finding vanishing points, but while I understand the meaning of the vanishing point, I do not get how it can help in restoring the perspective. Any good writeup on the topic?
A: To completely determine a scene 3D data from a given image, you need to know the perspective projection parameters that formed your image. They are:
*
*camera intrinsics: focal length (a must!), and distortion parameters (if you want high precision)
*
*camera extrinsic parameters (rotation/ translation on the three axes)
Detailed:
Focal length can be obtained from viewing angle, with this formula: fx = imageWidth/(2*tan(alphaX)), and similar for the other dimension. If you have neither fx, nor aperture, you cannot reconstruct your 3D image.
Another way to extract them is to calibrate the camera. See http://opencv.itseez.com/modules/calib3d/doc/calib3d.html, but it seems you cannot use it (you said you don't have access to camera.)
The vanishing point (VP) is used to determine the angles at which camera was orientated. So, a difference between the image center and the VP gives you the rotation info:
yaw = ((camera.center.x (pixels) - VP.x)/image.x )* aperture.
pitch = similar.
The roll angle cannot be extracted from VP, but from the horizon line.
The last parameters you need are the translations. Depending of the application, you can set them all 0, or consider only the height as being relevant. None of them can be usually recovered from the image.
Now, having all this data, you can look here
Opencv virtually camera rotating/translating for bird's eye view
to see how all this measures influence your perspective correction.
A: Not a very simple topic, but see the Feb 23 lecture here:
https://courses.engr.illinois.edu/cs543/sp2017/
There is not a one-size-fits-all solution, but depending on scene structure, it is often possible to add objects to photos. See also: http://dl.acm.org/citation.cfm?id=2024191
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7904925",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: MySQL data does not appear in tooltip I want to show MySQL data inside a tooltip.
Here is the code:
<?php
$abfrage = "SELECT * FROM tester";
$ergebnis = mysql_query($abfrage);
while($row = mysql_fetch_object($ergebnis)){
$Name=$row->Name;
$Bech=$row->Beschreibung;
}
?>
<a href="" title="<?=$Name?> <?=$Bech?>">Test Link</a>
It shows me an empty tooltip with nothing inside. If I print those two variables, the MySQL data appear. Is there any mistake in the code?
Thanks.
A: This is in conjunction with Seth McClaine's answer.
Echo your values using:
<?php echo $Name; ?> <?php echo $Bech; ?>
Instead of <?=$Name?> <?=$Bech?>
The use of short tags is not recommended for something like this.
Reformatted code:
<?php
$abfrage = "SELECT * FROM tester";
$ergebnis = mysql_query($abfrage);
$row = mysql_fetch_object($ergebnis);
$Name=$row->Name;
$Bech=$row->Beschreibung;
?>
<a href="" title="<?php echo $Name; ?> <?php echo $Bech; ?>">Test Link</a>
A: If you just want the first result remove the while...
<?php
$abfrage = "SELECT * FROM tester";
$ergebnis = mysql_query($abfrage);
$row = mysql_fetch_object($ergebnis);
$Name=$row->Name;
$Bech=$row->Beschreibung;
?>
<a href="" title="<?=$Name?> <?=$Bech?>">Test Link</a>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18198836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to prevent users to entering into website after logout by pressing back button? In my asp.net application user login is available. After user logged out and if pressed the back button it goes to the previously visited page. I need to control the user to again login to enter into the website. How to solve this problem. I writing code in vb.
A: At log out button_click ,
perform session.Abondon();
and Check the session in each page_Load like
if(session["userName"]!=null)
{
//Perform the action
}
else
{
//Redirect to login page
}
A: Use the following code on logout click
Session.RemoveAll();
Session.Abandon();
A: add this logout button
Session.Abandon();
A: You can use this...
<script type = "text/javascript" >
function preventBack() { window.history.forward(); }
setTimeout("preventBack()", 0);
window.onunload = function () { null };
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22505354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Document Clustering in Matlab I am working on a code for document clustering in matlab. My document is :
'The first step in analyzing the requirements is to construct an object model.
It describes real world object classes and their relationships to each other.
Information for the object model comes from the problem statement, expert knowledge of the application domain, and general knowledge of the real world.
Britvic plc is one of the leading soft drinks manufacturers of soft drinks in the Beverages Sector functioning in Europe with its distribution branches in Great Britain, Ireland and France. '
As seen, the paragraphs contain different classes of data. The following is my main program:
global n;
n=1;
file1=fopen('doc1.txt','r');
%file 1 is now open
%read data from file 1
text=fileread('doc1.txt');
i=0;
%now text1 has the content of doc1 as a string.Next split the sentences
%into words.For that we are calling the split function
[C1,C2]=clustering(text)
And below comes the code for 'clustering':
function [C1,C2]=clustering(text)
global C1;
text1=strsplit(text,'.');
[rt1,ct1]=size(text1);
for i=1:(ct1-1)
var=text1{i};
vv=strsplit(var,' ');
text2=setdiff(vv,{'this','you','is','an','with','as','well','like','and','to','it','on','off','of','in','mine','your','yours','these','this','will','would','shall','should','or','a','about','all','also','am','are','but','of','for','by','my','did','do','her','his','the','him','she','he','they','that','when','we','us','not','them','if','in','just','may','not'},'stable');
[rt2,ct2]=size(text2);
for r=1:ct2
tmar=porterStemmer(text2{r});
mapr{i,r}=tmar;
end
end
[mr,mc]=size(mapr);
mapr
A=zeros(mr,mr);
for i=1:mr
for j=1:mc
for m=i+1:mr
for k=1:mc
if ~isempty(mapr{i,j})
%if(~(mapr{i,j}=='[]'))
%mapr(i,j)
if strcmp(mapr{i,j},mapr{m,k})
p=mapr{i,j};
str=sprintf('Sentences %d and %d match',i,m)
str;
str1=sprintf('And the word is : %s ',p)
str1;
A(i,m)=1;
A(m,i)=1;
end
end
end
end
end
end
sprintf('Adjacency matrix is:')
A
sprintf('The corresponding diagonnal matrix is:')
[ar,ac]=size(A);
for i=1:ar
B(i)=0;
for j=1:ac
B(i)=B(i)+A(i,j);
end
end
[br,bc]=size(B);
D=zeros(bc,bc);
for i=1:bc
D(i,i)=B(i);
end
D
sprintf('The similarity matrix is:')
C=D-A
[V,D]=eig(C,'nobalance')
F=inv(V);
V*D*F
%mvar =no of edges/total degree of vertices
no_of_edges=0;
for i=1:ar
for j=1:ac
if(i<=j)
no_of_edges=no_of_edges+A(i,j);
end
end
end
no_of_edges;
tdv=0;
for i=1:bc
tdv=tdv+B(i);
end
tdv;
mvar=no_of_edges/tdv
[dr,dc]=size(D);
temp=abs(D(1,1)-mvar);
x=D(1,1);
for i=2:dc
temp2=abs(D(i,i)-mvar);
if temp>temp2
temp=temp2;
x=D(i,i);
q=i
end
end
x
[vr,vc]=size(V);
for i=1:vr
V(i,q);
Track(i)=V(i,q);
end
sprintf('Eigen vectors corresponding to the closest value:')
Track
j=1;
m=1;
C1=' ';
C2=' ';
for i=1:vr
if(Track(i)<0)
C1=strcat(C1,text1{1,i},'.');
else
C2=strcat(C2,text1{1,i},'.');
end
end
I could generate the initial two clusters from the document. But then again, I want the clustering process to continue on the generated clusters producing more and more subclusters of each untill there is no change in the population generated. Can somebody help me implement a solution to this so that I can not only generate the clusters but also to keep track of them for further processing. Thanks in advance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21659454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How To Display GlSurfaceView in Phonegap in android I have requirement in my Project. My project is Video conference call using third party library. I am doing this project in Native android and phonegap. In Native android, After succefully connect video conference call , The thrird party library gives a custom view which extends GLSurfaceView (For rendering Video). I added custom view as child of Relative layout in my Screen. So, it works well in Native android application. But ,I have a problem in Phonegap. After succefully connect Video conference call how to send or disply GlSurfaceView in phonegap. Could please anybody give a suggestion to my problem. Sorry for my bad english.
A: You can't put GlSurfaceView into CordovaWebView, but you can place in next/top of to each other.
Create Relative view and put both of them into it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25053314",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting all values from text field widgets and returning them to button widgets When I return values to a set of text fields and expect the same set of entries to display in the corresponding buttons,am only able to return the last entered text value into all the buttons using Tkinter python 3. How to get the corresponding text values in the corresponding button fields? This is the respective code for it.
def inputt(self):
x = int(self.number.get())
entries_list=[]
path_list=[]
button_list=[]
label_list=[]
button_1_list=[]
for i in range(0,x):
l = Label(root,text="Device "+str(i+1)+":")
l.grid(row=i+5,column=0)
label_list.append(l)
self.e = Entry(root)
self.e.grid(row=i+5,column=1)
entries_list.append(self.e)
b1 = Button(root,text="Next",command=lambda:load(self,self.inputt))
b1.grid(row=i+6,column=0)
def load(self, inputt):
for i in range(0,x):
b3=Button(root, text=self.e[i].get())
b3.grid(row=i+100,column=0)
button_list.append(b3)
For the given text entries,I want to return the values to Def(load) function's buttons.
A: The variables that declares widgets are needs to be declared separately, otherwise the last variable will overwrite the current widget and when it will called, it will show only last widget value.
This can be fixed using enumerating the list. The enumeration technique indexes objects as well as selects every object from a list at a same time.
Also it is required to declare every text variable for Entry widget is declared separately.For that every variable will be appended to list and then that list will enumerated when the variables are called.
Here's a Solution,
import tkinter
from tkinter import *
root = Tk()
entries_list = []
path_list = []
button_list = []
label_list = []
var_list = []
x = 5 #int variable that define how many times will loop run
for var in range(0,x):
#always define a variable type before adding it to Entry Box
se = StringVar()
var_list.append(se)
def inputt():
# use enumerate for indexing the list
for p,q in enumerate(var_list):
l = Label(root,text="Device "+str(p+1)+":")
l.grid(row=p,column=0)
label_list.append(l)
e = Entry(root, textvariable = var_list[p], width=25)
e.grid(row=p, column=1)
b1 = Button(root,text="Next",command=lambda:load())
b1.grid(row=p+2,column=0)
def load():
# Entered values will loaded to entries_list when next button is pressed
for u,v in enumerate(var_list):
entries_list.append(var_list[u].get())
for j,k in enumerate(entries_list):
b3=Button(root, text=k)
b3.grid(row= j + x + 2,column=0,columnspan = 2,sticky = EW)
button_list.append(b3)
inputt()
root.mainloop()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59450524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: What is wrong with this route? Hey.
I was going to make a "current" class for my menu component, that creates the menus. To find out the current class, it was suggested to use $this>getContext()->getRouting()->getCurrentRouteName();. To do this, I had to set up routes for all the menu-elements that was going to exist.
Lets say I have two elements so far, one for the frontpage, one for the customer. Whenever I am browsing the frontpage, matter what action and parameters, I would like the above code to return "frontpage". Same goes for customer.
My rule for customer now, is the following:
routing.yml
customer:
param: { module: customer }
I thought that setting up the url was not important, I have already specified the module to be customer. The menu element should have "current" class no matter the action used.
How I link:
if ($current == $name){
echo link_to($name, $link, array("class" => "selected"));
}else {
echo link_to($name, $link);
}
Links ($link) that now go to "customer/some_action" does not work, they show up as just "/". So I thought to use url_for around the $link, that didn't work either, same result.
There must be something wrong with my routing rules... Because when I enter lets say /customer/new manually, I can see the page. If I from the template write out $this>getContext()->getRouting()->getCurrentRouteName();, it says default. So my rule definitely does not work at all. I've tried other rules too, but haven't got anyone working. The trick is to make one rule that works for anything under the module customer..
And yes, I clear my cache after changing each of my rules.
Thanks a lot.
EDIT:
I made the routing rules work, but not for all actions under the customer module. I have to make rules for each action. But, the links are still broken, they show "/".
My new rules:
customer_index:
url: /:module
param: { module: customer, action: index }
customer_new:
url: /:module/:action
param: { module: customer, action: new }
None of these links works:
echo link_to("Customers", "@customer_index", array("module" => "customer"));
echo link_to("New customer", "@customer_new", array("module" => "customer"));
A: Yep, this is how I've done it a few times as well. You need separate routing rules to use getCurrentRouteName().
The problem you have with the links is that you cannot pass the "module" parameter in this way. It's not a valid parameter for the Symfony link_to() helper. Instead, you can pass it this way:
link_to('Customers', '@customer_index?url_variable=something');
customer_index:
url: /:url_variable
param: { module: customer, action: index, url_variable: some_default_value }
The default value is optional, but the link_to helper will throw an error if you don't pass the variable and the route doesn't have a default value for it.
Also, just pointing this out as you've got it twice wrong in your code above:
$this>getContext()->getRouting()->getCurrentRouteName();
...should be:
$this->getContext()->getRouting()->getCurrentRouteName();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4908831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to label Knob within the canvas I would like to know how to include a text also inside the value field provided in the knob.js plugin.
https://github.com/aterrien/jQuery-Knob
I did not come across a parameter where I can include text field also inside the value. If there is a work around please help me with it.
A: You can configure a 'format' hook to change the way that the text value is formatted before it gets displayed.
For example to add a percentage sign to the text you could do something like:
$(".dial").knob({
'format' : function (value) {
return value + '%';
}
});
The value that gets passed in is the number, and whatever the function returns is what gets displayed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19418657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: This referring to clicked object and not to namespace Let's say I have a namespace and several functions , e.g. in this way :
HTML
<input type="button" class="btn" value="click">
JAVASCRIPT
var nms = {
doAlert: function(){
alert('doing alert');
console.log(this);
},
bindBtn: function(){
var that = this;
$('.btn').on('click', that.doAlert);
}
}
nms.bindBtn();
the log prints <input type="button" class="btn" value="click"> ,in other words, this refers to the element I'm executing the function in.
It is probably my lack, but I would like to understand how can I refer to nms instead of input. If possible, using this
A: You should use proxy() jquery's method to apply specific context:
$('.btn').on('click', $.proxy( this.doAlert, this ));
DEMO
A: There are a number of ways to do this. I prefer to define the object inside an IIFE (immediately invoked function expression) so that it can use a private variable to keep track of itself:
var nms = (function () {
var myownself = {
doAlert: function () {
alert('doing alert');
console.log(myownself);
},
bindBtn: function () {
$('.btn').on('click', myownself.doAlert);
}
};
return myownself;
})();
nms.bindBtn();
Demo: http://jsfiddle.net/Yu5Mx/
That way, all of the methods of that object can just refer to the myownself variable but they don't need to know about the nms variable by which the object is known to the rest of your code. And if you do something like:
var temp = nms.bindBtn;
temp();
...which "messes up" the value of this within bindBtn() then it doesn't matter, because bindBtn() will still use myownself.
Note that this pattern assumes that nms will be a singleton object. If you want to be able to instantiate multiple copies you can still use the same general idea, but use a factory function or a conventional constructor function with new (rather than an IIFE).
A: var nms = {
doAlert: function(){
alert('doing alert');
console.log(this);
},
bindBtn: function(){
$('.btn').on('click', nms.doAlert.bind(nms));
}
}
To support bind for IE you can use this
A: Try this
var nms = {
doAlert: function(){
alert('doing alert');
console.log(this);
},
bindBtn: function(){
var that = this;
$('.btn').on('click', function(){
nms.doAlert.apply(that);
});
}
}
nms.bindBtn();
Demo
This passes that through the function as this
You can use call() for this too
Some links
apply()
call();
Or Without using call or apply
var nms = {
doAlert: function(){
var _this = nms;
alert('doing alert');
console.log(_this);
},
bindBtn: function(){
var that = this;
$('.btn').on('click', nms.doAlert);
}
}
nms.bindBtn();
Demo
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17629743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unknown amount of the nodes in yml - how to parse? In an application I have this:
def get_debt_for_month(api_requests_count)
case api_requests_count
when 0..50
5
when 50..100
9
when 100..200
13
# and so on
end
end
Obviously, having that hardcoded isn't a good idea. How would I do that? I figure the best way is that the prices should be moved to an yml file, but how why I parse it dynamically, given that the amount of the cases isn't known and can vary?
A: If there are no gaps in the range, just use the starting value...
# data.yml
0: 5
51: 9
101: 13
and then your method...
def get_debt_for_month(api_request_count)
thresholds = YAML.load_file('data.yml')
thresholds.sort.select{|e| e[0] <= api_request_count}.last[1]
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27872228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MS Access update query that calls a function doesn't return anything/update a field I have a text field Ran and I want to be able to update the field RanKeyNo5 (update query) with the numeric equivalent (2 digits) for a specified number of letters as they occur in the Ran field, i.e. the first 5 letters of the alphabet in the order that they occur in Ran.
For example, if Ran contains BFHCIEALGJDK, the answer would be 0203050104.
I put message boxes in the code to monitor the values, and it seemed to work, but the table doesn't get updated.
Query, 'update to':
KeyNo([Ran],5)
Public Function KeyNo(myStr As String, intLen As Integer) As String
Dim RandomString As String, strLetter As String, PosNo As Integer, LetSelect As String, LetNo As String, Count As Integer
RandomString = "00"
PosNo = 1
Count = Len(myStr)
'MsgBox myStr
Dim i As Long
For i = 1 To Count
LetSelect = Mid(myStr, PosNo, 1)
If LetSelect = "A" Then
LetNo = "01"
ElseIf LetSelect = "B" Then
LetNo = "02"
ElseIf LetSelect = "C" Then
LetNo = "03"
ElseIf LetSelect = "D" Then
LetNo = "04"
ElseIf LetSelect = "E" Then
LetNo = "05"
ElseIf LetSelect = "F" Then
LetNo = "06"
ElseIf LetSelect = "G" Then
LetNo = "07"
ElseIf LetSelect = "H" Then
LetNo = "08"
ElseIf LetSelect = "I" Then
LetNo = "09"
ElseIf LetSelect = "J" Then
LetNo = "10"
ElseIf LetSelect = "K" Then
LetNo = "11"
ElseIf LetSelect = "L" Then
LetNo = "12"
ElseIf LetSelect = "M" Then
LetNo = "13"
ElseIf LetSelect = "N" Then
LetNo = "14"
ElseIf LetSelect = "O" Then
LetNo = "15"
ElseIf LetSelect = "P" Then
LetNo = "16"
ElseIf LetSelect = "Q" Then
LetNo = "17"
ElseIf LetSelect = "R" Then
LetNo = "18"
ElseIf LetSelect = "S" Then
LetNo = "19"
ElseIf LetSelect = "T" Then
LetNo = "20"
ElseIf LetSelect = "U" Then
LetNo = "21"
ElseIf LetSelect = "V" Then
LetNo = "22"
ElseIf LetSelect = "W" Then
LetNo = "23"
ElseIf LetSelect = "X" Then
LetNo = "24"
ElseIf LetSelect = "Y" Then
LetNo = "25"
ElseIf LetSelect = "Z" Then
LetNo = "26"
End If
If Val(LetNo) <= intLen Then
RandomString = RandomString & LetNo
' MsgBox RandomString
End If
PosNo = PosNo + 1
Next
RandomString = Mid(RandomString, 3, intLen * 2)
End Function
A: It returns nothing because function is not set to return anything. Last line should be:
KeyNo = Mid(RandomString, 3, intLen * 2)
A: As @June7 correctly notes in their answer, the reason that your function does not return anything is because the symbol KeyNo is initialised as a null string ("") by virtue of the fact that the function is defined to return a string (Function KeyNo ... As String), however, you don't redefine KeyNo to anything else within the function, hence, the function will always return an empty string.
However, for the task that you have described:
I want to be able to update the field RanKeyNo5 with the numeric equivalent (2 digits) for a specified number of letters as they occur in the Ran field.
The code could be greatly simplified - for example, consider the following approach:
Function KeyNo(strStr As String, intLen As Integer) As String
Dim i As Integer
Dim a As Integer
For i = 1 To Len(strStr)
a = Asc(Mid(strStr, i, 1)) - 64
If a <= intLen Then KeyNo = KeyNo & Format(a, "00")
Next i
End Function
?KeyNo("BFHCIEALGJDK",5)
0203050104
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60011614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Any ideas to creating a "password tab"? This inquiry is quite ambiguous so let me try my best to clarify. I want to create a link on a webpage containing confidential samples that when a user clicks, opens a tab and requires the user to input a password in order to access the information.
Any help or word of advice would be greatly appreciated!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35532153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to see a history of email addresses to which an email was sent to, by Amazon SES? I have a subscription form that, when filled, sends an email using Amazon SES & stores user info in my database.
The database has not been working in recent weeks, although mail delivery has worked.
Since my storage mechanism has failed, can SES provide me with a history of email addresses to which an email was sent to?
A:
Since my storage mechanism has failed, can SES provide me with a history of email addresses to which an email was sent to?
No unfortunately, unless you previously configured it to do so.
Checking anything at a granular level within SES - including email sending/delivery - can only be done using event publishing.
Also, event publishing cannot be backdated so if you enable it now, it will also only work for emails sent from this point onwards.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74390352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to allow anonymous twitter connections in an MVC configuration Using
- spring-social 1.1.4
- spring-social-twitter 1.1.2
- spring-mvc-4.2
- on tomcat 7
Below is my tomcat config for my MVC Application including twitter set up and usersConnectionRepository.
This is all working fine for the logged in MVC user.
The problem for me arises when I want to allow clients to tweet from a public link available to non MVC authenticated users. (#{request.userPrincipal.name} will be null)
I have looked through many examples.
Most examples use old 1.0.0 spring-social.
I noticed that the new 1.1.2 version of spring-social-twitter Does not have a zero argument Twitter() constructor, which is in some examples is shown to be a way to work without the connectionRepository.
I am looking for a way to configure or code an option to allow both user logged in to my app and anonymous users to use some options on my site.
In the configuration below an anonymous user being redirected to connect/twitter will result in a problem getting a connetionRepository.
usersConnectionRepository must have a "#{request.userPrincipal.name}" because my connectController relies on this.
I am thinking maybe I need a custom connect controller...
There must be a correct approach to this.
Any suggestions welcome.
my web.xml
<listener>
<listener-class>
org.springframework.web.util.Log4jConfigListener
</listener-class>
</listener>
<display-name>Central Portal</display-name>
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>dev</param-value>
</context-param>
<context-param>
<param-name>spring.profiles.default</param-name>
<param-value>dev</param-value>
</context-param>
<context-param>
<param-name>spring.liveBeansView.mbeanDomain</param-name>
<param-value>dev</param-value>
</context-param>
<!-- Spring MVC -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<error-page>
<error-code>500</error-code>
<location>/WEB-INF//pages/error.jsp</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/pages/error.jsp</location>
</error-page>
<error-page>
<location>/WEB-INF/pages/error.jsp</location>
</error-page>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml,
/WEB-INF/spring-database.xml
</param-value>
</context-param>
<!-- Enable POST -->
<filter>
<filter-name>hiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Concurrency listener -->
<listener>
<listener-class>
org.springframework.security.web.session.HttpSessionEventPublisher
</listener-class>
</listener>
one bit of java config
mvc-dispatcher-servlet.xml
<context:component-scan base-package="org.schoolit.usermanager.config" />
<!-- component-scan / controllers -->
<context:component-scan base-package="org.schoolit.webapplication.*" />
<context:component-scan base-package="org.schoolit.spring.social.*"/>
<!-- property-placeholder's -->
<context:property-placeholder location="classpath:oauth.properties"/>
<!-- resource mapping -->
<mvc:resources mapping="/gen/**" location="/WEB-INF/gen/" cache-period="31556926"/>
<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" cache-period="31556926"/>
<!-- JSP ViewResolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<!-- twitter stuff start -->
<bean id="handlerExceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="Exception">error</prop>
</props>
</property>
</bean>
<bean id="twitterTemplate"
class="org.springframework.social.twitter.api.impl.TwitterTemplate">
<constructor-arg value="${twitter.oauth.consumerKey}"/>
<constructor-arg value="${twitter.oauth.consumerSecret}"/>
<!--<constructor-arg value="${twitter.oauth.accessToken}"/>
<constructor-arg value="${twitter.oauth.accessTokenSecret}"/> -->
</bean>
<bean id="connectionFactoryLocator" class="org.springframework.social.connect.support.ConnectionFactoryRegistry">
<property name="connectionFactories">
<list>
<bean class="org.springframework.social.twitter.connect.TwitterConnectionFactory">
<constructor-arg value="${twitter.oauth.consumerKey}" />
<constructor-arg value="${twitter.oauth.consumerSecret}" />
</bean>
</list>
</property>
</bean>
<bean id="connectionRepository" factory-method="createConnectionRepository" factory-bean="usersConnectionRepository" scope="request">
<constructor-arg value="#{request.userPrincipal.name}" />
<aop:scoped-proxy proxy-target-class="true" />
</bean>
<bean id="usersConnectionRepository"
class="org.springframework.social.connect.jdbc.JdbcUsersConnectionRepository">
<constructor-arg ref="dataSource" />
<constructor-arg ref="connectionFactoryLocator" />
<constructor-arg ref="textEncryptor" />
</bean>
<bean id="textEncryptor" class="org.springframework.security.crypto.encrypt.Encryptors"
factory-method="noOpText" />
<bean id="connectController" class="org.springframework.social.connect.web.ConnectController">
<constructor-arg ref="connectionFactoryLocator"/>
<constructor-arg ref="connectionRepository"/>
<property name="applicationUrl" value="http://localhost:8080/CentralPortal/" />
<property name="connectInterceptors">
<list>
<bean class="org.schoolit.spring.social.TweetAfterConnectInterceptor"/>
</list>
</property>
</bean>
spring-database.xml
<!-- App's dataSource used by jdbcTemplate,jdbc-user-service and connectController -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/spring_me" />
<property name="username" value="root" />
<property name="password" value="<mypassword>" />
</bean>
<!-- jdbcTemplate used in usermanager bit only for now. -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="dataSource" />
</bean>
spring-security.xml
<!-- enable use-expressions -->
<http auto-config="true" use-expressions="true">
<!-- Set up rolefilter's for requestmapping's -->
<intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="/usermanager**" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="/users**" access="hasRole('ROLE_ADMIN')" />
<!-- access denied page -->
<access-denied-handler error-page="/403" />
<!-- loginform-setup Spring Security -->
<form-login
login-page="/login"
default-target-url="/home"
login-processing-url="/j_spring_security_check"
authentication-failure-url="/login?error"
username-parameter="username"
password-parameter="password" />
<logout logout-success-url="/login?logout" />
<!-- enable csrf protection default is enabled from 4.0 spring
<csrf /> <csrf disabled="true"/> -->
<csrf request-matcher-ref="connect/*" disabled="true"/>
<!-- Prevent Clickjacking iframe's -->
<headers>
<frame-options policy="SAMEORIGIN"/>
</headers>
<!-- One login per username should be one set to 5 for testing-->
<session-management>
<concurrency-control max-sessions="1" error-if-maximum-exceeded="true" expired-url="/login?error" />
</session-management>
</http>
<!-- Select users and user_roles from database -->
<authentication-manager>
<authentication-provider>
<password-encoder ref="encoder" />
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query="select username,password, enabled from users where username=?"
authorities-by-username-query="select username, role from user_roles where username =? " />
</authentication-provider>
</authentication-manager>
<!-- encoder bean. Used for password encryption -->
<beans:bean id="encoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
<beans:constructor-arg name="strength" value="11" />
</beans:bean>
A: I see that you have twitterTemplate bean configured, if you are able to use it in the application you won't need to do anything else.
Use TwitterTemplate instead of Twitter.
TwitterTemplate implements Twitter interface, so all methods are available.
Examples:
//1. Search Twitter
SearchResults results = twitterTemplate.searchOperations().search("#WinterIsComing");
List<Tweet> tweets = results.getTweets();
int i =0;
for (Tweet tweet : tweets) {
System.out.println(tweet.getUser().getName() + " Tweeted : "+tweet.getText() + " from " + tweet.getUser().getLocation()
+ " @ " + tweet.getCreatedAt() + tweet.getUser().getLocation() );
}
//2. Search Place by GeoLocation
RestTemplate restTemplate = twitterTemplate.getRestTemplate();
GeoTemplate geoTemplate = new GeoTemplate(restTemplate, true, true);
List<Place> place = geoTemplate.search(37.423021, -122.083739);
for (Place p : place) {
System.out.println(p.getName() + " " + p.getCountry() + " "+p.getId());
}
//3. Get Twitter UserProfile
TwitterProfile userProfile = twitterTemplate.userOperations().getUserProfile();
System.out.println(userProfile.getName()+" has " +userProfile.getFriendsCount() + " friends");
Using TwitterTemplate, users don't need to login. Hope this helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34727911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Vega text mark renders "undefined" when not hovering I'm trying to create a simple bar chart using Vega on the Vega editor.
To re-create my issue, navigate to this bar chart example on vega site, and try to change the text property of the text mark as follows:
*
*Original: "text": {"signal": "tooltip.amount"},
*Modify to: "text": {"signal": "tooltip.amount + ' + ' + tooltip.category"},
This leads to undefined + undefined displayed on the top left corner of the chart when no hover event occurs. How do I get around this issue to make sure its not displayed? (issue depicted below)
I think this is something to do with how the scales and the text mark are functioning, but I was not able to figure out the solution. Tried adding a default value in mouse hover events by setting category to null and testing it while configuring mark opacity, but it didn't work. Code for this (only specifying updates to the raw example on site):
"signals": [
{
"name": "tooltip",
"value": {"category":null},
"on": [
{"events": "rect:mouseover", "update": "datum"},
{"events": "rect:mouseout", "update": "{'category':null}"}
]
}
],
...
"marks": [
...
{
"type": "text",
"encode": {
...
"update": {
"text": {"signal": "tooltip.amount + ' + ' tooltip.category"},
"fillOpacity": [
{"test": "datum === tooltip && tooltip.category!=null", "value": 0},
{"value": 1}
]
}
}
}
A: Thanks to a friend for helping me with the answer:
"text": [
{
"signal": "tooltip.amount + ' + ' + tooltip.category",
"test": "tooltip.amount"
},
{"value": ""}
],
The issue was when you hover out the tooltip object does not have a value
since we are concatenating the values with the ' + ' string. The undefined object is coerced to the 'undefined' string.
Updating the string value to an empty string again is what is required.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63836398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Update multiple column with activeAndroid I want to update multiple cell of single row with active android.
some thing like this,
new Update(Question.class).set("UserAnswer ="+answerID,
"UserAnswerType = "+userAnswerType)
.where("QID = ?", questionID).execute();
but that will gives me error. is there any other way to do this? or am i missing something?
Here is my Question.class for reference
@Table(name = "Questions")
public class Question extends Model {
@Expose
@Column(name = "QID")
private Integer ID;
@Expose
@Column(name = "AnswerID")
private Integer AnswerID;
@Expose
@Column(name = "UserAnswer")
private Integer UserAnswer;
@Expose
@Column(name = "UserAnswerType")
private Integer UserAnswerType;
//Getter and setter methods for fields
public Question() {
// You have to call super in each constructor to create the table.
super();
}
}
A: You can do something like below. I have done it in one of my project and it worked fine.
String updateSet = " UserAnswer = ? ," +
" UserAnswerType = ? ";
new Update(Question.class)
.set(updateSet, answerID, userAnswerType)
.where(" QID = ? ", questionID)
.execute();
Following similar pattern for any number of columns will work. In case if you have Boolean type fields in your table, this issue can help you.
A: We Can achieve it like this way.
StringBuilder data=new StringBuilder();
if (!TextUtils.isEmpty(name.getText().toString()))
{
data.append("Name = '"+name.getText().toString()+"',");
}
if (!TextUtils.isEmpty(age.getText().toString()))
{
data.append("Age = '"+age.getText().toString()+"',");
}
if (!TextUtils.isEmpty(empCode.getText().toString()))
{
data.append("EmployeeCode = '"+empCode.getText().toString()+"',");
}
if (!TextUtils.isEmpty(mobNum.getText().toString()))
{
data.append("MobileNumber = '"+mobNum.getText().toString()+"',");
}
if (!TextUtils.isEmpty(adress.getText().toString()))
{
data.append("address = '"+adress.getText().toString()+"'");
}
String str=data.toString();
//-------------and update query like this-----------------
new Update(EmpProfile.class).set(str).where("EmployeeCode = ?", empCode)
.execute();
A: String x="sent = 1,file = "+n.getString("file");
new Update(Messages.class)
.set(x)
.where("id = ?", lid)
.execute();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34453744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: vs code : java.rmi.ConnectException: Connection refused to host: 127.0.0.1 i have created an app in flutter language and it worked perfect at the beginning then after i flutter pub get it stopped running in vs code and i'm getting this error
java.rmi.ConnectException: Connection refused to host: 127.0.0.1; nested exception is:
java.net.ConnectException: Connection refused: connect
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:foodies_app/breakfast.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:footer/footer.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:video_player/video_player.dart';
import 'package:footer/footer_view.dart';
import 'package:localize_and_translate/localize_and_translate.dart';
// void main() => runApp(MyApp());
main() async {
WidgetsFlutterBinding.ensureInitialized();
await translator.init(
localeType: LocalizationDefaultType.device,
languagesList: <String>['ar', 'en'],
assetsDirectory: 'assets/langs/',
// apiKeyGoogle: '<Key>', // NOT YET TESTED
); // intialize
runApp(LocalizedApp(child: MyApp()));
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Home(),
localizationsDelegates: translator.delegates, // Android + iOS Delegates
locale: translator.locale, // Active locale
supportedLocales: translator.locals(),
title: 'Flutter Demo',
theme: ThemeData(),
);
}
}
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
VideoPlayerController _controller;
@override
@override
@override
void initState() {
super.initState();
// Pointing the video controller to our local asset.
_controller = VideoPlayerController.asset("assets/02.mp4")
..initialize().then((_) {
// Once the video has been loaded we play the video and set looping to true.
_controller.play();
_controller.setLooping(true);
// Ensure the first frame is shown after the video is initialized.
setState(() {});
});
@override
void dispose() {
super.dispose();
_controller.dispose();
}
}
Widget build(BuildContext context) {
return
Scaffold(
// TODO 6: Create a Stack Widget
body: Stack(children: <Widget>[
// TODO 7: Add a SizedBox to contain our video.
SizedBox.expand(
child: FittedBox(
// If your background video doesn't look right, try changing the BoxFit property.
// BoxFit.fill created the look I was going for.
fit: BoxFit.fill,
child: SizedBox(
width: _controller.value.size?.width ?? 0,
height: _controller.value.size?.height ?? 0,
child: VideoPlayer(_controller),
),
),
),
]));
}
}
A: wipe the emulator data from the ADB manager
edit:
I had the same issue on my Mac, the solution was to go to ADB manager on android studio and wipe the emulator data like the screenshot provided:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69780329",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting an error with trying to set up Firebase push Notifications I am following the Firebase Push Notifications quick start but am receiving this error.
Not sure what's going on as this is the documentation for the quick start guide.
A: You're trying to set your AppDelegate as a UNUserNotificationCenterDelegate, but your AppDelegate does not implement that protocol yet. Find out more information about protocols here. The spec for UNUserNotificationCenterDelegate can be found here. Something like this will work:
extension AppDelegate: UNUserNotificationCenterDelegate {
optional func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// TODO: Implement
}
optional func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
// TODO: Implement
}
}
The second error means the property does not exist. The documentation is most likely out of date with the framework.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40315263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I pick the photo from the device in Zebble for Xamarin? I want to get the picture from the user in my application and for this reason, I use file picker which exists in Zebble UI components like this code:
In my page:
<FilePicker Id="MyFilePicker"></FilePicker>
I did find the code from this link
http://zebble.net/docs/filepicker-class
But, I had a problem with this component, because I just want to pick some pictures from the device, not video or anything else.
A: As you mentioned in your question I review the website and find this code, after that I tested it on my android device and I figure out this is the answer.
First, add this code to your page to show the file picker user interface
<z-place inside="Body">
<FilePicker Id="MyFilePicker"></FilePicker>
</z-place>
Then, add below code to the page code behind to set the control just for picking the photos.
public override async Task OnInitializing()
{
await base.OnInitializing();
await InitializeComponents();
MyFilePicker.Set(x => x.AllowOnly(MediaSource.PickPhoto,
MediaSource.TakePhoto));
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43503830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can get the right size images when setting some resource to imageview? I hope to put some item into a gridview like following :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/llBg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="vertical"
android:paddingBottom="40dp" >
<ImageView
android:id="@+id/mudImg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:scaleType="fitCenter"
android:src="@drawable/icon_m0_r"
android:visibility="visible" />
<TextView
android:id="@+id/mudTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="8dp"
android:gravity="center"
android:text="fsafdsf"
android:textColor="@color/white"
android:textSize="16dp" />
</LinearLayout>
While the 'mudImg' part got something wrong with the image's size on a true android machine.Actually It never works util I set a indeed num to 'layout_width' and 'layout_height' like '50dp' or something like this.
What I want is show the origin size image and if necessary expended to the size what the parent view left to it.
Now my solution is that calculating the image size with app screen params(height width) and parent view's margins and gridview's numColumns and setting the result by code (since can not do it in xml)
any better idea?
A: Try this for your ImageView:
<ImageView
android:id="@+id/mudImg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:src="@drawable/icon_m0_r"
android:visibility="visible" />
adjustViewBounds="true" tells the ImageView to set the height so that the image has the correct aspect ratio using the given width.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34891475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Changing the content of view dynamically in android i am new in android and i got some question about the project that i am doing right now.
i am developing an apps that display a total of 9 images in 3x3 like the picture below.
when i press the next button, the images changed to another 9 images. if the remaining images is not 9, then the images will showing according the number of remaining like the picture below. (example the remaining is 6 images)
and the questions is:
*
*what is the best method to display the images? my idea is create a view that contains 9 ImageViews
*If i have 2 xml layout, first is the main layout and the second is layout contains the ImageViews, how to insert the second one to first one?
*and how to insert the images dynamically according to the explanation above?
please help me with some code. i very appreciate any help. sorry if my english is not so good.
Thank you in advance.
UPDATE
i have tried using GridView for this case, this is the first time i using GridView, so i using the example from here and implement it to mine (i have tried the example that contained there, and it's works).
But, i have checked it many time, there's no error comes from LogCat, no Force Closed, the image didn't show. i have no idea where's the wrong part.
Here's my code:
choosepic.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/bg_inner">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/book_inner"
android:layout_marginTop="50dp"
/>
<ImageButton
android:id="@+id/homeBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/home_btn"
android:background="@null"
/>
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/bg_arrow_btn"
android:layout_alignParentRight="true"
/>
<ImageButton
android:id="@+id/nextBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/right_arrow"
android:background="@null"
android:layout_alignParentRight="true"
android:layout_marginTop="5dp"
android:layout_marginRight="7dp"
android:layout_marginLeft="7dp"
/>
<ImageButton
android:id="@+id/prevBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/left_arrow"
android:background="@null"
android:layout_toLeftOf="@+id/nextBtn"
android:layout_marginTop="5dp"
/>
<GridView
android:id="@+id/gridView1"
android:numColumns="3"
android:gravity="center"
android:columnWidth="30dp"
android:stretchMode="columnWidth"
android:layout_width="300dp"
android:layout_height="200dp"
android:layout_marginLeft="60dp"
android:layout_marginTop="70dp"
>
</GridView>
</RelativeLayout>
animalbutton.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="@+id/grid_item_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"
/>
</LinearLayout>
ImageAdapter.java
public class ImageAdapter extends BaseAdapter{
private Context context;
private final String[] animalValues;
public ImageAdapter(Context context, String[] animalValues) {
this.context = context;
this.animalValues = animalValues;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
// get layout from mobile.xml
gridView = inflater.inflate(R.layout.animalbutton, null);
// set image based on selected text
ImageView imageView = (ImageView) gridView.findViewById(R.id.grid_item_image);
String animal = animalValues[position];
if (animal.equals("Cat")) {
imageView.setImageResource(R.drawable.anim_cat);
} else if (animal.equals("Cow")) {
imageView.setImageResource(R.drawable.anim_cow);
} else if (animal.equals("Croc")) {
imageView.setImageResource(R.drawable.anim_croc);
} else if(animal.equals("Duck")){
imageView.setImageResource(R.drawable.anim_duck);
} else if(animal.equals("Elephant")){
imageView.setImageResource(R.drawable.anim_elephant);
} else if(animal.equals("Giraffe")){
imageView.setImageResource(R.drawable.anim_giraffe);
} else if(animal.equals("Lion")){
imageView.setImageResource(R.drawable.anim_lion);
} else if(animal.equals("Moose")){
imageView.setImageResource(R.drawable.anim_moose);
} else if(animal.equals("Mouse")){
imageView.setImageResource(R.drawable.anim_mouse);
}else {imageView.setImageResource(R.drawable.ic_launcher);}
} else {
gridView = (View) convertView;
}
return gridView;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getItem(int position) {
// TODO Auto-generated method stub
return animalValues[position];
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
choosepic.java
public class choosepic extends Activity {
/** Called when the activity is first created. */
ImageAdapter mAdapter;
GridView gridView;
static final String[] animal = new String[] {
"Cat", "Cow","Croc", "Duck", "Elephant", "Giraffe", "Lion", "Moose", "Mouse"};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choosepic);
mAdapter = new ImageAdapter(this, animal);
gridView = (GridView) findViewById(R.id.gridView1);
gridView.setAdapter(mAdapter);
gridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
Toast.makeText(getApplicationContext(), mAdapter.getItem(position), Toast.LENGTH_SHORT).show();
}
});
}
}
i need some help. thank you in advance!
A: i've figured out the answer.
*
*i am using GridView to display the images. just changes the adapter to change the content
*this question doesn't have to be answered.
*same as answer no. 1. the code is like choosepic.xml that i post before.
and the problem why my `GridView is not displayed images, coz getCount() in ImageAdapter is return 0, so no images is displayed in GridView.
i changed return 0; with return animalValues.size()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11332421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Input validation : Remove value on backspace I am running into a query; I have multiple html input box on my webpage, even inside multiple table column where user can edit for business calculations.
*
*Text box support positive as well as negative value
*maxlength etc etc....
Problem is when user enter value in any text box; there are four ways he can clear the value if he intend to type another.
*
*backspace or delete - working fine
*ctrl A + delete - working fine
*ctrl A + backspace - working fine
*select all text using mouse left click and dragging it to select
text + backspace/delete
Fourth case is failing. Kindly help in 4th scenario.
Code:
<input type="text" id="tust"/>
$(document).ready(function(){
document.getElementById('tust').onblur = issueDes;
$("input").on("keyup keydown",function (e) {
if(this.value!='-')
while(isNaN(this.value))
this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'').split('').reverse().join('');
});
});
function issueDes() {
$("#tust").val(this.value+"%");
}
Fiddle:
DEMO - MOST CLOSE I CAN RE-CREATE THIS SCENARIO
A: Detect selction and keyCode. Hope this will work for you. Only selected value will remove.
arr = [08,127,46];
$(document).ready(function(){
document.getElementById('tust').onblur = issueDes;
$("input").on("keyup keydown",function (e) {
var checkCode = $.inArray( e.keyCode, arr );
if (window.getSelection) {
var selectionRange = window.getSelection ().toString ();
if((selectionRange.length > 0) && (checkCode != -1)){
var value = $("#tust").val();
$("#tust").val(value.replace(selectionRange,""))
}
}
if(this.value!='-')
while(isNaN(this.value))
this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'').split('').reverse().join('');
});
});
function issueDes() {
var currVal = this.value;
if(currVal != "" && currVal.indexOf("%") == -1){
$("#tust").val(this.value+"%");
}
}
demo http://jsfiddle.net/farhanbaloch/awug6h9a/6/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32008257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Field set toggle on page load I have a similar code to this. but I'd like to have the fieldset toggled when the page load. Also, show and hide when someone click on legend
<fieldset>
<legend class="hide">Tags</legend>
<div>
<label>
<input type="checkbox" name="col" value="summary"
checked="checked" />
Name
</label>
<label>
<input type="checkbox" name="col" value="lastname" />
LastName
</label>
</div>
</fieldset>
JQuery
$(function(){
$('legend').click(function(){
$(this).nextAll('div').toggle();
$(this).hasClass('hide')?($(this).attr("class", "show")):
($(this).attr("class", "hide"));
});
})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53418098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Eclipse "go to definition" problem I'm using PyDev for eclipse and am experiencing some issues with "go to definition". It works for most modules, but for some site packages it does not. It does the "bump" sound and then nothing happens. One of the packages that doesn't work is Twisted, which is weird since the source is included and right there. Any idea how to fix this?
A: The go to definition works just fine. The problem was that eclipse didn't know where to find the source. You can go to window > preferences > pydev > interpreter > New folder, and add the folders missing. Even though you've added site-packages to the configuration, you still have to add subfolders separately to get code assist and to be able to go to the definition.
A: Pydev (also bundle with the Aptana distro) does not seem to have any bug exactly similar to the one you are describing.
Here is the list of bugs including the word "definition" for PyDev: bugs
You could open a bug report there with the exact version of eclipse, pydev, java used
But first:
What version of Pydev are you using? The open-source one or the commercial one (i.e. open-source + Pydev extensions)?
Because the matrix feature is quite clear:
Feature List Pydev "Open Source" Pydev Extensions
---------------------------------------------------------------
Go to definition BRM* Pydev Extensions(2)
BRM*: Bicycle Repair Man is an open-source program that provides 'go-to-definition' and refactoring. Its 'go-to-definition' only works for Python, and only works 'well' for global or local tokens (does not work very well on methods from parameters or on 'self'). It is currently 'unsupported'.
Pydev Extensions (2): Pydev extensions provides a 'go-to-definition' that works for python and jython, and should work even on methods from parameters and 'self'.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1216104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: SQLite3 with PHP How to do Cross Referencing of Columns with data found in other Columns Here is how my Sample data looks like
hwid: 1502e3c3-b49c-4907-92fd-2ffac2d50ace
ip: 68.197.140.109
character name: none
hwid: 1502e3c3-b49c-4907-92fd-2ffac2d50ace
ip: 219.100.37.236
character name: none
hwid: 1502e3c3-b49c-4907-92fd-2ffac2d50acd
ip: 68.197.140.109
character name: kalgame
Now say I'm logging in with
this hwid
1502e3c3-b49c-4907-92fd-2ffac2d50ace
and this ip address
219.100.37.236
which has a link to using a previous IP address of 68.197.140.109
and that IP address has a link to a 3rd hwid that has a character name : kalgame.
Thats what I need to do cross referencing with all IP's linked to all hwid's and then check if any of those hwid's have a character_name.
If they have a character_name associated to them return them in a SELECT DISTINCT COUNT(totalMatchesOfUniqueCharacterNames)
I also need to check if the current HWID or current IP you are using has 3 days trial period, if it does then also add it to the SELECT DISTINCT COUNT.. then I could easily check in PHP if SELECT DISTINCT COUNT is greater then 1, then abort giving out any more free trials to the specific user as he already logged in before with a character_name, and also maybe had a 3 day trial period before hand on either his PC hwid or his IP address, note I would also like to exclude blank character_name's as those players didn't login with a character yet.. so they don't count. I also have to match the locale which is which game are they playing if they are playing a different game then they also don't count.
Here is my attempt at cross referencing I been working at this for 6 hours and today is my first day using SQLite or any SQL in general so I have no clue what i'm doing
Here is my table schema DDL for both tables.. they are also both in the same database file.
CREATE TABLE ips (
hwid VARCHAR,
ip VARCHAR,
character_name VARCHAR,
locale VARCHAR,
botver VARCHAR,
reg_time DATETIME,
last_time DATETIME,
ping_count INTEGER DEFAULT 0
);
CREATE TABLE users (
hwid VARCHAR UNIQUE,
timestamp INTEGER,
daysToUse INTEGER,
pcLimit INTEGER,
comment VARCHAR
);
Here is my attempt at putting it all together
SELECT users2.hwid,
ips2.character_name,
ips2.ip
FROM users AS users2
INNER JOIN
ips AS ips2 ON ips2.hwid = users2.hwid
WHERE EXISTS (
SELECT 1
FROM users
INNER JOIN
ips ON ips.hwid = users.hwid
WHERE ips.character_name != '' AND
ips.locale = ips2.locale AND
(ips.hwid = '1502e3c3-b49c-4907-92fd-2ffac2d50ace' OR
ips.ip = '219.100.37.236') AND
EXISTS (
SELECT 1
FROM users
INNER JOIN
ips ON ips.hwid = users.hwid
WHERE ips.character_name != '' AND
ips2.ip = ips.ip AND
ips2.locale = ips.locale
)
)
OR
(ips2.hwid = '1502e3c3-b49c-4907-92fd-2ffac2d50ace' AND
users2.daysToUse = 3) OR
(ips2.ip = '219.100.37.236' AND
users2.daysToUse = 3);
Here is what I left in the production website.. which isn't that good.. doesn't do cross referencing that well skips certain columns but atleast it kinda works unlike the top code above which just sounds like it should work but doesn't work at all.
SELECT COUNT(DISTINCT users2.hwid)
FROM users AS users2
INNER JOIN
ips AS ips3 ON ips3.hwid = users2.hwid
WHERE ips3.character_name = (
SELECT ips.character_name
FROM users,
ips AS ips2
INNER JOIN
ips ON ips.hwid = users.hwid
WHERE ips.character_name != '' AND
ips.locale = ips2.locale AND
(ips.hwid = '$HWID' OR
ips.ip = '$IP')
)
OR
(ips3.hwid = '$HWID' AND
users2.daysToUse = 3) OR
(ips3.ip = '$IP' AND
users2.daysToUse = 3);
If anyone can help me out i will be forever grateful :D
A: Since your subqueries share same FROM and JOIN clauses, simplify to a compact WHERE clause:
SELECT i.ip, i.character_name, u.hwid, u.daysToUse, i.locale
FROM users u
INNER JOIN ips i
ON i.hwid = u.hwid
WHERE (i.hwid = '1502e3c3-b49c-4907-92fd-2ffac2d50ace'
AND u.daysToUse = 3)
OR (i.ip = '219.100.37.236' AND u.daysToUse = 3)
ORDER BY i.last_time
A: Solved it myself.. turns out it is very simple to do this, I just had the query done in backwards order I flipped the order and bam it works as expected.
The locale problem was hard.. I couldn't detect which locale is currently used, so I relayed on using ips.lasttime which shows which IP or HWID was used last, and being used last its obviously the locale I want to check
Final result
SELECT ips.ip,
ips.character_name,
users.hwid,
users.daysToUse,
ips.locale
FROM users
INNER JOIN
ips ON ips.hwid = users.hwid
WHERE ips.ip IN (
SELECT ips.ip
FROM users
INNER JOIN
ips ON ips.hwid = users.hwid
WHERE (ips.hwid = '1502e3c3-b49c-4907-92fd-2ffac2d50ace' AND
users.daysToUse = 3) OR
(ips.ip = '219.100.37.236' AND
users.daysToUse = 3)
)
AND
ips.locale = (
SELECT ips.locale
FROM users
INNER JOIN
ips ON ips.hwid = users.hwid
WHERE (ips.hwid = '1502e3c3-b49c-4907-92fd-2ffac2d50ace' AND
users.daysToUse = 3) OR
(ips.ip = '219.100.37.236' AND
users.daysToUse = 3) ORDER BY ips.last_time ASC
);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62318057",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Polynomial Expansion from scratch with numpy/python I am building a polynomial regression without using Sklearn.
I'm having trouble with Polynomial Expansion of features right now.
I have a dataframe with columns A and B.
When I imported and ran PolynomialFeatures(degree of 2) from Sklearn, I found that it returns 6 different features.
I understand that 2 features became 6 features because it is (A + B + Constant)*(A + B + Constant)
which becomes A2 + 2AB + 2AC + 2BC + B2 + C2, 6 different features. I am trying to recapitulate this with Python and Numpy.
As there is constant c, I created a new column C to my dataframe. However, I am very stuck on how to proceed after this. I tried for loop for (number of features * degree #) times but got confused for the combination of features.
'''
def polynomial_expansion(features_df, order):
return expanded_df
'''
Can someone help me out? What would be Python/Numpy/Pandas method I can use for this situation?
Thank you.
A: I created a simple example of what you need to do in order to create your polynomial features from scratch. The first part of the code creates the result from Scikit Learn:
from sklearn.preprocessing import PolynomialFeatures
import pandas as pd
import numpy as np
df = pd.DataFrame.from_dict({
'x': [2],
'y': [5],
'z': [6]})
p = PolynomialFeatures(degree=2).fit(df)
f = pd.DataFrame(p.transform(df), columns=p.get_feature_names(df.columns))
print('deg 2\n', f)
p = PolynomialFeatures(degree=3).fit(df)
f = pd.DataFrame(p.transform(df), columns=p.get_feature_names(df.columns))
print('deg 3\n', f)
The result looks like:
deg 2
1 x y z x^2 x y x z y^2 y z z^2
0 1.0 2.0 5.0 6.0 4.0 10.0 12.0 25.0 30.0 36.0
deg 3
1 x y z x^2 x y x z y^2 y z z^2 x^3 x^2 y x^2 z x y^2 x y z x z^2 y^3 y^2 z y z^2 z^3
0 1.0 2.0 5.0 6.0 4.0 10.0 12.0 25.0 30.0 36.0 8.0 20.0 24.0 50.0 60.0 72.0 125.0 150.0 180.0 216.0
Now to create a similar feature without Scikit Learn, we can write our code like this:
row = [2, 5, 6]
#deg = 1
result = [1]
result.extend(row)
#deg = 2
for i in range(len(row)):
for j in range(len(row)):
res=row[i]*row[j]
if res not in result:
result.append(res)
print("deg 2", result)
#deg = 3
for i in range(len(row)):
for j in range(len(row)):
for z in range(len(row)):
res=row[i]*row[j]*row[z]
if res not in result:
result.append(res)
print("deg 3", result)
The result looks like:
deg 2 [1, 2, 5, 6, 4, 10, 12, 25, 30, 36]
deg 3 [1, 2, 5, 6, 4, 10, 12, 25, 30, 36, 8, 20, 24, 50, 60, 72, 125, 150, 180, 216]
To get the same results recursively, you can use the following code:
row = [2, 5, 6]
def poly_feats(input_values, degree):
if degree==1:
if 1 not in input_values:
result = input_values.insert(0,1)
result=input_values
return result
elif degree > 1:
new_result=[]
result = poly_feats(input_values, degree-1)
new_result.extend(result)
for item in input_values:
for p_item in result:
res=item*p_item
if (res not in result) and (res not in new_result):
new_result.append(res)
return new_result
print('deg 2', poly_feats(row, 2))
print('deg 3', poly_feats(row, 3))
And the results will be:
deg 2 [1, 2, 5, 6, 4, 10, 12, 25, 30, 36]
deg 3 [1, 2, 5, 6, 4, 10, 12, 25, 30, 36, 8, 20, 24, 50, 60, 72, 125, 150, 180, 216]
Also, if you need to use Pandas data frame as an input to the function, you can use the following:
def get_poly_feats(df, degree):
result = {}
for index, row in df.iterrows():
result[index] = poly_feats(row.tolist(), degree)
return result
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58867481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Git commit is incredibly slow Lately when I use git commit after changing a few lines of code, it may take a few minutes to finish. I'm unsure what has changed.
When I run it with diagnostics:
GIT_TRACE2_PERF=1 git commit -m "message"
I get a verbose output, which hangs for at least a minute on this line. After a long time it moves on to print other lines.
... Some more lines ...
14:17:21.697862 trace2/tr2_tgt_perf.c:213 | d1 | main | atexit | | 0.024188 | | | code:0
Any ideas what may be causing this?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64426239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: FormatException of DateTime.Parse. Check which part is wrong in my date string I'd like to validate a date string in my TextBox.
If I have 2018-06-07 string in my TextBox, I can parse it with success with DateTime.TryParse or DateTime.Parse.
But if I have 2018-12-35 in my TextBox, the DateTime.Prase throws FormatException that is absolutely right.
How can I determine which part of DateTime is wrong. For Example how to determine if Day or Month is wrong.
A: DateTime.Parse tries a number of formats - some to do with the current culture, and some more invariant ones. It looks like it's including an attempt to parse with the ISO-8601 format of "yyyy-MM-dd" - which is valid for your first example, but not for your second. (There aren't 35 days in December.)
As it's trying to parse multiple formats, it doesn't necessarily make sense to isolate which part is "wrong" - different parts could be invalid for different formats.
How you should tackle this depends on where your data comes from. If it's meant to be machine-readable data, it's best to enforce a culture-invariant format (ideally ISO-8601) rather than using DateTime.Parse: specify the format you expect using DateTime.ParseExact or DateTime.TryParseExact. You still won't get information about which part is wrong, but it's at least easier to reason about. (That will also make it easier to know which calendar system is being used.)
If the data is from a user, ideally you'd present them with some form of calendar UI so they don't have to enter the text at all. At that point, only users who are entering the text directly would produce invalid input, and you may well view it as "okay" for them to get a blanket error message of "this value is invalid".
I don't believe .NET provides any indication of where the value was first seen to be invalid, even for a single value. Noda Time provides more information when parsing via the exception, but not in a machine-readable way. (The exception message provides diagnostic information, but that's probably not something to show the user.)
In short: you probably can't do exactly what you want to do here (without writing your own parser or validator) so it's best to try to work out alternative approaches. Writing a general purpose validator for this would be really hard.
If you only need to handle ISO-8601 dates, it's relatively straightforward:
*
*Split the input by dashes. If there aren't three dashes, it's invalid
*Parse each piece of the input as an integer. That can fail (on each piece separately)
*Validate that the year is one you're happy to handle
*Validate that the month is in the range 1-12
*Validate that the day is valid for the month (use DateTime.DaysInMonth to help with that)
Each part of that is reasonably straightforward, but what you do with that information will be specific to your application. We don't really have enough context to help write the code without making significant assumptions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52161683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL - reset cumulative value while keeping historical data I've been encharged, during my university internship, to create a web application to manage maintenace operations in the factory I work in. I'm an industrial engineer with just a little knowledge about database programming, so maybe this question will sound easy to you, I apologize.
That's the situation: the item is a mold, which needs ordinary maintenance after a number of operations (huge number, I'm talking about tiles manufacturing, and the maintenance frequency can be assumed as a mean value of once per year). I set up a database and the web application connected to it, and I created a view with the molds' list and the relative cumulative work, so that the department's responsible can have a fast perspective of the situation and see which molds need maintenance, and that works fine.
The problem is they "labeled" the molds, and I used that number as the row ID in the database. When the maintenance is performed the cumulative work needs to be resetted, but he wants to keep historical data about working operations.
Thus, what I need to do now, is "tell the system" when an item is manteined, then it has to reset the cumulative value while keeping historical data.
Values for the view I created are taken from 2 different tables: Molds and UnmountingOperations. In the latter there are information about which press the mold has been mounted on and the total work done during that operation. I thougt the solution is in the use of triggers, but I'd would like to ask:
What's the best practice to do so?
here you are the scripts created by SqlServer management studio.Sorry but record names are in Italian.
mold table:
CREATE TABLE [dbo].[Stampo](
[ID] [int] NOT NULL,
[Formato] [nchar](10) NOT NULL,
[n∞ uscite] [int] NULL,
[Spessore] [nchar](10) NULL,
[Descrizione] [nvarchar](max) NULL,
[Fornitore] [nvarchar](50) NULL,
CONSTRAINT [PK_Stampo] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
press table:
CREATE TABLE [dbo].[Pressa](
[Numero] [int] NOT NULL,
[Modello] [nchar](10) NULL,
CONSTRAINT [PK_Pressa] PRIMARY KEY CLUSTERED
(
[Numero] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
association mold-press for unmounting operations(mq_pressati) is the work amount driver,stands for square meters pressed:
CREATE TABLE [dbo].[SmontaggioStampi](
[NumeroPressa] [int] NOT NULL,
[IDStampo] [int] NOT NULL,
[DataSmontaggio] [datetime] NOT NULL,
[mq_pressati] [int] NOT NULL,
[Descrizione] [nvarchar](max) NULL,
CONSTRAINT [PK_Produzione presse] PRIMARY KEY CLUSTERED
(
[NumeroPressa] ASC,
[IDStampo] ASC,
[DataSmontaggio] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[SmontaggioStampi] WITH CHECK ADD CONSTRAINT [FK_SmontaggioStampi_Pressa] FOREIGN KEY([NumeroPressa])
REFERENCES [dbo].[Pressa] ([Numero])
GO
ALTER TABLE [dbo].[SmontaggioStampi] CHECK CONSTRAINT [FK_SmontaggioStampi_Pressa]
GO
ALTER TABLE [dbo].[SmontaggioStampi] WITH CHECK ADD CONSTRAINT [FK_SmontaggioStampi_Stampo] FOREIGN KEY([IDStampo])
REFERENCES [dbo].[Stampo] ([ID])
GO
ALTER TABLE [dbo].[SmontaggioStampi] CHECK CONSTRAINT [FK_SmontaggioStampi_Stampo]
GO
A: As for best practices, "avoid triggers like the plague" is the best advice I could give you.
What I've done in a similar situation is to add a column that indicates that a row is now archived. I used a datetime column called ArchivedDt. Normal queries exclude this column like:
where ArchivedDt is null
You can even do this in a view. The hierarchical data is still there, and a specific archive run can be easily undone.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8564304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to to duplicate a 4 partitions image on an eMMC from U-Boot? I have an image (more specifically a wic image for those who are familiar with Yocto framework) that contains a partition table along with its 4 partitions. It's size is bit less than 1GB.
In order to write this image to the eMMC:
*
*I first load it to RAM through TFTP
=> tftp 0x600000000 <image>.wic
*
*Then I write the image from RAM to the eMMC
=> mmc write 0x600000000 0x0 0x1FFFFF
*
*The image gets written correctly and I can list the 4 partitions. So far, so good.
=> mmc part
Partition Map for MMC device 1 -- Partition Type: EFI
Part Start LBA End LBA Name
Attributes
Type GUID
Partition GUID
1 0x00000800 0x0000681f "boot"
attrs: 0x0000000000000000
type: 0fc63daf-8483-4772-8e79-3d69d8477de4
guid: cd5df8ce-ded3-4cf4-b364-33d7a4b24953
2 0x00006820 0x000139e7 "first"
attrs: 0x0000000000000000
type: 0fc63daf-8483-4772-8e79-3d69d8477de4
guid: 3acc4557-2273-462a-a2bd-d130b3a5745d
3 0x00014000 0x000fefff "second"
attrs: 0x0000000000000000
type: 0fc63daf-8483-4772-8e79-3d69d8477de4
guid: efe25a87-e0ba-401e-8bf6-e81ae29cbc35
4 0x000ff000 0x001e9fff "third"
attrs: 0x0000000000000000
type: 0fc63daf-8483-4772-8e79-3d69d8477de4
guid: 150f9151-7710-42f4-b819-3b3bd506a2bf
Now I want to duplicate the image in the eMMC so that I end up with 8 partitions like so:
Part Start LBA End LBA Name
Attributes
Type GUID
Partition GUID
1 0x00000800 0x0000681f "boot"
attrs: 0x0000000000000000
type: 0fc63daf-8483-4772-8e79-3d69d8477de4
guid: cd5df8ce-ded3-4cf4-b364-33d7a4b24953
2 0x00006820 0x000139e7 "first"
attrs: 0x0000000000000000
type: 0fc63daf-8483-4772-8e79-3d69d8477de4
guid: 3acc4557-2273-462a-a2bd-d130b3a5745d
3 0x00014000 0x000fefff "second"
attrs: 0x0000000000000000
type: 0fc63daf-8483-4772-8e79-3d69d8477de4
guid: efe25a87-e0ba-401e-8bf6-e81ae29cbc35
4 0x000ff000 0x001e9fff "third"
attrs: 0x0000000000000000
type: 0fc63daf-8483-4772-8e79-3d69d8477de4
guid: 150f9151-7710-42f4-b819-3b3bd506a2bf
5 0x00000800 0x0000681f "boot"
attrs: 0x0000000000000000
type: 0fc63daf-8483-4772-8e79-3d69d8477de4
guid: cd5df8ce-ded3-4cf4-b364-33d7a4b24953
6 0x00006820 0x000139e7 "first"
attrs: 0x0000000000000000
type: 0fc63daf-8483-4772-8e79-3d69d8477de4
guid: 3acc4557-2273-462a-a2bd-d130b3a5745d
7 0x00014000 0x000fefff "second"
attrs: 0x0000000000000000
type: 0fc63daf-8483-4772-8e79-3d69d8477de4
guid: efe25a87-e0ba-401e-8bf6-e81ae29cbc35
8 0x000ff000 0x001e9fff "third"
attrs: 0x0000000000000000
type: 0fc63daf-8483-4772-8e79-3d69d8477de4
guid: 150f9151-7710-42f4-b819-3b3bd506a2bf
So I write again the same image to eMMC with an offset (to not override the existing one)
=> mmc write 0x600000000 0x200000 0x3FFFFF
MMC write: dev # 1, block # 2097152, count 4194303 ... 4194303 blocks written: OK
However, I don't get the 8 partitions I was expecting but only 4 partitions:
=> mmc rescan
=> mmc part
Partition Map for MMC device 1 -- Partition Type: EFI
Part Start LBA End LBA Name
Attributes
Type GUID
Partition GUID
1 0x00000800 0x0000681f "boot"
attrs: 0x0000000000000000
type: 0fc63daf-8483-4772-8e79-3d69d8477de4
guid: cd5df8ce-ded3-4cf4-b364-33d7a4b24953
2 0x00006820 0x000139e7 "first"
attrs: 0x0000000000000000
type: 0fc63daf-8483-4772-8e79-3d69d8477de4
guid: 3acc4557-2273-462a-a2bd-d130b3a5745d
3 0x00014000 0x000fefff "second"
attrs: 0x0000000000000000
type: 0fc63daf-8483-4772-8e79-3d69d8477de4
guid: efe25a87-e0ba-401e-8bf6-e81ae29cbc35
4 0x000ff000 0x001e9fff "third"
attrs: 0x0000000000000000
type: 0fc63daf-8483-4772-8e79-3d69d8477de4
guid: 150f9151-7710-42f4-b819-3b3bd506a2bf
A: When you write an image that contains one or more partitions, you also write the partition table, which is expected to be at some offset or your memory by u-boot (according to this post it must be 0x60000000). So if you write your image again somewhere else, u-boot will still refer to the partition table from your first writing operation, which itself contains the memory address of your first 4 partitions. Your second partition table is somewhere else on the disk, but u-boot doesn't know.
You can try to repair the partition table using the testdisk command line utility. It will scan the whole disk and hopefully it will find that there is 8 partitions in total, and create a new partition table at 0x60000000 that refers to all of them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59988521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JAXB adding unwanted tags in XML and removing desired ones I'm having the following structure of my classes:
@XmlRootElement(name = "storage")
@XmlType(propOrder = {
"entries"
})
@XmlAccessorType(XmlAccessType.FIELD)
public class A {
@XmlElement(name = "configuration")
private Set<ClassB> entries;
...
}
@XmlRootElement(name = "configuration")
@XmlType(propOrder = {
"name",
"entries"
})
@XmlAccessorType(XmlAccessType.FIELD)
public class B {
private String name;
@XmlElement(name = "configurationEntry")
private Set<ClassC> entries;
...
}
@XmlRootElement(name = "configurationEntry")
@XmlType(propOrder = {
"property1",
"property2",
"property3"
})
@XmlAccessorType(XmlAccessType.FIELD)
public class C {
private String property1;
private String property2;
private String property3;
...
}
When I use Jersey to make me an XML out of that, I get the following output when I try to access the root container (Class A). I have no idea why instead of tags are there tags.
<Bes>
<configuration>
<name>Name1</name>
<configurationEntry>
<property1>...</property1>
<property2>...</property2>
<property3>...</property2>
</configurationEntry>
<configurationEntry>
<property1>...</property1>
<property2>...</property2>
<property3>...</property2>
</configurationEntry>
</configuration>
<configuration>
<name>Name2</name>
<configurationEntry>
<property1>...</property1>
<property2>...</property2>
<property3>...</property2>
</configurationEntry>
<configurationEntry>
<property1>...</property1>
<property2>..</property2>
<property3>...</property2>
</configurationEntry>
</configuration>
</Bes>
When I try to access one of ClassB containers, I get the following. (Similiar issue as previous), instead of I get and there is no tag included.
<Aes>
<configurationEntry>
<property1>...</property1>
<property2>...</property2>
<property3>...</property2>
</configurationEntry>
<configurationEntry>
<property1>...</property1>
<property2>...</property2>
<property3>...</property2>
</configurationEntry>
<Aes>
The only one that works as expected is the one on the lowest level, Class C
<configurationEntry>
<property1>...</property1>
<property2>...</property2>
<property3>...</property2>
</configurationEntry>
Just to be clear, my desired outputs are as following:
When accessing storages (Class A) container:
<storage>
<configuration>
<name>Name1</name>
<entries>
<configurationEntry>
<property1>...</property1>
<property2>...</property2>
<property3>...</property2>
</configurationEntry>
<configurationEntry>
<property1>...</property1>
<property2>...</property2>
<property3>...</property2>
</configurationEntry>
</entries>
</configuration>
<configuration>
<name>Name2</name>
<entries>
<configurationEntry>
<property1>...</property1>
<property2>...</property2>
<property3>...</property2>
</configurationEntry>
<configurationEntry>
<property1>...</property1>
<property2>..</property2>
<property3>...</property2>
</configurationEntry>
</entries>
</configuration>
</storage>
When accessing 2nd level container, Class B, I would like the following:
<configuration>
<name>Name1</name>
<entries>
<configurationEntry>
<property1>...</property1>
<property2>...</property2>
<property3>...</property2>
</configurationEntry>
<configurationEntry>
<property1>...</property1>
<property2>...</property2>
<property3>...</property2>
</configurationEntry>
</entries>
</configuration>
Class C is OK with:
<configurationEntry>
<property1>...</property1>
<property2>...</property2>
<property3>...</property2>
</configurationEntry>
A: since i see tag <Bes> and <Aes> in class A and class B.. i feel that you have already defined root element.. i mean class A and Class B are subset of another class.. check this because an xml can have only one root element. if it is so then root element in class A and B is not valid. i don't see any issue with the xml defined in the class. for more information please visit http://java.dzone.com/articles/jaxb-and-root-elements
A: Never mind, I'm an idiot. -.-'
In my client code, for some reason I was retrieving Set<B> and Set<C> instead of A and B, respectively.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18571711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Drupal 7, Not sure how to theme my output correctly from query data I’ve been using Views to selectively returned nodes, but right now I want to return my nodes and use the Taxonomy term as a group header. I can't see anyway to get Views to do this for me, other then create multiple views on one page.
So I thought I'd right a module. I've written the SQL to return the correct nodes, but I can't work out how to send them to the themeing engine properly. I would like some advice on how to go about this, my tutorial book has examples of building a list as shown below.
foreach ($result as $row2) {
$items[] = l($row2->title,'node/'.$row2->nid.'/edit');
}
return array('#markup' => theme('item_list',array('items' => $items)));
now I want to return my nodes attached image file in Teaser mode, and the title of the node, plus (and I dont want to get ahead of myself) I may also want a couple of the addition node fields appended to the title. Should be easy right? I can't work it out at all.
I have wrangled my way around it (a bit) by using what I'm sure is a non drupal method which looks a bit like this, trouble is I can't get my output to work with ColorBox module, so I'm thinking if I can get official Teaser node data out it might work better, and i'd feel better knowing I was doing things in a drupaly way :)
foreach ($result as $row2) {
$items .= '<img title="'.$row2->title.' '.$row2->fielddata.'" alt="'.$row2->title.'" src="http://localhost/theme/sites/default/files/styles/thumbnail/public/field/image/'.$row2->filename .'"></a>';
$items .= '</div></div></div></div>';
}
return array('#markup' => $items);
Really appreciate any time you take to help me out and thanks in advance.
A: The following code should help. If you don't already have it, install the devel module, it gives you a wonderful function called dpm() which will print the contents of an array/object to the messages area.
// Get some nodes ids
$nids = db_query('SELECT nid FROM {node}')->fetchCol();
// Load up the node objects
$nodes = node_load_multiple($nids);
// This will print the node object out to the messages area so you can inspect it to find the specific fields you're looking for
dpm($nodes);
// I guess you'll want to do something like this:
$terms = array();
foreach ($nodes as $node) {
// Load the taxonomy term associated with this node. This will be found in a field as this is how taxonomy terms and nodes are related in D7
$term = taxonomy_term_load($node->field_vocab_name['und'][0]['tid']);
// Set up the array
if (!isset($terms[$term->name])) {
$terms[$term->name] = array();
}
// Create some markup for this node
$markup = '<h3>' . l($node->title . ' ' . $node->field_other_field['und'][0]['value'], "node/$node->nid") . '</h3>';
// Add an image
$image = theme('image', array('path' => $node->field_image['und'][0]['uri'], 'alt' => $node->title));
$markup.= $image;
// Add the markup for this node to this taxonomy group's list
$terms[$term->name][] = $markup;
}
// Make up the final page markup
$output = '';
foreach ($terms as $term_name => $node_list) {
$output .= '<h2>' . check_plain($term_name) . '</h2>';
$output .= theme('item_list', array('items' => $node_list));
}
return $output;
Hope that helps
A: You can get views to group the returned nodes by the taxonomy term for you. Assuming you are using a field view type, just add the taxonomy field and then where it says Format:Unformatted list | Settings click on Settings at the right hand side and choose your taxonomy field as the grouping field.
Note: if you are not using a field view type, or if you are not using unformatted list then the instructions will be a variation of the above.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7293391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Concat variable names in GitLab We use a Gitlab Project in a team. Each developer has his own Kubernetes cluster in the cloud and an own branch within GitLab. We use GitLab-CI to automatically build new containers and deploy them to our Kubernetes clusters.
At the moment we have a .gitlab-ci.yml looks something like this:
variables:
USERNAME: USERNAME
CI_K8S_PROJECT: ${USERNAME_CI_K8S_PROJECT}
REGISTRY_JSON_KEY_FILE: ${USERNAME_REGISTRY_JSON_KEY_FILE}
[...]
stages:
- build
- deploy
- remove
build-zeppelin:
stage: build
image: docker:latest
variables:
image_name: "zeppelin"
only:
- ${USERNAME}@Gitlab-Repo
tags:
- cloudrunner
script:
- docker login -u _json_key -p "${REGISTRY_JSON_KEY_FILE?}" https://eu.gcr.io
- image_name_fqdn="eu.gcr.io/${CI_K8S_PROJECT?}/${image_name?}:latest"
- docker build -t ${image_name_fqdn?} .
- docker push ${image_name_fqdn?}
- echo "Your new image is '${image_name_fqdn?}'. Have fun!"
[...]
So in the beginning we reference the important information by using a USERNAME-prefix. This works quite well, but is problematic, since we need to correct them after every pull request from another user.
So we search for a way to keep the gitlab-ci file the same to every developer while still referencing some gitlab-variables different for every developer.
Things we thought about, that don't seem to work:
Use multiple yml files and import them into each other => not supported.
Try to combine Gitlab Environment variables as Prefix:
CI_K8S_PROJECT: ${${GITLAB_USER_ID}_CI_K8S_PROJECT}
or
INDIVIDUAL_CI_K8S_PROJECT: ${GITLAB_USER_ID}_CI_K8S_PROJECT
CI_K8S_PROJECT: ${INDIVIDUAL_CI_K8S_PROJECT}
A: Solution from @nik will work only for bash. For sh will work:
before_script:
- variableName=...
- export wantedValue=$( eval echo \$$variableName )
A: We found a solution using indirect expansion (bash feature):
before_script:
- variableName=${GITLAB_USER_ID}_CI_K8S_PROJECT
- export wantedValue=${!variableName}
But we also recognised, that our setup was somehow stupid: It does not make sense to have multiple branches for each user and use prefixed variables, since this leads to problems such as the above and security concerns, since all variables are accessible to all users.
It is way easier if each user forks the root project and simply creates a merge request for new features. This way there is no renaming/prefixing of variables or branches necessary at all.
A: Something like this works (on 15.0.5-ee):
variables:
IMAGE_NAME: "test-$CI_PROJECT_NAME"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41723062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: How to navigate from Content Page to Shell in native forms? In my xamarin forms native 3.x project, currently I am navigating from content page to content page using below code
Android.Support.V4.App.Fragment mainPage = new ContentPage().CreateSupportFragment(this);
SupportFragmentManager
.BeginTransaction()
.Replace(Resource.Id.fragment_frame_layout, mainPage)
.Commit();
Ref:- https://learn.microsoft.com/en-us/xamarin/xamarin-forms/platform/native-forms
But this is not working in case of navigation from content page to Shell (Xamarin Forms 4.0.0).
Any help is appreciated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56807086",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: TypeError: unorderable types: int() > list() # Import Packages
import random
# Global Variables
perf_num = 500
species = [20]
temp_num = 0
length = 0
s = 0
# Main Program
for num in range(100):
r1 = int(random.random()*10)
r2 = int(random.random()*10)
species.append(r1)
length = len(species)
while s < length:
print(s)
if species[s-1] > species[s]:
temp_num = species[s-1] - r1
species[s-1] = temp_num
else:
temp_num = species[s] - r1
species[s] = temp_num
if s-1 < 5:
species[s-1] = []
s += 1
print(species)
Please don't explain in very complicated coding language as I just started learning Python from youtube. I tried making my own program and continue to get this error.
A: In the following line:
species[s-1] = []
you're assigning an empty list to a list of numbers, which results in something like:
20 [20, 2] 2
Then when you try to compare a number and a list:
if species[s-1] > species[s]:
you'll get that error:
TypeError: unorderable types: int() > list()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33586052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: javapos: how to set font size? I'm using javapos 1.15 to print on some epson thermal printer.
All basics feats works properly except one: I don't know how to change the font size (neither type, but that's ok).
According to documentation I could use some escaped caractere but none works. I can make text wider
and bolder but not smaller.
Any help here?
So basically
mPrinter.printNormal(POSPrinterConst.PTR_S_RECEIPT,ESC+"|bC hello"); //That's works
mPrinter.printNormal(POSPrinterConst.PTR_S_RECEIPT,ESC+"|50P hello"); //doesn't works
Thanks in advance
(fyi I print on epson TM-m30 that allow all text size (works fine with and AndroidEpsonSDK))
A: To change the font size (decrease), you need to change the RecLineChars property.
Only the values contained in the RecLineCharsList property can be specified for the RecLineChars property.
It cannot normally be specified in the middle of a PrintNormal print request string.
It may be possible to support it as a vendor-specific feature, but even in that case, it is only possible to change line units, and it is not possible to change only the middle of a line.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74849249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Pop up not showing outside when used with resize column by using PrimeNG Table I am using PrimeNG components in Angular 5 project. In my landing I have requirements like resize column and filters(pop up).
Pop up is showing correctly on table without using resize column class pResizableColumn. But when I use resize column class, pop up is limited to that header column only, rest of the part is hiding that because that pResizableColumn is using position relative.
I want to show pop up with column resize function, if any one know please help me out.
Below Images is the shows clearly.
Popu up showing proper
Pop up hiding when i use resize column
file.html
<div class="card-body" style="padding:0">
<div class="tab-content">
<div role="tabpanel" class="landing-table tab-pane active" id="all_cases">
<p-table (click)="hideFilterPopup()" (scroll)="hideFilterPopup()" #dt [columns]="cols" [value]="fetchCases" [totalRecords]="totalRecords"
[rows]="10" [(selection)]="selectedTableRow" [resizableColumns]="true" dataKey="ticketRef" (onRowSelect)="openDetailsAndView($event.data.ticketRef)"
[scrollable]="true" scrollHeight="350px" [style]="{width:'100%'}">
<ng-template pTemplate="colgroup" let-columns>
<colgroup>
<col style="width:30px">
<col style="width:150px">
<col *ngFor="let col of columns" style="width:150px">
</colgroup>
</ng-template>
<ng-template pTemplate="header" let-columns let-fetchCases>
<tr>
<th style="width:30px"></th>
<th id="case_reference" pResizableColumn>Ticket Reference
<span class="lnr lnr-funnel"></span>
<p-sortIcon [pSortableColumn]="fetchCases.ticketRef" [field]="fetchCases.ticketRef" ariaLabel="Activate to sort" ariaLabelDesc="Activate to sort in descending order"
ariaLabelAsc="Activate to sort in ascending order"></p-sortIcon>
</th>
<th *ngFor="let col of columns" pResizableColumn>
{{col.title}}
<p-sortIcon [pSortableColumn]="col.mapper" [field]="col.mapper" ariaLabel="Activate to sort" ariaLabelDesc="Activate to sort in descending order"
ariaLabelAsc="Activate to sort in ascending order"></p-sortIcon>
<div class="inlineFilters" [ngClass]="selectedFilter === col.title ? 'displayBlock' : 'displayNone'">
<div class="row marginZro">
<input class="col-sm-12 inlineInput" type="text" placeholder="Filter...">
<button class="col-sm-6 btn btn-stable">Search</button>
<button class="col-sm-6 btn btn-stable">Clear</button>
</div>
</div>
<span class="lnr lnr-funnel" (click)="opeenFilter(col.title)"></span>
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-fetchCases let-columns="columns">
<tr [pSelectableRow]="fetchCases">
<td style="width:30px">
<p-tableCheckbox [value]="fetchCases"></p-tableCheckbox>
</td>
<td class="caseRefLink ui-resizable-column" (click)="openHandlingTab(fetchCases)">
<div class="extentedNotes" title="{{fetchCases.ticketRef}}">{{fetchCases.ticketRef}}</div>
</td>
<td *ngFor="let col of columns" class="ui-resizable-column">
<div class="extentedNotes" title="{{fetchCases[col.field]}}" [ngClass]="{'timeLeftCol':(col.mapper == 'timeLeft'),
'rag-status-green':(col.mapper == 'timeLeft' && fetchCases['rag'] == 'Green'),
'rag-status-red':(col.mapper == 'timeLeft' && fetchCases['rag'] == 'Red'),
'rag-status-yellow':(col.mapper == 'timeLeft' && fetchCases['rag'] == 'Amber')}">{{fetchCases[col.mapper]}}</div>
</td>
</tr>
</ng-template>
</p-table>
</div>
</div>
<p-paginator *ngIf="totalRecords > 10" [rows]="10" [totalRecords]="totalRecords" [first]="first" (onPageChange)="loadTicketDetailsLazy($event)"></p-paginator>
</div>
component.ts
opeenFilter(selectedFilter){
event.stopPropagation()
if(this.selectedFilter == selectedFilter) {
this.selectedFilter = "";
}else {
this.selectedFilter = selectedFilter;
}
}
hideFilterPopup(){
if(this.selectedFilter != ""){
this.selectedFilter = "";
}
}
style.css
.inlineFilters {
position: absolute;
z-index: 2;
padding: 5px;
background: #EFEFEF;
border-radius: 5px;
max-width: 15%;
}
.inlineFilters .inlineInput {
margin-bottom: 5px;
}
.inlineFilters button {
padding: 0 !important;
}
A: Change the position of the inlineFilters class and replace absolute with fixed :
.inlineFilters {
position: fixed;
z-index: 2;
padding: 5px;
background: #EFEFEF;
border-radius: 5px;
width: 188px;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54033723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why does the 'like' count in my page rollback? I'm attempting to implement facebook "likes" and having a bit of trouble. The count keeps rolling back after a page refresh.
Steps to reproduce
*
*Navigate to http://bookmill.co.kr/books/9/quotations/79 (note: this page is in Korean)
*Click Like
*Notice the like count increments
*Refresh your browsers
Notice that after step #4 the count is rolled back? The like is posted to my Facebook wall. I'm not clear what's going wrong.
I attempted the same thing with: https://developers.facebook.com/docs/reference/plugins/like/
and it's rollback too.
Any idea what's going on? og tag is wrong? incorrect AppId?
A: facebooklikes: Well, developer.facebook has limitation. So you probably need to hire an expert in programming.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10479752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Integrating Symfony2 and Redis I am trying to integrate Redis with my Symfony API, I found this bundle : RedisBundle
I installed it and configured so that I can cache Doctrine like so config.yml:
# Doctrine Configuration
doctrine:
dbal:
driver: pdo_mysql
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
orm:
auto_generate_proxy_classes: "%kernel.debug%"
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
metadata_cache_driver: redis
# enable query caching
query_cache_driver: redis
snc_redis:
# configure predis as client
clients:
default:
type: predis
alias: default
dsn: redis://localhost
doctrine:
type: predis
alias: doctrine
dsn: redis://localhost
# configure doctrine caching
doctrine:
metadata_cache:
client: doctrine
entity_manager: default
document_manager: default
result_cache:
client: doctrine
entity_manager: [default]
query_cache:
client: doctrine
entity_manager: default
In my FetchBookRepository I am trying to use RedisCache there:
<?php
namespace BooksApi\BookBundle\Repositories;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Query\QueryException;
use Snc\RedisBundle\Doctrine\Cache\RedisCache;
use Predis\Client;
class FetchBookRepository
{
/**
* @var EntityManager
*/
public $em;
/**
* @param EntityManager $entityManager
*/
public function __construct(
EntityManager $entityManager
){
$this->em = $entityManager;
}
/**
* @param $id
* @return null|object
* @throws QueryException
*/
public function fetchBook($id)
{
$predis = new RedisCache();
$predis->setRedis(new Client);
$cache_lifetime= 3600;
try {
$book = $this->em->getRepository('BooksApiBookBundle:BooksEntity')
->find($id);
} catch (\Exception $ex) {
$this->em->close();
throw new QueryException('003', 502);
}
return $book;
}
}
I called the RedisCahce and Client classes but how do I now use it with my query..? I cant really find much on Google in regards to Symfony & Redis.
UPDATE:
When I use redis-cli and type in MONITOR i get this output:
1454337749.112055 [0 127.0.0.1:60435] "GET" "[BooksApi\\BookBundle\\Entity\\BooksEntity$CLASSMETADATA][1]"
A: Your Redis config looks OK.
You are using Redis to cache Meatada (Doctrine collected about Entities mappings, etc) and Query (DQL to SQL).
To use Redis as Cache for Results you must write custom Query and define that it is cacheable. Please follow the Doctrine manual http://docs.doctrine-project.org/en/latest/reference/caching.html#result-cache and this GitHub issue https://github.com/snc/SncRedisBundle/issues/77
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35130794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.