id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23536600
|
However, on one of my pages I've got some content above the GridView that I want to be part of the scroll.
Here's the XAML:
<ScrollViewer x:Name="RootScroller" VerticalScrollMode="Enabled" HorizontalScrollMode="Disabled" VerticalScrollBarVisibility="Auto">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<!--static content here-->
</Grid>
<GridView Grid.Row="1"
ItemsSource="{Binding Items}"
ScrollViewer.HorizontalScrollMode="Disabled" ScrollViewer.VerticalScrollMode="Disabled">
</GridView>
</Grid>
</ScrollViewer>
The when loading the page, the LoadMoreItemsAsync is fired over and over again. I know this same issue can happen when the GridView is inside of a StackPanel because the GridView never get's a proper height. Perhaps the layout I have is causing the same issue? Any thoughts on how I can get the dynamic loading to work in this scenario?
A:
I know this can happen when the GridView is inside of a StackPanel because the GridView never get's a proper height. Perhaps the layout I have is causing the same issue?
No. If you put a GridView inside a StackPanel as you known, the GridView never get its proper height. It will lead the GridView not scroll according to this thread.
This is because the height of a stack panel is infinite. Since the height and the width are basically inherited by the container, the scroll viewer never has a reason to scroll as it is already allows to grow to infinite size.
But for your scenario, the ScollerViewer can work well. I tested your code, the ScrollerView can work but the data cannot be fetched virtualization, it will load all the data when loaded the GridView.
The when loading the page, the LoadMoreItemsAsync is fired over and over again.
If you have a GridView inside ScrollViewer , the LoadMoreItemsAsync will be fired over and over again until the data load completed. The ScrollerViewer defeats virtualization. For the reason please see the description about UI virtualization .
Some panels allow child elements unlimited space, examples being ScrollViewer and a Grid, with auto-sized rows or columns. When a virtualized ItemsControl is placed in a panel like that, it takes enough room to display all of its items, which defeats virtualization. Restore virtualization by setting a width and height on the ItemsControl.
According to the article, your solution is easy, restore virtualization by setting a height for the GridView. You will find another issue after height set, the content above the GridView cannot scroll together with GridView since it is in different row with GridView. You need to put them inside same container. Here comes the sample code I suggested which you can test.
<ScrollViewer
x:Name="RootScroller"
HorizontalScrollMode="Disabled"
VerticalScrollBarVisibility="Auto"
VerticalScrollMode="Enabled">
<StackPanel>
<TextBlock x:Name="tbCollectionChangeStatus" />
<ListView x:Name="lvEmployees" Height="800">
...
</ListView>
</StackPanel>
</ScrollViewer>
You can also set the height in code behind.
| |
doc_23536601
|
@Service
public class UserService {
@Autowired private TokenService tokenService;
@Autowired private UserRepository userRepository;
public User updateUser(User user) {
validateUser(user); // can throw some validation errors
createToken(user); // creates token to my user
return userRepository.save(user);
}
}
In my test method, I want to skip the validation and the token creation before the user gets updated.
UserService userService = mock(UserService.class);
doNothing(userService).validateUser(any());
doNothing(userService).createToken(any());
So the problem occurs in my test method when I call the updateUser method, it fails because my userRepository is not injected (NullPointerException).
I tried with @Mock and @InjectMocks, but these annotations are used to inject mocks. How can I inject a real bean into my mock? Is this possible using mockito?
Thank you.
A: Currently you are mocking a service, which means you are replacing whole instance with mock object, even the fields. If you are interested in partial mocking (because you want to use real beans inside) you should read about spying (@Spy takes a real object, but allows to do a partial mocking).
I am not sure what are you trying to do, but my advice is to create SpringBootTest (which loads application context and creates all beans), spy on UserService bean and eventually mock behaviour of service like you are doing now.
I never tried spying beans, but I have found something: https://shekhargulati.com/2017/07/20/using-spring-boot-spybean/
A: The idea of Mockito is to mock the integration points, essentially any third party calls that you make, so that you can test your unit of code. Something like , if everything else i talk to works, then my code should also work.
With that in mind, I dont think you should be using mockito for saving the entity to database. If you need to persist something in DB try writing an integration test, you can use Spring configuration to provide actual beans in that case.
Having said that, if you really need to do that, you can use ReflectionTestUtils.setField in Spring or Whitebox.setInternalState(userService, "userRepository", userRepository) for mockito.
| |
doc_23536602
|
Example 15-01-2012
I have a booking date stored in Session variable $_SESSION['Date'] and date is in format "DD-MM-YYYY" I want to pass this date date('l jS \of F Y') so that i can get the out put in following as Sunday, 15 of January
Can i do this with date or i have to use some other function. I did google it but could not find much & confusing to me as i am new to php
Any reply of appreciated
A: $date = date('l jS \of F Y', strtotime ( $_SESSION['Date'] ));
That's taking what you provided assuming you used PHP Date for reference
A: date('l jS \of F Y' ,strtotime("15-01-2012"));
You can use the strtotime function to convert your stored string to a timestamp, which is then used as the second parameter of the date function.
Demo
Edit
As Paul says, there is a safer way to do this using the DateTime::createFromFormat technique, but it is only available for PHP 5.3.0 and above.
<?php
$date = DateTime::createFromFormat('j-M-Y', '15-01-2012');
echo $date->format('l jS \of F Y');
?>
A: Take a look at DateTime::createFromFormat in the PHP Manual.
They have this example:
<?php
$date = date_create_from_format('j-M-Y', '15-Feb-2009');
echo date_format($date, 'Y-m-d');
?>
Because the date format you are using is ambiguous, it's better to use the DateTime object. Think of the case of 12-12-2011.
| |
doc_23536603
|
NB: Dont want to use redux or bloc.
class _HomePageState extends State<HomePage> {
List<String> names = [];
List<String> _shownNames = [];
int currentPage = 0;
int limit = 20;
String _loadingState = 'loading';
bool loading = true;
@override
void initState() {
super.initState();
for (int i = 0; i < 200; i++) {
names.add("hello $i");
}
_loadNames();
}
@override
Widget build(BuildContext context) {
// TODO: implement build
return new Scaffold(
appBar: new AppBar(title: new Text('User')),
body: Column(children: <Widget>[
Text(_loadingState),
Expanded(child:_getListViewWidget()),
],)
);
}
Widget _getListViewWidget(){
ListView lv = new ListView.builder(
itemCount: _shownNames.length,
itemBuilder: (context, index){
if(index >= _shownNames.length - 5 && !loading){
_loadNames(); // Getting error when this is called
}
return ListTile(
title: Text(_shownNames[index]),
);
});
RefreshIndicator refreshIndicator = new RefreshIndicator(
key: _refreshIndicatorKey,
onRefresh: (){
_loadNames();
return null;
},
child: lv
);
return refreshIndicator;
}
_loadNames(){
loading = true;
setState(() {
_loadingState = 'loading...';
});
new Timer(const Duration(seconds: 5), () {
setState(() {
_shownNames.addAll(names.getRange(currentPage, currentPage + limit));
currentPage += limit;
_loadingState = 'loaded';
});
loading = false;
});
}
}
A: Change _loadNames() {
to
_loadNames(){
loading = true;
// setState(() {
_loadingState = 'loading...';
// });
and
onRefresh: (){
_loadNames();
return null;
},
to
onRefresh: (){
setState(() => _loadNames());
},
update
_loadNames(){
loading = true;
new Future.delayed(Duration.zero, () => setState(() {
_loadingState = 'loading...';
}));
| |
doc_23536604
|
If the file has no icon associated with it Windows will return you the default one that it uses in explorer for unknown file types. In this case I don't want to display the icon.
How can I tell if the file has no associated icon and Windows is giving me back the default one?
On my system SHFILEINFO.iIcon is always equal to 3 in this case but i'm not sure how reliable that is and I expect there is a better way to check this.
Edit: I am targeting Windows XP and upwards
Thanks
A: Which OS versions are you targeting? If you can assume Vista and later, there's an API SHGetStockIconInfo that you may find useful.
SHGetStockIconInfo(SIID_DOCNOASSOC, SHGSI_SYSICONINDEX, &sii)
will return the icon index you're looking for in sii.iSysImageIndex.
A: You could try passing a fictitious filename with an unknown extension to SHGetFileInfo(), keep track of which icon index it reports, and then compare that index to your real files.
| |
doc_23536605
|
<activity android:theme="@android:style/Theme.Dialog"
android:name="com.example.myapp.AuthActivity" />
and it contains a button run your app inside this dialog view itself
On clicking this button, App should run or open under this dialog.
Is this possible? or its a worst question?
Could anyone help me out in this?
A: I think so Its not possible to run other app inside a dialog. Android will not allow to run or display other app inside any dialog, views etc. Its not Web Development where you show other websites in a iframe, frame etc.
I think so the best solution for this is to separately launch other app by pressing button.
| |
doc_23536606
|
Error: The handle is invalid
System.ComponentModel.Win32Exception (0x80004005): The handle is
invalid at System.Drawing.Graphics.CopyFromScreen(Int32 sourceX,
Int32 sourceY, Int32 destinationX, Int32 destinationY, Size
blockRegionSize, CopyPixelOperation copyPixelOperation) at
System.Drawing.Graphics.CopyFromScreen(Int32 sourceX, Int32 sourceY,
Int32 destinationX, Int32 destinationY, Size blockRegionSize) at
Main.Capture(String CapturedFilePath)
System.ComponentModel.Win32Exception (0x80004005): The handle is
invalid at System.Drawing.Graphics.CopyFromScreen(Int32 sourceX,
Int32 sourceY, Int32 destinationX, Int32 destinationY, Size
blockRegionSize, CopyPixelOperation copyPixelOperation) at
System.Drawing.Graphics.CopyFromScreen(Int32 sourceX, Int32 sourceY,
Int32 destinationX, Int32 destinationY, Size blockRegionSize) at
Main.Capture(String CapturedFilePath)
System.ComponentModel.Win32Exception (0x80004005): The handle is
invalid at System.Drawing.Graphics.CopyFromScreen(Int32 sourceX,
Int32 sourceY, Int32 destinationX, Int32 destinationY, Size
blockRegionSize, CopyPixelOperation copyPixelOperation) at
System.Drawing.Graphics.CopyFromScreen(Int32 sourceX, Int32 sourceY,
Int32 destinationX, Int32 destinationY, Size blockRegionSize) at
Main.Capture(String CapturedFilePath)
My Asp.net Code behind code is as follows:
Bitmap bitmap = new Bitmap(2700, 800);
Graphics graphics = Graphics.FromImage(bitmap as System.Drawing.Image);
graphics.CopyFromScreen(25, 25, 25, 25, bitmap.Size);
using (MemoryStream ms = new MemoryStream())
{
// bitmap.Save(@"d:\\Screen", ImageFormat.Jpeg);
bitmap.Save(ms, ImageFormat.Jpeg);
Ret = ms.ToArray();
}
A: What are you trying to achieve? If you want to take screenshot of user's desktop - it is not possible from C# (i.e. server side).
If you are trying to take a screenshot of a server - it kinda makes no sense. It doesn't work for you since there could be no desktop at all on the server: ASP.NET is hosted by IIS which is logged in as a service and thus doesn't have access to server's desktop.
| |
doc_23536607
|
I wrote the following code in head section:
<head runat="server">
<title>SampleApp</title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
<script src='<%=ResolveClientUrl("~/Scripts/jquery-1.7.2.js")%>' type="text/javascript" language="javascript"/>
</head>
when i run the application i got following error:
Is there anything wrong in this code?
Thanks
A: Try to wrap it inside a placeholder it should work.
<asp:ContentPlaceHolder ID="script" runat="server">
<script src='<%=ResolveClientUrl("~/Scripts/jquery-1.7.2.js")%>' type="text/javascript" language="javascript"/>
</asp:ContentPlaceHolder>
| |
doc_23536608
|
I have written the code but get an error when i run docker-compose up --build, that says
ERROR: Service "backend" uses an undefined network "AIservice"
because of this part of the code
networks:
AIservice:
aliases:
- backend.docker
how do i fix this error
| |
doc_23536609
|
cl <- makeCluster(2)
registerDoParallel(cl)
foreach(i = 1:100) %dopar% rnorm(1)
Is it correct or are there any additional steps needed for random generation to work properly? I guess it's enough and fast checks seem to "prove" that seeds work properly, but I'd like to be sure that it is so on other platforms, since I want the code to be portable.
A: Your worries are correct; random number generation does not magically work in parallel and further steps need to be taken. When using the foreach framework, you can use the doRNG extension to make sure to get sound random numbers also when done in parallel.
Example:
library("doParallel")
cl <- makeCluster(2)
registerDoParallel(cl)
## Declare that parallel RNG should be used for in a parallel foreach() call.
## %dorng% will still result in parallel processing; it uses %dopar% internally.
library("doRNG")
y <- foreach(i = 1:100) %dorng% rnorm(1)
EDIT 2020-08-04: Previously this answer proposed the alternative:
library("doRNG")
registerDoRNG()
y <- foreach(i = 1:100) %dopar% rnorm(1)
However, the downside for that is that it is more complicated for the developer to use registerDoRNG() in a clean way inside functions. Because of this, I recommend to use %dorng% to specify that parallel RNG should be used.
| |
doc_23536610
|
What is best practice in such a case?
Maybe I should update the state only when the user submits the form?
A: if you don't want to use any other library that manages form state,
you can move the form to another component, in this case only the child component that conains your form will rerender on changing inputs values, not the parent component, and pass to it the function that handles submit in props to trigger changes in the parent component when you submit the form
| |
doc_23536611
|
For instance with the following tensor:
1 2 3 4
5 6 7 8
I want to extract columns 1 and 3 in one op to get:
2 4
6 8
However it seems I cannot do it in a single op with slicing.
What's the correct/fastest/most elegant way to do this?
A: 1. Using tf.gather(tensor, columns, axis=1) (TF1.x, TF2):
import tensorflow as tf
tensor = tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=tf.float32)
columns = [1, 3]
print(tf.gather(tensor, columns, axis=1).numpy())
%timeit -n 10000 tf.gather(tensor, columns, axis=1)
# [[2. 4.]
# [6. 8.]]
82.6 µs ± 5.76 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
2. With indexing (TF1.x, TF2):
import tensorflow as tf
tensor = tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=tf.float32)
columns = [1, 3] # <--columns you want to extract
transposed = tf.transpose(tensor)
sliced = [transposed[c] for c in columns]
stacked = tf.transpose(tf.stack(sliced, axis=0))
# print(stacked.numpy()) # <-- TF2, TF1.x-eager
with tf.Session() as sess: # <-- TF1.x
print(sess.run(stacked))
# [[2. 4.]
# [6. 8.]]
Wrapping it to a function and running %timeit in tf.__version__=='2.0.0-alpha0':
154 µs ± 2.61 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
Decorating it with @tf.function is more than 2 times faster:
import tensorflow as tf
tensor = tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=tf.float32)
columns = [1, 3] # <--columns you want to extract
@tf.function
def extract_columns(tensor=tensor, columns=columns):
transposed = tf.transpose(tensor)
sliced = [transposed[c] for c in columns]
stacked = tf.transpose(tf.stack(sliced, axis=0))
return stacked
%timeit -n 10000 extract_columns()
66.8 µs ± 2.03 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
3. One-liner for eager execution (TF2, TF1.x-eager):
import tensorflow as tf
tensor = tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=tf.float32)
columns = [1, 3] # <--columns you want to extract
res = tf.transpose(tf.stack([t for i, t in enumerate(tf.transpose(tensor))
if i in columns], 0))
print(res.numpy())
# [[2. 4.]
# [6. 8.]]
%timeit in tf.__version__=='2.0.0-alpha0':
242 µs ± 2.97 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
4. Use tf.one_hot() to specify rows/columns and then tf.boolean_mask() to extract these rows/columns (TF1.x, TF2):
import tensorflow as tf
tensor = tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=tf.float32)
columns = [1, 3] # <--columns you want to extract
mask = tf.one_hot(columns, tensor.get_shape().as_list()[-1])
mask = tf.reduce_sum(mask, axis=0)
res = tf.transpose(tf.boolean_mask(tf.transpose(tensor), mask))
# print(res.numpy()) # <-- TF2, TF1.x-eager
with tf.Session() as sess: # TF1.x
print(sess.run(res))
# [[2. 4.]
# [6. 8.]]
%timeit in tf.__version__=='2.0.0-alpha0':
494 µs ± 4.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
A: You can get all odd numbered columns with a combination of reshapes and a slice:
N = 4
M = 10
input = tf.constant(np.random.rand(M, N))
slice_odd = tf.reshape(tf.reshape(input, (-1, 2))[:,1], (-1, int(N/2)))
| |
doc_23536612
|
But when I go on the portal home page and go Administration -->Portlet Management --> Portlets, I still see the old portlets.
How do I remove the old portlets from the portal server configuration?
A: Go the the Administration --> Portlet Management --> Web Modules.
Check if the application that contains the portlet is still registered. Delete the application the is containing the portlets.
If you don't want to delete the whole application you can click the trash bin in the view you mentioned behind the portlet. I'd however suggest to delete the application.
| |
doc_23536613
|
The error I'm seeing is "The type of parameter "EmployeeType" is expected as "Object[]", not "java.lang.String".
I've tried multiple variations in the beforeOpen clause to get it to parse these correctly but it always returns the same error when running the report.
The section of the query where the values need to go looks like where pebempl_stgr_code in (?)
And it should be just a list of comma separated values, but its not working. All the searching I've done comes up with problems from 2011 and prior and I'm out of ideas.
Edit:
1st beforeOpen script tried was this
this.queryText=this.queryText.replace("placeHolder","where pebempl_stgr_code in ('" + params["employeeType"].value.join("','") + "')");
Worked in the built in web viewer, but will not work with the Engine API
Then tried a modified version of this:
var parmcount = params["parmorders"].value.length
var whereclause = "";
if( parmcount > 0 ){
whereclause = " where customernumber in ( ";
}
for( i=0; i < parmcount; i++ ){
if( i == 0 ){
whereclause = whereclause + params["parmorders"].value[i];
}else{
whereclause = whereclause + " , " + params["parmorders"].value[i];
}
}
if( parmcount > 0 ){
this.queryText = this.queryText + whereclause + " ) ";
}
And it works the same way, runs fine in the web viewer, but will not run in the Engine API.
A: We cannot do this with a regular SQL parameter '?'.
Please see a workaround here, you have to build this 'in' clause in beforeOpen script of the dataset
EDIT:
Furthermore, as mentionned by the exception you get, you have to set an array of object (for example an array of string or an array of integer, depending on the datatype of the report parameter) not a String representing a comma separated list of values. That means if the java application gets a such String, it is necessary to split it into an array before setting the parameter to engine tasks.
| |
doc_23536614
|
Thank you.
Here is the code.
In the popover:
safari.self.addEventListener("message", (function(theMessageEvent){
safari.extension.globalPage.contentWindow.console.log("popover message");
//this is the listener that is not called
}));
safari.application.activeBrowserWindow.activeTab.page.dispatchMessage("get");
//this works and sends message to injected script
in the injected script:
safari.self.addEventListener("message", (function(theMessageEvent){
if(theMessageEvent.name=="get"){
theMessageEvent.target.tab.dispatchMessage("setpopover");
//this sends the message back, maybe the target.tab should be changed to something else?
}
}
EDIT:
I found one solution: the popover send message to the injected script, the injected script sends reply to the background page, and the background page directly calls functions from script in the popover using safari.extension.popovers[0].contentWindow.somefunction();
| |
doc_23536615
|
'Folder is invalid'
and it won't open. Below is the part of the step that compresses the file on Windows Server 2012:
COMPRESS "%DIR_IP_INTERFACES%\SP_Backups\Outbound_GDC_Req.txt" "%DIR_IP_INTERFACES%\SP_Backups\Outbound_GDC_Req_%DATE:/=%_%TIME::=%.zip"
I need it to zip during the batch file, but I will not be the one unzipping. So, I was looking for a standard way to allow anybody to open/unzip the folder when they receive the email (that doesn't require multiple downloads/changes on each computer that might open these files).
Any ideas?
| |
doc_23536616
|
this my class this work for test but don't know how to implement in real case
public class MainActivity extends ActionBarActivity implements OnClickListener {
private WebView webView;
private Button subscription;
IInAppBillingService mservice;
ServiceConnection connection;
String inappid = "android.test.purchased";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
mservice = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mservice = IInAppBillingService.Stub.asInterface(service);
}
};
bindService(new Intent(
"com.android.vending.billing.InAppBillingService.BIND"),
connection, Context.BIND_AUTO_CREATE);
}
public void showDialog(View v) {
ArrayList skuList = new ArrayList();
skuList.add(inappid);
Log.i("TAG", "CLICK");
Bundle querySkus = new Bundle();
querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
Bundle skuDetails;
try {
skuDetails = mservice.getSkuDetails(3, getPackageName(),
"inapp", querySkus);
int response = skuDetails.getInt("RESPONSE_CODE");
if (response == 0) {
ArrayList<String> responseList = skuDetails
.getStringArrayList("DETAILS_LIST");
for (String thisResponse : responseList) {
Log.i("PRICE_TAG", thisResponse);
JSONObject object = new JSONObject(thisResponse);
String sku = object.getString("productId");
String price = object.getString("price");
if (sku.equals(inappid)) {
System.out.println("price " + price);
Bundle buyIntentBundle = mservice
.getBuyIntent(3, getPackageName(), sku,
"inapp",
"bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ");
PendingIntent pendingIntent = buyIntentBundle
.getParcelable("BUY_INTENT");
startIntentSenderForResult(
pendingIntent.getIntentSender(), 1001,
new Intent(), Integer.valueOf(0),
Integer.valueOf(0), Integer.valueOf(0));
}
}
}
} catch (RemoteException e) {
Toast.makeText(getBaseContext(), "Remote erroer",
Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
Toast.makeText(getBaseContext(), "json error",
Toast.LENGTH_SHORT).show();
} catch (SendIntentException e) {
Toast.makeText(getBaseContext(), "sending intent error",
Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1001) {
String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
if (resultCode == RESULT_OK) {
try {
JSONObject jo = new JSONObject(purchaseData);
String sku = jo.getString(inappid);
Toast.makeText(
MainActivity.this,
"You have bought the " + sku
+ ". Excellent choice,adventurer!",
Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Toast.makeText(this.getBaseContext(),
"Failed to parse data", Toast.LENGTH_SHORT).show();
}
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (connection != null) {
unbindService(connection);
}
}
@Override
public void onClick(View arg0) {
showDialog(arg0);
}
| |
doc_23536617
|
I wanted to make the labels in the Highcharts chart to be clickable and run a function when clicked but this returns this error
I do know that the click is being recognized but the isNumber function that is in customEvents.js is not existing. Does the highcharts-custom-events plugin have to be modified to get it to work with highcharts-ng? If so, how could I make this work?
Thanks.
A: In the high-charts plugin page [as accessed from the link above], click on the demo link.. you should be directed to a JS fiddle page.
Ensure that you have added the external resources mentioned in the Left hand side page of the JS fiddle page as accessed above.
| |
doc_23536618
|
I'm trying to achieve it doing it this way:
int numbers[];
puts("Enter number");
int x;
scanf("%d",x);
numbers = malloc(x);
numbers = x;
A: Two quick tricks :
Integer to string :
int N;
char buf[10];
scanf("%d",&N);
sprintf(buf,"%d",N);
Integer to array:
int N,i,
buf[10],
Dig;
scanf("%d",&N);
Dig = log10(N);
for(i = Dig; N ; i--){
buf[i] = N % 10;
N /= 10;
}
A: You can just read it in as a string %s into a char array.
At that point you have each digit in a char.
A char is just an int value. So you can apply any transformation after that to the character that you read in.
You can convert each char digit to its int value and you could then iterate over each char in the string and do something like this:
myInts[i] = charBuffer[i] - '0'; /* where i = 0.. string length -1 */
A: Not magically like that, you would need to read in the int and break up the digits yourself, or read it as a string so you can access each character individually
A: Everyone else has pretty good answers to what you want, just want to point out what your code is really doing---
numbers = malloc(x);
Here you've read in the user's input and allocated an array of x bytes on the heap. Numbers points to that memory. It's your only way to get to that array.
numbers = x;
Then you've assigned numbers to the integer x. You've now lost track of the memory allocated by malloc and have no way to delete it using free().
| |
doc_23536619
|
At the beginning of the graph I would like the lines to go from 0 up to the first data points. Is this possible in FLOT.
Thanks
A: $.plot($('#placeholder'), [data]); // is the format
within data array you need to push an array like [0,0] at first. so for example the data array will look like:
[0, 0], [1, 10],...
| |
doc_23536620
|
Following is the code I have used to load the .owl without succeed
File fileBase = new File("src/java/ontology.owl);
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
OWLOntology ontology= manager.loadOntologyFromOntologyDocument(fileBase);
but when i have used the rdf fromat as shown below it was loaded succefully
File fileBase = new File("src/java/ontology.rdf);
So how can I overcome this issue and load the .owl file?
Is the following command is the best command to save the axioms to ontology file?
manager.saveOntology(ontology);
A: I would suggest you checking your OWL file. If it can't parse the ontology it will throw an exception. You need to catch and read the exception. Most probably is a parsing problem. Your commands are totally fine.
Saving the ontology by your command is fine, but the best way according to OWL documentation is to "apply changes" after each change. Something like:
manager.applyChange(axiom);
A: Its an issue with the .owl file of yours. Use the link below to validate your ontology file
http://mowl-power.cs.man.ac.uk:8080/validator/
| |
doc_23536621
|
Has anyone succesfuly used this? I keep getting TypeError: self._init is not a function
The code can be found on gitub
My code so far:
function initiate() {
var $slider = $('ul.slider');
$slider.slitslider({
autoplay: true,
interval: 1000
});
}
initiate();
A: I've just implemented this slider on my website and struggled with getting it to work. Without seeing your full code it's difficult to say why it's not working for you. But I do believe the script needs to be called on the page very specifically like so:
S(document.ready(function(){
var loaded = false;
$(window).on('load resize',function(){
loaded = true;
var Page = (function() {
slitslider = $('ul.slider').slitslider({
autoplay: true,
interval: 1000
}
}),
init = function(){
initEvents();
},
initEvents = function(){
// add your custom navigation events here
};
return {init:init};
}) ();
Page.init();
});
});
I included the $(window).on('load resize') function to prevent the slitslider CSS elements from FOUC. Hope this helps!
Here's my site with the fullscreen slitslider fully implemented: http://www.estherlee.co
| |
doc_23536622
|
The reason is that I'm attaching a ObjectMaterialized event handler during DbContext construction, but this fails with an InvalidOperationException (underlying model has changed) if the model has changed, so I'd like to conditionalize that event handler attachment only if the model has not changed.
A: you can Try ChangeTracker
public bool ISContextChanges()
{
return this.ChangeTracker.Entries().Any(a => a.State == EntityState.Added
|| a.State == EntityState.Modified
|| a.State == EntityState.Deleted);
}
| |
doc_23536623
|
Im writing test for simple CRUD controllers, but i have no idea how to test for example if params passed to my create action, also if it was saved.
def create
@item = TextItem.new(params[:item])
if @item.save
redirect_to(:action => 'index')
else
render('new')
end
end
A: I think the better way is to become familiar with rails and ruby and only then dive into tdd/bdd with test/unit or minitest or rspec, cucumber or a lot of other testing techniques.
I recommend you to buy a book/ebook to start, for example this one Agile rails development with rails, ebook only $24. You will save a lot of time.
Sometimes Rspec is a little bit tricky/magical and without base knowledge of rails/ruby it can be difficult to start using.
I don't suggest you to study rails and rspec in one attempt.
BTW specs for this action can be like that:
describe "POST create" do
let(:item) { mock_model(TextItem) }
before(:each) do
TextItem.stub(:new).and_return(item)
end
it "saves the item" do
item.should_receive(:save)
post :create
end
context "when the item saves successfully" do
before(:each) do
item.stub(:save).and_return(true)
end
it "redirects to the items index" do
post :create
response.should redirect_to(:action => "index")
end
end
context "when the item fails to save" do
before(:each) do
item.stub(:save).and_return(false)
item.stub_chain(:errors, :empty?).and_return(false)
end
it "renders the new template" do
post :create
response.should render_template(:new)
end
end
end
| |
doc_23536624
|
struct world {
struct room** rooms;
int num_rooms;
};
struct room {
char name[MAX_NAME_LENGTH+1];
char* desc;
char objects; // bit mask for OBJ_* flags
struct room* exits[MAX_EXITS];
};
I'm trying to change the value of a room struct's objects in my world struct.
I've initialized a struct world *world = worlds;
What would the dereference code look like in order to change the values in one of the struct room *'s?
A: Assume struct world * worlds = &someObject, and if worlds->rooms is a pointer array to rooms, you could do as @Alan Au commented,
struct room * r_array[] = {&room1, &room2, &room3};
worlds->rooms = r_array;
printf("%s\n", worlds->rooms[index]->name);
If worlds->roomsis a pointer to pointer of a single room , you can printf name like,
printf("%s\n", (*worlds->rooms)->name);//or
printf("%s\n", (*(*worlds).rooms)->name);
A: Preliminary fixup
I've 'fixed' (modified, at any rate) your initialization code from the syntactically incorrect:
struct *world = worlds
to the syntactically correct (but not necessarily what you had in mind):
struct world *world = worlds;
That would mean that somewhere else you also have the following declaration and code to initialize the pointer:
struct world *worlds;
Note that struct world *world = worlds; is legitimate because struct world is a type name (and the first world is a structure tag) and the second world is an identifier in the ordinary identifier namespace, not in the structure tags namespace.
Accessing rooms
Given:
int n = 1; // For instance
You might write:
printf("Room %d: %s\n", n, world->rooms[n]->name);
That assumes you've initialized the structures properly.
A: When struct world *world points to a valid struct world:
world->num_rooms = NUMBER_OF_ROOMS_IN_WORLD;
world->rooms = malloc(sizeof(*(world->rooms)) * world->num_rooms);
// FIXME: check error
for (unsigned int room_i = 0; room_i < world->num_rooms; ++room_i) {
struct room *room = malloc(sizeof(*room)); // FIXME: check error
world->rooms[room_i] = room;
(void) strcpy(room->name, "room name");
// ... etc, init the room
}
You can access an individual room's fields with world->rooms[room_index]->field, or, perhaps preferably, by first assigning to a pointer struct room *room = world->rooms[room_index] and then through room->field.
| |
doc_23536625
|
$(document).ready(function () {
var selling = new Array();
$('table tr').each(function() {
var name = $(this).find('td:eq(1)').html();
var price = $(this).find('td:eq(3)').html();
var amount = 1;
var item = new Array(name,price,amount);
var found = 0; //selling.find(name)? notworking :)
if(found.length > 0) {
alert('found'); //get amount and change it
} else {
selling.push(item); //push new item to array
}
});
alert(selling);
});
I want to get an array
[cat, 10$, 150]
[cow, 120$, 7]
[bird, 500$, 1]
[horse, 400$, 2]
Can somebody tell me how to compare those names? or do this better way?
A: Try this, using $.inArray():
$(document).ready(function () {
var selling = new Array();
$('table tr').each(function() {
var name = $(this).find('td:eq(1)').html();
var price = $(this).find('td:eq(3)').html();
var amount = 1;
var item = new Array(name,price,amount);
if($.inArray(item,selling) > -1) {
alert('found'); //get amount and change it
} else {
selling.push(item); //push new item to array
}
});
alert(selling);
});
| |
doc_23536626
|
Following the direction from https://learn.microsoft.com/en-us/aspnet/samesite/system-web-samesite, this is the IIS web.config I got for Strict:
<system.web>
<anonymousIdentification cookieRequireSSL="true" />
<authentication>
<forms cookieSameSite="Strict" requireSSL="true" />
</authentication>
<sessionState cookieSameSite="Strict" />
<httpCookies sameSite="Strict" requireSSL="true" />
<roleManager cookieRequireSSL="true" />
<compilation targetFramework="4.7">
...
</compilation>
...
<httpRuntime targetFramework="4.7"/>
</system.web>
And the result (Sorry, I couldn't embed image directly. Got error "couldn't reach Imgur"):
samesite="Strict" image
For SameSite="None", I simply change all the "Strict" to "None":
<system.web>
<anonymousIdentification cookieRequireSSL="true" />
<authentication>
<forms cookieSameSite="None" requireSSL="true" />
</authentication>
<sessionState cookieSameSite="None" />
<httpCookies sameSite="None" requireSSL="true" />
<roleManager cookieRequireSSL="true" />
<compilation targetFramework="4.7">
...
</compilation>
...
<httpRuntime targetFramework="4.7"/>
</system.web>
But it is not being added to the cookies:
samesite="None" image
Thanks in advance. Appreciate your help.
A: There was a comment in another thread that I was thinking of trying as the last resort due to the trouble of installing any software on the machine. It doesn't exactly match my scenario as it didn't work even when he was using "Strict". However, it does fix my problem after installing URL Rewrite.
I tried with <httpCookies sameSite="Strict" /> in .Net 4.7.2 but it did not work for the Asp.Net Identity cookie. This rewrite rule did. – Augusto Barreto Nov 22 '18 at 22:30
@AugustoBarreto Asp.Net Identity ignore the .config settings. Solution is to implement your own Cookie Handler. Derive from System.IdentityModel.Services.CookieHandler and implement WriteInternal method. – Saftpresse99 Mar 18 '19 at 12:18
Thanks, Augusto!
| |
doc_23536627
|
Does anybody have a clue how to solve this?
Cheers!
A: This should work:
git log $(git merge-base HEAD^1 HEAD^2)..HEAD^2
| |
doc_23536628
|
O course, I could make a new field PreferredProjects and save the other Projects in a random order, since only the preferred one is important for me. But this is not an option, being given the context of the current project's software design.
Thank you in advance...
A: It sounds like you simply want to have sorted child collection results when you do a query, rather than take full control of the insert order.
You can achieve that using the techniques described in Tip 1 of my tips series.
Hope this helps.
Alex
Program Manager Entity Framework Team.
A: Try Employees.Projects.OrderBy(x => x).FirstOrDefault()
A: Unfortunately, there is no easy solution. I have the same problem. The only solution is to save after adding each child item (project). This is the only way to save the order without using a new field column to sort input.
| |
doc_23536629
|
My Problem
I have tried it with this code but it doesn't work:
body {
font-family: "Raleway", sans-serif;
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
background-color: dimgrey;
}
My Code:
https://jsfiddle.net/q64g3ft7/2/
A: In your nav1-1.css file, add the following to the html,body,div,p,a,ul,li:
height: 100%;
overflow: hidden;
It will look like this:
html,
body,
div,
p,
a,
ul,
li {
margin: 0;
padding: 0;
border: 0;
font: inherit;
font-size: 100%;
vertical-align: baseline;
height: 100%;
overflow: hidden;
}
| |
doc_23536630
|
import os
import smtplib
EMAIL_ADDRESS =os.environ.get('EMAIL_USER')
EMAIL_PASSWORD =os.environ.get('EMAIL_PASS')
with smtplib.SMTP('smtp.gmail.com', 465) as smtp:
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
subject = 'Practice email code'
body = 'This is my 1st output'
msg = f'Subject:{subject}\n{body}'
smtp.sendmail(EMAIL_ADDRESS, EMAIL_ADDRESS, msg)
Here is the traceback I've got:
Traceback (most recent call last):
File "/data/user/0 ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in
start(fakepyfile,mainpyfile)
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
exec(open(mainpyfile).read(), main.dict)
File "", line 7, in
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.7/smtplib.py", line 251, in init
(code, msg) = self.connect(host, port)
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.7/smtplib.py", line 338, in connect
(code, msg) = self.getreply()
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.7/smtplib.py", line 394, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
EDIT: When I tried 587 port, this is the error:
Traceback (most recent call last):
File "", line 12, in
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.7/smtplib.py", line 721, in login
initial_response_ok=initial_response_ok)
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.7/smtplib.py", line 638, in auth
authobject(challenge).encode('ascii'), eol='')
AttributeError: 'NoneType' object has no attribute 'encode'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in
start(fakepyfile,mainpyfile)
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
exec(open(mainpyfile).read(), main.dict)
File "", line 19, in
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.7/smtplib.py", line 280, in exit
raise SMTPResponseException(code, message)
smtplib.SMTPResponseException: (334, b'UGFzc3dvcmQ6')
I appreciate any suggestion!
A: This is the proper way of using SMTP
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login('EMAIL', 'PASSWORD')
server.sendmail('EMAIL to send from',to, msg)
server.close()
And also, your email should allow external sources to access your email making it less safe so I recommend using an extra email for this
| |
doc_23536631
|
A: If I understood you correctly, a CTE might help:
SQL> with years as
2 (select 2000 + level as year
3 from dual
4 connect by level <= 21
5 )
6 select year
7 from years
8 /
YEAR
----------
2001
2002
2003
2004
<snip>
2020
2021
21 rows selected.
SQL>
You'd now join years with other tables, e.g.
with years as
...
select y.year, e.hiredate
from years y join employees e on e.year = y.year
where ...
| |
doc_23536632
|
I have a data frame in Pandas like this:
A B Count
Cat Brown 6
Cat White 5
Cat White 2
Cat Brown 2
Cat Brown 2
Cat White 2
Dog Black 5
Dog Brown 4
Dog Black 8
Dog Brown 4
Dog Black 6
Dog Brown 2
I want to create a new column which calculates the rolling mean of the 2 prior values using groupby. For instance...
df['A_mean_2']=df.groupby('A').count.apply(lambda x : x.shift().rolling(2,min_periods=1).mean())
However, I am having issues including A & B within the groupby, with values spilling over to the next group. ive tried the following...
df['AB_mean_2']=df.groupby(['A', 'B']).count.apply(lambda x : x.shift().rolling(2,min_periods=1).mean())
The desired output for AB_mean_2 is:
0
0
5
6
4
3.5
0
0
5
4
6.5
4
| |
doc_23536633
|
typedef struct tagENT_PIDL_FILEITEM
{
// SHITEMID
USHORT cb;
// Type identifiers
BYTE magic;
BYTE reserved;
//
WCHAR cDocID[64];
WCHAR cShareID[64];
WCHAR cResourceId[64];
//WCHAR cFileType[10];
WCHAR cFileType[10];
// File data
WIN32_FIND_DATA wfd;
#if defined(_M_X64) || defined(_M_IA64)
// Alignment on 64bit platform
SHORT padding[56];
#endif // _M_X64
} ENT_PIDL_FILEITEM;
It works fine on 32-bit Windows 7, but on 64-bit Windows 10, just select the file or folder and press the delete shortcut (delete) or the f2 shortcut (rename).
. Explorer will automatically exit. Do not you know why.
About SHITEMID
https://learn.microsoft.com/en-us/windows/win32/shell/nse-implement#creating-an-shitemid-structure
| |
doc_23536634
|
For instance I have this test:
- (void)testAddMeal
{
HomeScreenController *hsCtrl = (HomeScreenController*)mainViewController;
[hsCtrl tableView:hsCtrl.tblView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
nutritionStrategyController = (NutritionStrategyController*)((UINavigationController*)mainViewController.modalViewController).topViewController;
[nutritionStrategyController tableView:nutritionStrategyController.tblView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
}
Which opens a first UIViewController selecting a table cell and then a second UIViewController should appear selecting a table cell in the new UIViewController.
Problem is, the test fails with this error:
Unknown.m:0: error: -[NutritionStrategyTests testAddMeal] : Attempting to begin a modal transition from <UINavigationController: 0x113a2fc0> to <NewMealTrackingController: 0x9353090> while a transition is already in progress. Wait for viewDidAppear/viewDidDisappear to know the current transition has completed
So my question is, how do I create a test for this?
A: Unit tests are for testing the behavior of specific bits of code, classes, modules etc. If you want to automate user input, it is a different kind of test, you can look into the UIAutomation instrument, which is dedicated to this type of testing.
The Automation instrument, guided by your test scripts, exercises the
user interface elements of your application, allowing you to log the
results for your analysis. The Automation feature can simulate many
user actions supported by devices that support multitasking and run
iOS 4.0 or later. Your test script can run both on the iOS device and
in the iOS Simulator without modification.
An important benefit of the Automation instrument is that you can use
it with other instruments to perform sophisticated tests such as
tracking down memory leaks and isolating causes of performance
problems.
| |
doc_23536635
|
class func getList(_ completion:@escaping (Array<Item>) -> Void) {
Alamofire.request("http://foo.com", method: .get, parameters: nil, headers: nil)
.responseJSON { response in
let list = parseList(response as! NSArray)
completion(list)
}
}
When I parse the list I need to make another call to get status of the item:
class func parseList(_ responseArray: NSArray) -> Array<Item> {
let list = NSMutableArray()
for itemDic in responseArray {
let item = Item()
item.id = itemDic.value(forKey: "Id") as? Int
item.name = itemDic.value(forKey: "Name") as? Int
Alamofire.request("http://bar.com", method: .get, parameters: nil, headers: nil)
.responseJSON { response in
item.status = response as? String
}
list.add(item)
}
return list as NSArray as! Array<Item>
}
The main issue is that I need to have all the items statuses before completion in the first func and now I get some status responses when the loop is already returned the Array. What is the best solution to return parsed list with statuses?
A: Change parse func to closure and add DispatchGroup till all statuses are set.
First func:
class func getList(_ completion:@escaping (Array<Item>) -> Void) {
Alamofire.request("http://foo.com", method: .get, parameters: nil, headers: nil)
.responseJSON { response in
self.parseList(response as! NSArray, completion: { (list) in
completion(list)
})
}
}
Second func:
class func parseList(_ responseArray: NSArray, completion:@escaping(Array<Item>) - Void) {
let dispatch = DispatchGroup()
let list = NSMutableArray()
for itemDic in responseArray {
let item = Item()
item.id = itemDic.value(forKey: "Id") as? Int
item.name = itemDic.value(forKey: "Name") as? Int
dispatch.enter()
Alamofire.request("http://bar.com", method: .get, parameters: nil, headers: nil)
.responseJSON { response in
item.status = response as? String
dispatch.leave()
}
list.add(item)
}
dispatchGroup.notify(queue: DispatchQueue.main) {
completion(list as NSArray as! Array<Item>)
}
}
A: You can use a simple loop counter to achieve what you want...
class func getList(_ completion:@escaping (Array<Item>) -> Void) {
Alamofire.request("http://foo.com", method: .get, parameters: nil, headers: nil)
.responseJSON { response in
let list = parseList(response as! NSArray)
completion(list)
}
}
from here I modified some of your code... I declared a counter to determine when to throw the callback with the complete list of the item with status.
class func parseList(_ responseArray: NSArray, _ completion: @escaping (Array<Any>) -> Void) {
let list = NSMutableArray()
let counter: Int = 0 // counter
for itemDic in responseArray {
let item = Item()
item.id = itemDic.value(forKey: "Id") as? Int
item.name = itemDic.value(forKey: "Name") as? Int
Alamofire.request("http://bar.com", method: .get, parameters: nil, headers: nil)
.responseJSON { response in
item.status = response as? String
list.add(item) // when the alamofire return the call we set the status then add it to our list..
counter += 1 // then increment our counter
// here ... we verify if the counter matches the total count of the item we need need to fetch
if responseArray.count == counter {
completion(list) // if it matches the total count then we will fire the callback with the list of the item with statuses.
}
}
}
}
| |
doc_23536636
|
Below code works on Windows 10, but has problem on Windows 2008R2(.net 4.7.2) with \\?\....
Get-ChildItem -Path '\\?\c:\test\users' | ?{ $_.CreationTime -le $(Get-Date).AddDays(-7) } | Remove-Item -recurse -force
And that has problem with long path name:
Get-ChildItem D:\foler\folder\file | ?{ $_.CreationTime -le $(Get-Date).AddDays(-7) } | Remove-Item -Force -Recurse
Get-ChildItem D:\foler\folder\file | ?{ $_.CreationTime -le $(Get-Date).AddDays(-7) } | Remove-Item -Force -Recurse
Also I try with robocopy. So will be ok any script on powershell, .bat or .vbs.
| |
doc_23536637
|
https://dev-yakuza.github.io/en/react-native/react-native-firebase-admob/
Admob has four types : Banner Interstitial Rewarded Native
But I can't find Native type in react-native-firebase.
Where can I find it ?
Any help would be appreciated. Thanks in advance.
A: react-native-firebase for admob is an open issue on github. You can find more info here: https://github.com/invertase/react-native-firebase/issues/1259.
You can use google admob, I used it in one of my application, it works fine. You can see following link:
https://dev-yakuza.github.io/en/react-native/react-native-admob/
| |
doc_23536638
|
EDITED BECAUSE I SCREWED UP THE CODE I HAD PASTED @_@.
The code I used for the birthdate keeps making it 0 or something. I'm not certain.
Could it be something with rounding or not being able to use "0.5"?
<?php
$birthDate = "2/17/2015";
$birthDate = explode("/", $birthDate);
$age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md")
? ((date("Y") - $birthDate[2]) - 1)
: (date("Y") - $birthDate[2]));
if($age <= 0.5){
echo "0-6 Months";
}
elseif($age > 0.5 && $age < 1) {
echo "7-12 Months Old";
}
elseif($age >= 1 && $age < 3) {
echo "1-2 Years Old";
}
elseif($age >= 2 && $age < 5) {
echo "2-4 Years";
}
elseif($age >= 1 && $age < 3) {
echo "5-8 Years Old";
}
elseif($age >= 2 && $age < 5) {
echo "9-11 Years";
}
elseif($age >= 1 && $age < 3) {
echo "12-17 Years Old";
}
elseif ($age >= 18 && $age < 65) {
echo "Adult";
}
elseif ($age >= 65){
echo "Senior";
}
else {
echo "Whoops!";
}
echo "</br></br>";
A: You're working way too hard at this. You need the DateTime class. Then you can do something like this:
$birthDate = new DateTime("2/17/2015");
$now = new DateTime();
$interval = $birthDate->diff($now);
echo $interval->format('%y years and %a days'); // 0 years and 331 days
$years = $interval->format('%y');
$days = $interval->format('%a');
if ($years == 0) {
echo ($days < 183) ? '0-6 months' : '7-12 months';
}
else {
switch ($years) {
case < 3:
echo '1-2 years old';
case < 5:
echo '2-4 years old';
// etc
}
}
| |
doc_23536639
|
My Problem this time:
I created a SQLite command to update some (not all) values in my table. Here is my code:
using (SQLiteConnection con = new SQLiteConnection(string.Format("Data Source={0};Version=3;", mstrDatabase)))
{
try
{
using (SQLiteCommand com = new SQLiteCommand("update WDATEN set TS_OUT = @TS_OUT, DATA_OUT = @DATA_OUT where ID = @ID", con))
{
com.Parameters.AddRange(new SQLiteParameter[]
{
new SQLiteParameter("TS_OUT", DbType.DateTime){ Value = date},
new SQLiteParameter("DATA_OUT", DbType.Double){ Value = numRest.Value}
});
con.Open();
com.ExecuteNonQuery();
mDa.Fill(dsWDaten.WDATEN);
con.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Beim Speichern des Datensatzes ist ein Fehler aufgetreten.\n" + ex.ToString(), "Fehler", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Sadly every time I execute this code block - I get the exception:
SQLite error. Insufficient parameters supplied to the command.
Searching here and on other pages didn't help me. What am I missing?
A: Your query has three parameters (@TS_OUT, @DATA_OUT and @ID) but you're only supplying parameters for the first two, not for @ID.
A: I do not see where you set the parameter @ID in your code. Your SQL statement contains three parameters, you supply values for only two.
| |
doc_23536640
|
I've the main register.php that contains the form and javascript and calls another register.php file with the php code that calls the registration function. I can create new account and data files to the database without any problem, but I am unable to get the response back in my div. Please help!
register.php
<body>
<div class="logo"></div>
<div class="form">
<form id="register" method="post">
<input type="text" name="email" id="email" placeholder="Email Address" /><br/><br/>
<input type="text" name="username" id="username" placeholder="Username" />
<input type="password" name="password" id="password" placeholder="Password" />
<input type="submit" id="register" value="Register" />
</form>
</div>
<div class="small">
<a href="?page=login">I already have an account</a><br/>
</div>
<div id="message"></div>
<script type="text/javascript">
$(document).ready(function(){
var myForm = $('#register');
myForm.validate({
errorClass: "errormessage",
onkeyup: false,
errorClass: 'error',
validClass: 'valid',
rules: {
email: { required: true, email: true, minlength: 3, maxlength: 100 },
username: { required: true, minlength: 3, maxlength: 30 },
password: { required: true, minlength: 3, maxlength: 100 }
},
errorPlacement: function(error, element)
{
var elem = $(element),
corners = ['right center', 'left center'],
flipIt = elem.parents('span.right').length > 0;
if(!error.is(':empty')) {
elem.filter(':not(.valid)').qtip({
overwrite: false,
content: error,
position: {
my: corners[ flipIt ? 0 : 1 ],
at: corners[ flipIt ? 1 : 0 ],
viewport: $(window)
},
show: {
event: false,
ready: true
},
hide: false,
style: {
classes: 'ui-tooltip-red'
}
})
.qtip('option', 'content.text', error);
}
else { elem.qtip('destroy'); }
},
success: $.noop,
})
});
$("#register").submit(function(event) {
if($("#register").valid()) {
event.preventDefault();
var $form = $( this ),
mail = $form.find('input[name="email"]').val(),
user = $form.find('input[name="username"]').val(),
pass = $().crypt({method:"sha1",source:$().crypt({method:"sha1",source:$form.find('input[name="password"]').val()})});
$.post("inc/action.php?a=register", {email: mail, username: user, password: pass},
function(data) {
$("#message").html('<p> code: ' + data.error + '</p>');
$("#message").append('<p> message: ' + data.message + '</p>');
}, "json"
);
}
else
{
$("[id^=ui-tooltip-]").effect("pulsate", {times: 3}, 300);
return false;
}
});
</script>
</body>
register.php
<?php
if(isset($_POST['email'])) { $email = $_POST['email']; } else { echo 1; exit(); }
if(isset($_POST['username'])) { $username = $_POST['username']; } else { echo 1; exit(); }
if(isset($_POST['password'])) { $password = $_POST['password']; } else { echo 1; exit(); }
$register = $auth->register($email, $username, $password);
$return = array();
switch($register['code'])
{
case 0:
$return['error'] = 1;
$return['message'] = "You are temporarily locked out of the system. Please try again in 30 minutes.";
break;
case 1:
$return['error'] = 1;
$return['message'] = "Username / Password is invalid";
break;
case 2:
$return['error'] = 1;
$return['message'] = "Email is already in use";
break;
case 3:
$return['error'] = 1;
$return['message'] = "Username is already in use";
break;
case 4:
$return['error'] = 0;
$return['message'] = "Account created ! Activation email sent to " . $register['email'];
break;
default:
$return['error'] = 1;
$return['message'] = "System error encountered";
break;
}
$return = json_encode($return);
echo $return;
A: Add header('Content-Type: application/json') before returning the json-encoded data.
in json.php
<?php
$data['error']=1;
$data['msg']="error";
header('Content-Type: application/json');
echo json_encode($data);
?>
in index.php
<script type="text/javascript">
$.ajax({
url:'json.php',
success:function(data){
$('body').html(data.msg);
}
});
</script>
| |
doc_23536641
|
function buyerclick() {
div = document.getElementById('block2');
div.style.display = "block";
var elem = document.getElementsByClassName('block1');
elem.parentNode.remove(elem);
}
Block2 is working OK but block1 isn't remove it just stayed under block2. What I did wrong? I need that block1 removed with all its elements.
A: getElementsByClassName returns a collection, so you have to change that line to:
var elem = document.getElementsByClassName('block1')[0];
| |
doc_23536642
|
// `uncurryThis` is equivalent to `func => Function.prototype.call.bind(func)`.
// It is using `bind.bind(call)` to avoid using `Function.prototype.bind`
// and `Function.prototype.call` after it may have been mutated by users.
const { apply, bind, call } = Function.prototype;
const uncurryThis = bind.bind(call);
primordials.uncurryThis = uncurryThis;
// `applyBind` is equivalent to `func => Function.prototype.apply.bind(func)`.
// It is using `bind.bind(apply)` to avoid using `Function.prototype.bind`
// and `Function.prototype.apply` after it may have been mutated by users.
const applyBind = bind.bind(apply);
primordials.applyBind = applyBind;
All that is needed to save Array for internal library use is to assign it to a variable scoped to the internal libraries. Saving Array.prototype.push for reuse is trickier because it normally has to be a property of an object to work. uncurryThis(Array.prototype.push) produces a function whose first parameter is the this value that gets used by Array.prototype.push, which is now usable even if user code deletes the method from the prototype of Array.
Unlike apply and call, bind is unavailable in older JavaScript engines, so it cannot be used to save preserve builtin methods. P"Bound" functions returned by polyfills for Function.prototype.bind that I have encountered thus far are written a way that is susceptible to breaking if, for instance, apply and call were deleted from Function.prototype.
Is there some way to polyfill Function.prototype.bind in such a way that functions returned by it cannot be broken by monkey patching?
| |
doc_23536643
|
I see no console logs with JS errors, and the problem happens on only about 1/4 of all requests.
Here's my init:
<script type="text/javascript">
tinyMCE.init({
mode : "textareas",
plugins : "paste,spellchecker, table",
paste_auto_cleanup_on_paste : true,
theme : "advanced",
theme_advanced_buttons1 : "spellchecker,separator,pastetext,pasteword,separator,bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,separator,code",
theme_advanced_buttons2: "tablecontrols",
theme_advanced_buttons3: "",
theme_advanced_buttons4: "",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
width : "700",
height: "500"
});
</script>
A: Do you include tinyMCE right before your initialization script?
In some cases including tinyMCE after the init part might be the problem...
A: I don't know how in the world this could be related to my issue, but I haven't seen the problem reappear after I made a setting change in IIS. I added a web garden to handle load issues and this problem has not been seen since.
It's a purely anecdotal solution though.
| |
doc_23536644
|
I have the following config in package.json:
"env": {
"browser": true,
"amd": true
},
"extends": "eslint:recommended",
and invoke it via a lint task using this Grunt config:
eslint: {
target: [
'src/app/**/*.js'
],
format: 'checkstyle'
},
How can I enable the --fix flag in this scenario?
A: Adding to the answer, If You don't wan't always to fix, You could pass the flag to the grunt like
grunt eslint --fix
And in the grunt config for eslint
eslint: {
options: {
fix: grunt.option('fix') // this will get params from the flags
}
}
So Running grunt eslint won't fix anything. You have to run grunt eslint --fix for eslint to fix errors.
Read More about grunt.option
A: For the --fix flag, you only have to add an options: { fix: true } to your gruntfile.
Here is an example of my gruntfile eslint task (grunt-eslint 18.1.0 with eslint 2.12.0):
eslint: {
options: {
configFile: '.eslintrc.json',
format: 'html',
outputFile: 'report.html',
fix: true
},
target: [
'routes/**',
'server.js',
'gruntfile.js'
]
}
A: If it didn't
extend(config, ctx) {
// Run ESLint on save
if (ctx.isDev && ctx.isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/,
options: {
fix: true
}
})
}
}
You. You can use this on the first page
const colors = require('vuetify/es5/util/colors').default
const pkg = require('./package')
require('dotenv').config()
module.exports = {
mode: 'universal',
/*
** Headers of the page
*/
head: {
titleTemplate: '%s - ' + process.env.npm_package_name,
title: process.env.npm_package_name || '',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{
hid: 'description',
name: 'description',
content: process.env.npm_package_description || ''
}
],
link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }]
},
/*
** Customize the progress-bar color
*/
loading: { color: '#fff' },
/*
** Global CSS
*/
css: [],
/*
** Plugins to load before mounting the App
*/
plugins: [],
/*
** Nuxt.js dev-modules
*/
buildModules: [
// Doc: https://github.com/nuxt-community/eslint-module
'@nuxtjs/eslint-module',
'@nuxtjs/vuetify'
],
/*
** Nuxt.js modules
*/
modules: [
// Doc: https://axios.nuxtjs.org/usage
'@nuxtjs/axios',
'@nuxtjs/pwa',
// Doc: https://github.com/nuxt-community/dotenv-module
'@nuxtjs/dotenv'
],
/*
** Axios module configuration
** See https://axios.nuxtjs.org/options
*/
axios: {},
/*
** vuetify module configuration
** https://github.com/nuxt-community/vuetify-module
*/
/*
** Build configuration
*/
build: {
extend(config, ctx) {
// Run ESLint on save
if (ctx.isDev && ctx.isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/,
options: {
fix: true
}
})
}
}
}
}
| |
doc_23536645
|
Directory structure:
hello-world/
clojure-1.1.0.jar
build/
classes/
src/
test/
hello.clj
hello.clj:
(ns test.hello
(:gen-class))
(defn -main [& args]
(println "Hello" (nth args 0)))
Interaction:
$ cd hello-world
[hello-world]$ java -cp ./clojure-1.1.0.jar:./build/classes:./src clojure.main
Clojure 1.1.0
user=> (require 'test.hello)
nil
user=> (test.hello/-main "there")
Hello there
nil
user=> (compile 'test.hello)
java.io.IOException: No such file or directory (hello.clj:2)
user=> *compile-path*
"classes"
user=> (doseq [p (.split (System/getProperty "java.class.path") ":")] (println p))
./clojure-1.1.0.jar
./build/classes
./src
nil
So I can load and call the file from the REPL, but it doesn't compile.
According to clojure.org, compilation needs
*
*namespace must match classpath-relative file path - check
**compile-path* must be on the classpath - check
*:gen-class argument to the ns form - check
I found this post from a year back, as far as I can tell I'm doing exactly the same, but it doesn't work.
What am I missing?
System: OS X 10.6, Java 1.6.0, Clojure 1.1
A: Got it, there's a fourth requirement:
*
**compile-path* is resolved relative to the JVMs working directory, normally the directory where java is started. Or by REPL: (System/getProperty "user.dir"),
So this works:
user=> (set! *compile-path* "build/classes")
"build/classes"
user=> (compile 'test.hello)
test.hello
A: Why you don't use Leiningen? It's much easier to use it, than compile code manually. You can use my article about it as introduction...
A: To run clojure file
clojure filename.clj
| |
doc_23536646
|
I've checked a couple of links, which confuse me, see this link, it talks about authorizing developer accounts by using AAD B2C, but does not tell how to authenticate end users
- https://learn.microsoft.com/en-us/azure/api-management/api-management-howto-aad-b2c
I am creating an Architecture where I have a couple of microservices behind Azure API Management, I want to authenticate users through B2C before the request hits API management. Once the request is authenticated, I am assuming B2C will provide a JWT token which the API management will validate and then give access to the backend microservices.
A: The document you referred to is authorizing developer accounts.
You should refer to this document. This also applies to Azure AD B2C.
Protect an API by using OAuth 2.0 with Azure Active Directory and API Management
| |
doc_23536647
|
Name of the argument editable in the build definition window: FixedMajorVersion
Name of the argument that will receive FixedMajorVersion value: MSBuildArgument
I need to set MSBuildArgument as: "/p:FixedMajorVersion=" & FixedMajorVersion
However, the workflow editor on Visual Studio is not recognizing FixedMajorVersion.
What is wrong with it?
A:
Name of the argument that will receive FixedMajorVersion value:
MSBuildArgument
This just needs to be a variable. The argument is exposed, as with the Argument you wish the Build Engineer to supply, but MSBuild "argument" only needs to be internal.
set MSBuildArgument, in the variable declaration tab, default value to be
"/p:FixedMajorVersion=" & FixedMajorVersion
| |
doc_23536648
|
ABf.x<-as.matrix(ABflip)
hc<-hclust(dist(ABf.x),method="ward")
plot(hc,hang=-1,labels=ABf.x[,1])
plot(hc,main="", hang=-1,ylab="Similarity",axes=FALSE,labels=ABf.x[,1])
scale=seq(0,max(hc$height),by=10)
sequence<-as.integer(seq(1,max(hc$height)),by=10)
percent<-as.integer((sequence/max(hc$height)*100))
lines(x = c(0,0), y = c(0,max(hc$height)),type = "n")
axis(2,at=scale, labels=percent)
the plot current comes out without a scale giving the error:
Error in axis(2, at = scale, labels = percent) :
'at' and 'labels' lengths differ, 36 != 351
A: Using the iris dataset as example data. You could play with the scale to get it to top out at 100 instead of 99
ABf.x<-as.matrix(iris)
hc<-hclust(dist(ABf.x),method="ward")
plot(hc,hang=-1,labels=ABf.x[,1])
plot(hc,main="", hang=-1,ylab="Similarity",axes=FALSE,labels=ABf.x[,1])
scale=seq(0, max(hc$height), by=10)
sequence<-as.integer(seq(1,(max(hc$height)), by=10)) #get sequence of heights from dendrogram
percent<-as.integer((sequence/max(hc$height)*100)) #Convert these to a percent of the maximum height
lines(x = c(0,0), y = c(0,max(hc$height)),type = "n")
axis(2,at=scale, labels=percent)
Link to result: example
| |
doc_23536649
|
A: I ended up here looking for this information too, but as it turns out, you don't have to search for the ID in your HangOuts but in your Hass interface:
https://www.home-assistant.io/components/hangouts/#finding-the-conversation-id
The ID is in the developer tools provided in your Hass installation. Look in the "Status" tab. If the information doesn't show up, try refreshing going to the "Services" tab, select "hangouts.reconnect" and then press "Call Service". You should now see the conversation ID under the "Status" tab.
| |
doc_23536650
|
So is there a way I can remove that white background ?
A: Only setting the BackColor to Color.Transparent is not enough to get rid of the little border that is around the RadioButton.
What you will need to also do is call the following code for each radio button to ensure that the background does actually go transparent
rbnTest.BackColor = Color.Transparent;
Point pos = this.PointToScreen(rbnTest.Location);
rbnTest.Parent = pibPicture;
rbnTest.Location = pibPicture.PointToClient(pos);
Source (Not a true duplicate, but similar, hence not flaggin as duplicate)
I would recommend refactoring that code into a reusable method so that you do not scatter the code all over your project.
A: Locate the constructor for your control class. The constructor appears in the control's code file. In C#, the constructor is the method with the same name as the control and with no return value.
Call the SetStyle method of your form in the constructor.
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
add the following line. This will set your control's BackColor to Transparent.
this.BackColor = Color.Transparent;
Note
Windows Forms controls do not support true transparency. The background of a transparent Windows Forms control is painted by its parent.
A: You can use the RadioButton.BackgroundImage or the RadioButton.BackColor property. Choose the one that suits you best
| |
doc_23536651
|
import random
def random_digit_1():
return int(10 * random.random())
def random_digit_2():
return random.randint(0, 9)
I was curious about what would happen if one generated a random number between 0 and 1, and kept the last digit. I didn't necessarily expect the distribution to be uniform, but I found the result quite surprising.
from random import random, seed
from collections import Counter
seed(0)
counts = Counter(int(str(random())[-1]) for _ in range(1_000_000))
print(counts)
Output:
Counter({1: 84206,
5: 130245,
3: 119433,
6: 129835,
8: 101488,
2: 100861,
9: 84796,
4: 129088,
7: 120048})
A histogram is shown below. Note that 0 does not appear, since trailing zeros are truncated. But can anyone explain why the digits 4, 5, and 6 are more common than the rest? I used
Python 3.6.10, but the results were similar in Python 3.8.0a4.
A: TL;DR Your example is not actually looking at the last digit. The last digit of a finite binary-represented mantissa converted to base-10 should always be 0 or 5.
Take a look at the comment in cpython/pystrtod.c:
char * PyOS_double_to_string(double val,
char format_code,
int precision,
int flags,
int *type)
{
char format[32];
Py_ssize_t bufsize;
char *buf;
int t, exp;
int upper = 0;
/* Validate format_code, and map upper and lower case */
switch (format_code) {
// ...
case 'r': /* repr format */
/* Supplied precision is unused, must be 0. */
if (precision != 0) {
PyErr_BadInternalCall();
return NULL;
}
/* The repr() precision (17 significant decimal digits) is the
minimal number that is guaranteed to have enough precision
so that if the number is read back in the exact same binary
value is recreated. This is true for IEEE floating point
by design, and also happens to work for all other modern
hardware. */
precision = 17;
format_code = 'g';
break;
// ...
}
Wikipedia confirms this:
The 53-bit significand precision gives from 15 to 17 significant decimal digits precision (2-53 ≈ 1.11 × 10-16). If a decimal string with at most 15 significant digits is converted to IEEE 754 double-precision representation, and then converted back to a decimal string with the same number of digits, the final result should match the original string. If an IEEE 754 double-precision number is converted to a decimal string with at least 17 significant digits, and then converted back to double-precision representation, the final result must match the original number.
Thus, when we use str (or repr), we are only representing 17 significant digits in base-10. This means some of the floating point number will be truncated. In fact, to get the exact representation, you need a precision of 53 significant digits! You can verify this as follows:
>>> counts = Counter(
... len(f"{random():.99f}".lstrip("0.").rstrip("0"))
... for _ in range(1000000)
... )
>>> counts
Counter({53: 449833,
52: 270000,
51: 139796,
50: 70341,
49: 35030,
48: 17507,
47: 8610,
46: 4405,
45: 2231,
44: 1120,
43: 583,
42: 272,
41: 155,
40: 60,
39: 25,
38: 13,
37: 6,
36: 5,
35: 4,
34: 3,
32: 1})
>>> max(counts)
53
Now using the maximum precision, here's the proper way to find the "last digit":
>>> counts = Counter(
... int(f"{random():.53f}".lstrip("0.").rstrip("0")[-1])
... for _ in range(1000000)
... )
>>> counts
Counter({5: 1000000})
Thus, the last digit is always 5. (Or, in very rare cases, 0.) This makes sense since:
2**0 == 1.0
2**-1 == 0.5
2**-2 == 0.25
2**-3 == 0.125
2**-4 == 0.0625
2**-5 == 0.03125
2**-6 == 0.015625
2**-7 == 0.0078125
2**-8 == 0.00390625
2**-9 == 0.001953125
...
2**-k == 0.[k-1 digits]5
And all mantissas are some partial sum of these coefficients.
NOTE: As pointed out by user2357112, the correct implementations to look at are PyOS_double_to_string and format_float_short, but I'll leave the current one in because it's more pedagogically interesting.
A: That's not "the last digit" of the number. That's the last digit of the string str gave you when passed the number.
When you call str on a float, Python gives you enough digits that calling float on the string will give you the original float. For this purpose, a trailing 1 or 9 is less likely to be necessary than other digits, because a trailing 1 or 9 means the number is very close to the value you'd get by rounding off that digit. There's a good chance no other floats are closer, and if so, that digit can be discarded without sacrificing float(str(original_float)) behavior.
If str gave you enough digits to exactly represent the argument, the last digit would almost always be 5, except when random.random() returns 0.0, in which case the last digit would be 0. (Floats can only represent dyadic rationals, and the last nonzero decimal digit of a non-integer dyadic rational is always 5.) The outputs would also be extremely long, looking like
>>> import decimal, random
>>> print(decimal.Decimal(random.random()))
0.29711195452007921335990658917580731213092803955078125
which is one of the reasons str doesn't do that.
If str gave you exactly 17 significant digits (enough to distinguish all float values from each other, but sometimes more digits than necessary), then the effect you're seeing would disappear. There would be a nearly uniform distribution of trailing digits (including 0).
(Also, you forgot that str sometimes returns a string in scientific notation, but that's a minor effect, because there's a low probability of getting a float where that would happen out of random.random().)
| |
doc_23536652
|
I know I could achieve that by nesting MenuItems. Is there another way?
A: I'm not too clear on what you want to do but I suspect a style will be handy. I'll give an example. Here I create a button in a grid that has a context menu. In the Button's resources I create a style (that's not named) for MenuItems. In the style you can specify how the visibilty should behave by replacing the Binding I created.
<Window x:Class="StackOverflow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Content="Testing" VerticalAlignment="Center" HorizontalAlignment="Center">
<Button.Resources>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Visibility" Value="{Binding SomeBinding, Converter=SomeConverter}"/>
</Style>
</Button.Resources>
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="1"/>
<MenuItem Header="2"/>
<MenuItem Header="3"/>
<MenuItem Header="4"/>
</ContextMenu>
</Button.ContextMenu>
</Button>
</Grid>
</Window>
| |
doc_23536653
|
<Grid>
<AbsoluteLayout Grid.Row = 0>
// Contains header
</AbsoluteLayout>
<AbsoluteLayout Grid.Row = 1>
<Scrollview>
<Grid>
<AbsoluteLayout Grid.Row = 0>
// Contains Image
</AbsoluteLayout>
<Grid>
<ListView Grid.Row = 0>
// I know its not good thing to use listview inside scrollview but I have to use it.
</ListView>
<Button Grid.Row = 1 Text = "Add Item1"/>
</Grid>
<Grid>
<ListView Grid.Row = 0>
</ListView>
<Button Grid.Row = 1 Text = "Add Item2"/>
</Grid>
</Grid>
</Scrollview>
</AbsoluteLayout>
<AbsoluteLayout Grid.Row = 2>
// Contains Footer
</AbsoluteLayout>
</Grid>
Now when I navigate to this page on click of button it takes around 3-4 seconds to load which is I think too much.
I have used only 2 StackLayout in footer because I read that Stacklayout slows down the application.
Is there any other way so that I can speed up my navigation ?
EDIT - It takes 1 second to jump from constructor to OnAppearing(). In OnAppeaeing() I fill the lists shown in code.
Thank you so much.
| |
doc_23536654
|
Elasticsearch docker settings
"HostConfig": { "Binds": [ "/mnt/mydisk/data:/usr/share/elasticsearch/data", "/mnt/mydisk/logs:/usr/share/elasticsearch/logs" ],
I changed elasticsearch index settings like below;
{
"index.search": {
"slowlog": {
"level": "info",
"threshold": {
"fetch": {
"warn": "2s",
"trace": "200ms",
"debug": "500ms",
"info": "800ms"
},
"query": {
"warn": "10s",
"trace": "500ms",
"debug": "2s",
"info": "5s"
}
}}}}
I can only see gc.logs in "/mnt/mydisk/logs" path, and there is no "/usr/share/elasticsearch/logs" folder or path.
How can I save slow logs into /mnt/mydisk/logs ?
BTW I can see slow logs via "docker logs elasticsearch" command, but I cannot find where its saved or change the path.
A: You are looking for this properties file: log4j2.properties. If you are using the official elastisearch image, the default setting is to log everything on stdout (i.e. docker logs )
Read more here.
| |
doc_23536655
|
A: Have just found the answer! It was installed in the project already, but I needed to go back into Nuget package manager in order to then install it onto the Unit Test project. Thank you for the suggestions!
| |
doc_23536656
|
I try to make an simple image gallery with backbone. I load 100 images and i want them to fade in if they are loaded.
I have this in my AppView. For every image url I get i create one PhotoView
var view = new PhotoView({model: photo, list:this.imageList});
this.imageList.append(view.render().el);
In the Photoview I use this code to attach the onload() on the img tag (found here):
render: function() {
var self = this;
this.$el.append(some_html_with_img_elements);
this.$el.find('img').on('load', function() { self.img_loaded() });
return this;
}
The problem is that in the img_loaded() i get the same view over and over (the last view). Anyone know how to keep reference to the right view
A: Pass this as an argument to img_loaded, so that you'll get a reference to the image that just loaded, and manipulate it however you want.
Since you didn't post the code for the img_loaded function I'm not sure if you're trying to fade them in one at a time as each is loaded (a simple job once you pass in the image reference), or wait until they're all loaded and fade them all in at once (would need some extra code for that).
A: You can pass referance of view to call back function like this.
var me = this;
me.$el.find("img").on("load", { me: me }, function (event) { event.data.me.img_loaded(); });
| |
doc_23536657
|
In the end the test says that all test cases went through without any problems but in fact they are not executed at all. I set break points in every step method and my debugger doesn't stop me at all not to mention the exceptions that these steps currently throw.
This is my scenario:
Narrative:
In order for the user to start using the application, he first needs to register and log in
Scenario: Successful registration
Given a user with email 'test@test.com'
When the user specifies password 'aaaaaa'
Then the user should be successfully registered with email 'test@test.com' and hashed password 'aaaaaa'
the steps:
public class UserRegistrationSteps extends Steps {
@Given("a user with email '$email'")
public void addNewUser(@Named("email") String email) {
User u = new User();
u.setEmail(email);
throw new RuntimeException("test");
}
@When("the user specifies password '$password'")
public void setPassword(@Named("password") String password) {
System.out.println("test");
throw new RuntimeException("test");
}
@Then("the user should be successfully registered with email '$email' and hashed password '$password'")
public void verifySuccessfulRegistration(@Named("email") String email, @Named("password") String password) {
System.out.println("test");
throw new RuntimeException("test");
}
}
and the test executor:
public class UserRegistrationTest extends JUnitStories {
public UserRegistrationTest() {
super();
this.configuredEmbedder().candidateSteps().add(new UserRegistrationSteps());
}
@Override
protected List<String> storyPaths() {
return Arrays.asList("bdd/users/user_registration.story");
}
}
Any idea what is wrong with it?
A: I'm not sure if it is just simple formatting issue in stackoverflow, but i can see, that you indented your steps in your story file with four whitespaces. I think JBehave will not find the steps this way.
So, your .story file should look like this:
Narrative:
In order for the user to start using the application, he first needs to register and log in
Scenario: Successful registration
Given a user with email 'test@test.com'
When the user specifies password 'aaaaaa'
Then the user should be successfully registered with email 'test@test.com' and hashed password 'aaaaaa'
| |
doc_23536658
|
But the way of adding it it's just by getting it from file name. UILocalNotification has just a property soundName where it gets the sound only by its name on the App Bundle.
I have set a SQLite Database when I save sounds in blob format and get it back to NSData. I need to set this sound which I have and give it as a parameter to localNotification in NSData format.
Here is how I set up the localNotification
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"HH-mm";
NSDate* date = [dateFormatter dateFromString:[dateFormatter stringFromDate:timeToSetOff.date]];
localNotification.soundName = @""; //Here is the line where I am having issues
[localNotification setFireDate:date];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
Has anyone dealt with this before, or implemented this algorithm?
A: fire this method when you receive notification
-(void) playSound {
NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"soundfile" ofType:@"caf"];
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath: soundPath], &soundID);
AudioServicesPlaySystemSound (soundID); }
A: The soundName property only accepts a filename of a sound in you app s bundle. So when you app is running in the foreground you will be able to play the sound with AVplayer or something. You can not use the soundName to store the name. Also saving the sound as blobs will make it harder, just save the file in the documents directory and path to that file in your SQLite database.
Then you pass the path to the sound file in the userInfo of the UILocalNotification.
| |
doc_23536659
|
<Response [422]>]". I have tried the same request using Postman and Curl and it works perfectly. Does anyone know what could be causing this problem? The following curl command works fine.
curl -X 'POST'
'https://cafte.easyredmine.com/projects.json?key=0224b4238XXXX'
-H 'accept: application/json'
-H 'X-Redmine-API-Key: 0224b4238XXX'
-H 'Content-Type: application/json'
-d '{
"project": {
"easy_external_id": "external-system-1",
"name": "Blue 2",
"homepage": "blue-7",
"description": "I can’t abide these Jawas. Disgusting creatures.",
"author_id": 0,
"is_planned": true,
"easy_is_easy_template": true,
"easy_currency_code": "EUR"
}
This is the methode code:
def create_project(self, name: str, description="", external_id="", homepage="", parent_id="", author_id="",
is_planned= 'false', is_easy_template= "true", start_date="", due_date="", custom_fields=[],
tag_list=[], currency='EUR'):
print(name)
data = {"project": {
"easy_external_id": external_id,
"name":name,
"homepage": homepage,
"description": description,
"parent_id": parent_id,
"author_id": author_id,
"is_planned": is_planned,
"easy_is_easy_template": is_easy_template,
"easy_start_date": start_date,
"easy_due_date": due_date,
"custom_fields": custom_fields,
"tag_list": tag_list,
"easy_currency_code": currency
}
}
endpoint_path = "/projects"
endpoint = f'{self.base_url}{endpoint_path}'
headers = {'X-Redmine-API-Key': f'{self.api_key}',
'accept': 'application/json',
'Content-Type': 'application/json'
}
r = requests.post(endpoint, headers=headers, json= data)
| |
doc_23536660
|
In IntelliJ, if you hit shift-enter you get similar behavior minus adding the semicolon. I have read and tried cntrl-shift-enter and you get the exact same behavior. However, that is such an awkward key combination to be using all the time, at least much more so than the one-button approach using Eclipse.
Any ideas?
IntelliJ autocomplete escape
A: In InteiJ IDEA use (Ctrl-Shift-Enter) for "Smart Autocomplete".
It will end the line "smartly" with a semicolon as you wish. It also works in a few different situations like IF statements of FOR loops.
A: Why don't you redo the key binding?
Go to: (spanner icon) Settings -> Keymap -> Complete Current Statement and rebind how you will (for example, ctrl-enter might suit you better).
Or there's also a default keymap set for Eclipse that you can choose. I'm not sure if it affects the complete-current-line action, but you could take a look.
A: you can also use ctrl+shift+space
A: if you want always have it just do this
| |
doc_23536661
|
Thanks,
| |
doc_23536662
|
A: It sounds like you're looking for something like
$('.ShowLink').click(function() {
$('#' + this.rel).toggle();
return false;
});
This will toggle the element with the ID specified by the rel= attribute of each element with the ShowLink class.
For example:
<a href="#" rel="Text1" class="ShowLink">Show something</a>
...
<div id="Text1">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
A: innerHTML method is probably best performance-wise. If you don't retrieve additional content (for example through AJAX calls), put all blocks inside separate divs in advance, and set their "display" css attribute to "none". Then you can trigger attribute change for particular div to "block" with an event attached to some button or link.
A: This could be done by absolutely positioning several divs on top of each other, then showing/hiding the appropriate ones based on user input. This way you don't need to manipulate the content of the elements, just show/hide them. The trick is to absolutely position the elements though. If you do this, you may want to have the last div in the list to be statically positioned (assuming they will all be the same size) so that the rest of the page flows around those elements appropriately. Alternatively you could place all of these elements inside another div that is statically positioned that reserves the space for the absolutely positioned elements.
| |
doc_23536663
|
The index.page is working, but other pages defined in wp_posts table not working properly.
like:
https://mysite.amazonaws.com/?page_id=622
I got 404 not find error.
I use apache2 with configuration:
<Directory /home/admin/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
The .htaccess file is:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
the page editor part do not present the review page properly.
Anyone know where is the problem and how to fix it?
A: find the wp_options table, edit siteurl and home entries with the new url.
A: You can try in following order
*
*Set the permalink to default(Plain ?p=ID) from wp-admin login page (http(s)://site.name/wp-admin/options-permalink.php)
*If this works, then set the permalink to your desired format and try again.
*Try disabling plugins.
*If you domain is changed then you have to update the new website name in wp_options table. Refer to https://codex.wordpress.org/Changing_The_Site_URL
A: Refresh permalink fist after that.
Go to the WordPress backend where you have all pages and data from there you go inside "tool menu " and import all page and content.
After that
Go to another website where you want to migration
and export file which you import from the first WordPress backend
A: 1st methord:
Go to file manager and you can remove the .htaccess file and again refresh the site URL.
2nd method:
Go to settings->permalinks and click the Save button to rewrite flush. And then hard reload the browser. It'll work hopefully.
3rd method:
Go to settings->permalinks edit your permalinks settings as "Custom Structure"
and edit like this /index.php/%postname%/
| |
doc_23536664
|
one two three
Now dw produces:
one three
But vwd produces:
one hree
Is there some setting to make this more consistent, or do I need to write my own custom definition to fix it?
Also, the capital W selector is similarly inconsistent, and I'm wondering if there's a key for visually selecting the same portion that dW would have deleted? Best I can come up with is vfspace which is OK but wondered if there's anything shorter I'm missing that's built in.
A: The w key does the same in both cases, it puts the cursor in the begining of the next word.
What is "inconsistent" is the v command.
In the first case dw means, delete up to, but not including, the cursor.
In the second case vwd deletes the selection, however the selection includes the cursor. You can clearly see this when you do vw.
A: yes there is one option: selection which default is inclusive. it makes v to select the last char.
:h 'selection'
to check detail.
w is exclusive motion. but if in visual mode, it depends on the selection setting.
you could set selection to exclusive to make vwd and dw to behave identical.
| |
doc_23536665
|
And it gives me next output:
Windows PowerShell Copyright (C) 2009 Microsoft Corporation. All rights reserved.
Host receive failed 10054
So looks like it calls powershell, but next commands are not passed as input, nothing happens, so Process exited with timeout.
Why? Does PowerShell has some specific input, so it can't be launched like this? Any workarounds?
PS executed like next:
RemoteExecute.ExecutePowerShell(testPSName, testIp, testUserName, testPasswd);
ExecutePowerShell:
FTPTransfer.SendBinary(shellScriptName, ipaddress, userName, password); // This one sends script to remote system. Works OK.
string fullFilePath = "\"" + FTPTransfer.UploadDirectoryRootPath + shellScriptName + "\"";
string cmd;
using (StringWriter sw = new StringWriter())
{
//sw.WriteLine("powershell.exe"); // Tried launch remexec with cmd, and then pass powershell as first parameter. Results the same, as now, so no matter.
sw.WriteLine("Set-ExecutionPolicy RemoteSigned");
sw.WriteLine(fullFilePath);
cmd = sw.ToString();
}
result = ExecutePSCommandWithInput(cmd, ipaddress, userName, password);
ExecutePSCommandWithInput:
//command = cmd from ExecutePowerShell
string remexecCmd = "remexec.exe";
string remexecArgs = string.Format("{0} -q -t {1} -l {2} -p {3} powershell.exe 2>&1", ipaddress, timeout, userName, password);
result = Common.ExecuteCmdWithInput(remexecCmd, remexecArgs, command, out outp, timeout);
ExecuteCmdWithInput:
public static int ExecuteCmdWithInput(string mainCmd, string arguments, string commands, out string output, int timeout = 60000)
{
List<string> commandsArr = new List<string>();
using (StringReader sr = new StringReader(commands))
{
string line = sr.ReadLine();
while (!string.IsNullOrEmpty(line))
{
commandsArr.Add(line);
line = sr.ReadLine();
}
}
return ExecuteCmdWithInput(mainCmd, arguments, commandsArr.ToArray(), out output, timeout);
}
public static int ExecuteCmdWithInput(string mainCmd, string arguments, string[] commands, out string output, int timeout = 60000)
{
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = mainCmd;
p.StartInfo.Arguments = arguments;
p.Start();
using (StreamWriter inputWriter = p.StandardInput)
{
foreach(string line in commands)
{
inputWriter.WriteLine(line);
}
}
output = p.StandardOutput.ReadToEnd();
output += Environment.NewLine;
output += p.StandardError.ReadToEnd();
p.WaitForExit(timeout);
return p.ExitCode;
}
A: PowerShell doesn't use standard input or output, so I had to use workaround, or different implementation.
Solved like this:
string remexecArgs = string.Format("{0} -q -t {1} -l {2} -p {3} cmd 2>&1", ipaddress, timeout, userName, password);
and as input passed next:
using (StringWriter sw = new StringWriter())
{
sw.WriteLine("powershell.exe -Command Set-ExecutionPolicy RemoteSigned");
sw.WriteLine();
string logFilePath = "\"" + FTPTransfer.UploadDirectoryRootPath + shellScriptName + ".log\"";
sw.WriteLine("powershell.exe -File " + fullFilePath + " " + (pars ?? string.Empty) + "> " + logFilePath);
sw.WriteLine();
sw.WriteLine();
sw.WriteLine("type " + logFilePath);
cmd = sw.ToString();
}
ExecuteOneCommandWithInput(cmd, ipaddress, userName, password, timeoutS);
Empty lines are nesesery, otherwise it stucks
And small hack added to process itself:
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = mainCmd;
p.StartInfo.Arguments = arguments;
p.Start();
using (StreamWriter inputWriter = p.StandardInput)
{
foreach(string line in commands)
{
//Wait before next input in case when empty string passed
if (string.IsNullOrEmpty(line))
System.Threading.Thread.Sleep(1000 * 2);
inputWriter.WriteLine(line);
}
}
output = p.StandardOutput.ReadToEnd();
output += Environment.NewLine;
output += p.StandardError.ReadToEnd();
p.WaitForExit(timeout);
| |
doc_23536666
|
<button onclick="document.getElementById('myImage').src='C:\Users\81001876\Desktop\On.png'">Turn on the light</button>
<button onclick="document.getElementById('myImage').src='C:\Users\81001876\Desktop\Off.png'"> Turn off the light</button>
JavaScript Unable to change the value of the src attribute of an image
A: The first obstacle to overcome is to have the backslash separators in the image file path recognized in a JavaScript string : if you use \ before a character which is not special in JavaScript strings the backslash is ignored without generating an error.
E.G. Source string "C:\Users\81001876\Desktop\On.png" is decoded by the JavaScript compiler as
C:Users81001876DesktopOn.png
Choices are to either backslash-escape the backslahes in source code:
C:\\Users\\81001876\\Desktop\\On.png
or convert them to forward slashes because (these days) Windows accepts both forward or backslash separators in file paths. E.G.
C:/Users/81001876/Desktop/On.png
After fixing the backslash issue, Windows absolute filepaths are not valid href value and should be converted to use the file:// protocol before setting image src attributes: E.G.
sr="file:///C:/Users/81001876/Desktop/On.png"
Note that file:// protocol based URLs do not accept backslash separators which means there are advantages to converting them to forward slashes early on.
Not withstanding the above, Microsoft used to support windows filenames in some versions of IE. This was and remains non-standard and should not be used outside of a code laboratory.
| |
doc_23536667
|
In addition, for Cloud Data Fusion from google, I noticed that it could achieve real time from mysql/postgresql to cloud spanner, but I did not find the way go from cloud spanner to pubsub/kafka in real time.
Also, I found another two ways, which to be listed here for any comments or suggestions.
*
*Use Debezium, a log-based change data capture Kafka connector from the link https://cloud.google.com/architecture/capturing-change-logs-with-debezium#deploying_debezium_on_gke_on_google_cloud
*Create a polling service (which may miss some data) to poll data from cloud spanner from the link: https://cloud.google.com/architecture/deploying-event-sourced-systems-with-cloud-spanner
If you have any suggestion or comment on this, I will be really grateful.
A: There's a open source implementation of a polling service for Cloud Spanner that can also automatically push changes to PubSub here: https://github.com/cloudspannerecosystem/spanner-change-watcher
It is however not log-based. It has some inherent limitations:
*
*It can miss updates if the same record is updated twice within the polling interval. In that case, only the last value will be reported.
*It only supports soft deletes.
You could have a look at the samples to see if it is something that might suit your needs at least to some degree: https://github.com/cloudspannerecosystem/spanner-change-watcher/tree/master/samples
A: Cloud Spanner has a new feature called Change Streams that would allow building a downstream pipeline from Spanner to PubSub/Kafka.
At this time, there's not a pre-packaged Spanner to PubSub/Kafka connector.
The way to read change streams currently is to use the SpannerIO Apache Beam connector that would allow building the pipeline with Dataflow, or also directly querying the API.
Disclaimer: I'm a Developer Advocate that works with the Cloud Spanner team.
| |
doc_23536668
|
components/Root.js
import React from 'react';
import { Provider } from 'react-redux';
import App from './App'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
const Root = ({ store }) => (
<Provider store={store}>
<Router>
<Switch>
<Route exact path='/' component={ App }/>
<Route path="/:filter" component={ App }/>
</Switch>
</Router>
</Provider>
);
export default Root;
components/Footer.js
import React from 'react'
import FilterLink from '../containers/FilterLink'
const Footer = () => (
<p>
Show:
{" "}
<FilterLink filter="all">
All
</FilterLink>
{", "}
<FilterLink filter="active">
Active
</FilterLink>
{", "}
<FilterLink filter="completed">
Completed
</FilterLink>
</p>
)
export default Footer
containers/FilterLink.js
import React from 'react';
import { NavLink } from 'react-router-dom'
const FilterLink = ({ filter, children }) => {
console.log("filter: "+filter);
console.log("children: "+children);
return (
<NavLink
to={filter === 'all' ? '' : filter}
activeStyle={{
textDecoration: 'none',
color: 'black',
}}
>
{children}
</NavLink>
);
}
export default FilterLink;
The results i get are:
As per the code the active link should be same as the URL. Even the URL shows "localhost:3008/active" the active link shows as "all" and similar to completed.
Whats going wrong and why the corresponding link is not getting activated as per the URL.
A: Try adding a /
const FilterLink = ({ filter, children }) => {
console.log("filter: "+filter);
console.log("children: "+children);
return (
<NavLink
// / is added via string interpolation
to={filter === 'all' ? '' : `/${filter}`}
activeStyle={{
textDecoration: 'none',
color: 'black',
}}
>
{children}
</NavLink>
);
}
or
import React from 'react'
import FilterLink from '../containers/FilterLink'
const Footer = () => (
<p>
Show:
{" "}
<FilterLink filter="/all">
All
</FilterLink>
{", "}
<FilterLink filter="/active">
Active
</FilterLink>
{", "}
<FilterLink filter="/completed">
Completed
</FilterLink>
</p>
)
export default Footer
and update the check in the FilterLink Component:
to={filter === '/all' ? '' : filter}
| |
doc_23536669
|
<script>
document.getElementById("demo").innerHTML = Math.floor(Math.random()*50)*2;
document.cookie="document.getElementById("demo").value";
</script>
<script>
var x = document.value;
document.getElementById("number").innerHTML = "x"
</script>
A: This is from Mozilla Document.cookie docs:
document.cookie = "name=oeschger";
document.cookie = "favorite_food=tripe";
alert(document.cookie);
// displays: name=oeschger;favorite_food=tripe
A: Check out the W3Schools tutorial on cookies. As for your case, this is how you implement it:
<!-- Start of the Application -->
<script>
document.getElementById("demo").innerHTML = Math.floor(Math.random()*50)*2;
// Following functions from W3Schools
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
// set a cookie "number" to the `innerHTML` of the element with Id `demo`.
setCookie("number",document.getElementById("demo").innerHTML,365);
</script>
<!-- End of the application -->
<script>
// get the value of the cookie "number" that was set earlier
var x = getCookie("number");
// Change the Id to whatever you need
document.getElementById("whatever").innerHTML = x;
</script>
| |
doc_23536670
|
how can i solve this problem ? I am getting the error in the picture. What is the solution of this error? react-native code =>
how can i solve this problem ? I am getting the error in the picture. What is the solution of this error? react-native code =>
const Listdesing = (props) => {
const isDarkMode = useDarkMode();
return(
<TouchableOpacity onPress={() => this.props.navigation.navigate('Detail',{
text: 'item.text',
name: 'item.title'
})}>
<ListItem
titleStyle={{ color: isDarkMode ? 'white' : 'black' }}
containerStyle={{ backgroundColor: isDarkMode ? '#1C1C1E' : '#FFFFFF' }}
key={props.id}
title={props.title}
rightIcon={{ name: 'chevron-right', color: isDarkMode ? 'white' : 'black' }}
/>
</TouchableOpacity>
)}
class Direm extends Component{
state = {
text: '',
contact : []
};
componentDidMount() {
this.getContacts();
}
getContacts = async () => {
const {data: { Konular } } = await axios.get('www.site.com');
this.setState({
contact: Konular,
});
console.log(Konular)
};
renderContactItem = ({ item, index }) => {
return(
<Listdesing
id={item.id}
title={item.title}
/>
)
};
render(){
return(
<FlatList
renderItem={this.renderContactItem}
keyExtractor={(item) => item.id}
data={this.state.contact}
/>
)
}}
const Ana = ({navigation}) => {
//const isDarkMode = useDarkMode();
return(
<Direm />
)}
A: It seems like you are trying to access this.props.navigation when you are only storing props.navigation, try this:
const Listdesing = (props) => {
const isDarkMode = useDarkMode();
return(
<TouchableOpacity onPress={() => props.navigation.navigate('Detail',{ // This should be props.navigation, not this.props.navigation
text: 'item.text',
name: 'item.title'
})}>
<ListItem
titleStyle={{ color: isDarkMode ? 'white' : 'black' }}
containerStyle={{ backgroundColor: isDarkMode ? '#1C1C1E' : '#FFFFFF' }}
key={props.id}
title={props.title}
rightIcon={{ name: 'chevron-right', color: isDarkMode ? 'white' : 'black' }}
/>
</TouchableOpacity>
)}
| |
doc_23536671
|
A: REST is based on HTTP.
In HTTP you do not know if you data is cached somewhere. It may be in the browser or in any node in between the client and the server.
However your REST-Server may add the Cache-Control HTTP header to its response, e.g. Cache-Control: No-Cache to mark the response as not to cache.
It is not assured if this will not be ignored by a proxy or whatever.
Your client can also request to not cache data. In jquery you just add cache: no to the AJAX-request and it will do the trick.
If jquery is not available you will have to use the if-modified-since header (http://www.w3.org/Protocols/HTTP/HTRQ_Headers.html#if-modified-since).
A: Probably this post cleared my doubt.
http://www.openlogic.com/wazi/bid/283625/Caching-web-service-results-can-enhance-Apache-application-performance.
| |
doc_23536672
|
data Attributes
= TextAlignment TextAlign
| TextScale String
| LineHeight String
instance encodeAttributes :: EncodeJson Attributes where
encodeJson r =
case r of
(TextAlignment p) ->
"key" := (fromString "text-align")
~> "value" := p
(TextScale p) ->
"key" := (fromString "font-size")
~> "value" := p
(LineHeight p) ->
"key" := (fromString "line-height")
~> "value" := p
instance decodeElementAttributes :: DecodeJson ElementAttributes where
decodeJson json = do
obj <- decodeJson json
key <- getField obj "key"
value <- getField obj "value"
case key of
"text-align" -> Right $ TextAlignment value
"font-size" -> Right $ TextScale value
"line-height" -> Right $ LineHeight value
_ -> Left "Unkown element property"
data TextAlign
= LeftAlign
| RightAlign
| CenterAlign
| Justify
instance encodeTextAlign :: EncodeJson TextAlign where
encodeJson r =
case r of
LeftAlign -> fromString "left"
RightAlign -> fromString "right"
CenterAlign -> fromString "center"
Justify -> fromString "justify"
instance decodeTextAlign :: DecodeJson TextAlign where
decodeJson obj = do
case toString obj of
Just "left" -> Right LeftAlign
Just "right" -> Right RightAlign
Just "center" -> Right CenterAlign
Just "justify" -> Right Justify
Just _ -> Left "Unknown alignment"
Nothing -> Left "Unknown alignment"
This gives the following error
Could not match type
TextAlign
with type
String
while checking that type t0
is at least as general as type String
while checking that expression value
has type String
in value declaration decodeElementAttributes
where t0 is an unknown type
Basically, I would like to know what would be the proper way to decode a Sum type like Attributes in this case
A:
(..) But the following does not work
TLDR; This should work:
instance decodeElementAttributes :: DecodeJson Attributes where
decodeJson json = do
obj <- decodeJson json
key <- getField obj "key"
case key of
"text-align" -> TextAlignment <$> getField obj "value"
"font-size" -> TextScale <$> getField obj "value"
"line-height" -> LineHeight <$> getField obj "value"
_ -> Left "Unkown element property"
Let's jump into compiler shoes for a moment and try to infer the value type.
In the monadic block in decodeJson there is a call to getField:
value <- getField obj "value"
getField is polymorphic on its return type:
getField :: forall a. DecodeJson a => Object Json -> String -> Either String a
So from this call alone we are not able to guess the type of the value. We need some more information / context.
But luckily few lines below we can find a usage of value which gives us some solution:
"text-align" -> Right $ TextAlignment value
So for sure our value has to be typed as TextAlign because TextAlignment constructor expects such a parameter.
But wait... just line underneath there is another usage of value:
"font-size" -> Right $ TextScale value
and here we have a problem because this tells us that value has type String and... TextAlign at the same time...
We have no other choice than tell the World about our discovery:
Could not match type
TextAlign
with type
String
Basically, I would like to know what would be the proper way to decode a Sum type like Attributes in this case
*
*Your approach is OK to me. It gives you full control over coding / decoding process. It can be error prone though...
*You can give a try and use fully generic solution like purescript-argounaut-generic.
*You can also try different generic approach and use purescript-simple-json. I wasn't able to find example for generic sum handling - here is only enum like type encoded / decoded: https://www.reddit.com/r/purescript/comments/7b5y7q/some_extra_examples_of_simplejson_usage/. You can always ask Justin Woo for suggestions - he is really responsive author :-)
*I haven't used purescript-codec-argonaut yet but it should help you minimize some duplication related to coding and decoding definitions. With this approach you are still responsible for defining everything by hand I think.
*Here is interesting post, which I think is mostly relevant if you do not have PureScript on both ends of the wire (consumer and producer) by @garyb about downsides of generic codecs: http://code.slipthrough.net/2018/03/13/thoughts-on-typeclass-codecs/
Do you have PureScript on both ends of the wire?
| |
doc_23536673
|
import csv
lines2 = open('TopUni.csv','r')
open = csv.DictReader(lines2)
counter2 = 0
country = []
for i in open:
counter2 += 1
country.append(i['Country'])
country_upper = [country.upper() for country in country ]
country_dictionary = dict.fromkeys(country_upper)
x = country_dictionary.keys()
result = ', '.join(str(item) for item in list(country_dictionary.keys()) )
print('Available countries =>',result)
#Function 3 Available Continets
lines3 = open('capitals.csv','r')
open2 = csv.DictReader(lines3)
counter3 = 0
continent = []
for i in open2:
counter3 += 1
continent.append(i['Continent'])
continent_upper = [continent.upper() for continent in continent ]
continent_dictionary = dict.fromkeys(continent_upper)
x = continent_dictionary.keys()
result = ', '.join(str(item) for item in list(continent_dictionary.keys()) )
print('Available continents =>',result)
I tried to make is work but nothing i seem to be doing is working. I tried to make all the vairbles the same but I'm still getting a error. One way I can try is to make these 2 parts into functions instead of keeping it as the main.
| |
doc_23536674
|
I have tried field formatting
I want the user to see the state in this format but when the user selects the state, I would like the field to only read "FL" and not the entire name as stated before the selection is made. So when the drop down activates you see the name but after selected only the abbreviation is displayed.
A: Make sure the states are in two columns, first column the abbreviation, second column the full name. Set the following properties for the combobox:
*
*BoundColumn: 2 (or 1 if you want the linkedcell to receive the
abbreviated state name)
*ColumnCount: 2
*ListSource: A1:B55 (or wherever your states are located)
*ColumnWidths: 30;100
Now if the dropdown is "dropped" you see both abbreviation and full state name. If the state is chosen, it only displays the abbreviation.
| |
doc_23536675
|
Situation
(Requirements: Handle input keys without changing the Android Framework.)
I want to handle key events coming from a device (keyboard/gamepad/controller/...) but there are some requirements. For one, I don't want to change the Android framework. This means, I don't want to extends the WindowManagerPolicy and its functions like interceptKeyBeforeDispatching where the home-key is being handled. This would result in the key event being dispatched into the application layer which is fine. The downside is, I have another tricky requirement here.
Example: When I am playing Angry Birds and I press my GoToAlpha-button on my connected input device, the Alpha-application has to start. Angry Birds has no clue which button GoToAlpha is, will not handle/recognize it and there will be for example no intent broadcasted to start my Alpha-application.
Question
Is there a way to handle my (custom) key event after it is being dispatched, knowing that the application in the foreground can not handle the key?
My (failed) solutions
*
*Create a service which will handle the key events. This is not possible because an application like Angry Birds will not bind to my service and the key event will not be caught inside my service. If I am wrong, please provide more information :).
*Create an external library where I allow my application's activities to inherit from my own ActivityBase. All the key events and there default behavior can be handled here. Downside, existing applications will not support my custom key events because they don't use the library.
*Extend the framework would be in my eyes the cleanest solution but that will result in not meeting my requirement.
Any help or useful information would be appreciated
Extra
If the first question could be solved on one way or another.. I want
to customize my Intent behind the GoToAlpha-button. This means.. By
default the Alpha-application will be started but after the user has
customized it, the Beta-application will be started from now on.. Any
thoughts?
Thanks
A: Thanks for the comment Victor.
Using the InputMethodService will not provide me with enough freedom and functionality to handle my problems.
My Solution / Compromise
Within the Android Framework, there is a PhoneWindowManager which is responsible for handling InputEvents. The WindowManagerService which is started by the SystemServer, is owner of this manager and creates an instance.
By creating my own custom WindowManager and let it inherit from Android's PhoneWindowManager, I don't lose any default functionality and this allows me to add my own implementation within this class. This results is adding a new file to the framework and changing only one line inside the Android Framework: The WindowManagerService will not create a PhoneWindowManager, but will create a CustomPhoneWindowManager (extends PhoneWindowManager).
If anyone sees a better solution or has any specific thoughts about my compromis, don't hesitate to comment. :)
A: I doubt that it's possible with public API's (Boy and Martijn pointed out security concerns).
Most like your best bets (if you don't want to customize Android) would be
a) Try to use InputMethodService (http://developer.android.com/reference/android/inputmethodservice/InputMethodService.html)
It doesn't give that kind of control which you wish, but it could be enough for some needs.
b) Try to go through whole stack (from Kernel to Application) and find some vulnerabilities to use.
This definitely will take a lot of time and doesn't guarantee to bring any fruits.
| |
doc_23536676
| ||
doc_23536677
|
class EditUserView(LoginRequiredMixin, UserPassesTestMixin, TemplateView):
"""handles get and post for adding a new AEUser"""
template_name = 'editUser.html'
title = 'Edit User'
def get(self, request, *args, **kwargs):
"""handles the GET"""
post_url = reverse('edit_user', args=[kwargs['user_id']])
usr = get_object_or_404(AEUser, pk=kwargs['user_id'])
form = EditUserForm(initial={'is_active':usr.is_active, 'is_superuser':usr.is_superuser}, \
user=usr, request=request)
return render(request, self.template_name, \
{'title_text':self.title, 'post_url':post_url, 'form':form})
The Test Case:
class TestEditUser(TestCase):
"""test the AddUser view"""
@classmethod
def setUpTestData(cls):
cls.user = AEUser.objects.create_user(username='shawn', email='shawn@gmail.com', password='test')
cls.user.is_superuser = True
cls.user.save()
def setUp(self):
self.client = Client()
def test_get(self):
"""tests the GET"""
self.client.login(username=self.user.username, password=self.user.password)
get_url = reverse('edit_user', args=[self.user.id])
response = self.client.get(get_url, follow=True)
self.assertEqual(self.user.is_superuser, True)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'editUser.html')
I have 3 asserts in the test case. If I comment out the last two, and only assert that the user is a superuser, the test passes. For whatever reason, though, on the other two asserts, I get failures. The error I receive is:
AssertionError: False is not true : Template 'editUser.html' was not a template used to render the response. Actual template(s) used: 404.html, base.html, which leads me to believe the get_object_or_404 call is what's triggering the failure. Where am I going wrong with this test case? Thanks!
A: Test should be:
class TestEditUser(TestCase):
"""test the AddUser view"""
@classmethod
def setUpTestData(cls):
cls.user = AEUser.objects.create_user(username='shawn', email='shawn@gmail.com', password='test')
cls.user.is_superuser = True
cls.user.save()
def setUp(self):
self.client = Client()
def test_get(self):
"""tests the GET"""
self.client.login(username=self.user.username, password='test')
get_url = reverse('edit_user', args=[self.user.id])
response = self.client.get(get_url, follow=True)
self.assertEqual(self.user.is_superuser, True)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'editUser.html')
| |
doc_23536678
|
I get the following error message when I'm trying to access my 3.5 sdf/database using the new CE4.0 connection provide :-
System.Data.EntityException: The underlying provider failed on Open. ---> System.Data.SqlServerCe.SqlCeInvalidDatabaseFormatException: The database file has been created by an earlier version of SQL Server Compact. Please upgrade using SqlCeEngine.Upgrade() method.
Anyone know how I can do this? Obviously I need to do it programatcially but i'm not sure what I should do / what references I need to add, etc.
Cheers!
A: Call System.Data.SqlServerCe.SqlCeEngine.Upgrade. See MSDN, which contains sample code.
A: You needn't upgrade when you see this error:
The database file has been created by an earlier version of SQL Server Compact. Please upgrade using SqlCeEngine.Upgrade() method.
Simply:
*
*Right-click your Project in Solution Explorer
*Choose properties, go to References tab
*You'll see a reference called: System. Data.SqlServerCe Type/net version/4.0 - delete this item (select item and then click remove in the bottom of this window).
*Click on the "add..." button left of the "remove" button
*In the .NET tab, find System.Data.SqlServerCe 3.5 and add this.
*Compile your project!
I think this will work.
| |
doc_23536679
|
Neither tf workspace nor tf workfold seem to allow it or am I missing the obvious?
A: You can use the tf workfoldcommand to list the working folders (including the cloaked folders) from a specific workspace:
tf workfold /workspace:YourWorkspaceName /collection:http://server:8080/tfs/defaultcollection
Please see Workfold Command for details.
| |
doc_23536680
|
*
*mocha
*flexmock
*rr
Upvote to anyone who can give me a decent answer as far as pros and cons on at least one of these frameworks versus rspec's own mocking framework.
I'll accept an answer if you can give me a break down on all three versus rpsec
| |
doc_23536681
|
When I checked from Google Chrome Dev Tools, I noticed that the corresponding input field has no "click" event listener attached to it. In Primefaces Showcase the input fields has "click" event listener so when you click, calendar shows up.
I am also having the same trouble with sorting of datatable. The column has no "click" event listener, so it does not send any request when the header of a sortable column is clicked.
Please help me with that problem.
P.S: The application I am working on was a JSF 1.2 application and were using JWL libraries of IBM. Since I am upgrading the application to JSF 2, I am not able to use that library anymore. That's way I am trying to integrate Primefaces. primefaces-5.2.jar is placed under /WEB-INF/lib and I also still have jsf-ibm.jar, odc-jsf.jar in that directory.
A: try to create a lib folder out of the meta-inf and PrimeFaces put the library, or you could also try creating a page with the component PrimeFaces calendar to see if it works and put in
<html xmlns:p="http://primefaces.org/ui"</html>
A: Are you sure that you save your XHTML file with proper extension? If you have deafult settings it would be *.jsp as far as I remember
| |
doc_23536682
|
A: The getting started guides using docker (both the single and multi-nodes examples) are not meant to be used in a production deployment. They are meant to provide the lowest friction path to getting a cluster running where you can experiment with the Kubernetes concepts in a running cluster.
If your choices are between running a variant of the docker multi-node configuration and bare metal on Ubuntu, I would definitely recommend running on Ubuntu. See the Kubernetes Deployment On Bare-metal Ubuntu Nodes getting started guide.
| |
doc_23536683
|
data={'product_id':['a','a','b','b'],
'start':[datetime.date(2016,1,1),datetime.date(2016,1,1),datetime.date(2016,1,3),datetime.date(2016,1,1)],
'end':[datetime.date(2016,1,4),datetime.date(2016,1,3),datetime.date(2016,1,4),datetime.date(2016,1,3)],
'store':['X','Y','X','Y']}
df=pd.DataFrame.from_dict(data)
sales={'date':[datetime.date(2016,1,1),datetime.date(2016,1,2),datetime.date(2016,1,3),datetime.date(2016,1,4),
datetime.date(2016,1,1),datetime.date(2016,1,2),datetime.date(2016,1,3),datetime.date(2016,1,4),
datetime.date(2016,1,1),datetime.date(2016,1,2),datetime.date(2016,1,3),datetime.date(2016,1,4),
datetime.date(2016,1,1),datetime.date(2016,1,2),datetime.date(2016,1,3),datetime.date(2016,1,4)],
'product':['a','a','a','a','b','b','b','b','a','a','a','a','b','b','b','b'],
'store':['X','X','X','X','X','X','X','X','Y','Y','Y','Y','Y','Y','Y','Y'],
'sales':[20,30,59,110,30,40,80,20,80,59,110,30,40,80,20,10]}
df2=pd.DataFrame.from_dict(sales)
I want to summarize the sales for each of the product by store per the time range defined in df. In excel I can use sumifs function but not sure how to do this in python. Can someone help me? Thank you!
A: You can merge your date ranges to the sales data the look for records between the ranges and do a groupby/sum on that.
df = df2.merge(df, left_on=['store','product'], right_on=['store', 'product_id'])
df.loc[df['date'].between(df['start'], df['end'])].groupby(['store','product'])['sales'].sum().reset_index(name='total_sales')
Output
store product total_sales
0 X a 219
1 X b 100
2 Y a 249
3 Y b 140
| |
doc_23536684
|
*
*http://golem.tk/pictures/embossed.jpg
I started out with photoshop, I thought it would be easy to change to css, but clearly its not. here is the photoshop file (.psd)
*
*golem.tk/pictures/embossed.psd
------------------- edit ---------------------
I created another embossed layer in photoshop but this time with shadows and glows.
*
*http://golem.tk/pictures/embossed2.psd
Then i used CSS3Ps to change it into css code, what i got was:
body{
background-color: #949494;}
.shape4{
width: 300px;
height: 44px;
-webkit-border-radius: 10px;
-moz-border-radius: l0px;
border-radius: 10px;
background-color: #949494;
-webkit-box-shadow: 0 0 20px rgba(31,31,31,.2),
5px 9px 10px rgba(224,224,224,.65),
inset 5px 9px l0px rgba(31,31,31,.6),
inset 0 0 25px rgba(224,224,224,.25);
-moz-box-shadow: 0 0 20px rgba(31,31,31,.2),
5px 9px 10px rgba(224,224,224,.65),
inset 5px 9px 10px rgba(31,31,31,.6),
inset 0 0 25px rgba(224,224,224,.25);
box-shadow: 0 0 20px rgba(31,31,31,.2),
5px 9px 10px rgba(224,224,224,.65),
inset 5px 9px 10px rgba(31,31,31,.6),
inset 0 0 25px rgba(224,224,224,.25);}
Unfortunately there is no glow effect (thus making it less smooth)... how can i fix this?
A: You would just use 3 divs and box-shadows, like this:
FIDDLE
CSS
#embossedboxbefore {
background-color:#777;
width: 210px;
height: 60px;
top:0px;
left:0px;
position:absolute;
-webkit-box-shadow: -1px -1px 8px 3px rgba(119,119,119,1);
-moz-box-shadow: -1px -1px 8px 3px rgba(119,119,119,1);
box-shadow: -1px -1px 8px 3px rgba(119,119,119,1);
}
#embossedbox {
background-color:#949494;
width: 200px;
height: 50px;
top:5px;
left:5px;
position:absolute;
-webkit-box-shadow: 0px 0px 15px 3px rgba(148,148,148,1);
-moz-box-shadow: 0px 0px 15px 3px rgba(148,148,148,1);
box-shadow: 0px 0px 15px 3px rgba(148,148,148,1);
}
#embossedboxafter {
background-color:#a5a5a5;
width: 205px;
height: 55px;
top:5px;
left:5px;
position:absolute;
-webkit-box-shadow: 2px 2px 8px 2px rgba(165,165,165,1);
-moz-box-shadow: 2px 2px 8px 2px rgba(165,165,165,1);
box-shadow: 2px 2px 8px 2px rgba(165,165,165,1);
}
HTML
<div id="embossedboxbefore">
</div>
<div id="embossedboxafter">
</div>
<div id="embossedbox">
</div>
Method Two
In this instance, you'd only use one div and multiple box-shadows. To use multiple box shadows, you simply put a comma after the first shadow's parameters - on the same line still - and enter the second shadow's parameters. The shadows are stacked in reverse order from the position you write them in; the last shadow you create on the line will be on top, and the first shadow in the line will be on the bottom.
I couldn't get it to look quite right in the JSFiddle, but you could try messing with the parameters to get it to look better. I'm just giving you possible solutions, not desinging it for you.
FIDDLE
CSS
#embossedbox {
background-color:#949494;
width: 200px;
height: 50px;
top:5px;
left:5px;
position:absolute;
-webkit-box-shadow: 0px 0px 10px 4px rgba(148,148,148,1),-4px -6px 15px 4px rgba(119,119,119,1),5px 6px 15px 3px rgba(165,165,165,1);
-moz-box-shadow: 0px 0px 10px 3px rgba(148,148,148,1),-4px -6px 15px 4px rgba(119,119,119,1),5px 6px 15px 3px rgba(165,165,165,1);
box-shadow: 0px 0px 10px 4px rgba(148,148,148,1),-4px -6px 15px 4px rgba(119,119,119,1),5px 6px 15px 3px rgba(165,165,165,1);
}
HTML
<div id="embossedbox">
</div>
| |
doc_23536685
|
I know that mysql allows import of xml data using the example xml structure below:
<row>
<field name='column1'>value1</field>
My problem is that phpPgAdmin has exported the data in this format:
<row>
<column name='column1'>value1</column>
Is there a way to map or SET the column name so I can import using LOAD XML LOCAL INFILE?
A: You've probably long since figured this out, but this answer from SO: LOAD XML LOCAL INFILE with Inconsistent Column Names should show you how if you have not. I'm new to MySQL and working with a very similar problem to yours. Hopefully this will help someone else if not you.
| |
doc_23536686
|
A: You should be able to create a folder inside the plugin folder with the name of your plugin. Inside that folder you could create a 'style.css' sheet or something that you reference from within your plugin. Just use that with your elements used in your plugin..
A quick glance into my plugins content folder on a local development site and I was able to nab this from a plugin that loads it's own css sheet, they implemented it like so:
$doc->addStyleSheet(JURI::base() . "plugins/content/componentname/style.css");
So that component grabs it's css from that style.css sheet and all of the elements created by that plugin use the appropriate classes/id's.
So I guess you could do something similar - create a folder called 'finarchivo' in the folder, then create a css sheet called 'style.css' within that folder.
In your finarchivo.php sheet you would then load that CSS sheet using a method similar to what I wrote above:
$doc->addStyleSheet(JURI::base() . "plugins/content/finarchivo/style.css");
A: enter code here
$document =JFactory::getDocument();
$document->addStyleSheet(JURI::base() . 'yor address');
$style =' your css';
$document->addStyleDeclaration( $style );
| |
doc_23536687
|
Here is a excerpt of the Symbolized log file:
Thread 0 name: tid_303 Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0 libsystem_kernel.dylib 0x0000000183b0d2ec __pthread_kill + 8
1 libsystem_pthread.dylib 0x0000000183cb26a8 pthread_kill$VARIANT$armv81 + 360
2 libsystem_c.dylib 0x0000000183a7bdb0 __abort + 152
3 libsystem_c.dylib 0x0000000183a7bd18 __abort + 0
4 Caregiver.iOS 0x0000000101fea8a8 xamarin_get_block_descriptor + 4536
5 Caregiver.iOS 0x0000000101f19e98 mono_invoke_unhandled_exception_hook + 19177112 (exception.c:1119)
6 Caregiver.iOS 0x0000000101edaa88 mono_handle_exception_internal + 18918024 (mini-exceptions.c:2080)
7 Caregiver.iOS 0x0000000101ed97d0 mono_handle_exception + 18913232 (mini-exceptions.c:2371)
8 Caregiver.iOS 0x0000000101ed1da4 mono_arm_throw_exception + 18881956 (exceptions-arm64.c:414)
9 Caregiver.iOS 0x0000000100ffcdb8 throw_exception + 168
10 Caregiver.iOS 0x0000000101fea68c xamarin_get_block_descriptor + 3996
11 Caregiver.iOS 0x000000010180ea04 wrapper_native_to_managed_ObjCRuntime_Runtime_throw_ns_exception_intptr + 308
12 CoreFoundation 0x00000001840871c8 __handleUncaughtException + 828
13 libobjc.A.dylib 0x00000001832408c8 _objc_terminate+ 35016 () + 112
14 libc++abi.dylib 0x000000018323137c std::__terminate(void (*)+ 111484 ()) + 16
15 libc++abi.dylib 0x0000000183231400 std::terminate+ 111616 () + 84
16 libdispatch.dylib 0x0000000183978af8 _dispatch_client_callout + 36
17 libdispatch.dylib 0x00000001839b57a8 _dispatch_continuation_pop$VARIANT$armv81 + 416
18 libdispatch.dylib 0x00000001839bec20 _dispatch_source_invoke$VARIANT$armv81 + 1248
19 libdispatch.dylib 0x00000001839b9c44 _dispatch_main_queue_callback_4CF$VARIANT$armv81 + 680
20 CoreFoundation 0x000000018402f070 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 12
21 CoreFoundation 0x000000018402cbc8 __CFRunLoopRun + 2272
22 CoreFoundation 0x0000000183f4cda8 CFRunLoopRunSpecific + 552
23 GraphicsServices 0x0000000185f2f020 GSEventRunModal + 100
24 UIKit 0x000000018df2d78c UIApplicationMain + 236
25 Caregiver.iOS 0x000000010180d6a0 wrapper_managed_to_native_UIKit_UIApplication_UIApplicationMain_int_string___intptr_intptr + 368
26 Caregiver.iOS 0x00000001017a5dbc UIKit_UIApplication_Main_string___intptr_intptr + 11361724 (UIApplication.cs:79)
27 Caregiver.iOS 0x00000001017a5d7c UIKit_UIApplication_Main_string___string_string + 11361660 (UIApplication.cs:64)
28 Caregiver.iOS 0x0000000100d0b724 Caregiver_iOS_Application_Main_string__ + 243492 (/<unknown>:1)
29 Caregiver.iOS 0x0000000100fc98c8 wrapper_runtime_invoke_object_runtime_invoke_dynamic_intptr_intptr_intptr_intptr + 248
30 Caregiver.iOS 0x0000000101ee8fd0 mono_jit_runtime_invoke + 18976720 (mini-runtime.c:2783)
31 Caregiver.iOS 0x0000000101f50178 mono_runtime_invoke_checked + 19399032 (object.c:2887)
32 Caregiver.iOS 0x0000000101f5537c mono_runtime_exec_main_checked + 19420028 (object.c:0)
33 Caregiver.iOS 0x0000000101ed15b0 mono_jit_exec + 18879920 (driver.g.c:1210)
34 Caregiver.iOS 0x0000000101ff0d14 xamarin_find_protocol_wrapper_type + 25552
35 Caregiver.iOS 0x0000000100cf23e0 main + 140256 (main.m:90)
36 libdyld.dylib 0x00000001839ddfc0 start + 4
The code is basically an input form which allows the user to enter a number of text fields including Text Picker, a time picker and a date picker. The app randomely crashes at different points when filling in the fields.
The XAML code is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Caregiver.NewItemPage"
Title="{Binding Itemstatus.Title}"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
NavigationPage.HasBackButton="False"
>
<ContentPage.Resources>
<ResourceDictionary>
<OnPlatform x:Key="TitleEnable" x:TypeArguments="x:Boolean" Android="true" iOS="true" WinPhone="false"/>
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.ToolbarItems>
<ToolbarItem Text="Save" Clicked="Save_Clicked" />
<ToolbarItem Text="Cancel" Clicked="Cancel_Clicked" />
</ContentPage.ToolbarItems>
<ContentPage.Content>
<ScrollView>
<StackLayout Spacing="2" Padding="2">
<!-- Link Button -->
<StackLayout Padding="20,0,20,0">
<Grid>
<StackLayout Grid.Row="0" Grid.Column="0">
<Button Text="{Binding Itemstatus.ButTxt} " x:Name="LinkButton" Clicked="OnLinkButtonClicked" TextColor="White" BackgroundColor="Accent"/>
</StackLayout>
</Grid>
</StackLayout>
<!-- Device ID -->
<StackLayout Orientation="Horizontal" >
<StackLayout Orientation="Vertical" >
<StackLayout Padding="10,20,10,10">
<Label x:Name="IDLabel" Text="Device ID(*)" FontSize="Medium" FontAttributes="Bold" TextColor="{Binding Itemstatus.LblColDevice}" />
</StackLayout>
</StackLayout>
<StackLayout Orientation="Vertical" >
<StackLayout Padding="10,20,10,0">
<Label x:Name = "IDText" Text="{Binding Itemstatus.DeviceID}" FontSize="Medium" />
</StackLayout>
</StackLayout>
</StackLayout>
<!-- Participant -->
<StackLayout Orientation="Horizontal" >
<StackLayout Orientation="Vertical" >
<StackLayout Spacing="0" Padding="10">
<Label x:Name = "LblColPtpName" Text="Participant (*) :" FontSize="Medium" FontAttributes="Bold" TextColor="{Binding Itemstatus.LblColPtp}" />
</StackLayout>
</StackLayout>
<StackLayout Orientation="Vertical" >
<Entry x:Name="entryInput" TextChanged="IDEnter_TextChanged" Placeholder="Participant ID Code " Text="{Binding Itemstatus.Text}" FontSize="Medium" />
</StackLayout>
</StackLayout>
<!-- Country -->
<StackLayout Orientation="Horizontal" >
<StackLayout Orientation="Vertical" >
<StackLayout Spacing="0" Padding="10">
<Label x:Name = "NTimezone" Text="Country (*): " FontSize="Medium" FontAttributes="Bold" TextColor="{Binding Itemstatus.LblColTzs}" />
</StackLayout>
</StackLayout>
<StackLayout Orientation="Vertical" >
<Picker Title="Country " x:Name="PickerCtl" SelectedIndexChanged="PickerCtl_OnSelectedIndexChanged">
<Picker.Items>
<x:String>China</x:String>
<x:String>India</x:String>
<x:String>Kenya</x:String>
<x:String>Madagascar</x:String>
<x:String>South Africa</x:String>
<x:String>Uganda</x:String>
<x:String>Vietnam</x:String>
</Picker.Items>
</Picker>
</StackLayout>
</StackLayout>
<!-- Participant Mobile -->
<StackLayout Orientation="Horizontal" >
<StackLayout Orientation="Vertical" >
<StackLayout Spacing="0" Padding="10">
<Label x:Name = "LblColMedTimeName" Text="Medication Time(*):" FontSize="Medium" FontAttributes="Bold" TextColor = "{Binding Itemstatus.LblColMedTime}"/>
</StackLayout>
</StackLayout>
<StackLayout Orientation="Vertical" >
<TimePicker Time="{Binding Itemstatus.MedicationTime}" x:Name="TimeCtl">
</TimePicker>
</StackLayout>
</StackLayout>
<StackLayout Padding="10,5,20,0">
<StackLayout Orientation="Horizontal" >
<StackLayout Orientation="Vertical" >
<StackLayout Spacing="0" Padding="0">
<Label x:Name = "ParMobCol" Text="Participant Mobile:" FontSize="Small" FontAttributes="Bold" WidthRequest="90" TextColor="{Binding Itemstatus.LblColMobileP}" />
</StackLayout>
</StackLayout>
<StackLayout Orientation="Vertical" >
<StackLayout Orientation="Vertical" >
<Picker Title="Area Code" x:Name="PickerCtlIntCodeP" SelectedIndexChanged="PickerCtlIntCodeP_OnSelectedIndexChanged" >
<Picker.Items>
<x:String>(+86)</x:String>
<x:String>(+91)</x:String>
<x:String>(+254)</x:String>
<x:String>(+261)</x:String>
<x:String>(+27)</x:String>
<x:String>(+256)</x:String>
</Picker.Items>
</Picker>
</StackLayout>
</StackLayout>
<StackLayout Orientation="Vertical" >
<Entry x:Name="entryPInput" TextChanged="PEnter_TextChanged" Keyboard="Numeric" Placeholder="Mobile Number" Text="{Binding Itemstatus.PMobile}" FontSize="Medium" WidthRequest="150" />
</StackLayout>
</StackLayout>
</StackLayout>
<!-- Reminder Message -->
<StackLayout Padding="10,10,10,20">
<Label x:Name="ReminderMessage" Text="Reminder Message:" FontSize="Medium" FontAttributes="Bold" />
<Entry x:Name="entryRInput" TextChanged="RemEnter_TextChanged" Placeholder="Please remember to take your Medicine" Text="{Binding Itemstatus.Message}" FontSize="Medium" />
</StackLayout>
<!-- Reminder Options -->
<!-- SMS Reminder - Participant -->
<StackLayout Orientation="Horizontal" HorizontalOptions="FillAndExpand">
<StackLayout Orientation="Vertical" HorizontalOptions="FillAndExpand">
<StackLayout Padding="10,0,10,0">
<Label Text="Send SMS Reminder to Participant " FontSize="Medium"/>
</StackLayout>
</StackLayout>
<StackLayout Orientation="Vertical" HorizontalOptions="FillAndExpand">
<Switch IsToggled="{Binding Itemstatus.EnableReminderP}"></Switch>
</StackLayout>
</StackLayout>
<!-- SMS Reminder Supporter -->
<StackLayout Orientation="Horizontal" HorizontalOptions="FillAndExpand">
<StackLayout Orientation="Vertical" HorizontalOptions="FillAndExpand">
<StackLayout Padding="10,0,10,0">
<Label Text="Send SMS Reminder to Supporter " FontSize="Medium"/>
</StackLayout>
</StackLayout>
<StackLayout Orientation="Vertical" HorizontalOptions="FillAndExpand">
<Switch IsToggled="{Binding Itemstatus.EnableReminderC}"></Switch>
</StackLayout>
</StackLayout>
<!-- Enable Alarm on Dispenser -->
<StackLayout Orientation="Horizontal" HorizontalOptions="FillAndExpand">
<StackLayout Orientation="Vertical" HorizontalOptions="FillAndExpand">
<StackLayout Padding="10,0,10,0">
<Label Text="Enable Alarm on Dispenser " FontSize="Medium"/>
</StackLayout>
</StackLayout>
<StackLayout Orientation="Vertical" HorizontalOptions="FillAndExpand">
<Switch IsToggled="{Binding Itemstatus.EnableAlarm}"></Switch>
</StackLayout>
</StackLayout>
<!-- Date of Birth -->
<StackLayout Orientation="Horizontal" >
<StackLayout Orientation="Vertical" >
<StackLayout Padding="10,20,0,0">
<Label x:Name = "DOBCol" Text="Date of Birth:" FontSize="Medium" FontAttributes="Bold" TextColor="{Binding Itemstatus.LblColDOB}" />
</StackLayout>
</StackLayout>
<StackLayout Orientation="Vertical" >
<StackLayout Padding="10,10,0,0">
<DatePicker x:Name="DateCtl" Format = "dd MMM yyyy" DateSelected="DatePicker_Changed">
</DatePicker>
</StackLayout>
</StackLayout>
</StackLayout>
</StackLayout>
</ScrollView>
</ContentPage.Content>
</ContentPage>
I have attached a screenshot of the form:
IOS App Entry Form
This is the Page code :
public NewItemPage(NewItemEViewModel viewModel)
{
Item = new Item
{
Id = viewModel.Itemstatus.Id,
Text = viewModel.Itemstatus.Text,
DateOfBirth = viewModel.Itemstatus.DateOfBirth,
Gender = viewModel.Itemstatus.Gender,
DeviceID = viewModel.Itemstatus.DeviceID,
PMobile = viewModel.Itemstatus.PMobile,
CMobile = viewModel.Itemstatus.CMobile,
MedicationTime = viewModel.Itemstatus.MedicationTime,
Message = viewModel.Itemstatus.Message,
EnableAlarm = viewModel.Itemstatus.EnableAlarm,
EnableReminderP = viewModel.Itemstatus.EnableReminderP,
EnableReminderC = viewModel.Itemstatus.EnableReminderC,
TimeZone = viewModel.Itemstatus.TimeZone,
Notes = viewModel.Itemstatus.Notes,
IntCodeP = viewModel.Itemstatus.IntCodeP,
IntCodeC = viewModel.Itemstatus.IntCodeC
};
if (viewModel.Itemstatus.DeviceID == "No Device Linked") viewModel.Itemstatus.ButTxt = "Link Device "; else viewModel.Itemstatus.ButTxt = " Unlink Device ";
InitializeComponent();
BindingContext = this.viewModel = viewModel;
PickerCtl.SelectedIndex = viewModel.Itemstatus.TimezoneIndex;
PickerCtlGender.SelectedIndex = viewModel.Itemstatus.GenderIndex;
PickerCtlIntCodeP.SelectedIndex = viewModel.Itemstatus.IntCodePIndex;
PickerCtlIntCodeC.SelectedIndex = viewModel.Itemstatus.IntCodeCIndex;
DateCtl.Date = viewModel.Itemstatus.DateOfBirth;
DateCtl.MaximumDate = System.DateTime.Now.Date;
}
A: After trying absolutely everything, I replaced the Buttons (Switches) with Item Pickers. This stopped the app from crashing randomly.
I am not sure why the buttons/switches cause instability.
| |
doc_23536688
|
I have a value from the index.php page that when I click to it (example Photos/Images) I get the value using GET then when I echo the value to my Category.php page, the value is projected OK within my BODY page using 'echo' but what I wanted is when the page loaded, the GET variable will be the searchkey in my pagination code. But when I echoed the GET variable within my pagination code, I get this result 'UNDEFINED' which means the variable is not defined within my pagination code. Here is my pagination. Oh yes, I made changes to my code i while back im sorry but this is the previous code where i used $mycat and GET method. I am sorry.
<?php
session_start();
$mycat =$_GET['category'];
//PHP code for specific search
$action = (isset($_REQUEST['action'])&& $_REQUEST['action'] !=NULL)?$_REQUEST['action']:'';
if($action == 'ajax'){
/* Connect To Database*/
$dbname = 'ufile';
$link = mysql_connect("localhost","root","") or die("Couldn't make connection.");
$db = mysql_select_db($dbname, $link) or die("Couldn't select database");
$mycat = htmlspecialchars ($_GET['category']) ? trim($_GET['category']) : ''; //SQL injection protection
include 'pagination.php'; //include pagination file
//pagination variables
$page = (isset($_REQUEST['page']) && !empty($_REQUEST['page']))?$_REQUEST['page']:1;
$per_page = 10; //how many records you want to show
$adjacents = 4; //gap between pages after number of adjacents
$offset = ($page - 1) * $per_page;
echo 'Result: ' .$mycat; //////////THIS IS THE GET VALUE....WHICH TURNS OUT AS UNDEFINED IN VALUE IT SHOULD BE 'PHOTOS/IMAGES, AUDIOS/VIDEOS or COMPRESSED FILES'....PLEASE HELP ME.
//Count the total number of row in your table*/
$count_query = mysql_query("SELECT COUNT(category) AS numrows FROM udocs WHERE category LIKE '%" . $mycat . "%'"); //Count the number of search result here (tagal kitang hinanap dito ka lng pala)
$row = mysql_fetch_array($count_query);
$numrows = $row['numrows'];
$total_pages = ceil($numrows/$per_page);
$reload = 'cat_index.php';
//main query to fetch the data
$result = mysql_query("SELECT * FROM udocs WHERE category LIKE '%" . $mycat . "%' ORDER BY date_upload LIMIT $offset,$per_page");
//loop through fetched data
while($test = mysql_fetch_array($result)){
$id = $test['file_name'];
$fileid=$test['file_path'];
echo "<div class='content'>";
echo'<div class="img_content" ><img src='.$test['file_icon'].' style=height:50px;width:50px;float:left;margin-right:10px;></div>';
echo"<font color='black'; font size='2px !important' ;font family='Century Gothic, sans-serif' ;letter spacing='2px';>Name: </font><font color='yellowgreen'; font size='2px !important' ;font family='Century Gothic, sans-serif' ;letter spacing='2px';>" .$test['file_name']."</font><br>";
echo"<font color='black'; font size='2px !important' ;font family='Century Gothic, sans-serif' ;letter spacing='2px';>Category: </font><font color='gray'; font size='2px !important' ;font family='Century Gothic, sans-serif' ;letter spacing='2px';>" .$test['category']."</font></font><font color='skyblue'; font size='2px !important' ;font family='Century Gothic, sans-serif' ;letter spacing='2px';> | </font><font color='black'; font size='2px !important' ;font family='Century Gothic, sans-serif' ;letter spacing='2px';>Size: </font><font color='gray'; font size='2px !important' ;font family='Century Gothic, sans-serif' ;letter spacing='2px';>" .$test['file_size']."</font></font><font color='skyblue'; font size='2px !important' ;font family='Century Gothic, sans-serif' ;letter spacing='2px';> | </font><font color='black'; font size='2px !important' ;font family='Century Gothic, sans-serif' ;letter spacing='2px';>Credits to: </font><font color='gray'; font size='2px !important' ;font family='Century Gothic, sans-serif' ;letter spacing='2px';>" .$test['author']."</font><font color='skyblue'; font size='2px !important' ;font family='Century Gothic, sans-serif' ;letter spacing='2px';> | </font><font color='black'; font size='2px !important' ;font family='Century Gothic, sans-serif' ;letter spacing='2px';>Date Uploaded: </font><font color='gray'; font size='2px !important' ;font family='Century Gothic, sans-serif' ;letter spacing='2px';>" .$test['date_upload']."</font><br>";
echo"<font color='black'; font size='2px !important' ;>Description:". $test['description']. "</font><br>";
echo"<a href ='download.php?file_path=$fileid' ><font color='orange' title='$mycat'>Download File</p></a>";
echo "</div>";
}
//BOTTOM
if ($numrows==0)
{
}
else
{
echo paginate($reload, $page, $total_pages, $adjacents);
}
//header('Location:index.php');
//die();
} // end of ajax first condition
else
{
?>
<body>
<?php
echo 'You are searching for: '.$mycat;
?>
</body>
<?php } ?>
A: If $_REQUEST will allow you to access the parameters, but $_GET will not, try $_POST, meaning that the HTTP method used was POST and not GET. Check the form/javascript that is submitting to this script as well. $_REQUEST is a catch all superglobal that contains both get and post parameters (and cookies too!).
$_REQUEST
I'd also recommend doing a little reading on the HTTP protocol in depth, it can help with these sorts of issues :)
In addition to what Joren just commented, do include the URL you're using to access this page.
A: As i understood on ajax u could get variable , but when refresh u couldnt right? If im true , u should store it on session , and then first look on get/request and then session.
Take it easy
| |
doc_23536689
|
Originally only the top block of code was in the RunWithElevatedPrivileges delegate, but I tried moving it all inside. I'll insert some using blocks once I get it working:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
rootWeb = SPContext.Current.Site.RootWeb;
rootWeb.AllowUnsafeUpdates = true;
currentWeb = SPContext.Current.Web;
currentWeb.AllowUnsafeUpdates = true;
try
{
// Get site information
SPList franDir = rootWeb.GetList("/Lists/Directory");
SPQuery query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name='Subsite'/><Value Type='Text'>" + currentWeb.Name +
"</Value></Eq></Where>";
SPListItemCollection items = franDir.GetItems(query);
SPList l = rootWeb.GetList("/Lists/Request");
SPListItem li = l.Items.Add();
li["Location"] = siteName;
//...set more fields
li.Update();
}
catch (Exception ex)
{
rootWeb.Dispose();
logger.ErrorException("An error occured adding item", ex);
throw ex;
}
rootWeb.Dispose();
});
A: Thanks to @AlexeiLevenkov I see that this doesn't work because I'm using an existing instance of the SP objects which were created using the default privileges. As proof that the code does nothing, when running as an anonymous user the code succeeds even without the RunWithElevatedPrivileges call. I made this change and it took care of it.
SPSecurity.RunWithElevatedPrivileges(delegate()
{
rootWeb = new SPSite(SPContext.Current.Site.ID).RootWeb;
Thanks a lot!
| |
doc_23536690
|
I'm trying to left/right swipe between images using a QLabel but I didn't manage to receive any gesture events yet with my PyQt5 based application.
Here is what I have:
class MyViewer(QtWidgets.QLabel):
def __init__(self, parent=None):
super().__init__(parent=parent)
self.setAttribute(QtCore.Qt.WA_AcceptTouchEvents) # just gave it a try
self.grabGesture(QtCore.Qt.SwipeGesture)
def event(self, event):
if event.type() == QtCore.QEvent.Gesture: # <= this won't happen
print("Hello event!")
return super().event(event)
I also tried to look for QtWidgets.QGestureEvent but even when I just print out event.type() I only see events seemingly unrelated to any gestures (except some QToucheEvent instances)
Similar questions are this one, this one, this one and I even read some documentation but I didn't see a working example yet. Only questions and example C++ snippets..
I'm using PyQt5.15.0 for both Linux and Android and I didn't see a single trace of anything gesture-ish yet.
What did I forget to do? Does the parent have to be set up somehow?
A: How many fingers were you swiping with? According to the Qt forum, Qt.SwipeGesture is only registered when swiping with two or more fingers, depending on the platform. One finger is represented as a QtGui.QMouseEvent.
If you have been using two or more fingers, it is also possible that the reason that you saw no events is because you did not explictly accept them. The docs say:
A QGesture is by default accepted when it arrives at your widget. However, it is good practice to always explicitly accept or reject a gesture. The general rule is that, if you accept a gesture, you are using it. If you are ignoring it you are not interested in it. Ignoring a gesture may mean it gets offered to another target object, or it will get canceled. [...] Ignoring the gesture will mean the gesture will never be offered to you again.
| |
doc_23536691
|
$result = mysql_query("SELECT * FROM params");
while($row = mysql_fetch_array($result))
{
$param = $row['value'] ;
}
is this right, if so is their away i can add one to the variable name each time round so i get $param1, $param2....
I dont want to have to send a query to the database for each param, is it possible to get them all like this?
A: You can create variable names like this:
${'var'.1}
${'var'.'1.cat'}
${'var'.$x}
${$y.$x}
and so on.
A: The simpliest way is to use an array:
$result = mysql_query("SELECT * FROM params");
$param = array();
$i = 0;
while($row = mysql_fetch_array($result)) {
$param[$i] = $row['value'] ;
$i++;
}
Than you get $param[0], $param[1], ...
A: This seems like a design flaw. But what you can do is:
$count = 1;
$result = mysql_query("SELECT * FROM params");
while($row = mysql_fetch_array($result))
{
$paramname = 'param' . $count++;
$$paramname = $row['value'] ;
}
A: You may find the list function useful - http://php.net/manual/en/function.list.php
list($param1,$param2,$param3,$param4,$param5,$param6) = mysql_fetch_row($result);
Probably more use when using descriptive variables, just a thought.
| |
doc_23536692
|
Let's say i want to use the worker's smartphone to check when they enter or exit a building site in a not counterfeit way. But building sites can be in different places with some possibility of slow network. The app should be running on an Android or IOS Device.
Also NFC is not a good idea since the worker is going to use his own phone.
QR code would be fit but is it 100% counterfeit proof?
| |
doc_23536693
|
I followed these steps:
*
*Create Groups in user pool with roles created in IAM having separate
policies
*Create User and add them to user groups
*Create an Identity Pool and add that Cognito provider under
Authentication providers using app id and client id.
Here I don't get Authenticated role selection under which I have to select Choose role from token
*I Save Changes and generate the default policies for authenticated and unauthenticated users
*After the Identity Pool creation i edit it to get Authenticated role selection and select Choose role from token and save it.
*After saving the changes if I go back to edit it i see Use default role is selected.
Is anyone facing the same problem or I have some errors. The policies and Roles work if I define for authenticated role but it overrides User Group roles.
| |
doc_23536694
|
The Function is called on the keypress event.
Any help is appreciated
Thanks!!
function isDecimalNumberWithOnlyNumbersandScaleTwoFunc(event) {
if (!event)
event = window.event;
var charCode = (event.which) ? event.which : event.keyCode;
var elementValue = event.target.value;
if (event.key == "." && elementValue.indexOf('.') != -1) {
event.preventDefault();
return false;
}
if ((event.key == "." || isNumberKey(event))) {
if ((event.key == "." || isNumberKey(event)) && (elementValue.substring(elementValue.indexOf('.'), elementValue.length).length <= 2)) {
return true;
}
else if (isNumberKey(event)) {
if ((elementValue.indexOf('.') != -1)) {
event.preventDefault();
return false;
}
else if (elementValue.length < 9) {
if (isNumberKey(event) || event.key.toLowerCase() == "del" || event.key.toLowerCase() == "delete" || charCode == 46) {
return true;
}
else
return false;
}
}
else if (event.key == ".") {
return true;
}
event.preventDefault();
return false;
}
else
return false;
}
| |
doc_23536695
|
<img src="http://subtlepatterns.com/patterns/grey_wash_wall.png"
data-src-400px="http://subtlepatterns.com/patterns/dark_wood.png"
alt="">
@media (min-width: 400px) {
img[data-src-400px] {
content: attr(data-src-10px, url);
}
}
http://codepen.io/anon/pen/qEqbbQ
but it give an error in my chrome, it says "invalid property value". Screenshot:
what happens and why it didnt work??
A: *
*content is only applied to pseudo elements. SPEC
The '::before' and '::after' pseudo-elements are used to insert content immediately before and immediately after the content of an element (or other pseudo-element). The 'content' propety is used to specify the content to insert.
*Just a remind (which may be irrelevant). <img> cannot have :before/:after pseudo elements (it cannot have decendant elements at all).
| |
doc_23536696
|
first one is where i store all my functions, and the 2nd one is primarily just to customize all the calculator buttons, etc.
import static com.example.calculator.R.string.display;
import androidx.appcompat.app.AppCompatActivity;
import org.mariuszgromada.math.mxparser.*;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private EditText display;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display = findViewById(R.id.input);
display.setShowSoftInputOnFocus(false);
display.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (getString(R.string.display).equals(display.getText().toString())){
display.setText("");
}
}
});
}
private void updateText(String strToAdd){
String oldStr = display.getText().toString();
int cursorPos = display.getSelectionStart();
String leftStr = oldStr.substring(0, cursorPos); //code that prints the numbers on the screen
String rightStr = oldStr.substring(cursorPos);
if (getString(R.string.display).equals(display.getText().toString())){
display.setText(strToAdd);
display.setSelection(cursorPos + 1);
}
else{
display.setText(String.format("%s%s%s", leftStr, strToAdd, rightStr));
display.setSelection(cursorPos + 1); //moves cursor position to one right
}
}
public void zeroBTN(View view){
updateText("0");
}
public void oneBTN(View view){
updateText("1");
}
public void twoBTN(View view){
updateText("2");
}
public void threeBTN(View view){
updateText("3");
}
public void fourBTN(View view){
updateText("4");
}
public void fiveBTN(View view){
updateText("5");
}
public void sixBTN(View view){
updateText("6");
}
public void sevenBTN(View view){
updateText("7");
}
public void eightBTN(View view){
updateText("8");
}
public void nineBTN(View view){
updateText("9");
}
public void multiplyBTN(View view){
updateText("×");
}
public void divideBTN(View view){
updateText("÷");
}
public void subtractBTN(View view){
updateText("-");
}
public void addBTN(View view){
updateText("+");
}
public void clearBTN(View view){
display.setText("");
}
public void expBTN(View view){
updateText("^");
}
public void parenthesesBTN(View view){
int cursorPos = display.getSelectionStart();
int openPar = 0;
int closedPar = 0;
int textLength = display.getText().length();
for (int i = 0; i < cursorPos; i++){
if (display.getText().toString().substring(i, i+1).equals("(")){
openPar += 1;
}
if (display.getText().toString().substring(i, i+1).equals(")")){
closedPar += 1;
}
}
if (openPar == closedPar || display.getText().toString().substring(textLength - 1, textLength).equals("(")){
updateText("(");
display.setSelection(cursorPos + 1);
}
else if (closedPar < openPar && !display.getText().toString().substring(textLength - 1, textLength).equals("(")){
updateText(")");
}
display.setSelection(cursorPos + 1);
}
public void plusMinusBTN(View view){
updateText("thx for using my calc, you found an easter egg :)");
}
public void decimalBTN(View view){
updateText(".");
}
public void equalBTN(View view){
String userExp = display.getText().toString();
userExp = userExp.replaceAll("÷", "/");
userExp = userExp.replaceAll("×", "*");
Expression exp = new Expression(userExp);
String result = String.valueOf(exp.calculate());
display.setText(result);
display.setSelection(result.length());
}
public void backspaceBTN(View view){
int cursorPos = display.getSelectionStart();
int textLen = display.getText().length();
if (cursorPos != 0 && textLen !=0){ //code to delete stuff
SpannableStringBuilder selection = (SpannableStringBuilder) display.getText();
selection.replace(cursorPos - 1, cursorPos, "");
display.setSelection(cursorPos - 1);
}
}
}
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TableLayout
android:id="@+id/tableLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@+id/input"
app:layout_constraintVertical_bias="0.95"
tools:layout_editor_absoluteX="1dp">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/clearBTN"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@drawable/circle"
android:onClick="clearBTN"
android:text="@string/clear"
android:textColor="#000000"
android:textSize="24sp"
tools:ignore="UsingOnClickInXml" />
<Button
android:id="@+id/parenthesesBTN"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@drawable/circle"
android:onClick="parenthesesBTN"
android:text="@string/parentheses"
android:textColor="#000000"
android:textSize="24sp"
tools:ignore="UsingOnClickInXml" />
<Button
android:id="@+id/exponentBTN"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@drawable/circle"
android:onClick="expBTN"
android:text="@string/exponent"
android:textColor="#000000"
android:textSize="24sp"
tools:ignore="UsingOnClickInXml" />
<Button
android:id="@+id/divideBTN"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@drawable/circle"
android:onClick="divideBTN"
android:text="@string/divide"
android:textColor="#000000"
android:textSize="24sp"
tools:ignore="UsingOnClickInXml" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/sevenBTN"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@drawable/circle"
android:onClick="sevenBTN"
android:text="@string/seven"
android:textColor="#000000"
android:textSize="24sp"
tools:ignore="UsingOnClickInXml" />
<Button
android:id="@+id/eightBTN"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@drawable/circle"
android:onClick="eightBTN"
android:text="@string/eight"
android:textColor="#000000"
android:textSize="24sp"
tools:ignore="UsingOnClickInXml" />
<Button
android:id="@+id/nineBTN"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@drawable/circle"
android:onClick="nineBTN"
android:text="@string/nine"
android:textColor="#000000"
android:textSize="24sp"
tools:ignore="UsingOnClickInXml" />
<Button
android:id="@+id/multiplyBTN"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@drawable/circle"
android:onClick="multiplyBTN"
android:text="@string/multiply"
android:textColor="#000000"
android:textSize="24sp"
tools:ignore="UsingOnClickInXml" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/fourBTN"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@drawable/circle"
android:onClick="fourBTN"
android:text="@string/four"
android:textColor="#000000"
android:textSize="24sp"
tools:ignore="UsingOnClickInXml" />
<Button
android:id="@+id/fiveBTN"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@drawable/circle"
android:onClick="fiveBTN"
android:text="@string/five"
android:textColor="#000000"
android:textSize="24sp"
tools:ignore="UsingOnClickInXml" />
<Button
android:id="@+id/sixBTN"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@drawable/circle"
android:onClick="sixBTN"
android:text="@string/six"
android:textColor="#000000"
android:textSize="24sp"
tools:ignore="UsingOnClickInXml" />
<Button
android:id="@+id/subtractBTN"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@drawable/circle"
android:onClick="subtractBTN"
android:text="@string/subtract"
android:textColor="#000000"
android:textSize="24sp"
tools:ignore="UsingOnClickInXml" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/one"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@drawable/circle"
android:onClick="oneBTN"
android:text="@string/one"
android:textColor="#000000"
android:textSize="24sp"
tools:ignore="UsingOnClickInXml" />
<Button
android:id="@+id/two"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@drawable/circle"
android:onClick="twoBTN"
android:text="@string/two"
android:textColor="#000000"
android:textSize="24sp"
tools:ignore="UsingOnClickInXml" />
<Button
android:id="@+id/three"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@drawable/circle"
android:onClick="threeBTN"
android:text="@string/three"
android:textColor="#000000"
android:textSize="24sp"
tools:ignore="UsingOnClickInXml" />
<Button
android:id="@+id/add"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@drawable/circle"
android:onClick="addBTN"
android:text="@string/add"
android:textColor="#000000"
android:textSize="24sp"
tools:ignore="UsingOnClickInXml" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/plusMinusBTN"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@drawable/circle"
android:onClick="plusMinusBTN"
android:text="@string/plusMinus"
android:textColor="#000000"
android:textSize="24sp"
tools:ignore="UsingOnClickInXml" />
<Button
android:id="@+id/zeroBTN"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@drawable/circle"
android:onClick="zeroBTN"
android:text="@string/zero"
android:textColor="#000000"
android:textSize="24sp"
tools:ignore="UsingOnClickInXml" />
<Button
android:id="@+id/pointBTN"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@drawable/circle"
android:onClick="decimalBTN"
android:text="@string/point"
android:textColor="#000000"
android:textSize="24sp"
tools:ignore="UsingOnClickInXml" />
<Button
android:id="@+id/equalsBTN"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@drawable/circle"
android:onClick="equalBTN"
android:text="@string/equals"
android:textColor="#000000"
android:textSize="24sp"
tools:ignore="UsingOnClickInXml" />
</TableRow>
</TableLayout>
<EditText
android:id="@+id/input"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:text="@string/display"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:autofillHints="false"
android:inputType="none"
android:textSize="36sp"
android:textAlignment="textEnd"
tools:ignore="LabelFor" />
<ImageButton
android:id="@+id/backspace"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="@drawable/circle"
android:contentDescription="@string/backspace"
android:onClick="backspaceBTN"
app:layout_constraintBottom_toTopOf="@+id/tableLayout2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:srcCompat="@drawable/backspace"
tools:ignore="UsingOnClickInXml" />
</androidx.constraintlayout.widget.ConstraintLayout>
| |
doc_23536697
|
0x0 - _core_reset (this is part of crt0.S)
...
0x460 - fw_reset (this is called from main)
...
0x484 - main (this is the main function)
(-) my ELF undergoes stripping of sections to create a binary file of instructions only, starting in _core_reset
(-) the binary image from last step is loaded to virtual address 0xADB00000, which is physical 0x2DB00000
(-) the first problem is that in _core_reset we do:
la t0,main
mtc0 t0,C0_ERRPC //store it as return address
but main has the address relative to 0x0, which causes memory exception,
what I need is main to be in address loaded + (offset relative to zero),
How do I do that? we can say that the address the image is loaded to and run from is constant
*
*I tried to write in the crt0.S file, hardcoded to change the jump to main address:
lui t0, 0xa6b0 /* Assumtion the FW is loaded to 0xa6b00000 */
addiu t0, t0, main
and it worked an I reached main(), but later when tried to call fw_reset() from main, the address of fw_reset() was again relative to 0x0 and I got a memory exception
*I tried from the makefile to add that the .text section of ELF will start from the address loaded, but then I get an issue that my image is loaded to:
(value i provide) + (actual loading address) and so it also doesn't work
I expected my code to reach main() and be stuck in the endless while loop, instead I get memory exceptions since the functions are relative to 0x0, while the code is loaded to another address not zero
| |
doc_23536698
|
def html_filter(value, allowed_tags = 'p h1 h2 h3 div span a:href:title img:src:alt:title table:cellspacing:cellpadding th tr td:colspan:rowspan ol ul li br'):
js_regex = re.compile(r'[\s]*(&#x.{1,7})?'.join(list('javascript')))
allowed_tags = [tag.split(':') for tag in allowed_tags.split()]
allowed_tags = dict((tag[0], tag[1:]) for tag in allowed_tags)
soup = BeautifulSoup(value)
for comment in soup.findAll(text=lambda text: isinstance(text, Comment)):
comment.extract()
for tag in soup.findAll(True):
if tag.name not in allowed_tags:
tag.hidden = True
else:
tag.attrs = [(attr, js_regex.sub('', val)) for attr, val in tag.attrs.items() if attr in allowed_tags[tag.name]]
return soup.renderContents().decode('utf8')
It works well for unwanted or whitelisted tags, attributes not whitelisted and even badly formatted html. However if any whitelisted attributes are present, it raises
'list' object has no attribute 'items'
at the last line, which is not helping me much. type(soup) is <class 'bs4.BeautifulSoup'> whether it raises an error or not, so I don't know what it's referring to.
Traceback:
[...]
File "C:\Users\Mark\Web\www\fnwidjango\src\base\functions\html_filter.py" in html_filter
30. return soup.renderContents().decode('utf8')
File "C:\Python27\lib\site-packages\bs4\element.py" in renderContents
1098. indent_level=indentLevel, encoding=encoding)
File "C:\Python27\lib\site-packages\bs4\element.py" in encode_contents
1089. contents = self.decode_contents(indent_level, encoding, formatter)
File "C:\Python27\lib\site-packages\bs4\element.py" in decode_contents
1074. formatter))
File "C:\Python27\lib\site-packages\bs4\element.py" in decode
1021. indent_contents, eventual_encoding, formatter)
File "C:\Python27\lib\site-packages\bs4\element.py" in decode_contents
1074. formatter))
File "C:\Python27\lib\site-packages\bs4\element.py" in decode
1021. indent_contents, eventual_encoding, formatter)
File "C:\Python27\lib\site-packages\bs4\element.py" in decode_contents
1074. formatter))
File "C:\Python27\lib\site-packages\bs4\element.py" in decode
1021. indent_contents, eventual_encoding, formatter)
File "C:\Python27\lib\site-packages\bs4\element.py" in decode_contents
1074. formatter))
File "C:\Python27\lib\site-packages\bs4\element.py" in decode
983. for key, val in sorted(self.attrs.items()):
Exception Type: AttributeError at /"nieuws"/article/3-test/
Exception Value: 'list' object has no attribute 'items'
A: Try replacing
tag.attrs = [(attr, js_regex.sub('', val)) for attr, val in tag.attrs.items() if attr in allowed_tags[tag.name]]
with
tag.attrs = dict((attr, js_regex.sub('', val)) for attr, val in tag.attrs.items() if attr in allowed_tags[tag.name])
A: It looks like renderContents() expects you to set attrs to a dict (which would have an items method), rather than the list of tuples you pass. Hence it throws AttributeError when it tries to access it.
To fix the error, you can use a dict comprehension in Python 3:
tag.attrs = {attr: js_regex.sub('', val)) for attr, val in tag.attrs.items() if attr in allowed_tags[tag.name]}
In Python 2, dict comprehensions aren't supported so you should pass an iterator to the dict constructor:
tag.attrs = dict((attr, js_regex.sub('', val)) for attr, val in tag.attrs.items() if attr in allowed_tags[tag.name]))
| |
doc_23536699
|
POST {
host: '192.168.78.243:3000',
accept: '*/*',
'content-length': '1178',
'content-type': 'multipart/form-data; boundary=------------------------f519f81dc2e1d562'
}
--------------------------f519f81dc2e1d562
Content-Disposition: form-data; name="event"; filename="event_3913.json"
Content-Type: application/octet-stream
{"packetCounter":"3913",
"capture_timestamp":"1600677267347",
"datetime":"20200921 204027000",
"stateUTF8":"ABC123",
"stateASCII":"ABC123",
.....
I want to access the JSON data, and are using express. As per this SO answer I have tried this approach with express.json():
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/test', (req, res) =>{
if (req.method === 'POST') {
console.log('POST request recd');
}
console.log(req.body);
res.status(200).send('It works');
});
app.listen(3000, () => console.log('server started'));
However all I get on console is undefined {}.
UPDATE
Even with the correct imports the express/body-parser method does not work.
This method below works in so far as it proves a POST request is being received. But I need to use a express method so that I can access the incoming data:
let buffers = [];
const http =require('http')
http.createServer((request, response) => {
console.log('Now we have a http message with headers but no data yet.');
if (request.method === 'POST' && request.url === '/test') {
console.log('Hit');
}
request.on('data', chunk => {
console.log('A chunk of data has arrived: ', chunk);
buffers.push(chunk);
});
request.on('end', () => {
console.log('No more data');
let body = Buffer.concat(buffers);
console.log(String(body));
})
}).listen(3000)
How do I get to the data with express?
A: You installed body-parser but haven't imported body-parser in order to work.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.get('/', (req, res) => {
res.sendFile('public/index.html');
});
app.post('/test', (req, res) =>{
console.log(req.body);
res.status(200).send('It works');
});
app.listen(3000, () => console.log('server started'));
Updated Answer
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.get('/', (req, res) => {
res.send(`<form action="/test" method="POST" >
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<input type="submit" value="Submit">
</form>`)
});
app.post('/test', (req, res) =>{
console.log(req.body);
res.status(200).send('It works');
});
app.listen(3000, () => console.log('server started'));
Try it online https://repl.it/join/ldopaeji-pprathameshmore
A: const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('192.168.78.243:3000/', (req,res) =>{
console.log(req.body.stateUTF8);
console.log(req.body);
res.sendStatus(200);
});
app.listen(3000, ()=> console.log('listening'));
Try this!!
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.