id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_2000
|
In other words, I am trying to build a custom Construct_plane_3 functor that, which may use exact arithmetic internally but rounds the result back to an inexact kernel plane coordinates.
In code:
#include <CGAL/Filtered_kernel.h>
#include <CGAL/Filtered_construction.h>
typedef CGAL::Filtered_kernel<CGAL::Simple_cartesian<float>> Kernel;
typedef CGAL::Filtered_construction<...> Custom_construct_plane_3;
// standard inexact construction
K::Point_3 point(0, 0, 0);
K::Plane_3 inexact_plane(point, point, point);
// custom inexact construction with filtered exact
// arithmetic for the intermediate computations
Custom_construct_plane_3 custom_construct_plane_3_object;
K::Plane_3 exact_plane = custom_construct_plane_3_object(point, point, point);
The template parameters ... is the missing piece of the puzzle that I can't figure out.
| |
doc_2001
|
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public OrchestratingClassTest {
@Inject
private OrchestratingClass oc;
@Test
public void test1() {
// I would like to mock classA's do1() method to send back "1"
// I would like to mock classB's do2() method to send back "2"
}
@Test
public void test2() {
// I would like to mock classA's do1() method to send back "100"
// I would like to mock classB's do2() method to send back "200"
}
static class SimpleConfig {
@Bean
public InterfaceA interfaceA() {
return new ClassA();
}
@Bean
public InterfaceB interfaceB() {
return new ClassB();
}
@Bean
public OrchestratingClass orchestratingClass() {
return new OrchestratingClass();
}
}
}
And the orchestratingClass itself is quite basic, but I've added some sample code to aid in visualization:
@Named
public OrchestratingClass {
@Inject
private InterfaceA interfaceA;
@Inject
private InterfaceB interfaceB;
public String orchestrate() {
return interfaceA.do1() + " " + interfaceB.do2();
}
}
Now I'm aware I could tweak my SimpleConfig class to have the mocked out versions of classA and classB, but then I'm locked into 1 particular mock and can't "re-mock" things when I move onto test2(). I'm convinced that playing around with the java config files for 1 single test class would not work if we're trying to inject different "flavors" of beans "per-test". Does anyone have any recommendation on what I can do to make sure I'm really testing this thoroughly without being invasive (ex: adding superfluous "setters" for the specific classes in the orchestratingClass to side-step the bean injection pain)? Essentially, I'm looking to "tamper" the applicationContext on a per-test basis for specific beans of interest (along with the necessary housekeeping that's required) by applying a variety of mocks.
A: Here's a simple example using Mockito:
public class OrchestratingClassTest {
@Mock
private ClassA mockA;
@Mock
private ClassB mockB;
@InjectMocks
private OrchestratingClass oc;
@Before
public void prepare() {
MockitoAnnotations.initMocks(this);
}
@Test
public void shouldConcatenate() {
when(mockA.do1()).thenReturn("1");
when(mockB.do2()).thenReturn("2");
assertEquals("1 2", oc.orchestrate());
}
}
The magic happens in the call to MockitoAnnotations.initMocks(this), which will create mock instances for the fields annotated with @Mock, then create a real instance of Orchestrating class and inject its fields, thanks to @InjectMocks.
Note that, even without this magic, you could make your class easily testable by just adding a constructor taking ClassA and ClassB as arguments to OrchestratingClass, and annotate that constructor with @Autowired instead of annotating the fields. So, in short, use constructor injection rather than field injection.
| |
doc_2002
|
this is a code that will explain what i want.
for ($i=0;$i<5;$i++) {
my $new$i=$i;
print "\$new$i is $new$i";
}
expecting variables to be named $new0,$new1,$new2,$new3,$new4,$new5.
and to have the abillty to use them in a loop like the print command is trying to do.
Thanks
A: You are asking a common question. The answer in 99.9% of cases is DON'T DO THAT.
The question is so common that it is in perlfaq7: How can I use a variable as a variable name?.
See "How do I use symbolic references in Perl?" for lots of discussion of the issues with symbolic references.
A: use a hash instead.
my %h=();
$new="test";
for ($i=0;$i<5;$i++) {
$h{"$new$i"}=$i;
}
while( my( $key, $value ) = each( %h ) ) {
print "$key,$value\n";
}
A: You want to use a hash or array instead. It allows a collection of data to remain together and will result in less pain down the line.
my %hash;
for my $i (0..4) {
$hash{$i} = $i;
print "\$hash{$i} is $hash{$i}\n";
}
A: Can you describe why exactly you need to do this.
Mark Jason Dominus has written why doing this is not such a good idea in Why it's stupid to "use a variable as a variable name"
part 1, part 2 and part 3.
If you think your need is an exception to cases described there, do let us know how and somebody here might help.
A: if you want to create variables like $newN you can use eval:
eval("\$new$i=$i");
(using hash probably would be better)
| |
doc_2003
|
A: you are directly requesting foo.com server to look into images/ directory for the file mymage.jpg. If the foo.com resolves to server1 and server1 has the images/myimage.jpg then it will be downloaded to your browser. Otherwise it wont. But instead if you have the image in a < img href=server1/images/myimage.jpg> tag which will always resolve to server1 and get the images displayed on the browser.
| |
doc_2004
|
However, my code outputs 1 only once.
Why does this happen? What is the error in my code?
(define (separate x)
(cond ((= 0 x) 0 )
((> 0 x) (separate (/ x 10))))
1)
Also, how do I add the actual digits of the number to a list? I am getting confused about lists in scheme.
A: Your code outputs 1 because in the last line that's what you return:
1)
It completely ignores the value of the cond expression (in Scheme only the value of the last expression is returned), and besides you're not doing anything with the result of the recursive call.
If you want to return a list then your base case changes - you must return an initial list and in the recursive step add a new element to that list using cons: that's the standard template for building an output list.
Also, notice that asking if (< x 10) is a better base case, if x happens to be 0 (an edge case) we must return a single-element list, not 0. Assuming a non-negative input, this should work:
(define (separate x)
(cond ((< x 10) '(1)) ; base case: return a single-element list
(else (cons 1 ; recursive step: add `1` to the output list
(separate (quotient x 10)))))) ; and advance recursion
The output is as expected:
(separate 123)
=> '(1 1 1)
| |
doc_2005
|
So this is my code:
import sys
def main(argv):
if len(argv) != 3:
print("Usage: python walk.py n l", file=sys.stderr)
else:
l = argv[2]
n = argv[1]
print("You ended up", simuleer(n,l), "positions from the starting point.")
if __name__ == "__main__":
main(sys.argv)
And this is my error
MacBook-Air-van-Luuk:documents luuk$ python walk.py 5 1 2
File "walk.py", line 21
print("Usage: python walk.py n l", file=sys.stderr)
^
I hope someone can explain me why this happens, thanks in advance!
A: You think you're using Python 3.x, but it's actually Python 2.x. On most systems python executable means Python 2.x.
print is not a function in Python 2.x, and can't be used like that, causing a syntax error.
You should look for some way to run Python 3.x instead.
For this particular case, you could also use from __future__ import print_function, which would make the code compatible with both versions.
A: There is a way to fix it
Just remove the "file=" from print method
e.g:
print("Usage: python walk.py n l", sys.stderr)
| |
doc_2006
|
I've come back to XCode 3, opened the same project, and there could find that setting. I set a value, and came back to XCode 4. The build setting has appeared.
It seems like the build settings are by default displayed only if they have a non-default value.
Is there any way to show all build settings, including the ones with default value?
| |
doc_2007
|
*
*Change to another tab.
*Switch orientation to landscape.
*Switch orientation back to portrait.
*Change back to TabOne.
Android App Description: I have a pretty bare-bones android app with three tabs that were built using google's TabLayout tutorial, we'll call them TabOne, TabTwo, and TabThree. Only TabOne has any content: a simple EditText view and Button that lets you add text to the body of TabOne. This is rigged up using a custom ArrayAdapter, which may have something to do with the strange behavior.
Note that this does not occur if I change orientation while remaining on TabOne. This is because I have implemented OnSaveInstanceState() and OnRestoreInstanceState() to save my list of data in my TabOneActivity class.
A: I had the same problem - the solution I found was to create a 'Dummy' tab and activity for the first tab in the TabLayout onCreate, then in onResume of the Tab Layout Activity, hide the 'Dummy' tab and select the 2nd tab programmatically. Not nice, but works as saves state of 2nd tab (i.e. 1st visible tab).
@Override
protected void onResume() {
super.onResume();
if (getTabHost() != null && getTabHost().getTabWidget()!= null) {
getTabHost().getTabWidget().getChildAt(0).setVisibility(View.GONE);
if (getTabHost().getCurrentTab() == 0) {
getTabHost().setCurrentTab(1);
}
}
}
A: You also need to restore your activity state in onCreate, as well as in OnRestoreInstanceState.
I should point out though that this technique is only for transient data, not for long term data storage. For that you should be saving the data to a database or to SharedPreferences in onPause, and then retrieving the data in onResume.
| |
doc_2008
|
d3.selectAll("input[name='test1']").on("click", function() {
// log 'this'
console.log("this will always be true", d3.select(this).property("checked"))
// log selected property yields different result on 'no'
var selectTest = d3.selectAll("input[name='test1']").property("checked")
console.log("This will be false on 'no': ", selectTest)
})
<html>
<head>
<meta charset ="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<input value="Yes" type="radio" name="test1">Yes
<input value="No" type="radio" name="test1">No
</body>
</html>
As you can see, the first method
console.log("this will always be true", d3.select(this).property("checked"))
Works as intended, but the other method gives you a false value when you select "No" for some reason I can't figure out, and I can't find any other examples of this.
A: The explanation is simple: your selection has two elements. However, the getter will get only the first one.
You can see this if you use an each:
d3.selectAll("input[name='test1']").on("click", function() {
d3.selectAll("input[name='test1']").each(function(_, i) {
console.log("radio " + (i + 1) + " is: " + d3.select(this).property("checked"))
})
})
<script src="https://d3js.org/d3.v4.min.js"></script>
<input value="Yes" type="radio" name="test1">Yes
<input value="No" type="radio" name="test1">No
Another way to show this even clearer is the following demo: I'm selecting all circles and using a getter to get the fill value. Despite the fact that there are two circles, blue and red, I'm getting only "blue" as result (the first one):
console.log(d3.selectAll("circle").attr("fill"))
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg>
<circle cx="100" cy="75" r="10" fill="blue"></circle>
<circle cx="200" cy="75" r="10" fill="red"></circle>
</svg>
A: You can add an id to differentiate the two:
<input value="Yes" type="radio" name="test1" id="test1">Yes
<input value="No" type="radio" name="test1" id="test2">No
then..
d3.select("input[id='test1']").on("click", function() {..})
| |
doc_2009
|
My code (mostly copy-pasted from their tutorial):
package test;
import weka.core.Instances;
import weka.experiment.InstanceQuery;
public class Test {
public static void main(String[] args) throws Exception{
InstanceQuery query = new InstanceQuery();
query.setUsername("root");
query.setPassword("");
query.setQuery("select id_activite from ACTIVITES limit 1");
Instances data = query.retrieveInstances();
System.out.println(data.toString());
}
}
I get this exception:
Trying to add database driver (JDBC): RmiJdbc.RJDriver - Error, not in CLASSPATH?
Trying to add database driver (JDBC): jdbc.idbDriver - Error, not in CLASSPATH?
Trying to add database driver (JDBC): com.mckoi.JDBCDriver - Error, not in CLASSPATH?
Trying to add database driver (JDBC): org.hsqldb.jdbcDriver - Error, not in CLASSPATH?
Exception in thread "main" java.sql.SQLException: No suitable driver found for jdbc:idb=experiments.prp
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at weka.experiment.DatabaseUtils.connectToDatabase(DatabaseUtils.java:523)
at weka.experiment.InstanceQuery.retrieveInstances(InstanceQuery.java:286)
at weka.experiment.InstanceQuery.retrieveInstances(InstanceQuery.java:271)
at seniorhome.Test.main(Test.java:17)
I have added both the weka.jar and weka-src.jar files separately through Build Path - Add External JARs and I've also added the mysql-connector-java-5.1.34-bin.jar file through the same method.
If I write another test class to connect to the database it works (so it's definitely not an issue with the server):
public class test {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// new com.mysql.jdbc.Driver();
Class.forName("com.mysql.jdbc.Driver").newInstance();
// conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdatabase?user=testuser&password=testpassword");
String connectionUrl = "jdbc:mysql://localhost:3306/b3l";
String connectionUser = "root";
String connectionPassword = "";
conn = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT id_activite FROM activites");
while (rs.next()) {
String id = rs.getString("id_activite");
System.out.println("ID: " + id);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try { if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (stmt != null) stmt.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
}
A: Between switching the files, adding them to the build path etc, I had accidentally added a file without modifying the database parameter in the DatabaseUtils.prop file.
| |
doc_2010
|
public class game1 extends Activity implements View.OnClickListener
{
static Button next;
static ImageView mainpic;
static RadioGroup radioGroup;
static RadioButton option1;
static RadioButton option2;
static RadioButton option3;
static int[] mapPics = new int[]{R.drawable.america, R.drawable.england, R.drawable.australia, R.drawable.poland, R.drawable.sweden, R.drawable.spain};
static String [] answers= new String[]{"Spain", "Poland", "Sweden", "America", "England", "Australia"};
static int [] correctAnswer= new int[]{2, 1};
static int score=0;
static int i=0;
static int a=0;
static int b=1;
static int c=2;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.game1);
next= (Button)findViewById(R.id.nextButton);
mainpic= (ImageView)findViewById(R.id.imageView);
mainpic.setImageResource(mapPics[i]);
next.setOnClickListener(this);
addListenerRadioGroup();
option1.setText(String.valueOf(answers[a]));
option2.setText(String.valueOf(answers[b]));
option3.setText(String.valueOf(answers[c]));
}//On Create
public void addListenerRadioGroup(){
option1= (RadioButton)findViewById(R.id.radioButton);
option2= (RadioButton)findViewById(R.id.radioButton2);
option3= (RadioButton)findViewById(R.id.radioButton3);
radioGroup = (RadioGroup)findViewById(R.id.radioGroupAnswers);
radioGroup.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
radioGroup.getCheckedRadioButtonId();
}
});
}
@Override
public void onClick(View v)
{
getSelectedAnswer();
i++;
a=a+3;
b=b+3;
c=c+3;
if(i >=1) {
Intent myIntent = new Intent(this, scores.class);
myIntent.putExtra("scores", score);
startActivity(myIntent);
}//if
mainpic.setImageResource(mapPics[i]);
option1.setText(String.valueOf(answers[a]));
option2.setText(String.valueOf(answers[b]));
option3.setText(String.valueOf(answers[c]));
mapPics[i]=null;
}//onClick
public void getSelectedAnswer() {
int index = radioGroup.indexOfChild(findViewById(radioGroup.getCheckedRadioButtonId()));
if (index==correctAnswer[i])
score++;
}//get selected answer
}//class
A: The error message you are getting is telling you exactly what the problem is.
You have declared mapPics as an array of int:
static int[] mapPics = new int[]{R.drawable.america, R.drawable.england, R.drawable.australia, R.drawable.poland, R.drawable.sweden, R.drawable.spain};
int is a primitive type, so you cannot set it to null. If you want a nullable type, use an Integer[] instead.
| |
doc_2011
|
I have a variable which i on printing gives me the above objects but i am not able to retrieve their values.
encryptedBytes = toSupportedArray(e.target.result);
where ,
console.log("to send for encryption - e.target.result : "+e.target.result);
gives me the result :
to send for encryption - e.target.result : [object ArrayBuffer]
and
console.log("encryptedBytes : "+encryptedBytes);
gives me the result :
encryptedBytes : [object Uint8Array]
but how can i retrieve the values of the same.
| |
doc_2012
|
(a) Web Server (b) File Server
In Web Server, i hosted a NET application under IIS. I have a asp.net file upload control and i want to upload file to File Server by using this control. but when i am trying it is showing
Network path is not found error. I am using below command.
FileUpload1.PostedFile.SaveAs(Server.MapPath("@"\server ip\Uploaded\"));
Thanks in Advance.
| |
doc_2013
|
<strings>
sentence
this is
this is a sentence
outlook
microsoft outlook
I want to search and remove the strings in this column that are a substring of another string.
My output should be
<strings>
this is a sentence
microsoft outlook
A: 1.Create test data:
tt <- c("sentence", "this is", "this is a sentence", "outlook", "microsoft outlook")
2.Suggested solution using base sapply and grepl:
We check for each element tt[i] in 'tt' if it appears anywhere in tt[-i] i.e. if it appears anywhere in the rest of the list. We then negate the result using ! and use the resulting vector from sapply as a logical index for the original list:
tt[sapply(seq_along(tt), function(x) !any(grepl(tt[x], tt[-x])))]
Returns:
> [1] "this is a sentence" "microsoft outlook"
| |
doc_2014
|
I have this in one of my cells.
from IPython.display import Javascript
from plotly.offline import get_plotlyjs
Javascript(get_plotlyjs())
I load data and run Plotly in another cell. The plots show in the notebook. I save the notebook and run this from the command line.
jupyter nbconvert notbook.ipynb --to slides --no-prompt --embed-images
For some notebooks, I'm seeing the plots embedded in the HTML. For other notebooks, they are missing.
When the notebooks are missing, I'm seeing this error:
python3.9/site-packages/nbconvert/filters/widgetsdatatypefilter.py:69: UserWarning: Your element with mimetype(s) dict_keys(['application/vnd.plotly.v1+json']) is not able to be represented.
warn("Your element with mimetype(s) {mimetypes}"
A: The error comes from running the notebook inside VS Code.
Running the notebook in jupyter lab and then saving it solves the problem. You can now run jupyter nbconvert and create an HTML presentation with plots.
| |
doc_2015
|
I'm also passing free as a custom delete function.
// a chunk of memory that will automatically be deleted
struct bytes : public std::shared_ptr<void> {
public:
unsigned int length;
bytes(std::nullptr_t) :
std::shared_ptr<void>(nullptr),
length(0) { }
bytes(int len) :
std::shared_ptr<void>(malloc(len), free),
length(len) { }
};
// a sample use case
bytes foo(int n){
if( condition1)
return nullptr;
bytes b(100);
// ....
fread(b.get(),1,100,file_pointer);
// ....
return b;
}
I'm just not sure if this code has hidden bugs or not ? (I'm new to c++11).
A: This is a truly terrible idea. It's just std::shared_ptr<std::vector<char>>, but with added awful like inheriting from a class with a non-virtual destructor.
You should really favour composing existing Standard classes rather than crapping around on your own. It is vastly superior.
| |
doc_2016
|
public Element GetAnyoneElseFromTheList(Element el)
{
Element returnElement = el;
Random rndElement = new Random();
if (this.ElementList.Count>2)
{
while (returnElement == el)
{
returnElement = this.ElementList[rndElement.Next(0,this.ElementList.Count)];
}
return returnElement;
}
else return null;
}
But that while loop has been bothering me for days and nights and I need to get some sleep. Any other good approaches to this? ie. something that returns in a fixed-number-of-steps ?
Edit : In my case, the list is guaranteed to contain the "el" Element to avoid, and the list contains no duplicates, but it would be interesting to see some more general cases aswell.
A: public Element GetAnyoneElseFromTheList(Element el)
{
if(this.ElementList.Count < 2) return null;
Random rndElement = new Random();
int random = rndElement.Next(0,this.ElementList.Count -1);
if(random >= this.ElementList.indexOf(el)) random += 1;
return this.ElementList[random];
}
Get a random number between 0 and the list length minus 2.
If that number is greater or equal to the index of your element add one to that number.
Return the element at the index of that number
Edit:
Someone mentioned in a comment which they then deleted that this doesn't work so well if you have duplicates.
In which case the best solution would actually be.
public Element GetAnyoneElseFromTheList(int elId)
{
if(elId >= this.ElementList.Count) throw new ArgumentException(...)
if(this.ElementList.Count < 2) return null;
Random rndElement = new Random();
int random = rndElement.Next(0,this.ElementList.Count -1);
if(random >= elId) random += 1;
return this.ElementList[random];
}
Edit 2: Another alternative for duplicate elements is you could use an optimised shuffle (random sort) operation on a cloned version of the list and then foreach through the list. The foreach would iterate up to the number of duplicate elements there were in the list. It all comes down to how optimised is your shuffle algorithm then.
A: public Element GetAnyoneElseFromTheList(Element el)
{
Random rndElement = new Random();
int index;
if (this.ElementList.Count>1)
{
index = rndElement.Next(0,this.ElementList.Count-1);
if (this.ElementList[index] == el)
return this.ElementList[this.ElementList.Count-1];
else
return this.ElementList[index];
}
else return null;
}
A: I have had to resolve a similar problem. Here's what I would do:
public Element GetAnyoneElseFromTheList(Element el)
{
// take a copy of your element list, ignoring the currently selected element
var temp = this.ElementList.Where(e => e != el).ToList();
// return a randomly selected element
return temp[new Random().Next(0, temp.Count)];
}
A: First count how many matching elements there are to avoid. Then pick a random number based on the remaining items and locate the picked item:
public Element GetAnyoneElseFromTheList(Element el) {
int cnt = this.ElementList.Count(e => e != el);
if (cnt < 1) return null;
Random rand = new Random();
int num = rand.Next(cnt);
index = 0;
while (num > 0) {
if (this.ElementList[index] != el) num--;
index++;
}
return this.ElementList[index];
}
A: public Element GetAnyoneElseFromTheList(Element el)
{
// first create a new list and populate it with all non-matching elements
var temp = this.ElementList.Where(i => i != el).ToList();
// if we have some matching elements then return one of them at random
if (temp.Count > 0) return temp[new Random().Next(0, temp.Count)];
// if there are no matching elements then take the appropriate action
// throw an exception, return null, return default(Element) etc
throw new Exception("No items found!");
}
If you're not using C#3 and/or .NET 3.5 then you'll need to do it slightly differently:
public Element GetAnyoneElseFromTheList(Element el)
{
// first create a new list and populate it with all non-matching elements
List<Element> temp = new List<Element>();
this.ElementList.ForEach(delegate(int i) { if (i != el) temp.Add(i); });
// if we have some matching elements then return one of them at random
if (temp.Count > 0) return temp[new Random().Next(0, temp.Count)];
// if there are no matching elements then take the appropriate action
// throw an exception, return null, return default(Element) etc
throw new Exception("No items found!");
}
A: How about:
public Element GetAnyoneElseFromTheList(Element el)
{
Random rand = new Random();
Element returnEle = ElementList[rand.Next(0, this.ElementList.Count];
return returnEle == el ? GetAnyoneElseFromTheList(Element el) : el;
}
Or in the case you do not like the possibility of a loop:
public Element GetAnyoneElseFromTheList(Element el)
{
Random rand = new Random();
List<Element> listwithoutElement = ElementList.Where(e=>e != el).ToList();
return listwithoutElement[rand.Next(listwithoutElement.Count)];
}
| |
doc_2017
|
If I fork a project in the GitHub website as a server side, and I clone the project into my local disc and do editing, deleting , adding files……, then:
1) If I "commit" all the changes, will these changes impact my forked project on the server side?
2) If I then "Push" all the changes after commit, will these changes impact my forked project on the server side?
3) If I then "Push" all the changes after commit, will this also send a pull request to the original project where I forked so that the original author knows I've sent some changes and maybe he/she can do merges?
4) If I click "Pull", and if the original has some changes (differing from mine), will my fork project be synchronized with the latest version from the original one?
5) If I click "Fetch", what will happen? what's the most difference between "Fetch" and "Pull" in VS2013?
A:
1) If I "commit" all the changes, will these changes impact my forked project on the server side?
No, when you do a commit locally this affects the local branch, not the remote one.
2) If I then "Push" all the changes after commit, will these changes impact my forked project on the server side?
Yes, pushing your branch is how you "sync" the local and remote versions.
3) If I then "Push" all the changes after commit, will this also send a pull request to the original project where I forked so that the original author knows I've sent some changes and maybe he/she can do merges?
Yes, my recollection is GitHub will do this.
4) If I click "Pull", and if the original has some changes (differing from mine), will my fork project be synchronized with the latest version from the original one?
What happens depends on your pull strategy. You could trigger a merge or a rebase. This will depend on your settings. In either case, yes you will "sync" with the remote branch.
5) If I click "Fetch", what will happen? what's the most difference between "Fetch" and "Pull" in VS2013?
Doing a fetch will tell Git to bring in the changes from the remote to your local Git system but it will not merge or rebase the changes in to any branch. Here is a simple equation for you to remember:
git pull = git fetch + git merge/rebase
| |
doc_2018
|
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
bool _isLoading = false;
@override
Widget build(BuildContext context) {
return Scaffold(
body: _isLoading
? Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: Center(child: CircularProgressIndicator()))
: SingleChildScrollView(
child: Column(
children: <Widget>[
CarouselSliderList(),
Banner1Slot(),
TopCategoriesList(),
HotProducts(),
TopCategoriesIconList(),
AllProduct(),
],
),
),
);
}
}
Example of 1 widget in SingleChildScrollView in HomeScreen.
class Banner1Slot extends StatefulWidget {
@override
_TopCategoriesListState createState() => _TopCategoriesListState();
}
class _TopCategoriesListState extends State<Banner1Slot> {
@override
Widget build(BuildContext context) {
return FutureBuilder<List<Banner1>>(
future: getBanner1(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? Banner1Image(
banner1: snapshot.data,
)
: Center(
child: CircularProgressIndicator(
backgroundColor: Colors.black26,
),
);
},
);
}
}
| |
doc_2019
|
// Find which elements are in the visible list that do not exist in the database
foreach(var tr in visibleList.Where((entry) =>
{
return fullList.Contains(entry);
}))
{
toRemove.Add(tr);
}
After tearing apart the code and running some tests, I narrowed the problem down to this:
// Returns true in DEBUG mode, but false in RELEASE mode
// (when entry does in fact equal fullList[0])
bool equalityResult = entry.Equals(fullList[0]);
fullList and toRemove are just basic C# List<Entry> objects, and visibleList is an ObservableCollection<Entry>.
Entry.Equals is not overloaded.
Why would this function behave differently between the two configurations? What can I do to fix this?
EDIT: The bulk of the Entry definition is:
public class Entry : INotifyPropertyChanged
{
public String Name { get; set; }
public String Machine { get; set; }
public Int32 Value { get; set; }
// Output values separated by a tab.
public override string ToString()
{
return String.Format("{0}\t{1}\t{2}", Name, Machine, Value);
}
public String ToCSVString()
{
return String.Format("{0},{1},{2}", Name, Machine, Value);
}
#region WPF Functionality
// Enable one-way binding in WPF
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string name)
{
PropertyChangedEventHandler h = PropertyChanged;
if (h != null)
{
h(this, new PropertyChangedEventArgs(name));
}
}
#endregion
// ...
}
EDIT: I implemented Entry.Equals, and that fixed the problem. Turns out I had some linking errors on top of everything that caused the Entry.Equals change in my code to be excluded from release builds. Having fixed that, and having implemented Equals, everything works like a charm. It makes me sad that I have to override that method though, seems like a bit too much work.
A: If you have not defined an Equals implementation in your Entry class, then, assuming it is a class and not a struct, Equals by default only performs a reference comparison. See What is the default behavior of Equals Method?
For instance:
public class AgeWrapper {
public int Age { get; set; }
public AgeWrapper( int age ) { this.Age = age; }
}
public void DoWork() {
AgeWrapper a = new AgeWrapper(21);
AgeWrapper b = new AgeWrapper(21);
AgeWrapper c = a;
Console.WriteLine( a.Equals(b) ); // prints false;
Console.WriteLine( a.Equals(c) ); // prints true;
}
The only way to make it work they way you expect, is to provide your own Equals comparison.
And since you will be doing that, you will need to override GetHashCode so that the two generate consistent values. The Amazing Jon Skeet can help you with the proper way to do that.
You do not want ReferenceEquals - you care about the values contained in your object, not where they happen to be stored in memory.
public class Entry : INotifyPropertyChanged
{
public String Name { get; set; }
public String Machine { get; set; }
public Int32 Value { get; set; }
public override bool Equals( object other )
{
Entry otherEntry = other as Entry;
if ( otherEntry == null ) { return false; }
return
otherEntry.Name.Equals( this.Name ) &&
otherEntry.Machine.Equals( this.Machine ) &&
otherEntry.Value.Equals( this.Value );
}
public override int GetHashCode()
{
// Thanks Jon Skeet!
unchecked // Overflow is fine, just wrap
{
int hash = (int) 2166136261;
hash = hash * 16777619 ^ this.Name.GetHashCode();
hash = hash * 16777619 ^ this.Machine.GetHashCode();
hash = hash * 16777619 ^ this.Value.GetHashCode();
return hash;
}
}
}
The above assumes that Name, Machine and Value define the identity of your object.
A: Equals method, unless overriden, does a reference comparison for classes, regardless of being in a debug or a release build.
So, your problem is that the list contains copies (clones) of your objects, probably after a roundtrip to the database through your favorite ORM. If you examine their properties inside the debugger, they will look identical, but as far as Equals is concerned, these are different instances.
It's hard to say where is the difference between your builds (is your ORM configured differently?), but you in fact probably want to create your own Equals override (or a custom IEqualityComparer implemenatation) to make sure that you can compare objects which were instantiated by the ORM.
| |
doc_2020
|
say();
function say()
{
alert("say");
}
The forward-declaration worked and popup "say"
On the opposite
say();
say = function()
{
alert("say");
}
did not work, although it also declared a function object
If we declare the function and redeclare that afterwards:
function say()
{
alert("speak");
}
say();
function say()
{
alert("say");
}
I got "say" instead of "speak". That's surprise!
OK. It seems that only the latest function declaration works. Then lets declare function object first and then a "regular" function:
say = function()
{
alert("speak");
}
say();
function say()
{
alert("say");
}
say();
Another surprise, it was "speak" followed by "speak". The "regular" function declaration did not work at all!
Is there an explanation of all of them? And, if the "regular" function declaration is really that "fragile" and can be easily override by the function object with same name, should I stay away from that?
Another question is: with only the function object format, does that forward-declaration become impossible? Is there any way to "simulate" that in Javascript?
A: Javascript works like this:
The document is parsed, and the function declarations are all taken taken into account immediately, before the execution of the actual statements occur. This explains your first example.
If you assign a function to a local variable, that is done during the execution, so you can't use the method in your second example.
What you experience is that if you declare a function twice, the last one will be used by the entire application. That's your third example.
These functions are made members of the window object, they are in effect declared globally. If you assign a local variable to a value of a function, then that local variable takes precedence over members in the window object. If javascript can't find a local variable, it searches up in scope to find it, the window object being the last resort. That's what happened in your last example, it has a variable say that is in a more specific scope than the global function say.
If you would redeclare say at runtime, i.e. swap the order of declarations in your last example, then you would see the two different alerts you'd expect:
say(); //speak, the global function
function say() {
alert('speak');
}
var say = function() {
alert('say');
}
say(); //say, the declared local variable
A: say();
function say()
{
alert("say");
}
Here the interpreter fetches the definition of say() when it is called, and executes it.
say();
say = function()
{
alert("say");
}
Here there is no definition of say() to fetch - instead you are assigning an anonymous function to a variable. The interpreter can't "find" this like it can find forward declarations.
function say()
{
alert("speak");
}
say();
function say()
{
alert("say");
}
Here say is defined and then redefined - the last definition wins out.
say = function()
{
alert("speak");
}
say();
function say()
{
alert("say");
}
say();
Here say is a variable pointing to an anonymous function (after the first statement is interpreted). This takes precedence over any function definition, the same as if you had placed the function definition before the assignment.
But if you had
say();
say = function()
{
alert("speak");
}
say();
function say()
{
alert("say");
}
Then you would get "say" followed by "speak".
A: You can expect your function definitions to be applied in order. Then all of your non-method lines of code will be executed in order, including the assignment of function objects. This explains each of your examples. It is an interesting issue though. You really can't assign a function object after attempting to call it, and expect it to work. However, a function definition that follows executable code will actually be applied first.
A: Its always good idea calling the function later, even though javascript works like that.
Most of the languages won't work that way, instead do this.
function say(){
alert("say");
}
say();
or
say = function(){
alert("say");
}
say();
or
(function(){
alert("say");
})();
| |
doc_2021
|
ValueWarning: A date index has been provided, but it has no associated
frequency information and so will be ignored when e.g. forecasting.
' ignored when e.g. forecasting.', ValueWarning)
So I found these two questions:
ValueWarning: No frequency information was provided, so inferred frequency MS will be used
https://stackoverflow.com/a/35860703
But when I tried to run the code in the example ( the 2nd link ) :
import pandas as pd
from statsmodels.tsa.arima_model import ARMA
df=pd.DataFrame({"val": pd.Series([1.1,1.7,8.4 ],
index=['2015-01-15 12:10:23','2015-02-15 12:10:23','2015-03-15 12:10:23'])})
print df
'''
val
2015-01-15 12:10:23 1.1
2015-02-15 12:10:23 1.7
2015-03-15 12:10:23 8.4
'''
print df.index
'''
Index([u'2015-01-15 12:10:23',u'2015-02-15 12:10:23',u'2015-03-15 12:10:23'], dtype='object')
'''
df.index = pd.DatetimeIndex(df.index)
print df.index
'''
DatetimeIndex(['2015-01-15 12:10:23', '2015-02-15 12:10:23',
'2015-03-15 12:10:23'],
dtype='datetime64[ns]', freq=None)
'''
model = ARMA(df["val"], (1,0))
print model
I also received the same ValueWarning, so I tried to change this line:
df.index = pd.DatetimeIndex(df.index)
to this:
df.index = pd.DatetimeIndex(df.index.values, freq=df.index.inferred_freq)
But then I get this error:
AttributeError: 'Index' object has no attribute 'inferred_freq'
A: You current index, as printed, is string index. You should convert it to DatetimeIndex and pass a frequency by to_period:
df.index = pd.DatetimeIndex(df.index).to_period('M')
A: If your time series is irregular, you might end up receiving an error like this.
"ValueError: Inferred frequency None from passed values does not
conform to passed frequency M"
Depending on what you want to do with you data, you could try different things.
What worked for me was pandas resampling, better explained here.
| |
doc_2022
|
#include "stdafx.h"
#include "shoes_sharedlibrary.h"
#include <iostream>
#include <string.h>
#include "mex.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
/* Call the MCR and library initialization functions */
if( !mclInitializeApplication(NULL,0) )
{
exit(1);
}
if (!shoes_sharedlibraryInitialize())
{
exit(1);
}
mwArray img= "C:/Users/aadbi.a/Desktop/dressimages/T1k5aHXjNqXXc4MOI3_050416.jpg";
double wt1 = 0;
mwArray C(wt1);
double wt2=0;
mwArray F(wt2);
double wt3=0;
mwArray T(wt3);
double wt4=1;
mwArray S(wt4);
test_shoes(img,C,F,T,S);
shoes_sharedlibraryTerminate();
mclTerminateApplication();
return 0;
}
The C,F,T,S are value between 0 and 1. How can I pass the input arguments as it is in _TCHAR*?How can I convert the _TCHAR* into decimal or double and again converting that into mwArray to pass into test_shoes. The test_shoes only takes mwArray as input.
The test_shoes function definition is:
void MW_CALL_CONV test_shoes(const mwArray& img_path, const mwArray& Wcoarse_colors,
const mwArray& Wfine_colors, const mwArray& Wtexture, const
mwArray& Wshape)
{
mclcppMlfFeval(_mcr_inst, "test_shoes", 0, 0, 5, &img_path, &Wcoarse_colors, &Wfine_colors, &Wtexture, &Wshape);
}
A: You can convert the command line string arguments to double using the atof() function from stdlib.h. As I see you are using the TCHAR equivalents, there is a macro that wraps the correct call for UNICODE and ANSI builds, so you can do something like this (assuming your command line arguments are in the correct order)
#include "stdafx.h"
#include "shoes_sharedlibrary.h"
#include <iostream>
#include <string.h>
#include "mex.h"
#include <stdlib.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
// ... initial code
// convert command line arguments to doubles ...
double wt1 = _tstof(argv[1]);
mwArray C(wt1);
double wt2 = _tstof(argv[2]);
mwArray F(wt2);
double wt3 = _tstof(argv[3]);
mwArray T(wt3);
// ... and so on ....
}
Note that argv[0] will contain the name of your program as specified on the command line, so the arguments begin at argv[1]. Then your command line can be something like:
yourprog.exe 0.123 0.246 0.567 etc.
| |
doc_2023
|
Here is the last solution I tried:
HttpClientBuilder builder = HttpClients.custom();
System.setProperty("javax.net.ssl.trustStore", "NONE");
System.setProperty("jsse.enableSNIExtension", "false");
System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");
SSLConnectionSocketFactory sslsf = null;
try {
SSLContextBuilder sslbuilder = new SSLContextBuilder();
sslbuilder.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
});
sslsf = new SSLConnectionSocketFactory(sslbuilder.build(), new NoopHostnameVerifier());
} catch (Exception e) {
e.printStackTrace();
}
builder.setSSLSocketFactory(sslsf);
CloseableHttpClient httpclient = builder.build();
HttpGet httpget = new HttpGet("https://ru-moto.com/");
HttpResponse response = httpclient.execute(httpget);
InputStream instream = response.getEntity().getContent();
... // Here goes InputStream reading etc.
I got this exception:
javax.net.ssl.SSLProtocolException: no more data allowed for version 1 certificate
at sun.security.ssl.HandshakeMessage$CertificateMsg.<init>(HandshakeMessage.java:452)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1026)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:961)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1072)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1385)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1413)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1397)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:396)
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.upgrade(DefaultHttpClientConnectionOperator.java:193)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.upgrade(PoolingHttpClientConnectionManager.java:389)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:416)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:237)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:185)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:111)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)
...
Caused by: java.security.cert.CertificateParsingException: no more data allowed for version 1 certificate
at sun.security.x509.X509CertInfo.parse(X509CertInfo.java:672)
at sun.security.x509.X509CertInfo.<init>(X509CertInfo.java:167)
at sun.security.x509.X509CertImpl.parse(X509CertImpl.java:1804)
at sun.security.x509.X509CertImpl.<init>(X509CertImpl.java:195)
at sun.security.provider.X509Factory.engineGenerateCertificate(X509Factory.java:102)
at java.security.cert.CertificateFactory.generateCertificate(CertificateFactory.java:339)
at sun.security.ssl.HandshakeMessage$CertificateMsg.<init>(HandshakeMessage.java:449)
... 26 more
I tried many solutions:
http://www.nakov.com/blog/2009/07/16/disable-certificate-validation-in-java-ssl-connections/
https://gist.github.com/wellsb1/bb01c625886633b29eec9444821d7f56
https://stackoverflow.com/a/44019472
https://stackoverflow.com/a/43613265
https://stackoverflow.com/a/45768724
https://memorynotfound.com/ignore-certificate-errors-apache-httpclient/
https://stackoverflow.com/a/5297100
Nothing works, I always get the same exception.
| |
doc_2024
|
iterate3 f x = x:map f (iterate3 f x)
iterate3 (2*) 1
= 1:map (2*) (iterate3 (2*) 1)
= 1:2:map (2*) (map (2*) (iterate3 (2*) 1))
= 1:2:4:map (2*) (map (2*) (map (2*) (iterate3 (2*) 1)))
The other, which uses where, evaluates in linear time:
iterate2 f x = xs where xs = x:map f xs
iterate2 (2*) 1
xs where xs = 1:map (2*) xs
= 1:ys where ys = map (2*) (1:ys)
= 1:2:zs where zs = map (2*) (2:zs)
= 1:2:4:ts where ts = map (2*) (4:ts)
I don't quite understand this evaluation. How is x getting reassigned to each successive list element, instead of 1 (as in the first version)?
A: The important detail is that xs in iterate2 is defined in terms of itself, creating a circular structure.
(This is sometimes called "tying the knot".)
Visualizing it as a graph, the evaluation goes something like this (warning: ASCII art).
xs where xs = 1 : map (2*) xs:
: <----------+
/ \ | applies to
1 map (2*) --+
-->
:
/ \
1 : <--------+
/ \ | applies to
2 map (2*) --+
-->
:
/ \
1 :
/ \
2 : <---------+
/ \ | applies to
4 map (2*) --+
And so on.
A: Let's unroll the recursion in iterate2:
xs = x : map f xs
= x : map f (x : map f xs) -- Inline xs
= x : (f x) : map f (map f xs) -- Definition of map
= x : (f x) : map f (map f (x : map f xs)) -- Inline xs
= x : (f x) : map f ((f x) : map f (map f xs)) -- Definition of map
= x : (f x) : (f (f x)) : map f (map f (map f xs))) -- Definition of map
...
So you can see that the list returned by iterate2 f x has x as the first element, f x as the second, and so on.
| |
doc_2025
|
(Code shown is a much simplified version to highlight the issue encountered.)
If I launch the dialog as follows everything works fine.
var dialog = new MyDialog(new MyDialogViewModel());
new Application().Run(dialog);
If I open the dialog as follows then the escape key binding won't work but the button still does.
new MyDialog(new MyDialogViewModel()).Show();
MyDialog.xaml
<Window x:Class="MyDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Topmost="True"
Visibility="{Binding Visibility}">
<Window.InputBindings>
<KeyBinding Key="Escape" Command="{Binding HideCommand}" />
</Window.InputBindings>
<Button Command="{Binding HideCommand}">Hide</Button>
</Window>
MyDialog.xaml.cs
public partial class MyDialog : Window
{
public MyDialog(MyDialogViewModel vm)
{
DataContext = vm;
InitializeComponent();
}
}
MyDialogViewModel.cs
public class MyDialogViewModel : INotifyPropertyChanged
{
private Visibility _visibility = Visibility.Visible;
public MyDialogViewModel()
{
HideCommand = new DelegateCommand(Hide);
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public DelegateCommand HideCommand { get; private set; }
public Visibility Visibility
{
get
{
return _visibility;
}
set
{
_visibility = value;
PropertyChanged();
}
}
private void Hide()
{
Visibility = Visibility.Hidden;
}
}
Using Snoop I can see the following binding error, this is present when launched either way.
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=HideCommand; DataItem=null; target element is 'KeyBinding' (HashCode=30871361); target property is 'Command' (type 'ICommand')
I'm trying to understand why the escape key works in one scenario and not the other. Any ideas?
A: A few thoughts/questions:
*
*In the version that does not work, where are you opening the dialog? From the main window that is started by the application?
*In your MyDialog constructor, I'm assuming you have a call to InitializeComponent. Is that correct? Otherwise, it would not properly initialize from the XAML file.
*Is there a reason you cannot use the Button.IsCancel property?
EDIT:
If you are loading a WPF Window from a WinForms application you need to do some additional work. This blog explains this and includes the following example:
using System;
using System.Windows.Forms;
using System.Windows.Forms.Integration;
....
var wpfwindow = new WPFWindow.Window1();
ElementHost.EnableModelessKeyboardInterop(wpfwindow);
wpfwindow.Show();
A: I wonder if it's a timing issue with the KeyBinding. I just checked one of my projects that has tons of KeyBinding and the commands are all static so there would be no issue. I wonder if perhaps the KeyBinding command binding is occurring before the VM is updated and the binding is never being updated.
UPDATE: Check this out, it may be the answer:
http://joyfulwpf.blogspot.com/2009/05/mvvm-commandreference-and-keybinding.html
and this:
Keybinding a RelayCommand
| |
doc_2026
|
select @CountResult = count(*) from ViewDefinition where DefinitionID = @ObjektID and
(case
when IsGepa=0 and Gepa is not null then @CountResult
when NotGepa=0 and GepaListeID is not null then @CountResult
end )
select @CountResult
A: Try this:
select @CountResult = SUM
(
CASE when (IsGepa=0 and Gepa is not null ) OR (NotGepa=0 and GepaListeID is not null) THEN 1 ELSE 0 END
)
from ViewDefinition
where DefinitionID = @ObjektID
A: Your CASE conditions need to go into the WHERE:
select @CountResult = count(*)
from ViewDefinition
where DefinitionID = @ObjektID and
((IsGepa=0 and Gepa is not null) or
(NotGepa=0 and GepaListeID is not null)
)
select @CountResult
| |
doc_2027
|
$current_date_time = new DateTime("now", new DateTimeZone("Asia/Tehran"));
$user_current_time = $current_date_time->format("H:i:s");
$start_limit_time = date("H:i:s",strtotime('2015-09-15 14:57:31'));
$finish_limit_time = date('H:i:s', strtotime($start_limit_time) + (60 * 60 * 1));
$date1 = DateTime::createFromFormat('H:i:s', $user_current_time);
$date2 = DateTime::createFromFormat('H:i:s', $start_limit_time);
$date3 = DateTime::createFromFormat('H:i:s', $finish_limit_time);
if ($date1 > $date2 && $date1 < $date3)
{
echo 'here';
}
this code is not correct and i can not fix that,
A: You can try this, it shows the difference in minutes:
$current_date_time = new DateTime("now", new DateTimeZone("Asia/Tehran"));
$user_current_time = $current_date_time->format("H:i:s");
$start_limit_time = date("H:i:s",strtotime('2015-09-15 14:57:31'));
$finish_limit_time = date('H:i:s', strtotime($start_limit_time) + (60 * 60 * 1));
$date1 = DateTime::createFromFormat('H:i:s', $user_current_time);
$date2 = DateTime::createFromFormat('H:i:s', $start_limit_time);
$date3 = DateTime::createFromFormat('H:i:s', $finish_limit_time);
if ($date1 > $date2 && $date1 < $date3)
{
$tryAgainIn = $date3->diff( $date1 );
// just minutes
echo "try again in ".$tryAgainIn->format( "%i minutes" );
// or hours and minutes
$hours = $tryAgainIn->format('%h');
$minutes = $tryAgainIn->format('%i');
echo "try again in $hours hours and $minutes minutes";
}
For more information take a look at: DateTime::diff
A: At first you should avoid operating with strings format, as they should only be used IMHO to printing and retrieving data from outside. Use only timestamp or OOP methods.
I believe, that this is something you are looking for:
$startTime = new DateTime('2015-09-15 14:57:31');
$endTime = clone $startTime;
$endTime->modify('+1 hour');
if ($startTime->getTimestamp() <= time() && time() < $endTime->getTimestamp()) {
echo 'here';
}
I wonder why you need to use H:i:s format. Can you give some bigger picture?
Edit: Try this, as prior to now I did not fully understand what you want to do ;)
$origin = new DateTime('2015-09-15 14:57:31');
$startTime = new DateTime('today '.$origin->format('H:i:s'));
$endTime = clone $startTime;
$endTime->modify('+1 hour');
if ($startTime->getTimestamp() <= time() && time() < $endTime->getTimestamp()) {
echo 'here';
}
| |
doc_2028
|
It installed successfully. But later I tired to share the APK from my mobile to other mobiles. But none of them are able to Install it.
However, if I build the APK and share the app-debug.apk to other mobiles. It Installs successfully.
I can't build APK and share app-debug.apk it everyone.
I usually deploy it in my mobile, share APK(which used to work before)
Can anyone please help
Please excuse typos, I have typed from mobile.
A: There might be a signing issue. Is your app signed? The default signing is the debug signing. When you just build and deploy or run it on a connected device, it is signed by default as a debug sign.
If it is not uniquely signed, then running or installing on other devices might not be possible. Look at the app signing instruction and guide by Google, here, if you wish to distribute your app on other devices.
Another problem might be in the security authorization of other devices. Your device on which you are building has the developer options turned on. To run and install unsigned apps you'll need to activate the developer options in the device you want to run it on. Look at this link about Developer Options and how to turn it on.
A: by default the Android Studio packages just the needed files and installs the app in your mobile. If you share to other mobiles, the app will not install in few devices due to a few reasons like OS version, files mismatch, SHA keys mismatch, etc.
However, if you build the APK and share, the APK is equipped to be installed in any device starting from the minimum SDK version to the target SDK version.
| |
doc_2029
|
sorry im new to object pascal
A: Simply add the second form, and then in the button handler do a
secondform.showmodal;
Don't forget to add the unit where "Secondform" is in to the uses clauses of the first unit.
A: At the FreePascal Wiki you will find a tutorial on how to use Lazarus. You can read it in several different languages.
You can also see this Developing a GUI Application tutorial.
| |
doc_2030
|
|------------| |------------|
|Title 1 | |Title 1 | Widget1
|------------| |------------|
|QTextEdit1 | Widget 1 |Title 2 |
| | |------------|
|------------|Which, by clicking on the title, contract: |QTextEdit2 | Widget2
|------------| | |
|Title 2 | |------------|
|------------|
|QTextEdit1 |
| | Widget 2
|------------|
Problem is, so far ive only be able to achieve the following: (After clicking on title 1)
|------------|
|Title 1 |
|------------|
| |
| |
|------------|
|------------|
|Title 2 |
|------------|
|QTextEdit1 |
| |
|------------|
That is, i am able to make the QtextEdit of my first widget disappear, keeping the title height intact (this is important), but the second widget does not replace the space left by the first QTextEdit. It is as if the QtextEdit is still there, and the second widget cannot occupy that space.
¿Does anyone know how to solve this? I have the feeling its not that complicated but Ive looked around and I havent been able to solve it. I have tried setting a maxmimum height for the widget1 when I contract it, but that doesnt seem to work. Oh, and each widget contains a QVBoxLayout, where title and QtextEdit are inserted, and then the list of widgets is another QVBoxLayout, where all the widgets are inserted.
EDITED: Added some source code by request
Constructor:
mainLayout = new QVBoxLayout;
QHBoxLayout *headerLayout = new QHBoxLayout;
title = new QLabel("My title!!");
m_arrowLabel->setPixmap(m_arrowDown);
m_activated = true;
title->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
title->setMaximumHeight(16);
headerLayout->addWidget(title, 0, Qt::AlignLeft);
headerLayout->setContentsMargins(0,0,0,0);
textEdit = new QTextEdit;
textEdit->setReadOnly(true);
textEdit->setText("My text!!!");
textEdit->setMaximumHeight(textEdit->document()->size().height() + 50);
mainLayout->addLayout(headerLayout);
mainLayout->addWidget(textEdit);
mainLayout->setContentsMargins(QMargins(0,0,0,0));
this->setLayout(mainLayout);
Mouse Press event:
event->accept();
if (event->buttons() & Qt::LeftButton)
{
if (m_activated)
{
m_activated = false;
textEdit->setVisible(false);
}else
{
m_activated = true;
textEdit->setVisible(true);
}
}
On my window where I populate it with widgets:
m_mainLayout = QVector<QVBoxLayout *> (10);
for (int i=0; i<m_mainLayout.size(); i++)
{
myWidget[i] = new myWidget;
myWidget[i]->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
m_mainLayout->addWidget(myWidget[i]);
}
A: You're setting a fixed vertical size policy for your widgets. This is why when you hide the text edit inside them, they won't shrink. Use QWidget::setMaximumHeight if you want to limit the height of the widgets.
Here is a small working example:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QLayout>
#include <QLabel>
#include <QPushButton>
#include <QTextEdit>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
centralWidget()->setLayout(new QVBoxLayout);
centralWidget()->layout()->setAlignment(Qt::AlignTop);
for(int i = 0; i < 10; i++)
{
QWidget *widget = new QWidget;
widget->setMaximumHeight(200);
widget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Maximum);
QVBoxLayout *w_layout = new QVBoxLayout;
widget->setLayout(w_layout);
QHBoxLayout *top_layout = new QHBoxLayout;
top_layout->addWidget(new QLabel("Title"));
QPushButton *toggle_button = new QPushButton("Toggle");
top_layout->addWidget(toggle_button);
toggle_button->setCheckable(true);
QTextEdit *text_edit = new QTextEdit;
connect(toggle_button, SIGNAL(clicked(bool)), text_edit, SLOT(setHidden(bool)));
w_layout->addLayout(top_layout);
w_layout->addWidget(text_edit);
centralWidget()->layout()->addWidget(widget);
}
}
MainWindow::~MainWindow()
{
delete ui;
}
Clicking the buttons will either hide or show the text edits of the widgets. The widget will shrink if the text edit is hidden and expand if it is shown.
| |
doc_2031
|
(defun garde-o (liste)
(cond
((not liste) 0)
((equal (car liste) 'o) (+ 1 (garde-o(cdr liste))) )
((garde-o(cdr liste)) )
)
)
Instead of returning the number of occurence I would like to return the given list with only the 'o.
Like that:
(garde-o '(a o x & w o o))
should return => (o o o)
I don't want to use pop,push,set... just I can't find of to return this.
A: Notice that given the number of occurrences, for example 10, you can simply do
(make-list 10 :initial-element 'o)
or equivalently
(loop repeat 10 collect 'o)
To count the 'o in your list, you can do
(count 'o '(a b c o p o a z))
Thus, a simple solution for your function would be
(defun garde-o (a)
(make-list (count 'o a) :initial-element 'o))
However, you can do this recursively too
(defun garde-o (a)
(cond ((null a) nil)
((eq (car a) 'o) (cons 'o (garde-o (cdr a))))
(t (garde-o (cdr a)))))
and non-recursively
(defun garde-o (a)
(loop for x in a when (eq x 'o) collect x))
| |
doc_2032
|
A: You can use <input type=...> as mentioned in the input specification.
A: There are a few different ways to accomplish this but one of them would be capturing the keypress itself and returning false if the input is not a number.
Also if I understand you correctly, to add a default value of "0", just define it in the input directly like value="0", or you could use a placeholder="0" if that's what you're looking for.
<input type="number" value="0" onkeydown="javascript: return event.keyCode === 8 || event.keyCode === 46 ? true : !isNaN(Number(event.key))" />
A: While this wouldn't enforce the user input to numbers only, you may want to consider using the pattern attribute to leverage some built-in behaviour. If you type non-numeric characters, the text colour will turn red:
input:invalid {
color: red;
}
<input type="text" pattern="[0-9]+"/>
Then we can start looking at the constraint validation API:
The Constraint Validation API enables checking values that users have entered into form controls, before submitting the values to the server.
If you type non-numeric characters and try to submit the form, you should see a built-in tooltip displaying a custom error message:
const input = document.querySelector('input');
input.addEventListener('invalid', () => {
if (input.validity.patternMismatch) {
input.setCustomValidity('Numbers only please!!');
}
});
input:invalid {
color: red;
}
<form>
<input type="text" pattern="[0-9]+"/>
<button type="submit">submit</button>
</form>
A:
$("#but").click(function(){
let inp_val = $("#txt").val();
if(isNaN(inp_val)){
alert("Just enter a number.");
$("#txt").val("");
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="txt">
<input type="button" value="CLICK" id="but">
| |
doc_2033
|
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string line;
fstream file;
file.open("taches.txt", ios::in);
return 0;
}
Problem is Eclipse is giving Method 'open' could not be resolved but since I included fstreams and iostream I am baffle. Can soemone point out what I am doing wrong?
| |
doc_2034
|
ProcessList.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,nameList ));
ProcessList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
for example like ProcessList.(check these items...)
Just like we get items 'checked' by user from: ProcessList.getItemAtPosition(position);
Pls also suggest me anyother way..
A: Call setItemChecked() on the ListView for each position to be checked.
Also, please grow up. Badgering people on Twitter minutes after you post a question on StackOverflow is infantile. This is a volunteer resource -- if you require answers to questions in under an hour, hire a consultant.
| |
doc_2035
|
http://jsfiddle.net/4bwsY/
<body>
<ul id="sortable1" class="connectedSortable">
<li class="ui-state-default">Item 1</li>
<li class="ui-state-default">Item 2</li>
<li class="ui-state-default">Item 3</li>
<li class="ui-state-default">Item 4</li>
<li class="ui-state-default">Item 5</li>
</ul>
<ul id="sortable2" class="connectedSortable">
<li id="balls" class="ui-state-highlight">balls</li>
<li class="ui-state-highlight">Item 2</li>
<li class="ui-state-highlight">Item 3</li>
<li class="ui-state-highlight">Item 4</li>
<li class="ui-state-highlight">Item 5</li>
</ul>
</body>
$(function() {
$( "#sortable1, #sortable2" ).sortable({
connectWith: ".connectedSortable",
receive: function( event, ui ) { alert($(this).attr('id') +' - '+ ui.draggable); },
stop: function( event, ui ) { alert($(this).ui.draggable.attr('id')); }
}).disableSelection();
});
A: Use ui.item (see http://api.jqueryui.com/sortable/#event-receive):
$(function() {
$( "#sortable1, #sortable2" ).sortable({
connectWith: ".connectedSortable",
receive: function( event, ui ) { alert($(this).attr('id') +' - '+ ui.item); },
stop: function( event, ui ) { alert($(ui.item).attr('id')); }
}).disableSelection();
});
Working example: http://jsfiddle.net/4bwsY/2/
| |
doc_2036
|
So the high level view, for example, is:
"confluence-api"<--"spring-boot-api"<--"react-app"<---"user"
andthe JSON response is:
{
"results": [
{
"id": "xxxxx",
"type": "xxxx",
"status": "xxxx",
"title": "file",
"restrictions": {},
"_links": {
"webui": "xxx",
"tinyui": "",
"self": "xxx",
},
"_expandable": {
"container": "",
"body": "",
"version": "",
"space": "xxx"
}
},
],
"start": 0,
"limit": 25,
"size": 9,
"_links": {
"self": "",
"base": "",
"context": ""
}
}
However in my react app
import React, { Component } from "react";
import axios from "axios";
class Connect extends Component {
state = {
some:[],
results:[],
};
componentDidMount() {
const title = "sometext"
axios.get(`http://localhost:xxxx/api/PageByTitle?title=${title}`,
{
headers : {
'Content-Type': "application/json",
}})
.then((res)=> {
this.setState({ some: res.data?res.data:[]})
this.setState({results:res.data.results?res.data.results:[]})
console.log(this.state.some)
console.log(this.state.some.results)
})
.catch(err => console.log(err))
}
render (){
return(
<div>
{this.state.results.map(
(result) => <p>{result._links.tinyui}</p>
)}
</div>
)
}
}
export default Connect;
A: the correct syntax for reading nested objects in webstorm is
{this.state.results.map((result)=><p key = {result.id}>{result['_links']['tinyui']}</p>)}
How to fight tons of unresolved variables warning in WebStorm?
JavaScript property access: dot notation vs. brackets?
| |
doc_2037
|
sudo apt-get install php-xml
sudo service apache2 restart
In Laravel 5.4 under App\Helpers I have XMLGenerator.php and the following command:
$writer = new XmlWriter();
$writer->openMemory();
....
I get the error:
FatalErrorException in XMLGenerator.php line 90: Class 'App\Helpers\XmlWriter' not found
I don't understand how can i include the XmlWriter.
Thank you
A: I believe you want:
$writer = new XMLWriter();
Caps n' stuff.
A: try installing xmlwriter php extension.
sudo apt-get install php-xmlwriter
or
sudo apt-get install php7-xmlwriter
| |
doc_2038
|
final static char [] BASES = new char[]{'A', 'T', 'C', 'G'};
.
.
char c= in.charAt(i);
switch(c){
case BASES[0] : break;
case BASES[1] : packed =(char) (packed | 1); break;
.
.
.
}
but if I say:
final static char a ='A';
final static char t ='T';
switch(c){
case a : break;
...
it's happy?
I feel like I'm being thick here. :-/
A: The argument to a case must be a constant, i.e. a primitive/string constant or literal or an enum constant. Your array is constant but not its content...
In your case, an enum would be indicated and the code below is an example of how you could write it. It puts all the logic linked to the bases in the enum which you can now reuse where you need to - you can add methods too. And the main code is now clean and easy to read.
Main code:
public static void main(String[] args) {
String input = "ATC";
char packed = 0;
for (char c : input.toCharArray()) {
Base base = Base.valueOf(String.valueOf(c));
packed = base.getPacked(packed);
}
}
And your enum would look like:
public enum Base {
A {
public char getPacked(char packed) {
return packed;
}
}, T {
public char getPacked(char packed) {
return (char) (packed | 1);
}
}, C {
public char getPacked(char packed) {
return packed;
}
}, G {
public char getPacked(char packed) {
return packed;
}
};
public abstract char getPacked(char packed);
}
| |
doc_2039
|
My current markup looks like this:
<div id="wallpaper">
<img />
</div>
And the styles are:
div#wallpaper
{
height: 100%;
left: 0px;
position: absolute;
top: 0px;
width: 100%;
z-index: 1;
}
div#wallpaper img
{
display: block;
margin: 0px auto;
}
I'm using an img tag, because I load it async through jquery, and I'm using position absolute on the parent div to ensure it stays out of the page flow. Finally my content is positioned on top of it with z-index higher than 1.
The problem with the above is, when you browser is only 1024x768 you'll just see the left side of the image - I want it to be the middle portion.
Meaning it should crop from both left and right sides, when the wallpaper is larger than the browser window.
Hope all this made sense, otherwise please ask :-)
A: I'm not sure what you want to do is possible, the way you're doing it.
What I would do is set the image to be the background-image of the wallpaper div, and then set the background position to center the image.
eg.
<div id="wallpaper" style="background-image: foo.jpg"></div>
and in CSS...
div#wallpaper
{
background-position: top 50%;
}
| |
doc_2040
|
$('.option_vehiculo', '#form_login').each(function()
{
if (this.id == tipo_vehiculo_def)
{
this.value = "option";
};
});
.option_vehiculo is a class that I give to all my dropdownlists so I can find them quickly.
I iterate through all my form dropdownlists until I find the one I want to modify. Finding the select I want to change works fine, but I can't set the selected value, I tried this as I am doing with my input fields:
this.value = "option";
where option is an option inside my dropdownlist, but all I get from this is my dropdownlist with no selected value, it just appears with no text inside and with the possibility to select one of my available options.
How do I set the selected value of a jQuery dropdownlist?
Attempts: I tried with this, but I am getting no results and I am not sure if I can use it with 'this' variable as the object I want to modify:
this.val("option");
tried this:
$('#tipo_vehiculo_1000').val("4");
var test = $('#tipo_vehiculo_1000').val();
selecting my dropdownlist by id and trying to change my selected option and outputting it later and it keeps giving me the default value "0".
A: Instead of iterating through all of them you can simply use your id value in a jQuery selector
$('#'+tipo_vehiculo_def).val('option')
This assumes that you have an option tag in the select with value="option". Also assumes that since ID's must be unique in a page you haven't duplicated any ID's
| |
doc_2041
|
$locale = setlocale(LC_ALL, 'fr_FR.UTF-8');
print_r($locale);
echo PHP_EOL;
$verbs = [
'être',
'faire',
'ecouter',
'dire',
'euphoriser',
];
sort($verbs, SORT_LOCALE_STRING);
print_r($verbs);
On my web server, it works as expected, printing:
fr_FR.UTF-8
Array
(
[0] => dire
[1] => ecouter
[2] => être
[3] => euphoriser
[4] => faire
)
The accent is ignored and ê behaves like e. But there's a problem with PHP in my console on macOS. The same app prints the following result:
fr_FR.UTF-8
Array
(
[0] => dire
[1] => ecouter
[2] => euphoriser
[3] => faire
[4] => être
)
The locale is found, because setlocale() returns fr_FR.UTF-8 correctly (it returns false for invalid locale). But for some reason, être is the last element of the array after sorting. It's like this French locale is broken, or never used. How can I make my console PHP use locale correctly?
When I run locale -a, fr_FR.UTF-8 is listed as one of available locales on my machine.
I'm using PHP 7.4.9.
| |
doc_2042
|
def preload_vectors(word2vec_path, word2id, vocab_size, emb_dim):
if word2vec_path:
print('Load word2vec_norm file {}'.format(word2vec_path))
with open(word2vec_path,'r') as f:
header=f.readline()
print(vocab_size, emb_dim)
scale = np.sqrt(3.0 / emb_dim)
init_W = np.random.uniform(-scale, scale, [vocab_size, emb_dim])
print('vocab_size={}'.format(vocab_size))
while True:
line=f.readline()
if not line:break
word=line.split()[0]
if word in word2id:
init_W[word2id[word]] = np.array(line.split()[1:], dtype = np.float32)
return init_W
init_W = preload_vectors("data/GoogleNews-vectors-negative300.txt", word2id, word_vocab_size, FLAGS.word_embedding_dim)
Output:
Load word2vec_norm file data/GoogleNews-vectors-negative300.txt
2556 300
vocab_size=2556
In the computational graph, I have this:
W = tf.Variable(tf.constant(0.0, shape = [word_vocab_size,FLAGS.word_embedding_dim]),trainable = False, name='word_embeddings')
embedding_placeholder = tf.placeholder(tf.float32, shape = [word_vocab_size, FLAGS.word_embedding_dim])
embedding_init = W.assign(embedding_placeholder)
And finally, in the session I feed the init_W to embedding_placeholder:
_,train_cost,train_predict=sess.run([train_op,cost,prediction], feed_dict={
//other model inputs here
embedding_placeholder: init_W
})
But I get this error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-18-732a79dc5ebd> in <module>()
68 labels: next_batch_input.relatedness_scores,
69 dropout_f: config.keep_prob,
---> 70 embedding_placeholder: init_W
71 })
72 avg_cost+=train_cost
/Users/kurt/anaconda2/envs/tensorflow/lib/python2.7/site- packages/tensorflow/python/client/session.pyc in run(self, fetches, feed_dict, options, run_metadata)
764 try:
765 result = self._run(None, fetches, feed_dict, options_ptr,
--> 766 run_metadata_ptr)
767 if run_metadata:
768 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)
/Users/kurt/anaconda2/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/client/session.pyc in _run(self, handle, fetches, feed_dict, options, run_metadata)
935 ' to a larger type (e.g. int64).')
936
--> 937 np_val = np.asarray(subfeed_val, dtype=subfeed_dtype)
938
939 if not subfeed_t.get_shape().is_compatible_with(np_val.shape):
/Users/kurt/anaconda2/envs/tensorflow/lib/python2.7/site-packages/numpy/core/numeric.pyc in asarray(a, dtype, order)
480
481 """
--> 482 return array(a, dtype, copy=False, order=order)
483
484 def asanyarray(a, dtype=None, order=None):
TypeError: float() argument must be a string or a number
I checked the values of the init_W array and they are float:
type(init_W[0][0])
numpy.float64
I used to be able to do this recently with no problems. I must have missed out something here? Please, I need your help. Thanks!
A: Apparently, the problem was not with the embedding_placeholder but with some other input to feed_dict. It was not clear though with the error message.
| |
doc_2043
|
I'm trying to serve a static file, crossdomain.xml, to an app that connects to a datasource I run from jetty. To do this, I configured a servlet and its mapping thus:
<servlet>
<servlet-name>default </servlet-name>
<servlet-class>org.eclipse.jetty.servlet.DefaultServlet </servlet-class>
<init-param>
<param-name>resourceBase </param-name>
<param-value>/foo/foo </param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>default </servlet-name>
<url-pattern>/* </url-pattern>
</servlet-mapping>
Sadly all I get are 404's. Any help would be much appreciated, btw the rest of my web.xm lfile looks like:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"version="2.5">
<servlet>
<servlet-name>cometd </servlet-name>
<servlet-class>org.cometd.server.continuation.ContinuationCometdServlet </servlet-class>
<load-on-startup>1 </load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>cometd </servlet-name>
<url-pattern>/cometd/* </url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>default </servlet-name>
<servlet-class>org.eclipse.jetty.servlet.DefaultServlet </servlet-class>
<init-param>
<param-name>resourceBase </param-name>
<param-value>/foo/foo </param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>default </servlet-name>
<url-pattern>/* </url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>initializer </servlet-name>
<servlet-class>com.foo.research.Initializer </servlet-class>
<load-on-startup>2 </load-on-startup>
</servlet>
<filter>
<filter-name>cross-origin </filter-name>
<filter-class>org.eclipse.jetty.servlets.CrossOriginFilter </filter-class>
</filter>
<filter-mapping>
<filter-name>cross-origin </filter-name>
<url-pattern>/cometd/* </url-pattern>
</filter-mapping>
</web-app>
A: I had the same issue; here is a snippet that works (Jetty 6.1.22).
I basically replaced org.eclipse with org.mortbay and removed the
resourceBase parameter (but see below). And this actually ends up in my web.xml file inside my WAR file:
<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>foo.bar.MyServlet</servlet-class>
<display-name></display-name>
<description>The smallest Servlet ever!</description>
</servlet>
<servlet>
<servlet-name>default</servlet-name>
<servlet-class>org.mortbay.jetty.servlet.DefaultServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/static/*</url-pattern>
</servlet-mapping>
Then, you have to put your static files in the "static" directory in your
WAR file. Like this (just to make it clear):
ROOT.war
|_ WEB-INF/
|_ static/
If you want to put your static files elsewhere (but still map them under
the /static/ URI), you can use the resourceBase parameter to specify the
directory, just like you did.
Jetty's documentation helped me to understand this a little bit better:
http://docs.codehaus.org/display/JETTY/Servlets+Bundled+with+Jetty
| |
doc_2044
|
Mail::send('email', ['name' => "EE"], function($m) {
$m->to(Input::get('email'), '')->subject('Password Request');
});
The email template is:
Hello,
Your password has been changed, successfully.
Your new password is:"**password from database**"
Kindly, change your password later on.
Thanks!
So the "password from database" has to be from database. How may I do that? any help?
A: According to your question you wish to grab the password from database table,
well this not possible because password are encrypted and sending encrypted version to user is useless.
What you could do is generate a new password, save new password in database under user row, email column then email the generated password to user:
You could do this:
I assume user email address is stored under email column in `user table and you have a User model:
$email = Input::get('email');
$user = User::where('email', $email)->first();
if($user){
$new_password = str_random(8); //generates random string , eight character long
$user->password = \Hash::make($new_password);
$user->save();
$data = [
'name' => $user->first_name,
'new_password ' => $new_password
];
Mail::send('emails.password-reset', $data, function($m) use ($user){
$m->to($user->email, '')->subject('Password Request');
});
}
In email template: views\emails\password-reset.blade.php:
Hello {!!$name!!},
Your password has been changed, successfully.
Your new password is:"{!!$new_password!!}"
Kindly, change your password later on.
A: $userDetail = User::find(1);
Mail::send('yourTemplate', array('userInfo'=> $userDetail), function($message) {
$message->from('[email protected]', 'test')
->to('[email protected]', 'name')
->subject('subject');
});
Then in your template file use this variable,like
Hello,
Your password has been changed, successfully.
Your new password is: {!! $userInfo->password !!};
Kindly, change your password later on.
Thanks!
| |
doc_2045
|
On my average android, the movement takes place in small jerks.
If the elements are reduced to 10 then move be smooth.
Such a large number of items are needed for the puzzle.
The user will be able to click and change any an element. Therefore, any element can have a different appearance.
Using zoom, the user can see everything at the same time.
Below is an example of a code with the generation of 3600 elements and processing the event on the movements of group.
Sample code:
main.lua
local composer = require( "composer" )
composer.gotoScene( "demo" )
demo.lua
local composer = require( "composer" )
local scene = composer.newScene()
local COUNT_ROWS = 60
local COUNT_CELLS = 60
local MARGIN_RECT = 3
local RECT_SIZE = 30
local viewGroup
local rectsPreferenses = {}
local cretateRectsGroup
, initRectsPrefs
, onTouch
, scalePropByWidthHeight
function scene:create(event)
self.sceneGroup = self.view
local bg = display.newRect(display.screenOriginX, display.screenOriginY, display.actualContentWidth, display.actualContentHeight)
bg.anchorX = 0
bg.anchorY = 0
bg:setFillColor(1,1,0)
self.sceneGroup:insert(bg)
end
function scene:destroy( event )
end
function scene:show( event )
if event.phase == "will" then
viewGroup = cretateRectsGroup(self.sceneGroup)
local maxWidth = display.actualContentWidth
local maxHeight = display.actualContentWidth
local initScale = scalePropByWidthHeight(viewGroup, {height = maxHeight, width = maxWidth})
viewGroup.xScale = initScale
viewGroup.yScale = initScale
elseif event.phase == "did" then
end
end
function scene:hide( event )
end
function cretateRectsGroup(sceneGroup)
local group = display.newGroup()
group.x = display.actualContentWidth/2 + display.screenOriginX
group.y = display.actualContentHeight/2 + display.screenOriginY
group.anchorChildren = true
local bgW = COUNT_ROWS*RECT_SIZE + COUNT_ROWS*MARGIN_RECT
local bgH = COUNT_CELLS*RECT_SIZE + COUNT_CELLS*MARGIN_RECT
local bg = display.newRect(0, 0, bgW, bgH)
bg.anchorX = 0
bg.anchorY = 0
bg:setFillColor(0,1,0)
bg:addEventListener("touch", onTouch)
group:insert(bg)
initRectsPrefs(0,0)
for i=1, #rectsPreferenses do
local rectPref = rectsPreferenses[i]
local rect = display.newRect(0, 0, rectPref.width, rectPref.height)
rect.anchorX = 0
rect.anchorY = 0
rect.x = rectPref.x
rect.y = rectPref.y
rect:setFillColor(rectPref.fillColor[1], rectPref.fillColor[2], rectPref.fillColor[3])
group:insert(rect)
end
sceneGroup:insert(group)
return group
end
function initRectsPrefs(x, y)
local index = 0
local curX = x
local curY = y
math.randomseed(os.time())
local rand = math.random
for i=1, COUNT_ROWS do
curX = x
for j=1, COUNT_CELLS do
index = index + 1
local r = rand()
local g = rand()
local b = rand()
local optRect = {
id = index
, x = curX
, y = curY
, width = RECT_SIZE
, height = RECT_SIZE
, fillColor = {r, g, b}
}
rectsPreferenses[index] = optRect
curX = curX + RECT_SIZE + MARGIN_RECT
end
curY = curY + RECT_SIZE + MARGIN_RECT
end
end
function onTouch(event)
local group = event.target.parent
local newTouchX, newTouchY = event.x, event.y
if (event.phase == "began") or (group.lastTouchPosX == nil) or (group.lastTouchPosY == nil) then
group.lastTouchPosX = newTouchX
group.lastTouchPosY = newTouchY
return
end
if (event.phase == "ended") or (event.phase == "cancelled") then
group.lastTouchPosX = nil
group.lastTouchPosY = nil
return
end
local deltaX = (newTouchX - group.lastTouchPosX)
local deltaY = (newTouchY - group.lastTouchPosY)
group.x = group.x + deltaX
group.y = group.y + deltaY
group.lastTouchPosX = newTouchX
group.lastTouchPosY = newTouchY
end
function scalePropByWidthHeight(target, targerTo)
local scale = 1
local scaleSize = target.width
if target.height > target.width then
scaleSize = target.height
end
if ( scaleSize/targerTo.width > scaleSize/targerTo.height ) then
scale = targerTo.width/scaleSize
else
scale = targerTo.height/scaleSize
end
return scale
end
scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )
scene:addEventListener( "hide", scene )
scene:addEventListener( "destroy", scene )
return scene
A: I found a solution to this problem using the output to the texture.
texture = graphics.newTexture( {type="canvas", width=textureW, height=textureH} )
local imgTexture = display.newImageRect(group, texture.filename, texture.baseDir, textureW, textureH)
texture:draw(textureGroup)
texture:invalidate( {source="cache", accumulate=false} )
demo.lua:
local composer = require( "composer" )
local scene = composer.newScene()
local COUNT_ROWS = 60
local COUNT_CELLS = 60
local MARGIN_RECT = 3
local RECT_SIZE = 30
local viewGroup
local rectsPreferenses = {}
local cretateRectsGroup
, initRectsPrefs
, onTouch
, scalePropByWidthHeight
function scene:create(event)
self.sceneGroup = self.view
local bg = display.newRect(display.screenOriginX, display.screenOriginY, display.actualContentWidth, display.actualContentHeight)
bg.anchorX = 0
bg.anchorY = 0
bg:setFillColor(1,1,0)
self.sceneGroup:insert(bg)
end
function scene:destroy( event )
if self.sceneGroup.texture then
self.sceneGroup.texture:removeSelf()
end
end
function scene:show( event )
if event.phase == "will" then
viewGroup = cretateRectsGroup(self.sceneGroup)
local maxWidth = display.actualContentWidth
local maxHeight = display.actualContentWidth
local initScale = scalePropByWidthHeight(viewGroup, {height = maxHeight, width = maxWidth})
viewGroup.xScale = initScale
viewGroup.yScale = initScale
elseif event.phase == "did" then
end
end
function scene:hide( event )
end
function cretateRectsGroup(sceneGroup)
local group = display.newGroup()
group.x = display.actualContentWidth/2 + display.screenOriginX
group.y = display.actualContentHeight/2 + display.screenOriginY
group.anchorChildren = true
local bgW = COUNT_ROWS*RECT_SIZE + COUNT_ROWS*MARGIN_RECT
local bgH = COUNT_CELLS*RECT_SIZE + COUNT_CELLS*MARGIN_RECT
local bg = display.newRect(0, 0, bgW, bgH)
bg.anchorX = 0
bg.anchorY = 0
bg:setFillColor(0,1,0)
bg:addEventListener("touch", onTouch)
group:insert(bg)
local textureGroup = display.newGroup()
textureGroup.anchorX = 0
textureGroup.anchorY = 0
local bgTetxture = display.newRect(0, 0, bgW, bgH)
bgTetxture.anchorX = 0
bgTetxture.anchorY = 0
bgTetxture:setFillColor(0,1,0)
textureGroup:insert(bgTetxture)
initRectsPrefs(0,0)
for i=1, #rectsPreferenses do
local rectPref = rectsPreferenses[i]
local rect = display.newRect(0, 0, rectPref.width, rectPref.height)
rect.anchorX = 0
rect.anchorY = 0
rect.x = rectPref.x
rect.y = rectPref.y
rect:setFillColor(rectPref.fillColor[1], rectPref.fillColor[2], rectPref.fillColor[3])
textureGroup:insert(rect)
end
local textureW = bgW
local textureH = bgH
local texture = graphics.newTexture( {type="canvas", width=textureW, height=textureH} )
sceneGroup.texture = texture
local offsetZerroTextureX = -(textureW*0.5)
local offsetZerroTextureY = -(textureH*0.5)
local imgTexture = display.newImageRect(group, texture.filename, texture.baseDir, textureW, textureH)
sceneGroup.imgTexture = imgTexture
imgTexture.anchorX = 0
imgTexture.anchorY = 0
textureGroup.x = offsetZerroTextureX
textureGroup.y = offsetZerroTextureY
texture:draw(textureGroup)
texture:invalidate( {source="cache", accumulate=false} )
return group
end
function initRectsPrefs(x, y)
local index = 0
local curX = x
local curY = y
math.randomseed(os.time())
local rand = math.random
for i=1, COUNT_ROWS do
curX = x
for j=1, COUNT_CELLS do
index = index + 1
local r = rand()
local g = rand()
local b = rand()
local optRect = {
id = index
, x = curX
, y = curY
, width = RECT_SIZE
, height = RECT_SIZE
, fillColor = {r, g, b}
}
rectsPreferenses[index] = optRect
curX = curX + RECT_SIZE + MARGIN_RECT
end
curY = curY + RECT_SIZE + MARGIN_RECT
end
end
function onTouch(event)
local group = event.target.parent
local newTouchX, newTouchY = event.x, event.y
if (event.phase == "began") or (group.lastTouchPosX == nil) or (group.lastTouchPosY == nil) then
group.lastTouchPosX = newTouchX
group.lastTouchPosY = newTouchY
return
end
if (event.phase == "ended") or (event.phase == "cancelled") then
group.lastTouchPosX = nil
group.lastTouchPosY = nil
return
end
local deltaX = (newTouchX - group.lastTouchPosX)
local deltaY = (newTouchY - group.lastTouchPosY)
group.x = group.x + deltaX
group.y = group.y + deltaY
group.lastTouchPosX = newTouchX
group.lastTouchPosY = newTouchY
end
function scalePropByWidthHeight(target, targerTo)
local scale = 1
local scaleSize = target.width
if target.height > target.width then
scaleSize = target.height
end
if ( scaleSize/targerTo.width > scaleSize/targerTo.height ) then
scale = targerTo.width/scaleSize
else
scale = targerTo.height/scaleSize
end
return scale
end
scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )
scene:addEventListener( "hide", scene )
scene:addEventListener( "destroy", scene )
return scene
| |
doc_2046
|
I am using the code below for this :
int deleteposition=CustomizedListView.deleteposition;
CustomizedListView.list.removeViewAt(deleteposition);
CustomizedListView.adapter.notifyDataSetChanged();
finish();
But there is an error at this line :
CustomizedListView.list.removeViewAt(deleteposition);
Please Tell me how to fix it ?
Logcat Details:
java.lang.UnsupportedOperationException: removeViewAt(int) is not supported in AdapterView
at android.widget.AdapterView.removeViewAt(AdapterView.java:511)
at com.example.androidhive.openedmsg$1.onClick(openedmsg.java:35)
at android.view.View.performClick(View.java:3549)
at android.view.View$PerformClick.run(View.java:14393)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:4945)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
The entire Code :
CustomizedListView.class
public class CustomizedListView extends Activity {
// All static variables
static final String URL = "https://itunes.apple.com/us/rss/topalbums/limit=20/json";
// XML node keys
static final String KEY_SONG = "song"; // parent node
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_ARTIST = "artist";
static final String KEY_DURATION = "duration";
static final String KEY_THUMB_URL = "thumb_url";
static ListView list;
static LazyAdapter adapter;
HashMap<String, String> map;
public static String newactivityno;
public static int deleteposition;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions.getJSONfromURL(URL);
try {
JSONObject arr2 = json.getJSONObject("feed");
JSONArray arr = arr2.getJSONArray("entry");
for (int i = 0; i < arr.length(); i++) {
JSONObject e1 = arr.getJSONObject(i);
JSONArray arr3 = e1.getJSONArray("im:image");
JSONObject arr8 = e1.getJSONObject("im:name");
JSONObject arr10 = e1.getJSONObject("im:artist");
JSONObject e12 = arr3.getJSONObject(0);
// creating new HashMap
map = new HashMap<String, String>();
map.put(KEY_THUMB_URL, e12.getString("label"));
map.put(KEY_ARTIST, arr8.getString("label"));
map.put(KEY_TITLE, arr10.getString("label"));
// adding HashList to ArrayList
songsList.add(map);
}
} catch (JSONException e) {
// Log.e("log_tag", "Error parsing data "+e.toString());
Toast.makeText(getBaseContext(),
"Network communication error!", 5).show();
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, songsList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
@SuppressWarnings("unchecked")
HashMap<String, String> o= (HashMap<String, String>) list.getItemAtPosition(position);
// Toast.makeText(CustomizedListView.this, "ID '" + o.get("title") + "' was clicked.", Toast.LENGTH_SHORT).show();
deleteposition=position;
newactivityno= o.get("title");
Intent ii= new Intent(getBaseContext(),newactivity.class);
startActivity(ii);
}
});
}
}
newactivity.class
public class newactivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newlayout);
TextView tv1=(TextView)findViewById(R.id.textView11);
TextView tv2=(TextView)findViewById(R.id.textView12);
Button bn=(Button)findViewById(R.id.button1);
tv2.setText(CustomizedListView.newactivityno);
bn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int deleteposition=CustomizedListView.deleteposition;
CustomizedListView.list.removeViewAt(deleteposition);
CustomizedListView.adapter.notifyDataSetChanged();
finish();
}
});
}
}
A: You are approaching this problem in the wrong manner. Rather than remove the View from the AdapterView, simply remove the data from the data set and call notifyDataSetChanged(). (This will remove the unwanted View automatically.)
| |
doc_2047
|
*
*When a user signs in via an OAuth provider (e.g. Facebook, Twitter, Github) a new user record is created...but if the same user clears their cookies or uses a different browser to log in, a new user record is created.
*If I do something clever (read: hacky) and assign users with social logins an ID based on the socialAccount and socialAccountId (something unique but constant for each social account), someone could use the standard method of user creation to spoof a user by making a POST request to the /users endpoint if they knew that user's socialAccount and socialAccountId.
My question is: How can I A) prevent #1 from occurring, or B) disable the standard method of user creation without also preventing OAuth user creation?
Has anyone ever successfully used Deployd and dpd-passport in production? If so, I want to speak with you...
Thanks in advance!
A: First of all, I think you haven't added the custom fields per the docs.
https://www.npmjs.com/package/dpd-passport#requirements
I hadn't either, and observed the new user feature (because it couldn't lookup the response from the auth service to find the user from before). Adding these fields fixed it.
Also, there is a google group here:
https://groups.google.com/forum/#!forum/deployd-users
Hope that helps.
| |
doc_2048
|
For example if I have column name Country in excel, I want the data in this column to be inserted in the lookup column Country in SharePoint List. I tried using access db and it didn't work.
Is there any other way using JSOM or access other than Powershell? (cannot use powershell or any server side coding).
A: I think the lookup fields in the lists are different than those in excel. You cannot link any lookup or formulas from excel to a list column as from what I remember, also mapping excel column to list lookup field would not work as well. Probably you may have to add the data from the list and then create similar 'Country' field in the list, but as SharePoint List lookup field by hand. Doubt this can be automated without CSOM code and usage of some excel tooling like Open XML SDK.
A: What you should do is save your Excel file to a CSV-file (avoiding the openXML approach which will makes things more complex than they are). Then in c# you can use System.IO.File to read the file and loop through each row
string[] _fileData = System.IO.File.ReadAllLines(_filePath);
_fileData will be a multi-dimensional array, for row and columns.
Filling in the lookup field, you can use CSOM to achieve this. See this sample code i copied from: https://karinebosch.wordpress.com/2015/05/11/setting-the-value-of-a-lookup-field-using-csom/
CamlQuery camlQueryForItem = new CamlQuery();
camlQueryForItem.ViewXml = string.Format(@"<View>
<Query>
<Where>
<Eq>
<FieldRef Name='{0}'/>
<Value Type='{1}'>{2}</Value>
</Eq>
</Where>
</Query>
</View>", lookupFieldName, lookupFieldType, value);
listItemCollection listItems = list.GetItems(camlQueryForItem);
clientContext.Load(listItems, items => items.Include
(listItem => listItem["ID"],
listItem => listItem[lookupFieldName]));
clientContext.ExecuteQuery();
if (listItems != null)
{
ListItem item = listItems[0];
lookupValue = new FieldLookupValue();
lookupValue.LookupId = Int.Parse(item["ID"].ToString());
So you first get the listItem through a CAML query, and then set the value through the FieldLookupValue object
Good luck!
| |
doc_2049
|
The scenario to achieve a bug:
1) Click the ListBoxItem -> it receive the focus and styles(ok).
2) Move the pointer over this ListBoxItem -> it’s still focused and receive the styles for ‘MouseOver’ (it is within a separate VisualStateGroup ‘CommonStates’ as suggested here: https://msdn.microsoft.com/en-us/library/system.windows.controls.listboxitem%28v=vs.95%29.aspx )(ok).
3) Make the mouse leave the ListBoxItem’s bounds -> it loses the style for MouseOver(ok).
4) Now, the ListBoxItem is in ‘Normal’ state of ‘CommonStates’ and is also ‘Focused’, but doesn’t have the stylish for ‘Focused’(it is my problem).
5) Attampting to click this ListBoxItem has no effect
Could you give me some advice, how to deal with it?
I’m using Silverlight, so triggers are forbidden 4 me.
Here is my style:
<Style x:Key="ListBoxItemStyle1" TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="HorizontalAlignment" Value="Left" />
<Setter Property="ContentControl.Foreground" Value="{StaticResource ViewModeButtonForeground}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border x:Name="RootElement">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal" />
<VisualState x:Name="MouseOver">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="Content" Storyboard.TargetProperty="(ContentControl.Foreground)">
<DiscreteObjectKeyFrame KeyTime="0:0:0" Value="{StaticResource ViewModeButtonForeground}" />
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="CheckOuterBorder" Storyboard.TargetProperty="BorderBrush">
<DiscreteObjectKeyFrame KeyTime="0:0:0" Value="{StaticResource ViewModeButtonOuterBorder_MouseOver}" />
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="CheckOuterBorder" Storyboard.TargetProperty="Background">
<DiscreteObjectKeyFrame KeyTime="0:0:0" Value="{StaticResource ViewModeButtonBackground_MouseOver}" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
<VisualStateGroup x:Name="FocusStates">
<VisualState x:Name="Focused">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="Content" Storyboard.TargetProperty="(ContentControl.Foreground)">
<DiscreteObjectKeyFrame KeyTime="0:0:0" Value="{StaticResource ViewModeButtonForeground_Focused}" />
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="CheckOuterBorder" Storyboard.TargetProperty="BorderBrush">
<DiscreteObjectKeyFrame KeyTime="0:0:0" Value="{StaticResource ViewModeButtonOuterBorder_Focused}" />
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="CheckOuterBorder" Storyboard.TargetProperty="Background">
<DiscreteObjectKeyFrame KeyTime="0:0:0" Value="{StaticResource ViewModeButtonBackground_Normal}" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Unfocused"></VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Grid>
<Border x:Name="CheckOuterBorder" CornerRadius="2" BorderThickness="1" BorderBrush="Transparent" Background="Transparent">
</Border>
<Grid x:Name="GridContent" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Width="Auto">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Image Grid.Column="0" Width="16" Height="16" VerticalAlignment="Center" HorizontalAlignment="Left" Source="{Binding ImgSource, Mode=OneWay}"/>
<ContentControl x:Name="Content" Grid.Column="1" Margin="3,0,0,0" Foreground="{TemplateBinding Foreground}" Content="{Binding Title}" ContentTemplate="{TemplateBinding ContentTemplate}" VerticalAlignment="Center" Width="Auto"/>
</Grid>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="ViewModeSelectionListBoxStyle" TargetType="ListBox">
<Setter Property="BorderThickness" Value="0" />
<Setter Property="IsTabStop" Value="True" />
<Setter Property="ItemContainerStyle" Value="{StaticResource ListBoxItemStyle1}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
</Style>
If I change my VisualStateGroup from ‘FocusStates’ into SelectionStates it behaves the same. I want it to be associated with focus rather than the selection, because there can be visual mismatch in the UI if user clicks somewhere and another control will have similar border too.
BTW: On another msdn site I’ve read:
‘The control is always in one state for each VisualStateGroup that is defined in its ControlTemplate and only leaves a state when it goes into another state from the same VisualStateGroup.’
From my code-behind I have ensured that the listBoxItem has still the focus on. Besides, I was trying to enforce going to that state after the mouse leaving my listBoxItem – with no results (simplifying: ActiveViewDefinition is an replacement for the actually focused item in the listbox):
private void It_MouseLeave(object sender, MouseEventArgs e)
{
ListBoxItem lbItem = sender as System.Windows.Controls.ListBoxItem;
if (lbItem != null && lbItem.Content == ActiveViewDefinition)
{
VisualStateManager.GoToState(lbItem, "Focused", true);
}
}
A: Easy. Your VisualStates from different groups manipulate the same properties of the same elements.
You always need to have separate elements (or use separate properties of shared elements) to indicate states from different groups, otherwise they will naturally clash and mess with each others settings (as you have observed).
An example in pseudo-xaml:
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"><NoChange/></VisualState>
<VisualState x:Name="MouseOver"><Change What="TheBorder" Color="Red"/></VisualState>
</VisualStateGroup>
<VisualStateGroup x:Name="FocusStates">
<VisualState x:Name="Focused"><Change What="TheBorder" Color="Blue"/></VisualState>
</VisualStateGroup>
<Border x:Name="TheBorder" Color="Transparent"/>
Initially the border is Transparent.
Now what happens when we move the mouse over the Border?
The mouseOver state changes it to red. Now we click our control (let's assume it gets selected and can be focused). The focusState changes it to blue. Now we move the mouse away from it. The normalState changes it to its initial state: Transparent. The focusState effect is lost.
Let's have a look at the modified example:
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"><NoChange/></VisualState>
<VisualState x:Name="MouseOver"><Change What="TheMouseoverBorder" Color="Red"/></VisualState>
</VisualStateGroup>
<VisualStateGroup x:Name="FocusStates">
<VisualState x:Name="Focused"><Change What="TheFocusBorder" Color="Blue"/></VisualState>
</VisualStateGroup>
<Border x:Name="TheFocusBorder" Color="Transparent"/>
<Border x:Name="TheMouseoverBorder" Color="Transparent"/>
Initially both borders are transparent.
Now what happens when we move the mouse over them?
The mouseOver state changes the TheMouseoverBorder to red. Now we click our control (let's assume it gets selected and can be focused). The focusState changes TheFocusBorder to blue. Now we move the mouse away from it. The normalState changes TheMouseoverBorder back to transparent. The focusState is still visible because the TheFocusBorder is uneffected by other state changes and still blue.
[Edit]
If you absolutely must modify the same property of the same element from separate VisualStateGroups, you can either use some kind of aggregator that has a resulting output property, or use some kind of fallthrough mechanism.
I can think of several possible solutions to modify the same Foreground property from separate VisualStateGroups. You can try those and see if they work.
Fallthrough
<VisualState x:Name="MouseOver"><Change What="Outer" ForegroundColor="Red"/></VisualState>
...
<VisualState x:Name="Focused"><Change What="Inner" ForegroundColor="Blue"/></VisualState>
<ContentControl x:Name="Outer">
<ContentControl x:Name="Inner">
...
</ContentControl>
</ContentControl>
In theory: if both states are active the inner state wins (focused: blue), if only the mouseover state is active the property is not explicitly set on the inner and will be inherited from the outer. Not tested. Try it.
Aggregator
<VisualState x:Name="MouseOver"><Change What="Aggregator" MouseOverColor="Red"/></VisualState>
...
<VisualState x:Name="Focused"><Change What="Aggregator" FocusedColor="Blue"/></VisualState>
<InvisibleAggregator x:Name="Aggregator"/>
<ContentControl Foreground="{Binding ElementName=Aggregator, Path=EffectiveColor}"/>
| |
doc_2050
|
Following is the code I am using to render the Pinterest button, I have tried alot but may be I am missing something simple
The config I am using is data-pin-config='beside' data-pin-do='buttonPin'
href="//pinterest.com/pin/create/button/?url=currentpage&media=http%3A%2F%2Ffarm8.staticflickr.com%2F7027%2F6851755809_df5b2051c9_z.jpg&guid=bj5u2KMfSVWK&media=http%3A%2F%2Ffarm8.staticflickr.com%2F7027%2F6851755809_df5b2051c9_z.jpg"
script src='http:// assets.pinterest.com/js/pinit.js'
Sorry I had to get rid of html tags as it was playing and not showing in the question
A: I don't think Pinterest ever shows zero you go from no number to the number one.
A: By default Pinterest does not show zero counts but you can enable it with the attribute data-pin-zero:
<a href="..." data-pin-zero="true" data-pin-config="beside" data-pin-do="buttonPin">...</a>
Although I could not find anything about this on developers.pinterest.com, it can be found in their js-file on github.
| |
doc_2051
|
My initial try is as follows:
j = 0
x = 9970024
total = 249250621
while (j <= total):
for i in range(j,x):
j = j +1
j = i+1
x = x+j
A: Let's use some smaller numbers for clarity.
total = 25
fragment = 10
for start in xrange(0, total, fragment):
print "start = ", start
for i in range(start, min([start + fragment, total])):
print i
Output:
start = 0
0
1
2
3
4
5
6
7
8
9
start = 10
10
11
12
13
14
15
16
17
18
19
start = 20
20
21
22
23
24
A: An alternative way of looking at this could be to simply iterate the whole range but determine when a segment boundary is reached.
total = 249250621
segment = total / 25 # 9970024
for j in xrange(0, total+1):
if j % segment == 0:
print "%u - start of segment" % j
A: for i in range(0,249250621,9970024):
for j in range(i,i+9970024+1):
pass
You can try this.Here i will increase by 9970024 everytime.And j will loop for 9970024 times.
| |
doc_2052
|
I am using istio 1.2.5
I have deployed istio using helm default profile from the istio documentation by enabling the tracing, kiali and logLevel to "debug".
My pods and service in istio system namespace looks like this:
(⎈ |cluster-dev:default)➜ istio-1.2.5 git:(master) ✗ k pods -n istio-system
NAME READY STATUS RESTARTS AGE
grafana-97fb6966d-cv5fq 1/1 Running 0 1d
istio-citadel-76f9586b8b-4bbcx 1/1 Running 0 1d
istio-galley-78f65c8469-v5cmn 1/1 Running 0 1d
istio-ingressgateway-5d5487c666-jjhb7 1/1 Running 0 1d
istio-pilot-65cb5648bf-4nfl7 2/2 Running 0 1d
istio-policy-8596cc6554-7sgzt 2/2 Running 0 1d
istio-sidecar-injector-76f487845d-ktf6p 1/1 Running 0 1d
istio-telemetry-5c6b6d59f6-lppqt 2/2 Running 0 1d
istio-tracing-595796cf54-zsnvj 1/1 Running 0 1d
kiali-55fcfc86cc-p2jrk 1/1 Running 0 1d
prometheus-5679cb4dcd-h7qsj 1/1 Running 0 1d
(⎈ |cluster-dev:default)➜ istio-1.2.5 git:(master) ✗ k svc -n istio-system
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
grafana ClusterIP 172.20.116.246 <none> 3000/TCP 1d
istio-citadel ClusterIP 172.20.177.97 <none> 8060/TCP,15014/TCP 1d
istio-galley ClusterIP 172.20.162.16 <none> 443/TCP,15014/TCP,9901/TCP 1d
istio-ingressgateway LoadBalancer 172.20.199.160 xxxxxxxxxxxxx... 15020:31334/TCP,80:31380/TCP,443:31390/TCP,31400:31400/TCP,15029:30200/TCP,15030:32111/TCP,15031:32286/TCP,15032:32720/TCP,15443:30857/TCP 1d
istio-pilot ClusterIP 172.20.137.21 <none> 15010/TCP,15011/TCP,8080/TCP,15014/TCP 1d
istio-policy ClusterIP 172.20.188.114 <none> 9091/TCP,15004/TCP,15014/TCP 1d
istio-sidecar-injector ClusterIP 172.20.47.238 <none> 443/TCP 1d
istio-telemetry ClusterIP 172.20.77.52 <none> 9091/TCP,15004/TCP,15014/TCP,42422/TCP 1d
jaeger-agent ClusterIP None <none> 5775/UDP,6831/UDP,6832/UDP 1d
jaeger-collector ClusterIP 172.20.225.255 <none> 14267/TCP,14268/TCP 1d
jaeger-query ClusterIP 172.20.181.245 <none> 16686/TCP 1d
kiali ClusterIP 172.20.72.227 <none> 20001/TCP 1d
prometheus ClusterIP 172.20.25.75 <none> 9090/TCP 1d
tracing ClusterIP 172.20.211.135 <none> 80/TCP 1d
zipkin ClusterIP 172.20.204.123 <none> 9411/TCP 1d
I have't use any egress gateway and my outboundTrafficPolicy mode is ALLOW_ANY. So, I am assuming I don't need any service entry.
I am using nginx ingress controller as a entrypoint to my cluster and haven't started istio ingress gateway.
Issue:
I have a micro service in my cluster that is hitting/reaching-out to an external URL(out of my cluster to legacy system) with a HTTP POST query. This system normally respond backs to my microservice in 25 seconds and have hard timeout on itself 0f 30 seconds.
When I am not using istio sidecar, my microservice is responding normally. But after deploying istio with sidecar I am getting 504 gateway everytime after 15 seconds.
Logs of microservice and well as istio-proxy:
Microservice logs without istio(search response took 21.957 Seconds in logs)
2019-09-06 19:42:20.113 INFO [xx-xx-adapter,9b32565791541300,9b32565791541300,false] 1 --- [or-http-epoll-4] c.s.t.s.impl.common.PrepareRequest : Start Preparing search request
2019-09-06 19:42:20.117 INFO [xx-xx-adapter,9b32565791541300,9b32565791541300,false] 1 --- [or-http-epoll-4] c.s.t.s.impl.common.PrepareRequest : Done Preparing search request
2019-09-06 19:42:42.162 INFO [xx-xx-adapter,9b32565791541300,9b32565791541300,false] 1 --- [or-http-epoll-8] c.s.t.service.impl.TVSearchServiceImpl : xxxx search response took 21.957 Seconds
2019-09-06 19:42:42.292 INFO [xx-xx-adapter,9b32565791541300,9b32565791541300,false] 1 --- [or-http-epoll-8] c.s.t.service.impl.common.Transformer : Doing transformation of supplier response into our response
2019-09-06 19:42:42.296 INFO [xx-xx-adapter,9b32565791541300,9b32565791541300,false] 1 --- [or-http-epoll-8] c.s.t.service.impl.common.Transformer : Transformer: Parsing completed in 3 mSeconds
Microservice logs with istio(response took 15.009 Seconds in logs)
2019-09-06 19:40:00.048 INFO [xxx-xx-adapter,32c55821a507d6f3,32c55821a507d6f3,false] 1 --- [or-http-epoll-3] c.s.t.s.impl.common.PrepareRequest : Start Preparing search request
2019-09-06 19:40:00.048 INFO [xxx-xx-adapter,32c55821a507d6f3,32c55821a507d6f3,false] 1 --- [or-http-epoll-3] c.s.t.s.impl.common.PrepareRequest : Done Preparing search request
2019-09-06 19:40:15.058 INFO [xx-xx-adapter,32c55821a507d6f3,32c55821a507d6f3,false] 1 --- [or-http-epoll-7] c.s.t.service.impl.xxxx : xxx Search Request {"rqst":{"Request":{"__type":"xx","CheckIn":"/Date(1569628800000+0000)/","CheckOut":"/Date(1569801600000+0000)/","DetailLevel":9,"ExcludeHotelDetails":false,"GeoLocationInfo":{"Latitude":25.204849,"Longitude":55.270782},"Nights":0,"RadiusInMeters":25000,"Rooms":[{"AdultsCount":2,"KidsAges":[2]}],"DesiredResultCurrency":"EUR","Residency":"GB","TimeoutSeconds":25,"ClientIP":"127.0.0.1"},"RequestType":1,"TypeOfService":2,"Credentials":{"UserName":"xxxx","Password":"xx"}}}
2019-09-06 19:40:15.058 ERROR [xx-xx-adapter,32c55821a507d6f3,32c55821a507d6f3,false] 1 --- [or-http-epoll-7] c.s.t.service.impl.xxxx : xxx Search request failed 504 GATEWAY_TIMEOUT
2019-09-06 19:40:15.058 INFO [xxx-xx-adapter,32c55821a507d6f3,32c55821a507d6f3,false] 1 --- [or-http-epoll-7] c.s.t.service.impl.xxxx : xx search response took 15.009 Seconds
2019-09-06 19:40:15.059 ERROR [xxx-xx-adapter,32c55821a507d6f3,32c55821a507d6f3,false] 1 --- [or-http-epoll-7] a.w.r.e.AbstractErrorWebExceptionHandler : [79d38e2f] 500 Server Error for HTTP POST "/search/geo-location"
java.lang.RuntimeException: Error occurred, We did not receive proper search response from xx please check internal logs for more info
<Java Stack trace >
2019-09-06 19:40:15.061 ERROR [xxx-xx-adapter,32c55821a507d6f3,32c55821a507d6f3,false] 1 --- [or-http-epoll-7] c.s.t.service.impl.xxxx : xxx search response upstream request timeout
2019-09-06 19:41:16.081 INFO [xxx-xx--adapter,,,] 1 --- [ Thread-22] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'executor'
Envoy sidecar proxy logs Masked
[2019-09-06T20:32:15.418Z] "POST /xxxxxx/xxxxx.svc/xx/ServiceRequest HTTP/1.1" 504 UT "-" "-" 517 24 14997 - "-" "ReactorNetty/0.8.10.RELEASE" "c273fac1-8xxa-xxxx-xxxx-xxxxxx" "testdomain.testurl.com" "40.67.217.71:80" PassthroughCluster - 1.7.17.71:80 1.20.21.25:42386 -
[2019-09-06 20:39:01.719][34][debug][router] [external/envoy/source/common/router/router.cc:332] [C57][S17104382791712695742] cluster 'PassthroughCluster' match for URL '/xxxxx/xxxx.svc/json/ServiceRequest'
[2019-09-06 20:39:01.719][34][debug][router] [external/envoy/source/common/router/router.cc:332] [C57][S17104382791712695742] cluster 'PassthroughCluster' match for URL '/xxxxx/xxxx.svc/json/ServiceRequest'
[2019-09-06 20:39:01.719][34][debug][upstream] [external/envoy/source/common/upstream/original_dst_cluster.cc:87] Created host 40.67.217.71:80.
[2019-09-06 20:39:01.719][34][debug][router] [external/envoy/source/common/router/router.cc:393] [C57][S17104382791712695742] router decoding headers:
':authority', 'x.x.com'
':path', '/xxxxx/xxxxx.svc/json/ServiceRequest'
':method', 'POST'
':scheme', 'http'
'user-agent', 'ReactorNetty/0.8.10.RELEASE'
'accept', 'application/json'
'accept-encoding', 'gzip, deflate'
'x-newrelic-transaction', 'PxRSBVVQXAdVUgNTUgcPUQUBFB8EBw8RVU4aB1wLB1YHAA8DAAQFWlNXB0NKQV5XCVVQAQcGFTs='
'x-newrelic-id', 'VgUDWFVaARADUFNWAgQHV1A='
'content-type', 'application/json;charset=UTF-8'
'content-length', '517'
'x-forwarded-proto', 'http'
'x-request-id', '750f4fdb-83f9-409c-9ecf-e0a1fdacbb65'
'x-istio-attributes', 'CloKCnNvdXJjZS51aWQSTBJKa3ViZXJuZXRlczovL2hvdGVscy10di1hZGFwdGVyLXNlcnZpY2UtZGVwbG95bWVudC03ZjQ0ZDljNjVjLWhweHo3LmRlZmF1bHQ='
'x-envoy-expected-rq-timeout-ms', '15000'
'x-b3-traceid', '971ac547c63fa66e'
'x-b3-spanid', '58c12e7da54ae50f'
'x-b3-parentspanid', 'dc7bda5b98d522bf'
'x-b3-sampled', '0'
[2019-09-06 20:39:01.719][34][debug][pool] [external/envoy/source/common/http/http1/conn_pool.cc:88] creating a new connection
[2019-09-06 20:39:01.719][34][debug][client] [external/envoy/source/common/http/codec_client.cc:26] [C278] connecting
[2019-09-06 20:39:01.719][35][debug][upstream] [external/envoy/source/common/upstream/cluster_manager_impl.cc:973] membership update for TLS cluster PassthroughCluster added 1 removed 0
[2019-09-06 20:39:01.719][28][debug][upstream] [external/envoy/source/common/upstream/cluster_manager_impl.cc:973] membership update for TLS cluster PassthroughCluster added 1 removed 0
[2019-09-06 20:39:01.719][34][debug][connection] [external/envoy/source/common/network/connection_impl.cc:704] [C278] connecting to 40.67.217.71:80
[2019-09-06 20:39:01.720][35][debug][upstream] [external/envoy/source/common/upstream/original_dst_cluster.cc:41] Adding host 40.67.217.71:80.
[2019-09-06 20:39:01.720][28][debug][upstream] [external/envoy/source/common/upstream/original_dst_cluster.cc:41] Adding host 40.67.217.71:80.
[2019-09-06 20:39:01.720][34][debug][connection] [external/envoy/source/common/network/connection_impl.cc:713] [C278] connection in progress
[2019-09-06 20:39:01.720][34][debug][pool] [external/envoy/source/common/http/conn_pool_base.cc:20] queueing request due to no available connections
[2019-09-06 20:39:01.720][34][debug][filter] [src/envoy/http/mixer/filter.cc:102] Called Mixer::Filter : decodeData (517, false)
[2019-09-06 20:39:01.720][34][debug][http] [external/envoy/source/common/http/conn_manager_impl.cc:1079] [C57][S17104382791712695742] request end stream
[2019-09-06 20:39:01.720][34][debug][filter] [src/envoy/http/mixer/filter.cc:102] Called Mixer::Filter : decodeData (0, true)
[2019-09-06 20:39:01.720][34][debug][upstream] [external/envoy/source/common/upstream/cluster_manager_impl.cc:973] membership update for TLS cluster PassthroughCluster added 1 removed 0
[2019-09-06 20:39:01.748][34][debug][connection] [external/envoy/source/common/network/connection_impl.cc:552] [C278] connected
[2019-09-06 20:39:01.748][34][debug][client] [external/envoy/source/common/http/codec_client.cc:64] [C278] connected
[2019-09-06 20:39:01.748][34][debug][pool] [external/envoy/source/common/http/http1/conn_pool.cc:245] [C278] attaching to next request
[2019-09-06 20:39:01.748][34][debug][router] [external/envoy/source/common/router/router.cc:1210] [C57][S17104382791712695742] pool ready
[2019-09-06 20:39:02.431][35][debug][filter] [external/envoy/source/extensions/filters/listener/original_dst/original_dst.cc:18] original_dst: New connection accepted
[2019-09-06 20:39:02.431][35][debug][filter] [external/envoy/source/extensions/filters/listener/tls_inspector/tls_inspector.cc:72] tls inspector: new connection accepted
[2019-09-06 20:39:02.431][35][debug][filter] [src/envoy/tcp/mixer/filter.cc:30] Called tcp filter: Filter
[2019-09-06 20:39:02.431][35][debug][filter] [src/envoy/tcp/mixer/filter.cc:40] Called tcp filter: initializeReadFilterCallbacks
[2019-09-06 20:39:02.431][35][debug][filter] [external/envoy/source/common/tcp_proxy/tcp_proxy.cc:200] [C279] new tcp proxy session
[2019-09-06 20:39:02.431][35][debug][filter] [src/envoy/tcp/mixer/filter.cc:135] [C279] Called tcp filter onNewConnection: remote 1.210.4.2:39482, local 1.10.1.5:80
[2019-09-06 20:39:02.431][35][debug][filter] [external/envoy/source/common/tcp_proxy/tcp_proxy.cc:343] [C279] Creating connection to cluster inbound|80|xx-xx-adapter-service|xx-xx-adapter-service.default.svc.cluster.local
[2019-09-06 20:39:02.431][35][debug][pool] [external/envoy/source/common/tcp/conn_pool.cc:80] creating a new connection
[2019-09-06 20:39:02.431][35][debug][pool] [external/envoy/source/common/tcp/conn_pool.cc:372] [C280] connecting
[2019-09-06 20:39:02.431][35][debug][connection] [external/envoy/source/common/network/connection_impl.cc:704] [C280] connecting to 127.0.0.1:80
[2019-09-06 20:39:02.431][35][debug][connection] [external/envoy/source/common/network/connection_impl.cc:713] [C280] connection in progress
[2019-09-06 20:39:02.431][35][debug][pool] [external/envoy/source/common/tcp/conn_pool.cc:106] queueing request due to no available connections
[2019-09-06 20:39:02.431][35][debug][main] [external/envoy/source/server/connection_handler_impl.cc:257] [C279] new connection
[2019-09-06 20:39:02.431][35][debug][connection] [external/envoy/source/common/network/connection_impl.cc:552] [C280] connected
[2019-09-06 20:39:02.431][35][debug][pool] [external/envoy/source/common/tcp/conn_pool.cc:293] [C280] assigning connection
[2019-09-06 20:39:02.431][35][debug][filter] [external/envoy/source/common/tcp_proxy/tcp_proxy.cc:542] TCP:onUpstreamEvent(), requestedServerName:
[2019-09-06 20:39:02.431][35][debug][filter] [src/envoy/tcp/mixer/filter.cc:143] Called tcp filter completeCheck: OK
[2019-09-06 20:39:02.432][35][debug][filter] [src/istio/control/client_context_base.cc:140] Report attributes: attributes {
key: "connection.event"
value {
string_value: "open"
}
}
attributes {
key: "connection.id"
value {
string_value: "82e869af-aec6-406a-8a52-4168a19eb1f0-279"
[2019-09-06 20:39:02.432][35][debug][filter] [src/envoy/tcp/mixer/filter.cc:102] [C279] Called tcp filter onRead bytes: 130
[2019-09-06 20:39:02.435][35][debug][filter] [src/envoy/tcp/mixer/filter.cc:125] [C279] Called tcp filter onWrite bytes: 147
[2019-09-06 20:39:02.435][35][debug][filter] [src/envoy/tcp/mixer/filter.cc:102] [C279] Called tcp filter onRead bytes: 0
[2019-09-06 20:39:02.436][35][debug][filter] [src/envoy/tcp/mixer/filter.cc:125] [C279] Called tcp filter onWrite bytes: 0
[2019-09-06 20:39:02.436][35][debug][connection] [external/envoy/source/common/network/connection_impl.cc:520] [C280] remote close
[2019-09-06 20:39:02.436][35][debug][connection] [external/envoy/source/common/network/connection_impl.cc:190] [C280] closing socket: 0
[2019-09-06 20:39:02.436][35][debug][pool] [external/envoy/source/common/tcp/conn_pool.cc:121] [C280] client disconnected
[2019-09-06 20:39:02.436][35][debug][connection] [external/envoy/source/common/network/connection_impl.cc:101] [C279] closing data_to_write=0 type=0
[2019-09-06 20:39:02.436][35][debug][connection] [external/envoy/source/common/network/connection_impl.cc:190] [C279] closing socket: 1
[2019-09-06 20:39:02.436][35][debug][filter] [src/envoy/tcp/mixer/filter.cc:174] [C279] Called tcp filter onEvent: 1 upstream 127.0.0.1:80
[2019-09-06 20:39:02.436][35][debug][filter] [src/istio/control/client_context_base.cc:140] Report attributes: attributes {
key: "connection.duration"
value {
duration_value {
nanos: 4358000
}
}
}
attributes {
key: "connection.event"
value {
string_value: "close"
}
}
at
[2019-09-06 20:39:02.436][35][debug][main] [external/envoy/source/server/connection_handler_impl.cc:68] [C279] adding to cleanup list
[2019-09-06 20:39:02.436][35][debug][pool] [external/envoy/source/common/tcp/conn_pool.cc:246] [C280] connection destroyed
I tried creating a virtual service over my MS with timeout of 30seconds but no luck.
I am not sure what I am missing. Need Help.
Crux:
Internet(or from pod console) --> micro-service --> micro-service calling 3rd part legacy URL internally in code and getting timeouts in exact 15 seconds every-time.
Editing and adding more details:
Just to add the delay, I tried "curl http://slowwly.robertomurray.co.uk/delay/17000/url/http://www.google.com" (17000 = 17 seconds )from any of the microservice pod that have istio-proxy sidecar and always getting timeouts at 15 seconds.
I am not sure where to change this 15 seconds envoy setting.
A: After lot of hit and trial we got this working.
Reference: https://github.com/istio/istio/issues/16915#issuecomment-529210672
So for any outbound traffic no matter if you have egress gateway or not default timeout is 15 seconds. So, if you want to increase that you need to have a ServiceEntry and a VirtualService that defines the timeout.
ServiceEntry
apiVersion: networking.istio.io/v1alpha3
kind: ServiceEntry
metadata:
name: external-se-test
spec:
hosts:
- slowwly.robertomurray.co.uk
location: MESH_EXTERNAL
ports:
- number: 80
name: example-http
protocol: HTTP
resolution: DNS
VirtualService
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: slow-ext
spec:
hosts:
- slowwly.robertomurray.co.uk
http:
- timeout: 30s
route:
- destination:
host: slowwly.robertomurray.co.uk
weight: 100
A: It seems 15 seconds is a default timeout value. Whether it is Istio or Envoy which sets that, I have yet to read further.
But, there's a couple of reported issue such as #1888 (Istio 0.2.12 and Kubernetes 1.8.1) and #6860 which was discussed to be very similar to your issue.:
INGRESS > PUBLICSERVICE (Timeout 60 works)
PUBLICSERVICE > BACKENDSERVICE (Timeout 60 works)
but
INGRESS > PUBLICSERVICE > BACKENDSERVICE (i get timeout after default 15seconds)
You can read through the discussion of 6860, but in summary, they have introduced a fix starting 1.0.0 so that the timeout can be set greater than 15 seconds. To do that, you need to write the timeout in your VirtualServices. For example, for the internal service set 60 seconds, for your external service set to 40 seconds so that there is enough allowance.
Please check and see if it helps.
| |
doc_2053
|
However, we need to migrate to a new server, and new cobol compiler. We're under the impression that we need to recompile the code to get it to work on the new server. Running the exising compiled program gave runtime memory errors.
We have some source code for the program, but it is old. Not sure what the diff is between it and the compiled program.
Okay, so the question -- what should we do?
Time is not on our side, since we have to send our old server back to get credit for it. Ideas, suggestions, crazy or otherwise? (source control is obvious and its not up to me to do it, so save the lectures)
A: In the short run it would probably be cheaper to arrange to keep the old server. In the semi-long run, you need to make time and budget to reengineer the program, either re-write it or see how much effort it would be to hack the old code into shape doing what the program currently does.
A: It's sadly. You should consult the Source Recovery Company
A: If your source code is relatively close to the compiled version, try this:
*
*decompile new version into assembler
*compile the old source code into assembler
*compare
*reconcile as best you can the differences from new version with old version, into the old souce code
*repeat
To augment this, and probably as a second step, as it will bring the source code farther from the new compiled version, test with input data and just try reverse-engineering based on the output what would be needed to create that output. The more test input data you have the better this could work.
Good luck!
A: Create an image of your old server. Then run the old server as a virtual machine on your new server.
However, I agree a better option is probably to keep your production server.
A: (I'm not a COBOL programmer but..)
If you know what version the compiler was that compiled the original program, you could at least compile the old cobol source; if the compiled versions is identical you know the source actually is the current version.
If they differ, you could try to (somehow) decompile, or at least disassemble, the working compiled version and the freshly compiled version and use a diff tool to get an idea of how big difference there is.
A: crazy sugestion: COBOL DECOMPILER --> SOURCE --> NEW COBOL COMPILER...?
(edit: http://juggersoft.com - PAID cobol decompiler)
A: if you have the .int (intermediate) binary files you can just run on the new server, if not, them you musto to recompile.
A: The program could have been produced by an external resource and that person or software house or organisation could have the latest source in their repository. It may be held by your parent organisation if you have recently merged, or may be in a different or backup computer installation in your organisation. There may be a copy on the developer's user account and may not have been sent to the production or live site or someone from head office has a copy to assess and try to resolve the situation. You may have success if phone those people or you could always talk to the installation computer operator or support staff and see if they have one on mag tape, CDROM or other backup storage.
| |
doc_2054
|
The result is my git clone fails.
_create_folder -path $destinationPath
"$NL Downloading clone of repository ...."
git clone $repoAddress $destinationPath
Dir $destinationPath
"$NL Trying a repository pull ...."
git pull $repoAddress
....
function _create_folder
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true)]
[string]$path = ""
)
Begin {}
Process
{
"$NL Creating $path ....."
if(!(Test-Path -Path $path)) {
New-Item -ItemType Directory -Path $path -Verbose:$true
}
Dir $path
}
}
| |
doc_2055
|
I'm using a custom RadioButton component, but having trouble resetting the value's for these once the timer is reset.
How do I reset the internal values (userOption) of the Radio Button, when the timer runs it's onExpire() method?
What's the best way to go about this? Do I need to restructure my code?
TIA
RadioButton Component
import React, { useState } from 'react';
import { View, Text, Pressable } from 'react-native';
import styles from './styles';
export default function RadioButton({ data, onSelect }) {
const [userOption, setUserOption] = useState(null);
const selectHandler = (value) => {
onSelect(value);
setUserOption(value);
};
return (
<View style={{flexDirection: "row"}}>
{data.map((item) => {
return (
<Pressable value={item.value} key={item.key} style={
[ (item.value === userOption ? styles.selected : styles.unselected),styles.baseStyles]
}
onPress={() => selectHandler(item.value)}
>
<Text style={styles.controlText}>{item.value}</Text>
</Pressable>
);
})}
</View>
);
}
Main App Code (excluding css)
import React, { useState, useRef, useEffect } from 'react';
import { StyleSheet, Text, View, SafeAreaView, TouchableHighlight, useWindowDimensions, StatusBar, Modal, ScrollView } from 'react-native';
import { useFonts} from '@expo-google-fonts/inter';
import { useTimer } from 'react-timer-hook';
import { AntDesign, Foundation } from '@expo/vector-icons';
import { Audio, Video } from 'expo-av';
import { SliderPicker } from 'react-native-slider-picker';
import { Slider, Box , NativeBaseProvider, extendTheme, Radio, Button,Pressable } from 'native-base';
//import EZSlider from './EZSlider.js';
import RadioButton from './RadioButton';
export default function App() {
const window = useWindowDimensions();
const [loaded] = useFonts({
/*Dont use dash in name */
DSDigital : require('./assets/fonts/DSDigital.ttf'),
LatoReg : require('./assets/fonts/Lato-Regular.ttf'),
});
function MyTimer({ expiryTimestamp }) {
const bgcolour = '#fef8ea';
const buttonColor = '#023e8a';
//color canvas
//egg black 181304
const [sound, setSound] = React.useState();
async function playSound() {
console.log('Loading Sound');
const { sound } = await Audio.Sound.createAsync(
require('./assets/alarm1.mp3')
);
setSound(sound);
console.log('Playing Sound');
await sound.playAsync(); }
React.useEffect(() => {
return sound
? () => {
console.log('Unloading Sound');
sound.unloadAsync(); }
: undefined;
}, [sound]);
const {
seconds,
minutes,
hours,
days,
isRunning,
start,
pause,
resume,
restart,
} = useTimer({ expiryTimestamp, autoStart: false, onExpire: () => {
//TO DO - check if stop or play button was pressed - exit
if(!userCancelled){
setModalVisible(!modalVisible);
console.log('timer expired') ;
playSound();
}
setDoneness(null);
setEggSize(null);
setTemp(null);
/*******RESET RADIO BUTTONS HERE***********/
}});
//initialTime: 220,
const [modalVisible, setModalVisible] = useState(false);
const buttonActiveOpacity = 0.9;
const buttonUnderlayColor = '#bed9f9';
//const [value, setValue] = React.useState('one');
const [state, setState] = React.useState(false);
const toggleState = () => {
setState(!state);
console.log('toggle State ran');
};
var time = new Date();
const timer_presets = [
{ key: '1', doneness: 'Soft', egg_size: 'S', temp:'Room Temp', time:'0:05' /*'3:10' */ },
{ key: '2', doneness: 'Soft', egg_size: 'M', temp:'Room Temp', time:'3:40' },
{ key: '3', doneness: 'Soft', egg_size: 'L', temp:'Room Temp', time:'4:10' },
{ key: '4', doneness: 'Soft', egg_size: 'XL', temp:'Room Temp', time:'4:30' },
{ key: '5', doneness: 'Medium', egg_size: 'S', temp:'Room Temp', time:'4:10' },
{ key: '6', doneness: 'Medium', egg_size: 'M', temp:'Room Temp', time:'4:40' },
{ key: '7', doneness: 'Medium', egg_size: 'L', temp:'Room Temp', time:'5:10' },
{ key: '8', doneness: 'Medium', egg_size: 'XL', temp:'Room Temp', time:'5:40' },
{ key: '9', doneness: 'Hard', egg_size: 'S', temp:'Room Temp', time:'8:00' },
{ key: '10', doneness: 'Hard', egg_size: 'M', temp:'Room Temp', time:'8:40' },
{ key: '11', doneness: 'Hard', egg_size: 'L', temp:'Room Temp', time:'9:30' },
{ key: '12', doneness: 'Hard', egg_size: 'XL', temp:'Room Temp', time:'10:20' },
{ key: '13', doneness: 'Soft', egg_size: 'S', temp:'Fridge', time:'4:00' },
{ key: '14', doneness: 'Soft', egg_size: 'M', temp:'Fridge', time:'4:40' },
{ key: '15', doneness: 'Soft', egg_size: 'L', temp:'Fridge', time:'5:20' },
{ key: '16', doneness: 'Soft', egg_size: 'XL', temp:'Fridge', time:'5:40' },
{ key: '17', doneness: 'Medium', egg_size: 'S', temp:'Fridge', time:'5:00' },
{ key: '18', doneness: 'Medium', egg_size: 'M', temp:'Fridge', time:'5:40' },
{ key: '19', doneness: 'Medium', egg_size: 'L', temp:'Fridge', time:'6:20' },
{ key: '20', doneness: 'Medium', egg_size: 'XL', temp:'Fridge', time:'6:50' },
{ key: '21', doneness: 'Hard', egg_size: 'S', temp:'Fridge', time:'8:50' },
{ key: '22', doneness: 'Hard', egg_size: 'M', temp:'Fridge', time:'9:40' },
{ key: '23', doneness: 'Hard', egg_size: 'L', temp:'Fridge', time:'10:40' },
{ key: '24', doneness: 'Hard', egg_size: 'XL', temp:'Fridge', time:'11:30' },
];
const [doneness, setDoneness] = useState();
const [eggsize, setEggSize] = useState();
const [temp, setTemp] = useState();
const [isReset, setisReset] = useState(false);
const [userCancelled, setUserCancelled] = useState(false);
//const [timerreset, setTimerreset] = useState(true);
function calcTime(doneness, eggsize, temp){
if(doneness == '' || eggsize == '' || temp == '')return;
console.log( "current params are: " + doneness + " " + eggsize + " " + temp)
//timer_presets
for(var i=0; i < timer_presets.length; i++){
//console.log(JSON.stringify(timer_presets[i].doneness, null, 2));
if(timer_presets[i].doneness == doneness && timer_presets[i].egg_size == eggsize && timer_presets[i].temp == temp ){
const timeparts = timer_presets[i].time.split(":");
var seconds = parseInt(timeparts[1]) + parseInt(timeparts[0]) * 60;
var time = new Date();
time.setSeconds(time.getSeconds() + seconds);
console.log('New time is: ' + timer_presets[i].time);
console.log('Seconds ' + seconds);
restart(time);
pause();
break;
}
}
}
return (
/*,borderWidth: 1, borderColor: 'black'*/
<NativeBaseProvider>
<View style={styles.container}>
<View style={styles.topHalfContainer}>
<View style={styles.timerDigitsContainer} >
<View style={styles.timerDigitsContainerV}>
<Text style={styles.timerNumbers}><Text style={styles.timerNumbers}>{String(hours).padStart(2, '0')}:{String(minutes).padStart(2, '0')}:{String(seconds).padStart(2, '0')}</Text></Text>
</View>
</View>
</View>
<View style={styles.bottomHalfContainer}>
<SafeAreaView style={{flex:1}}>
<ScrollView style={{flex:1}}>
<View><Text style={{ paddingVertical: 5, paddingHorizontal: 5, textAlign:'center'}}>Doneness</Text></View>
<View style={styles.container, {marginBottom: 10}}>
<RadioButton data={ [
{value: 'Soft', key: '1'},
{value: 'Medium', key: '2'},
{value: 'Hard', key: '3'}
] } onSelect={(value) => {
setDoneness(value);
calcTime(value, eggsize, temp);
}} />
</View>
<View><Text style={{ paddingVertical: 5, paddingHorizontal: 5, textAlign:'center'}}>Egg size</Text></View>
<View style={styles.container, {marginBottom: 10}}>
<RadioButton data={ [
{value: 'S', key: '1'},
{value: 'M', key: '2'},
{value: 'L', key: '3'},
{value: 'XL', key: '4'}
] } onSelect={(value) => {
setEggSize(value);
calcTime(doneness, value, temp);
}} />
</View>
<View><Text style={{ paddingVertical: 5, paddingHorizontal: 5, textAlign:'center'}}>Starting temp</Text></View>
<View style={styles.container, {marginBottom: 10}}>
<RadioButton data={ [
{value: 'Room Temp', key: '2'},
{value: 'Fridge', key: '3'}
] } onSelect={(value) => {
setTemp(value);
calcTime(doneness, eggsize, value);
}} />
</View>
<View style={{ /*borderColor:'black', borderWidth:1,*/ paddingHorizontal:30,paddingVertical:10, flex:1, alignItems:'center'}}>
{ !isRunning ?
<Pressable
disabled={(doneness == null || eggsize == null || temp == null) ? true : false}
style={[(doneness == null || eggsize == null || temp == null ? styles.disabled_style : null), styles.start_button]}
onPress={start}
><Text style={{color:'black',fontSize:30}}>Start</Text></Pressable>
:
<Pressable style={{borderRadius:30,paddingVertical:10,paddingHorizontal:70,backgroundColor:'#FCEBBF',color:'black', borderColor:'black', borderWidth:1 }}
onPress={() => {
var time = new Date();
restart(time);
setUserCancelled(true);
}}
><Text style={{color:'black',fontSize:30}}>Cancel</Text></Pressable>
}
</View>
</ScrollView>
</SafeAreaView>
</View>
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
Alert.alert("Modal has been closed.");
setModalVisible(!modalVisible);
}}
>
<View style={styles.centeredView}>
<View style={styles.modalView}>
<Text style={styles.modalText}>Time is up!</Text>
<TouchableHighlight activeOpacity={buttonActiveOpacity} underlayColor={buttonUnderlayColor}
style={[styles.button, styles.buttonClose]}
onPress={() => {
setModalVisible(!modalVisible);
sound.stopAsync();
}}
>
<Text style={styles.textStyle}>Dismiss</Text>
</TouchableHighlight>
</View>
</View>
</Modal>
</View>
</NativeBaseProvider>
);
}
if (!loaded) {
return null;
}
const time = new Date();
time.setSeconds(time.getSeconds());
return (
<SafeAreaView style={styles.container}>
<MyTimer expiryTimestamp={time} />
</SafeAreaView>
);
}
| |
doc_2056
|
I have yet to find a concise document on the minimum steps needed to generate a public key and private key using DSA, sign a byte[], and verify it.
The documentation from Oracle is too broken up and requires running across multiple JVMs.
A: I have successfully signed a byte array with a private key and verified it with a public key.
Example.
byte[] data = "hello.".getBytes();
/* Test generating and verifying a DSA signature */
try {
/* generate a key pair */
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
keyGen.initialize(1024, new SecureRandom());
KeyPair pair = keyGen.generateKeyPair();
/* create a Signature object to use
* for signing and verifying */
Signature dsa = Signature.getInstance("SHA/DSA");
/* initialize the Signature object for signing */
PrivateKey priv = pair.getPrivate();
dsa.initSign(priv);
/* Update and sign the data */
dsa.update(data);
/* Now that all the data to be signed
* has been read in, sign it */
byte[] sig = dsa.sign();
/* Verify the signature */
/* Initialize the Signature object for verification */
PublicKey pub = pair.getPublic();
dsa.initVerify(pub);
/* Update and verify the data */
dsa.update(data);
boolean verifies = dsa.verify(sig);
Assert.assertTrue(verifies);
} catch (Exception e) {
System.err.println("Caught exception " + e.toString());
}
In this version, I serialize the public key into a byte array and then create a PublicKey from that byte array.
byte[] data = "hello.".getBytes();
/* Test generating and verifying a DSA signature */
try {
/* generate a key pair */
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
keyGen.initialize(1024, new SecureRandom());
KeyPair pair = keyGen.generateKeyPair();
/* create a Signature object to use
* for signing and verifying */
Signature dsa = Signature.getInstance("SHA/DSA");
/* initialize the Signature object for signing */
PrivateKey priv = pair.getPrivate();
dsa.initSign(priv);
/* Update and sign the data */
dsa.update(data);
/* Now that all the data to be signed
* has been read in, sign it */
byte[] sig = dsa.sign();
/* Verify the signature */
/* Initialize the Signature object for verification */
PublicKey pub = pair.getPublic();
/* Encode the public key into a byte array */
byte[] encoded = pub.getEncoded();
/* Get the public key from the encoded byte array */
PublicKey fromEncoded = KeyFactory.getInstance("DSA", "SUN").generatePublic(new X509EncodedKeySpec(encoded));
dsa.initVerify(fromEncoded);
/* Update and verify the data */
dsa.update(data);
boolean verifies = dsa.verify(sig);
Assert.assertTrue(verifies);
} catch (Exception e) {
System.err.println("Caught exception " + e.toString());
}
| |
doc_2057
|
When I run Comment.last.user in the console, it returns the information pertaining to the user. However, when I run Comment.last.guide in the console, it returns nil. Something is going wrong with the creation of the comment.
The models all have the classic has_many and belongs_to relationships set up, so I'll omit those from here. Here is the comments controller:
class CommentsController < ApplicationController
before_action :set_comment, only: [:show, :edit, :update, :destroy]
# GET /comments
# GET /comments.json
def index
@comments = Comment.all
end
# GET /comments/1
# GET /comments/1.json
def show
end
# GET /comments/new
def new
@comment = Comment.new
end
# GET /comments/1/edit
def edit
end
# POST /comments
# POST /comments.json
def create
@comment = current_user.comments.build(comment_params)
respond_to do |format|
if @comment.save
format.html { redirect_to :back, notice: 'Comment was successfully created.' }
format.json { render action: 'show', status: :created, location: @comment }
else
format.html { render action: 'new' }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /comments/1
# PATCH/PUT /comments/1.json
def update
respond_to do |format|
if @comment.update(comment_params)
format.html { redirect_to @comment, notice: 'Comment was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
# DELETE /comments/1
# DELETE /comments/1.json
def destroy
@comment.destroy
respond_to do |format|
format.html { redirect_to comments_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_comment
@comment = Comment.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def comment_params
params.require(:comment).permit(:body, :user_id, :guide_id)
end
end
Here is the comments migration:
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.text :body
t.references :user, index: true
t.references :guide, index: true
t.timestamps
end
end
end
Log output when creating comment:
Started POST "/comments" for 127.0.0.1 at 2014-01-08 08:30:54 -0500
Processing by CommentsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"D2BvBIgU+tniZvr2NgQE/TpHY6J2xHOUm701jqTcJ9A=", "comment"=>{"body"=>"NitinJ Sample Comment", "user_id"=>"some value", "guide_id"=>"some value"}, "commit"=>"Create Comment"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
(0.1ms) begin transaction
SQL (21.7ms) INSERT INTO "comments" ("body", "created_at", "guide_id", "updated_at", "user_id") VALUES (?, ?, ?, ?, ?) [["body", "NitinJ Sample Comment"], ["created_at", Wed, 08 Jan 2014 13:30:54 UTC +00:00], ["guide_id", 0], ["updated_at", Wed, 08 Jan 2014 13:30:54 UTC +00:00], ["user_id", 1]]
(21.0ms) commit transaction
Redirected to http://localhost:3000/guides/1-attack
Completed 302 Found in 53ms (ActiveRecord: 43.1ms)
Started GET "/guides/1-attack" for 127.0.0.1 at 2014-01-08 08:30:54 -0500
Processing by GuidesController#show as HTML
Parameters: {"id"=>"1-attack"}
Guide Load (0.2ms) SELECT "guides".* FROM "guides" WHERE "guides"."id" = ? LIMIT 1 [["id", "1-attack"]]
CACHE (0.0ms) SELECT "guides".* FROM "guides" WHERE "guides"."id" = ? LIMIT 1 [["id", "1-attack"]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
Comment Load (0.2ms) SELECT "comments".* FROM "comments" WHERE "comments"."guide_id" = ? [["guide_id", 1]]
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
Rendered comments/_form.html.erb (6.6ms)
Rendered guides/show.html.erb within layouts/application (18.9ms)
DEPRECATION WARNING: Calling #sum with a block is deprecated and will be removed in Rails 4.1. If you want to perform sum calculation over the array of elements, use `to_a.sum(&block)`. (called from _app_views_layouts__navbar_html_erb__2351226726967046587_2202447400 at /Users/DylanRichards/Desktop/runescapeguides/app/views/layouts/_navbar.html.erb:35)
Guide Load (0.2ms) SELECT "guides".* FROM "guides" WHERE "guides"."user_id" = ? [["user_id", 1]]
(0.2ms) SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ? AND "votes"."vote_flag" = 't' AND "votes"."vote_scope" IS NULL [["votable_id", 1], ["votable_type", "Guide"]]
(0.2ms) SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ? AND "votes"."vote_flag" = 'f' AND "votes"."vote_scope" IS NULL [["votable_id", 1], ["votable_type", "Guide"]]
Rendered layouts/_navbar.html.erb (7.4ms)
Completed 200 OK in 54ms (Views: 47.8ms | ActiveRecord: 1.5ms)
Second log output
Started POST "/guides/1-attack/comments" for 127.0.0.1 at 2014-01-08 08:52:29 -0500
Processing by CommentsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"D2BvBIgU+tniZvr2NgQE/TpHY6J2xHOUm701jqTcJ9A=", "comment"=>{"body"=>"Another sample NitinJ comment.", "user_id"=>"some value", "guide_id"=>"some value"}, "commit"=>"Create Comment", "guide_id"=>"1-attack"}
Completed 500 Internal Server Error in 69ms
NoMethodError (undefined method `[]=' for nil:NilClass):
app/controllers/comments_controller.rb:27:in `create'
Rendered /Users/DylanRichards/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.2/lib/action_dispatch/middleware/templates/rescues/_source.erb (1.0ms)
Rendered /Users/DylanRichards/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.2/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.7ms)
Rendered /Users/DylanRichards/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.2/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.5ms)
Rendered /Users/DylanRichards/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.2/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (21.7ms)
A: try this <%= f.association :guide, :as => :hidden, :input_html => { :value => @guide.id }%>
| |
doc_2058
|
<button onClick= "<%helper.openNav()%>" class = "bro"> Click me </button>
Here is the function inside the helper.js file:
function openNav(){
console.log('hello')
}
;
module.exports = {
openNav: openNav,
}
| |
doc_2059
|
Not sure if this matter, but the only thing that I did in Eclipse other than installing the Groovy/Grails plugin is to also install support for the Groovy 2.1 compiler.
A: Everything in 2.3 is forked by default, so there's one JVM that you start, and it has the Ant jars and other stuff that's needed to start Grails, but that pollutes the JVM unnecessarily. The 2nd JVM that the first process starts is lighter-weight with only the jars that the app depends on, i.e. the Grails, Spring, Hibernate, etc. jars. But this is a tricky thing to do, and unfortunately Windows doesn't get much testing during development because the Grails developers get to choose which OS to use (unlike a lot of Grails users who often have Windows forced on them) and Windows is not chosen - it's all Mac and Linux.
I haven't followed this closely because it was quite buggy early on and I'm now in the habit of just disabling forking any time I create an app. There's probably a better approach, but I delete the grails.project.fork property from BuildConfig.groovy. You can comment it out, or disable forking for a particular launch type ("run", "test", etc.) but deleting the whole block disables it across the board and I find that things work well after that.
| |
doc_2060
|
[{"name": "name1", "value": "value1"}, {"name": "name2", "value": "value2"}]
I would like to remove only those elements from that list which do contains specific name. For example with:
blacklist = "name2"
I should get the same dataframe, with all the columns including request_headers, but it's value (based on the example above) should be:
[{"name": "name1", "value": "value1"}]
How to achieve it ? I've tried first to explode, then filter, but was not able to "implode" correctly.
Thanks,
A: Exploding is expensive, rather us a list comprehension:
blacklist = "name2"
df['request_headers'] = [[d for d in l if 'name' in d and d['name'] != blacklist]
for l in df['request_headers']]
Output:
request_headers
0 [{'name': 'name1', 'value': 'value1'}]
A: can use a .apply function:
blacklist = 'name2'
df['request_headers'] = df['request_headers'].apply(lambda x: [d for d in x if blacklist not in d.values()])
A: df1=pd.DataFrame([{"name": "name1", "value": "value1"}, {"name": "name2", "value": "value2"}])
blacklist = "name2"
col1=df1.name.eq(blacklist)
df1.loc[col1]
out:
name value
1 name2 value2
| |
doc_2061
|
As part of the app, I'm trying to develop a mana bar like component. Clicking a button costs mana, and the mana refills over time. If there is not enough mana, the user cannot click the button.
My question is, how do I sync the mana bar with the back-end? I need the back-end to keep track of the users mana, so a user can't bypass the front-end and send a frame anyway, but I also don't want any lag that would be caused by the back-end sending the front-end "eligable to be clicked" signals
This leads me to believe that the best way to achieve this is for both the front-end and the back-end to keep track of mana separately, but I feel like slight differences over time could cause the two to be very out of sync with each other over time.
A: Keep track of the player's mana on the backend. This is your system-of-record.
Also keep track of the player's mana on the frontend, including the regneration-over-time parameters. Whenever the client and server communicate, the server's response should include any updates to the game state, including mana. This should correct any drift that occurs over time in the regeneration algorithm.
This was answered fairly well on the gamedev stackexchange:
https://gamedev.stackexchange.com/questions/84402/mmo-client-server-architecture-nosql
A: I would suggest not contacting the server for this at all.
Keep track of mana on the client side, and only allow the user to click a button if there is enough mana. If this is some sort of game app, and other users need to be able to see how much mana you have, then simply send that up to the server every update.
For example:
Client Server
user clicks button
user has no mana -------> update server with mana=0
nothing happens
mana increases -------> update server with mana=20
user clicks button
mana is spent -------> update server with mana=5
perform button action ----> update server action performed
nowhere did you have to wait for the server, yet it is still being updated with current information
As for security/game hacking concerns, you will need to look into methods of securing javascript games: Prevent Javascript games tweaking/hacking
| |
doc_2062
| ||
doc_2063
|
//Add change handler for the task completion date.
dateCompletion.addValueChangeHandler(new ValueChangeHandler<java.util.Date>() {
public void onValueChange(ValueChangeEvent<java.util.Date> event) {
//TODO currentRow = flexAwardDescription.getRowIndex();
//Display all YM who have not completed this task.
AsyncCallback<List<YouthMember>> callback = new YMWithoutAwardHandler<List<YouthMember>>(CubBulkAward3View.this);
rpc.getYMWithoutAwardList(ymAwardDetails.getad_Id(), callback);
}
});
I have found an answer for click event; however, not for change event.
A: Please check my answer here: Gwt getCellForEvent flexTable
There's no obvious way to do it, what you can do is
*
*Get event source
*Cast it to widget
*Get it's Element via .getElement() then use getParent() to get Cell, and getParent() one more time to get row element.
You can get it's index then, comparing it to rows from rowFormatter in a loop.
A: The work around I came up with is to capture row number on the click event (as you must first click before you can change) and then use this row number if a change event occurs.
//Get the row number of the row selected to display the names below it.
flexAwardDescription.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
currentRow = flexAwardDescription.getCellForEvent(event).getRowIndex();
}
});
//Add change handler for the task completion date.
dateCompletion.addValueChangeHandler(new ValueChangeHandler<java.util.Date>() {
public void onValueChange(ValueChangeEvent<java.util.Date> event) {
//Check if this is the completion row
if (ymAwardDetails.getad_Description().matches("(.*)Completed:(.*)")) {
groupCompleted = "C";
}else{
groupCompleted = "S";
}
awardDescriptionID = ymAwardDetails.getad_Id();
//Display all YM who have not completed this task.
AsyncCallback<List<YouthMember>> callback = new YMWithoutAwardHandler<List<YouthMember>>(CubBulkAward3View.this);
rpc.getYMWithoutAwardList(ymAwardDetails.getad_Id(), accountId, callback);
}
});
| |
doc_2064
|
My question is how do I see what the registered shutdown hooks are? I want to iterate them and then call the remove method. The collection holding the hooks is private static and doesn't contain an accessor. We've tried reflection but since the class is package private we have to make our cracker part of java.lang which is a prohibited package.
Any ideas?
/*
* %W% %E%
*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
class ApplicationShutdownHooks {
static {
Shutdown.add(1 /* shutdown hook invocation order */,
new Runnable() {
public void run() {
runHooks();
}
});
}
/* The set of registered hooks */
private static IdentityHashMap<Thread, Thread> hooks = new IdentityHashMap<Thread, Thread>();
private void ApplicationShutdownHooks() {}
/* Add a new shutdown hook. Checks the shutdown state and the hook itself,
* but does not do any security checks.
*/
static synchronized void add(Thread hook) {
if(hooks == null)
throw new IllegalStateException("Shutdown in progress");
if (hook.isAlive())
throw new IllegalArgumentException("Hook already running");
if (hooks.containsKey(hook))
throw new IllegalArgumentException("Hook previously registered");
hooks.put(hook, hook);
}
/* Remove a previously-registered hook. Like the add method, this method
* does not do any security checks.
*/
static synchronized boolean remove(Thread hook) {
if(hooks == null)
throw new IllegalStateException("Shutdown in progress");
if (hook == null)
throw new NullPointerException();
return hooks.remove(hook) != null;
}
/* Iterates over all application hooks creating a new thread for each
* to run in. Hooks are run concurrently and this method waits for
* them to finish.
*/
static void runHooks() {
Collection<Thread> threads;
synchronized(ApplicationShutdownHooks.class) {
threads = hooks.keySet();
hooks = null;
}
for (Thread hook : threads) {
hook.start();
}
for (Thread hook : threads) {
try {
hook.join();
} catch (InterruptedException x) { }
}
}
}
A: Package private shouldn't slow you down, this is Reflection! All sorts of voodoo magic are allowed.
In this case, you need to get the class, then the field, then set it to accessible, then read its value.
Class clazz = Class.forName("java.lang.ApplicationShutdownHooks");
Field field = clazz.getDeclaredField("hooks");
field.setAccessible(true);
Object hooks = field.get(null);
System.out.println(hooks); //hooks is a Map<Thread, Thread>
A simpler way to view this sort of information might just be to take a heap dump of the application and analyze it in a memory analyzer like MAT (for Eclipse) or JProfiler.
| |
doc_2065
|
This: doesn't work:
ng-init='tables=!{JSON.stringify(tables)}'
This: expands but,
ng-init='tables=#{JSON.stringify(tables)}'
the output is unescaped and filled with "s
ng-init="tables={"12":{"id":....
and the view isn't updated in either of the cases. This article implies that first one should work, but like I said, it doesn't even expand,
ng-init='tables=!{JSON.stringify(tables)}'
in source code shows up exactly the same in the HTML source
ng-init='tables=!{JSON.stringify(tables)}'
A: Actually, the #{...} approach seems to work fine.
It is probably the way console.log prints attributes' values that confused you.
ng-init="tables=#{JSON.stringify(tables)}"
Take a look at this short demo.
A: In what use-case you want to pass data directly from Jade to angular? I think you could to this job in controller like this :
$scope.init = function () {
// init stuff
}
...and in your view :
ng-init = init()
| |
doc_2066
|
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
And it seems to me that first of all I must find out what is context. Documentation explanation looks too complicated and doesn't even give its definition, so I can't understand what it is and what's its purpose.
A: It states in the first sentence with the headline Context objects: "A window object encapsulates both a top-level window and an OpenGL or OpenGL ES context."
So it will be an OpenGL/OpenGL ES context. The functions set the OpenGL/OpenGL ES version requirement for that context the window will create when you create the window.
In your example above GLFW will try to create an OpenGL 3.3 context for that window.
| |
doc_2067
|
This is\ta test.
^^^^^^^^^^^^^^^^
I get an output like this:
This is
^^^^^^^^^^^
This is the solution I've written, and I'm almost certain it should work; it makes sense logically, but there's something that just isn't adding up.
#include <stdio.h>
#define MAX_SIZE 1000
#define TAB_STOP 4
char line[MAX_SIZE];
int getline_(void);
int main()
{
int c, len;
extern char longest[];
while ((len = getline_()) > 0)
printf("Line: %s", line);
return 0;
}
int getline_(void)
{
int chr, index;
extern char line[];
int x;
for (index = 0; index < (MAX_SIZE - 1)
&& ((chr = getchar()) != EOF) && chr != '\n'; ++index) {
if (chr == '\t') {
for (x = 0; x < TAB_STOP && index < MAX_SIZE - 5; ++x) {
line[index + x] = ' ';
printf("%d\n", index);
}
index = index + x;
}
else
line[index] = chr;
}
if (chr == '\n') {
line[index] = chr;
++index;
}
line[index] = '\0';
return index;
}
A: In the case where chr == '\t' you are incrementing index twice:
*
*the first time with index = index + x;
*the second time within the for statement ++index
An easy, dirty, trick would be to change the first increment to index = index + x - 1;.
I fully agree with @Sneftel that it would be better to only increment index with the correct value. That means not increment it within a for statement. And do the increment once in each alternative of the if… else blocks with the right value.
| |
doc_2068
|
Instead of transitioning smoothly to the next slide, as it does for each of the first 12 slides, each slide after the 12th transitions by going all the way back to the first slide and then sliding all the way to the slides past 12.
Any clue why this is happening, or how I can resolve it apart from using only 12 slides? I've seen it work on other sites with more than 12 items, so it must be an issue with my implementation.
EDIT: I'm seeing the behavior on Chrome (newest build)
EDIT2: to clarify, I see the behavior not just on Chrome, but also on Safari and Firefox.
A: Upgrade jQuery from your current use of 1.4 (latest) to 1.5.2:
Change line 33 (in the rendered HTML):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
To this
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
| |
doc_2069
|
http://screencast.com/t/VpSPRsr1Jkss
I understand that is a limitation of canvas rendering - but it seems like this is is a really simple thing to do - rotate a cube that has an image on one face without the distortion.
Is there another canvas library or approach i can take? I was really looking forward to using Three.js for animating some logos and other elemnets - but we can't have distortion like that in a logo or a customer facing landing page.
Thanks for reading, I'm open to suggestions here.
I don't accept increasing the complexity of the face as a solution because that just distributes the distortion through out the face. I really just want to render the image to a flat surface and be able to rotate that object.
A: The distortion you see is because only two triangles make that plane.
A quick fix is to have more detailed plane.
If you are using PlaneGeometry, increase the number of segments.
If you are using CubeGeometry, increase the number of segments on the plane you need (2 out of 3).
It will take a bit of fiddling to find the best balance between a decent look and optimal performance (as more segments will require more computing). Hopefully for simple scene you'll get away with no major delays.
| |
doc_2070
|
MasterTestSuite.html
- ComponentTestSuite.html
- TestCase1.html
- TestCase2.html
- OtherComponentTestSuite.html
- TestCase3.html
- TestCase4.html
I NEED to be able to achieve something equivalent to this. I have started to try an Include extension, which allows me to include the contents of another test case, but I am running into problems with it. How have you achieved this? What advice can you give on how to help me achieve this?
A: This might not be an explicit answer, but I played with Selenium IDE for 3 months. Then I found out that WebDriver is so much more powerful. Your situation is a piece of cake with Selenium WebDriver. The more complex the logic, the better off you are using source code instead of a GUI interface to define your workflows. The input and output parameters can get very confusing if not documented properly. And they can break very easily if they upgrade Selenium IDE. The Selenium IDE is very good at showing a novice programmer how to automate a workflow with a recorder, but if you are a programmer, it'll hold you back.
However, if you really want to accomplish your situation, you can develop your own custom JavaScript function that calls other functions (or other test cases).
A: As far as I know, Selenium IDE does not support this. The way most people do this is to create the individual test suites and run them individually.
I do this in C#/NUnit by creating a *.cs file for each main area and then setting categories for each of the tests to get the extra granularity
e.g.
namespace Test.The.World
{
[TestFixture]
public class UK
{
[Test]
[Category("Southern Counties")]
public void Sussex_Brighton(){
.....
}
[Test]
[Category("Southern Counties")]
public void Hampshire_Southampton(){
.....
}
}
}
And then use the NUnit functionality to run tests accordingly.
I am sure most frameworks for most languages have this kind of feature
A: I'm using model based testing together with Selenium on a daily basis and with a model you can put the logic how the tests should be executed and as well the tests its self.
There are some Open Source/Free Software "robots" like http://www.xqual.com/ XStudio. I have tried it a bit and does the work but quite messy to work with but good if your test environment does not change to often. You can here put start automatic executions at a daily basis etc and does report back the results.
Cheers,
Stefan
A: I have a few dozen test suites built in Selenium IDE to assist with testing my Store Locator Plus WordPress plugin. Sometimes I need to run a single Selenium test suite. However when I release a new version of the base plugin I want to run a dozen test suites one-after-another.
While not a perfect fit for your use case of creating several "master suites", I did find a pair of Selenium IDE plugins that allow me to create a single "favorites list of suites" and run all of my favorites back-to-back.
It may be possible to investigate & modify the plugin JavaScript to create several different "favorites lists" that may suit your needs. In the meantime you can get at least one "master list of suites" by combining these Selenium IDE add-ons:
*
*Favorites plugin for Selinium IDE
*Extension Sequencer for Selenium IDE (needed for Run All)
*Run All Favorites for Selenium IDE
After installing each of these add-ons (technically Mozilla Firefox plugins) you will see a favorites button inside the Selenium IDE interface. Mark your favorite suites and you will have your "list". You can now select "Favorites / Run All" from the Selenium IDE menu.
You may want to be careful about the sequence in which you mark your favorites. I marked them in the order I wanted them to run. Open test suite #1, favorite, test suite #2 favorite etc. then "run all". Worked great and shows me the total run count and fail count across all suites (and thus tests) that were executed. The log, sadly, appears to be reset at each suite however.
A: You need SeleniumRC and some programming language tool to write and run tests.
SeleniumIDE allow to save test in several languages (C#, JAVA, PHP, Python and etc.)
Use one you familiar with.
Also with out SetUp and TearDown it is difficult to do good tests. Selenium IDE does not allow these methods.
A: This should be there in mainsuite.
public static Test suite() {
TestSuite testSuite = new TestSuite();
testSuite.addTest(ComponentTestSuite1.suite());
testSuite.addTest(OtherComponentTestSuite2.suite());
}
| |
doc_2071
|
Start-Process -FilePath "$Installer_Path" -Args '/s /v"/qb SETUPTYPE=\"$Setup_type\" USERNAME=$user_name PASSWORD=$password SERVER=$sql_server INSTALLDIR=\"$Transfer_Path\\\" SHAREPATH=\"$Transfer_Path\\\""' –Wait
In the above command the variable are not getting replaced except $Installer_Path. I believe issue is because of variables located inside ' " " '. Could any one help me with the variable substitution?
Thanks.
A: The problem is that you are using single quotes and not double quotes. In order for your variables to expand you need to use double quotes. If you have to use double quotes inside of those you can escape them by preceding them with a backtick ` or by doubling them up "".
Start-Process -FilePath "$Installer_Path" -Args "/s /v`"/qb SETUPTYPE=\`"$Setup_type\`" USERNAME=$user_name PASSWORD=$password SERVER=$sql_server INSTALLDIR=\`"$Transfer_Path\\\`" SHAREPATH=\`"$Transfer_Path\\\`"`"" –Wait
| |
doc_2072
|
I don't know why this happened . Thanks for any answer .
cshtml code :
<ul style="text-align: center; list-style-type: none; vertical-align: top;">
<li>
@foreach (var item in Model.SocialNetworks)
{
<ul class="list-inline" style="text-align:center;list-style-type:none;padding-top:15px;">
<li class="col-xs-3">
<a class="aFooter" href="@item.SocialLink">
<img class="img-responsive center-block socialIcon" src="@Url.Content(item.SocialIcon.ToString())" />
</a>
</li>
</ul>
}
</li>
</ul>
Result :
A: Try float left to li element
ie, li{ float: left;}
A: Remove the padding-top: 15px; at the inside <li> tag.
With running fiddle.
| |
doc_2073
|
<div ng-controller="myController" class="container-fluid">
<div class="row clear-fix">
<div ng-repeat="product in shop" class="col-md-4">
<div class="panel-heading">
<h1>{{product.name}}</h1>
</div>
<div class="panel-body">
<div>
<img ng-repeat="image in product.images" ng-src='{{image.full}}' />
</div>
<h2>{{product.price | currency}}</h2>
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#exampleModal">More Details</button>
<div class="modal fade" id="exampleModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{product.name}}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>{{product.description}}</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary">Purchase</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
| |
doc_2074
|
To check that @Cacheable gets picked up, I'm using the name of a non-existing cache manager. The regular run-time behavior is that an exception is thrown. But in this case, no exception is being thrown, which suggests that the @Cacheable annotation isn't being applied to the intercepting object.
/* { package, some more imports... } */
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.cache.annotation.Cacheable;
@Aspect
public class GetPropertyInterceptor
{
@Around( "call(* *.getProperty(..))" )
@Cacheable( cacheManager = "nonExistingCacheManager", value = "thisShouldBlowUp", key = "#nosuchkey" )
public Object intercepting( ProceedingJoinPoint pjp ) throws Throwable
{
Object o;
/* { modify o } */
return o;
}
}
Given that my Aspect is working already, how can I make @Cacheable work on top of it?
A: You can achieve similar results, by using Spring regular dependency injection mechanism and inject a org.springframework.cache.CacheManager into your aspect:
@Autowired
CacheManager cacheManager;
Then you can use the cache manager in the around advice:
@Around( "call(* *.getProperty(..))" )
public Object intercepting( ProceedingJoinPoint pjp ) throws Throwable
{
Cache cache = cacheManager.getCache("aopCache");
String key = "whatEverKeyYouGenerateFromPjp";
Cache.ValueWrapper valueWrapper = cache.get(key);
if (valueWrapper == null) {
Object o;
/* { modify o } */
cache.put(key, o);
return o;
}
else {
return valueWrapper.get();
}
}
| |
doc_2075
|
import xmltodict
data = """<node1>
<node2 id='test'><![CDATA[test]]></node2>
<node3 id='test'>test</node3>
</node1>"""
data = xmltodict.parse(data,force_cdata=True, encoding='utf-8')
print data
print xmltodict.unparse(data, pretty=True)
And this is the output:
OrderedDict([(u'node1', OrderedDict([(u'node2', OrderedDict([(u'@id', u'test'), ('#text', u'test')])), (u'node3', OrderedDict([(u'@id', u'test'), ('#text', u'test')]))]))])
<?xml version="1.0" encoding="utf-8"?>
<node1>
<node2 id="test">test</node2>
<node3 id="test">test</node3>
</node1>
We can see here that the CDATA is missing in the generated node2, and also node2 is the same as node3. However, in the input the nodes are different.
Regards
A: I want to clarify that there is no officially supported way to keep the CDATA section.
You could check the issue here.
Based on the above facts, you need DIY. There are two approaches:
Firstly, let's create some helper functions.
def cdata(s):
return '<![CDATA[' + s + ']]>'
def preprocessor(key, value):
'''Unneccessary if you've manually wrapped the values. For example,
xmltodict.unparse({
'node1': {'node2': '<![CDATA[test]]>', 'node3': 'test'}
})
'''
if key in KEEP_CDATA_SECTION:
if isinstance(value, dict) and '#text' in value:
value['#text'] = cdata(value['#text'])
else:
value = cdata(value)
return key, value
*
*Unescaping the escaped XML
import xmltodict
from xml.sax.saxutils import unescape
KEEP_CDATA_SECTION = ['node2']
out_xml = xmltodict.unparse(data, preprocessor=preprocessor)
out_xml = unescape(out_xml) # not safe !
You shall not try it on the untrusted data, cuz this approach not only unescapes the character data but also unescapes the nodes' attributes.
*Subclassing XMLGenerator
To alleviate the safety problem of unescape() , we could remove the escape() call in XMLGenerator so that there is no need to unescape the XML again.
class XMLGenerator(xmltodict.XMLGenerator):
def characters(self, content):
if content:
self._finish_pending_start_element()
self._write(content) # also not safe, but better !
xmltodict.XMLGenerator = XMLGenerator
It is not a hack, so it won't change the rest behavior of xmltodict other than unparse() . More importantly, it won't pollute the built-in library xml .
For one-line fans.
xmltodict.XMLGenerator.characters = xmltodict.XMLGenerator.ignorableWhitespace # now, it is a hack !
Even more, you can wrap the character data directly in XMLGenerator like the following.
class XMLGenerator(xmltodict.XMLGenerator):
def characters(self, content):
if content:
self._finish_pending_start_element()
self._write(cdata(content))
From now on, every nodes having character data will keep the CDATA section.
A: I finally managed to get it working by performing this monkey-patch. I am still not very happy with it, It's really a 'hack' this feature should be included somewhere properly:
import xmltodict
def escape_hacked(data, entities={}):
if data[0] == '<' and data.strip()[-1] == '>':
return '<![CDATA[%s]]>' % data
return escape_orig(data, entities)
xml.sax.saxutils.escape = escape_hacked
and then run your python code normally:
data = """<node1>
<node2 id='test'><![CDATA[test]]></node2>
<node3 id='test'>test</node3>
</node1>"""
data = xmltodict.parse(data,force_cdata=True, encoding='utf-8')
print data
print xmltodict.unparse(data, pretty=True)
To explain, the following line detect if the data is a valid XML, then it add the CDATA tag arround it:
if data[0] == '<' and data.strip()[-1] == '>':
return '<![CDATA[%s]]>' % data
Regards
| |
doc_2076
|
u4/07/03 11:37:41 ERROR Remoting: Remoting error: [Startup failed] [
akka.remote.RemoteTransportException: Startup failed
at akka.remote.Remoting.akka$remote$Remoting$$notifyError(Remoting.scala:129)
at akka.remote.Remoting.start(Remoting.scala:194)
at akka.remote.RemoteActorRefProvider.init(RemoteActorRefProvider.scala:184)
at akka.actor.ActorSystemImpl._start$lzycompute(ActorSystem.scala:579)
at akka.actor.ActorSystemImpl._start(ActorSystem.scala:577)
at akka.actor.ActorSystemImpl.start(ActorSystem.scala:588)
at akka.actor.ActorSystem$.apply(ActorSystem.scala:111)
at akka.actor.ActorSystem$.apply(ActorSystem.scala:104)
at org.apache.spark.util.AkkaUtils$.createActorSystem(AkkaUtils.scala:96)
at org.apache.spark.SparkEnv$.create(SparkEnv.scala:126)
at org.apache.spark.SparkContext.<init>(SparkContext.scala:139)
at shark.SharkContext.<init>(SharkContext.scala:42)
at shark.SharkEnv$.initWithSharkContext(SharkEnv.scala:90)
at com.datastax.bdp.spark.SparkILoop.createSparkContext(SparkILoop.scala:41)
at $line3.$read$$iwC$$iwC.<init>(<console>:10)
at $line3.$read$$iwC.<init>(<console>:32)
at $line3.$read.<init>(<console>:34)
at $line3.$read$.<init>(<console>:38)
at $line3.$read$.<clinit>(<console>)
at $line3.$eval$.<init>(<console>:7)
at $line3.$eval$.<clinit>(<console>)
at $line3.$eval.$print(<console>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.spark.repl.SparkIMain$ReadEvalPrint.call(SparkIMain.scala:772)
at org.apache.spark.repl.SparkIMain$Request.loadAndRun(SparkIMain.scala:1040)
at org.apache.spark.repl.SparkIMain.loadAndRunReq$1(SparkIMain.scala:609)
at org.apache.spark.repl.SparkIMain.interpret(SparkIMain.scala:640)
at org.apache.spark.repl.SparkIMain.interpret(SparkIMain.scala:604)
at org.apache.spark.repl.SparkILoop.reallyInterpret$1(SparkILoop.scala:793)
at org.apache.spark.repl.SparkILoop.interpretStartingWith(SparkILoop.scala:838)
at org.apache.spark.repl.SparkILoop.command(SparkILoop.scala:750)
at com.datastax.bdp.spark.SparkILoop$$anonfun$initializeSparkContext$1.apply(SparkILoop.scala:66)
at com.datastax.bdp.spark.SparkILoop$$anonfun$initializeSparkContext$1.apply(SparkILoop.scala:66)
at org.apache.spark.repl.SparkIMain.beQuietDuring(SparkIMain.scala:258)
at com.datastax.bdp.spark.SparkILoop.initializeSparkContext(SparkILoop.scala:65)
at com.datastax.bdp.spark.SparkILoop.initializeSpark(SparkILoop.scala:47)
at org.apache.spark.repl.SparkILoop$$anonfun$process$1$$anonfun$apply$mcZ$sp$5.apply$mcV$sp(SparkILoop.scala:908)
at org.apache.spark.repl.SparkILoopInit$class.runThunks(SparkILoopInit.scala:140)
at org.apache.spark.repl.SparkILoop.runThunks(SparkILoop.scala:53)
at org.apache.spark.repl.SparkILoopInit$class.postInitialization(SparkILoopInit.scala:102)
at org.apache.spark.repl.SparkILoop.postInitialization(SparkILoop.scala:53)
at org.apache.spark.repl.SparkILoop$$anonfun$process$1.apply$mcZ$sp(SparkILoop.scala:925)
at org.apache.spark.repl.SparkILoop$$anonfun$process$1.apply(SparkILoop.scala:881)
at org.apache.spark.repl.SparkILoop$$anonfun$process$1.apply(SparkILoop.scala:881)
at scala.tools.nsc.util.ScalaClassLoader$.savingContextLoader(ScalaClassLoader.scala:135)
at org.apache.spark.repl.SparkILoop.process(SparkILoop.scala:881)
at org.apache.spark.repl.SparkILoop.process(SparkILoop.scala:973)
at com.datastax.bdp.spark.SparkReplMain$.main(SparkReplMain.scala:22)
at com.datastax.bdp.spark.SparkReplMain.main(SparkReplMain.scala)
Caused by: org.jboss.netty.channel.ChannelException: Failed to bind to: /54.xx.xx.xx:0
at org.jboss.netty.bootstrap.ServerBootstrap.bind(ServerBootstrap.java:272)
at akka.remote.transport.netty.NettyTransport$$anonfun$listen$1.apply(NettyTransport.scala:391)
at akka.remote.transport.netty.NettyTransport$$anonfun$listen$1.apply(NettyTransport.scala:388)
at scala.util.Success$$anonfun$map$1.apply(Try.scala:206)
at scala.util.Try$.apply(Try.scala:161)
at scala.util.Success.map(Try.scala:206)
at scala.concurrent.Future$$anonfun$map$1.apply(Future.scala:235)
at scala.concurrent.Future$$anonfun$map$1.apply(Future.scala:235)
at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:32)
at akka.dispatch.BatchingExecutor$Batch$$anonfun$run$1.processBatch$1(BatchingExecutor.scala:67)
at akka.dispatch.BatchingExecutor$Batch$$anonfun$run$1.apply$mcV$sp(BatchingExecutor.scala:82)
at akka.dispatch.BatchingExecutor$Batch$$anonfun$run$1.apply(BatchingExecutor.scala:59)
at akka.dispatch.BatchingExecutor$Batch$$anonfun$run$1.apply(BatchingExecutor.scala:59)
at scala.concurrent.BlockContext$.withBlockContext(BlockContext.scala:72)
at akka.dispatch.BatchingExecutor$Batch.run(BatchingExecutor.scala:58)
at akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:42)
at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:386)
at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
Caused by: java.net.BindException: Cannot assign requested address
at sun.nio.ch.Net.bind0(Native Method)
at sun.nio.ch.Net.bind(Net.java:444)
at sun.nio.ch.Net.bind(Net.java:436)
at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:214)
at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
at org.jboss.netty.channel.socket.nio.NioServerBoss$RegisterTask.run(NioServerBoss.java:193)
at org.jboss.netty.channel.socket.nio.AbstractNioSelector.processTaskQueue(AbstractNioSelector.java:366)
at org.jboss.netty.channel.socket.nio.AbstractNioSelector.run(AbstractNioSelector.java:290)
at org.jboss.netty.channel.socket.nio.NioServerBoss.run(NioServerBoss.java:42)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
]
org.jboss.netty.channel.ChannelException: Failed to bind to: /54.xxx.xxx.xxx.xxx:0
at org.jboss.netty.bootstrap.ServerBootstrap.bind(ServerBootstrap.java:272)
at akka.remote.transport.netty.NettyTransport$$anonfun$listen$1.apply(NettyTransport.scala:391)
at akka.remote.transport.netty.NettyTransport$$anonfun$listen$1.apply(NettyTransport.scala:388)
at scala.util.Success$$anonfun$map$1.apply(Try.scala:206)
at scala.util.Try$.apply(Try.scala:161)
at scala.util.Success.map(Try.scala:206)
at scala.concurrent.Future$$anonfun$map$1.apply(Future.scala:235)
at scala.concurrent.Future$$anonfun$map$1.apply(Future.scala:235)
at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:32)
at akka.dispatch.BatchingExecutor$Batch$$anonfun$run$1.processBatch$1(BatchingExecutor.scala:67)
at akka.dispatch.BatchingExecutor$Batch$$anonfun$run$1.apply$mcV$sp(BatchingExecutor.scala:82)
at akka.dispatch.BatchingExecutor$Batch$$anonfun$run$1.apply(BatchingExecutor.scala:59)
at akka.dispatch.BatchingExecutor$Batch$$anonfun$run$1.apply(BatchingExecutor.scala:59)
at scala.concurrent.BlockContext$.withBlockContext(BlockContext.scala:72)
at akka.dispatch.BatchingExecutor$Batch.run(BatchingExecutor.scala:58)
at akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:42)
at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:386)
at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
Caused by: java.net.BindException: Cannot assign requested address
at sun.nio.ch.Net.bind0(Native Method)
at sun.nio.ch.Net.bind(Net.java:444)
at sun.nio.ch.Net.bind(Net.java:436)
at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:214)
at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
at org.jboss.netty.channel.socket.nio.NioServerBoss$RegisterTask.run(NioServerBoss.java:193)
at org.jboss.netty.channel.socket.nio.AbstractNioSelector.processTaskQueue(AbstractNioSelector.java:366)
at org.jboss.netty.channel.socket.nio.AbstractNioSelector.run(AbstractNioSelector.java:290)
at org.jboss.netty.channel.socket.nio.NioServerBoss.run(NioServerBoss.java:42)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
Type in expressions to have them evaluated.
Type :help for more information.
scala>
==========================================================================================
And my configuration in spark-env.sh
export SPARK_HOME="/usr/share/dse/spark"
export SPARK_MASTER_IP=54.xx.xx.xx (public IP)
export SPARK_MASTER_PORT=7077
export SPARK_MASTER_WEBUI_PORT=7080
export SPARK_WORKER_WEBUI_PORT=7081
export SPARK_WORKER_MEMORY="4g"
export SPARK_MEM="2g"
export SPARK_REPL_MEM="2g"
export SPARK_CONF_DIR="/etc/dse/spark"
export SPARK_TMP_DIR="$SPARK_HOME/tmp"
export SPARK_LOG_DIR="$SPARK_HOME/logs"
export SPARK_LOCAL_IP=54.xx.xx.xx (public IP)
export SPARK_COMMON_OPTS="$SPARK_COMMON_OPTS -Dspark.kryoserializer.buffer.mb=10 "
export SPARK_MASTER_OPTS=" -Dspark.deploy.defaultCores=1 - Dspark.local.dir=$SPARK_TMP_DIR/master -Dlog4j.configuration=file://$SPARK_CONF_DIR/log4j- server.properties -Dspark.log.file=$SPARK_LOG_DIR/master.log "
export SPARK_WORKER_OPTS=" -Dspark.local.dir=$SPARK_TMP_DIR/worker -Dlog4j.configuration=file://$SPARK_CONF_DIR/log4j-server.properties -Dspark.log.file=$SPARK_LOG_DIR/worker.log "
export SPARK_EXECUTOR_OPTS=" -Djava.io.tmpdir=$SPARK_TMP_DIR/executor -Dlog4j.configuration=file://$SPARK_CONF_DIR/log4j-executor.properties "
export SPARK_REPL_OPTS=" -Djava.io.tmpdir=$SPARK_TMP_DIR/repl/$USER "
export SPARK_APP_OPTS=" -Djava.io.tmpdir=$SPARK_TMP_DIR/app/$USER "
# Directory to run applications in, which will include both logs and scratch space (default: SPARK_HOME/work).
export SPARK_WORKER_DIR="$SPARK_HOME/work"
Anyone have any idea.Please suggest.
Thanks
| |
doc_2077
|
Could someone please tell me why my code for the jquery autocomplete is not working?
jquery code:
<link href="../Script/MainCSS.css" rel="stylesheet" />
<link href="../Script/jquery-ui.css" rel="stylesheet" />
<script src="../Script/jquery-1.10.2.js"></script>
<script src="../Script/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$('.textBox').autocomplete({
source: function (request, response) {
$.ajax({
url: "/Services/BusService.asmx/GetRouteInfo",
data: { param: $('.textBox').val() },
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
var err = eval("(" + XMLHttpRequest.responseText + ")");
alert(err.Message)
// console.log("Ajax Error!");
}
});
},
minLength: 2 //This is the Char length of inputTextBox
});
});
</script>
my c# code:
[WebMethod]
public string[] GetRouteInfo(string param)
{
List<string> list_result = new List<string>();
AutoTaxiEntities useEntity = new AutoTaxiEntities();
System.Data.Entity.Core.Objects.ObjectResult<DAL.Model.SP_FIND_ROUTE_ROUTESTOPS_Result> sp_result = useEntity.SP_FIND_ROUTE_ROUTESTOPS(param);
foreach (DAL.Model.SP_FIND_ROUTE_ROUTESTOPS_Result sp_result_item in sp_result.ToList())
{
list_result.Add(sp_result_item.ID + "," + sp_result_item.ITEMTYPE + "," + sp_result_item.TITLE);
}
return list_result.ToArray();
}
A: Looking at your added script references, i think you have not added autocomplete.js script. Please add it and try it once.Please click here
A: $(document).ready(function () {
$('#<%=txtSearch.ClientID%>').autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
url: "/Services/BusWebService.asmx/GetRouteInfo",
data: "{ 'param': '" + request.term + "' }",
dataType: "json",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
itemid: item.split(',')[0],
itemtype: item.split(',')[1],
label: item.split(',')[2]
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2,
select: function (event, ui) {
$('#<%=hfItem.ClientID%>').val(ui.item.itemid + ',' + ui.item.itemtype + ',' + ui.item.label);
//$("form").submit();
}
});
});
| |
doc_2078
|
Assertions: System: Test runner never began executing tests after launching. If you believe this error represents a bug, please attach the result bundle at /Users/apple/Library/Developer/Xcode/DerivedData/MunchON-eeidlzwuounsfvbrmieuosqzpsih/Logs/Test/Test-MunchON (Staging)-2021.10.05_11-35-54-+0500.xcresult
I'm unable to resolve this issue. Other questions that i have checked already:
*
*http://twobitlabs.com/2011/06/adding-ocunit-to-an-existing-ios-project-with-xcode-4/
*Xcode 4.2, can't run unit test
*OCUnit tests not running / not being found
*OCUnit test cases not running
A: Try deleting DerivedData
*
*Open Xcode > Preferences > Locations
*Click on the arrow to open DerivedData folder
*Delete all from DerivedData folder
*Reopen Xcode project
P.S. DerivedData contains cached data such that indexed files etc
FYI It is safe
A: I had a similar problem and solved it by checking the "Allow testing Host Application APIs" option in the test target.
| |
doc_2079
|
class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Text { get; set; }
public int AuthorId { get; set; }
public Author Author { get; set; }
}
class Author
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int PostId { get; set; }
public Post Post { get; set; }
}
Okay, nobody in their right minds would have a one-to-one relationship in this context; that's not the issue at play here...
You'll notice that for each navigation property (Author and Post) there are explicit Id columns defined (AuthorId and PostId) respectively.
Personally I don't like this approach (though I can see some potential benefit). I'd prefer EF to manage the Id columns internally for me, and just let me expose a relationship between Post and Author.
What I want to know is, is there any official recommendation for or against explicit Id columns?
NOTE: I do know of one place where explicit Id mapping is valuable, and that is when you're implementing a many-to-many join table. You can use the Ids to create a unique constraint which prevents record duplication for the same many-to-many relationship.
A:
What I want to know is, is there any official recommendation for or against explicit Id columns?
Yes:
It is recommended to include properties in the model that map to
foreign keys in the database. With foreign key properties included,
you can create or change a relationship by modifying the foreign key
value on a dependent object. This kind of association is called a
foreign key association. Using foreign keys is even more essential
when working with N-Tier applications.
Entity Framework Relationships and Navigation Properties
A: This is not an "official recommendation". But here is how I see it.
You want the navigational properties to be virtual for lazy loading, and you will need the two Id columns for the mapping into the database.
But your code never uses those foreign keys. Here is an example that links a Post with an Author.
var p = new Post {Title="Foo"};
p.Author = _db.Authors.First(a => a.Id == 5);
_db.Posts.Add(p);
_db.SaveChanges();
You also need to map those fields up into your domain layer to keep track of relations.
| |
doc_2080
|
def hello_pubsub(event, context):
from googleapiclient.discovery import build
import google.auth
credentials, project_id = google.auth.default(scopes=['https://www.googleapis.com/auth/spreadsheets'])
service = build('sheets', 'v4', credentials=credentials)
spreadsheet_id = 'my_spreadsheet_id_goes_here'
# Call the Sheets API
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=spreadsheet_id,range="A1:B4").execute()
values = result.get('values', [])
for value in values:
print(value)
range_ = 'A7'
request = service.spreadsheets().values().append(spreadsheetId=spreadsheet_id, range=range_, valueInputOption='RAW', insertDataOption='OVERWRITE', body={"values":[['test cell input']]})
response = request.execute()
print(response)
if __name__ == '__main__':
hello_pubsub('a', 'b')
I'm getting several errors in Google Cloud Platform > Logging:
file_cache is unavailable when using oauth2client >= 4.0.0
File "/env/local/lib/python3.7/site-packages/google_api_python_client-1.8.0-py3.7.egg/googleapiclient/discovery_cache/init.py", line 36, in autodetect
from google.appengine.api import memcache ModuleNotFoundError: No module named 'google.appengine'
I can run this same script locally from Terminal and it works perfectly.
Any help or ideas are appreciated. Again, I want to read/write to a Google Sheet from a Cloud Function. It is my own Google Sheet run through the same Google Cloud account.
A: To answer my own question, I was deploying the Cloud Function wrong.
To have it work correctly, I had to put my function main.py, requirements.txt and my service_account.json in the same folder, then deploy it from Terminal.
There are two ways I found to read/write to a sheet:
# METHOD 1 -- using googleapiclient.discovery.build
def hello_pubsub(event, context):
from googleapiclient.discovery import build
import google.auth
credentials, project_id = google.auth.default(scopes=['https://www.googleapis.com/auth/spreadsheets'])
service = build('sheets', 'v4', credentials=None)
spreadsheet_id = 'redacted'
# Call the Sheets API
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=spreadsheet_id,range="A1:B4").execute()
values = result.get('values', [])
# Print the values in the sheet in range A1:B4
for value in values:
print(value)
# Insert values into the sheet in cell A7
range_ = 'A7'
request = service.spreadsheets().values().append(
spreadsheetId=spreadsheet_id,
range=range_,
valueInputOption='RAW',
insertDataOption='OVERWRITE',
body={"values":[['This value gets inserted into the cell A7']]})
response = request.execute()
print(response)
# METHOD 2 -- using gspread (I prefer this because it's cleaner & does all I need)
import gspread
def hello_pubsub(event, context):
credentials_filepath = 'default_app_engine_service_account_key.json'
gc = gspread.service_account(filename=credentials_filepath)
sh = gc.open("the-title-of-your-sheet-goes-here")
# Print all values in the sheet
print(sh.sheet1.get_all_records())
sh.sheet1.append_row(['This value gets appended to the last row in the sheet'],
value_input_option='RAW',
insert_data_option=None,
table_range=None)
Note:
deploy the main.py with:
gcloud functions deploy hello_pubsub --runtime python37 --trigger-topic test-topic
and don't forget your requirements.txt file
A: I think you have the dependencies installed globally and you use them. But when you deploy on Cloud Function, your local context is lost and the required library are missing.
Add a requirements.txt file in the root directory of your function with this content
google-api-python-client==1.8.2
google-auth==1.14.1
And deploy again.
| |
doc_2081
|
Everything was fine under VS2008 Pro, but after installing VSTS this seems broken. Is it possible to modify this behaviour somewhere in the settings or should I blame this on a broken install and reinstall VS?
A: Under Tools >> Options >> Device Tools >> General, is "Show skin" in Windows Forms Designer checked?
When you open the form, is the "FormFactor" property set to a windows mobile style form?
A: Believe it or not, someone else encountered the exact same problem AND found the solution!
The full solution is here, but in short, you need to run the following registry fix and the designer is back :)
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETCompactFramework\v3.5.0.0\PocketPC\AsmmetaBinder]
"TypeName"="Microsoft.CompactFramework.Build.PocketPC.BindingService, Microsoft.CompactFramework.Build.Tasks, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, Custom=null"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETCompactFramework\v3.5.0.0\PocketPC\AsmmetaBinder\4118C335-430C-497f-BE48-11C3316B135E]
"TypeName"="Microsoft.CompactFramework.Build.WM50PocketPC.BindingService, Microsoft.CompactFramework.Build.Tasks, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, Custom=null"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETCompactFramework\v3.5.0.0\Smartphone\AsmmetaBinder]
"TypeName"="Microsoft.CompactFramework.Build.SmartPhone.BindingService, Microsoft.CompactFramework.Build.Tasks, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, Custom=null"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETCompactFramework\v3.5.0.0\Smartphone\AsmmetaBinder\BD0CC567-F6FD-4ca3-99D2-063EFDFC0A39]
"TypeName"="Microsoft.CompactFramework.Build.WM50SmartPhone.BindingService, Microsoft.CompactFramework.Build.Tasks, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, Custom=null"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETCompactFramework\v3.5.0.0\WindowsCE\AsmmetaBinder]
"TypeName"="Microsoft.CompactFramework.Build.WindowsCE.BindingService, Microsoft.CompactFramework.Build.Tasks, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, Custom=null"
| |
doc_2082
|
1st way:
// here serializeObject just converts form inputs into a serialized object
var inputs_data = this.ui.form.serializeObject();
// here in 3rd param from extend is the same as this.model.unset('logged');
var data = _.extend(this.model.toJSON(), inputs_data ,{logged: undefined});
// here I save and the data goes Ok!
this.model.save(data);
2nd way:
// here i serialize the object the same as above
var inputs_data = this.ui.form.serializeObject();
// here i exclude 3rd parameter
var data = _.extend(this.model.toJSON(), inputs_data);
// set data with model.set instead of model.save
this.model.set(data);
// remove unwanted attributes
this.model.unset('logged',{silent:true});
// finnaly just save
this.model.save(data);
So far I am using the 1st way, so I do not know if the app goes bigger it will bring any problems because of this.
A: If I were you I would use either Backbone.StickIt to synchronise an existing model with the form or use Backbone.Syphon to do something similar to what you are doing above.
A: I would go this way. You don't have to pass all attributes to model's save method, only the attributes that need to be changed (http://backbonejs.org/#Model-save)
var inputs_data = this.ui.form.serializeObject();
// remove unwanted attributes
delete inputs_data.logged;
// finally just save
this.model.save(inputs_data);
| |
doc_2083
|
Then I compiled with the gcc but after that I only see my .c file and an .exe file. The program runs perfectly. But where is the .o file that I learned in theory? Has it been overwritten to .exe and all done by the gcc in on step? (Preprocessing, compiling, assembling and linking)
I'm on a VM running Debian.
A: By default, gcc compiles and links in one step. To get a .o file, you need to compile without linking. That's done with the -c option.
Suppose you want to compile two files separately, then link them. You would do the following:
gcc -c file1.c # creates file1.o
gcc -c file2.c # creates file2.o
gcc -o myexe file1.o file2.o
If you want just the output of the preprocessor, use the -E option along with the -o to specify the output file:
gcc -E file1.c -o file1-pp.c # creates file1-pp.c
A: Compile and link in two steps:
gcc -Wall -c tst.c
gcc tst.c -o tst
After first command you'll get a .o file.
A: if you did something like gcc test.c then it produces only the executable file (in order to compile only, see the -c option)
A: here is steps on compiling with gcc to create a .o file from your C file:
http://www.gnu.org/software/libtool/manual/html_node/Creating-object-files.html
| |
doc_2084
|
There is a variable called $(environment) in my script.postdeployment.sql that depends on the server environment (prd,uat,dev) and I use the command sqlcmd.exe -v environment="dev" to set this value to this variable. The problem is the Visual Studio throw a compilation error
SQL72008: Variable Environment is not defined.
Ok, I know why this error is trown, It is because the variable is not defined in the Prject properties (SQLCMD Variables tab), BUT if I add this variable in the project properties the value will be setted in the script overriding the value I passed in the sqlcmd.exe -v environment="dev".
For example
, If I set the $(environment) variable in the project properties as "uat" and execute sqlcmd.exe -v environment="dev", the highest precedence is the value I set in the project properties, so UAT, because the project generate the following statment in my script:
:setvar app_environment "uat"
How could I handle this issue between visual studio database project and sqlcmd.exe?
A: The way I have fixed this is to Set the properties of the post deployment script as follows:
Build Action: None
Copy to Output Directory: Copy always
When you do this, Visual Studio won't build the post script file, but will copy it to the /bin folder. You can then call SQLCMD twice. Once for the database creation script, and then a second time for the post build script using the -v option.
| |
doc_2085
|
A: Simple: reimplement Xlib inside your program, or at least the portion of it you need to grab the screen. You should start by reading about the X protocol.
Edit: Maybe you should read the Wikipedia page on the X protocol before the formal specification. What you want is to send a GetImage X request, as documented on page 61 of the PDF linked above.
| |
doc_2086
|
I’ve been doing some searching and the so far I see suggestions of using and external config file, use the machine.config, or maybe a web service to get the information.
Using an external file doesn’t seem that it would help a whole lot because if a change is needed you still have to change the file on all the apps even though it’s external.
In theory the machine.config seems to be logical to me right now. You just put the connection information at the machine level and any app, site, or Web API should be able to pick it up. However, I see a lot of discussions where people are discouraging that practice. In addition I’m trying to get my code to pull the connection information from the machine.config but I haven’t been able to get it to work at the moment.
So, what are some suggestions? Anyone with real world pros/cons on using the machine.config, external file or maybe a webservice to store connection string information?
A: A simplest way of doing it is to use keep your configuration file in a single project and add that configuration file to other projects as "Link".
You can also just keep the connection strings separate from the application configuration in separate configuration file. and use the reference of the connection string in separate configuration files. This is more concrete solution.
<configuration>
<connectionStrings configSource="connections.config"/>
</configuration>
With file connections.config containing
<connectionStrings>
<add name="name" connectionString="your conn_string" providerName="System.Data.SqlClient" />
<add name="name2" connectionString="your conn_string2" providerName="System.Data.SqlClient" />
</connectionStrings>
A: Create a separate class library JUST for this purpose, Add connection string as a property in a class file. Then you can always reference this library in any application that needs the connection string to the database.
Retrieve the connection string in code from the property value. However with this approach, if you make any changes you would always have to re-compile the code.
| |
doc_2087
|
[boringssl] boringssl_metrics_log_metric_block_invoke(151) Failed to log metrics
I've rode that the error can disappear if you test it on a real device, but I've still got the error.
import UIKit
class DetailViewController: UIViewController {
var model: DetailModel?
override func viewDidLoad() {
super.viewDidLoad()
loadSteuer()
// Do any additional setup after loading the view.
}
func loadSteuer(){
let url = URL(string: "https://www.bmf-steuerrechner.de/interface/2022Version1.xhtml")!
guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false )else {
return
}
let queryItemCode = URLQueryItem(name: "code", value: "Lohn2022")
let queryItemLzz = URLQueryItem(name: "LZZ", value: "1")
let queryItemRe4 = URLQueryItem(name: "Re4", value: model?.bruttolohnCents)
let queryItemStk1 = URLQueryItem(name: "STKL", value: model?.steuerklasseString)
let queryItemAJahr = URLQueryItem(name: "AJAHR", value: model?.alterString)
components.queryItems = [queryItemCode, queryItemLzz, queryItemRe4, queryItemStk1, queryItemAJahr]
guard let queryURL = components.url else {
return
}
let request = URLRequest(url: queryURL)
URLSession.shared.dataTask(with: request) {[weak self] (data, response, error) in
guard let data = data, error == nil else{
return
}
let parser = XMLParser(data: data)
parser.delegate = self
parser.parse()
}.resume()
}
}
extension DetailViewController: XMLParserDelegate {
func parser(_ parser: XMLParser,
didStartElement elementName: String,
namespaceURI: String?,
qualifiedName qName: String?,
attributes attributeDict: [String : String] = [:]) {
switch elementName {
case "ausgabe":
if attributeDict["name"] == "LSTLZZ"{
print(attributeDict["value"])
}
if attributeDict["name"] == "SOLZLZZ"{
print(attributeDict["value"]) }
default:
break
}
}
}
| |
doc_2088
|
EDIT: Need to remove everything before 'use strict' in example below, as well as closing }); Code in between, everything below 'use strict' except for the final closing }); needs to be left in tact. That code does contain functions and objects which complicate things. Example of what code may look like:
define([
'backbone',
'common',
'marionette',
'bootstrap'
],
function (Backbone, Common) {
'use strict';
var foo = 'stuff';
foo = Backbone.Marionette.ItemView.extend({
template: 'stuff',
className: 'more stuff',
events: {
"click #a": "s"
},
s: function () {
//
// On click of a button, hide the modal
//
this.$el.modal('hide');
}
});
});
A: You can use this regex:
.*(?='use strict')|}\);$
Working demo
| |
doc_2089
|
from typing import Union, Generic, TypeVar, get_args
T = TypeVar('T')
class MyClass(Generic[T]):
def __init__(self):
self.print_generic_args() # always prints 'no generic args'
def print_generic_args(self):
try:
generic_args = get_args(self.__orig_class__)
print(f'generic args are: {generic_args}')
except AttributeError:
print(f'no generic args')
if __name__ == '__main__':
x1 = MyClass()
x2 = MyClass[Union[int, str]]()
x1.print_generic_args()
x2.print_generic_args()
Output:
>>> no generic args
>>> no generic args
>>> no generic args
>>> generic args are: (typing.Union[int, str],)*
Questions:
*
*Is there a better way to access the type-args from an instance of a Generic-derived class?
*Is there a way to access them in __init__()?
| |
doc_2090
|
A: AngularUI bootstrap has a ngModal module, you can use that to display the table in a modal pop-up with buttons and what not. Check it out.
| |
doc_2091
|
Given two equal-sized (numpy) arrays, the goal is to find the average of values in one array, say a, corresponding to the values of another array, say b. The indices of the arrays are in sync.
For example;
a = np.array([1, 1, 1, 2, 2, 2])
b = np.array([10, 10, 10, 20, 20, 20])
There are two distinct values in a, 1 and 2. The values in b where there is a "1" in a at the same index are [10, 10, 10]. Hence average(1) is 10. Analogously, average(2) is 20.
We can assume that the distinct set of values in a are known apriori. The values in a need not be consecutive, the order is random. I have chosen the example as such just to ease the description.
Here is how I approached it:
# Accumulate the total sum and count
for index, val in np.ndenumerate(a):
val_to_sum[val] += b[index]
val_to_count[val] += 1
# Calculate the mean
for val in val_to_sum.keys():
if val_to_count[val]: # skip vals with zero count
val_to_mean[val] = val_to_sum[val] / val_to_count[val]
Here val_to_sum and val_to_count are dictionaries that are initialized to zeros based on the known list of values that can be seen in a (1 and 2 in this case).
I doubt that this is the fastest way to calculate it. I expect the lists to be quite long, say a few million, and the set of possible values to be in the orders of tens.
How can I speed up this computation?
Could the solution be?
Inspired by one of the answers below, this might do it:
for val in a
b[a==val].mean()
A: Perhaps something like this would work:
import numpy as np
a = np.array([1, 1, 1, 2, 2, 2])
b = np.array([10, 10, 10, 20, 20, 20])
np.average(b[a==1])
np.average(b[a==2])
For larger datasets:
import numpy as np
a = np.random.randint(1,30,1000000)
b = np.random.random(size=1000000)
for x in set(a):
print("Average for values marked {0}: {1}".format(x,np.average(b[a==x])))
A: You can go over the list once:
means_dict = {}
for i in range(len(a)):
val = a[i]
n = b[i]
if val not in means_dict.keys():
means_dict[val] = np.array([0.0,0.0])
arr = means_dict[val]
arr[0] = arr[0] * (arr[1] / (arr[1] + 1)) + n * (1 / (arr[1] + 1))
arr[1] = arr[1] + 1
calculating running average for each one of the values. in the end you will have a dict, with each value avarage, and the count.
Edit:
Actually, playing around, showed this to be having the best results:
def f3(a,b):
means = {}
for val in set(a):
means[val] = np.average(b[a==val])
return means
Which is similar to what you suggested, just going over the set, saving much time.
A: It can be done by removing the duplicate :
So, try this:
from collections import OrderedDict
import numpy as np
a = np.array([1, 1, 1, 2, 2, 2])
b = np.array([10, 10, 10, 20, 20, 20])
a=list(OrderedDict.fromkeys(a))
b=list(OrderedDict.fromkeys(b))
print(b)
if you have different elements in b so use this
import pandas as pd
import numpy as np
a = np.array([1, 1, 1, 2, 2, 2])
b = np.array([10, 10, 10, 20, 20, 20])
d = {}
for l, n in zip(a, b):
d.setdefault(l, []).append(n)
for key in d:
print key, sum(d[key])/len(d[key])
code:https://onlinegdb.com/BJih3DplE
| |
doc_2092
|
Note: I am not using OpenGL nor any other graphics library.
Data which I have:
Screen X
Screen Y
Screen Height
Screen Width
Aspect Ratio
A: If you have the Camera world Matrix and Projection Matrix this is pretty simple.
If you don't have the world Matrix you can compute it from it's position and rotation.
worldMatrix = Translate(x, y, z) * RotateZ(z_angle) * RotateY(y_angle) * RotateX(x_angle);
Where translate returns the the 4x4 translation matrices and Rotate returns the 4x4 rotation matrices around the given axis.
The projection matrix can be calculated from the aspect ratio, field of view angle, and near and far planes.
This blog has a good explanation of how to calculate the projection matrix.
You can unproject the screen coordinates by doing:
mat = worldMatrix * inverse(ProjectionMatrix)
dir = transpose(mat) * <x_screen, y_screen, 0.5, 1>
dir /= mat[3] + mat[7] + mat[11] + mat[15]
dir -= camera.position
Your ray will point from the camera in the direction dir.
This should work, but it's not a super concreate example on how to do this.
Basically you just need to do the following steps:
calculate camera's worldMatrix
calculate camera's projection matrix
multiply worldMatrix with inverse projection matrix.
create a point <Screen_X_Value, Screen_Y_Value, SOME_POSITIVE_Z_VALUE, 1>
apply this "inverse" projection to your point.
then subtract the cameras position form this point.
The resulting vector is the direction from the camera. Any point along that ray are the 3D coordinates corresponding to your 2D screen coordinate.
| |
doc_2093
|
dice_select = input('Enter the amount of sides are on the dice you want to throw, either 4, 6, or 12: ')
while dice_select != 4 or dice_select != 6 or dice_select != 12:
dice_select = int(input('Sorry thats not quite right. Enter the amount of sides are on the dice you want to throw, either 4, 6, or 12: '))
if i enter 4, 6 or 12 then it still puts me into the loop when it is supposed to continue.
A: Try This:
dice_select = int(input('Enter the amount of sides are on the dice you want to throw, either 4, 6, or 12: '))
while not (dice_select == 4 or dice_select == 6 or dice_select == 12):
dice_select = int(input('Sorry thats not quite right. Enter the amount of sides are on the dice you want to throw, either 4, 6, or 12: '))
This means loop until dice_select equals 4, 6 or 12.
With your program, your while loop condition is always true, because when it equals 4, your program is checking false or true or true which will always be true.
In other words your program is looking for when dice_select equals 4,6 and 12 at the same time. Which is not possible.
| |
doc_2094
|
<h:field
path="configuredChannels"
required="true"
code="admin.menu.channels">
<div class="row-fluid"
data-channel-checkboxes="#">
<form:checkboxes
element="div class='span1 checkbox'"
items="${channels}"
path="configuredChannels" />
</div>
</h:field>
However the checkbox items works fine on all other resolutions but the item channel value facebook just overlaps with the next checkbox only on 1024 X 768.
here is the jpeg image.
Here is the resulting client code in HTML
<div class="controls">
<div class="row-fluid" data-channel-checkboxes="#">
<div class='span1 checkbox'>
<input id="configuredChannels1" name="configuredChannels" type="checkbox" value="SMS"/><label for="configuredChannels1">SMS</label>
</div class='span1 checkbox'>
<div class='span1 checkbox'>
<input id="configuredChannels2" name="configuredChannels" type="checkbox" value="Voice"/><label for="configuredChannels2">Voice</label></div class='span1 checkbox'>
<div class='span1 checkbox'><input id="configuredChannels3" name="configuredChannels" type="checkbox" value="Facebook"/><label for="configuredChannels3">Facebook</label></div class='span1 checkbox'>
<div class='span1 checkbox'><input id="configuredChannels4" name="configuredChannels" type="checkbox" value="Twitter"/><label for="configuredChannels4">Twitter</label>
</div class='span1 checkbox'><input type="hidden" name="_configuredChannels" value="on"/></div>
<span class="help-inline">
</span>
</div>
</div>
Latest Images
A: The problem is that you're using a fluid row grid and give the checkboxes a fluid span width:
<div class="row-fluid" data-channel-checkboxes="#">
<div class='span1 checkbox'>
This means that the row-fluid is always 100% of the width of it's container (whatever that may be in the context of your HTML, and the checkbox divs have the span1 class, which is always 6.382978723404255% of the row-fluid width. (This is defined in Twitter Bootstrap)
When you resize the window the 100% of the row-fluid becomes smaller, and at a certain point it hits the mark where ~6.38% of that is not enough to fit the entire contents of the checkbox.
There is no simple solution for this while maintaining this fluid grid, it's doing exactly what it's supposed to do but you probably didn't intend this. A better solution would probably be to not give the checkboxes a defined width just let them use all the width they need.
Try removing span1 from the checkbox divs, and add this CSS:
.checkbox {
float: left;
}
This means that they will not have the evenly distributed width they used to have, but instead once there is not enough room to show all of them on one line the checkboxes will continue on a new line.
addition
You're setting classes on the closing tag of a div. That is completely useless. Classes (and all other attributes) should only be set on the opening tag (<div>), never on </div>
| |
doc_2095
|
I have tried setting the events to null in the constructor but I can't seem to find a way to remove the functionality via the API. Essentially the problem I'm facing is that a user is likely to "zoom in" to read the graph and then can't really do much because all the events are captured by the chart. I'd like it simply to display without any interactivity.
chart :{
....
events : null;
...
},
...
http://jsfiddle.net/MTyzv/26/
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
animation: false,
events: null
},
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct']
},
plotOptions: {
series: {
cursor: 'ns-resize',
states : {
hover : {
enabled: false
}
},
stickyTracking : false
},
column: {
stacking: 'normal'
}
},
tooltip: {
enabled: false,
yDecimals: 0
},
series: [
{
name: "test",
data: [0, 10, 20, 30, 40, 50, 60, 70, 100, 70],
draggable: false,
dragMin: 0,
dragMax: 100
}]
});
$('document').ready(new function(){
('container').events = null;
('contener').css({'background-color':'#ff0000','pointer-events': 'none'});
});
A: Can you: $('#myChartDiv').click(function() { return false; }); and only run that code if the browser is identified as mobile (probably using server-side code)? Also, $('#myChartDiv').children().click(function() { return false; });
| |
doc_2096
|
I'm use pyspark to export a hive table to SQL Server.
I found I exported column names as lines in the SQL Server.
I just want to do it without column names.
I don't want these columns in tables...
My pyspark code here:
df.write.jdbc("jdbc:sqlserver://10.8.12.10;instanceName=sql1", "table_name", "overwrite", {"user": "user_name", "password": "111111", "database": "Finance"})
Is there an option to skip column names?
A: I think the JDBC connector isn't actually what adds those header lines.
The header is already present in your Dataframe, it's a known problem when reading data from Hive table.
If you're using SQL to load data from Hive, you can try filtering the header with condition col != 'col':
# adapt the condition by verifiying what is in df.show()
df = spark.sql("select * from my_table where sold_to_party!='Sold-To Party'")
| |
doc_2097
|
proj_create: Error 1027 (Invalid value for an argument): utm: Invalid value for zone
Error in CRS("+proj=utm +zone=37N") : NA
This script worked fine before I updated my R & RStudio, and I am struggling to find the root of the problem. Any help would be appreciated
sps.37N <- SpatialPoints(dd3.full[,c("longitude", "latitude")],
proj4string = CRS("+proj=utm +zone=37N"))
spst.37N <- spTransform(sps.37N, CRS("+proj=longlat +datum=WGS84"))
dd3.full[, c("long", "lat")] <- coordinates(spst.37N)
Thanks
Sample data: structure(list(longitude = c(811674L, 811674L, 812382L, 811674L,
812382L, 811674L, 807900L, 807900L, 812382L, 812405L), latitude = c(1061627L,
1061627L, 1061168L, 1061627L, 1061168L, 1061627L, 1064949L, 1064949L,
1061168L, 1061386L), site = c("DD City", "DD City", "DD City",
"DD City", "DD City", "DD City", "DD City", "DD City", "DD City",
"DD City"), idindividual = c("DDIC-001-C1-F01", "DDIC-001-C1-F02",
"DDIC-001-C1-F03", "DDIC-001-C1-F04", "DDIC-001-C1-F05", "DDIC-001-C1-F06",
"DDIC-001-C2-F01", "DDIC-001-C2-F02", "DDIC-001-C2-F03", "DDIC-001-C3-F01"
)), row.names = c(NA, 10L), class = "data.frame")
| |
doc_2098
|
Protected Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
If TextBox7.Text = Nothing Then
MsgBox(“Please enter Username”, vbExclamation, “Error”)
Exit Sub
End If
If TextBox8.Text = Nothing Then
MsgBox(“Please enter Password”, vbExclamation, “Error”)
Exit Sub
End If
If TextBox9.Text = Nothing Then
MsgBox(“Please enter Email”, vbExclamation, “Error”)
Exit Sub
End If
Dim un, pw, em, dbUN, dbPW, dbEM As String
un = TextBox7.Text
pw = TextBox8.Text
em = TextBox9.Text
Dim cmdUN As New SqlCommand("Select UserName from MembershipInfo where UserName = @p1", con)
With cmdUN.Parameters
.Clear()
.AddWithValue("@p1", un)
End With
Dim cmdPW As New SqlCommand("Select Password from MembershipInfo where UserName = @p1", con)
With cmdPW.Parameters
.Clear()
.AddWithValue("@p1", un)
End With
Dim cmdEM As New SqlCommand("Select Email from MembershipInfo where UserName = @p1", con)
With cmdEM.Parameters
.Clear()
.AddWithValue("@p1", un)
End With
Dim cmdPUN As New SqlCommand("Select Firstname, Lastname From MembershipInfo where Username = @p1, Password = @p2, Email = @p3")
Dim myreader As SqlDataReader
With cmdPUN.Parameters
.Clear()
.AddWithValue("@p1", un)
.AddWithValue("@p2", pw)
.AddWithValue("@p3", em)
End With
Try
If con.State = ConnectionState.Closed Then con.Open()
dbUN = cmdUN.ExecuteScalar
dbPW = cmdPW.ExecuteScalar
dbEM = cmdEM.ExecuteScalar
myreader = cmdPUN.ExecuteReader()
myreader.Read()
If myreader.HasRows Then
TextBox1.Text = myreader.Item("Firstname").ToString
TextBox2.Text = myreader.Item("Lastname").ToString
End If
Catch ex As Exception
Response.Write(ex.Message)
Finally
con.Close()
End Try
If (un = dbUN And pw = dbPW And em = dbEM) Then
MsgBox("Login Sucessful", vbExclamation, "Welcome")
Else
If un <> dbUN Then
MsgBox("Username does not match, please try again", vbExclamation, "Error")
Else
If pw <> dbPW Then
MsgBox("Password does not match, please try again", vbExclamation, "Error")
Else
If em <> dbEM Then
MsgBox("Email does not match, please try again", vbExclamation, "Error")
End If
End If
End If
End If
TextBox7.Text = String.Empty
TextBox8.Text = String.Empty
TextBox9.Text = String.Empty
End Sub
A: I would have thought that an email could uniquely identify your user and a User Name would be unnecessary. You should NEVER store passwords as plain text. I already gave explanations in my last answer to you. I hope you go back and look. I gave your controls descriptive names and I suggest you do the same.
Protected Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
If Not ValidateInput() Then
Exit Sub
End If
Dim dt As DataTable
Try
dt = ValidateUser(txtUserName.Text, txtEmail.Text, txtPassword.Text)
Catch ex As Exception
Response.Write(ex.Message)
Exit Sub
End Try
If dt.Rows.Count > 0 Then
txtFirstName.Text = dt(0)("Firstname").ToString
txtLastName.Text = dt(0)("Lastname").ToString
MsgBox("Login Sucessful", vbExclamation, "Welcome")
txtUserName.Text = String.Empty
txtEmail.Text = String.Empty
txtPassword.Text = String.Empty
End If
End Sub
Private Function ValidateInput() As Boolean
If txtUserName.Text = Nothing Then
MsgBox(“Please enter Username”, vbExclamation, “Error”)
Return False
End If
If txtEmail.Text = Nothing Then
MsgBox(“Please enter Email”, vbExclamation, “Error”)
Return False
End If
If txtPassword.Text = Nothing Then
MsgBox(“Please enter Password”, vbExclamation, “Error”)
Return False
End If
Return True
End Function
Private Function ValidateUser(UName As String, Email As String, PWord As String) As DataTable
Dim dt As New DataTable
Using cn As New SqlConnection("Your connection string."),
cmdUN As New SqlCommand("Select FirstName, LastName from MembershipInfo where UserName = @User And Email = @Email And Password = @Password", cn)
cmdUN.Parameters.Add("@User", SqlDbType.VarChar).Value = UName
cmdUN.Parameters.Add("@Email", SqlDbType.VarChar).Value = Email
cmdUN.Parameters.Add("@Password", SqlDbType.VarChar).Value = PWord
cn.Open()
Using reader = cmdUN.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
| |
doc_2099
|
const Chart = require('chart.js/auto').default;
I just updated to chart.js 4.0.1 and now I get the following error:
Module not found: Error: Package path ./auto is not exported from package node_modules/chart.js (see exports field in node_modules/chart.js/package.json)
Any hint?
Thank you
Stefano
A: You must use UMD packages.
const Chart = require('chart.umd.js/auto').default;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.