text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: How to resolve : "The hierarchy of the type StepsCode is inconsistent" problem How to use a method of class of project A in a class on project B, all projects are maven projects and it's an existing projects with lot of packages and classes , it's for a cucumber test projects, I have the application with lot of projects and packages, and i need to make test with cucumber on it, so i tried to create a new maven project and when I tried to call a function from one of the existing project, it says : " The hierarchy of the type StepsCode is inconsistent"
All the configuration is done, i refresh all projects and it still don't work .
A: first check if the methods and the classes you are going to use are public, then you can add the projects, with the methods you need to call, as dependency in the pom.xml file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55479401",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Can Python 2 still be installed for use with Spyder? This may be somewhat of a novice question. I don't have a lot of python knowledge, but run a script written by a previous employee of ours. It was written in Python 2 and there are issues larger than using parentheses when trying to rewrite to Python 3. However, we can no longer install Python 2 through Anaconda and many of us use Spyder to run python scripts. We will hire someone to rewrite soon, but need to run the scripts now.
I went through the instructions listed here How to revert to python 2 in conda root environment?, but nothing changed with respect to Python version. Is it still possible to downgrade to Python 2 and have Spyder run that Python version?
I appreciate any insight, thank you.
A: I think your best bet is to create a virtual environment.
Open your conda cli and write this command:
conda create -n legacy python=2.7 anaconda
where legacy is the name I've arbitrarily chosen for the virtual environment
After this runs, you can activate the virtual environment with conda activate legacy and you'll be running in python 2.7
running the command spyder should then open spyder in the legacy environment running 2.7
Python 2.7 is past end of life, if you're connecting to the internet I'd strongly consider deprecating this code asap python 2.7 does not reliably back port security updates.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69438286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ASP.NET Can't set value to datepicker from code behind I have a datepicker field
$(function () {
$("#dateTextBox").datepicker({
changeMonth: true,
changeYear: true
});
$("#dateTextBox").datepicker("option", "dateFormat", "dd/mm/yy");
});
In code behind, on button click, I'm trying to set value to datepicker field:
dateTextBox.Value = date.ToString("dd/MM/yyyy");
But after postback, textbox is empty...
A: In order to achieve this, you need to read details from client side using hidden field. This hiddenfield value can be set at server side.
For example:
create hidden field on page
<asp:HiddenField id="hdnDate" runat="server" />
set date string in hiddenField :
protected void button_Clicked (...)
{
DateTime dt = DateTime.Now;
hdnDate.Value = dt.Year.ToString() + "," + (dt.Month - 1 ).ToString() + "," + dt.Day.ToString();
}
now, on document.ready of jquery event, do this
$(document).ready(function() {
$("#dateTextBox").datepicker({
changeMonth: true,
changeYear: true
});
dtString = $("#<%=hdnDate.ClientID%>").val();
dtString = dtString.split(',');
var defaultDate = new Date(dtString[0], dtString[1], dtString[2]);
$("#dateTextBox").datepicker("setDate",defaultDate);
});
A: Try this:
dateTextBox.Value = DateTime.Now.ToString("yyyy-MM-dd");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28728434",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Length of cells depending on the length of the string in Excel/CSV Recently I mastered fgetcsv in the hope of writing an array to a file so that I could later open it via Excel, there was no problem with it. Everything turned out ok. But, as far as I understand, there can not be done so to automatically push apart the cells to the length of the string (maybe looked bad)
Now it is written like this:
I want to know are there are any libraries, so that the cells length is set to the length of the string written to the cell?
It is necessary that it was like this:
Or maybe there is another approach? For example, manually in Excel to convert all at once so?
I will be grateful for any help, thanks!
A: CSV files doesn't have any cell length defintion
They are text files, with Comma Seperated Values (CSV ...)
xlsx files however DO hold such a feature
They are basically xml zipped
You can either look for a php excel library with a function ready or parse the XML yourself...
XML sturcture is reffred to here
Looking for a clear description of Excel's .xlsx XML format
A: Worksheets("Sheet1").Columns("A:D").AutoFit
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52145845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to display the notification using service? I was trying to display the notifications using background service for which I wrote 3 classes. The service should run in background even if the appllication closed and and it should start running automatically so I used ,
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name="com.s2si.ucom.ui.UcomBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
So in onReceive() of BroadcastReceiver class I am starting the service using,
Intent service = new Intent(context, AlarmService.class);
context.startService(service);
In service class I am using AlarmManager to set particular interval so that I can display notification for every period of time. and finally I am invoking the BroadcastReceiver class to display the notification using AlarmManager. The problem is I am not getting the output :-(...instead of that I am getting error like, Couldn't load memtrack module (No such file or directory)... I am literally new to android coding...Can any one help me how to display notifications in such manner..and let me know what I did wrong above...Thanks much :-).
code in onCreate() method of service class,
Intent intent = new Intent(context, NotificationServiceReceiver.class);
PendingIntent sender = PendingIntent
.getBroadcast(context, 0, intent, 0);
// We want the alarm to go off 5 seconds from now.
long firstTime = SystemClock.elapsedRealtime();
firstTime += 5 * 1000;// start 5 seconds after first register.
// Schedule the alarm!
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
firstTime, 5000, sender);// 5seconds interval
A: in short this is how you create a broadcast
private static final String ACTION_ALARM = "your.company.here.ACTION_ALARM";
public static void createAlarm(){
Intent alarmIntent = new Intent();
alarmIntent.setAction(ACTION_ALARM);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, timestamp for alarm, pi);
}
public void onReceive(...){
//whatever is supposed to happen on receive
}
and you need to declare that broadcastreceiver and the actionname its supposed to receive in manifest:
<receiver
android:name="your.company.here.AlarmReciever">
<intent-filter>
<action android:name="your.company.here.ACTION_ALARM" />
</intent-filter>
</receiver>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20880937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Best way to do file transfer via SCP using python and a .pem file I wanna to replicate that command in python:
scp -i aKey.pem aFile.txt ec2-user@serverIp:folder
I found some examples of SCP but didn't found neither using a .pem key, and without informing the user password. How can I make this in python?
A: Try to use paramiko module.
Check here for connect function in paramiko which has key_filename argument.
In paramiko module, there is SFTP command which you can use to transfer file.
Check here for SFTP info.
Demo code will looks like below:
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(<IP Address>, username=<User Name>, key_filename=<.PEM File path)
# Setup sftp connection and transmit this script
#print "copying"
sftp = client.open_sftp()
sftp.put(<Source>, <Destination>)
sftp.close()
**
OR
**
You can execute above command directly using python directly.
Please check this link how to execute command in python.
Demo code:
from subprocess import call
cmd = 'scp -i aKey.pem aFile.txt ec2-user@serverIp:folder'
call(cmd.split())
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39573434",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Running with_items inside with_items I'm currently running a command as follows:
name: Generate a timed-based code for user
command: "{{ item.command }} creates={{ item.file}}"
with_items:
- { command: '/usr/bin/google-authenticator -t -f -d --label=user1 --qr-mode=ANSI -r 3 -R 30 -w 1 --secret=/home/user1/.google_authenticator', file: '/home/user1/.google_authenticator' }
- { command: '/usr/bin/google-authenticator -t -f -d --label=user2 --qr-mode=ANSI -r 3 -R 30 -w 1 --secret=/home/user2/.google_authenticator', file: '/home/user2/.google_authenticator' }
This works fine but isn't DRY at all.
I'm attempting to do a second with_items like this role:
- include_vars: main.yml
- name: Generate a timed-based code for user
command: "{{ item.command }} creates={{ item.file }}"
with_items:
- { command: '/usr/bin/google-authenticator -t -f -d --label="{{ item.username }}" --qr-mode=ANSI -r 3 -R 30 -w 1 --secret=/home/"{{ item.username }}"/.google_authenticator', file: '/home/"{{{ item.username }}"/.google_authenticator' }
with_items: "{{ users }}"
become: true
Inside vars/main.yml I have:
---
users:
username: user1
username: user2
username: user3
Upon running the playbook I'm presented with:
[WARNING]: While constructing a mapping from /Users/bshutter/Dev/server/roles/googlemfa/tasks/main.yml, line 55, column 3, found a duplicate dict key (with_items). Using last
defined value only.
[WARNING]: While constructing a mapping from /Users/bshutter/Dev/server/roles/googlemfa/vars/main.yml, line 4, column 3, found a duplicate dict key (username). Using last defined
value only.
When it runs through the role and gets to the task Generate a timed-based code for user
TASK [googlemfa : Generate a timed-based code for user] **************************************
fatal: [10.1.10.36]: FAILED! => {"failed": true, "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'ansible.vars.unsafe_proxy.AnsibleUnsafeText object' has no attribute 'file'\n\nThe error appears to have been in '/Users/bshutter/Dev/server/roles/googlemfa/tasks/main.yml': line 55, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: Generate a timed-based code for user\n ^ here\n"}
A: I'm not sure I fully understand your issue as it looks like you only have one type of command to run.
So, if you really only have the google authenticator command to run, I'd do something like this :
- name: Generate a timed-based code for user
command: '/usr/bin/google-authenticator -t -f -d --label="{{item}}" --qr-mode=ANSI -r 3 -R 30 -w 1 --secret=/home/{{item}}' creates='/home/{{{ item }}/.google_authenticator'
with_items: "{{ users }}"
become: true
A: You are probably looking for with_nested.
However, it will be difficult to implement with the creates option, since only one of the commands will create that file. Also note that the loops must be distinct -- you cannot reference one list from the other.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44033834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Softlayer: SoftLayer_Account::getAllBillingItems. Getting Empty Array [] when i pass "parentId" as null working on SoftLayer_Account::getAllBillingItems passing Filter where I am getting all items with all child Items seperatly. But I want only parent items, so I included parentId as null in filter and I am getting an empty array as result. I am able to get items when I pass particular ParentId.
https://Username:API_KEY@api.softlayer.com/rest/v3/SoftLayer_Account/getAllBillingItems.json?objectFilter={"allBillingItems":{"nextBillDate": {"operation": "betweenDate","options":[{"name": "startDate","value": ["03/07/2017"]},{"name": "endDate","value": ["03/20/2017"]}]},"parentId": {"operation": null}}}&objectMask=category;location;associatedChildren;associatedChildren.category
I tried passing is null but no output.
Can some one help me? What's the operation to get all items with parentId null?
A: According to documentation you need to use "is null" not "null" see https://sldn.softlayer.com/article/object-filters
I noticed you are trying to get parent billing items with their children, I updated the object-mask in order to reduce retrieved data, take account that you could get errors if you are working with a large set of data. Review how-solve-error-fetching-http-headers. You can use any of the following masks:
objectMask=mask[id,parentId,category,location,associatedChildren.category]
objectMask=id;parentId;category;location;associatedChildren.category
But if you are trying to get only parent billing items, it’s not necessary to use mask unless you want data like category and location, on that case you can use following mask:
objectMask=mask[category,location]
This last will show you the information of parent item including the category and location.
You should be able to get parent billing items with their children using the following REST call.
https://<user_name>:<api_key>@api.softlayer.com/rest/v3/SoftLayer_Account/getAllBillingItems?objectFilter={"allBillingItems":{"nextBillDate":{"operation":"betweenDate","options":[{"name":"startDate","value":["03/07/2017"]},{"name":"endDate","value":["03/20/2017"]}]},"parentId":{"operation": "is null"}}}&objectMask=mask[id,parentId,category,location,associatedChildren.category]
Take account that some REST clients don’t support blank spaces between letters. And finally, If you have a lot of billing items I suggest to use result-limit feature in order to avoid time out errors.
References:
http://sldn.softlayer.com/article/rest
http://sldn.softlayer.com/article/object-Masks
https://sldn.softlayer.com/article/object-filters
http://sldn.softlayer.com/reference/services/SoftLayer_Billing_Item
I recomend you to read documentaqtion before going any further
Regards
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42647642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CDialog child windows I just wanted to use insde of a good old MFC Dialog based application 2 more moveable dialogs as childs. After solution wizard, i made a Default Dialog resource (child style) and created 2 dialogs in OnInitDialog of the main Dialog:
m_P1 = new CMyDlg();
m_P2 = new CMyDlg();
m_P1->Create(IDD_DIALOG1, this);
m_P2->Create(IDD_DIALOG1, this);
m_P1->ShowWindow(SW_SHOWNORMAL);
m_P2->ShowWindow(SW_SHOWNORMAL);
Now, they both Show up but when i move them around the redraw of the Client area does not happen. If i overlap both Windows, and pick the one behind in the system bar and start to move it around, the Client area still has Areas which are not updated so they Show Contents of the 2nd overlapping Dialog.
I tried to overwrite OnPaint and invalidate the rectangle there, but as both dialogs are of same class, both dialogs get the OnPaint and both update the full Client area, so there happens a lot of flickering.
I tried to invalidate the Client area only once using ON_WM_ACTIVATE() or ON_WM_SETFOCUS(), but These Events are not called at all.
So what would the correct way to make a moveable child dialog which updates nicely the client area once you drag it around, being in the foreground after selection?
Thx a lot for help
Stefan
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38901934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Compiled Expression Trees misunderstanding? I have this expression :
Expression<Func<string, bool>> f = s => s.Length < 5;
ParameterExpression p = Expression.Parameter (typeof (string), "s");
MemberExpression stringLength = Expression.Property (p, "Length");
ConstantExpression five = Expression.Constant (5);
BinaryExpression comparison = Expression.LessThan (stringLength, five);
Expression<Func<string, bool>> lambda= Expression.Lambda<Func<string, bool>> (comparison, p);
//lets : test
Func<string, bool> runnable = lambda.Compile();
Console.WriteLine (runnable ("kangaroo")); // False
Console.WriteLine (runnable ("dog")); //True
I want to ask about the .Compile()
What does it compile ? And what is the difference between the first execution vs later executions...?
Compile should be something that happens once and not happens again later ....
What / How does it help me ?
A: The Expression<Func<string,bool>> is only a representation of an expression, it cannot be executed. Calling Compile() gives you a compiled delegate, a piece of code that you can call. Essentially, your program composes a small code snippet at runtime, and then call it as if it were processed by the compiler. This is what the last two lines of your code do: as you can see, the compiled snippet can analyze the length of the string that you pass in - when the length is less than five, you get a True back; when it's five or more, you get a False.
What happens on first execution of the compiled snippet is platform-dependent, and should not be detectable by programmers using the .NET platform.
A: Compile() takes the expression tree (which is a data representation of some logic) and converts it to IL which can then be executed directly as a delegate.
The only difference between the first execution and later executions is the possibility that Compile() won't trigger the JIT compilation from IL to native processor code. That may happen on first execution.
A: When you are building the expression tree at runtime there's no code emitted. It's a way to represent .NET code at runtime.
Once you call the .Compile method on the expression tree the actual IL code is emitted to convert this expression tree into a delegate (Func<string, bool> in your case) that you could invoke at runtime. So the code that this expression tree represents can be executed only after you compile it.
Calling Compile is an expensive operation. Basically you should be calling it once and then caching the resulting delegate that you could use to invoke the code many times.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9453322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Casting and pointer casting in C++ Can anyone explain me why this is true:
char *p;
short i;
long l;
(long *) p = &l ; /* Legal cast */
(long) i = l ; /* Illegal cast */
I know it has something to do with lvalue and rvalue but shouldn't (long *) p be a rvalue?
edit:
sorry it seems I confused myself and others, I asked this while reading "this MDSN" and I was surprised to see this syntax, I see it's a special feature that allows to convert lvalue into lvalue as long as it's the same size.
A: Neither of these expressions are legal, they should both fail to compile.
C++11, 5.17.1:
The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand and return an lvalue referring to the left operand.
5.4:
Explicit type conversion (cast notation) [expr.cast]
1 The result of the expression (T) cast-expression is of type T. The result is an lvalue if T is an lvalue reference type or an rvalue reference to function type and an xvalue if T is an rvalue reference to object type; otherwise the result is a prvalue.
So both expressions violate these constraints.
A:
shouldn't (long *) p be a rvalue?
It is.
They're both prvalues and, as such, both statements are ill-formed:
[C++03: 5.4/1]: The result of the expression (T) cast-expression is of type T. The result is an lvalue if T is a reference type, otherwise the result is an rvalue.
[C++11: 5.4/1]: The result of the expression (T) cast-expression is of type T. The result is an lvalue if T is an lvalue reference type or an rvalue reference to function type and an xvalue if T is an rvalue reference to object type; otherwise the result is a prvalue. [..]
GCC 4.8 rejects your "legal cast", but Visual Studio has an extension that accepts this (for no apparent reason).
A: Why do you think your cast is legal? I'm getting error C2106: '=' : left operand must be l-value on both casts.
This shouldn't be legal. If you really want to do it, you have to cast it like this:
(long*&)p = &l; // equivalent to *(long**)&p = &l
But don't do that unless you know what you are doing.
A: The result of a value conversion is an rvalue. You cannot assign to rvalues of fundamental types.
In other words, for int a = 10;, a is an lvalue of type int, but (long) a is a temporary rvalue of type long, and you cannot assign to the temporary. Likewise for pointers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20871139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What does (($2 :: fst $1), snd $1) do in ocaml? I'm a beginner in ocaml just need some guidance with the syntax sometimes
(($2 :: fst $1), snd $1)
I know $2 must be the second token in the line, $1 the first, and fst and snd refer to the first and second component of a pair. I know :: usually indicates to make a list?
And then the overall placement of the parentheses makes me think it's a returning a pair.
But what does this entire line mean, everything taken together?
A: This syntax uses the ocamlyacc rule grammar, which is a DSL for writing parsers. Symbols $N refer to N-th semantic attribute of the defined non-terminal. You can think of them as simple variables, that are bound by the non-terminal pattern expression. So what does (($2 :: fst $1), snd $1) mean?
It is a pair, the first constituent is a list $2 :: fst $1 made from the $2 and the first element of $1, which is itself a pair. And the second part of $1 makes the second constituent of the resulting pair. E.g., suppose that $1 = (5,7) and $2 is 42, you will get, ([42;5],7) as the result of this semantic action.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70129383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Copy and paste from other workbook Im trying to copy all the cells that contain blue font and copy in another workbook in the same range of the source, but im lost at this point. Everytime that i try to run this code, i get an run-time error.
Sub test2()
Application.EnableEvents = False
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.Calculation = xlManual
Dim FonteA As Workbook, FonteB As Workbook
Dim ws As Worksheet
Dim vFile As Variant
Dim rCell As Range
Dim lColor As Long
Dim rColored As Range
'Set source workbook
Set FonteB = ActiveWorkbook
'Open the target workbook
vFile = Application.GetOpenFilename
'if the user didn't select a file, exit sub
If TypeName(vFile) = "Boolean" Then Exit Sub
Workbooks.Open vFile
'Set targetworkbook
Set FonteA = ActiveWorkbook
FonteB.Worksheets("USD - SCHEDULE A").Activate
lColor = RGB(0, 0, 255)
Cells.CurrentRegion.Select
Set rColored = Nothing
For Each rCell In Selection
If rCell.Font.Color = lColor Then
If rColored Is Nothing Then
Set rColored = rCell
Else
Set rColored = Union(rColored, rCell)
End If
End If
Next
If rColored Is Nothing Then
MsgBox "No cells match the color"
Else
rColored.Select
rColored.Copy
End If
Set rCell = Nothing
Set rColored = Nothing
FonteA.Worksheets("Matriz_Produto").PasteSpecial Paste:=xlPasteFormats
FonteA.Worksheets("Matriz_Produto").PasteSpecial Paste:=xlPasteValues
Application.Calculation = xlAutomatic
End Sub
A: No idea where that specific error is coming from (it looks like it should actually be an error 1004), but I'm guessing just switching from using Activate and Select will resolve it. Try the following:
'Set source workbook
Set FonteB = ActiveWorkbook
'Open the target workbook
vFile = Application.GetOpenFilename
'if the user didn't select a file, exit sub
If TypeName(vFile) = "Boolean" Then Exit Sub
'Set targetworkbook
Set FonteA = Workbooks.Open(vFile)
Dim ws As Worksheet
Set ws = FonteB.Worksheets("USD - SCHEDULE A")
lColor = RGB(0, 0, 255)
For Each rCell In ws.Cells.CurrentRegion
If rCell.Font.Color = lColor Then
If rColored Is Nothing Then
Set rColored = rCell
Else
Set rColored = Union(rColored, rCell)
End If
End If
Next
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39713657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android custom Intent class I want to send a complex object from one Activity to another, so this complex object cannot be serialize, because some fields in this object are system classes and natively non-serializable. That's why I want to create my custom class named "MyIntent" inherits from android.content.Intent, with this way, I can put any type of objects in my custom Intent. But, in the second activity, getIntent() method returns android.content.Intent instance, not MyIntent instance. I don't understand why, maybe i did not implement android.content.Intent class correctly.
public class MyIntent extends Intent
{
}
//starting activity
MyIntent intent = new MyIntent();
intent.setClass(context, SecondActivity.class);
context.startActivity(intent);
//inside of onCreate() of SecondActivity
Intent i = getIntent();
i instanceof MyIntent = false
A: startActivity() involves inter-process communication, even when the activity you are starting is in the same app and the same process. Android will ignore your subclass, because the OS process that handles startActivity() requests cannot use your subclass, as that is in your app, and the OS process is not your app. And, the IPC that delivers the request to start the activity back to your process will not know anything about your subclass.
Either:
*
*Combine these into one activity (e.g., using two fragments), or
*Use some sort of singleton data manager that both activities can work with
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39532031",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery Validate submitHandler not displaying response I have a jQuery validation script that is working perfectly with the except of the event handler. I have simplified this post for troubleshooting purposes.
jQuery
submitHandler: function (form) {
$.ajax({
type: $(form).attr("method"),
url: $(form).attr("action"),
data: $(form).serialize(),
dataType : "json"
})
.done(function (data) {
if (data.resp > 0 ) {
alert(data.message);
}
});
return false; // required to block normal submit since you used ajax
},
// rest of the validation below, truncated for clarity
The submitHandler successfully posts to my PHP script that adds a user to a database and then echoes back a json_encode() result.
PHP
<?php
// All processing code above this line has been truncated for brevity
if($rows == "1"){
$resp = array("resp"=>1, "message"=>"Account created successfully. Waiting for user activation.");
}else{
$resp = array("resp"=>2, "message"=>"User account already exists.");
}
echo json_encode($resp);
?>
As you can see the idea is simple. Alert the user with the proper response message. When I run my script the user account is added successfully to the database but no alert is displayed to the user. The Console in Chrome shows no errors, what am I missing?
A: The data variable in the done() is a string. You have to transform it to an object like this
var response = $.parseJSON(data);
in order to access the attributes
A: I am sorry I missed dataType : "json" in your code in my previous answer.
Any way I tried your code and it is working. The alert shows the message. I think you have an error somewhere else. I think it has some thing to do with the array you are encoding to json(PHP part). The response you get is not complete. Try to debug your PHP and test the page separately from AJAX and see what is the result
A: After some tinkering I was able to get things working the way I wanted. Here's the updated code.
jQuery
.done(function (data) {
$("#user_add_dialog").dialog({
autoOpen: false,
modal: true,
close: function (event, ui) {
},
title: "Add User",
resizable: false,
width: 500,
height: "auto"
});
$("#user_add_dialog").html(data.message);
$("#user_add_dialog").dialog("open");
});
return false; // required to block normal submit since you used ajax
PHP
<?php
// All processing code above this line has been truncated for brevity
if($rows == "1"){
$resp = array("message"=>"Account created successfully. Waiting for user activation.");
}else{
$resp = array("message"=>"User account already exists.");
}
echo json_encode($resp);
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22794120",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Extensive String Manipulation - Cursor or While-Loop? Quick Background
I have received a project from our marketing team to make bulk updates to the descriptions of products that will be displayed on our website (>500k items). They have decided to take many decades worth of descriptions and try to make them as similar as possible. (Ex. 'screw driver', 'screwdriver', 'screw-driver' should all look like 'Screwdriver')
I successfully accomplished the task at hand to 95% of their satisfaction using a clunky, long and hard to maintain series of update statements on a table only I maintain, to modify the strings. I then pass these on to our web deployment team, but wasn't thinking they would want to maintain this indefinitely.
I can easily produce a table of sub-strings and conditions to find and what to replace portions of the string. I think something depending on a table like this would be easiest to maintain for 90% of the cases we encounter.
Now, I'm uncertain about the best way to proceed to make this dependable and easy to maintain. I've received conflicting information that a good use would be a 'while loop' and other say a Cursor would be just fine.
Now to the question
Given we will/may/could be adding somewhere around 1k new products a month, and I have a table of conditions like the following, what is the most efficient and dependable way to execute the manipulation regularly?
Condition, Find_substring, Replace_with
like '%screw driver%', 'screw driver', 'Screwdriver'
like '%screw-driver%', 'screw driver', 'Screwdriver'
like '%screwdriver%', 'screwdriver', 'Screwdriver'
Open to any and all ideas, suggestions and advice.
A: If your rules are really as simple as that then simply having "old_value" and "new_value" in the table should suffice, with a single statement to fix all of the data:
UPDATE
MT
SET
description = REPLACE(description, old_value, new_value)
FROM
dbo.My_Table MT
INNER JOIN dbo.Fix_Table FT ON MT.description LIKE '%' + FT.old_value + '%'
You might need to adjust the query if you expect multiple matches on a single product. Also, be careful of strings that might be part of another string. For example, fixing "ax" to "axe" might cause problems with a "fax machine". There are a lot of little details like this that might affect the exact approach.
A: Have a table like bad_val and good_val (call it tblMod). you can write a stored procedure that loops on tblMod and generate SQL statement and execute the statement as dynamic SQL.
loop on tblMod
-- generate SQL statements like:
set sqlText = 'update myTable set description = ' + good_val + ' where description = ' + bad_val
sp_execute sqlText
This approach also allows you to use SQL functions or any other functions in good_val field of tblMod. for instance you can have below data in good_val field: 'upper(description)'
or 'substring(description, 1 ,4)'
as you are generating dynamic SQL, those will work.
in this case your sqlText will be something like
'update myTable set description = substring(description, 1, 4) where description = 'some bad value'
example above might not be correct but I hope you get my idea.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34726667",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Are C++ compilers allowed to replace construct + moveconstruct with just a construct? Are C++ compilers allowed to replace:
const auto myType = MyType(1, 2, 3);
with:
const MyType myType(1, 2, 3);
ie, emit the assignment, or is there anything which prevents this?
Note:
The reason I ask is that I prefer the first version.
A: Yes, an implementation is allowed to omit the copy/move construction of a class
object when certain criteria are met, it's called copy elision.
Under the following circumstances, the compilers are permitted to omit
the copy- and move-constructors of class objects even if copy/move
constructor and the destructor have observable side-effects.
And for your code,
If a function returns a class type by value, and the return
statement's expression is the name of a non-volatile object with
automatic storage duration, which isn't the function parameter, or a
catch clause parameter, and which has the same type (ignoring
top-level cv-qualification) as the return type of the function, then
copy/move is omitted. When that local object is constructed, it is
constructed directly in the storage where the function's return value
would otherwise be moved or copied to. This variant of copy elision is
known as NRVO, "named return value optimization".
Note that the copy/move ctor still need to be accessible.
Even when copy elision takes place and the copy-/move-constructor is not called, it must be present and accessible (as if no optimization happened at all), otherwise the program is ill-formed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37478797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to add custom image to font awesome icon I'm a fan of Font Awesome I'm using lots of icons from there. But, now I need adding my custom image to font awesome file for using as icon. I want to add them to font icons files so that I can use their property like .fa-2x .fa-lg etc By researching on internet I found that I can convert my svg image to font using icomoon or font custom But, my confusion is after downloading files of my generating images as fonts how can I add those to font awesome files. I mean, there are already some files named
*
*FontAwesome (Open Type Font File)
*fontawesome-webfont.eot
*fontawesome-webfont (SVG Document)
*fontawesome-webfont (True Type Font File)
*fontawesome-webfont.woff
Should I've to put anything on those files after downloading my custom generated fonts files? Or, should I've to put the CSS code from custom generated fonts files to fontawesome.css? if this, what CSS code should I put on there? I ain't experienced so much with this process. So, I'm confused with this. That's why, I can't tell everything arranged way. Sorry for this. Thanks
A: Best bet might be using a service like Fontello where you can "create" your own custom icon font and upload the custom icons there in addition to selecting the icons you need from Font Awesome.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24042219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Insert formula with relative cell in a range I've been searching how to insert a formula in a range where each cell refers to a different cell but I still have no clue on how to do it.
I've tried this:
Dim datejour As String
Dim datemois As String
Dim dateannee As String
datejour = Format(Day(Date), "00")
datemois = Format(Month(Date), "00")
dateannee = Year(Date)
lastrow2 = wsdata.range("C" & Rows.Count).End(xlUp).Row + 1
wsdata.range("E2:E" & lastrow2).FormulaR1C1 = "=SDM(D[0]" & "CALC" & dateannee & datemois & datejour & ")"
I basically want something like this:
D
E
Marc
=SDM(D1CALC20220609)
Paul
=SDM(D2CALC20220609)
Thanks in advance!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72558691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: android - data binding to field, displaying matching icon I have a class WifiManager that holds a Boolean value that represents either wifi connected or wifi disconnected.
the Boolean field gets updated with a broadcastReceiver I have in that class.
private BroadcastReceiver wifiScanReceiver;
private boolean isWifiConnected = false;
wifiScanReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent intent) {
// Wifi connected/disconnected
NetworkInfo nwInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
if (nwInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
// wifi connect
isWifiConnected = true;
} else {
// wifi disconnected
isWifiConnected = false;
}
}
};
context.registerReceiver(wifiScanReceiver, wifiIntentFilter);
In my MainActivity I have a WifiManager field, and what I want is to do data binding that will change one of the menu items based on the Boolean value -> if isWifiConnected=false set icon to @drawalbe/xxx, if isWifiConnected=true set icon to @drawalbe/yyy.
Meaning - having sort of a "listener" to changes of the isWifiConnected value, and based on that - set one of the MenuItem's icon to either @drawalbe/xxx or @drawalbe/yyy.
I know there are tons of ways to do it, from broadcasting an Intent in the BroadcastReceiver and catch it in the MainActivity to just have a Handler running and checking the isWifiConnected every 3 seconds..
What I am really looking for is sort of data binding with a converter, like you would do in a MVVM project.
Is there such a thing in android?
A: I assume you know about android data binding and you're just asking how to do it for this specific case. If not, here is the android data binding guide.
You will need a way to observe the boolean value so the UI can remain updated. The easiest way is to make it an ObservableBoolean field of your model object:
public class ViewModel {
public final ObservableBoolean isWifiConnected = new ObservableBoolean();
// other things you want to bind to your layout...
}
When you create the binding, you must also assign the model:
public void onCreate(Bundle icicle) {
ActivityMainBinding binding =
DataBindingUtil.setContentView(this, R.layout.activity_main);
this.model = new ViewModel();
binding.setModel(this.model);
}
And when you receive the broadcast, you update the model:
wifiScanReceiver = new BroadcastReceiver() {
//...
model.isWifiConnected.set(newValue);
//...
};
And your layout would be something like this:
<layout ...>
<data>
<variable name="model" type="com.example.ViewModel"/>
</data>
<!-- rest of layout -->
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@{model.isWifiConnected ? @drawable/xxx : @drawable/yyy}"/>
</layout>
You could also avoid the model class if you keep track of the binding and set the variable directly on it. In that case, you'd have a variable:
<variable name="isWifiConnected" type="boolean"/>
And your broadcast receiver would set the value:
binding.setIsWifiConnected(newValue);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39530947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: c# Building Dynamic SQL in c# Trying to build a Dynamic SQL string in my c# code. Not sure where I'm going wrong with it.
private void Save_Item_Drop_Data()
{
string uri = string.Empty;
string strUpdate = string.Empty;
WBGUpdateValue Update = new WBGUpdateValue();
Update.Email = Game_Data._User_Account.Email;
try
{
foreach (Base_Item item in Game_Data._Item_Drop)
{
//Recipe
if (item.Name.Contains("Recipe"))
{
if (Update_Recipe(item.Name))
{
uri = Game_Data._EndPoint + "api/WhiteboxGaming/Post_UnlockRecipe";
strUpdate = strUpdate + "UPDATE Skill_Gemology SET " + item.Name + "= 1 WHERE Email = ''" + Update.Email + "'' ";
_txtGameMessage.text = item.Name + " Unlocked";
}
}
//Rune
else if (item.Name.Contains("Rune") || item.Name == "Polished_Ancient_Stone" || item.Name == "Ancient_Stone")
{
uri = Game_Data._EndPoint + "api/WhiteboxGaming/Post_SaveItemdrop";
strUpdate = strUpdate + "UPDATE Inventory_Runes SET " + item.Name + "=" + item.Name + " + " + item.Count.ToString() + " WHERE Email = ''" + Update.Email + "'' ";
_txtGameMessage.text = "Found Rune";
}
Debug.Log(Update);
}
}
catch (Exception ex)
{
Debug.Log(ex);
}
if (Game_Data._Item_Drop.Count > 0)
{
Update.Value_1 = strUpdate;
StartCoroutine(booleanwebrequest(uri, Update));
}
Game_Data._Item_Drop = new List<Base_Item>();
}
The string builds this:
UPDATE Inventory_Runes SET Polished_Ancient_Stone=Polished_Ancient_Stone + 1 WHERE Email = ''help.whiteboxgaming@gmail.com''
When I run it via SQL I get an error:
Msg 911, Level 16, State 4, Line 74
Database 'UPDATE Inventory_Runes SET Polished_Ancient_Stone=Polished_Ancient_Stone + 1 WHERE Email = 'help' does not exist. Make sure that the name is entered correctly.
I understand what its telling me but I'm not sure how to fix the Email part in my c# code.
Update: now I'm really confused. I have the dynamic SQL correct but it still fails.
Update:
//Rune
else if (item.Name.Contains("Rune") || item.Name == "Polished_Ancient_Stone" || item.Name == "Ancient_Stone")
{
uri = Game_Data._EndPoint + "api/WhiteboxGaming/Post_SaveItemdrop";
strUpdate = strUpdate + "UPDATE Inventory_Runes SET [" + item.Name + "] = [" + item.Name + "] + " + item.Count.ToString() + " WHERE Email = ''' + @Email + '''";
_txtGameMessage.text = "Found Rune";
}
Outputs:
'UPDATE Inventory_Runes SET [Polished_Ancient_Stone] = [Polished_Ancient_Stone] + 4 WHERE Email = ''' + @Email + '''UPDATE Inventory_Runes SET [Rune_sa] = [Rune_sa] + 1 WHERE Email = ''' + @Email + '''UPDATE Inventory_Runes SET [Polished_Ancient_Stone] = [Polished_Ancient_Stone] + 1 WHERE Email = ''' + @Email + '''UPDATE Inventory_Runes SET [Ancient_Stone] = [Ancient_Stone] + 2 WHERE Email = ''' + @Email + '''UPDATE Inventory_Runes SET [Ancient_Stone] = [Ancient_Stone] + 1 WHERE Email = ''' + @Email + ''''
When I tear it apart it looks like this:
UPDATE Inventory_Runes SET [Polished_Ancient_Stone] = [Polished_Ancient_Stone] + 4 WHERE Email = 'help.whiteboxgaming@gmail.com'
UPDATE Inventory_Runes SET [Rune_sa] = [Rune_sa] + 1 WHERE Email = 'help.whiteboxgaming@gmail.com'
UPDATE Inventory_Runes SET [Polished_Ancient_Stone] = [Polished_Ancient_Stone] + 1 WHERE Email = 'help.whiteboxgaming@gmail.com'
UPDATE Inventory_Runes SET [Ancient_Stone] = [Ancient_Stone] + 2 WHERE Email = 'help.whiteboxgaming@gmail.com'
UPDATE Inventory_Runes SET [Ancient_Stone] = [Ancient_Stone] + 1 WHERE Email = 'help.whiteboxgaming@gmail.com'
A: There could be multiple reasons why this query is failing
You are using '''+@Email+'''
SQL server changes '' into ' which means when you pass ''' it converts to ''
If you want to pass a string variable in you query it should be like
WHERE Email = '" + Update.Email + "'
This way it be passed as string
Second option is you could send all the parameter in procedure and according to data can execute you query, It will be much easier to maintain and understand in future
A: I found a solution to my issue. Based on suggested feedback I came up with this:
try
{
foreach (Base_Item item in Game_Data._Item_Drop)
{
//Recipe
if (item.Name.Contains("Recipe"))
{
if (Update_Recipe(item.Name))
{
uri = Game_Data._EndPoint + "value";
Update.Value_1 = "1";//Update.Value_1 + "UPDATE Skill_Gemology SET " + item.Name + "= 1 WHERE Email = ''" + Update.Email + "'' ";
Update.Value_2 = "Skill_Gemology";
Update.Value_3 = item.Name;
}
}
//Rune
else if (item.Name.Contains("Rune") || item.Name == "Polished_Ancient_Stone" || item.Name == "Ancient_Stone")
{
uri = Game_Data._EndPoint + "value";
Update.Value_1 = item.Count.ToString();//Update.Value_1 + "UPDATE [dbo].[Inventory_Runes] SET [" + item.Name + "] = [" + item.Name + "] + " + item.Count.ToString() + " WHERE Email = ''" + Update.Email + "''";
Update.Value_2 = item.Name;
}
StartCoroutine(booleanwebrequest(uri, Update));
Debug.Log(Update);
}
}
catch (Exception ex)
{
Debug.Log(ex);
}
API Backend:
public bool Save_Item_Drop(string Email, string value, string column)
{
try
{
SqlConnection SQLConn = new SqlConnection(cn);
SqlCommand cmd = new SqlCommand("spHere", SQLConn);
bool Success;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Email", Email);
cmd.Parameters.AddWithValue("@Value", value);
cmd.Parameters.AddWithValue("@Column", column);
SQLConn.Open();
Success = Convert.ToBoolean(cmd.ExecuteScalar());
SQLConn.Close();
return Success;
}
catch (Exception ex)
{
string _Product = "White Box Gaming API";
dynamic _Method = Convert.ToString(System.Reflection.MethodBase.GetCurrentMethod().Name);
dynamic _Class = Convert.ToString(this.GetType().Name);
string _Exception = Convert.ToString(ex.ToString());
Log_Product_Exception(_Product, _Class, _Method, _Exception);
return false;
}
}
SQL:
ALTER PROCEDURE [dbo].[spHere]
@Email AS NVARCHAR(500),
@Value AS NVARCHAR(1000),
@Column As NVARCHAR(1000)
AS
BEGIN
DECLARE @Response AS BIT = 0
DECLARE @Statement AS NVARCHAR(MAX)
SET @Statement = 'UPDATE Inventory_Runes SET ' + @Column + ' = ' + @Column + ' + ' + @Value + ' WHERE Email = ''' + @Email + ''''
-------Pre Check-----------------------------------------------------------------------------------------------------
--Runes
IF Not EXISTS(SELECT Email FROM [dbo].[Inventory_Runes] WHERE Email = @Email) BEGIN
INSERT INTO [dbo].[Inventory_Runes] (Email) VALUES (@Email)
END
BEGIN TRY
EXECUTE sp_executesql @Statement
SET @Response = 1
END TRY
BEGIN CATCH
SET @Response = 0
END CATCH
SELECT @Response
END
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59923192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: R readHTMLTable function not working I have the following code written in R in which I would like to obtain some names from this particular webpage.
library(RCurl)
library(XML)
x <- getURL("http://www.encyclopedia-titanica.org/titanic-passengers-crew-lived/country-17/england.html")
x_2 <- htmlParse(x)
x_3 <- readHTMLTable(x_2)
However, whenever I look at the contents of x_3, I get the following...
x_3
named list()
It seems as though the readHTMLTable function is not able to obtain the tables. Can anyone help me obtain the names of the passengers from this web page without having to copy and paste? Much appreciated.
A: library(rvest)
library(dplyr)
base <- "http://www.encyclopedia-titanica.org/titanic-passengers-crew-lived/country-17/england.html"
# I use the older rvest package...`html` might be `read_html` now.Link to git repo below:
# https://github.com/hadley/rvest/blob/7d65d84e013b1bb3827ae0a2e05ddaed4875c112/R/parse.R
data_df <- (html(base) %>% html_table)[[1]]
knitr::kable(summary(data_df))
| | Name | Age | Class/Dept | Ticket | Joined | Job |Boat [Body] | |
|:--|:----------------|:----------------|:----------------|:----------------|:----------------|:----------------|:----------------|:------------|
| |Length:1190 |Length:1190 |Length:1190 |Length:1190 |Length:1190 |Length:1190 |Length:1190 |Mode:logical |
| |Class :character |Class :character |Class :character |Class :character |Class :character |Class :character |Class :character |NA's:1190 |
| |Mode :character |Mode :character |Mode :character |Mode :character |Mode :character |Mode :character |Mode :character |NA |
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36628875",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Throw error when creating react component conditionally I have a react component called ListChats and another called Chat.
ListChats calls the rendering of a Chat
I need that if an error occurs when rendering the Chat, ListChats knows and comes back with the list of available chats.
A possible error, its capture has not yet been implemented, would be if the user has no name, Chat captures this error and returns to ListChat.
ListChats component:
import React, { Component } from "react";
import Chat from "../Chat";
import { Button } from 'react-bootstrap';
export default class ListChats extends Component {
constructor(props) {
super(props);
this.state = {
chat: <div />
}
this.toSala = this.toSala.bind(this);
}
toSala() {
//this is where I render a Chat component, I need that, if it returns an error, I set this.state.chat to "<div />"
this.setState({chat: <Chat/> });
}
render() {
const { chat} = this.state;
return (
<>
<Button onClick={this.toSala}>abrir chat</Button>
{chat}
</>
)
}
};
Chat component
import React,{ useState, useEffect } from 'react'
const Chat = (props) => {
const [name, setName] = useState('');
const [room, setRoom] = useState('');
const [users, setUsers] = useState([]);
useEffect(() => {
//depending on the value of a variable of mine I have the need or not to throw an error when rendering this component
}, []);
return (
<div>
my chat
</div>
);
};
export default Chat;
In short, I need to throw an error in the Chat component and catch it in ListChats component
A: you can do this in two ways:
first you can pass props from the parent to the child and communicate between the two components by this.set your variable in the parent component and pass that via props to the child component.in this case your child component is responsible to show whatever comes from the parent.
the second one is using a global state management like Redux,ContextApi or mobX to catch error in the child and save it to an state and then use that state in the parent component or wherever you want to use.
depend on the size of your project you can use either way.
A: Thanks to the responses and comments I managed to elaborate the following solution:
1- I created a function in ListChat that will receive the error message (msg) by parameter:
setError = (msg) => {
this.setState({error:msg});
}
2- I passed the function as props in rendering the chat:
this.setState({chat: <Chat setError={this.setError}/> });
3- When I need to now pass an error by the Chat for ListChat,
I call in the Chat component:
props.setError("Name is null");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66232474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Play 2.3 with ReactiveMongo to serialize JsObject I have a case class like this:
case class MemberOptions(
@Key("_id") memberId: Long,
settingsJson: JsObject,
updateDate: DateTime = DateTime.now()
)
How can I serialize and deserialize JsObject? I tried to look for Writes and Reads but found nothing yet. There is one plugin reactivemongo-play-json but it is for 2.4 only.
I decided to convert to String if there is no better solution.
import reactivemongo.bson._
implicit object JsObjectHandler extends BSONHandler[BSONString, JsObject] {
override def read(bson: BSONString): JsObject = Json.parse(bson.value).as[JsObject]
override def write(jsObject: JsObject): BSONString = BSONString(jsObject.toString)
}
implicit val handler = Macros.handler[MemberOptions]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42763434",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Failure to normalize the dynamic range of an image When I try to use the following function to normalize the dynamic range of an image:
void normalize(uint8_t array[], unsigned int cols, unsigned int rows) {
uint8_t minValue = min(array, cols, rows);
uint8_t maxValue = max(array, cols, rows);
uint8_t MIN_RANGE = 0;
uint8_t MAX_RANGE = 255;
uint8_t new_range = MAX_RANGE - MIN_RANGE;
uint8_t old_range = maxValue - minValue;
int range = 0;
double scale = 0;
for (range = 0; range < rows * cols; range++) {
scale = (array[range] - minValue) / (old_range);
array[range] = scale * new_range + MIN_RANGE;
}
}
All I get is 0, but I can't identify the mistake. min() and max() are functions that work correctly to return the darkest and lightest colors respectively.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38819343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to make changes to XAML during runtime/debugging and show changes without a restart? When running my application it is fairly slow to load. So in order to speed up development I am wanting to run my views independently using a testing framework (to avoid needing the whole application load up).
In the process of doing this, I have found that when my views are run from the test runner. I am unable to make changes in XAML and have them reflect in the running application. For example; If I add a textbox to the view via XAML while running, it will not show. I have to restart the test to make it show.
However, when I run my application as a whole. I can edit the XAML and have it make changes to the running app. That is adding a textbox to the view via XAML during running DOES show.
At first I thought it was because the tests were in a different project. So I moved it into the main assembly (everything is in the one assembly/project). The problem is still there. So there must be something else.
One difference, is that I am running my tests from a base class, although I am not sure that should make a difference.
Can anyone tell me how to ensure I can make changes without needing to restart the test?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51412538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What dropdown box does rails_admin use? I want to use it in my rails projects instead of the default selectbox, but can't figure out what kind it is or how to implement it in my code.
The rails_admin one is more like a textbox with typeahead instead of just a standard dropdown.
Thanks!
A: It looks like they have created their own, here take a look:
https://github.com/sferik/rails_admin/blob/master/app/assets/javascripts/rails_admin/ra.filtering-multiselect.js
It would be nice to pull it out and make a plugin, as a note it does look like it depends on jQuery, and jQueryUI.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10987366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to create package with main and test classes? I'm making a PageRank class that relies on some linear algebra operations that I've written myself. Since I couldn't be bothered to learn JUnit testing, I decided to write my own testing class for my PageRank class. Unfortunately, it wasn't as easy as I expected. Here's my basic idea:
pagerank/PageRankTest.java:
package pagerank;
public class PageRankTester{
public static PageRank pagerank = new PageRank();
public static void main(String[] args){
testNorm();
testSubtract();
testDot();
testMatrixMul();
}
private static void testNorm(){
// Tests pagerank.norm()
}
private static void testSubtract(){
// Tests pagerank.subtract()
}
public static void testDot(){
// Tests pagerank.dot()
}
public static void testMatrixMul(){
// Tests pagerank.matrixMul()
}
}
pagerank/PageRank.java:
package pagerank;
import java.util.*;
import java.io.*;
public class PageRank {
public PageRank( String filename ) {
}
/* --------------------------------------------- */
private double[] dot(double[] x, double[][] P){
//returns dot product between vector and matrix
return res;
}
private double[][] matrixMul(double x, double[][] J){
//returns x*J
return J;
}
private double[] subtract(double[] x, double[] y){
//returns elementwise x-y
return v;
}
private double norm(double[] x){
// returns euclidean norm of x
return norm;
}
public static void main( String[] args ) {
if ( args.length != 1 ) {
System.err.println( "Please give the name of the link file" );
}
else {
new PageRank( args[0] );
}
}
}
This causes a number of issues.
1: When compiling the test class using javac PageRankTester.java I get the following error:
$ javac PageRankTester.java
PageRankTester.java:4: error: cannot find symbol
public static PageRank pagerank = new PageRank();
^
symbol: class PageRank
location: class PageRankTester
PageRankTester.java:4: error: cannot find symbol
public static PageRank pagerank = new PageRank();
^
symbol: class PageRank
location: class PageRankTester
2 errors
I thought when you put everything in a package you didn't have to import? My only conclusion is that I'm compiling the wrong way because I've worked in packages where I don't need to import anything from another package.
2: Compiling PageRank.java works fine, but when trying to run PageRank using java PageRank I get:
$ java PageRank
Error: Could not find or load main class PageRank
Caused by: java.lang.NoClassDefFoundError: pagerank/PageRank (wrong name: PageRank)
I've tried java -cp . PageRank, to prevent this error, but with no success.
What is the proper way to achieve what I want here?
A: You have a problem with compiling, start using ide eclipse or intelij Idea.
The PageRank class is not compilable
Another problem is in your package name, try like that:
java pagerank.PageRank
So if you would create a folder structure like that:
src/
pagerank/
PageRank.java
PageRankTester.java
PageRank.java
package pagerank;
public class PageRank {
public PageRank(String filename) {}
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Please give the name of the link file");
} else {
new PageRank(args[0]);
}
}
}
PageRankTester.java
package pagerank;
public class PageRankTester{
public static PageRank pagerank = new PageRank("filename");
public static void main(String[] args){
testNorm();
testSubtract();
testDot();
testMatrixMul();
}
private static void testNorm(){
// Tests pagerank.norm()
}
private static void testSubtract(){
// Tests pagerank.subtract()
}
public static void testDot(){
// Tests pagerank.dot()
}
public static void testMatrixMul(){
// Tests pagerank.matrixMul()
}
}
in cmd cd into src folder and do:
javac pagerank/*.java
java pagerank.PageRank
java pagerank.PageRankTester
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48962369",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Javascript Mouseevent On Hover Currently I am looking for some help with my mouse over event.
<div class="video-container">
<video id="my_video" loop muted poster="IMAGE_URL"> <!-- put your image here -->
<source src="VIDEO_URL" type="video/mp4"> <!-- path to your video here -->
</video>
</div>
Above is my video-container, on my index page I am displaying 10 videos. Each of them should show a preview of the video when being hovered, however with my current javascript only the first video with my_video id is displaying the video preview when hovering.
let myVideo = document.getElementById("my_video");
myVideo.addEventListener("mouseover", () => {
myVideo.play()
image.style.display = 'none'
});
myVideo.addEventListener("mouseleave", () => {
myVideo.pause();
});
How can I make it so that all videos on my homepage, behave in the same manner?
A: Since you do the getElementById, it only covers one element. And ID must be unique to elements in HTML, you cannot have multiple elements with same ID. You can give all of the video elements the same class and apply all of them at once, or just apply to all video elements directly
let myVideos = document.querySelectorAll("video");
myVideos.forEach(vid => {
vid.addEventListener("mouseover", () => {
vid.play();
});
vid.addEventListener("mouseleave", () => {
vid.pause();
});
})
<div id="container">
<video id="my_video_1" loop muted poster="https://external-content.duckduckgo.com/iu/?u=http%3A%2F%2Fwww.tiverton.ri.gov%2Fimg%2Fcontent%2Ftrees%2Fhome_tree.png&f=1&nofb=1&ipt=c0fbdc7aa01163cdffb57908bb424286af2ebd3b6352a581d61660f31a299a51&ipo=images"> <!-- put your image here -->
<source src="VIDEO_URL" type="video/mp4"> <!-- path to your video here -->
</video>
<video id="my_video_2" loop muted poster="https://external-content.duckduckgo.com/iu/?u=http%3A%2F%2Fwww.tiverton.ri.gov%2Fimg%2Fcontent%2Ftrees%2Fhome_tree.png&f=1&nofb=1&ipt=c0fbdc7aa01163cdffb57908bb424286af2ebd3b6352a581d61660f31a299a51&ipo=images"> <!-- put your image here -->
<source src="VIDEO_URL" type="video/mp4"> <!-- path to your video here -->
</video>
</div>
A: You have multiple elements with the same ID. This is your problem, ID's must be unique.
You want something like this
Note you also should not use fat arrow functions for event listeners
//Get the video elements we want
let videos = document.querySelectorAll(".video-container video");
//Loop the elements
videos.forEach((el) => {
//Add the event listeners
el.addEventListener("mouseover", function() {
console.log("Play " + this.querySelector("source").src);
this.play();
});
el.addEventListener("mouseleave", function() {
console.log("Pause " + this.querySelector("source").src);
this.pause();
});
});
<div class="video-container">
<video loop muted poster="IMAGE_URL"> <!-- put your image here -->
<source src="VIDEO_URL" type="video/mp4"> <!-- path to your video here -->
</video>
</div>
<div class="video-container">
<video loop muted poster="IMAGE_URL"> <!-- put your image here -->
<source src="VIDEO_URL2" type="video/mp4"> <!-- path to your video here -->
</video>
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74697373",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: F* Raising Exception in match body I am trying to create a function in F* to determine the minimum element of a list, and I want to throw an exception if the list is empty. The code I have so far is below:
module MinList
exception EmptyList
val min_list: list int -> Exn int
let rec min_list l = match l with
| [] -> raise EmptyList
| single_el :: [] -> single_el
| hd :: tl -> min hd (min_list tl)
When I try to verify the file, however, I get the following error:
mcve.fst(7,10-7,15): (Error 72) Identifier not found: [raise]
1 error was reported (see above)
How can I fix this error?
A: This error comes up because raise is not a primitive in F* but needs to be imported from FStar.Exn (see ulib/FStar.Exn.fst), which exposes this function -- raise. Simply opening this module should be sufficient. There is one more minor issue in the code that I have also fixed below.
Here's the version of the code that goes through:
module MinList
open FStar.Exn
exception EmptyList
val min_list: list int -> Exn int (requires True) (ensures (fun _ -> True))
let rec min_list l = match l with
| [] -> raise EmptyList
| single_el :: [] -> single_el
| hd :: tl -> min hd (min_list tl)
Notice that I also have added requires and ensures clauses. This is because the Exn effect expects a these clauses to reason about the code in it. If your use case however, has exactly the above clauses (i.e., true and true), then you can use the convenient synonym for this, Ex (see ulib/FStar.Pervasives.fst). Thus, the following code is also valid and will behave exactly the same as the above code.
module MinList
open FStar.Exn
exception EmptyList
val min_list: list int -> Ex int
let rec min_list l = match l with
| [] -> raise EmptyList
| single_el :: [] -> single_el
| hd :: tl -> min hd (min_list tl)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57838693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Query is not working or any connection issue I have an issue in my search box, I actually want to show products on a page when anyone searches for the similar product but I am just getting a header and footer not any product.
This is my query in the controller
public function showsearchpage()
{
$query = Product::where('product_name','LIKE','%$q%');
return view('search', ['searchbox'=>$query]);
}
and this is my search.blade.php view source code that I want to show up on my search page
@foreach($searchbox as $query)
<div class="iso-box photoshop branding col-md-4 col-sm-6">
<div class="portfolio-thumb">
<img src="images/portfolio-img1.jpg" class="img-responsive" alt="Portfolio">
<div class="portfolio-overlay">
<div class="portfolio-item">
<a href="/categoriesViewPost"><i class="fa fa-link"></i></a>
<h2>{{$query->product_name}}</h2>
<p>{{$query->product_description}}</p>
</div>
</div>
</div>
</div>
@endforeach
And this is the screenshot that I am getting (I have a similar product in my database of product but still its showing nothing):
ScreenShot of the search page
A: problems :
*
*'%$q%'
*->get();
public function showsearchpage($q)
{
$query = Product::where('product_name','LIKE','%'.$q.'%')->get();
return view('search',['searchbox'=>$query]);
}
A: You forgot get();
public function showsearchpage()
{
$query = Product::where('product_name','LIKE','%$q%')->get();
return view('search',['searchbox'=>$query]);
}
A:
I found out the answer , actually my "q" was not taking input properly . and thanks guys for the help .
public function showsearchpage(Request $request)
{
$q=$request->input('q');
$query = Product::where('product_name', 'like', "%$q%")->get();
return view('search',compact('query'));
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43669873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using the natural width of an element while limiting its height I have elements A, B, and C. I want them to appear in roughly this configuration:
.---.---.
| | B |
. A .---.
| | C |
.---.---.
I want to limit the height of B (and have it overflow: scroll) such that combined height of B and C is the natural height of A. I can do this by wrapping B in an extra container div, specifying position: relative; on the container and position: absolute; height: 100%; on B, and then using flex layout to have the container expand to use all the space that isn't used by C.
So far, so good. But B also has a natural width, and I'd like the overall width of the three elements together to include the width of B, e.g. so I can centre them accurately within their containing element. This makes the position: absolute approach untenable, since that results in the dimensions of B being ignored in the layout of its parents.
Is there some other approach to limiting the height of B to the natural, content-determined height of A minus C? Or is there some way to make the position: absolute technique still allow the width of B to affect the width of the containing element?
A: //Hi Bob
I approached the problem from a slightly different angle: Instead of using position absolute I used display flex 2 times. Is this the flex you're looking for?
.container {
display: flex;
flex-direction: row;
}
.container > div {
flex: 0 0 50%;
}
.container2 {
display: flex;
flex-direction: column;
}
.a {
background: yellow;
}
.b {
background: orange;
flex: 0 1 100%;
}
.c {
background: red;
}
<div class="container">
<div class="a">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</div><div class="container2">
<div class="b">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</div>
<div class="c">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</div>
</div></div>
Saw your comment and edited my first answer in this new code snippet. Does this one work?
.container {
display: flex;
flex-direction: row;
}
.container > div {
flex: 0 0 50%;
}
.container2 {
display: flex;
flex-direction: column;
justify-content: space-between;
}
.a {
background: yellow;
}
.b {
background: orange;
flex: 1 0 auto;
overflow: auto;
position: relative;
}
.b-inner {
position: absolute;
width: 100%
}
.c {
background: red;
flex: 0 0 auto;
}
<div class="container">
<div class="a">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</div><div class="container2">
<div class="b"><div class="b-inner">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</div></div>
<div class="c">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</div>
</div></div>
|
{
"language": "la",
"url": "https://stackoverflow.com/questions/39944041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Make a record from a list of Text values Starting from a list of Text, I'd like to convert this into a Record where each field corresponds to a value in the list.
import Data.Text
data MyRecord = MyRecord {
rOne :: Text,
rTwo :: Text,
rThree :: Int
}
txt :: [Text]
txt = ["foo", "bar", "12"]
I'm not sure how to (cleanly) proceed from the list of Text up to the record. It is assumed that this list will always be of the same size (here, 3) and there will always be an Int-like value in third position.
The minimal naive working version I've got to is so desperately hacky that I can't resign myself to committing this into the codebase:
-- assuming RecordWildCards
readText :: [Text] -> MyRecord
readText l =
let rOne = l !! 0
rTwo = l !! 1
rThree :: Int = read $ l !! 2
in MyRecord {..}
What would be a more Haskell-friendly way of doing this?
Note: what I'm actually after is parsing a comma-separated file into a list of MyRecord, without a csv library. The rows will not contain commas inside a value, so splitting on commas can be considered safe here (e.g. values = T.splitOn "," <$> lines).
A: If you are absolutely sure the list is three elements long, you could use
readText :: [Text] -> MyRecord
readText [rOne, rTwo, rThreeText] = MyRecord {..}
where rThree :: Int = read rThreeText
Still, you might wish to make the pattern matching exhaustive, just in case:
readText :: [Text] -> MyRecord
readText [rOne, rTwo, rThreeText] = MyRecord {..}
where rThree :: Int = read rThreeText
readText _ = error "readText: list length /= 3"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67462494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Stuck at debugging with message "Waiting for Debugger" in Android studio Whenever I try to use Android Studio's Debug function, the Run status would always stuck at:
Launching application: No local changes, not deploying APK
$ adb shell am start -D -n "com.example.nagamacmini.retrofitomdb/com.example.nagamacmini.retrofitomdb.activities.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Waiting for application to come online: com.example.nagamacmini.retrofitomdb.test | com.example.nagamacmini.retrofitomdb
Waiting for application to come online: com.example.nagamacmini.retrofitomdb.test | com.example.nagamacmini.retrofitomdb
Waiting for application to come online: com.example.nagamacmini.retrofitomdb.test | com.example.nagamacmini.retrofitomdb
Waiting for application to come online: com.example.nagamacmini.retrofitomdb.test | com.example.nagamacmini.retrofitomdb
Waiting for application to come online: com.example.nagamacmini.retrofitomdb.test | com.example.nagamacmini.retrofitomdb
Waiting for application to come online: com.example.nagamacmini.retrofitomdb.test | com.example.nagamacmini.retrofitomdb
Waiting for application to come online: com.example.nagamacmini.retrofitomdb.test | com.example.nagamacmini.retrofitomdb
Waiting for application to come online:
So the question is what can I do to make Android Studio debugging work?
A: Try to Restart/Reboot your Device. It's work for me.
A: Try to kill the debugger an re-attach it while process is running -
*
*Run | Stop -> kill the debugger
*Run | Attach debugger to android process (last option in the menu) | choose your app's process. -> re-attaches your debugger to your app process while it's alive.
A: remove -D from your command:
$ adb shell am start -n "com.example.nagamacmini.retrofitomdb/com.example.nagamacmini.retrofitomdb.activities.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
A: Remove your debuggeable device or close emulator and reconnect it or relaunch it. It will work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38699829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: C# - Replacing an item in the backpack I'm trying to create a simple backpack-program. It is an assignment for school and I'm almost finished except I cannot manage to replace the item in my backpack with a new one.
My guess for why it might not be working is that I cannot replace item because it is in the global scope but I have no idea how to fix it. Here is the code:
static void Main(string[] args)
{
bool isRunning = true;
while (isRunning)
{
Console.WriteLine("\n\tWelcome to the backpack!");
Console.WriteLine("\t[1]Add an item");
Console.WriteLine("\t[2]Show contents");
Console.WriteLine("\t[3]Clear contents");
Console.WriteLine("\t[4]Exit");
Console.Write("\tChoose: ");
int menyVal = Convert.ToInt32(Console.ReadLine());
string item;
item = "Empty space";
switch (menyVal)
{
case 1:
Console.WriteLine("\n\tContents of backpack:");
Console.WriteLine("\n\t" + item);
Console.WriteLine("\n\tWhat do you want to replace " + item + " with?");
item = item.Replace(item, Console.ReadLine());
Console.WriteLine("\n\tYou have packed " + item + " in your backpack");
break;
case 2:
Console.WriteLine("\n\tContents of backpack:");
Console.WriteLine("\n\t" + item);
Console.WriteLine("\n\tPress any key...");
Console.ReadKey();
break;
case 3:
item = "Tom plats";
Console.WriteLine("\n\tYou have emptied the backpack!");
break;
case 4:
isRunning = false;
break;
default:
Console.WriteLine("Incorrect input!");
break;
}
}
}
Any ideas on how to fix this? Tips are much appreciated!
Thanks!
A: Move the assignment of
string item;
item = "Empty space";
Before the while loop.
Right now, every time you loop you overwrite the item value.
Here's how the whole code would look after the change:
static void Main(string[] args)
{
bool isRunning = true;
string item = "Empty space";
while (isRunning)
{
Console.WriteLine("\n\tWelcome to the backpack!");
Console.WriteLine("\t[1]Add an item");
Console.WriteLine("\t[2]Show contents");
Console.WriteLine("\t[3]Clear contents");
Console.WriteLine("\t[4]Exit");
Console.Write("\tChoose: ");
int menyVal = Convert.ToInt32(Console.ReadLine());
switch (menyVal)
{
case 1:
Console.WriteLine("\n\tContents of backpack:");
Console.WriteLine("\n\t" + item);
Console.WriteLine("\n\tWhat do you want to replace " + item + " with?");
item = Console.ReadLine());
Console.WriteLine("\n\tYou have packed " + item + " in your backpack");
break;
case 2:
Console.WriteLine("\n\tContents of backpack:");
Console.WriteLine("\n\t" + item);
Console.WriteLine("\n\tPress any key...");
Console.ReadKey();
break;
case 3:
item = "Tom plats";
Console.WriteLine("\n\tYou have emptied the backpack!");
break;
case 4:
isRunning = false;
break;
default:
Console.WriteLine("Incorrect input!");
break;
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42165289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Does people train object detection methods with early stopping and what were their settings? I'm working on some stuff related to object detection methods (YOLOv3, Faster-RCNN, RetinaNet, ... ) and I need to train on VOC2007 and VOC2012 (using pretrained models of course). However when I read the relevant papers I do not see people describe if they trained using early stopping or just fixed number of iterations. And if they used early stopping, how many steps were set before stopping ? Because when I tried 100 steps before stopping, it got really poor results . Please help me, thank you very much.
A: I found an implementation of the PASCAL VOC2012 dataset trained for semantic segmentation that uses the following early stopping parameters:
earlyStopping = EarlyStopping(
monitor='val_loss', patience=30, verbose=2, mode='auto')
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59772828",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: See if Input Has Spaces with jQuery I'm trying to write a function that reads a inputs value, and determines if a space has been used in it's creation. I'm not trying to trim anything -- just see if it would have needed the ability to trim.
I'm not even sure where to begin on this, so I don't have any code to look at. Please help if you can!
I was trying this solution but it doesn't seem to work (I don't think I'm using .has() correctly)
if ($('#id').val().has(" ")) {
alert('has spaces')
}
A: Use val and indexOf :
var hasSpace = $('#myInputId').val().indexOf(' ')>=0;
If you want to test other types of "spaces" (for example a tabulation), you might use a regex :
var hasSpace = /\s/g.test($('#myInputId').val());
Demonstration
A: Use contains for include space:
var value = $('#myInputId').val();
if(value.contains(' ')){
console.log("has space");
}
Or you can find with these ascII code   and \xA0
if(value.contains(' ')){
console.log("has space");
}
A: use val and space:
$('#name').val().length <= 0 || $('#name').val(" ")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13257007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: SQL Rounding Query I have been doing alot of research attempting to find an answer to my question.
I am trying to work out which syntax is needed to round when the figure is less than one.
For example
SELECT 17/26
When running this in SQL, it bring up zero, however i am attempting to get it to return me an answer of 0.65.
I have tried using ROUND, CAST AS Numeric,Decimal and also Money.
So far.... no luck
Any help would be appreciated.
A: try this
SELECT round(convert(float,17)/26,2)
A: For whatever it's worth, when I'm doing something like this with an actual hard-coded value I just add a decimal place to one of the elements. A CAST() is better for a database field, but if you're typing something in just use a decimal ...
SELECT 17/26, 17/26.0, 17.0/26
A: try force engine to manage floats (multiplying with float number '1.0') like this...
SELECT (1.0*17/26) as x;
also to round... you can write it like
SELECT round((1.0*17/26),2) as x;
(tried on PostgreSQL and worked)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26354744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to fix a unexisting Reactive Forms error I'm building a form but, for whatever reason, the compiler is complaining about it.
Can anybody spot something wrong here?
This is what I get:
ERROR Error: No value accessor for form control with name: 'email'
ERROR Error: No value accessor for form control with name: 'password'
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { EmailLoginComponent } from './email/email-login.page';
import { LoginComponent } from './login.page';
import { RouterModule } from '@angular/router';
import { RegisterComponent } from './registration/register.page';
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
declarations: [
EmailLoginComponent,
LoginComponent,
RegisterComponent
],
imports: [
CommonModule,
RouterModule.forChild([
{ path: '', component: LoginComponent },
{ path: 'emailLogin' , component: EmailLoginComponent },
{ path: 'register' , component: RegisterComponent }
]),
ReactiveFormsModule
],
exports: [],
providers: [],
})
export class LoginModule {}
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-register',
templateUrl: './register.page.html',
styleUrls: ['./register.page.scss']
})
export class RegisterComponent implements OnInit {
platform: string;
registerForm: FormGroup;
constructor() { }
ngOnInit() {
this.registerForm = new FormGroup({
email: new FormControl(''),
password: new FormControl('')
});
}
}
<form [formGroup]="registerForm" (ngSubmit)="onRegisterUser()">
<ion-item lines="full" color="secondary">
<ion-input placeholder="Email" type="email" formControlName="email"></ion-input>
</ion-item>
<ion-item lines="full" color="secondary">
<ion-input placeholder="Password" type="password" formControlName="password"></ion-input>
</ion-item>
</form>
A: I copied your code into an ionic stackblitz project and was unable to reproduce your issue.
https://stackblitz.com/edit/ionic-ojdypw
Maybe there is something there that can help you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62283527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Copied data paste into String function Can anyone tell me how to store copied data into String in selenium?
example:
driver.findElement(By.xpath("//*[@id="x")).sendKeys(Keys.CONTROL, "a"));
driver.findElement(By.xpath("//*[@id="xy")).sendKeys(Keys.CONTROL, "c"));
driver.findElement(By.xpath("//*[@id="xy")).sendKeys(Keys.CONTROL, "v"));
I need put the copied data into String
Something like this
String text = driver.findElement(By.xpath("//*[@id="xy")).sendKeys(Keys.CONTROL, "v"));
A: It seems you want to send ctrl + c keys, which will copy some data in clipboard.. want to store that data in String variable..right?
You have to use Clipboard class to do so..See implementation below...
package resources;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class One {
@Test
public void getClipboardContents() {
String result = "";
System.setProperty("webdriver.chrome.driver", "C://WebDrivers/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com");
String copy = Keys.chord(Keys.CONTROL,Keys.chord("c"));
driver.findElement(By.linkText("Images")).sendKeys(copy);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable contents = clipboard.getContents(null);
boolean hasTransferableText = (contents != null)
&& contents.isDataFlavorSupported(DataFlavor.stringFlavor);
if (hasTransferableText) {
try {
result = (String) contents.getTransferData(DataFlavor.stringFlavor);
} catch (UnsupportedFlavorException | IOException ex) {
System.out.println(ex);
ex.printStackTrace();
}
}
System.out.println(result);
}
}
@Starlord ..modify locators as per your need.
A: @Gaurav Thanks for the code.. I have modified some part of the code.. now I am getting what i want exactly
public void getClipboardContents()
throws UnsupportedFlavorException, IOException {
String result = "google.com";
System.setProperty("webdriver.chrome.driver", "E:\\New folder\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.co.in/");
String copy = Keys.chord(Keys.CONTROL,Keys.chord("c"));
driver.findElement(By.xpath("//*[@id=\"lst-ib\"]")).sendKeys("google.com");
driver.findElement(By.xpath("//*[@id=\"lst-ib\"]")).sendKeys(Keys.CONTROL+"a");
driver.findElement(By.xpath("//*[@id=\"lst-ib\"]")).sendKeys(copy);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable contents = clipboard.getContents(null);
String x = (String) contents.getTransferData(DataFlavor.stringFlavor);
System.out.println(x);
int a= result.length();
int b = x.length();
System.out.println(a);
System.out.println(b);
if(a<=b)
{
System.out.println("Matched Character length")
}else
{
System.out.println("Issue In Character length");
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48793215",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Extract all function from source file without evaluating it For my package I am looking for a method to identify all function assignments in a user supplied R script, without executing it.
So let's assume the following example script (ex.R):
ex.R
## user supplied script
a <- function(x) 1
b1 = b2 <- function() {
y <- 1
2 -> j
j
}
d <<- function(x) {
k <- function(l) 1
k(x)
}
(function(x) 2) -> e
(function() {
y <- 1
2 -> j
j
}) -> f1 -> f2
(function() 1)()
g <- 4
5 -> h
i <- lapply(1:3, FUN = function(x) x + 1)
assign('j', function() 1)
k1 <- (function() {1}) -> k2
The function should return c("a", "b1", "b2", "d", "e", "f1", "f2", "j", "k1", "k2")
I came up with the following solution:
library(dplyr)
code <- parse("ex.R")
get_identifier <- function(nm) {
if (is.symbol(nm)) {
deparse(nm)
} else if (is.character(nm)) {
nm
} else {
stop(paste0("unknown type", typeof(nm), "for `nm`"))
}
}
get_fns <- function(expr) {
assignment_ops <- c("<-", "=", "assign", "<<-")
is_assign <- deparse(expr[[1L]]) %in% assignment_ops
is_call <- is_assign && is.call(expr[[3L]])
if (is_call) {
next_call <- deparse(expr[[3L]][[1L]])
if (next_call == "function") {
get_identifier(expr[[2L]])
} else if (next_call %in% c(assignment_ops, "(")) {
c(get_identifier(expr[[2L]]), Recall(expr[[3L]]))
} else {
NULL
}
} else {
NULL
}
}
unlist(lapply(code, get_fns))
# [1] "a" "b1" "b2" "d" "e" "f2" "f1" "j" "k1" "k2"
Which is correct for at least this use case.
But adding just two other nasty edge cases will break the code:
l1 <- (1 + (l2 <- function(x) 2 * x)(3))
(m <- function(x) x)
should return c("l2", "m"), but it does not. My recursion is somewhere at fault, but I cannot spot the problem. How would I fix the code?
Update
The comment showed that I should explain a bit what I want to achieve eventually:
*
*I want to develop a package which takes an "arbitrary" R script (script.R say) and transforms this script into a script which has a Command Line Interface (script_ammended.R say), that is which can be eventually called via Rscript ammended_script.R [ARGS].
*The idea is that user script contains some functions with some special comments and via those the CLI is auto-generated.
*I know that there a couple of libraries, which enable a decent command line parsing already, but all of them require of course that the user spends some time on CLI programming.
*My use case is somewhat different. I want a standalone script, which simply uses some functions to do what it is meant to do. If the user later wants to create a CL tool out of it, it should be as easy as pressing a button (assuming that the user add some minimal comments to the original functions).
*The auto generated script will always add extra code, to log, to make sure that needed libraries are installed and so on.
A contrived example may look like this:
script.R
greet <- function(msg, from = "me") {
#! short: -g
#! params: [., -f]
#! description: greeting <msg> from user <me> is shown
print(paste0("Message from <", from, ">: ", msg))
}
bye <- function() {
#! short: -b
greet("Good Bye", "system")
}
greet("Test")
This would be a typical user script, which can be quite conveniently used interactively. Now, my package should take this script and turn it into the following script:
script_amended.R
library(optigrab)
greet <- function(msg, from = "me") {
print(paste0("Message from <", from, ">: ", msg))
}
bye <- function() {
greet("Good Bye", "system")
}
msg <- opt_get("g", default = NA_character_,
description = "greeting <msg> from user <me> is shown")
from <- opt_get("f", default = "me")
bye_flag <- opt_get("b", default = FALSE)
if (!is.na(msg)) {
greet(msg, from)
quit(status = 0)
} else if (bye_flag) {
bye()
quit(status = 0)
}
A: Credits to Allan Cameron's comments to run the script, below a function to use exactly that approach.
functions_from_source <- function(source) {
myEnv <- new.env()
source(source, local = myEnv)
objects <- ls(envir = myEnv)
funs <- sapply(objects, \(x){
is.function(eval(parse(text = x), envir = myEnv))
})
objects[funs]
rm(envir = myEnv)
}
functions_from_source("ex.R")
# [1] "a" "b1" "b2" "e" "f1" "f2" "j" "k1" "k2" "m"
ex.R including m and l1 (note R does not interpret l2 as a function but as a value)
a <- function(x) 1
b1 = b2 <- function() {
y <- 1
2 -> j
j
}
d <<- function(x) {
k <- function(l) 1
k(x)
}
(function(x) 2) -> e
(function() {
y <- 1
2 -> j
j
}) -> f1 -> f2
(function() 1)()
g <- 4
5 -> h
i <- lapply(1:3, FUN = function(x) x + 1)
assign('j', function() 1)
k1 <- (function() {1}) -> k2
l1 <- (1 + (l2 <- (function(x) 2 * x)(3)))
(m <- function(x) x)
A: Tried reducing the function: Though might have some edge cases. Not sure.
get_fun <- function(x){
dp <- deparse1(x[[1]])
if( dp %in% c('<-', '=', '<<-')) c(x[[2]], get_fun(x[[3]]))
else if(dp == c('(')) get_fun(x[[2]])
else if(dp == 'assign') as.list(x[-1])
else if(dp == 'function') x
else if(any(i<-grepl("<<?-",x))) c(NA, get_fun(x[[which(i)]]))
}
get_name <- function(y){
x <- head(get_fun(y), -1)
if (length(x) > 1 & any(i <- is.na(x))) x <- tail(x,-max(which(i)))
as.character(x)
}
get_fns <- function(file){
unlist(lapply(parse(file), get_name))
}
get_fns('ex.R')
[1] "a" "b1" "b2" "d" "e" "f2"
[7] "f1" "j" "k1" "k2" "l2" "m"
The usage of get_fun is quite simple. eg:
suppose we have:
z <- alist( l1 <- (1 + (l2 <- function(x) 2 * x)(3)),
(s = (m <- function(x) x))->k,
d <- (((function(x)x+2))),
i <- lapply(1:3, FUN = function(x) x + 1),
j <- lapply(1:3, FUN <- function(x) x + 1))
Notice that we have l2, m, d, FUN. The FUN is from j and not i since we used <- meaning we assigned the function and not merely a parameter:
From l1 we get:
get_fun(z[[1]])
[[1]]
l1
[[2]]
[1] NA
[[3]]
[1] NA
[[4]]
l2
[[5]]
function(x) 2 * x
We only pick everything after all the NAs:
get_fun(z[[2]])
[[1]]
k
[[2]]
s
[[3]]
m
[[4]]
function(x) x
get_fun(z[[3]])
[[1]]
d
[[2]]
function(x) x + 2
get_fun(z[[4]])
[[1]]
i
For z[[4]] although there is a name, there is no function associated with the name. Thus not a valid function
get_fun(z[[5]])
[[1]]
j
[[2]]
[1] NA
[[3]]
FUN
[[4]]
function(x) x + 1
A: After a good sleep, I could reduce the (recursive) problem to 5 simple cases:
*
*If the expression under investigation (expr) is not a call, we stop and return NULL.
*If we hit a bracket, simply recurse into the expression and keep the current list of potential identifiers.
*If we hit a function, we simply return the vector of potential identifiers collected so far.
*If we hit an assignment operator, add the identifier to the list of potential identifiers and recurse into the RHS of the assignment.
*In any other case, we loop through all elements of the call, but reset the list of potential identifiers to NULL.
extract_function <- function(expr, identifiers = NULL) {
.OP <- 1L
.LHS <- 2L
.RHS <- 3L
.ASGNM <- c("<-", "<<-", "=", "assign")
if (is.call(expr)) {
op <- deparse(expr[[.OP]])
if (op == "(") {
## bracket case: simply recurse into the call and keep identifiers
res <- Recall(expr[[-.OP]], identifiers)
} else if (op == "function") {
## function case: we can stop and return stored identifiers
res <- identifiers
} else if (op %in% .ASGNM) {
## assignment case: add LHS to potential list of identifiers
res <- Recall(expr[[.RHS]], c(as.character(expr[[.LHS]]), identifiers))
} else {
## else case: drop identifiers and recurse into function
res <- lapply(expr, extract_function, identifiers = NULL) |>
unlist()
}
} else {
res <- NULL
}
res
}
unlist(lapply(parse("ex.r"), extract_function))
# [1] "a" "b2" "b1" "d" "e" "f1" "f2" "j" "k2" "k1" "l2" "m"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75374051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: having trouble compiling old VC++ 6 c++ code I am trying to compile MSVC 6 C++ code using MSVC 2008 Express on 64 bit windows 7. When I tried to open the .sln file, I get the error "project file dpcwebcfx.vproj could not be loaded". I don't have the .vproj file, but I do have dpcwebcfx.dsw file. So in the .sln file I changed
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "dpcwebcfx", "dpcwebcfx.vcproj", "{355F3EB4-3B37-4272-B454-340E9B3BD9D3}"
to
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "dpcwebcfx", "dpcwebcfx.dsw", "{355F3EB4-3B37-4272-B454-340E9B3BD9D3}"
Now I get an error converting the dsw file: Cannot load the project due to a corrupt project file. What should I do? Am I missing a file so that I can't open this project?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18018358",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Exception in VOCE sample C++ app I've been playing around with the C++ api of Voce for speech recognition in one of my projects. So far, I've been able to compile the C++ version of one of the sample apps provided by Voce named recognitionTest (provided under the samples directory in voce-0.9.1).
However, when I try running recognitionTest.exe, I hit an IndexOutOfBoundsException (console output is provided below).
[Voce] Java virtual machine created
[Voce] Initializing recognizer. This may take some time...
[Voce] Initialization complete
This is a speech recognition test. Speak digits from 0-9 into the microphone. Speak 'quit' to quit.
Exception in thread "Recognition thread" java.lang.IndexOutOfBoundsException: Index: 110,Size: 109
at java.util.SubList.rangeCheck(Unknown Source)
at java.util.SubList.get(Unknown Source)
at edu.cmu.sphinx.decoder.scorer.ScoreableJob.getFirst(ThreadedAcousticScorer.java:516)
at edu.cmu.sphinx.decoder.scorer.ThreadedAcousticScorer.scoreScoreables(ThreadedAcousticScorer.java:310)
at edu.cmu.sphinx.decoder.scorer.ThreadedAcousticScorer.calculateScores(ThreadedAcousticScorer.java:276)
at edu.cmu.sphinx.decoder.search.SimpleBreadthFirstSearchManager.scoreTokens(SimpleBreadthFirstSearchManager.java:337)
at edu.cmu.sphinx.decoder.search.SimpleBreadthFirstSearchManager.recognize(SimpleBreadthFirstSearchManager.java:258)
at edu.cmu.sphinx.decoder.search.SimpleBreadthFirstSearchManager.recognize(SimpleBreadthFirstSearchManager.java:226)
at edu.cmu.sphinx.decoder.Decoder.decode(Decoder.java:94)
at edu.cmu.sphinx.recognizer.Recognizer.recognize(Recognizer.java:116)
at edu.cmu.sphinx.recognizer.Recognizer.recognize(Recognizer.java:135)
at voce.SpeechRecognizer.run(SpeechRecognizer.java:129)
at java.lang.Thread.run(Unknown Source)
I'm using Windows 8 and 32-bit version of java 1.5.
Question: Has someone encountered a similar error before? The exception seems to be thrown by the underlying cmusphinx library. So, I'm unable to debug the issue.
Any help would be greatly appreciated!
Please let me know if any additional info would be helpful in figuring out the issue.
Thanks in advance!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29550317",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How does this function traverse Binary Tree? I am working on a coding challenge. I found a solution, but I did not understand a part of the solution.
The prompt is
Given a binary tree, find the leftmost value in the last row of the tree.
Input:
1
/ \
2 3
/ / \
4 5 6
/
7
Output:
7
Tree is defined:
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
This function works (I did not come up with it):
var findBottomLeftValue = function(root) {
var result = root.val;
var resultHeight = 0;
(function recurse (node, height) {
if (node === null) {
return;
}
if (node.left !== null) {
recurse(node.left, height + 1);
}
if (height > resultHeight) {
result = node.val;
resultHeight = height;
}
if (node.right !== null) {
recurse(node.right, height + 1);
}
})(root, 1);
return result;
};
I understand most of the line, but frankly, this is my first time seeing IIFE inside another function, so maybe that threw me off a little.
What I don't understand is, let's say we start with root 1 (using example above), it starts off with node being 1. Since node.left !== null, node is now 2, since node.left !== null, it goes down to 4. node.left is now null, it goes to the next line, which updates height and resultHeight. Then next line, node.right is null, and function ends. In my understanding, it never went to check nodes 3, 5, etc. But the function clearly shows the right answer.
Where on the solution did it check for nodes 3, 5, 6, and 7?
A: Your function descents to the left in the first call of recurse() (line 9).
If it is done with the left node, it'll go to the right in the second call to recurse() (line 16).
The sequence of the nodes will be 1 -> 2 -> 4 -> (2) -> (1) -> 3 -> 5 -> 7 -> (5) -> (3) -> 6 -> (3) -> (1).
The nodes in braces show where the call stack is reduced.
A: If you imagine what is happening as a stack,it's much easier to understand.
It starts on the node with value 1. When it checks the left node,it's left on hold as the first item of the stack(to be called again when it's the topmost item of the stack again)
It would look something like this when it starts on the second iteration:
2
---
1
Then,it would keep executing and adding to the stack until it check that the node 4 has no left or right node.
At this moment,it would look like this:
4
---
2
---
1
Then,since there's nothing else to do on the node with value 4,it gets removed out of the stack,and then it executes the next topmost of the stack from where it left off:checking the right node of it.
I hope this helped you visualise and understand what really happens because that really helped me and some college coleagues to understand binary trees.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47659452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why is AWS Lambda resetting every ~2hrs even with regular ping from EventBridge? I have a Lambda function that has an unacceptably long start-up time due to large files being transferred on initialisation. Once this is done, the actual data processing is very quick
I've set up a rule with EventBridge that keeps the function warm by sending a dummy request every 4 minutes. I've set these dummy requests up such that they only take a few ms after the initial request.
For this most part this seems to be working well - on the logs I see one long request and then all of the ones afterwards are quick.
However, I notice that every 128 minutes I get another long request, as if the Lambda function is 'resetting', despite the warming rule.
Does anyone know why this is happening? I don't understand why I'm getting these intermittent long requests if the function is being kept warm..
A: A lambda function instance has a maximum lifetime of about 2 hours even if it's in use. If you want to keep an instance alive then you should use provisioned concurrency.
A: What Matt said above is true, you should use provisioned concurrency. But you can also speed up the cold start by using lambda layers to include files there, instead of downloading on initialization (if the files you need to download don't change frequently).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73838898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Handling large JSON web response in VBA I need to create a program that accesses a REST API and imports the JSON response into Excel. I am using XMLHTTP WebRequest to get the response into an string and then use the VBA-JSON Library to parse it.
Sample code:
Dim Url As String
Dim Response As String
Dim HttpReq, ResponseObj As Object
Url = "https://jsonplaceholder.typicode.com/posts"
'Download JSON response and Parse it into an object
Set HttpReq = CreateObject("WinHttp.WinHttprequest.5.1")
HttpReq.SetTimeouts -1, -1, -1, -1
HttpReq.Open "GET", Url, False
HttpReq.Send
Response = HttpReq.ResponseText 'Line with Out of Memory Error
ResponseObj = ParseJson(Response)
'This is followed by further code that places the response rows into Excel Cells
The input is well structured array, similar to the URL used here and the current code works well for majority of requests. However there are some requests where the response is approximately 40 MB where I get an "Out of Memory" error on retrieving the response (Line with reference to HttpReq.ResponseText). I have tried restarting the machine, closing other programs, Excel Safe Mode, etc but the error persists.
The question I have is, is there any way that I can download, parse and import data into Excel in a more memory efficient manner so that I do not run into the memory error above. For reference, I need to use Excel 2010 32 bit as that's the only approved and installed version at my workplace.
A: Try the below approach to get the Id,Title and body from that webpage.
Sub Get_data()
Dim HTTP As New XMLHTTP60, res As Variant
Dim r As Long, v As Long
With HTTP
.Open "GET", "https://jsonplaceholder.typicode.com/posts", False
.setRequestHeader "User-Agent", "Mozilla/5.0"
.send
res = Split(.responseText, "id"":")
End With
r = UBound(res)
For v = 1 To r
Cells(v, 1) = Split(res(v), ",")(0)
Cells(v, 2) = Split(Split(Split(res(v), "title"":")(1), """")(1), """,")(0)
Cells(v, 3) = Split(Split(Split(res(v), "body"":")(1), """")(1), """,")(0)
Next v
End Sub
Reference to add to the library:
Microsoft XML, V6.0
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48846585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to write this sql query efficiently in this case Here I have a query like below and am looping the child id and passing it to this query and getting the appropriate result. Here I have 33 child ids so the result for this query contains 33 rows
DECLARE @DATETIMENOW DATETIME
SET @DATETIMENOW = GETDATE()-7
SELECT COUNT(1) FROM BKA.CHILDEVENTS CHE JOIN BKA.CHILDEVENTPROPERITIES CHEP ON CHEP.EVENTID = CHE.EVENTID
WHERE (CHE.TYPE = 'ACCIDENT' OR (CHE.TYPE = 'BREAK' AND CHEP.PROPERTY = 'SUCCESS' AND CHEP.PROPERTYVALUE = 'FALSE'))
AND CHE.CHILDID = @CHILDID AND CHE.ADDDATE BETWEEN DATEADD(DD, -(DATEPART(DW, @DATETIMENOW-7)-1), @DATETIMENOW-7) AND
DATEADD(DD, 7-(DATEPART(DW, @DATETIMENOW-7)), @DATETIMENOW-7) AS PREVIOUSWEEKACCIDENTS
here instead of looping the childid I have tried using join in this query but am getting the result in a single row. what I am doing wrong in this
DECLARE @DATETIMENOW DATETIME
SET @DATETIMENOW = GETDATE()-7
SELECT COUNT(1) FROM BKA.CHILDEVENTS CHE JOIN BKA.CHILDEVENTPROPERITIES CHEP
ON CHEP.EVENTID = CHE.EVENTID
JOIN BKA.CHILDINFORMATION CHINFO
ON CHE.CHILDID = CHINFO.CHILDID
WHERE (CHE.TYPE = 'ACCIDENT' OR (CHE.TYPE = 'BREAK' AND CHEP.PROPERTY = 'SUCCESS' AND CHEP.PROPERTYVALUE = 'FALSE'))
AND CHE.ADDDATE
BETWEEN DATEADD(DD, -(DATEPART(DW, @DATETIMENOW-7)-1), @DATETIMENOW-7) AND
DATEADD(DD, 7-(DATEPART(DW, @DATETIMENOW-7)), @DATETIMENOW-7)
Any suggestion?
A: You need to add a GROUP BY clause:
SELECT CHINFO.CHILDID
, COUNT(1)
FROM BKA.CHILDEVENTS CHE
JOIN BKA.CHILDEVENTPROPERITIES CHEP ON CHEP.EVENTID = CHE.EVENTID
JOIN BKA.CHILDINFORMATION CHINFO ON CHE.CHILDID = CHINFO.CHILDID
WHERE ( CHE.TYPE = 'ACCIDENT'
OR ( CHE.TYPE = 'BREAK'
AND CHEP.PROPERTY = 'SUCCESS'
AND CHEP.PROPERTYVALUE = 'FALSE'
)
)
AND CHE.ADDDATE BETWEEN DATEADD(DD,
-( DATEPART(DW, @DATETIMENOW - 7) - 1 ),
@DATETIMENOW - 7)
AND DATEADD(DD,
7 - ( DATEPART(DW, @DATETIMENOW - 7) ),
@DATETIMENOW - 7)
GROUP BY CHINFO.CHILDID
A: A value in the where will invalidate an outer join
SELECT CHE.CHILDID
, COUNT(1)
FROM BKA.CHILDEVENTS CHE
LEFT JOIN BKA.CHILDEVENTPROPERITIES CHEP
ON CHEP.EVENTID = CHE.EVENTID
AND ( CHE.TYPE = 'ACCIDENT'
OR ( CHE.TYPE = 'BREAK'
AND CHEP.PROPERTY = 'SUCCESS'
AND CHEP.PROPERTYVALUE = 'FALSE'
)
)
AND CHE.ADDDATE BETWEEN DATEADD(DD,
-( DATEPART(DW, @DATETIMENOW - 7) - 1 ),
@DATETIMENOW - 7)
AND DATEADD(DD,
7 - ( DATEPART(DW, @DATETIMENOW - 7) ),
@DATETIMENOW - 7)
GROUP BY CHE.CHILDID
A: DECLARE @DATETIMENOW DATETIME
SET @DATETIMENOW = GETDATE()
SELECT B.WEEK FROM BKA.CHILDINFORMATION CI LEFT OUTER JOIN
(SELECT Distinct CHINFO.CHILDID,COUNT(*) as week FROM BKA.CHILDINFORMATION CHINFO
JOIN BKA.CHILDEVENTS CHE
ON CHE.CHILDID = CHINFO.CHILDID
JOIN BKA.CHILDEVENTPROPERITIES CHEP
ON CHE.EVENTID = CHEP.EVENTID
WHERE
(CHE.TYPE = 'ACCIDENT' OR (CHE.TYPE = 'POTTYBREAK' AND CHEP.PROPERTY = 'SUCCESS'
AND CHEP.PROPERTYVALUE = 'FALSE'))
AND
CHE.ADDDATE
BETWEEN DATEADD(DD, -(DATEPART(DW, @DATETIMENOW-14)-1), @DATETIMENOW-14) AND
DATEADD(DD, 7-(DATEPART(DW, @DATETIMENOW-14)), @DATETIMENOW-14) group by CHINFO.CHILDID) b
on CI.ChildID = b.ChildID
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23547759",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Worst Case Binary Search? The question is:
In order to distinguish ordinary emails from spam,
an algorithm with several features has been designed. Every feature provides
information about the message, for instance number of suspicious words, the
length of the message, degree of matching with spam templates etc. Every feature is a discrete variable with two values, for example, low/high, short/long, and similar/dissimilar. A tree with 255 nodes has been employed to make the decision whether to reject an email. How many operations/steps/time units
are required at most to process each email?
I was thinking that this would be a perfect binary tree, so 2^n - 1 = 255, thus n = 8. However, I was starting to consider the following "worst-case" scenario:
...O
../\
.O..O
..../\
...O..O
and so forth.
So would this use a binary search recurrence relation. T(n)=T(n/2)+1?
A: I think you have the right answer Jay. From the question, I would draw the tree to look like this:
> o
> /\
> feature 1: o o
> /\ /\
> feature 2: o o o o
>
...
So you start with a root value. Then you ask if the feature has been successfully met by the email or not, so it breaks into 2 nodes, Y or N. For Y (left-subtree), you ask if the email has met the 2nd feature, Y or N and this breaks off into 2 more node and the same is repeated on the N side (right-subtree). Repeat for all features.
We know that the big-Omega (worst case) for a perfect binary tree is log(n) [base 2]. So log(255) [base 2] is approximately 8, & that must be the max number of steps required.
A: If your tree is a balanced binary tree, then the answer would be 8.
The wording of the problem doesn't seem to call that out though. So that being said, we could make a tree that is a chain (only right children), which would make 255 the worse case.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22442190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Externalize angular configuration file ( config.json ) I have an angular application (war format) that run on a jboss application server. My actual architecture is: Front app ( angular ) and back app ( java ), the front calls back services using the rest api link, that is provided in the src/conf/config.json file.
This is my app config file :
{
"restApiUrl": "https://jboss_host:8443/back/rest/",
"ldapAuthentication" : true
}
So, my needs for now ( the client need) is to externalize this config file to change the rest api link easily, without make a rebuild or redeploiment process.
I can't use any further elements in my architecture ( revers-proxy, conf server ) because it going to be a brain teaser for the client production, or api database ( the DB connection is provided by the back service ).
Please can you advise.
A: If you do not want load config file over http, try to use config.js file.
Rename config.json to config.js and change content to this:
var config = {
"restApiUrl": "https://jboss_host:8443/back/rest/",
"ldapAuthentication" : true
}
Then include config file into index.html in your application:
<script type="text/javascript" src="config.js"></script>
In angular application you can access to this config via (<any>window).config.
For more convenient use create ConfigService like:
@Injectable({providedIn: 'root'})
export class ConfigService {
getConfig(): Config { // You should create some model of your config too or you can use 'any'
return (<any>window).config;
}
}
A: @mpstv thank you for your replay.
I was able to solve this, by using the power of java servlet. The solution was adding to the project war the WEB-INF folder ( servlet.class + web.xml ) that will charge the config file from the filesystem and serve it to the angular, while HTTP call.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63673403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Calling NSXMLParser from static method does not parse I'm trying to build a nice little class with NSXMLParser for my needs.
I'm calling the class this way:
ViewController.m:
[IDAN_XML_Parser setXmlString:soapMsg];
[IDAN_XML_Parser setStringToFind:@"userID"];
[IDAN_XML_Parser setHeader:kAPP_PASSWORD andHeaderValue:kAPP_HEADER];
[IDAN_XML_Parser setSetupXml:kWEB_SERVICE_URL];
[IDAN_XML_Parser prepareParsingAndGetResponse];
NSString *answer = [IDAN_XML_Parser getResponse];
NSLog(@"Response: %@", answer);
And my class is this:
.h file:
#import <Foundation/Foundation.h>
@interface IDAN_XML_Parser : NSObject <NSXMLParserDelegate, NSURLConnectionDelegate>
+ (void)setXmlString:(NSString *)theXML;
+ (void)setStringToFind:(NSString *)stringToFind;
+ (void)setSetupXml:(NSString *)webServicesURL;
+ (void)setHeader:(NSString *)headerKey andHeaderValue:(NSString *)headerValue;
+ (BOOL)prepareParsingAndGetResponse;
- (NSInteger)startParsing;
+ (BOOL)isParsingOK;
+ (IDAN_XML_Parser *)sharedXML;
+ (NSString *)getXMLString;
+ (NSString *)getResponse;
@end
.m file
#import "IDAN_XML_Parser.h"
@implementation IDAN_XML_Parser
NSString *matchingElement;
NSString *xmlString;
NSMutableData *webData;
NSURLConnection *conn;
NSString *soapHeader_key;
NSString *soapHeader_value;
NSURL *url;
BOOL isHeader = NO;
NSInteger didGetError = 0;
BOOL elementFound;
NSMutableString *soapResults;
NSString *returnedString;
NSXMLParser *xmlParser;
NSString *exceptionReason;
NSString *resultXML;
#pragma mark - Setup Parsing
+ (IDAN_XML_Parser *)sharedXML
{
static IDAN_XML_Parser *theParser;
@synchronized(self) {
if (!theParser)
theParser = [[self alloc] init];
}
return theParser;
}
+ (void)setXmlString:(NSString *)theXML
{
xmlString = theXML;
NSLog(@"\n\nXML TO SEND: %@", xmlString);
}
+ (void)setStringToFind:(NSString *)stringToFind
{
matchingElement = stringToFind;
}
+ (void)setHeader:(NSString *)headerKey andHeaderValue:(NSString *)headerValue
{
isHeader = YES;
soapHeader_key = headerKey;
soapHeader_value = headerValue;
}
+ (void)setSetupXml:(NSString *)webServicesURL
{
url = [NSURL URLWithString:webServicesURL];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:@"%d", [xmlString length]];
[req addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[req addValue:msgLength forHTTPHeaderField:@"Content-Length"];
[req setHTTPMethod:@"POST"];
[req setHTTPBody: [xmlString dataUsingEncoding:NSUTF8StringEncoding]];
if (isHeader) {
[req setValue:soapHeader_value forHTTPHeaderField:soapHeader_key];
}
conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
if (conn)
{
webData = [NSMutableData data];
}
}
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *) response
{
[webData setLength: 0];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *) data
{
[webData appendData:data];
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *) error
{
didGetError = 1;
NSLog(@"\n\nConnection Error: %@", error);
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection
{
resultXML = [[NSString alloc] initWithBytes:[webData mutableBytes]
length:[webData length]
encoding:NSUTF8StringEncoding];
didGetError = 0;
NSLog(@"\n\nRESPONSE XML: %@", resultXML);
}
+ (BOOL)prepareParsingAndGetResponse
{
NSInteger isParsingOK;
isParsingOK = [[self sharedXML] startParsing];
if (isParsingOK == 1) {
return YES;
} else {
return NO;
}
}
- (NSInteger)startParsing
{
@try {
xmlParser = [[NSXMLParser alloc] initWithData:webData];
[xmlParser setDelegate:self];
[xmlParser setShouldResolveExternalEntities:YES];
[xmlParser parse];
}
@catch (NSException *exception) {
didGetError = 1;
exceptionReason = exception.reason;
NSLog(@"Exception Reason: %@", exception.reason);
}
if (didGetError != 1) {
didGetError = 0;
}
return didGetError;
}
+ (NSString *)getXMLString
{
return resultXML;
}
+ (BOOL)isParsingOK
{
if (didGetError == 1) { // We have error
return 1;
} else { // We don't have error
return 0;
}
}
+ (NSString *)getResponse
{
return returnedString;
}
#pragma mark - Start Parsing
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
NSLog(@"START PARSING!");
if ([elementName isEqualToString:matchingElement]) {
if (!soapResults) {
soapResults = [[NSMutableString alloc] init];
}
elementFound = YES;
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if (elementFound) {
[soapResults appendString:string];
NSLog(@"\n\nsoapResults: %@", soapResults);
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:matchingElement]) {
returnedString = soapResults; // Save the element we found
elementFound = NO;
}
}
@end
I manage to send and get back the correct xml but it's actually doesn't start the parsing.
Any idea how can I solve it?
A: You are initiating an asynchronous NSURLConnection and then immediately starting the parsing process. You need to defer the initiation of the parsing until connectionDidFinishLoading, or you should do a synchronous NSURLConnection (but obviously, not from the main queue). Thus, while you're eventually getting a response, the parsing is undoubtedly initiated before the response has been received.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16735013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Best way to transfer struct from one process to another? I have one server process and some clients, the clients need to send to the server as many structures as possible, they will not wait for any answer, just send and send. In which way i can transfer next struct in that case:
typedef struct tagTDATA {
BYTE c1;
DWORD dw1;
DWORD dw2;
char ch[255];
} TDATA, *PTDATA;
Cant use Boost. The best way its Win API. And i don't need code solution just point me in right direction. Thanks.
A: In my understanding you can solve this issue by implementing a shared queue. The pattern of your problem is more towards Producer Consumer Problem
You can also take these examples
*
*http://msdn.microsoft.com/en-us/library/dd728068.aspx
*How should i write producer /consumer code in C#?
A: Are the server and clients on different hosts? If so, why don't you take UDP and to methods to serialize your structure to send via network and the second one to get it back to structure? ...
A: WM_COPYDATA is specifically meant for transferring structs between processes. Check it out.
You mentioned pointers though - and no, you cannot expect pointers to work between processes. If you have variable-length arrays or pointers, it's probably necessary to serialize the data, for example with BSON or XML.
A: It sounds like you are looking for an asynchronous IPC mechanism. Sockets are probably the easiest way to achieve this. Pipes would be another obvious alternative, and there are many higher level libraries available, but I think sockets sound like the best fit.
A: ReadProcessMemory and WriteProcessMemory ought to be able to do the trick for you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7106714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Accordion animation in ui-bootstrap is different from the original bootstrap (size of the accordion is increased, visually it "jumps") The default animation in bootstrap does not change the size of the full accordion in the process. For some reason in the ui-bootstrap that is not the case and while it animates it does a strange increase in size which looks like it "jumps" (easy to notice if you look at the bottom of control). I think that the original behaviour is way more pleasant to the eye as the ui-bootstrap may even change the scrollbar size while it's animating.
Why is it doing it differently and is there an easy way to fix it? E.g. by changing the template.
A: The accordion-group template uses the uib-collapse directive to open/close the panels, see here Removing the uib-collapse directive will bypass some of the unexpected behavior you are seeing, but I think you will need to manage closing/opening the panels.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36721480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to prevent reordering of loads after stores using the C++11 atomics API? I know that you can use the C++11 atomics API in a producer-consumer context to make sure that a consumer sees the "done writing" flag only after some produced record has been completely written out, i.e.
producer:
data[write_index] = <something>
status[write_index].store(READABLE, std::memory_order_release)
consumer:
if (status[read_index].load(std::memory_order_acquire) == READABLE)
//do something with data[read_index]
My question is what happens next - how does the consumer safely tell the producer that it has finished reading from data[read_index], so that the producer can write to data[read_index] for some other purpose?
On x86, I can do (I think?)
consumer:
//do something with data[read_index] //LINE A
asm volatile("" : : : "memory"); //compiler barrier
status[read_index].store(AVAILABLE, std::memory_order_relaxed) //LINE B
and
producer:
if (status[write_index].load(std::memory_order_relaxed) == AVAILABLE)
//write_index is available for writing
My impression is that on an architecture where loads can be reordered after stores, the writer could observe LINE B before LINE A has finished, which would cause a problem.
Is there a way to do this using the C++11 atomics API? The atomic_thread_fence instructions seemed promising but after reading the documentation I don't see that it gives the guarantee I need here.
Thanks!
A: Always use sequential consistency if in doubt :)
memory_order_seq_cst
The operation is ordered in a sequentially consistent manner: All operations using this memory order are ordered to happen once all accesses to memory that may have visible side effects on the other threads involved have already happened.
This is the strictest memory order, guaranteeing the least unexpected side effects between thread interactions though the non-atomic memory accesses.
It applies either to the consumer's store which sends the signal back to the producer or the std::atomic_thread_fence before it.
void producer() {
for(;;) {
data[write_index] = <something>;
status[write_index].store(READABLE, std::memory_order_release);
// do something else while consumer reads it
// producer knows for sure that reader will consume it and signal back
while( status[write_index].load(std::memory_order_acquire) != WRITEABLE)
_mm_pause(); // or at least std::this_thread::yield();
}
}
void consumer() {
while (status[read_index].load(std::memory_order_acquire) != READABLE)
_mm_pause(); // or at least std::this_thread::yield();
//do something with data[read_index]
// signal back and prevent loads from reorder below
status[read_index].store(WRITEABLE, std::memory_order_seq_cst);
}
I'm afraid that this will result in excessive synchronization on x86.. but until someone else comes up with more tricky (but still portable C++11) approach, consider this as the price of portability.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27139261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Getting "TypeError: cannot pickle '_thread.RLock' object" when using Broadcast Variable in Spark Cluster The Spark Cluster has one Master and four Slaves. I have a small table in the database, so I read the table in Master node and set it as a Broadcast variable like this:
def checkTableExists(tablename, connection):
try:
query = 'SELECT * FROM {0}'.format(str(tablename))
print(query)
connection.cursor.execute(query)
return True
except odb.DatabaseError as e:
x = e.args[0]
if x.code == 942: ## Only catch ORA-00942: table or view does not exist error
return False
else:
raise e
def read_cheque_paper(spark, connection):
if create_tables.checkTableExists(small_table, connection) == True:
query_cheque = '''select * from {}'''.format(small_table)
df = connection.read_sql(query_cheque)
broadcastStates = spark.sparkContext.broadcast(df)
else:
df = spark.createDataFrame([], StructType([]))
broadcastStates = spark.sparkContext.broadcast(df)
return broadcastStates
def trx_features(dataframe, broadcast_df):
df_small = broadcast_df.value
if df_small.empty:
df = df.withColumn('field_check', lit(None).cast(StringType()))
else:
df = calculate_field_check(dataframe, df_small)
df.select('field_check').where('field_check==1').show()
return df
def distribute_data(spark):
connection = cx_Oracle.connect(
config.username,
config.password,
config.dsn,
encoding=config.encoding)
if gf.flag_trx:
source_table_name, table_name = gf.create_query('trx')
broadcast_df = read_cheque_paper(spark, connection)
predicates = list_predicates(connection, source_table_name, date_field)
dataframe = gf.read_spark(spark, table_name, predicates, connection)
df_trx = trx_features(dataframe, broadcast_df)
write_spark(dist_table_name_trx, df_trx)
return
if __name__ == '__main__':
master = "spark://IP master:7077"
conf = SparkConf() \
.setAppName('ETL') \
.setMaster(master) \
.set("spark.jars", "ojdbc8.jar")
sc = SparkContext.getOrCreate(conf=conf)
sqlContext = SQLContext(sc)
spark = sqlContext.sparkSession
spark.sparkContext.setLogLevel('ERROR')
start_time = datetime.datetime.now().timestamp()
distribute_data(spark)
end_time = datetime.datetime.now().timestamp()
duration = end_time - start_time
When this program run in local mode,I get the result without any errors. But, while I run that in the cluster,when it reach to the df_small = broadcast_df.value it was stopped with this error:
TypeError: cannot pickle '_thread.RLock' object
Would you please guide me what is wrong with defining the broadcast varible?
Any help is really appreciated .
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73080447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to draw perfect straight line passing through majority of given points in MATLAB? Can someone help me figure out how to draw a perfect straight line from given set of points passing through majority (may be 5-6 point out of 20) of these points? Please note that this is not a line fit problem, but perfect line should be drawn (horizontal, vertical or somewhat slanted) between majority of the given points.
Here is MATLAB code:
e=[161 162 193 195 155 40 106 102 125 155 189 192 186 188 185 186 147 148 180 183];
f =[138 92 92 115 258 124 218 114 125 232 431 252 539 463 643 571 582 726 726 676];
figure;scatter(f, e, 5, 'red');
axis ij;
and here is image:
A: Since you want the line to go through the majority of points, it sounds quite like a line fitting problem even though you say it isn't. Have you looked at the Theil-Sen estimator (for example this one on fex), which is a linear regression ignoring up to some 30% of the outliers.
If you simply want a line through the extrema you might do something like this:
% Setup data
e = [161 162 193 195 155 40 106 102 125 155 189 192 186 188 185 186 147 148 180 183];
f = [138 92 92 115 258 124 218 114 125 232 431 252 539 463 643 571 582 726 726 676];
% Create scatterplot
figure(1);
scatter(f, e, 5, 'red');
axis ij;
% Fit extrema
[min_e, min_idx_e] = min(e);
[max_e, max_idx_e] = max(e);
[min_f, min_idx_f] = min(f);
[max_f, max_idx_f] = max(f);
% Determine largest range and draw line accordingly
if (max_e-min_e)>(max_f-min_f)
line(f([min_idx_e, max_idx_e]), e([min_idx_e, max_idx_e]), 'color', 'blue')
text(f(max_idx_e), e(max_idx_e), ' Extrema')
else
line(f([min_idx_f, max_idx_f]), e([min_idx_f, max_idx_f]), 'color', 'blue')
text(f(max_idx_f), e(max_idx_f), ' Extrema')
end
% Fit using Theil-Sen estimator
[m, e0] = Theil_Sen_Regress(f', e');
line([min_f, max_f], m*[min_f, max_f]+e0, 'color', 'black')
text(max_f, m*max_f+e0, ' Theil-Sen')
However, as you'll notice neither solution automatically fits the points automatically, simply because there are too many outliers, unless you filter those beforehand. Therefore you probably are better off using the RANSAC algorithm as proposed by Shai and McMa.
A: That's a textbook example for the RANSAC algorithm. This free toolbox for Matlab actually has some very nice examples of line fitting.
A: An easy but not very efficient solution would be to compute slope between each two points and if a set of points lie on a straight line, all pairs of these set would have the same slope. So one algorithm could pick all the poirs with same slope and connect them if they have one point in common. finally you have to choose the largest set. The time complexity of this algorithm will be O(N^2 log N) which N is number of points.
As I see in your figure there is not a real perfect line going through all the points, rather there is a tolerance which in this algorithm could be defined as the criteria by which you connect two pairs. say if two slopes are different by less than 2 percent we connect the pairs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27775682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Unexpected binding behaviour I have select list i set default option to be chosen. what happen is for few second it works then it disappear and the blank option in the list is chosen as default.
<div class="form-group">
<select class="form-control" ng-model="item.action" ng-options="option.value as option.title for option in options">
</select>
</div>
i want to set defualt option to be chosen :
so my controller look like this:
$scope.item = {};
$scope.options = [{
title: 'On entering',
value: 'enter'
}, {
title: 'On exiting',
value: 'exit'
}];
$scope.item.action= $scope.options[0].value;
$scope.profile = me.getUser();
$scope.profile.then(
function(user) {
$scope.owner = user;
$scope.item = {};
$scope.item.data = '';
$scope.item.published = true;
$scope.item.action= $scope.action;
$scope.item.owner = $scope.owner.displayName;
},
function(response) {
console.log(response);
}
);
me is a service that fecth the user data.
the reason why am defining $scope.item = {}; again is because i can't apend the displayName to the $scope.item out of the scope.
I commented this part of the code and it works well:
$scope.profile = me.getUser();
$scope.profile.then(
function(user) {
$scope.owner = user;
$scope.item = {};
$scope.item.data = '';
$scope.item.published = true;
$scope.item.action= $scope.action;
$scope.item.owner = $scope.owner.displayName;
},
function(response) {
console.log(response);
}
);
But now i can't figure out how to build my item object to send it in HTTP request
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30108289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Simplify PHP for SQL data retrevial I'm new to PHP and SQL queries but trying to learn. Anyway, I have the following code which I'm sure there will be a simpler way of doing (hopefully as I intend to do the same for day of year not just month).
My current code is;
//Get jan power consumption
$janquery = mysql_query("SELECT SUM(kw*tdsecs) FROM data WHERE year(time) = year(CURDATE()) AND month(time) = 1");
$janresult = mysql_fetch_array($janquery);
$jankwm = $janresult[0] / 60;
$jankwh = round($jankwm / 60,2);
//Get feb power consumption
$febquery = mysql_query("SELECT SUM(kw*tdsecs) FROM data WHERE year(time) = year(CURDATE()) AND month(time) = 2");
$febresult = mysql_fetch_array($febquery);
$febkwm = $febresult[0] / 60;
$febkwh = round($febkwm / 60,2);
and so on then...
$values=array(
"Jan" => $jankwh,
"Feb" => $febkwh,
"Mar" => $markwh,
"Apr" => $aprkwh,
"May" => $maykwh,
"Jun" => $junkwh,
"Jul" => $julkwh,
"Aug" => $augkwh,
"Sep" => $sepkwh,
"Oct" => $octkwh,
"Nov" => $novkwh,
"Dec" => $deckwh
);
I want to avoid having 12 queries so any help would be appreciated.
A: SELECT
month(time) as `month`,
SUM(kw*tdsecs) as `sum`
FROM data
WHERE year(time) = year(CURDATE())
group by month(time)
order by month(time)
A: SELECT month(time), SUM(kw*tdsecs) FROM data
WHERE year(time) = year(CURDATE()) group by month(time);
A: mysql_query("SELECT month(time),SUM(kw*tdsecs) FROM data WHERE
year(time) = year(CURDATE()) AND month(time) in
(1,2,3,4,5,6,7,8,9,10,11,12) group by month(time)")
A: A simple solution (not the best) would be to loop through the months and store the results in a array:
for($month=1; $month<=12; $month++) {
$query = mysql_query(
"SELECT SUM(kw*tdsecs) FROM data
WHERE year(time) = year(CURDATE()) AND month(time) = $month");
$result = mysql_fetch_array($query);
$kwm[$month] = $result[0] / 60;
$kwh[$month] = round($kwm[$month] / 60,2);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12626670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to convert Object to List in c#? I have a List<string> in Model.
When I write a html helper, I can get the data from metadata.Model, which is an object
// this is from MVC3 (namespace System.Web.Mvc -> ModelMetadata), I did not write this
// Summary:
// Gets the value of the model.
//
// Returns:
// The value of the model. For more information about System.Web.Mvc.ModelMetadata,
// see the entry ASP.NET MVC 2 Templates, Part 2: ModelMetadata on Brad Wilson's
// blog
public object Model { get; set; }
My question is: how to get List<string> from an Object?
A: If the underlying type of the object variable is List<string>, a simple cast will do:
// throws exception if Model is not of type List<string>
List<string> myModel = (List<string>)Model;
or
// return null if Model is not of type List<string>
List<string> myModel = Model as List<string>;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9043773",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: How can I tell if a file has changed through .NET? I am looking for a way to determine when a particular file has changed, through .NET. (What I ultimately want is functionality that makes a copy of the file as soon as it has changed.) How can this be done?
A: class Program
{
static void Main(string[] args)
{
FileSystemWatcher fsw = new FileSystemWatcher(@"c:\temp");
fsw.Changed += new FileSystemEventHandler(fsw_Changed);
fsw.Deleted += new FileSystemEventHandler(fsw_Deleted);
fsw.Renamed += new RenamedEventHandler(fsw_Renamed);
fsw.Created += new FileSystemEventHandler(fsw_Created);
fsw.EnableRaisingEvents = true;
Console.ReadLine();
}
static void fsw_Created(object sender, FileSystemEventArgs e)
{
Console.WriteLine("{0} was created", e.FullPath);
}
static void fsw_Renamed(object sender, RenamedEventArgs e)
{
Console.WriteLine("{0} was Renamed", e.FullPath);
}
static void fsw_Deleted(object sender, FileSystemEventArgs e)
{
Console.WriteLine("{0} was Deleted", e.FullPath);
}
static void fsw_Changed(object sender, FileSystemEventArgs e)
{
Console.WriteLine("{0} was Changed", e.FullPath);
}
}
A: Microsoft Windows, and its ultimate ancestor MS-DOS, has always had an attribute on its files that indicates whether that file was changed since the last time that attribute was cleared, sort of a "dirty flag". It was used in the past by backup programs to find those files that needed to be backed up incrementally, and then cleared when a copy of that file had been made.
You can use File.GetAttributes to get the attributes on a file, and use File.SetAttributes to clear that "Archive" attribute. The next time that file is opened for writing, that archive flag will be set again.
Be careful about copying files that have been changed, as those files may still be open. You probably want to avoid concurrency problems by opening them for read exclusively when copying, and if that fails you know that file is still open for writing.
A: To all who responded with, use FileSystemWatcher, how do you deal with the time your app isn't running? For example, the user has rebooted the box, modified the file you are interested in, and then starts up your app?
Be sure to also read the docs on FileSystemWatcher Class carefully specially the section about Events and Buffer Sizes.
A: You can use a FileSystemWatcher object. This raises events on changes to files within the specified watched folder.
A: You're likely to run into issues with FileSystemWatcher (not getting events, too many events, etc.) This code wraps it up and solves many of them:
http://precisionsoftware.blogspot.com/2009/05/filesystemwatcher-done-right.html
A: You will have to note the modified date of files which you want to check.
After certain period you can check if the file was modified later.
If the file is modified with different date and time, you can make the copy.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/479114",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Linux: how to check the largest contiguous address range available to a process I want to enter the pid at the command line and get back the largest contiguous address space that has not been reserved. Any ideas?
Our 32 bit app, running on 64 bit RHEL 5.4, craps out after running for a while, say 24 hours. At that time it is only up to 2.5 gb of memory use, but we get out of memory errors. We think it failing to mmap large files because the app's memory space is fragmented. I wanted to go out to the production servers and just test that theory.
A: Slighly nicer version of my above comment:
#!perl -T
use warnings;
use strict;
scalar(@ARGV) > 0 or die "Use: $0 <pid>";
my $pid = $ARGV[0];
$pid = oct($pid) if $pid=~/^0/; # support hex and octal PIDs
$pid += 0; $pid = abs(int($pid)); # make sure we have a number
open(my $maps, "<", "/proc/".$pid."/maps") or
die "can't open maps file for pid ".$pid;
my $max = 0;
my $end = 0;
while (<$maps>) {
/([0-9a-f]+)-([0-9a-f]+)/;
$max = hex ($1) - $end if $max < hex ($1) - $end;
$end = hex ($2);
}
close ($maps);
END {
print "$max\n";
}
A: Probably not exactly what you want, but from inside a process it is possible to do binary search by mmaping without allocating. I.e. mmap(4GB), if that fails mmap(2GB), if that succeeds mmap(3GB), and so on.
A:
we get out of memory errors. We think it failing to mmap large files because the app's memory space is fragmented.
However, one can also get OOM errors while still having lots of free virtual address ranges on paper, for example by sufficient lack of RAM+swap. Furthermore your system and/or program(s) may have overcomitting turned off (sysctl -a), or have swapping inhibited (mlock(2)), or you actually have a very blunt limit on mappings (ulimit -v) — the latter is easy to run in given some distributions set such ulimits one way or another.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9403146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: REDIS-Python -> get all keys and respective values from 1 database I am trying to get all keys and values from a REDIS db. There are about 35000+ open connections on REDIS by the other users. I am using r.scan_iter()to get all the keys and I am appending them to a list. I am currently using pipeline.execute() to get all the values for these list of keys. Is this necessary to get the values for keys from redis? Or is there some way to access values of keys from r.scan_iter() loop.
Key = a|b|c
Value = V1:X1 V2:X2 V3:X3
My code is as below:
r = redis.Redis(host,port,db)
#To get all the keys and then use pipeline to get corresponding values
for key in r.scan_iter():
pipe.hgetall(key.decode('utf-8'))
values = pipe.execute()
#To loop through the values and read
for value in values:
# Get all the values for each key
for name, value in value.items():
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46677903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Facebook and Whatsapp sharing buttons I have an PHP page showing an image to the user, and I want them to share via Facebook or WhatsApp,
Here the code for the head part:
<meta name="description" content="<?php echo $Rowdati['metadescrizione'];?>">
<meta name="keywords" content="<?php echo $Rowdati['keywordsapp'];?>">
<meta property="og:image" content="<?php echo $urlimmagineuser; ?>">
<meta property="og:image:type" content="image/png">
<meta property="og:image:width" content="400">
<meta property="og:image:height" content="400">
<meta property="og:title" content="<?php echo $Rowdati['titolo_fb_share'];?>">
<meta property="og:description " content="<?php echo $Rowdati['descr_fb_share'];?>">
Here the code for getting the image to share and display on the web page:
<?php echo "<a href='". $url ."' download='image-ready'>
<img id='immaginelaborata' class='img-responsive' src='". $url ."' />
</a>";
?>
Here the share buttons:
<div class="col-sm-4" data-href="<?php echo $actual_link;?>" data-layout="button" data-size="large" data-mobile-iframe="true">
<button class="btn col-xs-12 scroll_effect shadow-top-down">
<a class="fb-xfbml-parse-ignore" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=<?php echo $actual_link;?>;src=sdkpreparse">
<i class="fa fa-facebook-square" aria-hidden="true"></i><br>share on FB</a>
</button>
</div>
<div class="col-sm-4">
<button class="btn col-xs-12 scroll_effect shadow-top-down">
<?php
$actual_link = (isset($_SERVER['HTTPS']) ? "https" : "http") .
"://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
?>
<a href="whatsapp://send?text=<?php echo $Rowdati['testo_whatsapp'] . "http://mydomain.it";?>" data-action="share/whatsapp/share">
<i class="fa fa-whatsapp" aria-hidden="true" ></i><br>share on Whatsapp<br>
</a>
</button>
</div>
The page works fine, except that when i share it on Facebook or WhatsApp it does not return the image preview...
I cannot figure out why after checking and rechecking the code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46861633",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Making a V-shaped pattern with Python I wanna make pattern by algorithm.
Result is the pattern like
..........
..........
..........
..........
..........
..........
.########.
.########.
##########
##########
But my ideal pattern is
##......##
##......##
.##....##.
.##....##.
..##..##..
..##..##..
...####...
...####...
....##....
....##....
So,I cannot understand why I cannot do it in my code.
By comparing current pattern & ideal one,I think data cannot use correctly. But I cannot know how to fix this. What should I do to do it?
A: A different approach:
final = []
for i in range(10):
temp = ["." for j in range(10)]
temp[int(i / 2)] = "#"
temp[int(i / 2) + 1] = "#"
temp[-int(i / 2) - 1] = "#"
temp[-int(i / 2) -2] = "#"
final.append(temp)
for a in final:
print("".join(a))
Will print:
##......##
##......##
.##....##.
.##....##.
..##..##..
..##..##..
...####...
...####...
....##....
....##....
This can be made even cleaner, but here you can see all the different steps, so I hope it helps
A: # 10x10
# first # start position second # start position from last
# LN 0 1: 0 -1
# LN 2 3: 1 -2
# LN 2k 2k+1: k -k-1
# LN 8 9: 4 -5
# dw: dot '.' width
# sw: sharp '#' width
# if k == 0 part is ugly, for list slicing
def draw(dw, sw):
for k in range(dw//2):
row = [ '.' for _ in range(dw) ]
row[k:k+sw] = '#' * sw
if k == 0:
row[-sw:] = '#' * sw
else:
row[-k-sw:-k] = '#' * sw
print("".join(row))
print("".join(row))
draw(10, 2)
with draw(20, 2) got
##................##
##................##
.##..............##.
.##..............##.
..##............##..
..##............##..
...##..........##...
...##..........##...
....##........##....
....##........##....
.....##......##.....
.....##......##.....
......##....##......
......##....##......
.......##..##.......
.......##..##.......
........####........
........####........
.........##.........
.........##.........
A: I would use itertools' product, and filter the indices that aren't relevant
def v(row):
return set([int(row/4), row-int(row/4), int(row/4)+1, row-int(row/4)-1])
from itertools import product
indices = product(range(len(array)),range(len(array[0])))
indices = filter(lambda i: i[1] in v(i[0]), indicies)
for r,c in indices:
array[r][c] = "#"
A: Don't know what you're trying to accomplish here, but I can do it, too:
a = "##..."
for i in range(10):
b = ("."*int(i/2) + a)[:5]
print(b + b[::-1])
A: Slightly more concise:
width = 10
for i in range(width):
line = ['.'] * width
m = i//2
line[m] = line[m+1] = line[-m-1] = line[-m-2] = "#"
print(''.join(line))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45183784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Do custom networks replace default network in docker-compose.yml Does specifying custom networks in docker-compose remove services from the default network? I can't find any information about this.
example
version: '3'
services:
nginx:
image: 'nginx:alpine'
restart: always
networks:
- web
- internal_network
labels:
- "traefik.docker.network=traefik"
- "traefik.backend=blog"
- "traefik.frontend.rule=Host:test.ondrovo.com"
- "traefik.port=80"
- "traefik.frontend.passHostHeader=true"
- "traefik.protocol=http"
volumes:
- ./www:/srv/www
- ./config/nginx.conf:/etc/nginx/nginx.conf
- ./config/conf.d:/etc/nginx/conf.d
php:
image: php:7-fpm
volumes:
- ./www:/srv/www
networks:
- internal_network
networks:
web:
external:
name: traefik
internal_network:
internal: true
in this case, is internal_network needed or can i just leave it out?
A: The answer is yes, the default network is removed if you specify them manually.
I went ahead and tried it.
You can specify 'default' in the networks list, however, and it apparently does not need to be declared in the top-level list.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50824072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to create filterable and sortable div elements I am using rails 3 and ruby 1.9 to develop a ecommerce app. I currently have a loop pulling product info from the database into a div for each product to populate the storefront.
Problem is I have been been trying without any luck to figure out how to make the products sortable and filterable. Basically i want potential customers to be able to filter and/or sort the products listing by some of the data associated with the products (e.g., sort by date added or filter by manufacturer).
So far i've come across some templates using jquery to accomplish this, but i haven't been able to find anything leveraging the rails framework. Ive included the code below. any assistance would be much appreciated.
<div class="store-header1"><h2>Today's</h2> </div><div class="store-header2"><h2>Offers</h2></div>
<% @products.each do |product| %>
<div class="Primary">
<div class="dots">
<div id="offer-title"> <%= product.title %> </div>
<%= image_tag(product.image_url, :alt =>product.title, :class=>"product-image")%>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17776309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Parse data from php to jsquery.flot.pie I've seen some questions about this already but I still couldn't clear the fog around this...
I have this sql statement to get data:
<script type="text/javascript">
<?php
$query = "SELECT rel_id, SUM(suma) FROM $tbl_rel_balansas INNER JOIN $tbl_balansas ON $tbl_rel_balansas.rel_id = $tbl_balansas.id WHERE $tbl_rel_balansas.member_id = '$_SESSION[id]'";
$result = mysql_query ($query);
while($row = mysql_fetch_array($result)){
echo 'var some_data = ' . json_encode( $viso );
}
?>
Next is the js part:
$(function () {
$.plot($("#placeholder"), [some_data],
{
series: {
pie: {
show: true
}
},
legend: {
show: false
}
});
});
</script>
I was thinking I could reach the data in some_data and use it to display it in the pie chart, unfortunately this is not the way to go.
Any help and suggestions are greatly appriciated ! :)
A: The most likely problem is that your numeric data is being interpreted as a string.
From the API.txt:
Note that to simplify the internal
logic in Flot both the x and y values
must be numbers (even if specifying
time series, see below for how to do
this). This is a common problem
because you might retrieve data from
the database and serialize them
directly to JSON without noticing the
wrong type. If you're getting
mysterious errors, double check that
you're inputting numbers and not
strings.
So either force your data to numeric types on the PHP side, or do it in javascript, perhaps with .Number(some_data)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5572911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: dotnet restore: An error occurred while retrieving package... metadata Root element is missing I have a nuget/docker build issue that I’ve spent a couple of days debugging and am running out of ideas: Do you know why I am getting the below error?
The issue is with one asp.net core solution (others that are very similar are unaffected): Although I can build the affected solution in visual studio 2019 using the docker compose file, it will not work using the dockerfile and so the docker build command can’t be run.
If I run the dockerfile by doing a build as below in command prompt:
docker build -f MStoreBosGateway/MStoreBosGatewayApi/Dockerfile --pull --no-cache -t mstorebosgateway:0.041 .
then I get the following error:
Step 11/26 : RUN dotnet restore "MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj"
> ---> Running in 30819cb5db4f
> /usr/share/dotnet/sdk/2.2.402/NuGet.targets(123,5): error : An error
> occurred while retrieving package metadata for
> 'System.Text.Encodings.Web.4.5.0' from source
> '/usr/share/dotnet/sdk/NuGetFallbackFolder'.
> [/src/MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj]
> /usr/share/dotnet/sdk/2.2.402/NuGet.targets(123,5): error : Root
> element is missing.
> [/src/MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj]
> The command '/bin/sh -c dotnet restore
> "MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj"'
> returned a non-zero code: 1
I’ve put RUN echo commands after each line in the dockerfile so it looks like it is the dotnet restore that is causing this issue. If I run the dotnet restore command by itself it runs ok.
To try to resolve this I’ve done quite a few things e.g.
*
*-Deleted the obj and bin folders from this solution and projects,
*-Uninstalled and reinstalled nuget,
*-Deleted the nuget caches to force the packages to be redownloaded,
*-uninstalled and reinstalled the dotnet core sdks,
*-Removed the package mentioned in the error message ('System.Text.Encodings.Web.4.5.0) from the project file (this did
not cause any errors so must have been redundant anyway). That did
not affect this error and it restores this package so there must be
something else saying to use this package or possibly system packages
are all included by default anyway.
My colleague can build this project and has sent me a copy of it that he can build; I get the same issue building his copy so assume it’s something external to the project.
I have added below the output if I add ‘ –verbosity detailed’ to the dotnet restore command in the docker file.
GET https://api.nuget.org/v3-flatcontainer/microsoft.extensions.dependencyinjection.abstractions/index.json
OK https://api.nuget.org/v3-flatcontainer/aspnet.security.oauth.validation/index.json 342ms
GET https://api.nuget.org/v3-flatcontainer/aspnet.security.oauth.validation/2.0.0/aspnet.security.oauth.validation.2.0.0.nupkg
OK https://api.nuget.org/v3-flatcontainer/aspnet.security.oauth.validation/2.0.0/aspnet.security.oauth.validation.2.0.0.nupkg 52ms
GET https://api.nuget.org/v3-flatcontainer/microsoft.aspnetcore.authentication/index.json
GET https://api.nuget.org/v3-flatcontainer/newtonsoft.json/10.0.2/newtonsoft.json.10.0.2.nupkg
1>/usr/share/dotnet/sdk/2.2.402/NuGet.targets(123,5): error : An error occurred while retrieving package metadata for 'System.Text.Encodings.Web.4.5.0' from source '/usr/share/dotnet/sdk/NuGetFallbackFolder'. [/src/MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj]
/usr/share/dotnet/sdk/2.2.402/NuGet.targets(123,5): error : Root element is missing. [/src/MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj]
OK https://api.nuget.org/v3-flatcontainer/swashbuckle.aspnetcore.swaggergen/index.json 156ms
GET https://api.nuget.org/v3-flatcontainer/swashbuckle.aspnetcore.swaggergen/4.0.1/swashbuckle.aspnetcore.swaggergen.4.0.1.nupkg
OK https://api.nuget.org/v3-flatcontainer/swashbuckle.aspnetcore.swaggerui/index.json 160ms
GET https://api.nuget.org/v3-flatcontainer/swashbuckle.aspnetcore.swaggerui/4.0.1/swashbuckle.aspnetcore.swaggerui.4.0.1.nupkg
OK https://api.nuget.org/v3-flatcontainer/automapper/index.json 155ms
GET https://api.nuget.org/v3-flatcontainer/automapper/8.0.0/automapper.8.0.0.nupkg
OK https://api.nuget.org/v3-flatcontainer/swashbuckle.aspnetcore.swaggergen/4.0.1/swashbuckle.aspnetcore.swaggergen.4.0.1.nupkg 44ms
OK https://api.nuget.org/v3-flatcontainer/swashbuckle.aspnetcore.swaggerui/4.0.1/swashbuckle.aspnetcore.swaggerui.4.0.1.nupkg 49ms
GET https://api.nuget.org/v3-flatcontainer/microsoft.aspnetcore.mvc.apiexplorer/index.json
GET https://api.nuget.org/v3-flatcontainer/microsoft.aspnetcore.mvc.core/index.json
GET https://api.nuget.org/v3-flatcontainer/microsoft.aspnetcore.mvc.dataannotations/index.json
NuGet.Protocol.Core.Types.FatalProtocolException: An error occurred while retrieving package metadata for 'System.Text.Encodings.Web.4.5.0' from source '/usr/share/dotnet/sdk/NuGetFallbackFolder'. ---> NuGet.Packaging.Core.PackagingException: An error occurred while retrieving package metadata for 'System.Text.Encodings.Web.4.5.0' from source '/usr/share/dotnet/sdk/NuGetFallbackFolder'. ---> System.Xml.XmlException: Root element is missing.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.Linq.XDocument.Load(XmlReader reader, LoadOptions options)
at NuGet.Packaging.Core.NuspecCoreReaderBase.LoadXml(Stream stream, Boolean leaveStreamOpen)
at NuGet.Packaging.Core.NuspecCoreReaderBase..ctor(Stream stream, Boolean leaveStreamOpen)
at NuGet.Packaging.NuspecReader..ctor(Stream stream)
at NuGet.Protocol.LocalPackageFileCache.GetNuspec(String manifestPath, String expandedPath)
at NuGet.Protocol.LocalPackageFileCache.<>c__DisplayClass6_1.<GetOrAddNuspec>b__1()
at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
at System.Lazy`1.CreateValue()
at NuGet.Protocol.LocalV3FindPackageByIdResource.ProcessNuspecReader[T](String id, NuGetVersion version, Func`2 process)
--- End of inner exception stack trace ---
--- End of inner exception stack trace ---
at NuGet.Protocol.LocalV3FindPackageByIdResource.ProcessNuspecReader[T](String id, NuGetVersion version, Func`2 process)
at NuGet.Protocol.LocalV3FindPackageByIdResource.GetDependencyInfoAsync(String id, NuGetVersion version, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken)
at NuGet.Commands.SourceRepositoryDependencyProvider.GetDependenciesCoreAsync(LibraryIdentity match, NuGetFramework targetFramework, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken)
at NuGet.Commands.SourceRepositoryDependencyProvider.<>c__DisplayClass21_0.<<GetDependenciesAsync>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at NuGet.Commands.SourceRepositoryDependencyProvider.GetDependenciesAsync(LibraryIdentity libraryIdentity, NuGetFramework targetFramework, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken)
at NuGet.DependencyResolver.ResolverUtility.CreateGraphItemAsync(RemoteMatch match, NuGetFramework framework, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken)
at NuGet.DependencyResolver.ResolverUtility.FindLibraryEntryAsync(LibraryRange libraryRange, NuGetFramework framework, String runtimeIdentifier, RemoteWalkContext context, CancellationToken cancellationToken)
at NuGet.DependencyResolver.RemoteDependencyWalker.CreateGraphNode(LibraryRange libraryRange, NuGetFramework framework, String runtimeName, RuntimeGraph runtimeGraph, Func`2 predicate, GraphEdge`1 outerEdge)
at NuGet.DependencyResolver.RemoteDependencyWalker.CreateGraphNode(LibraryRange libraryRange, NuGetFramework framework, String runtimeName, RuntimeGraph runtimeGraph, Func`2 predicate, GraphEdge`1 outerEdge)
at NuGet.DependencyResolver.RemoteDependencyWalker.CreateGraphNode(LibraryRange libraryRange, NuGetFramework framework, String runtimeName, RuntimeGraph runtimeGraph, Func`2 predicate, GraphEdge`1 outerEdge)
at NuGet.DependencyResolver.RemoteDependencyWalker.CreateGraphNode(LibraryRange libraryRange, NuGetFramework framework, String runtimeName, RuntimeGraph runtimeGraph, Func`2 predicate, GraphEdge`1 outerEdge)
at NuGet.DependencyResolver.RemoteDependencyWalker.CreateGraphNode(LibraryRange libraryRange, NuGetFramework framework, String runtimeName, RuntimeGraph runtimeGraph, Func`2 predicate, GraphEdge`1 outerEdge)
at NuGet.DependencyResolver.RemoteDependencyWalker.CreateGraphNode(LibraryRange libraryRange, NuGetFramework framework, String runtimeName, RuntimeGraph runtimeGraph, Func`2 predicate, GraphEdge`1 outerEdge)
at NuGet.DependencyResolver.RemoteDependencyWalker.CreateGraphNode(LibraryRange libraryRange, NuGetFramework framework, String runtimeName, RuntimeGraph runtimeGraph, Func`2 predicate, GraphEdge`1 outerEdge)
at NuGet.Commands.ProjectRestoreCommand.WalkDependenciesAsync(LibraryRange projectRange, NuGetFramework framework, String runtimeIdentifier, RuntimeGraph runtimeGraph, RemoteDependencyWalker walker, RemoteWalkContext context, CancellationToken token)
at NuGet.Commands.ProjectRestoreCommand.TryRestoreAsync(LibraryRange projectRange, IEnumerable`1 frameworkRuntimePairs, NuGetv3LocalRepository userPackageFolder, IReadOnlyList`1 fallbackPackageFolders, RemoteDependencyWalker remoteWalker, RemoteWalkContext context, Boolean forceRuntimeGraphCreation, CancellationToken token, TelemetryActivity telemetryActivity)
at NuGet.Commands.RestoreCommand.ExecuteRestoreAsync(NuGetv3LocalRepository userPackageFolder, IReadOnlyList`1 fallbackPackageFolders, RemoteWalkContext context, CancellationToken token, TelemetryActivity telemetryActivity)
at NuGet.Commands.RestoreCommand.ExecuteAsync(CancellationToken token)
at NuGet.Commands.RestoreRunner.ExecuteAsync(RestoreSummaryRequest summaryRequest, CancellationToken token)
at NuGet.Commands.RestoreRunner.ExecuteAndCommitAsync(RestoreSummaryRequest summaryRequest, CancellationToken token)
at NuGet.Commands.RestoreRunner.CompleteTaskAsync(List`1 restoreTasks)
at NuGet.Commands.RestoreRunner.RunAsync(IEnumerable`1 restoreRequests, RestoreArgs restoreContext, CancellationToken token)
at NuGet.Commands.RestoreRunner.RunAsync(RestoreArgs restoreContext, CancellationToken token)
at NuGet.Build.Tasks.RestoreTask.ExecuteAsync(ILogger log)
Done executing task "RestoreTask" -- FAILED.
1>Done building target "Restore" in project "MStoreBOSGatewayApi.csproj" -- FAILED.
1>Done Building Project "/src/MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj" (Restore target(s)) -- FAILED.
Build FAILED.
"/src/MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj" (Restore target) (1) ->
(Restore target) ->
/usr/share/dotnet/sdk/2.2.402/NuGet.targets(123,5): error : An error occurred while retrieving package metadata for 'System.Text.Encodings.Web.4.5.0' from source '/usr/share/dotnet/sdk/NuGetFallbackFolder'. [/src/MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj]
/usr/share/dotnet/sdk/2.2.402/NuGet.targets(123,5): error : Root element is missing. [/src/MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj]
0 Warning(s)
1 Error(s)
Time Elapsed 00:00:04.70
The command '/bin/sh -c dotnet restore "MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj" --verbosity detailed' returned a non-zero code: 1
C:\Applications\VB2017Apps\MStoreBOSGateway>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58697460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Find "complete cases" with awk Using awk, how can I output the lines of a file that have all fields non-null without manually specifying each column?
foo.dat
A||B|X
A|A|1|
|1|2|W
A|A|A|B
Should return:
A|A|A|B
In this case we can do:
awk -F"|" -v OFS="|" '$1 != "" && $2 != "" && $3 != "" && $4 != "" { print }' foo.dat
But is there a way to do this without specifying each column?
A: You can loop over all fields and skip the record if any of the fields are empty:
$ awk -F'|' '{ for (i=1; i<=NF; ++i) { if (!$i) next } }1' foo.dat
A|A|A|B
if (!$i) is "if field i is not non-empty", and 1 is short for "print the line", but it is only hit if next was not executed for any of the fields of the current line.
A: Another in awk:
$ awk -F\| 'gsub(/[^|]+(\||$)/,"&")==NF' file
A|A|A|B
print record if there are NF times | terminating (non-empty, |-excluding) strings.
A: awk '!/\|\|/&&!/\|$/&&!/^\|/' file
A|A|A|B
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43378932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Prevent Popup template to shows multiple feature in ArcGIS 4.16 Angular 10 I have integrated a popup on the map for a specific layer. Some time the poup shows pagination (featureNavigation) multiple data. Sometimes it fails to show the data, or mismatch in the data that actually the service returns.
var popupTrailheads = {
title: "ID: {ID}",
content: this.getcustomcontent.bind(this),
};
// Add layer special layer
this.layer_fifteen = new FeatureLayer({
url: `${this.esriURL}/15`,
visible: true,
outFields: ['*'],
popupTemplate: popupTrailheads,
});
getcustomcontent(feature) {
// The popup content will become here from angular service
return `<div>content</div>`;
}
I have a few options to fix the issue.
1)Popup for this layer enables only at a specific Zoom level. Else the popup won't appear.
2)The click on the map should trigger only for a point. (I believe when click on the layer it triggers multiple points that is the reason it shows multiple feature details.)
Can you please suggest an idea, how to enable a popup in specific zoom level, or select only one feature in one click on the map.
Thanks in advance.
A: So, there are a number of possible ways to enable the popup under certain conditions, like the zoom level of the view.
In the example that I made for you popup only opens if zoom is greatest than 10.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no" />
<title>PopupTemplate - Auto Open False</title>
<link rel="stylesheet" href="https://js.arcgis.com/4.15/esri/themes/light/main.css" />
<script src="https://js.arcgis.com/4.15/"></script>
<style>
html,
body,
#viewDiv {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
}
</style>
<script>
var populationChange;
require(["esri/Map", "esri/views/MapView", "esri/layers/Layer"], function (
Map,
MapView,
Layer
) {
var map = new Map({
basemap: "dark-gray"
});
var view = new MapView({
container: "viewDiv",
map: map,
zoom: 7,
center: [-87, 34]
});
var highlightSelect = null;
Layer.fromPortalItem({
portalItem: {
id: "e8f85b4982a24210b9c8aa20ba4e1bf7"
}
}).then(function (layer) {
map.add(layer);
var popupTemplate = {
title: "Population in {NAME}",
outFields: ["*"],
content: [{
type: 'fields',
fieldInfos: [
{
fieldName: "POP2010",
format: {
digitSeparator: true,
places: 0
},
visible: false
},
{
fieldName: "POP10_SQMI",
format: {
digitSeparator: true,
places: 2
}
},
{
fieldName: "POP2013",
format: {
digitSeparator: true,
places: 0
}
},
{
fieldName: "POP13_SQMI",
format: {
digitSeparator: true,
places: 2
}
}
]
}],
};
layer.popupTemplate = popupTemplate;
function populationChange(feature) {
var div = document.createElement("div");
var upArrow =
'<svg width="16" height="16" ><polygon points="14.14 7.07 7.07 0 0 7.07 4.07 7.07 4.07 16 10.07 16 10.07 7.07 14.14 7.07" style="fill:green"/></svg>';
var downArrow =
'<svg width="16" height="16"><polygon points="0 8.93 7.07 16 14.14 8.93 10.07 8.93 10.07 0 4.07 0 4.07 8.93 0 8.93" style="fill:red"/></svg>';
var diff =
feature.graphic.attributes.POP2013 -
feature.graphic.attributes.POP2010;
var pctChange = (diff * 100) / feature.graphic.attributes.POP2010;
var arrow = diff > 0 ? upArrow : downArrow;
div.innerHTML =
"As of 2010, the total population in this area was <b>" +
feature.graphic.attributes.POP2010 +
"</b> and the density was <b>" +
feature.graphic.attributes.POP10_SQMI +
"</b> sq mi. As of 2013, the total population was <b>" +
feature.graphic.attributes.POP2013 +
"</b> and the density was <b>" +
feature.graphic.attributes.POP13_SQMI +
"</b> sq mi. <br/> <br/>" +
"Percent change is " +
arrow +
"<span style='color: " +
(pctChange < 0 ? "red" : "green") +
";'>" +
pctChange.toFixed(3) +
"%</span>";
return div;
}
view.popup.autoOpenEnabled = false; // <- disable view popup auto open
view.on("click", function (event) { // <- listen to view click event
if (event.button === 0) { // <- check that was left button or touch
console.log(view.zoom);
if (view.zoom > 10) { // <- zoom related condition to open popup
view.popup.open({ // <- open popup
location: event.mapPoint, // <- use map point of the click event
fetchFeatures: true // <- fetch the selected features (if any)
});
} else {
window.alert(`Popup display zoom lower than 10 .. Zoom in buddy! .. (Current zoom ${view.zoom})`);
}
}
});
});
});
</script>
</head>
<body>
<div id="viewDiv"></div>
</body>
</html>
Related to only display one result in the popup, you could hide the navigation like this,
view.popup.visibleElements.featureNavigation = false;
Now if what you actually want is to get only one result, then I suggest to use view method hitTest, that only gets the topmost result of the layers. You could do this after inside the click handler and only open if any result of desire layer. For this you need to set featFeatures: false, and set the features with the hit one.
Just as a comment it could result weird or confusing to the user retrieve just one of all possible features. I think probable you may have a problem with the content.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64336716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Ambiguous use of a subscript when accessing a 2-dimensional array bridged from Obj-C This code which ran perfectly in Xcode 7.0 now complains with a error : Ambiguous use of a subscript in Xcode 7.3.1 on the second line.
let ar = sender.draggingPasteboard().propertyListForType("ABLinkedPeopleUIDsPboardType") as! NSArray?
let uniqueID = ar![0][0] as! String
I understand that the NSArray on its own is now considered bad practice, but what do I need to do to get this to compile and run?
A: NSArray is a single-dimensioned array, but you're trying to use it as a two-dimensional array. I can't see how this would ever compile.
You need to translate into Swift types immediately so you can continue programming in Swift, not go adrift in a sea of force-unwrapped Optionals.
How about:
if let ar = sender.draggingPasteboard().propertyListForType("ABLinkedPeopleUIDsPboardType") as? [[String]] {
// I'm assuming you're expecting to get back a two-dimensional array of Strings, or in the Obj-C realm, an NSArray of NSArrays of NSStrings
let uniqueID = ar[0][0]
}
else {
print("Property List for ABLinkedetc. is not a 2D String Array!")
}
Hayden's link is the correct general discussion but if you're new to bridging Obj C to Swift it may be difficult to apply in your particular case.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38733518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP ECHO VARIABLE I managed to create a new line for each only with :
$content1= hot("britney") ? "britney found" : "";
$content2= hot("gaga") ? "gaga found" : "";
$content3= hot("carol") ? "carol found" : "";
$filename = 'result.txt';
$handle = fopen($filename, 'a');
fwrite($handle, "$Content1\r\n");
fwrite($handle, "$Content2\r\n");
fwrite($handle, "$Content3\r\n");
fwrite($handle, "$Content4\r\n");
fclose($handle);
But i have many lines and it makes a lot of modifications...
How could i automatize the process ?
maybe something like foreach < i really don't know how to implement this one here'
I have the following codes:
require("class.XMLHttpRequest.php");
function hot($news){
$url="https://localhost/search.aspx?search=".$news."";
$ajax=new XMLHttpRequest();
$ajax->setRequestHeader("Cookie","Cookie: host");
$ajax->open("GET",$url,true);
$ajax->send(null);
if($ajax->status==200){
$rHeader=$ajax->getResponseHeader("Set-Cookie");
if(substr_count($rHeader, "Present!")>0) { return true; }
}else{ return false; }
}
echo ( hot("britney") )?"britney found":"<br>";
echo ( hot("gaga") )?"gaga found":"<br>";
echo ( hot("carol") )?"carol found":"<br>";
AND
<?php
$filename = 'test.txt';
$Content = "Add this to the file\r\n";
echo "open";
$handle = fopen($filename, 'x+');
echo " write";
fwrite($handle, $Content);
echo " close";
fclose($handle);
?>
and i have many echo ( hot("britney") )?"britney found":"<br>"; in my script and because of that i want to send them to a file
how can i set a string for echo ( hot("britney") )?"britney found":"<br>";to be able to use it in my code that sends the info to file
i also don't want the page to print anything to the screen
A: $Content = hot("britney") ? "britney found" : "<br>";
A: Just store stuff in a variable then write variable.
// put stuff in $content instead of printing
$content = '';
$content .= hot("britney") ? "britney found" : "<br>";
$content .= hot("gaga") ? "gaga found" : "<br>";
$content .= hot("carol") ? "carol found" : "<br>";
// write to file
$handle = fopen($filename, 'x+');
fwrite($handle, $content);
fclose($handle);
A: As others have already stated, put the contents of your echos into a variable then write that into a file. There are two ways to do this. You can use file handlers:
<?php
// "w" will create the file if it does not exist and overwrite if it does
// "a" will create the file if it does not exist and append to the end if it does
$file = fopen('/path/to/file', 'w');
fwrite($file, $content);
fclose($file);
A slightly simpler way is to use file_put_contents():
<?php
file_put_contents('/path/to/file', $contents);
And if you want to append to the file:
<?php
file_put_contents('/path/to/file', $contents, FILE_APPEND);
As for the parenthesis you have around the conditional for your echos, I prefer something more like the following:
<?php
$contents = '';
$contents .= (hot('britney') ? 'britney found' : '<br />');
If you want to be able to easily read the file outside of a web browser, you should use a new line instead of a <br /> to separate your output. For example:
<?php
$contents = '';
$contents .= (hot('britney') ? 'britney found'."\n" : "\n");
A: Replace all of the echo statements with a variable, then write that variable to a file.
$Content.= ( hot("britney") )?"britney found":"<br>";
etc...
A: First off, your parentheses are in the wrong place. Should be like this:
echo ( hot("britney") ? "britney found" : "" );
If you want to capture your echo and other output, use the ob_start and ob_flush methods.
But if you're making HTTP requests to that file it won't echo on the screen.
If that's what you meant, then that's your answer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3827080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: perl6 Is using junctions in matching possible? Is it possible to use junction to match any of the values in a junction? I want to match any of the values in an array. What is the proper way to do it?
lisprog$ perl6
To exit type 'exit' or '^D'
> my @a=<a b c>
[a b c]
> any(@a)
any(a, b, c)
> my $x=any(@a)
any(a, b, c)
> my $y = "a 1"
a 1
> say $y ~~ m/ $x /
False
> say $y ~~ m/ "$x" /
False
> my $x = any(@a).Str
any("a", "b", "c")
> say $y ~~ m/ $x /
False
> say $y ~~ m/ || $x /
False
> say $y ~~ m/ || @a /
「a」
>
Thanks !!
A: Junctions are not meant to be interpolated into regexes. They're meant to be used in normal Perl 6 expressions, particularly with comparison operators (such as eq):
my @a = <x y z>;
say "y" eq any(@a); # any(False, True, False)
say so "y" eq any(@a); # True
To match any of the values of an array in a regex, simply write the name of the array variable (starting with @) in the regex. By default, this is interpreted as an | alternation ("longest match"), but you can also specify it to be a || alternation ("first match"):
my @a = <foo bar barkeep>;
say "barkeeper" ~~ / @a /; # 「barkeep」
say "barkeeper" ~~ / || @a /; # 「bar」
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41457242",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Rename the newly created sheet based on active cell in Sheet1 I am newbie at VBA and have a problem to solve, which for you will be more than simple, I am sure. Here is the problem:
I have table with company names in column A. What I want is to select cell with company name, click the button which will run a macro creating new sheet based on template, and rename the newly created sheet with name of the selected cell in Sheet1 (company name).
The macro generally works, I have only problem with renaming it. Your help will be greatly appriciated. Also any comments on my code in general will be very useful. Here is the code:
Sub NewSheet()
Dim wb As Workbook
Dim ws As Worksheet
Dim activeWB As Workbook
Dim FilePath As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
On Error Resume Next
Set wb = Application.Workbooks.Open(FilePath)
wb.Worksheets(1).Copy After:=activeWB.Sheets(activeWB.Sheets.Count)
activeWB.Activate
ActiveSheet.Name = Worksheets("Arkusz1").ActiveCell.Value
wb.Close False
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
A: If you need to use the ActiveCell, you can use something like the code below:
Dim ShtName As String
ShtName = ActiveCell.Value2 ' <-- save the value of the ActiveCell
Set wb = Application.Workbooks.Open(FilePath)
wb.Worksheets(1).Copy After:=activeWB.Sheets(activeWB.Sheets.Count)
' rename the sheet
activeWB.Sheets(activeWB.Sheets.Count).Name = ShtName
A: You've copied the new worksheet to the end, so you can get hold of the last worksheet like so:
Set activeWB = ActiveWorkbook
' You copied sheet 1
wb.Worksheets(1).Copy After:=activeWB.Sheets(activeWB.Sheets.Count)
' New sheet is last sheet
Dim sh As WorkSheet
Set sh = activeWB.Sheets(activeWB.Sheets.Count)
' Rename sheet
sh.Name = activeWB.Sheets("Arkusz1").ActiveCell.Value
Please note, relying on selections and active cells/sheets/workbooks is risky, and can create hard-to-diagnose errors. Try and use cell addresses instead of active cells.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45301925",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Change value in private member in JFrame with reflection Hello,
I have the following code, what I want is to modify the value of the instance called number to any value
I have both classes in the same package
ReflectionOnClass.class
import javax.swing.*;
import java.awt.*;
public class ReflectionOnClass extends JFrame {
private int number = 2;
private JLabel jLabel = new JLabel("X: " + number);
public ReflectionOnClass() {
setLayout(new FlowLayout());
setPreferredSize(new Dimension(200,200));
add(jLabel);
setDefaultCloseOperation(3);
setLocationRelativeTo(null);
pack();
setVisible(true);
}
}
ExecReflection.class
import java.lang.reflect.Field;
import java.util.stream.Stream;
public class ExecReflection {
private static final String C = "ReflectionOnClass";
public ExecReflection() {
try {
final Field field = Class.forName(C).getDeclaredField("number");
field.setAccessible(true);
final ReflectionOnClass rF = new ReflectionOnClass();
field.set(rF , 100);
mostrar("Value number: " + field.get(rF));
}catch (Exception ex){
ex.printStackTrace();
}
}
public <T> void mostrar(final T t){System.out.println(t);}
public static void main(String ...gaga) {
final Runnable r = ExecReflection::new;
r.run();
}
}
the output is the correct as in the image but in the JFrame there is no
there is no possibility to change the value of said variable before the JFrame starts?
Update this was what I wanted, to modify the value before the JFrame started, but with reflection
final Field field = Class.forName(C).getDeclaredField("jLabel");
field.setAccessible(true);
if(field.getType() == JLabel.class) {
final JLabel j = (JLabel)field.get(ReflectionOnClass.class.newInstance());
j.setText("X: " + 5000);
}
A: Its possible.
You can add this functions to ReflectionOnClass:
public void setNumber(int num){
this.number = num;
label.setText("X: " + this.number);
}
public int getNumber(){
return this.number;
}
and just call them from ExecReflection:
final ReflectionOnClass rF = new ReflectionOnClass();
rF.setNumber(4);
System.out.println("Value number: " + rF.getNumber());
A: Nothing is changing because you are not actually changing value that is displayed
private int number = 2;
private JLabel jLabel = new JLabel("X: " + number);
You need to access jLabel field, as this is your displayed value, and change text to something else, if number is used in other places, then you probably need to change both of them, so number to this example 100 value, and jLabel text to X: 100
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52677449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to make a Twitter-like following system How can i make a Twitter-like following system where, if you follow someone, you will receive their tweets. I have a database table called "users", "followings", and "posts". The users table holds the users that are on my site. The followings shows the persons followers, this table is setup like this :'id, user_one, user_two'. And the posts table holds all the tweets or posts that the unique user has.
I have a profile page set up for each user, with a follow button. And also I have a news feed for the user, but in that news feed I need it to show posts from users that the logged-in user is following. So is there anyway for me to have a user follow someone and receive the posts from that user on their news feed.
Now I did some research: their system wouldn't seem to work. I kept getting this error:
Warning: implode() [function.implode]: Invalid arguments passed in function.php on line 12
SELECT
user_id,
body,
stamp
FROM posts
WHERE user_id in ()
ORDER BY stamp DESC
Warning: mysql_fetch_object(): supplied argument is not a valid MySQL result resource in function.php.
This line right here was suppose to help make it where when you follow that person you will receive there tweets and stuff
function show_posts($userid,$limit=0){
$posts = array();
$user_string = implode(',', $userid);
$extra = " and id in ($user_string)";
if ($limit > 0){
$extra = "limit $limit";
}else{
$extra = '';
}
$sql = "select user_id,body, stamp from posts
where user_id in ($user_string)
order by stamp desc $extra";
echo $sql;
$result = mysql_query($sql);
while($data = mysql_fetch_object($result)){
$posts[] = array( 'stamp' => $data->stamp,
'userid' => $data->user_id,
'body' => $data->body
);
}
return $posts;
}
I believe this piece of code, which is supposed to show posts from other users, is causing this problem but I don't know why.
A: Use a join. For example:
select user_id, text from posts
inner join followings on posts.user_id = followings.followed_id
where followings.follower_id = :user_id;
If I may recommend, stop using the mysql_ functions; they are deprecated and should not be used in newer applications. Instead, I'd recommend using PDO.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15937260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Changing JSON return object names I have this function for returning users and user count
List<User> entitiesList = DB.Users.OrderBy(x => x.UserName).ToList();
var count = DB.Users.Count
return (entitiesList, count)
The result from HTTP request is this
{
"item1":
[
{
"fullName":"Joe Smith"
},
{"fullName":"Bob Rogan"
}
]
"item2":["2"]
}
Question is why does JSON result has objects named item1 and item2, where does these names come from, I haven't specified such names anywhere, shouldn't there just be no name in such case? And how do I rename 'item1' to 'users' and 'item2' to 'count'?
A: It's because you return a tuple, in your case (Class User, integer). You should return a custom class:
public class Response {
public List<User> Users;
public int Count;
}
....
return (new Response { Users = entitiesList, Count = count});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56772138",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Does javascript loaded via .load run even after it's "deleted"? I don't know any better way of asking this, or search for it, so here it goes:
I have a webpage that's basically a menu and a big white DIV in the center. All the subpages are loaded inside that div via .load. This is all fine, but:
I want to know if scripts loaded with the page are still going to run after the div's content is changed to another sub-page. To get what I mean, please visit http://carnbox.zapto.org (testing VPS) and log in using the credentials tomi : tomi .
Once logged in, go ahead and click on "My Services". All these scripts are inlined in the PHP pages that display the content. I found their lenght to be too small to make them external, and I wished to only load the scripts when viewing the page so the initial loading time of the website is smaller.
After clicking on another page, which will replace the contents of the white space with another page, will the setintervals from the previous page still be running? Will the scripts still be loaded in the user's browser or will they also be wiped?
Or more importantly, will swithing between the pages multiple times cause any trouble for the users?
Is this error related to the way I'm loading scripts, and should I switch to external files and jquery.getscript() ?
Synchronous XMLHttpRequest on the main thread is deprecated because of
its detrimental effects to the end user's experience. For more help,
check http://xhr.spec.whatwg.org/
A: Yes, JavaScript code loaded by .load continues running even if the elements it was loaded with are removed from the DOM. Removing a script tag has no effect whatsoever on the code that the script loaded.
Here's a live example doing the same thing with html (load ends up calling html under the covers):
var content = [
// foo
"This loads a script saying 'foo' once a second " +
"for 100 seconds." +
"<script>" +
"var fooCounter = 0;\n" +
"var fooTimer = setInterval(function() {\n" +
" $('<p>Foo</p>').appendTo(document.body);\n" +
" if (++fooCounter >= 100) {\n" +
" clearInterval(fooTimer);\n" +
" }\n" +
"}, 1000);\n" +
"</scr" + "ipt>",
// bar
"This loads a script saying 'bar' once a second " +
"for 100 seconds." +
"<script>" +
"var barCounter = 0;\n" +
"var barTimer = setInterval(function() {\n" +
" $('<p>Bar</p>').appendTo(document.body);\n" +
" if (++barCounter >= 100) {\n" +
" clearInterval(barTimer);\n" +
" }\n" +
"}, 1000);\n" +
"</scr" + "ipt>"
];
$(".load").on("click", function() {
$("#target").html(content[this.getAttribute("data-index")]);
});
<p>Click 'Load Foo', which loads content in to a target div, then once you see its script running, click 'Load Bar', which replaces the content in that div with new content. Note that now both scripts are running.</p>
<input type="button" data-index="0" class="load" value="Load Foo">
<input type="button" data-index="1" class="load" value="Load Bar">
<div id="target"></div>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29912959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Graphql-Client ruby OpenSSL::SSL::SSLError I am trying to test if I can connect to a graphql API from a rails backend by using graphql-client with the following code:
require "graphql/client"
require "graphql/client/http"
HTTP = GraphQL::Client::HTTP.new("https://x.x.x.x:3100/graphql")
Schema = GraphQL::Client.load_schema(HTTP)
Client = GraphQL::Client.new(schema: Schema, execute: HTTP)
but I get the following error:
9: from db/seeds.rb:14:in `<main>'
8: from /Library/Ruby/Gems/2.6.0/gems/graphql-client-0.16.0/lib/graphql/client.rb:61:in `load_schema'
7: from /Library/Ruby/Gems/2.6.0/gems/graphql-client-0.16.0/lib/graphql/client.rb:77:in `dump_schema'
6: from /Library/Ruby/Gems/2.6.0/gems/graphql-client-0.16.0/lib/graphql/client/http.rb:73:in `execute'
5: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/net/http.rb:1470:in `request'
4: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/net/http.rb:919:in `start'
3: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/net/http.rb:930:in `do_start'
2: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/net/http.rb:996:in `connect'
1: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/net/protocol.rb:44:in `ssl_socket_connect'
/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/net/protocol.rb:44:in `connect_nonblock': SSL_connect returned=1 errno=0 state=SSLv3 read server hello A: wrong version number (OpenSSL::SSL::SSLError)
SSL_connect returned=1 errno=0 state=SSLv3 read server hello A: wrong version number (OpenSSL::SSL::SSLError)
I have no idea how to get that solved as when I look that error up it is always in different situation than mine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65023280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: android AVD (Emulator) exit I cannot open the emulator, each time I Press launch avd. the emulato exit immidately before launching.
and it seems like there is no integration ? or something wrong as I have the below error: emulator unknow.
even though I have an emulator.
I don't even know what sort of issues is this!
as it exits without any error message.
Edit:
I solved the issue by simply reinstalling Intel HAXM
A: When this type of problem happens, best way is to make sure you have followed below points correctly.
*
*You have proper SDK installed
*You have Intel HAXM & virtualization option enabled in your BIOS
*Configure emulator correctly, download the Intel X86 Atom system image for better performance.
*Disable and then Enable ADB Integration
*User arm instead of x86 if you have AMD processor when creating emulator.(In most of case)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44336377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Creating index by concatinating multiple columns MySQL I am new to mySQL and trying to migrate to MySQL from oracle and I have an index that I need to convert to mySQL. In oracle I have created this index by using 2 columns as :
CREATE INDEX TEST ON TABLE(COL1||'/'||COL2, COL3)
Now I am trying to find alternate for this in mySQL. I know that I can create index on multiple columns in my sql like :
CREATE INDEX TEST on TABLE(COL1, COL2)
But I want to create index on multiple columns such that I can combine COL1 and COL2 using '/' delimiter and create index on it. I Found that I can create a generated column and create index on it. So basically I will have something like this :
CREATE INDEX TEST on TABLE(GENERATED_COL, COL2)
when I try to create this generated column I keep getting syntax error for generated column. Here is my syntax to create table :
CREATE TABLE PATH (
ID INT(38) NOT NULL,
PATH_PREFIX VARCHAR(2000) NOT NULL,
PATH_SUFFIX VARCHAR(255) NOT NULL,
FULLPATH VARCHAR(3000) AS (CONCAT(PATH_PREFIX,'/',PATH_SUFFIX)),
PRIMARY KEY (ID)
)
Here is my error :
SQL Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS (CONCAT(PATH_PREFIX,'/',PATH_SUFFIX)),
PRIMARY KEY (ID)
Not sure if I am doing something wrong here? If this is not right way can someone please advise me on what is the right way of creating index like CONCAT(PATH_PREFIX,'/',PATH_SUFFIX)
A: From mysql v5.7.6 you can create generated columns. If you set its type to stored, then you can create secondary indexes on it. From v5.7.8 you can even create indexes on virtual generated columns, see mysql's documentation on create table:
As of MySQL 5.7.8, InnoDB supports secondary indexes on virtual
generated columns. Other index types are not supported.
A secondary index may be created on one or more virtual columns or on
a combination of virtual columns and non-virtual generated columns.
Secondary indexes on virtual columns may be defined as UNIQUE.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35050416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to auto-backup Access Database I want to autoback up my access database with the below code and it didn't work for me. I got an error "cannot find the input table or query "WinAutoBackup" Please view the picture. Also, did I use CurrentProject correctly?
[Function fMakeBackup() As Boolean
Dim Source As String
Dim Target As String
Dim retval As Integer
On Error GoTo sysBackup_Err
Source = CurrentDb.name
Target = "CurrentProject.path\backups\"
Target = Target & Format(Now, "yyyymmdd-hhnn") & ".accdb"
If DateDiff("d", DLookup("\[BackupDate\]", "WinAutoBackup", "\[BckID\]
=1"), Date) = 3 Then
retval = 0
Dim objFSO As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
retval = objFSO.CopyFile(Source, Target, True)
Set objFSO = Nothing
DoCmd.SetWarnings False
DoCmd.RunSQL "UPDATE WinAutoBackup SET WinAutoBackup.BackupDate =
Date();"
DoCmd.SetWarnings True
MsgBox "Backup successfull. Next auto backup in 3 days"
Else
Exit Function
End If
sysBackup_Exit:
Exit Function
sysBackup_Err:
MsgBox Err.Description, , "sysBackup()"
Resume sysBackup_Exit
End Function][1]
A: Start with including:
Option Explicit
at the top of the module.
Then try with:
Function fMakeBackup() As Boolean
Dim objFSO As Object
Dim Source As String
Dim Target As String
Dim retval As Integer
' Disable error handling during development.
' On Error GoTo sysBackup_Err
Source = CurrentDb.Name
' Adjust if if backup folder is not \backups\.
Target = CurrentProject.Path & "\backups\"
Target = Target & Format(Now, "yyyymmdd-hhnn") & ".accdb"
' To run every time, use this line in plade of If DateDiff ...:
' If True Then
If DateDiff("d", DLookup("[BackupDate]", "[WinAutoBackup]", "[BckID] = 1"), Date) >= 3 Then
Set objFSO = CreateObject("Scripting.FileSystemObject")
retval = objFSO.CopyFile(Source, Target, True)
Set objFSO = Nothing
DoCmd.SetWarnings False
DoCmd.RunSQL "UPDATE WinAutoBackup SET WinAutoBackup.BackupDate = Date() WHERE [BckID] = 1;"
DoCmd.SetWarnings True
MsgBox "Backup successful. Next auto backup in 3 days."
End If
sysBackup_Exit:
Exit Function
sysBackup_Err:
MsgBox Err.Description, , "sysBackup()"
Resume sysBackup_Exit
End Function
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57742075",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: GridView button with condition I have a gridview with 3 columns Name,Surname,Change(ButtonField column) which is populated from an SqlDataReader with the following code
SqlCommand sqlCommand = new SqlCommand("select * from Empl where userId ='" + userid + "'", sqlConnection);
sqlConnection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
In my database there are 4 columns UserId,Name,Surname,Change(bit). How can i show the button change only when Change(bit) column is true inside the database?
A: You can do like..
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnChange" runat="server" Text="Change"
Visible='<%# (Boolean) Eval("Change") %>' />
</ItemTemplate>
</asp:TemplateField>
As you mentioned in the comment you are getting error on the above code, you try like...
Visible='<%# Convert.ToBoolean(Eval("Change")) == true ? true : false %>'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7110858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to make inserted items sortable
$('.parent').sortable({
containment: "parent",
tolerance: "pointer",
axis: "x"
});
$('button').on('click', function(){
var str = $('#store').html();
$(str).insertBefore($('.parent').eq(0));
});
.parent{
background:silver;
margin:9px 0;
}
.title{
background:gold;
display:inline-block;
width:25%;
cursor:cell;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div id='store'>
<div class='parent'>
<div class='title'>lorem</div>
<div class='title'>ipsum</div>
</div>
</div>
<br>
<button>CLICK</button>
How to make inserted items sortable?
I tried all solutions here and here and ...
Nothing works.
A: When adding items, you need to run refresh:
Refresh the sortable items. Triggers the reloading of all sortable items, causing new items to be recognized.
In regards to placement, you appear to selecting more than you need. I suspect you just need to insert more items to the same list. Consider the following:
$(function() {
$('.parent').sortable({
containment: "parent",
tolerance: "pointer",
axis: "x"
});
$('button').on('click', function() {
var str = $('#store .parent').html();
$(str).insertBefore($('.parent div:eq(0)'));
$('.parent').sortable("refresh");
});
});
.parent {
background: silver;
margin: 9px 0;
}
.title {
background: gold;
display: inline-block;
width: auto;
cursor: cell;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div id='store'>
<div class='parent'>
<div class='title'>lorem</div>
<div class='title'>ipsum</div>
</div>
</div>
<br>
<button>CLICK</button>
If you need a new list, then you need to add it and re-assign sortable to the new item.
$(function() {
$('.parent').sortable({
containment: "parent",
tolerance: "pointer",
axis: "x"
});
$('button').on('click', function() {
var str = $('#store .parent:last').prop("outerHTML");
$(str).insertBefore($('.parent:eq(0)'));
$("#store .parent").sortable({
containment: "parent",
tolerance: "pointer",
axis: "x"
});
});
});
.parent {
background: silver;
margin: 9px 0;
}
.title {
background: gold;
display: inline-block;
width: 25%;
cursor: cell;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div id='store'>
<div class='parent'>
<div class='title'>lorem</div>
<div class='title'>ipsum</div>
</div>
</div>
<br>
<button>CLICK</button>
Hope that helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53768536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I align elements vertically in Vuetify? I have these social media buttons in the top left corner:
And here is the code:
<v-row v-for="(button, index) in socialMediaButtons" :key="index">
<v-col>
<v-btn fixed fab class="mt-5 ml-1"><v-icon>{{ button.logo }}</v-icon></v-btn>
</v-col>
</v-row>
As you can see, the buttons are overlapping each other. How can I achieve that they have space between them vertically?
A: This is because you have fixed props, which makes v-col thinks there is nothing inside the column. So the height of the button is not calculated, which makes the buttons overlap.
Try something like this (example)
<v-row>
<v-col sm="12">
<v-btn fab dark small color="primary">
<v-icon dark>mdi-minus</v-icon>
</v-btn>
</v-col>
<v-col sm="12">
<v-btn fab dark small color="pink">
<v-icon dark>mdi-heart</v-icon>
</v-btn>
</v-col>
</v-row>;
Your code
<v-row v-for="(button, index) in socialMediaButtons" :key="index">
<v-col sm="12>
<v-btn fab class="mt-5 ml-1"><v-icon>{{ button.logo }}</v-icon></v-btn>
</v-col>
</v-row>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58900624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript won't work when passed in jquery AJAX / jquery call in loaded DIV I know this question has sort of been asked, but it's been asked for other issues not related to how my code is set up, and I believe it's unrelated to how this works. I can't for the life of me figure how to fix this.
I have two PHP pages set up. index.php and getresult.php. index is paginated using AJAX. The AJAX calls to getresult.php for the data. I have a script to load youtube videos(lazy load JS, not your typical embed). My problem is that the page will load via AJAX, but the javascript for my youtube embeds isn't working. They appear as black boxes. The html, video titles, etc all come through, but the JS just won't work on the div now. Here's the div used on getresult.php ( <div class=\"videoplayer\"><div class=\"youtube-player\" data-id=\"" . $embedid . "\"></div> ) where class="youtube-player" is supposed to activate the JS, but the JS isn't triggered by it. Here is the JS for the youtube player if it matters. The Youtube lazy load JS was working without pagination/ajax(if I were to keep everything on the same page), but with pagination and ajax, it won't.
On index.php I have the following:
function getresult(url) {
$.ajax({
url: url,
type: "GET",
data: {
rowcount: $("#rowcount").val(),
"pagination_setting": $("#pagination-setting").val()
},
beforeSend: function () {
$("#overlay").show();
},
success: function (data) {
$("#pagination-result").html(data);
setInterval(function () {
$("#overlay").hide();
}, 500);
},
error: function () {}
});
}
function changePagination(option) {
if (option != "") {
getresult("pagination/getresult.php");
}
}
I'll keep a close eye on this. I've spent literally hours trying to figure it out and I can't figure it out. Thanks!
Edit: Some magical wizard stopped by and helped me. Solution in the comments.
A: In your JS file, you ara attaching DomContentLoaded event to your code that activates youtube player. So, when your first get result is fired, it shall work fine as DOM is loaded and JS activates. But, in subsequent get calls your dom is not getting loaded, it’s changing.
I believe, you need to call the code which is activating youtube player everytime AJAX call succeeds.
What tou can do is attach your JS code to a custom event and then trigger this even everytime AJAX call succeeds.
In JS:
You can follow this link to see how an event can be created and triggered in JS
How to trigger event in JavaScript?
A: Try re-initializing the function for the youtube embeds as shown below:
function getresult(url) {
$.ajax({
url: url,
type: "GET",
data: {
rowcount: $("#rowcount").val(),
"pagination_setting": $("#pagination-setting").val()
},
beforeSend: function () {
$("#overlay").show();
},
success: function (data) {
$("#pagination-result").html(data);
var div, n,
v = document.getElementsByClassName("youtube-player");
for (n = 0; n < v.length; n++) {
div = document.createElement("div");
div.setAttribute("data-id", v[n].dataset.id);
div.innerHTML = labnolThumb(v[n].dataset.id);
div.onclick = labnolIframe;
v[n].appendChild(div);
}
setInterval(function () {
$("#overlay").hide();
}, 500);
},
error: function () {}
});
}
function changePagination(option) {
if (option != "") {
getresult("pagination/getresult.php");
}
}
function labnolThumb(id) {
var thumb = '<img src="https://i.ytimg.com/vi/ID/hqdefault.jpg">',
play = '<div class="play"></div>';
return thumb.replace("ID", id) + play;
}
function labnolIframe() {
var iframe = document.createElement("iframe");
var embed = "https://www.youtube.com/embed/ID?autoplay=1";
iframe.setAttribute("src", embed.replace("ID", this.dataset.id));
iframe.setAttribute("frameborder", "0");
iframe.setAttribute("allowfullscreen", "1");
this.parentNode.replaceChild(iframe, this);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45899156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Multiple select statements in single query while using 'group by' and 'join' I have three tables -
podcasts, videos and others.
Each of the entities under these are associated with a category and subcategories.
Example for podcasts -
This category_id and subcategory_id have their name values in their respective tables -
Now, I want to get the count of podcasts, videos and text under each category & subcategory combination. My individual SQL query are these -
For podcasts -
SELECT c.category_name, sc.sub_category_name, count(p.*) AS podcast_count
FROM podcasts p
JOIN categories c ON c.category_id = p.podcast_category_id
JOIN sub_categories sc ON sc.sub_category_id = p.podcast_subcategory_id
WHERE p.podcast_owner = 14 AND p.podcast_upload_time_stamp >= timestamp '2020-10-22 00:00:00'
GROUP BY 1, 2
For others -
SELECT c.category_name, sc.sub_category_name, count(o.*) AS other_count
FROM otherlinks o
JOIN categories c ON c.category_id = o.other_link_category_id
JOIN sub_categories sc ON sc.sub_category_id = o.other_link_subcategory_id
WHERE o.other_link_owner = 14 AND o.other_link_add_time_stamp >= timestamp '2020-10-22 00:00:00'
GROUP BY 1, 2
And similar one for videos
Now, I want to combine them into a single query so that I get three columns for counts in a single result - podcast_count, other_count and videos_count. How do I do that?
A: Join the CROSS join of categories to sub_categories, so you get all the combinations of categories and subcategories, to the other 3 tables with LEFT joins and group by each combination and aggregate:
select c.category_name, sc.sub_category_name,
count(distinct p.podcast_id) podcast_count,
count(distinct v.video_id) videos_count,
count(distinct o.other_link_id) other_count
from categories c cross join sub_categories sc
left join podcasts p on (p.podcast_category_id, p.podcast_subcategory_id) = (c.category_id, sc.sub_category_id)
and p.podcast_owner = 14 AND p.podcast_upload_time_stamp >= timestamp '2020-10-22 00:00:00'
left join videos v on (v.video_category_id, v.video_subcategory_id) = (c.category_id, sc.sub_category_id)
and v.video_owner = 14 AND v.video_upload_time_stamp >= timestamp '2020-10-22 00:00:00'
left join otherlinks o on (o.other_link_category_id, o.other_link_subcategory_id) = (c.category_id, sc.sub_category_id)
and o.other_link_owner = 14 AND o.other_link_add_time_stamp >= timestamp '2020-10-22 00:00:00'
where coalesce(p.podcast_id, v.video_id, o.other_link_id) is not null
group by c.category_id, c.category_name, sc.sub_category_id, sc.sub_category_name
The WHERE clause filters out any combination of category and subcategory that does not contain any podcast, video or other link.
A: You can use UNION ALL and add a constant to distinguish them.
SELECT 'podcasts' as "rowtype", c.category_name, sc.sub_category_name, count(p.*) AS type_count
FROM podcasts p
JOIN categories c ON c.category_id = p.podcast_category_id
JOIN sub_categories sc ON sc.sub_category_id = p.podcast_subcategory_id
WHERE p.podcast_owner = 14 AND p.podcast_upload_time_stamp >= timestamp '2020-10-22 00:00:00'
GROUP BY 1, 2, 3
UNION ALL
SELECT 'videos' as "rowtype", c.category_name, sc.sub_category_name, count(o.*) AS type_count
FROM videolinks o
JOIN categories c ON c.category_id = o.other_link_category_id
JOIN sub_categories sc ON sc.sub_category_id = o.other_link_subcategory_id
WHERE o.other_link_owner = 14 AND o.other_link_add_time_stamp >= timestamp '2020-10-22 00:00:00'
GROUP BY 1, 2, 3
UNION ALL
SELECT 'other' as "rowtype", c.category_name, sc.sub_category_name, count(o.*) AS type_count
FROM otherlinks o
JOIN categories c ON c.category_id = o.other_link_category_id
JOIN sub_categories sc ON sc.sub_category_id = o.other_link_subcategory_id
WHERE o.other_link_owner = 14 AND o.other_link_add_time_stamp >= timestamp '2020-10-22 00:00:00'
GROUP BY 1, 2, 3
I want to note that even just union might work, but union all is more often than not the one that gives the desired result.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64622274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Gant table in excel Experts, can you help me with one task I have? I have to make a Gant table in excel for real production. Do you have any teplate of working gant in excel? I would be grateful if someone could share an example. Thank you in advance.
Isue for excel Gant table
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71625862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there any way to compile a C# assembly statically into a project? I'd like to compile the same build number into a number of separate assemblies written in C#.
When I update the build number in a single place, I need it to update in all of the individual assemblies.
Whats the easiest method to do this?
A: Use a shared AssemblyInfo file as described here: http://blogs.msdn.com/b/jjameson/archive/2009/04/03/shared-assembly-info-in-visual-studio-projects.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5485404",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Creating a websocket ping in vanilla browser JS I've searched a lot but cannot find a specific example of how to send - using javascript - a ping over a websocket (https://www.rfc-editor.org/rfc/rfc6455#section-5.5.2) from the browser. I'm told that the server I'm using will reply to a ping, but I've been trying variations on the following theme without success.
var sockets= {};
// ... code that attaches sockets to this object
for (let key in sockets) {
console.log("about to send pings to", key)
sockets[key].send(0x9)
}
A: const ws = new WebSocket('URL goes here');
ws.onopen = () => { ws.send('ping') };
ws.onmessage = (data) => { console.log(data); } // this should be pong
EDIT the script that you'll need,
<script src="https://cdnjs.cloudflare.com/ajax/libs/web-socket-js/1.0.0/web_socket.min.js"></script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64712649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: why is the value being changed even in a const function? #include<iostream>
using namespace std;
class temp
{
int value1;
public :
void fun() const
{
((temp*)this)->value1 = 10;
}
void print()
{
cout<<value1<<endl;
}
};
int main()
{
temp t;
t.fun();
t.print();
}
A: $5.4/5 is about explicit type conversion (which is what is being used here)
The conversions performed by
— a const_cast (5.2.11),
— a static_cast (5.2.9),
— a static_cast followed by a const_cast,
— a reinterpret_cast (5.2.10), or
— a reinterpret_cast followed by a const_cast,
can be performed using the cast notation of
explicit type conversion. The same
semantic restrictions and behaviors
apply. If a conversion can be
interpreted in more than one of the
ways listed above, the interpretation
that appears first in the list is
used, even if a cast resulting from
that interpretation is ill-formed.
If a conversion can be interpreted in
more than one way as a static_cast
followed by a const_cast, the
conversion is ill-formed.
In this case, ((temp*)this) got treated as (const_cast<temp *>(this)) and was well-formed. This removed away the constness, thereby allowing to change the class member value.
A: C++ tries to prevent accidental errors, but it doesn't go out of its way to fight a programmer who's determined to have things their own way. If you use cast operators you're telling it "trust me, I know what's there", demanding it ignore it's own knowledge of the program. It's precisely because the C-style casting operator you've used is dangerous and can be easily misused that C++ introduces static_cast, const_cast and reinterpret_cast, which communicate the programmer's intent in such a way that the compiler can still say "hey, hold on there, that'd require more than just the type of leniency you're asking for". reinterpret_cast is the big daddy though... no arguing with that... just as brutal as the C-cast and rarely needed in a high-level application. Precisely because it's rarely needed, verbose and easily seen, it draws scrutiny. Code littered with C-style casts can easily hide bugs.
A: Because you're casting away const...
When you cast something, the responsibility is yours for making sure that it doesn't do something dumb.
Note that if temp t; is changed to const temp t;, you get undefined behavior, for modifying a const value.
Coincidentally I literally just touched on this in my blog. (Almost the same function, too.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3574059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Not hide soft-deleted instances while using `get_or_create` Let's say you are modifying get_queryset in you manager something like this
class VoteManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(is_deleted=False)
class Vote(models.Model):
objects = VoteManager()
This works as expected but the problem when you use something like get_or_create on Vote model it creates an instance even if it is present in the database because we modified the get_queryset() method. Can we not shadow the soft-deleted instance while creating??
A: You can try override get_or_create method too. Like this:
class VoteQuerySet(models.query.QuerySet):
def get_or_create(...):
"""Your realization"""
class VoteManager(models.Manager):
def get_queryset(self):
return VoteQuerySet(model=self.model, using=self._db, hints=self._hints).filter(is_deleted=False)
A: get_or_create() is a method from Queryset (check this). One way to solve this problem is create your own queryset class and overwrite this method to not hide the soft-deleted instances.
Another way is create a manager and override all() method adding a flag to return all items from database (even soft-deleted instances), like this:
class VoteManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(is_deleted=False)
def all(self, force_all=False):
if force_all:
return super().get_queryset() # queryset with all items
return self.get_queryset() # queryset without soft-deleted items
Now you can call get_or_create() and soft-deleted instances will not be hidden.
Vote.objects.all(force_all=True).get_or_create(**data)
Vote.objects.all(force_all=True) returns a queryset with all items from database. You can call methods over this queryset like filter(), get_or_create(), update_or_create() and soft-deleted instances will not be hidden.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53968557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Executing shell command in python: String error I want to execute a batch file and a command on the windows shell cmd.exe per Python. Its this command:
$cmd.exe /k ""C:\Program Files(x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" x86 & msbuild ALL_BUILD.vcxproj"
When I enter this line manually on the command prompt, it works. It starts a new shell, executes batch file vcvarsall.bat (with parameter x86) and then executes msbuild ALL_BUILD.vcxproj inside the shell. The path is quoted since it contains spaces.
Now if I try to execute this command in python with this command:
subprocess.call(["cmd.exe", "/k", '"C:/Program Files (x86)/Microsoft Visual Studio 10.0/VC/vcvarsall.bat" x86 & msbuild ALL_BUILD.vcxproj'])
I always get this error on the console:
The command "\"C:/Program Files (x86)/Microsoft Visual Studio 10.0/VC/vcvarsall.bat\"" could not be found.
Why does the command start with "\"C: instead of my entered "C: ?? Anyone has an idea how I could fix this?
A: Try this one:
'"C:\Program Files(x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" x86 & msbuild ALL_BUILD.vcxproj'
You can't use inside "" - " (it will be escaped)
A: the "x x" on command line is equivalent to a 'x x' in subprocess.call.
eventually you can leave some of the " out.
however.. did you try os.system?
import os
os.system('cmd.exe /k ""C:\Program Files(x86)\Microsoft Visual Studio 10.0\VC vcvarsall.bat" x86 & msbuild ALL_BUILD.vcxproj"')
A: The following from a Windows command-line reference I have seems relevant:
* Using multiple commands
You can use multiple commands separated by the command separator && for
string, but you must enclose them in quotation marks (for example,
"command&&command&&command").
* Processing quotation marks
If you specify /c or /k, cmd processes the remainder of string and quotation marks
are preserved only if all of the following conditions are met:
o You do not use /s.
o You use exactly one set of quotation marks.
o You do not use any special characters within the quotation marks (for
example: &<>( ) @ ^ |).
o You use one or more white-space characters within the quotation marks.
o The string within quotation marks is the name of an executable file.
If the previous conditions are not met, string is processed by examining the first
character to verify whether or not it is an opening quotation mark. If the first
character is an opening quotation mark, it is stripped along with the closing
quotation mark. Any text following the closing quotation marks is preserved.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13837612",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: When dumping assetic, using MopaBootstrapBundle, Runtime Exception occurs: The filename, directory name, or volume label syntax is incorrect Below is the complete output:
> php.exe C:\xampp\htdocs\bootstrap\app\console assetic:dump
Dumping all dev assets.
Debug mode is on.
[file+] C:\xampp\htdocs\bootstrap\app/../web/css/992f634.css
'stty' is not recognized as an internal or external command,
operable program or batch file.
[RuntimeException]
The filename, directory name, or volume label syntax is incorrect.
assetic:dump [--watch] [--force] [--period="..."] [write_to]
Process finished with exit code 1 at 23:12:02.
Execution time: 1,118 ms.
Am installing MopaBootstrapBundle. I am able to access the site without styling. What could have gone wrong? below is my config.yml
# Assetic Configuration
assetic:
debug: %kernel.debug%
use_controller: false
# java: /usr/bin/java
filters:
cssrewrite: ~
less:
node: C:\nodejs
node_paths: [C:\nodejs\node_modules]
cssembed:
jar: %kernel.root_dir%/Resources/java/cssembed-0.4.5.jar
yui_css:
jar: %kernel.root_dir%/Resources/java/yuicompressor-2.4.7.jar
yui_js:
jar: %kernel.root_dir%/Resources/java/yuicompressor-2.4.7.jar
# closure:
# jar: %kernel.root_dir%/java/compiler.jar
Please help me, I don't know what else to do. =(
A: I wasn't able to get less to work with my Symfony2 installation, so instead I used lessphp. here is how to configure lessphp with MopaBootstrapBundle and effectively eliminate my problem. BTW this solution is also like how to run MopaBootstrapBundle using a Windows Machine.
//add this to your deps file, then install
[lessphp]
git = "https://github.com/leafo/lessphp.git"
target = "/lessphp"
//add this to your autoload.php
$loader->registerPrefixes(array(
//some codes here
'lessc' => __DIR__.'/../vendor/lessphp',
));
//add this to config.yml
assetic:
filters:
less: ~
lessphp:
apply_to: "\.less$"
file: %kernel.root_dir%/../vendor/lessphp/lessc.inc.php
//override the layout.html.twig, either only to your bundle or from the app/Resources
{% extends 'MopaBootstrapBundle::layout.html.twig' %}
{% block head_style %}
{% stylesheets
'@MopaBootstrapBundle/Resources/public/less/mopabootstrapbundle.less'
%}
<link href="{{ asset_url }}" type="text/css" rel="stylesheet" media="screen" />
{% endstylesheets %}
{% endblock head_style %}
Hope this helps. =)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10451697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to fix "ViewDestroyedError: Attempt to use a destroyed view" error in Angular tests? First off, there is a long list of similar questions (1, 2, 3, 4, 5, 6, 7, 8 and more), but none of those actually have an answer applicable to my case and many other have not been answered at all.
Description and links to source code
The following code is a simple Minimal, Reproducible Example of a much bigger project.
When running npm run test from the project directory the
*
*expected result:
*
*all the tests to PASS without errors
*actual behavior:
*
*In Chromium the test commented below as // FAILING TEST! doesn't pass and report Uncaught Error: ViewDestroyedError: Attempt to use a destroyed view (link to travis report in the real project)
*In Google Chrome the tests pass, but if you open the console (F12) you see the same error being logged (so this also fails, but Chrome swallows it).
Code
app.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
hide: boolean = false;
someSubscription: Subscription;
constructor(private appServiceService: AppServiceService) { }
ngOnInit() {
this.someSubscription = this.appServiceService.shouldHide().subscribe(shouldHide => this.hide = shouldHide);
}
ngOnDestroy() {
this.someSubscription.unsubscribe();
}
}
app.component.html
<div class="row" id="jmb-panel" *ngIf="!hide">
Hello
</div>
app.component.spec
describe('AppComponent', () => {
let component: AppComponent;
let componentDe: DebugElement;
let fixture: ComponentFixture<AppComponent>;
const behaviorSubject = new BehaviorSubject<boolean>(false);
const appServiceStub = {
shouldHide: () => { spy.shouldHideSpyFn(); return behaviorSubject.asObservable() }
};
const spy = { shouldHideSpyFn: () => { } };
let spyShouldHide: jasmine.Spy;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [AppComponent],
schemas: [NO_ERRORS_SCHEMA],
providers: [{ provide: AppServiceService, useValue: appServiceStub }]
}).compileComponents();
}));
beforeEach(() => {
behaviorSubject.next(false);
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
componentDe = fixture.debugElement;
fixture.detectChanges();
spyShouldHide = spyOn(spy, 'shouldHideSpyFn');
});
it('should call AppServiceService#shouldHide on init', () => {
component.ngOnInit();
fixture.detectChanges();
expect(spyShouldHide).toHaveBeenCalledTimes(1);
});
it('should not render div if the AppServiceService#shouldHide observables emit true', () => {
appServiceStub.shouldHide().subscribe((li) => {
if (li) {
fixture.detectChanges();
expect(componentDe.query(By.css('#jmb-panel'))).toBeNull();
}
});
behaviorSubject.next(true);
});
// FAILING TEST!
it('should render div if the AppServiceService#shouldHide observables emit true', () => {
appServiceStub.shouldHide().subscribe((li) => {
if (!li) {
fixture.detectChanges();
expect(componentDe.query(By.css('#jmb-panel'))).not.toBeNull('Jumbotron panel should not be null');
}
});
behaviorSubject.next(false);
});
it('should create', () => {
fixture.detectChanges();
expect(component).toBeTruthy();
});
});
Additional notes:
The order in which the tests is specified in the posted spec matters! If the tests order is changed all the tests may pass. This is not correct: all the tests should pass independently from the order they are specified. In fact, in the real project the tests are failing randomly: when the tests order established by jasmine is set like this. For this reason it wouldn't work for me to "fix" this by changing the tests order.
Question
*
*Why does this error happen and what does it mean?, and more importantly,
*How can we avoid/fix this error when implementing the tests in angular?
A: You create one BehaviorSubject for all your tests, where you subscribe to it and never unsubscribe so it stays alive while all your tests are being executed.
Angular runs TestBed.resetTestingModule() on each beforeEach which basically destroys your Angular application and causes AppComponent view to be destroyed. But your subscriptions are still there.
beforeEach(() => {
behaviorSubject.next(false); (3) // will run all subscriptions from previous tests
...
});
...
// FAILING TEST!
it('should render jumbotron if the user is not logged in', () => {
appServiceStub.shouldHide().subscribe((li) => { // (1)
// will be executed
1) once you've subscribed since it's BehaviorSubject
2) when you call behaviorSubject.next in the current test
3) when you call behaviorSubject.next in beforeEach block
which causes the error since AppComponent has been already destoryed
fixture.detectChanges();
....
});
behaviorSubject.next(false); // (2)
});
To solve that problem you have to either unsubscribe in each of tests or don't use the same subject for all your tests:
let behaviorSubject;
...
beforeEach(async(() => {
behaviorSubject = new BehaviorSubject<boolean>(false)
TestBed.configureTestingModule({
...
}).compileComponents();
}));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56562397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Java. Changing the values of an inner array within an ArrayList I'm new to Java. I'm trying to create a Data Structure design for a simple snake game. I decided to have a dynamic size ArrayList of Arrays holding integers which represent Xs and Ys of a snakes "body". I have a quite bulky solution (with advanced for loop) to the problem of setting new values in an inner array.
class ArrayListOfArrays {
public static void main(String[] args) {
// create an arraylist
List<int[]> arrList = new ArrayList<>();
// populate an arraylist
arrList.add(new int[]{1, 2});
arrList.add(new int[]{4, 5});
// print arraylist before changing
System.out.println("The value before changing: " + arrList.get(0)[0]); // prints 1
// This is what I have come up with.
// the loop changes the values of the first array in a given arraylist
int i = 0;
for (int[] intArray: arrList) {
if (i == 0) {
intArray[0] = 9;
intArray[1] = 8;
}
i++;
break;
}
// print arraylist after changing
System.out.println("The value after changing: " + arrList.get(0)[0]); // prints 9
}
}
Is there a shorter solution to change the values in an inner array inside an ArrayList? Something like:
arrList.set(0, int[]{9, 8});
Thanks in advance! I will appreciate any help!
A: You can use = sign to set new value into array. If you have array inside ArrayList you have to get it first:
arrList.get(0)[0] = 9;
Full code:
// create an arraylist
List<int[]> arrList = new ArrayList<>();
// populate an arraylist
arrList.add(new int[] { 1, 2 });
arrList.add(new int[] { 4, 5 });
// print arraylist before changing
System.out.println("The value before changing: " + arrList.get(0)[0]); // prints
// 1
arrList.get(0)[0] = 9;
System.out.println("The value after changing: " + arrList.get(0)[0]); // prints
// This is what I have come up with.
// the loop changes the values of the first array in a given arraylist
int[] is = arrList.get(0);
for (int i = 0; i < is.length; i++) {
is[i] = i * i;
}
// print arraylist after changing
System.out.println("The value after changing: " + arrList.get(0)[0]); // prints
// 9
A: Instead of arrays better to create Segment class that represent one segment of your snake. Something like that:
public class Segment {
private int x;
private int y;
public Segment (int x, int y) {
this.x = x;
this.y = y;
}
public void setNewPosition(int x, int y) {
this.x = x;
this.y = y;
}
}
with this class you have simple:
for (Segment segment : segments) {
segment.setNewPosition(x, y);
}
p.s. after that you maybe to decide create class Snake that contains from sequence of Segment instances (incapsulate List presented now to class Snake), btw this depends of logic of your game, what methods will be present in Snake class.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44640088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Facebook login callback session always closed I have a facebook login feature in my app. Now my code works well in the emulator. But when I tried testing it to a android phone. There's no error but the session appears to be always closed even if I'm logged in.
Here's my code:
Session session = Session.getActiveSession();
//check if user is logged in at facebook
if (session != null && session.isOpened()) {
Log.i("", "Session Open");
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
@Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
facebookId = user.getId();
loginType = 2;
LogMeIn();
}
}
});
}
else
{
Log.i("", "Session Closed");
// start Facebook Login
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
@Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Log.i("", "Session Open");
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
@Override
public void onCompleted(GraphUser user, Response response) {
Log.i("", "Complete");
if (user != null) {
facebookId = user.getId();
loginType = 2;
LogMeIn();
}
}
});
}
else
{
Log.i("", "Session Closed"); //I always end up here
}
}
});
}
As you can see. I always end up on the session closed part when checking for the session after the session changed. I don't know what's wrong but this seemed to work on the emulator. Now, the code for getting the information of the graph user is not happening. Any ideas? Thanks!
Additional information: I tried to logged out my fb account. And hit my login button on my app. It redirects me to the login screen of the facebook, but again, the code for getting the graph user did not happen because the session is closed.
A: If you are using session in fragment, try this code, it works for me:
else {
Log.d("ss", "Session Closed");
// start Facebook Login
Session.openActiveSession(getActivity(),
MyFragment.this, true, callback);
}
Don't forget to use UiLifecycleHelper for onActivityResult, onResume, onCreate, onDestroy, onSaveInstancceState...
or manage the session yourself to save the state.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22405738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to prevent ios app from loading previous core data stored on device I want the app to pull new objects every time it is loaded (start-up) and not retrieve old information stored, how would I do this effectively?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44437149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I find my secret Key to add my Authy Application to clients phones? After setting up MFA, most clients have the account automatically added to their Authy app.
For others, they are trying to add the account by clicking Settings >> Add Account. It then asks them to scan a QR-Code or manually enter a key.
As the developer, I cannot for the life of me find out how to get this key or QR-Code. I have read through the docs entirely.
What am I missing? I am using the PHP SDK.
A: Authy developer evangelist here.
With Authy, the secret key is not exposed to you, the developer, for security reasons. It is only shared with the user directly via the application, without them having to do anything, as you described. Authy, in fact, manages the keys between the app and the user more than just on the first occasion, as keys can be rotated regularly without your or the user's intervention.
If a user is finding that they have signed up to your site but your application isn't appearing in their Authy app then a couple of things might have happened.
*
*Their phone may not be on a network at the time they signed up, leading to them not being able to receive the secret key from Authy
This should resolve itself over time as the user will eventually get their phone back on a network. You might consider suggesting they install Authy Desktop to use their desktop computer to authorise.
Alternatively, you could ensure they get a token and finish registering with your site by giving them the option to receive the token over SMS and forcing the token to be sent over SMS, using the force parameter when requesting a token.
*
*They may have signed up to your 2FA using a different phone number than the one they initially signed up to Authy with.
For this, again, you may want to give them the option to receive a token by SMS. Or get the user to check their Authy account settings in the application and perhaps re-enter their phone number.
Overall, you won't get access to the secret or a QR code as that is not how Authy manages the secrets. Instead, either give the option to receive an SMS or get them to install an application on a device that has a connection.
Let me know if that helps at all.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44464999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Any idea what would cause intermittent 500 serialization error on c#/.net/EF/MVC5 site? I've got an Azure web app .NET(4.6.1)/c#/MVC5/EF/Newtonsoft.JSON(6.0.4) that will run fine for a week, and then out of the blue, through 500 errors, and become unusable for everyone. Restarting and/or Recycling the site brings the site back to life. I'm struggling to find the root cause. I've seen some threads out there that suggest that untimely recycling of the app pool can cause this behavior. Within IIS, however, the site is configured to not ever recycle (idle timeout=0, and recycle schedule set to 0). Has anyone experienced this or have suggestions?
Below is the verbiage of the error:
{"Message":"An error has occurred.","ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.","ExceptionType":"System.InvalidOperationException","StackTrace":null,"InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Error getting value from 'IsCompleted' on 'Weaver.TruckScaleMgmt.Common.Models.TruckLoad'.","ExceptionType":"Newtonsoft.Json.JsonSerializationException","StackTrace":" at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)\r\n at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.WebHost.HttpControllerHandler.d__1b.MoveNext()","InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Object reference not set to an instance of an object.","ExceptionType":"System.NullReferenceException","StackTrace":" at Weaver.TruckScaleMgmt.Common.Models.TruckLoad.<>c.b__71_0(TruckLoadQuality t) in C:\Users\wh741\Source\Repos\Scalehouse\Weaver.TruckScaleMgmt.Common\Models\TruckLoad.cs:line 223\r\n at System.Linq.Enumerable.WhereListIterator`1.MoveNext()\r\n at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)\r\n at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)\r\n at Weaver.TruckScaleMgmt.Common.Models.TruckLoad.UpdateCompletedRequirements() in C:\Users\wh741\Source\Repos\Scalehouse\Weaver.TruckScaleMgmt.Common\Models\TruckLoad.cs:line 223\r\n at Weaver.TruckScaleMgmt.Common.Models.TruckLoad.get_IsCompleted() in C:\Users\wh741\Source\Repos\Scalehouse\Weaver.TruckScaleMgmt.Common\Models\TruckLoad.cs:line 335\r\n at GetIsCompleted(Object )\r\n at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)"}}}
.
.
.
Update:
I've been able to reproduce the problem, and believe it to be an issue with the serialization of a Boolean variable. I don't have it fixed yet, but I believe I know the root cause. The code I posted earlier was not related to the root cause....
Update2:
OK. I've fixed the problem. A case that happens once in a blue moon left a null value within a field that was within a linq query. What I don't know, however, is why this would make the app unusable for everyone. One instance makes the app wig out for everyone.....
A: I've fixed the problem. A case that happens once in a blue moon left a null value within a field that was within a linq query. What I don't know, however, is why this would make the app unusable for everyone. One instance makes the app wig out for everyone.....
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46447553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Change width of checkable area of checkbox I have a CheckBox object and it doesn't have any text associated with it.
It is in a Grid which has another coulmn used as the label for it.
The whitespace next to the checkbox you can click and it will toggle checkbox
I want it just be the area of the actual checkbox and not the white space around it(because the text for it is set to nothing).
I tried setting the width = 5 but that didn't make a difference
thank you very much!!
A: For that you will have to go into the checkboxes template and modify that. Specifically you should go in and remove the ContentPresenter which is what displays the text. Since you have no text, it is not a problem. The end result will look something like this. Just add that style to your checkbox.
The default templates ContentPresenter is housed under the Bullet. Because of this, clicking on that content presenter (even if empty, I think it has a default size) will activate the controls click logic.
<Style x:Key="CheckBoxStyle1" TargetType="{x:Type CheckBox}">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
<Setter Property="Background" Value="{StaticResource CheckRadioFillNormal}"/>
<Setter Property="BorderBrush" Value="{StaticResource CheckRadioStrokeNormal}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="FocusVisualStyle" Value="{StaticResource EmptyCheckBoxFocusVisual}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type CheckBox}">
<BulletDecorator Background="Transparent" SnapsToDevicePixels="true">
<BulletDecorator.Bullet>
<Microsoft_Windows_Themes:BulletChrome BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" IsChecked="{TemplateBinding IsChecked}" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderPressed="{TemplateBinding IsPressed}"/>
</BulletDecorator.Bullet>
</BulletDecorator>
<ControlTemplate.Triggers>
<Trigger Property="HasContent" Value="true">
<Setter Property="FocusVisualStyle" Value="{StaticResource CheckRadioFocusVisual}"/>
<Setter Property="Padding" Value="2,0,0,0"/>
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
A: It sounds like your CheckBox is stretching to the whole width of the grid cell (with all of that width clickable), and you don't want it to stretch.
Set the CheckBox's HorizontalAlignment property to Left (or Center, or Right). Then it will be exactly the width it needs to be for the checkbox, rather than stretching to the entire width provided by its parent.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6428545",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.