_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d13801 | train | The problem is that you can't assign arrays in C. You can only initialize them. Also, you can't pass an array to a function - what actually gets passed is a pointer to the first element of the array. The following statement
typedef char AirportCode[4];
defines a type AirportCode of type char[4] - an array of 4 characters. In your function insertFirst, you are assigning code which is of type char * to (*listPtr)->airport which is of type AirportCode or char[4]. These two are incompatible types and hence you are getting the error.
Since you can't pass an array to a function, what you should do is pass a pointer to the first element of the array and the array length as well. Then copy the array to the corresponding member of the structure.
The below three declarations are exactly the same. The array parameter in the function is actually a pointer to a character.
void insertFirst(AirportCode code, Node **listPtr);
void insertFirst(char code[4], Node **listPtr);
void insertFirst(char *code, Node **listPtr);
Also, you should not cast the result of malloc. Don't let the typedef clutter the namespace and cause confusion. You are better off without it in this case. If the if condition *listPtr == NULL is true, then you are dereferencing the null pointer in the block which is obviously an error.
if(*listPtr == NULL) {
// the below statements dereference the null pointer
// which is an error and would cause program crash
// due to segfault.
(*listPtr)->airport = code;
(*listPtr)->next = NULL;
}
From your else block, I assume you are trying to add a new node at the beginning of the linked list. I suggest the following changes (thanks to Jonathan Leffler).
typedef struct node {
char airport[4]; // no typedef. explicit array declaration.
struct node *next;
} Node;
void insertFirst(char *code, Node **listPtr) {
Node *oldHead = *listPtr;
Node *newNode = malloc(sizeof(Node));
if(newNode == NULL) { // check for NULL
printf("Not enough memory to allocate\n");
return;
}
// if the struct member code is a string, then use strncpy to
// guard against buffer overrun, else use memcpy to copy
// code to airport. this is assuming that the buffer pointed
// to by code is never smaller than sizeof newNode->airport
memcpy(newNode->airport, code, sizeof newNode->airport);
newNode->next = oldHead;
*listPtr = newNode; // make listPtr point to the new head
}
A: the basics goes like this
int a=10,b;
b=a
Above works Fine
the same thing for array
int a[]={1,2,3};
int b[3]
b=a; ---> this wrong way
correct way is
for(i=0;i<3;i++)
{
b[i]=a[i];
}
OR
strcpy(b,a);
char a[4],b[4];
gets(a);
b=a;----->wrong assigning
correct way
strcpy(b,a);
For more details find Inserting New Node | unknown | |
d13802 | train | The & in the type for the function-parameter intString means that the function gets a reference to the passed argument, instead of a copy of it.
Thus, the iterator which is returned from .find() and which it returns in turn will point into the passed argument, instead of being a dangling iterator pointing somewhere into a no longer existing copy.
And accessing destroyed objects, especially if the memory was re-purposed, can have all kinds of surprising results, which is why it is called Undefined Behavior (UB). | unknown | |
d13803 | train | The minSdkVersion attribute means that the library was designed without considering the API levels lower than that value. The developers didn't pay attention if a method or a field is unavailable on API level lower than 15, and this is the method to inform you.
For example the field THREAD_POOL_EXECUTOR used in the method getExecutor is available only from API level 11:
public static Executor getExecutor() {
synchronized (LOCK) {
if (FacebookSdk.executor == null) {
FacebookSdk.executor = AsyncTask.THREAD_POOL_EXECUTOR;
}
}
return FacebookSdk.executor;
}
In version 4.5.1 the getExecutor method is different and supports also API level 9:
public static Executor getExecutor() {
synchronized (LOCK) {
if (FacebookSdk.executor == null) {
Executor executor = getAsyncTaskExecutor();
if (executor == null) {
executor = new ThreadPoolExecutor(
DEFAULT_CORE_POOL_SIZE, DEFAULT_MAXIMUM_POOL_SIZE, DEFAULT_KEEP_ALIVE,
TimeUnit.SECONDS, DEFAULT_WORK_QUEUE, DEFAULT_THREAD_FACTORY);
}
FacebookSdk.executor = executor;
}
}
return FacebookSdk.executor;
}
In conclusion you shouldn't use the last version of the Facebook SDK but you should stick with the last compatible version (4.5.0).
The change in minApk version is shown in the upgrade log below: -
https://developers.facebook.com/docs/android/upgrading-4.x.
and the release of interest is below
https://github.com/facebook/facebook-android-sdk/releases?after=sdk-version-4.8.1 | unknown | |
d13804 | train | Given the new information i suspect you can just give the ttyUSB as the parameter, mono will handle the connection correctly. However the same caution for the line endings below still applies. You might also consider making the parameter a command-line parameter thus making your code run on any platform by being able to supply the COM/USB through the command line parameters. I see no other issues using this code. Did you try it yet?
PS: i think your confusion is actually the statement usb id's are not supported yet, i suspect that is because the library relies on a (text-based) serial connection wich are fundamentally different from direct USB connections (wich drivers normally handle) that handle the connection in a more direct way. The ttyUSB ports on linux however DO represent the (UART) serial connections the same way as windows COM-ports, these are not direct USB connections.
Some handy info about the differences: https://rfc1149.net/blog/2013/03/05/what-is-the-difference-between-devttyusbx-and-devttyacmx/
Old answer
I am assuming you run this program on Mono?
Mono expects the path to the port, so COM* will not do. You could try creating a symlink named COM* to the ttyUSB*. Preferrably located in the environment directory. Once you get them linked the program should see no difference. However line endings in the data/program might be different than on windows. If the device expects CRLF and the program uses Environment.NewLine you might get unexpected behaviour too. It might just be easier if you have the permission/rights to edit the assembly with recompilation tools. | unknown | |
d13805 | train | Since there was no easy way of solving this issue (at least, I hadn't found), I converted my async method to sync one. And called it on Python side as,
async fn my_method(s: &str) -> Result<String, Error> {
// do something
}
#[pyfunction]
fn my_sync_method(s: String) -> PyResult<String> {
let mut rt = tokio::runtime::Runtime::new().unwrap();
let mut contents = String::new();
rt.block_on(async {
result = format!("{}", my_sync_method(&s).await.unwrap()).to_string();
});
Ok((result))
}
#[pymodule]
fn MyModule(py: Python, m: &PyModule) -> PyResult<()> {
m.add_wrapped(wrap_pyfunction!(my_sync_method))?;
Ok(())
}
Edited
In the Cargo.toml file, I added the following dependencies,
[dependencies.pyo3]
git = "https://github.com/PyO3/pyo3"
features = ["extension-module"]
After running cargo build --release, target/release/libMyModule.so binary file is generated. Rename it as MyModule.so and it now can be imported from Python.
import MyModule
result = MyModule.my_sync_method("hello")
Using setuptools-rust, I could bundle it as an ordinary Python package.
All of the above code and commands are tested on newly-released Linux Mint 20. On MacOS, the binary file will be libMyModule.dylib.
A: If you want to use Python to control Rust's async function, I don't think it will work (Or at least it is very complicated, as you need to connect two different future mechanism). For async functions, Rust compiler will maintain a state machine to manage the coroutines run correctly under await's control. This is an internal state of Rust applications and Python cannot touch it. Similarly Python interpreter also has a state machine that cannot be touched by Rust.
I do found this topic about how to export an async function using FFI. The main idea is to wrap the async in a BoxFuture and let C control the timing of returning it to Rust. However, you cannot use BoxFuture in PyO3 since its pyfunction macro cannot convert a function returns BoxFuture to a Python callback. You may try to create a library using FFI and use python's cffi module to load it. | unknown | |
d13806 | train | I recommend you update to 3900 (hotfix coming very soon to address login and several other issues) and use the "Cordova export" feature to build apps. The ZIP that is generated by that export can be provided directly to PhoneGap Build, using the one free private slot. This will be a much simpler build process than having your students install node, Cordova CLI and the Android build tools. | unknown | |
d13807 | train | Actually suggestion in the documentation is the solution:
You do not have to wrap the Client in an Rc or Arc to reuse it, because it already uses an Arc internally.
Simply clone the client.
Please check the Client definition from the source:
#[derive(Clone)]
pub struct Client {
inner: Arc<ClientRef>,
}
You can think Client as a reference holder
The inner type(ClientRef) has wrapped with Arc as the documentation says and Client has Clone implementation, since there is no other fields except inner: Arc<_>, cloning the client will not cause any runtime overhead comparing to wrapping it with Arc by yourself.
Additionally Client implements Send this means clone of clients can be send across threads, since there is no explicit mutable operation over Client then Mutex is not needed in here. (I said explicit because there might be an interior mutability) | unknown | |
d13808 | train | Try this:
For i = 0 To UBound(tabValTextBox)
valTemp = tabValTextBox(i)
iTextBoxCableA = iTextBoxCableA + 1
If valTemp = 0 Then
Set textBoxCableA = UserForm1.Controls.Add("Forms.TextBox.1")
colTextBoxCableA.Add textBoxCableA
With textBoxCableA
.Name = "cable" & iTextBoxCableA
.Top = iTextBoxCableA * textBoxCableA.Height + 50
.Left = 150
.Text = "Nul"
End With
Else
For j = 0 To valTemp - 1
Set textBoxCableA = UserForm1.Controls.Add("Forms.TextBox.1")
colTextBoxCableA.Add textBoxCableA
With textBoxCableA
.Name = "cable" & iTextBoxCableA
.Top = iTextBoxCableA * textBoxCableA.Height + 50
.Left = 150
End With
Next j
End If
Next i
I've moved the iTextBoxCableA increment outside of the zero condition, and removed the iTextBoxMasqueA increment entirely as you weren't using it.
I can't test this myself but I think it'll sort the problem of overlapping out. | unknown | |
d13809 | train | Wow, people still use LCC... Last time I used it was ~10 years ago.
I decompiled wedit.exe and can confirm there is no official way to disable this behavior.
I patched the binary if that works for you. I uploaded it here.
To those who concerned about viruses and such I patched wedit taken from here. About box says it's version 4.0 compiled at Sep 16 2009.
Here is patched function to those who interested:
int __cdecl sub_44CF0D(HANDLE hProcess)
{
int result; // eax@1
int v2; // ST0C_4@10
int v3; // eax@20
int v4; // eax@23
int v5; // eax@25
int v6; // [sp+10h] [bp-68h]@11
int v7; // [sp+14h] [bp-64h]@1
struct _DEBUG_EVENT DebugEvent; // [sp+18h] [bp-60h]@1
v7 = 1;
result = WaitForDebugEvent(&DebugEvent, dwMilliseconds);
if ( result )
{
sub_44C67A(&DebugEvent);
if ( DebugEvent.dwDebugEventCode == 1 )
{
if ( DebugEvent.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_ACCESS_VIOLATION
&& !(dword_482860 & 1)
&& !dword_484328
&& DebugEvent.u.Exception.dwFirstChance )
{
sub_44E1A5(0);
sub_44CEB2(v2);
return ContinueDebugEvent(DebugEvent.dwProcessId, DebugEvent.dwThreadId, 0x80010001u);
}
v6 = 0;
v7 = sub_44D2C4((int)&DebugEvent, hProcess, (int)&v6);
if ( v6 && DebugEvent.u.Exception.dwFirstChance )
return ContinueDebugEvent(DebugEvent.dwProcessId, DebugEvent.dwThreadId, 0x80010001u);
goto LABEL_41;
}
if ( DebugEvent.dwDebugEventCode == 3 )
{
if ( dword_483C94 )
{
dword_48428C = 1;
LABEL_41:
if ( dword_483C6C )
sub_44ECDC();
if ( v7 )
{
result = ContinueDebugEvent(DebugEvent.dwProcessId, DebugEvent.dwThreadId, 0x10002u);
}
else
{
dword_49BF68 = 1;
ResetEvent(dword_484AE4);
dword_4843C8 = DebugEvent.dwThreadId;
result = sub_4524CD();
}
return result;
}
Sleep(0x32u);
dword_49BF64 = 1;
dword_49BF68 = 1;
qword_483C74 = __PAIR__(
(unsigned int)DebugEvent.u.Exception.ExceptionRecord.ExceptionAddress,
DebugEvent.u.Exception.ExceptionRecord.ExceptionInformation[2]);
if ( dword_484288 )
::hProcess = (HANDLE)DebugEvent.u.Exception.ExceptionRecord.ExceptionFlags;
else
::hProcess = hProcess;
dword_483C84 = DebugEvent.dwProcessId;
hThread = DebugEvent.u.Exception.ExceptionRecord.ExceptionRecord;
dword_483C9C = (HANDLE)DebugEvent.u.Exception.ExceptionRecord.ExceptionCode;
dwThreadId = DebugEvent.dwThreadId;
dword_483C94 = 0;
if ( sub_45A83A() )
{
v4 = sub_4026A6(28);
dword_484330 = v4;
*(_DWORD *)(v4 + 4) = hThread;
*(_DWORD *)(v4 + 8) = dwThreadId;
if ( dword_484288 )
{
sub_455B58();
}
else
{
Sleep(0x64u);
v5 = sub_45AAFC();
if ( !v5 )
return PostMessageA(dword_4849EC, 0x111u, 0x64u, 0);
if ( dword_484354 )
goto LABEL_50;
sub_455B58();
if ( dword_483C70 && *(_DWORD *)(dword_483C70 + 52) )
*(_DWORD *)(*(_DWORD *)(dword_483C70 + 52) + 36) = sub_451577(**(_DWORD **)(dword_483C70 + 52), 1u);
v5 = *(_DWORD *)(dword_483C70 + 52);
if ( v5 && *(_DWORD *)(v5 + 36) )
{
LABEL_50:
if ( !dword_483C6C )
sub_44E92A(v5);
sub_44CC3D();
sub_451600();
PostMessageA(dword_4849EC, 0x111u, 0x154u, 0);
}
else
{
sub_4029CA("Imposible to find %s\nRunning without source display", *(_DWORD *)(dword_483C70 + 20));
dword_484344 = 1;
v7 = 1;
PostMessageA(dword_4849EC, 0x111u, 0x154u, 0);
}
}
goto LABEL_41;
}
dword_484338 = 1;
v3 = sub_44DB56(qword_483C74);
if ( v3 )
*(_BYTE *)(v3 + 29) &= 0xFDu;
result = ContinueDebugEvent(DebugEvent.dwProcessId, DebugEvent.dwThreadId, 0x10002u);
}
else
{
if ( DebugEvent.dwDebugEventCode != 5 )
goto LABEL_41;
if ( DebugEvent.dwProcessId != dword_483C84 )
{
v7 = 1;
goto LABEL_41;
}
dword_49BF64 = 0;
dword_49BF68 = 1;
dword_481614 = 0;
result = sub_402A32(4520, SLOBYTE(DebugEvent.u.Exception.ExceptionRecord.ExceptionCode));
if ( !dword_483C6C )
result = sub_40B155(lpCmdLine);
}
}
else
{
if ( dword_483C6C )
result = sub_44ECDC();
}
return result;
}
if under LABEL_50 is what I patched (from 0x75 to 0xEB).
It was easy to spot the place because I expected WriteProcessMemory to be used to write 0xCC at entry-point of application that is being debugged. | unknown | |
d13810 | train | You can add staff in List and then write the list to file as below,
List<Staff> staffList = new LinkedList<>()
for(int i = 0; i < 4; i++) {
Staff staff = createStaff();
staffList.add(staff);
}
mapper.writeValue(file, staffList);
Hope it helps.
A: Jackson was implemented to parse and generate JSON payloads. All extra logic related with adding new element to array and writing back to file you need to implement yourself. It should not be hard to do:
class JsonFileAppender {
private final ObjectMapper jsonMapper;
public JsonFileAppender() {
this.jsonMapper = JsonMapper.builder().build();
}
public void appendToArray(File jsonFile, Object value) throws IOException {
Objects.requireNonNull(jsonFile);
Objects.requireNonNull(value);
if (jsonFile.isDirectory()) {
throw new IllegalArgumentException("File can not be a directory!");
}
JsonNode node = readArrayOrCreateNew(jsonFile);
if (node.isArray()) {
ArrayNode array = (ArrayNode) node;
array.addPOJO(value);
} else {
ArrayNode rootArray = jsonMapper.createArrayNode();
rootArray.add(node);
rootArray.addPOJO(value);
node = rootArray;
}
jsonMapper.writeValue(jsonFile, node);
}
private JsonNode readArrayOrCreateNew(File jsonFile) throws IOException {
if (jsonFile.exists() && jsonFile.length() > 0) {
return jsonMapper.readTree(jsonFile);
}
return jsonMapper.createArrayNode();
}
}
Example usage with some usecases:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class JsonPathApp {
public static void main(String[] args) throws Exception {
Path jsonTmpFile = Files.createTempFile("json", "array");
JsonFileAppender jfa = new JsonFileAppender();
// Add POJO
jfa.appendToArray(jsonTmpFile.toFile(), createStaff());
printContent(jsonTmpFile); //1
// Add primitive
jfa.appendToArray(jsonTmpFile.toFile(), "Jackson");
printContent(jsonTmpFile); //2
// Add another array
jfa.appendToArray(jsonTmpFile.toFile(), Arrays.asList("Version: ", 2, 10, 0));
printContent(jsonTmpFile); //3
// Add another object
jfa.appendToArray(jsonTmpFile.toFile(), Collections.singletonMap("simple", "object"));
printContent(jsonTmpFile); //4
}
private static Staff createStaff() {
Staff staff = new Staff();
staff.setName("mkyong");
staff.setAge(38);
staff.setPosition(new String[]{"Founder", "CTO", "Writer"});
Map<String, Double> salary = new HashMap<>();
salary.put("2010", 10000.69);
staff.setSalary(salary);
staff.setSkills(Arrays.asList("java", "python", "node", "kotlin"));
return staff;
}
private static void printContent(Path path) throws IOException {
List<String> lines = Files.readAllLines(path);
System.out.println(String.join("", lines));
}
}
Above code prints 4 lines:
1
[{"name":"mkyong","age":38,"position":["Founder","CTO","Writer"],"salary":{"2010":10000.69},"skills":["java","python","node","kotlin"]}]
2
[{"name":"mkyong","age":38,"position":["Founder","CTO","Writer"],"salary":{"2010":10000.69},"skills":["java","python","node","kotlin"]},"Jackson"]
3
[{"name":"mkyong","age":38,"position":["Founder","CTO","Writer"],"salary":{"2010":10000.69},"skills":["java","python","node","kotlin"]},"Jackson",["Version: ",2,10,0]]
4
[{"name":"mkyong","age":38,"position":["Founder","CTO","Writer"],"salary":{"2010":10000.69},"skills":["java","python","node","kotlin"]},"Jackson",["Version: ",2,10,0],{"simple":"object"}] | unknown | |
d13811 | train | In our team for input/output arguments we either use
void AdjustPassengerList(PassengerList&);
or
void AddPassengersTo(PassengerList&);
Depending on the use-case. For example the first one could be used if you want a list created from more than one car. The second usually reads well in code, something like:
car.AddPassengersTo(list); | unknown | |
d13812 | train | As an example, say that the height of your client is 100px and the height of your whole page is 500px.
When the scroll position is 0px, you're able to see the first 100px of your site, so from 0px to 100px.
At scroll position 100px, you can see the range 100px to 200px, because you've moved the page, and therefore the visible range, on by 100px.
At scroll position 400px, you can therefore see the range 400px to 500px – in other words, you've scrolled to the bottom.
This demonstrates that the scrollable height of the page (400px) is less than the actual height of the page (500px), namely by the height of the client.
To get the percentage scrolled, you need to use the scrollable height, so it is necessary to subtract the height of the client from the height of the page to get a correct value, or you'll never be able to scroll to the bottom. It's not possible to scroll by 500px on a site that is only 500px long! | unknown | |
d13813 | train | function validate(){
var email = $("#mce-EMAIL").val();
if (!validateEmail(email)) {
$("#mce-EMAIL").css("border-color", "red");
return false;
}
else{
$("#mce-EMAIL").css("border-color", "#dbdbdb");
$("form").submit();
return true;
}
}
$(document).ready(function(){
$("#mc-embedded-subscribe").on("click",function(){ validate()});
});
this might be better , binding submit with validate , would submit the form anyway ! | unknown | |
d13814 | train | Application level
You may try to force your app to only support TLS 1.3.
TLS 1.3 supports only ciphers thought to be secure.
This post explains how to do it for TLS 1.2, you would just have to change the
s.SslProtocols = SslProtocols.Tls12;
to
s.SslProtocols = SslProtocols.Tls13;
More informations here
Feel free to test it with SSL Labs
You can stay on TLS 1.2 and manually choosing your ciphers by doing this.
Proceed with absolute caution when doing this. You want to do this only if you absolutely know what you're doing.
var ciphersArray = new TlsCipherSuite[]
{
TlsCipherSuite.TLS_AES_256_GCM_SHA384, // etc
};
var builder = WebApplication.CreateBuilder(args);
builder.Host.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder.ConfigureKestrel(kestrelServerOptions =>
{
kestrelServerOptions.ConfigureHttpsDefaults(w =>
{
w.OnAuthenticate = (x, s) =>
{
var ciphers = new CipherSuitesPolicy(ciphersArray);
s.CipherSuitesPolicy = ciphers;
};
});
});
});
OS Level
It's not your OS version but this RHEL 8 doc could be interesting to you. As you can see the DEFAULT option doesn't allow RC4 and 3DES | unknown | |
d13815 | train | That will be:
file_put_contents('unique.txt', array_diff(file('text1.txt'), file('text2.txt')));
-since you're loading your files into RAM entirely, I suppose it's acceptable solution.
Also you may want to define your own function to determine if strings are equal. Logic then will be the same, but array_udiff() should be used | unknown | |
d13816 | train | You can't use import to import modules from a string containing their name. You could, however, use importlib:
import importlib
i = 0
while i < 51:
file_name = 'myfile' + str(i)
importlib.import_module(file_name)
i += 1
Also, note that the "pythonic" way of iterating a set number of times would be to use a for loop:
for i in range(0, 51):
file_name = 'myfile' + str(i)
importlib.import_module(file_name)
A: The other answer by @Mureinik is good, but simply doing - importlib.import_module(file_name) is not enough. As given in the documentation of importlib -
importlib.import_module(name, package=None)
Import a module. The name argument specifies what module to import in absolute or relative terms (e.g. either pkg.mod or ..mod). If the name is specified in relative terms, then the package argument must be specified to the package which is to act as the anchor for resolving the package name (e.g. import_module('..mod', 'pkg.subpkg') will import pkg.mod). The specified module will be inserted into sys.modules and returned.
importlib.import_module simply returns the module object, it does not insert it into the globals namespace, so even if you import the module this way, you cannot later on use that module directly as filename1.<something> (or so).
Example -
>>> import importlib
>>> importlib.import_module('a')
<module 'a' from '/path/to/a.py'>
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
To be able to use it by specifying the name, you would need to add the returned module into the globals() dictionary (which is the dictionary for the global namespace). Example -
gbl = globals()
for i in range(0, 51):
file_name = 'myfile{}'.format(i)
try:
gbl[file_name] = importlib.import_module(file_name)
except ImportError:
pass #Or handle the error when `file_name` module does not exist.
It might be also be better to except ImportError incase file_name modules don't exist, you can handle them anyway you want.
A: @Murenik and @Anand S Kumar already gave a right answers, but I just want to help a little bit too :) If you want to import all files from some folder, it's better to use glob function instead hardcoded for cycle. It's pythonic way to iterate across files.
# It's code from Anand S Kumar's solution
gbl = globals()
def force_import(module_name):
try:
gbl[module_name] = importlib.import_module(module_name)
except ImportError:
pass #Or handle the error when `module_name` module does not exist.
# Pythonic way to iterate files
import glob
for module_name in glob.glob("myfile*"):
force_import( module_name.replace(".py", "") ) | unknown | |
d13817 | train | you are passing the same address for all the values and key here, so by the time you reach the end, the last value is replicated in all the pointers
int i = arr[p];
int *key= &i;
int i2 = arr2[p];
int *value= &i2;
instead you can copy the number of bytes from the location like below.
//newNode->key = key;
newNode->key = malloc(sizeof(int));
memcpy(newNode->key, key,sizeof(int) );
//newNode->val = val;
newNode->val = malloc(sizeof(int));
memcpy(newNode->val, val,sizeof(int) );
NOTE: you will have to handle error checks for malloc and free the memory once done.
A: the problem came from the main function.
int i = arr[p];
int *key= &i;
Your key is a pointer to the i variable, not to the value in arr.
The right way:
int * key = &arr[p];
(same problem for the value) | unknown | |
d13818 | train | Setting IBOutlets to nil in viewDidUnload tells the compiler to release the outlets on memory warning.because on memory warning ..viewDidUnload and didReceiveMemoryWarning of the viewcontrollers gets called..Normally in ViewDidUnload the IBOutlets are set to nil and in didReceiveMemoryWarning properties or objects are released.Hence in such a case memory is regained and thus your app can continue to function else continuous pooling causes in crash due to low memory
A: After reading a lot articles on the web and going through similar questions on stackoverflow.com I reached at the following understanding:
*
*viewDidUnload is called by the compiler in low memory situation.
*We should set those properties to nil in the method, which are being re-instanciated in viewDidLoad. Almost all IBOutlet components falls under the category. So better we declare the IBOutlets to nil in the method. Not doing so will lead to continuous pooling and may cause crash due to low memory in future(the time, the app continues to run).
*I also read that we should not nil the instances of the class like NSString(may cause crash), which is right as per my experience. But reason for that I don't know.
*It has nothing to deal with ARC. Setting a property to nil simply means that the property doesnot keep the refrence of any memory location anymore.
I will keep on updating this answer every time i came to know something more about it.
Thanks. | unknown | |
d13819 | train | The filenames have no consequences on the result, you can name them whatever you want.
Even the extensions are just conventions to make human life simpler.
You just need to make sure of course that all applications using them will use their proper name.
My personal advice would be to use the full domain name in the filename, especially if you have to maintain many different certificates (in which case you may need to handle certificates for both example.com and example.net at the same time if they are two different certificates, you will need the TLD in the filename to discriminate between them). | unknown | |
d13820 | train | How can I know when the user is zooming in or zooming out?
At every zoom level, calculate how much map.getZoom() has changed.
Is it possible to know this when the event zoomstart is triggered?
No.
Consider the following scenario: A user, using a touchscreen (phone/tablet).
The user puts two fingers down on the screen. Half a frame after, one of the fingers moves a couple of pixels towards the center, triggering a pinch-zoom with a tiny change in the zoom level.
Your code catches the zoomstart and zoom events that happen inmediately after. "I know!" - your code says - "The user is zooming out!".
And then the user starts moving their fingers wider and wider, zooming in. And your code gets confused.
But the user changes their mind, and then starts zooming out for whatever reason. And then in again. And then out again. And then they lift the fingers and the zoom snaps to a zoom level.
This is why you can not know what the final zoom level is going to be when you listen to a zoomstart or zoom event in Leaflet. | unknown | |
d13821 | train | Possible variant:
procedure SwapDWordVar(var AValue: DWORD);
asm
mov edx, [eax]
bswap edx
mov [eax], edx
end;
You might find useful Guido Gybels articles
A: Just try
procedure SwapDWordVar(var AValue: DWORD);
asm
mov edx, dword ptr [AValue]
bswap edx
mov dword ptr [AValue], edx
end;
Note that this version will compile and work for both Win32 and Win64.
But note that it won't be faster than AValue := SWapDWord(AValue) since most of the time will be spent calling the function, not accessing the memory. | unknown | |
d13822 | train | The use case for both are the same. But the first one is just a short-hand code:
<div v-myDirective:foo.a.b="some value">
But remember foo.a.b has a and b modifier and the directives returns true for them when it presents inside the directive.
When you just use foo.a, then the b modifier is not present and it returns false.
if (binding.modifiers.a) {
// do something a
}
if (binding.modifiers.b) {
// do something b
}
But in an object syntax, you can do more thing rather than just a true value check.
<div v-myDirective="{arg: 'foo', a:'some string', b:100, value: 'some value'}">
This way, you can check if a has 'some string' and b has 100 in your directive function.
if (binding.value.a == 'some string') {
// do something a
}
if (binding.value.b == 100) {
// do something b
}
Most of us prefer short-hand syntax and I do as well. So, whenever you need to check if modifier is present or not, use short-hand syntax. And use object syntax when you need more complex check than just true value check.
A: Programming usability/convenience, that's all.
The reason one would prefer v-directive:foo="bar" instead of v-directive="{foo: bar}" is the same people prefer :prop="val" instead of v-bind:prop="val". Convenience.
Same with v-on:click and @click.
Using the declarative way (instead of the "value" way) can be much more readable and make much more sense for the end user (the programmer). The declarative way separates much better what is "metadata" and what is "payload" for the directive.
If the end user is a designer (not used to JavaScript's object notation), I'd argue this makes an even greater difference.
The "value" notation becomes much more error prone the more you have options:
v-directive="{a: 1, b: '123', c: message, d: 'false'}"
Will people really remember to quote '123' correctly so it means a string? Will they do it while not quoting a's value? Will they always remember they should quote one but not the other? Is it clear to the user that message there will be the value of this.message and not the string "message"? If d is a boolean property, how bad is it to quote it (by accident)?
Lastly, another important point that may have directed Vue's designers is that they try to make available to custom directives the very behaviors available on native directives. And all those modifiers/args exist in native directives (e.g. v-bind:address.sync="myAddressProp"). | unknown | |
d13823 | train | According to https://code.google.com/p/chromedriver/issues/detail?id=159 it has something to do with your browser has not yet finished loading a page, while selenium closes and quits the driver. | unknown | |
d13824 | train | You can use itertools.izip for example
g1=([s]*3 for s in string.ascii_lowercase)
g2=([s]*3 for s in string.ascii_uppercase)
g=itertools.izip(g1,g2)
This will ensure the resultant is also a generator.
If you prefer to use the second here is how you can do it
g1=([s]*3 for s in string.ascii_lowercase)
g2=([s]*3 for s in string.ascii_uppercase)
g=(x+y for x,y in itertools.izip(g1,g2))
A: You can get pairs of things (your first request) using zip(g1, g2). You can join them (your second request) by doing [a + b for a, b in zip(g1, g2)].
Almost equivalently, you can use map. Use map(None, g1, g2) to produce a list of pairs, and map(lambda x, y: x + y, g1, g2) to join the pairs together.
In your examples, your generators are producing a list or tuple each time, of which you're only interested in the first element. I'd just generate the thing you need, or preprocess them before zipping or mapping them. For example:
g1 = (g[0] for g in g1)
g2 = (g[0] for g in g2)
Alternatively, you can apply [0] in the map. Here's the two cases:
map(lambda x, y: (x[0], y[0]), g1, g2)
map(lambda x, y: x[0] + y[0], g1, g2)
A: Let's say you have g1 and g2 :
g1 = [
[['a', 'a', 'a'], ['e', 'e'], ['f', 'g']],
[['b', 'b', 'b'], ['e', 'e'], ['f', 'g']],
[['c', 'c', 'c'], ['e', 'e'], ['f', 'g']],
]
g2 = [
[[1, 1, 1], ['t', 'q'], ['h', 't']],
[[2, 2, 2], ['r', 'a'], ['l', 'o']],
[[3, 3, 3], ['x', 'w'], ['z', 'p']],
]
To get that :
[a, a, a],[1, 1, 1]
[b, b, b],[2, 2, 2]
[c, c, c],[3, 3, 3]
You can do that :
result1 = map(lambda a, b: (a[0], b[0]) , g1, g2)
# Which is like this :
[(['a', 'a', 'a'], [1, 1, 1]),
(['b', 'b', 'b'], [2, 2, 2]),
(['c', 'c', 'c'], [3, 3, 3])]
And for the second :
[a, a, a, 1, 1, 1]
[b, b, b, 2, 2, 2]
[c, c, c, 3, 3, 3]
result2 = map(lambda a, b: a[0]+b[0] , g1, g2)
# Which is like that :
[['a', 'a', 'a', 1, 1, 1],
['b', 'b', 'b', 2, 2, 2],
['c', 'c', 'c', 3, 3, 3]]
A: first case: use
for x, y in zip(g1, g2):
print(x[0], y[0])
second case: use
for x, y in zip(g1, g2):
print(x[0] + y[0])
You can of course use itertools.izip for the generator version. You get the generator automatically if you use zip in Python 3 and greater. | unknown | |
d13825 | train | Convert convertForLoopToPromiseAndWait to async method, then you can use await after for keyword and before dataService.addUpdateEndpointCall();
async convertForLoopToPromiseAndWait(someParameterOfTypeObject) {
for await (var test of someParameterOfTypeObject) {
var testVariable = test.setValue;
if (testVariable) {
await dataService.addUpdateEndpointCall();
console.log("Print Before");
}
}
console.log("Print After");
await save.emit();
}
A: Another way is to make a list of promises and wait for them to resolve:
const promises = [];
for await (your iterating condition) {
promises.push(dataService.addUpdateEndpointCall());
}
then use
await Promise.all(promises).then( this.save.emit());
A: I think that you have made a mistake here:
const promise1 = await this.dataService.addCall().take(1).toPromise();
const promise2 = await this.dataService.deleteCall().take(1).toPromise();
You await promises. The results put in the variables promise1 and promise2 will then not be promises.
Don't you mean the following?
async addUpdateEndpointCall() {
const promise1 = this.dataService.addCall().take(1).toPromise();
const promise2 = this.dataService.deleteCall().take(1).toPromise();
await Promise.all([promise1, promise2])
.then(_ => this.save.emit());
} | unknown | |
d13826 | train | There is an algorithm to code and decode a combination into its number in the lexicographical order of all combinations with a given fixed K. The algorithm is linear to N for both code and decode of the combination. What language are you interested in?
EDIT: here is example code in c++(it founds the lexicographical number of a combination in the sequence of all combinations of n elements as opposed to the ones with k elements but is really good starting point):
typedef long long ll;
// Returns the number in the lexicographical order of all combinations of n numbers
// of the provided combination.
ll code(vector<int> a,int n)
{
sort(a.begin(),a.end());
int cur = 0;
int m = a.size();
ll res =0;
for(int i=0;i<a.size();i++)
{
if(a[i] == cur+1)
{
res++;
cur = a[i];
continue;
}
else
{
res++;
int number_of_greater_nums = n - a[i];
for(int j = a[i]-1,increment=1;j>cur;j--,increment++)
res += 1LL << (number_of_greater_nums+increment);
cur = a[i];
}
}
return res;
}
// Takes the lexicographical code of a combination of n numbers and returns the
// combination
vector<int> decode(ll kod, int n)
{
vector<int> res;
int cur = 0;
int left = n; // Out of how many numbers are we left to choose.
while(kod)
{
ll all = 1LL << left;// how many are the total combinations
for(int i=n;i>=0;i--)
{
if(all - (1LL << (n-i+1)) +1 <= kod)
{
res.push_back(i);
left = n-i;
kod -= all - (1LL << (n-i+1)) +1;
break;
}
}
}
return res;
}
I am sorry I have an algorithm for the problem you are asking for right now, but I believe it will be a good exercise to try to understand what I do above. Truth is this is one of the algorithms I teach in the course "Design and analysis of algorithms" and that is why I had it pre-written.
A: This is what you (and I) need:
hash() maps k-tuples from [1..n] onto the set 1..C(n,k)\subset N.
The effort is k subtractions (and O(k) is a lower bound anyway, see Strandjev's remark above):
// bino[n][k] is (n "over" k) = C(n,k) = {n \choose k}
// these are assumed to be precomputed globals
int hash(V a,int n, int k) {// V is assumed to be ordered, a_k<...<a_1
// hash(a_k,..,a_2,a_1) = (n k) - sum_(i=1)^k (n-a_i i)
// ii is "inverse i", runs from left to right
int res = bino[n][k];
int i;
for(unsigned int ii = 0; ii < a.size(); ++ii) {
i = a.size() - ii;
res = res - bino[n-a[ii]][i];
}
return res;
} | unknown | |
d13827 | train | Your best bet is to define a custom model (QAbstractTableModel subclass). You probably want to have a QSqlQueryModel as a member in this custom class.
If it's a read-only model, you need to implement at least these methods:
int rowCount(const QModelIndex &parent) const;
int columnCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
and for well behaved models also
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
If you need the model to be able to edit/submit data, things get a bit more involved and you will also need to implement these methods:
Qt::ItemFlags flags(const QModelIndex &index) const;
bool setData(const QModelIndex &index, const QVariant &value, int role=Qt::EditRole);
bool insertRows(int position, int rows, const QModelIndex &index=QModelIndex());
bool removeRows(int position, int rows, const QModelIndex &index=QModelIndex());
What will actually change a row appearance lies in the return value of this method:
QVariant data(const QModelIndex &index, int role) const;
A dumb example:
QVariant MyCustomModel::data(const QModelIndex &index, int role) const
{
if ( !index.isValid() )
return QVariant();
int row = index.row();
int col = index.column();
switch ( role )
{
case Qt::BackgroundRole:
{
if(somecondition){
// background for this row,col is blue
return QVariant(QBrush (QColor(Qt::blue)));
}
// otherwise background is white
return QVariant(QBrush (QColor(Qt::white)));
}
case Qt::DisplayRole:
{
// return actual content for row,col here, ie. text, numbers
}
case Qt::TextAlignmentRole:
{
if (1==col)
return QVariant ( Qt::AlignVCenter | Qt::AlignLeft );
if (2==col)
return QVariant ( Qt::AlignVCenter | Qt::AlignTrailing );
return QVariant ( Qt::AlignVCenter | Qt::AlignHCenter );
}
}
}
A: The view draws the background based on the Qt::BackgroundRole role of the cell which is the QBrush value returned by QAbstractItemModel::data(index, role) for that role.
You can subclass the QSqlQueryModel to redefine data() to return your calculated color, or if you have Qt > 4.8, you can use a QIdentityProxyModel:
class MyModel : public QIdentityProxyModel
{
QColor calculateColorForRow(int row) const {
...
}
QVariant data(const QModelIndex &index, int role)
{
if (role == Qt::BackgroundRole) {
int row = index.row();
QColor color = calculateColorForRow(row);
return QBrush(color);
}
return QIdentityProxyModel::data(index, role);
}
};
And use that model in the view, with the sql model set as source with QIdentityProxyModel::setSourceModel.
OR
You can keep the model unchanged and modify the background with a delegate set on the view with QAbstractItemView::setItemDelegate:
class BackgroundColorDelegate : public QStyledItemDelegate {
public:
BackgroundColorDelegate(QObject *parent = 0)
: QStyledItemDelegate(parent)
{
}
QColor calculateColorForRow(int row) const;
void initStyleOption(QStyleOptionViewItem *option,
const QModelIndex &index) const
{
QStyledItemDelegate::initStyleOption(option, index);
QStyleOptionViewItemV4 *optionV4 =
qstyleoption_cast<QStyleOptionViewItemV4*>(option);
optionV4->backgroundBrush = QBrush(calculateColorForRow(index.row()));
}
};
As the last method is not always obvious to translate from C++ code, here is the equivalent in python:
def initStyleOption(self, option, index):
super(BackgroundColorDelegate,self).initStyleOption(option, index)
option.backgroundBrush = calculateColorForRow(index.row()) | unknown | |
d13828 | train | You will need to create a page (an extension) within the Directus App using VueJS.
Basic understanding of JavaScript and VueJS would be required, but once you create the page, you can then query as many collections as you wish to create reports.
For more information see:
https://docs.directus.io/extensions/pages.html | unknown | |
d13829 | train | A couple things...
*
*You're doing your drawing in surfaceCreated which is only called when the surface is first created, so there will not be any subsequent calls to this method.
*You should really be creating a custom View in your case. Simply extend View and do your drawing in onDraw. You'll also be given access to methods such as invalidate() which will re-draw your View. | unknown | |
d13830 | train | new Exception().getStackTrace()[0].getMethodName();
A: I'd use one of the logging frameworks (logback with slf4j is probably the best one at the moment, but log4j should suffice), then you can specify a layout that will print the method name logback layout documentation here | unknown | |
d13831 | train | The problem with the way of working in the question is in finding the correct location of RegAsm. Thanks to the comment of Hans Passant to use RegistrationService.RegisterAssembly I changed the ClassLibrary into a self-registering executable.
static void Main(string[] args)
{
if (args.Length != 1)
{
ShowHelpMessage();
return;
}
if (args[0].CompareTo("/register") == 0)
{
Assembly currAssembly = Assembly.GetExecutingAssembly();
var rs = new RegistrationServices();
if (rs.RegisterAssembly(currAssembly, AssemblyRegistrationFlags.SetCodeBase))
{
Console.WriteLine("Succesfully registered " + currAssembly.GetName());
} else
{
Console.WriteLine("Failed to register " + currAssembly.GetName());
}
return;
}
if (args[0].CompareTo("/remove") == 0)
{
Assembly currAssembly = Assembly.GetExecutingAssembly();
var rs = new RegistrationServices();
if (rs.UnregisterAssembly(currAssembly))
{
Console.WriteLine("Succesfully removed " + currAssembly.GetName());
}
else
{
Console.WriteLine("Failed to remove " + currAssembly.GetName());
}
return;
}
ShowHelpMessage();
} | unknown | |
d13832 | train | Assuming the question is kind of stated in your title, the answer is yes, the file wasn't written correctly. But you don't need all this. Change it to implement Serializable instead of Externalizable, and remove the readExternal() and writeExternal() methods. | unknown | |
d13833 | train | You may want to look at this question How to eliminate the flicker on the right edge of TPaintBox (for example when resizing)
Good overview of options to avoid flicker and also for TPanel.
Edit :
I made a quick test in my Delphi XE version on windows 7.
With this code I cannot reproduce any flicker.
The inherited Paint is removed and the Paint routine is quite fast.
If you still can see flicker, the proposal from Simon can be implemented, but better keep the bitmap created for the lifetime of the component itself.
unit MainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls;
type
TGradientPanel = class(TPanel)
protected
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
end;
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
sPanel : TGradientPanel;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
Uses Math;
procedure GradVertical(Canvas:TCanvas; Rect:TRect; FromColor, ToColor:TColor) ;
var
Y:integer;
dr,dg,db:Extended;
C1,C2:TColor;
r1,r2,g1,g2,b1,b2:Byte;
R,G,B:Byte;
cnt:Integer;
begin
C1 := FromColor;
R1 := GetRValue(C1) ;
G1 := GetGValue(C1) ;
B1 := GetBValue(C1) ;
C2 := ToColor;
R2 := GetRValue(C2) ;
G2 := GetGValue(C2) ;
B2 := GetBValue(C2) ;
dr := (R2-R1) / Rect.Bottom-Rect.Top;
dg := (G2-G1) / Rect.Bottom-Rect.Top;
db := (B2-B1) / Rect.Bottom-Rect.Top;
cnt := 0;
for Y := Rect.Top to Rect.Bottom-1 do
begin
R := R1+Ceil(dr*cnt) ;
G := G1+Ceil(dg*cnt) ;
B := B1+Ceil(db*cnt) ;
Canvas.Pen.Color := RGB(R,G,B) ;
Canvas.MoveTo(Rect.Left,Y) ;
Canvas.LineTo(Rect.Right,Y) ;
Inc(cnt) ;
end;
end;
constructor TGradientPanel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Self.ParentBackground := FALSE;
end;
procedure TGradientPanel.Paint;
var
rect : TRect;
begin
//inherited; // Avoid any inherited paint actions as they may clear the panel background
rect := GetClientRect;
GradVertical( Self.Canvas, rect, clBlue, clRed);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
sPanel := TGradientPanel.Create( Self);
sPanel.Parent := Self;
sPanel.Top := 10;
sPanel.Left := 10;
sPanel.Width := 300;
sPanel.Height := 300;
sPanel.Anchors := [akLeft,akRight,akTop,akBottom];
sPanel.Enabled := TRUE;
sPanel.Visible := TRUE;
end;
end.
A: A way to reduce flicker is to draw the gradient to a temporary bitmap the draw the entire contents of the bitmap to the panel. This method assumes you have an OnPaint method and a canvas to draw on in your inherited panel.
So something like this (untested)
var bmp : Tbitmap;
procedure AfterConstruction;
begin
bmp := TBitmap.Create;
end;
procedure Destroy()
begin
if Assigned(bmp) then FreeandNil(bmp);
end;
//redraw you bmp gradient
procedure Panel1.OnResize();
begin
if Assigned(bmp) then //ensure the bmp s created in your constructor
begin
try
bmp.SetBounds(Panel1.Clientrect); //ensure the bmp is the same size as the panel
//draw your gradient on the bmp
Panel1.OnPaint();//repaint the tpanel
finally
bmp.Free;
end;
end;
//paint to the panel
procedure Panel1.OnPaint()
begin
Panel1.Canvas.Draw(0,0,bmp); //use the OnPaint method to draw to the canvas
end;
end;
end; | unknown | |
d13834 | train | console.table() worked perfectly for me. | unknown | |
d13835 | train | I came up with this approach thanks to the comments in my question.
I hope it works and suits your problems.
First, I created a Published Timer, meaning every component will run the same Timer.
import Foundation
import Combine
class UIService : ObservableObject {
static let shared = UIService()
//MARK: Timer to be used for any interested party
@Published var generalTimer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
}
Finally, I am using that Timer wherever I want to use it. In this case, I use it in every LotCard component.
struct LotCard: View {
//MARK: Observable Class
@EnvironmentObject var UISettings: UIService
//MARK: Time for the counting down
@State var timeRemaining = 9999
var body: some View {
HStack{
Text(timeRemaining.toTimeString())
.onReceive(UISettings.generalTimer){ _ in
if self.timeRemaining > 0 {
self.timeRemaining -= 1
}
}
}
}
} | unknown | |
d13836 | train | For these kind of Access FAQs, you should always try the Access Web as a starting point for searching (though the search interface sucks -- it's easier to search the site with Google). That site is the official FAQ site for a number of the non-MS Access newsgroups. It doesn't get updated often, but the code is still quite useful, precisely because it answers questions that are asked frequently.
The code you need is in one of the API modules, helpfully titled Call the standard Windows File Open/Save dialog box
A: That should be "...to write a form application."
There is an unsupported declare not into the Windows API but into msaccess.exe itself. It was first publicized, I believe, in the AccessDeveloper's Handbook. I'm not on my development machine at the moment but I can look it up when I get there. Or, you can probably find it yourself without too much trouble. | unknown | |
d13837 | train | You may use the following perl solution:
echo "foObar" | perl -pe 's/([a-z])(?!\1)(?i:\1)//g'
See the online demo.
Details
*
*([a-z]) - Group 1: a lowercase ASCII letter
*(?!\1) - a negative lookahead that fails the match if the next char is the same as captured with Group 1
*(?i:\1) - the same char as captured with Group 1 but in the different case (due to the lookahead before it).
The -e option allows you to define Perl code to be executed by the compiler and the -p option always prints the contents of $_ each time around the loop. See more here.
A: This might work for you (GNU sed):
sed -r 's/aA|bB|cC|dD|eE|fF|gG|hH|iI|jJ|kK|lL|mM|nN|oO|pP|qQ|rR|sS|tT|uU|vV|wW|xX|yY|zZ//g' file
A programmatic solution:
sed 's/[[:lower:]][[:upper:]]/\n&/g;s/\n\(.\)\1//ig;s/\n//g' file
This marks all pairs of lower-case characters followed by an upper-case character with a preceding newline. Then remove altogether such marker and pairs that match by a back reference irrespective of case. Any other newlines are removed thus leaving pairs untouched that are not the same.
A: Here is a verbose awk solution as OP doesn't have perl or python available:
echo "foObar" |
awk -v ORS= -v FS='' '{
for (i=2; i<=NF; i++) {
if ($(i-1) == tolower($i) && $i ~ /[A-Z]/ && $(i-1) ~ /[a-z]/) {
i++
continue
}
print $(i-1)
}
print $(i-1)
}'
fbar
A: Note: This solution is (unsurprisingly) slow, based on OP's feedback:
"Unfortunately, due to the multiple passes - it makes it rather slow. "
If there is a character sequence¹ that you know won't ever appear in the input,you could use a 3-stage replacement to accomplish this with sed:
echo 'foObar foobAr' | sed -E -e 's/([a-z])([A-Z])/KEYWORD\1\l\2/g' -e 's/KEYWORD(.)\1//g' -e 's/KEYWORD(.)(.)/\1\u\2/g'
gives you: fbar foobAr
Replacement stages explained:
*
*Look for lowercase letters followed by ANY uppercase letter and replace them with both letters as lowercase with the KEYWORD in front of them foObar foobAr -> fKEYWORDoobar fooKEYWORDbar
*Remove KEYWORD followed by two identical characters (both are lowercase now, so the back-reference works) fKEYWORDoobar fooKEYWORDbar -> fbar fooKEYWORDbar
*Strip remaining² KEYWORD from the output and convert the second character after it back to it's original, uppercase version fbar fooKEYWORDbar -> fbar foobAr
¹ In this example I used KEYWORD for demonstration purposes. A single character or at least shorter character sequence would be better/faster. Just make sure to pick something that cannot possibly ever be in the input.
² The remaining occurances are those where the lowercase-versions of the letters were not identical, so we have to revert them back to their original state
A: There's an easy lex for this,
%option main 8bit
#include <ctype.h>
%%
[[:lower:]][[:upper:]] if ( toupper(yytext[0]) != yytext[1] ) ECHO;
(that's a tab before the #include, markdown loses those). Just put that in e.g. that.l and then make that. Easy-peasy lex's are a nice addition to your toolkit. | unknown | |
d13838 | train | Just use TriangularView < SystemMatrixType, Eigen::Lower >. Triangular and Selfadjoint views of dense and sparse expressions have been unified in 3.3. | unknown | |
d13839 | train | First of all, since what you'll be getting through a sequelize query are instances, you need to convert it to "plain" object. You could do that by using a module called sequelize-values.
Then you should be able to manually map the value to the one you're looking for.
model.findAll(query)
.then(function(data){
return data.map(function(d){
var rawValue = d.getValues();
rawValue.type = rawValue.type.name;
return rawValue;
});
})
.then(function(data){
$.data = data;
$.json();
})
.catch(function(err){
console.log(err);
errorHandler.throwStatus(500, $);
}); | unknown | |
d13840 | train | keyword = end="****" sets two variables. keyword = "****" and end = "****". It does not do what you think it does. Your second example prints what it does because it is equivalent to calling print("hi", "****")
To specify arguments without actually writing them in the function call, you can do it by argument unpacking.
You specify positional arguments by unpacking a list like so:
args = ['a', 'b', 'c']
print(*args)
# Output: a b c
Or, for keyword args, you unpack a dict like so:
kwargs = { "end": "****\n" }
print("abc", **kwargs)
Output: abc****
You can even do both:
args = ["hello", "world"]
kwargs = { "sep": "|", "end": "***\n" }
print(*args, **kwargs)
# Equivalent to print("hello", "world", sep="|", end="***\n")
# Output: hello|world***
A: You can't define a variable in a list. Here's how you could make this function work (assuming I read the question right)
keywords = ['spam', "****"]
print("hi", keywords[1])
if you're trying to find a word in a sequence, which is what I'm assuming this is trying to accomplish, you can do so easily by doing the following for loop:
check = "hi"
for item in keywords:
if check.find(item) != -1:
print("keyword found in input") | unknown | |
d13841 | train | Using sed:
s='aaaa ---- bbbb'
echo "$s"|sed 's/--* bb*/foo/'
aaaa foo | unknown | |
d13842 | train | Like so:
$(document).ready(function() {
$("a").click(function(){
var href= $(this).attr("href");
var id = href.substring(href.length - 1)
alert(id)
});
}); | unknown | |
d13843 | train | You can use the index function to get the index/place of the current element inside the parent (and you can use it also based on the tagname)
selectedArchiveLink.parent().index('ul')
Check the example:
http://jsfiddle.net/tg4hc9zr/
A: you might be looking for this. Just add this function to your accordion function call and it will give you the index of h4 tag. Hope this helps.
activate: function(evt, widget ) {
var index = $(this).find("h4").index(widget.newHeader[0]);
}
$("#blog-archive-accordion-year").accordion({
header: "h4",
activate: function(evt, widget ) {
var index = $(this).find("h4").index(widget.newHeader[0]);
}
}); | unknown | |
d13844 | train | They're not used, just like the compiler says. You assign but never read. a and b are used as arguments, the others are not. | unknown | |
d13845 | train | for(int i=random;i<=4;i++) looks suspect: there's no reason to initialise i to the random number picked by the computer.
I think you meant for (int i = 1; i <= 4; i++) instead.
A: You need to put
userinput=Integer.parseInt(br.readLine());
into your for loop if not successful.
else {
userinput=Integer.parseInt(br.readLine());
....
}
also the foor loop should be
for(int i=0; i < 4; i++)
A: There several mistakes in your program:
1. You can not guarantee user inputs a legal number. So, U should judge if br.readLine() is a integer number. The code is:
str = br.readLine();
while(!str.matches("[0-9]+")) {
System.out.println("Input Format Error!! Please Re. input:");
str = br.readLine();
}
userinput = Integer.parseInt(str);
2. The for loop should be coded as below if you wanna tried only 4 times:
for(i = 1 ; i <= 4 ; i++)
3. In the for loop, you should have interface for Re. input when the answer is wrong.
str = br.readLine();
while(!str.matches("[0-9]+")) {
System.out.println("Input Format Error!! Please Re. input:");
str = br.readLine();
}
userinput = Integer.parseInt(str);
4. if you wanna loop this process for many times, you should put all codes in a while(true){...} loop.
A: you have to look to "random" variable !!
you initialised it like :
int random = (int )(Math.random() * 10 + 1);
sometimes it is >4 , that's the problem caused on the For iterator
A: Here are my suggestion:
1.Read user input in each try.(BufferedReader with in the loop)
2.If user win break the loop.
3.Loop should be run 4 times only,
for (int i = 1; i <= 4; i++) | unknown | |
d13846 | train | this will be csv file and as you aware that it is to big.
if you are in local server you can change in .ini file and increase the limit for uploading file and if you are using web server add in .htaccess file
in the .htcaccess file add the following:
php_value upload_max_filesize 500M
php_value post_max_size 500M
in php.ini add:
upload_max_filesize = 500M
post_max_size = 500M
or you can split your csv file | unknown | |
d13847 | train | You're describing the basic usage of random.sample.
>>> colours = ["Red","Yellow","Blue","Green","Orange","White"]
>>> random.sample(colours, 4)
['Red', 'Blue', 'Yellow', 'Orange']
If you want to allow duplicates, use random.choices instead (new in Python 3.6).
>>> random.choices(colours, k=4)
['Green', 'White', 'White', 'Red']
A: To fix your original code, do
current.append(random.choice(colours))
instead of
current = random.choice(colours)
You should also make current a local variable and return it rather than a global variable. In the same light, you should pass the array of choices as a parameter rather than working on a global variable directory. Both of these changes will give your function greater flexibility. | unknown | |
d13848 | train | You can use ACF function update_field($selector, $value, $post_id); to set the value of a specific field.
More info here: https://www.advancedcustomfields.com/resources/update_field/ | unknown | |
d13849 | train | A foreign key constraint is from one table's columns to another's columns, so, no.
Of course the database should have a table COUNTRY(country_id). Commenters have pointed out that your admin is imposing an anti-pattern.
Good, you are aware that you can define a column and set it to the value you want and make the foreign key on that. That is an idiom used for avoiding triggers in constraining some subtyping schemes.
You may be able to compute a 'COUNTRY' column depending on your DBMS, at least.
Your question is essentially this one, see the end of the question & the comments & answers.
(Lots of functionality would be trivial to implement. Perhaps the difficulty (besides ignorance of consumers) is that arbitrary constraints become quickly expensive computationally. That might just get vendors aggravation. Also, optimization in SQL is impeded by its differences from the relatonal model.)
A: For Posrgres not having computed (or constant) columns, you can force them to a fixed value column, using DEFAULT plus (maybe) a check. This may be ugly, but it works:
CREATE TABLE dictionaries
( id integer primary key
, typename varchar NOT NULL CHECK ( typename IN ('person' ,'animal' ,'plant' ))
, content varchar NOT NULL
-- ...
, UNIQUE (typename, id)
, UNIQUE (typename, content)
);
CREATE TABLE person
( id integer primary key
, typename varchar NOT NULL DEFAULT 'person' CHECK( typename IN ('person' ))
, species_id integer
-- ...
, FOREIGN KEY (typename, species_id) REFERENCES dictionaries(typename, id) -- DEFERRABLE INITIALLY DEFERRED
);
INSERT INTO dictionaries( id, typename, content) VALUES
( 1 , 'person' , 'Bob')
,( 2 , 'person' , 'Alice')
,( 11 , 'animal' , 'monkey')
,( 12 , 'animal' , 'cat')
,( 13 , 'animal' , 'dog')
,( 21 , 'plant' , 'cabbage')
;
SELECT * FROM dictionaries;
-- this should succeed
INSERT INTO person( id, species_id) VALUES
( 1,1 )
,( 2,2 )
;
-- this should fail
INSERT INTO person( id, species_id) VALUES
( 3,11 )
,( 4,12 )
; | unknown | |
d13850 | train | Because doing this.changeName(book) will instantly call the function when rendering. And what your function returns is.. not a function, so when you click, nothing will happen.
And () => this.changeColor(book) is an arrow function, it has a similar (but not really) behavior as this syntax :
() => { this.changeColor(book) }
To avoid this, you could use your first code example or transform your function into a curried one and keep the second syntax in the render :
changeName = bookInfo => event => {
/* Your code here */
}
When called once in the render, this function will return another function receiving the event and set the bookInfo first. | unknown | |
d13851 | train | You can do this with javascript:
document.querySelector('source[type="application/x-mpegurl"]').src | unknown | |
d13852 | train | I think there are two issues with your example.
The first issue is with the request to the <Group>. You need to distinguish between requests to the <Group> resource itself and requests to the members of the <Grou>.
There is no child resource <la> of the <Group> resource itself. This is why you receive an error message. If you want to pass a request to all members of a <Group> resource then you need to target the virtual child resource <fopt>. In your case the request should target URI https://localhost:7579/Mobius/grp_text_100520/fopt. Since you already have the <la> resources as members you won't need to add the /la part to the request. However, I would recommend to only add the <Container> resources to the group and use the target URI https://localhost:7579/Mobius/grp_text_100520/fopt/la to retrieve the latest <ContentInstances> of each container.
The second (smaller) issue is that from what I can get from your example code that you add the same resource multiple times to the group, but only with different addressing schemes. Please be aware that the CSE must removes duplicate resources when creating or updating the mid attribute.
Edit after question update
It is not very clear what your resource tree looks like. So, perhaps you should start with only one resource references and continue from there. Valid ID's in the mid attribute are either structured (basically the path of the rn attributes) or unstructured ID's (the ri's). The CSE should filter the incorrect ID, so you should get the correct set of ID's in the result body of the CREATE request.
btw, where does "thyme" come from? This is only in a label, which does not form an ID.
Regarding the <fanOutPoint> resource: Normally all request would be targeted to the <Group> resource, but requests to the virtual <fanOuPoint> resource are forwarded to al the members of the group. If a resource referenced in mid is accessible then the request is forwarded and the result is collected and is part of the result body of the original request.
You also need to be careful and regard the resource types: only send valid requests to the group's members.
Update 2
From the IDs in the mid attribute of the <Group> resource it looks like that the CSE validated the targets (though the cnm (current number of members) is obviously wrong, which seems to be an error of the CSE).
So, you should be able to send requests to the group's <fopt> resource as discussed above.
For the CSE runtime error you should perhaps contact the Mobius developers. But my guess is that you perhaps should download and install the whole distribution, not only a single file.
A: for anyone in the future; who is dealing with this problem.
The problem is simply is that; in the app.js there is 4 function call (fopt.check). While calling the function in the app.js file, there are 5 parameter exists, on the other hand, while getting these arguments in the function it takes only 4 arguments. For this reason, body_obj always becomes "undefined" then it will never reach the "Container" or "ContainerInstance" source. Lately, KETI was sent a new commit to the Mobius Github page (https://github.com/IoTKETI/Mobius/commit/950182b725d5ffc0552119c5c705062958db285f) to solve this problem. It solves this problem unless you are using use_secure == 'disable'. If you try to use use_secure == 'enable' you should add an if statement to check use_secure and add import HTTPS module.
Also, while creating resource, defining the "mid" attribute is not very clear. Just for now, if you want to reach (latest) source; you should add "/la" for all members of the group. This is recommended by KETI on Github page issue 5.
(https://github.com/IoTKETI/Mobius/issues/5#issuecomment-625076540)
And lastly, thank you Andreas Kraft; your help was very useful. | unknown | |
d13853 | train | Closure, here is my solution:
handler_new = func(c *gin.Context){ return PreExecute(c, handler_old)(c) } // since there is no return value of handler, so just do not use `return` statements, I will not correct this error
and then handler_new can be used as:
handler_new(some_context)
It's the same as
handler_new = std::bind(PreExecute, _1, handler_old)
in C++ | unknown | |
d13854 | train | Second one.
http://datacharmer.blogspot.com/2009/03/normalization-and-smoking.html
[edited after updates to question]
In second case you can create an index on columns (x_id,date) which will improve performance of WHERE x_id = ? AND date = ? searches. Some ~550000 rows is not much for well indexed table.
A: Assuming that all the relationships in the data are one-to-one, then the second option of using a single table is the better (normalized) approach.
But there's no detail to the multi-table option, or the data that is being stored. Bad design, like a table per user, is responsible for performance - not the fact of numerous tables.
Update
Things are still quite vague, but the data you want to store is daily and over the course of years. What makes it different that you would consider separate tables with identical formats? The identical tables prompts me to suggest single main table, with some supporting tables involved for things like status and/or type codes to differentiate between records in a single table that were obvious in a separate table approach.
A: That depend on the engine you are using and also if you are going to have more read or more write.
For that look at the way each engine lock the table regarding read and write.
But 1500 table is a lot. I would expect something like 10 table.
1 table is not a bad choice either but if one day you want to have multiple server it gonna be more easy to spread them with 10 table.
Also if you change the structure of the table is going to be long with 1 table. (I know that it shouldn't append but the fact it does) | unknown | |
d13855 | train | Usually, you set your theme in the manifest, as shown in the Android developer documentation (and linked to from the ActionBarSherlock theming page).
If you want to use ActionBarSherlock everywhere within your app, this works:
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Theme.Sherlock">
A: <!--Provides resources-->
<dependency>
<groupId>com.actionbarsherlock</groupId>
<artifactId>library</artifactId>
<version>4.1.0</version>
<type>apklib</type>
</dependency>
<!-Provides import links-->
<dependency>
<groupId>com.actionbarsherlock</groupId>
<artifactId>library</artifactId>
<version>4.1.0</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
The hint is to use type "apklib", that's mean that maven will be using all sources (resources too). Other dependecy to jar file (scope "provided") is used to achieve link to sherlock classes during coding.
A: For me this was caused by not using the @style/ prefix. I.e. I had
<style name="AppTheme" parent="Theme.Sherlock.Light" />
instead of
<style name="AppTheme" parent="@style/Theme.Sherlock.Light" />
Which is kind of weird because I swear the default template value is something like:
<style name="AppTheme" parent="android:Theme.Holo.Light" />
A: If you wanna use custom style, I made a template for custom ActionBarSherlock style. Theme is defined in /values/styles.xml file. It is extended from Theme.Sherlock.Light theme. There are many parameters, you can set: icon, logo, divider, title, shadow overlay, action menu buttons, popup menu, action mode background, dropdown list navigation, tab style, display options etc. Almost everything, what you need, to create your custom action bar theme. I use this template in my apps, because it helps me to style action bar very quickly.
You can find this template on my GitHub. It is very easy to use. Just copy values and drawable directiories into your project and set android:theme parameter in application element in AndroidManifest.xml:
<application
...
android:theme="@style/Theme.Example">
Drawables in my template were generated via Android Action Bar Style Generator. I use different naming convention for resources. This simple script renames all resources generated with Android Action Bar Style Generator to my own convention, used in the template.
A: Had the same problem. The app crashed altough the theme was set in the manifest. Setting the theme programmatically solved the problem:
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.AppTheme);
super.onCreate(savedInstanceState);
A: This was happening to me in IntelliJ IDEA. I solved this issue by going to File > Project Structure > Project Settings > Facets > Select actionbarsherlock module in 2nd column > Check the "Library module" checkbox > Apply and OK > Save and Rebuild.
UPDATE After further review, my original response may be too specific, and will probably only work in certain cases. This error means that the dependencies have not been properly setup. In IntelliJ IDEA, follow these steps to properly setup actionbarsherlock as a module dependency:
*
*Download and extract the actionbarsherlock library from the zip (Note: You only need the “actionbarsherlock” folder)
*Copy and paste it alongside your Android project
*Open your project in IntelliJ
*File > Project Structure > Project Settings > Modules > Add (green ‘+’ above second column) > Import Module > Select actionbarsherlock directory in file browser dialog > OK > Create module from existing sources > Next
*Uncheck the “test” folder so it is not added to the project and click “Next”
*Under the Libraries tab, android-support-v4 should be checked, click “Next”
*Under the Modules tab, actionbarsherlock should be checked, click “Next”
*If it asks you to Overwrite actionbarsherlock.iml, choose “Overwrite” and then "Finish" (You should be returned to the Modules section of the Project Structure dialog)
*Select the actionbarsherlock module from the second colum and under the Dependencies tab in the third column, check “Export” next to the android-support-v4 library
*Almost there!
*Now select your project module from the second column, and under the Dependencies tab, click the Add button (green ‘+’ on the far right side of the dialog)
*Select Module Dependency and choose actionbarsherlock from the dialog that pops up and press “OK”
*Now click “Apply” or “OK” to accept the changes
That should do the trick.
A: This is not an answer for the OP's question, but I'll just describe how I managed to get the same exception as he mentions, in the hopes it may help someone else:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.Merlinia.MMessaging_Test/com.Merlinia.MMessaging_Test.TestObjectsActivity}:
java.lang.IllegalStateException: You must use Theme.Sherlock, Theme.Sherlock.Light, Theme.Sherlock.Light.DarkActionBar, or a derivative.
In my case the solution was very simple, although it took me way too long to find it. Everything you read about this exception says "check that you've specified the theme in the manifest.xml file", so I took a quick look at my manifest.xml file, and there it was. So then I tried various other things.
Finally, I took a closer look at my manifest.xml file. I'd made the mistake of specifying the theme for the main activity, not for the whole application! | unknown | |
d13856 | train | That is surely strange. Have you tried restarting Xcode? Xcode has a habit of not indexing symbols for me when I add new files.
You should also look into how your naming conventions. SendSMS is not really a good class name, more of a action method name. I would go for SendSMSViewController, since that is what it is.
By that it would follow that SMSProtocol should be named SendSMSViewControllerDelegate, since that is what it is.
Methods in a delegate protocol should contain the sender and one of the three words will, did, or should. If not at the very least it should name what it expects to return. -(NSString *)postbackType; should probably be -(NSString *)postbackTypeForSendSMSViewController:(SendSMSViewController*)controller;. | unknown | |
d13857 | train | PHP function stripslashes will work for you.
Example:
<?php
$str = "Is your name O\'reilly?";
echo stripslashes($str);
?>
Output
Is your name O'reilly?
Usage in your code:
foreach($row as $value) {
$line .= $comma . '"' . str_replace('"', '""', stripslashes($value)) . '"';
$comma = ",";
} | unknown | |
d13858 | train | The suid bit works only on binary executable programs, not on shell scripts. You can find more info here: https://unix.stackexchange.com/questions/364/allow-setuid-on-shell-scripts | unknown | |
d13859 | train | You probably need to change the column datatype from integer to varchar first, then update that row:
update `log` set `Station` = CONCAT('Arbeitsplatz ', `Station`);
But first, back up that table just in case something fails... | unknown | |
d13860 | train | If you can implement Facebook Graph API to login to your Facebook App in Laravel then you can post to Facebook Groups that you manage.
You can obtain Facebook Group IDs that you manage using the following Facebook Graph API(See Reading):
https://developers.facebook.com/docs/graph-api/reference/user/groups/
Once you have Facebook Group IDs that you manage, you can post on your groups by using the following Facebook Graph API (See Publishing):
https://developers.facebook.com/docs/graph-api/reference/v3.1/group/feed | unknown | |
d13861 | train | *
*You don't want Date$ because the $ means "This is the very end of the string."
*Since your examples show that the unwanted strings containing "Date" have it appearing right before </li>, you want to put your negative lookaround right there, not earlier.
*Now, since you want to be looking backward to find Date, you want a lookbehind, not a lookahead. (add < in the middle of your ?!)
This ends up looking like:
<li class="rcbItem">([^:()]{1,20})(?<!Date)<\/li>
If you're also trying to remove "Today" entries, then make it Today|Date:
<li class="rcbItem">([^:()]{1,20})(?<!Today|Date)<\/li>
P.S.: Do you really need to check for all that whitespace at the beginning?
A: As the location of 'Date' or 'Today' is not fixed,
so here is my suggestion:
string[] filter = {"date","today"};
var result = Regex.Matches(yourhtml,"(?i) <li class=\"rcbItem\">([^:()]{1,20})<\/li>")
.Cast<Match>()
.Where(m=>!filter.Any(f=>m.Groups[1].Value.ToLower().Contains(f)));
A: You cannot use the $ because it indicates the end of the entire string.
Try this one:
<li class="rcbItem">((?!(.)*(Date|Today))[^:()]{1,20})<\/li> | unknown | |
d13862 | train | You can use a list comprehension to compute the averages
>>> AverageTemp = [[i[0], sum(i[1:])/len(i[1:])] for i in temperature]
>>> AverageTemp
[['Jan', 16.0], ['Feb', 32.5], ['Mar', 24.25]]
Or if you have numpy
>>> import numpy as np
>>> AverageTemp = [[i[0], np.mean(i[1:])] for i in temperature]
>>> AverageTemp
[['Jan', 16.0], ['Feb', 32.5], ['Mar', 24.25]]
Then to sort you can use the key and reverse arguments
>>> AverageTemp = sorted([[i[0], np.mean(i[1:])] for i in temperature], key = lambda i: i[1], reverse = True)
>>> AverageTemp
[['Feb', 32.5], ['Mar', 24.25], ['Jan', 16.0]]
A: You can use a list comprehension within sorted function :
>>> from operator import itemgetter
>>> sorted([[l[0],sum(l[1:])/4]for l in temperature],key=itemgetter(1),reverse=True)
[['Feb', 32], ['Mar', 24], ['Jan', 16]]
In preceding code you first loop over your list then get the first element and the avg of the rest by [l[0],sum(l[1:])/4] and use operator.itemgetter as the key of your sorted function to sort your result based on the second item (the average)
A: Understanding more about list comprehension and slice notation will really help you do this simply with pythonic code.
To explain @CoryKramer's first answer:
>>> AverageTemp = [[i[0], sum(i[1:4])/len(i[1:4])] for i in temperature]
>>> AverageTemp
[['Jan', 15], ['Feb', 26], ['Mar', 21]]
What he is doing is using i to cycle through the lists in temperature (which is a list of lists) and then using slice notation to get the info you need. So, obviously i[0] is your month, but the notation sum(i[1:4]) gets the sum of the items in the list from index 1 to the 3 using slice notation. He then divides by the length and creates the list of lists AverageTemp with the information you need.
Note: I have edited his answer to not include the high temperature twice per the comment from @TigerhawkT3.
A: That's not a very good structure for the given data: you have differentiated items (name of a month, temperatures, maximum temperature) as undifferentiated list elements. I would recommend dictionaries or objects.
months = {"Jan":[12, 18, 16], "Feb":[10, 20, 50], "Mar":[23, 32, 10]}
for month in sorted(months, key=lambda x: sum(months.get(x))/len(months.get(x)), reverse=True):
temps = months.get(month)
print(month, max(temps), sum(temps)/len(temps))
Result:
Feb 50 26.666666666666668
Mar 32 21.666666666666668
Jan 18 15.333333333333334
class Month:
def __init__(self, name, *temps):
self.name = name
self.temps = temps
def average(self):
return sum(self.temps)/len(self.temps)
def maximum(self):
return max(self.temps)
months = [Month('Jan', 12, 18, 16), Month('Feb', 10, 20, 50), Month('Mar', 23, 32, 10)]
for month in sorted(months, key=lambda x: x.average(), reverse=True):
print(month.name, month.maximum(), month.average())
Result:
Feb 50 26.666666666666668
Mar 32 21.666666666666668
Jan 18 15.333333333333334 | unknown | |
d13863 | train | The format %VAR% doesn't work in VBA, you need to Environ("VAR")
That said username doesn't return a value with that method, but you can use VBA.Environ("Username") in this case:
Dim strScript, strUserName, strFile As String
Dim objFSO, objFile as Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
strScript = ("test" & vbCrLf & "2nd line?")
strUserName = VBA.Environ("Username")
strFile = "C:\Users\" & strUserName & "\Documents\Access.ps1"
Set objFile = objFSO.CreateTextFile(strFile)
objFile.WriteLine strScript
objFile.Close
Set objFSO = Nothing
Set objFile = Nothing | unknown | |
d13864 | train | Well, your machine has 2 cores and 4 threads.
You only have 2 cores, so you won't get 4x speedup from 1 - 4 threads.
Secondly, as you scale to more threads, you will likely start hitting resource contention such as maxing out your memory bandwidth. | unknown | |
d13865 | train | You can copy paste run full code below
Because your json string produce a List<ProductResponse> not ProductResponse
In your code you can directly return response.body as String and parse with productsResponseFromJson
code snippet
List<ProductsResponse> productsResponseFromJson(String str) =>
List<ProductsResponse>.from(
json.decode(str).map((x) => ProductsResponse.fromJson(x)));
Future<List<ProductsResponse>> fetchProducts() async {
ApiProvider _provider = ApiProvider();
String response = await _provider.getFromApi("products");
// here line 11 where exception is thrown
return productsResponseFromJson(response);
//return ProductsResponse.fromJson(response);
}
Future<String> getFromApi(String url) async {
String _response(http.Response response) {
switch (response.statusCode) {
case 200:
print(response.body);
//var responseJson = jsonDecode(response.body);
//print(responseJson);
return response.body;
working demo
full code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
// To parse this JSON data, do
//
// final productsResponse = productsResponseFromJson(jsonString);
import 'dart:convert';
List<ProductsResponse> productsResponseFromJson(String str) =>
List<ProductsResponse>.from(
json.decode(str).map((x) => ProductsResponse.fromJson(x)));
String productsResponseToJson(List<ProductsResponse> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class ProductsResponse {
int id;
Tenant tenant;
ExternalSystem type;
ExternalSystem subType;
ExternalSystem inventoryType;
String externalReference;
ExternalSystem externalSystem;
bool active;
int durationDays;
int durationNights;
int durationHours;
int durationMinutes;
Supplier supplier;
dynamic group;
dynamic subGroup;
String name;
List<Translation> translations;
String vatPercentage;
dynamic longitude;
dynamic latitude;
dynamic departureTime;
dynamic arrivalTime;
int arrivalDayPlus;
int stars;
List<Locality> localities;
ProductsResponse({
this.id,
this.tenant,
this.type,
this.subType,
this.inventoryType,
this.externalReference,
this.externalSystem,
this.active,
this.durationDays,
this.durationNights,
this.durationHours,
this.durationMinutes,
this.supplier,
this.group,
this.subGroup,
this.name,
this.translations,
this.vatPercentage,
this.longitude,
this.latitude,
this.departureTime,
this.arrivalTime,
this.arrivalDayPlus,
this.stars,
this.localities,
});
factory ProductsResponse.fromJson(Map<String, dynamic> json) =>
ProductsResponse(
id: json["id"],
tenant: Tenant.fromJson(json["tenant"]),
type: ExternalSystem.fromJson(json["type"]),
subType: ExternalSystem.fromJson(json["subType"]),
inventoryType: ExternalSystem.fromJson(json["inventoryType"]),
externalReference: json["externalReference"],
externalSystem: ExternalSystem.fromJson(json["externalSystem"]),
active: json["active"],
durationDays: json["durationDays"],
durationNights: json["durationNights"],
durationHours: json["durationHours"],
durationMinutes: json["durationMinutes"],
supplier: Supplier.fromJson(json["supplier"]),
group: json["group"],
subGroup: json["subGroup"],
name: json["name"],
translations: List<Translation>.from(
json["translations"].map((x) => Translation.fromJson(x))),
vatPercentage: json["vatPercentage"],
longitude: json["longitude"],
latitude: json["latitude"],
departureTime: json["departureTime"],
arrivalTime: json["arrivalTime"],
arrivalDayPlus: json["arrivalDayPlus"],
stars: json["stars"],
localities: List<Locality>.from(
json["localities"].map((x) => Locality.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id": id,
"tenant": tenant.toJson(),
"type": type.toJson(),
"subType": subType.toJson(),
"inventoryType": inventoryType.toJson(),
"externalReference": externalReference,
"externalSystem": externalSystem.toJson(),
"active": active,
"durationDays": durationDays,
"durationNights": durationNights,
"durationHours": durationHours,
"durationMinutes": durationMinutes,
"supplier": supplier.toJson(),
"group": group,
"subGroup": subGroup,
"name": name,
"translations": List<dynamic>.from(translations.map((x) => x.toJson())),
"vatPercentage": vatPercentage,
"longitude": longitude,
"latitude": latitude,
"departureTime": departureTime,
"arrivalTime": arrivalTime,
"arrivalDayPlus": arrivalDayPlus,
"stars": stars,
"localities": List<dynamic>.from(localities.map((x) => x.toJson())),
};
}
class ExternalSystem {
String code;
String name;
ExternalSystem({
this.code,
this.name,
});
factory ExternalSystem.fromJson(Map<String, dynamic> json) => ExternalSystem(
code: json["code"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"code": code,
"name": name,
};
}
class Locality {
int id;
Tenant locality;
ExternalSystem role;
Locality({
this.id,
this.locality,
this.role,
});
factory Locality.fromJson(Map<String, dynamic> json) => Locality(
id: json["id"],
locality: Tenant.fromJson(json["locality"]),
role: ExternalSystem.fromJson(json["role"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"locality": locality.toJson(),
"role": role.toJson(),
};
}
class Tenant {
int id;
String code;
String name;
Tenant({
this.id,
this.code,
this.name,
});
factory Tenant.fromJson(Map<String, dynamic> json) => Tenant(
id: json["id"],
code: json["code"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id,
"code": code,
"name": name,
};
}
class Supplier {
int id;
Tenant tenant;
String name;
Supplier({
this.id,
this.tenant,
this.name,
});
factory Supplier.fromJson(Map<String, dynamic> json) => Supplier(
id: json["id"],
tenant: Tenant.fromJson(json["tenant"]),
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id,
"tenant": tenant.toJson(),
"name": name,
};
}
class Translation {
int id;
String name;
String locale;
Translation({
this.id,
this.name,
this.locale,
});
factory Translation.fromJson(Map<String, dynamic> json) => Translation(
id: json["id"],
name: json["name"],
locale: json["locale"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"locale": locale,
};
}
void main() {
runApp(MyApp());
}
Future<List<ProductsResponse>> fetchProducts() async {
ApiProvider _provider = ApiProvider();
String response = await _provider.getFromApi("products");
// here line 11 where exception is thrown
return productsResponseFromJson(response);
//return ProductsResponse.fromJson(response);
}
class ApiProvider {
Future<String> getFromApi(String url) async {
var responseJson;
try {
//final response = await http.get(Uri.encodeFull(_baseApiUrl + url),headers:{"Accept":"application/json"} );
String jsonString = '''
[
{
"id":1,
"tenant":{
"id":1,
"code":"company",
"name":"company"
},
"type":{
"code":"activity",
"name":"Activité"
},
"subType":{
"code":"ticket",
"name":"Ticket"
},
"inventoryType":{
"code":"external_source",
"name":"Source externe"
},
"externalReference":"CAL6970",
"externalSystem":{
"code":"koedia",
"name":"Koedia"
},
"active":true,
"durationDays":12,
"durationNights":14,
"durationHours":9,
"durationMinutes":10,
"supplier":{
"id":1,
"tenant":{
"id":1,
"code":"company",
"name":"company"
},
"name":"Jancarthier"
},
"group":null,
"subGroup":null,
"name":"Hôtel Koulnoué Village",
"translations":[
{
"id":1,
"name":"Hôtel Koulnoué Village",
"locale":"fr"
},
{
"id":24,
"name":"Hôtel Koulnoué Village",
"locale":"en"
}
],
"vatPercentage":"0.00",
"longitude":null,
"latitude":null,
"departureTime":null,
"arrivalTime":null,
"arrivalDayPlus":1,
"stars":4,
"localities":[
{
"id":41,
"locality":{
"id":34,
"code":"ARM",
"name":"Armenia"
},
"role":{
"code":"stop",
"name":"Escale"
}
},
{
"id":49,
"locality":{
"id":55,
"code":"hossegor",
"name":"Hossegor"
},
"role":{
"code":"drop_off",
"name":"Retour"
}
},
{
"id":50,
"locality":{
"id":55,
"code":"hossegor",
"name":"Hossegor"
},
"role":{
"code":"localisation",
"name":"Localisation"
}
}
]
}
]
''';
http.Response response = http.Response(jsonString, 200);
print(response);
responseJson = _response(response);
} on Exception {
//throw FetchDataException('No Internet connection');
}
return responseJson;
}
String _response(http.Response response) {
switch (response.statusCode) {
case 200:
print(response.body);
//var responseJson = jsonDecode(response.body);
//print(responseJson);
return response.body;
/* case 400:
throw BadRequestException(response.body.toString());
case 401:
case 403:
throw UnauthorisedException(response.body.toString());
case 500:
default:
throw FetchDataException(
'Error occured while Communication with Server with StatusCode : ${response.statusCode}');*/
}
}
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
List<ProductsResponse> productResponseList;
void _incrementCounter() async {
productResponseList = await fetchProducts();
print('${productResponseList[0].inventoryType}');
setState(() {
_counter++;
});
}
@override
void initState() {
// TODO: implement initState
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
productResponseList == null
? CircularProgressIndicator()
: Text('${productResponseList[0].inventoryType.name}'),
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
} | unknown | |
d13866 | train | Change your dir.conf file :
<IfModule mod_dir.c>
DirectoryIndex index.html index.cgi index.pl index.php index.xhtml index.htm
</IfModule> | unknown | |
d13867 | train | You can set position: absolute or change display value to block-level (because a is inline by default) for transform to work.
a {
text-decoration: none;
display: block; /* Or inline-block */
animation: vibrate 1s linear infinite both;
}
@keyframes vibrate {
0% { transform: translate(0); }
20% { transform: translate(-2px, 2px); }
40% { transform: translate(-2px, -2px); }
60% { transform: translate(2px, 2px); }
80% { transform: translate(2px, -2px); }
100% { transform: translate(0); }
}
<a href="mailto:[email protected]" id="cta">Drop me a line and let’s do cool things together!</a>
A: The CSS animation is not used to target anchor.
so please use div for easy animation effects
<!DOCTYPE html>
<html>
<head>
<style>
.div {
text-decoration: none;
position:relative;
animation:vibrate 1s linear infinite both;
}
@keyframes vibrate {
0% {
transform: translate(0,0);
}
20% {
transform: translate(-2px, 2px);
}
40% {
transform: translate(-2px, -2px);
}
60% {
transform: translate(2px, 2px);
}
80% {
transform: translate(2px, -2px);
}
100% {
transform: translate(0);
}
}
</style>
</head>
<body>
<div class="div">
<a href="mailto:[email protected]" id="cta">Drop me a line and let’s do cool things together!</a>
</div>
</body>
</html> | unknown | |
d13868 | train | you can try this,
public static final String DEFAULT_STORAGE_LOCATION = "/sdcard/AudioRecording";
File dir = new File(DEFAULT_STORAGE_LOCATION);
if (!dir.exists()) {
try {
dir.mkdirs();
} catch (Exception e) {
Log.e("CallRecorder", "RecordService::makeOutputFile unable to create directory " + dir + ": " + e);
Toast t = Toast.makeText(getApplicationContext(), "CallRecorder was unable to create the directory " + dir + " to store recordings: " + e, Toast.LENGTH_LONG);
t.show();
return null;
}
} else {
if (!dir.canWrite()) {
Log.e(TAG, "RecordService::makeOutputFile does not have write permission for directory: " + dir);
Toast t = Toast.makeText(getApplicationContext(), "CallRecorder does not have write permission for the directory directory " + dir + " to store recordings", Toast.LENGTH_LONG);
t.show();
return null;
}
*you can get the sd card location by querying the system as,
Environment.getExternalStorageDirectory();
and don't forget to add the user permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> | unknown | |
d13869 | train | I think there can't be such a method because the name of the device is likely to be ambigious.
E.g. all BLE beacons from estimote are called 'Estimote' and so this name is not unique but the mac adresss is.
If you are sure that all device names are unique, you could use a map to store device names and macs. | unknown | |
d13870 | train | You mean something like this:
// In some headerfile:
class X
{
private:
static const MyStruct MY_STRUCTS[];
};
// in some .cpp file:
const X::MyStruct MY_STRUCTS[] = { { {"Hello"}, 1}, { "Other String"} , 3 } };
That assumes, however, that you have a char *str;, since char **str; requires a secondary variable to take the address off. Or, you could use std::vector<string>, and that would solve the problem.
A: Sure, you'd write it like this:
#include <string>
#include <vector>
struct MYStruct
{
std::vector<std::string> str;
int num;
};
MyStruct const data[] = { { { "Hello", "World" }, 1 }
, { { "my other string" }, 3 }
};
Unless I'm misunderstanding and you actually just want num to count the number of elements. Then you should just have:
std::vector<std::string> data[] = { { "Hello" }
, { "my", "other", "string" }
};
And you can recover the element sizes with data[0].size(), data[1].size(), etc.
If everything is determined statically and you just want a compact reference, you still need to provide storage, but everything is virtually the same as in C:
namespace // internal linkage
{
char const * a0[] = { "Hello" };
char const * a1[] = { "my", "other", "string" };
// ...
}
struct Foo
{
char const ** data;
std::size_t len;
};
Foo foo[] = { { a0, 1 }, { a1, 3 } };
Since the size is std::distance(std::begin(a0), std::end(a0)), you could simplify the last part with a macro that just takes a0 as an argument. And instead of handwriting Foo, you might just use std::pair<char const **, std::size_t>.
A: You can use something like
class foo {
MyStruct array[2];
public:
foo()
: array{ { "a", 1 }, { "b", 2 }}
{
}
};
assuming you struct's first member is actually char const* rather than char** as you initialization example suggests. | unknown | |
d13871 | train | You can't write a function that does an async call and then returns the results as the function result. That's not how async code works. Your function queues up the async dataTaskWithURL request, and then returns before it has even had a chance to send the request, much less receive the results.
You have to rewrite your get() function to be a void function (no result returned) but take a completion block. Then, in your data task's completion handler you get the data from the jsonArray and call the get() function's completion block, passing it the jsonArray.
See this project I posted on Github that illustrates what I'm talking about:
SwiftCompletionHandlers on Github | unknown | |
d13872 | train | As you have mentioned in your comments, you have an issue in your tryLocalSignin method. In that method, if there is no any token, you are navigating the user to the Signup screen. Instead of navigating to the Signup screen, navigate to the WelcomeScreen screen like:
const tryLocalSignin = (dispatch) => async () => {
const token = await AsyncStorage.getItem("token");
if (token) {
dispatch({ type: "signin", payload: token });
navigate("Main");
} else {
navigate("WelcomeScreen");
}
}; | unknown | |
d13873 | train | You can use the border-image css property. More info here
DEMO
#borderimg1 {
border: 10px solid transparent;
padding: 15px;
-webkit-border-image: url(https://www.w3schools.com/cssref/border.png) 30 round;
-o-border-image: url(https://www.w3schools.com/cssref/border.png) 30 round;
border-image: url(https://www.w3schools.com/cssref/border.png) 30 round;
}
#borderimg2 {
border: 10px solid transparent;
padding: 15px;
-webkit-border-image: url(https://www.w3schools.com/cssref/border.png) 30 stretch;
-o-border-image: url(https://www.w3schools.com/cssref/border.png) 30 stretch;
border-image: url(https://www.w3schools.com/cssref/border.png) 30 stretch;
}
<p id="borderimg1">Here, the image tiles to fill the area. The image is rescaled if necessary, to avoid dividing tiles.</p>
<p id="borderimg2">Here, the image is stretched to fill the area.</p>
A: You could achieve this with :before
HTML
<div class="wrap">
<p class="text">Lorem ipsum dolor sit amet</p>
<br />
<p class="text alt">Amet cum et ad earum commodi</p>
</div>
CSS
.wrap {
padding: 50px;
background: url(https://placedog.net/1000/500?id=12);
background-size: cover;
}
.text {
position: relative;
z-index: 1;
margin: 0 0 50px;
font-size: 40px;
font-family: sans-serif;
display: inline-block;
}
.text:before {
content: '';
position: absolute;
display: block;
top: 15px;
bottom: 15px;
left: -20px;
right: -20px;
background: rgba(255,255,255,0.8);
z-index: -1;
}
Change the values top, bottom, left, right in the :before to suit your needs.
JSFiddle:
https://jsfiddle.net/74kLwyxb/ | unknown | |
d13874 | train | I tend to copy the generated SQL script and execute it myself using SQL (Enterprise manager 2008 in my case), gives you better feedback and more control.
Haven't really bothered setting it up so that it executes automatically, because EF sometimes makes mistakes in its scripting (e.g. trying to delete every FK twice. Once in the beginning, and then again before the containing table will be deleted).
Also, if you made a lot of changes or dropped some tables, sometimes the script isn't 100% compatible with deleting the existing database. I then just drop all FK's and tables (not just what the script tells me to) and then execute the script.
But that's just how I like to do it. | unknown | |
d13875 | train | Well, the main thing you need to do is get the current working directory in your C script, and then you can either write some C code to combine the result with argv[0] to create the full path to the file and pass that to your python script as command line argument when you call it. Alternatively, you could pass both argv[0] and the result of getcwd() as parameters to your Python script, which is what I did below:
requestAudit.c
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, const char* argv[]) {
char* cwd = getcwd(NULL, 0);
char* command = "python audit.py ";
char* combine;
// I added 2 because 1 for the null terminator and 1 for the space
// between cwd and argv[0]
size_t len = strlen(command) + strlen(cwd) + strlen(argv[0]) + 2;
combine = malloc(sizeof(*combine)*len);
strncpy(combine, command, strlen(command) + 1);
strncat(combine, cwd, strlen(cwd) + 1);
strncat(combine, " ", 2);
strncat(combine, argv[0], strlen(argv[0]) + 1);
return system(combine);
}
audit.py
import sys
if __name__ == "__main__":
full_path = sys.argv[1] + sys.argv[2][1:]
print(full_path)
This is just one way to do it, I'm sure there are other, probably better, ways to do this. | unknown | |
d13876 | train | If you just want to sync entire repository to S3 bucket,you can use the task Amazon S3 Upload in your azure pipeline.
I'm not sure if that will fully address your problem, though.
If there is any misunderstanding, please feel free to add comments related to your issue. | unknown | |
d13877 | train | The problem is that you are sometimes trying to discharge a goal but further subgoals might lead to a solution you thought would work to be rejected. If you accumulate all the successes then you can backtrack to wherever you made a wrong choice and explore another branch of the search tree.
Here is a silly example. let's say I want to prove this goal:
Goal exists m, m = 1.
Now, it's a fairly simple goal so I could do it manually but let's not. Let's write a tactic that, when confronted with an exists, tries all the possible natural numbers. If I write:
Ltac existNatFrom n :=
exists n || existNatFrom (S n).
Ltac existNat := existNatFrom O.
then as soon as I have run existNat, the system commits to the first successful choice. In particular this means that despite the recursive definition of existNatFrom, when calling existNat I'll always get O and only O.
The goal cannot be solved:
Goal exists m, m = 1.
Fail (existNat; reflexivity).
Abort.
On the other hand, if I use (+) instead of (||), I'll go through all possible natural numbers (in a lazy manner, by using backtracking). So writing:
Ltac existNatFrom' n :=
exists n + existNatFrom' (S n).
Ltac existNat' := existNatFrom' O.
means that I can now prove the goal:
Goal exists m, m = 1.
existNat'; reflexivity.
Qed. | unknown | |
d13878 | train | composer global install will not install the command "globally" for all users, but "globally" as in "for all projects".
Generally, these packages are installed in the home directory for the user executing the command (e.g. ~/.composer), and if they are available in your path is because ~/.composer/vendor/bin is added to the session path.
But when you run composer global require (while building the image) or when you "log in" to the running container (using exec [...] bash) the user involved is root. But when your PHP script runs, it's being executed by another user (presumably www-data). And for that user, ~/.composer does not contain anything.
Maybe do not install drush using composer, but rather download the PHAR file directly or something like that while you are building the image, and put it in /usr/local/bin.
If you are using Drupal >= 8, the recommended way of installing Drush is not as a "global" dependency, but as "project" dependency, so that the appropriate drush version is installed. This comes straight from the docs:
It is recommended that Drupal 8 sites be built using Composer, with Drush listed as a dependency. That project already includes Drush in its composer.json. If your Composer project doesn't yet depend on Drush, run composer require drush/drush to add it. After this step, you may call Drush via vendor/bin/drush | unknown | |
d13879 | train | if(isset($_POST['banCheckBan']))
NCore::db('USER')->updateAsArray(array('BANNED' => 1))->eq('ID', $_POST['banCheckNoBan'])->execute();
You are using $_POST['banCheckNoBan'] instead of $_POST['banCheckBan'] in your query.
A: I see two problems:
*
*you have a syntax errors - you dont close the <input> tag with >!
*you should add value="something" attribute to the <input type="checkbox"> tag.
A: This bit:
{if $user4.banned}
<td><center><input type="checkbox" name="banCheckNoBan" checked value="{$user4.id}"</center></td>
{else}
<td><center><input type="checkbox" name="banCheckBan" value={$user4.id}</center></td>
{/if}
Should be:
{if $user4.banned}
<td><center><input type="checkbox" name="banCheckNoBan" checked value="{$user4.id}" /></center></td>
{else}
<td><center><input type="checkbox" name="banCheckBan" value="{$user4.id}" /></center></td>
{/if}
Notice that the input tag needs to close: />. You just went straight into </center>. | unknown | |
d13880 | train | externals: {
'gl-matrix': {
commonjs: 'gl-matrix',
commonjs2: 'gl-matrix',
amd: 'gl-matrix'
}
}
external dict name should match name of the lib
A: externals: [
{
'gl-matrix': {
root: 'window',
commonjs: 'gl-matrix',
commonjs2: 'gl-matrix',
amd: 'gl-matrix'
}
}
]
If you import gl-matrix via script tag, it will be several global variables like vec3,mat4, but not gl-matrix.vec3,gl-matrix.mat4.
So you can set them to one variable and then use this variable as webpack external root config.
Then I found that window object has window attr that points to it self, so use 'window' in root field is a better choice and it's doesn't need to declare a united variable anymore. | unknown | |
d13881 | train | Did you try using #include "opencv4/opencv2/imgproc/imgproc.hpp" instead? | unknown | |
d13882 | train | This module would do what you want: http://docs.python.org/3/library/pickle.html
An example:
import pickle
array = ["uno", "dos", "tres"]
with open("test", "wb") as f:
pickle.dump(array, f)
with open("test", "rb") as f:
unpickled_array = pickle.load(f)
print(repr(unpickled_array))
Pickle serializes your object. In essence this means it converts it to a storeable format that can be used to recreate a clone of the original.
Check out the wiki entry if you're interested in more info: http://en.wikipedia.org/wiki/Serialization
A: Python docs have a beautiful explanation on how to handle text files among other files to read/write. Here's the link:
http://docs.python.org/2/tutorial/inputoutput.html
Hope it helps!
A: You need to serialize the array somehow to store it in a file. Serialize basically just means turn into a representation that is linear. For our purposes that means a string. There are several ways (csv, pickle, json). My current favorite way to do that is json.dump() and json.load() to read it back in. See json docs
import json
def save_file():
with open('datafile.json', 'w') as f:
json.dump(datastore, f)
def load_file():
with open('datafile.json', 'r') as f:
datastore = json.load(f)
A: Use JSON; Python has a json module built-in :
import json
datastore = json.load(open("file.json")) // load the file
datastore["new"] = "new value" // do something with your data
json.dump(datastore, open("file.json", "w")) // save data back to your file
You could also use Pickle to serialize a dictionary, but JSON is better for small data and is human-readable and editable with a simple text editor, where as Pickle is a binary format.
I've updated your code to use JSON and dictionaries, and it works fine :
import json
import time
datastore = json.load(open("file.json"))
menuon = 1
def add_user():
userdata = input("How many users do you wish to input?")
print("\n")
if (userdata == 0):
print("Thank you, have a nice day!")
else:
def add_data(users):
for i in range(users):
datastore.append({"name":input("Enter Name: "), "mail":input("Enter Email: "), "dob":input("Enter DOB: ")})
add_data(int(userdata))
def print_resource(array):
for entry in datastore:
print("Name: "+entry["name"])
print("Email: "+entry["mail"])
print("DOB: "+entry["dob"])
print("\n")
def search_function(value):
for eachperson in datastore:
for i in eachperson.keys():
if value in eachperson[i]:
print_resource(eachperson)
while menuon == 1:
print("Hello There. What would you like to do?")
print("")
print("Option 1: Add Users")
print("Option 2: Search Users")
print("Option 3: Replace Users")
print("Option 4: End the program")
menuChoice = input()
if menuChoice == '1':
add_user()
if menuChoice == '2':
searchflag = input("Do you wish to search the user data? y/n")
if(searchflag == 'y'):
criteria = input("Enter Search Term: ")
search_function(criteria)
if menuChoice == '3':
break
if menuChoice == '4':
print("Ending in 3...")
time.sleep(1)
print("2")
time.sleep(1)
print("1")
json.dump(datastore, open("file.json", "w"))
menuon=0 | unknown | |
d13883 | train | Replace your code
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
with
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
Turn off all deprecated warnings including them from mysql_*:
error_reporting(E_ALL ^ E_DEPRECATED); | unknown | |
d13884 | train | I think you have two options:
*
*Make the end users obtain their own Netflix key.
*Proxy all the traffic through your own server and keep your secret key on your server.
You could keep casual users away from your secret key while still distributing it with some obfuscation but you won't keep it a secret from anyone with a modicum of skill.
Proxying all the traffic would pretty much mean setting up your own web service that mimics the parts of the Netflix API that you're using. If you're only using a small slice of the Netflix API then this could be pretty easy. However, you'd have to carefully check the Netflix terms of use to make sure you're playing by the rules.
I think you'd be better off making people get their own keys and then setting up your tool to read the keys from a configuration file of some sort. | unknown | |
d13885 | train | Rownum (numeric) = Generated Sequence Number of your output.
Rowid (hexadecimal) = Generated automatically at the time of insertion of row.
SELECT rowid,rownum fROM EMP
ROWID ROWNUM
----- ----------------------
AAAR4AAAFAAGzg7AAA, 1
AAAR4AAAFAAGzg7AAB, 2
AAAR4AAAFAAGzg7AAC, 3
AAAR4AAAFAAGzg7AAD, 4
AAAR4AAAFAAGzg7AAE, 5
A: Both, ROWNUM and ROWID are pseudo columns.
Rowid
For each row in the database, the ROWID pseudo column returns the
address of the row.
An example query would be:
SELECT ROWID, last_name
FROM employees
WHERE department_id = 20;
More info on rowid here: https://docs.oracle.com/cd/B19306_01/server.102/b14200/pseudocolumns008.htm
Rownum
For each row returned by a query, the ROWNUM pseudo column returns a
number indicating the order in which Oracle selects the row from a
table or set of joined rows. The first row selected has a ROWNUM of 1,
the second has 2, and so on.
You can limit the amount of results with rownum like this:
SELECT * FROM employees WHERE ROWNUM < 10;
More info on rownum here: https://docs.oracle.com/cd/B19306_01/server.102/b14200/pseudocolumns009.htm
Difference
The actual difference between rowid and rownum is, that rowid is a permanent unique identifier for that row. However, the rownum is temporary. If you change your query, the rownum number will refer to another row, the rowid won't.
So the ROWNUM is a consecutive number which applicable for a specific SQL statement only. In contrary the ROWID, which is a unique ID for a row.
A: *
*Rowid gives the address of rows or records. Rownum gives a count of records
*Rowid is permanently stored in the database. Rownum is not stored in the database permanently
*Rowid is automatically assigned with every inserted into a table. Rownum is a dynamic value automatically retrieved along with select statement output.
*It is only for display purpose.
A: row id shows the unique identification for row
rownum shows the unique default series of numbers.
select * from emp
where rownum<=5; (it will execute correctly and gives output first 5 rows in your table )
select * from emp
where rowid<=5; (wrong because rowid helpful to identify the unique value) | unknown | |
d13886 | train | Your div elements are empty and there is no CSS to give them any explicit size, so they will never be visible for you to click on them.
Also, the mousedown event handler can and should be combined with the click handler for butt and the mouseup event handler should just be a click event as well.
Additionally, you only need to update the number of clicks, not the word "Clicks", so make a separate placeholder for the number with a span element and then you can hard-code the word "Clicks" into the div.
Lastly, to increment a number by one, you can just use the pre or post-increment operator (++).
$(document).ready(function() {
var clicks = 0;
var divData = $("#clickCount");
$("#pushed").on("click", function() {
$("#butt").show();
});
$("#butt").on("click", function() {
$("#butt").hide();
clicks++; // increment the counter by one
divData.html(clicks);
});
});
#pushed, #butt {height:50px; width:150px; background-color:green; margin:5px;}
<body>
<form name="ButtonForm">
<div id="container">
<div id="pushed"></div>
<div id="butt"></div>
</div>
<div id="showCount">Clicks <span id="clickCount"></span></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
</form>
</body>
A: First of all, you should simplify your code. Hiding and showing the button is not necessary to produce the result you are looking for.
Second, change the #butt element to an actual button so that you have something to see and click.
Third, make sure your script is loading after jquery is included.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
<button id="butt">I'm a button</button>
<div id="showCount"></div>
<script>
$(document).ready(function() {
$("#butt").click(function() {
button_click();
});
var clicks = 0;
function button_click() {
clicks = parseInt(clicks) + parseInt(1);
var divData = document.getElementById("showCount");
divData.innerHTML = "Clicks:" + clicks;
}
});
</script> | unknown | |
d13887 | train | If I pass data to the camera intent, will get it back in the intent?
No.
I know one approach is to have class variable and store it there but I have feeling this is prone for errors
If by "class variable", you mean a field on your activity or fragment, that is the appropriate approach. However, since there is a chance that your process will be terminated while the camera app is in the foreground, you need to hold onto that information in the saved instance state Bundle, so you get it back if your activity or fragment gets re-created. This sample app demonstrates the technique. | unknown | |
d13888 | train | Using PSReadline (built-in to PS 5.1 or available via Install-Module) you can make a custom key handler:
Set-PSReadlineKeyHandler -Chord 'ctrl+tab' -ScriptBlock {
$text = ''
$cursor = 0
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$text, [ref]$cursor)
$lastNewLine = [math]::max(0, $text.LastIndexOf("`n", $cursor - 1))
[Microsoft.PowerShell.PSConsoleReadLine]::Replace([math]::min($cursor, $lastNewLine + 1), 0, " ")
}
Then Ctrl+Tab will indent the line which the cursor is on, no matter where in the line the cursor is.
Extending this to multiple lines, when you can't really select multiple lines in the console, is left as an exercise for the reader. | unknown | |
d13889 | train | Chances are that you don't have the test sources in your .NET solution, so when SonarQube tries to import the test execution results, it can't find to which files they should be attached.
In the .NET sample solution, you can see that there is a test project (Example.Core.Tests) which contains the sources of the test classes. | unknown | |
d13890 | train | See this set_time_limit, and also this memory-limit | unknown | |
d13891 | train | I think remain one step, run composer dump-autoload and php artisan clear-compiled
command. May be this command will solve this issue.
UPDATE
"autoload": {
"classmap": [
"database",
"app/Libraries/Main"
],
"psr-4": {
"App\\": "app/"
}
}
After update your composer.json with above code, run below command:
//To clears all compiled files.
php artisan clear-compiled
//To updates the autoload_psr4.php
composer dump-autoload
//updates the autoload_classmap.php
php artisan optimize | unknown | |
d13892 | train | Having multiple certificates on the same IP address and port relies on Server Name Indication.
Your server supports it, but your client needs to support it too.
Client-side support for SNI was only introduced in Java in Java 7 (see release notes)(*). I guess you're using Java 6 or below, otherwise your simple example with URLConnection should work out of the box like this.
(You may also need additional settings if you're using another client library, such as Apache HTTP Client, depending on the version.)
(*) And this was introduced on the server side in Java 8, but that's not really your problem here. | unknown | |
d13893 | train | You are using synchronous Ajax, which has been disabled for extensions and apps. You should instead use asynchronous Ajax with a callback passed into loadXMLDoc:
function loadXMLDoc(dname, callback) {
if (window.XMLHttpRequest) {
xhttp=new XMLHttpRequest();
} else {
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname);
xhttp.onload = function() {
callback(xhttp);
}
xhttp.send();
}
function isUpdateAvailable(type, build, callback) {
var buildNumber = localStorage["version" + build + type];
loadXMLDoc("http://dl.bukkit.org/api/1.0/downloads/projects/" + build + "/view/latest-" + type + "/", function(xml) {
var xmlDoc = xml.responseXML;
var x = xmlDoc.getElementsByTagName("title")[0];
var y = x.childNodes[0];
var txt = y.nodeValue;
if(txt == buildNumber) {
callback(true);
} else {
xml.close();
callback(false);
}
});
}
...
chrome.tabs.onActivated.addListener(function() {
var type = localStorage["type"];
var build = localStorage["build"];
if(!type) {
type = "rb";
}
if(!build) {
build = "craftbukkit";
}
isUpdateAvailable(type, build, function(isAvail) {
if(isAvail) {
notify(type, build);
var xml = loadXMLDoc("http://dl.bukkit.org/api/1.0/downloads/projects/" + type + "/view/latest-" + build + "/", function(xml) {
var xmlDoc=xml.responseXML;
localStorage["version" + build + type] = xmlDoc.getElementsByTagName("build_number")[0];
xml.close();
});
}
});
}); | unknown | |
d13894 | train | Main problem is that $short_smas and $mid_smas have different size. Moreover they are associative arrays so either you pick unique keys from both and will allow for empty values for keys that have only one value available or you pick only keys present in both arrays. Code below provides first solution.
// first lets pick unique keys from both arrays
$uniqe_keys = array_unique(array_merge(array_keys($short_smas), array_keys($mid_smas)));
// alternatively we can only pick those present in both
// $intersect_keys = array_intersect(array_keys($short_smas),array_keys($mid_smas));
// now lets build sql in loop as Marcelo Agimóvel sugested
// firs we need base command:
$sql = "INSERT INTO sma (short_sma, mid_sma) VALUES ";
// now we add value pairs to coma separated list of values to
// insert using keys from prepared keys array
foreach ($uniqe_keys as $key) {
$mid_sma = array_key_exists($key, $mid_smas)?$mid_smas[$key]:"";
$short_sma = array_key_exists($key, $short_smas)?$short_smas[$key]:"";
// here we build coma separated list of value pairs to insert
$sql .= "('$short_sma', '$mid_sma'),";
}
$sql = rtrim($sql, ",");
// with data provided in question $sql should have string:
// INSERT INTO sma (short_sma, mid_sma) VALUES, ('3.5', ''), ('4.5', ''), ('5.5', ''), ('6.5', '5'), ('7.5', '6'), ('8.5', '7'), ('9.5', '8'), ('10.5', '9'), ('11.5', '10'), ('12.5', '11')
// now we execute just one sql command
if ($con->query($sql) === TRUE) {
echo "New records created successfully<br><br>";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
// don't forget to close connection
Marcelo Agimóvel also suggested that instead of multiple inserts like this:
INSERT INTO tbl_name (a,b,c) VALUES (1,2,3);
its better to use single:
INSERT INTO tbl_name
(a,b,c)
VALUES
(1,2,3),
(4,5,6),
(7,8,9);
That's why I append value pairs to $sql in foreach loop and execute query outside loop.
Also its worth mentioning that instead of executing straight sql its better to use prepared statements as they are less prone to sql injection. | unknown | |
d13895 | train | The only Excel that exports to Mac OS Roman apparently is MS Excel for OSX. Unfortunately I don't have this so I can't check how to export with the correct character set
You now have two choices
a) Convert the CSV to UTF-8 using iconv for example
iconv -f MACROMAN -t UTF8 < yourfile.csv > yourfile-utf8.csv
b) Set the connection charset to the character set of the file before you import
SET NAMES macroman;
In codeigniter this would look like this
$this->db->simple_query('SET NAMES \'macroman\'');
After your import is done, don't forget to set it back
$this->db->simple_query('SET NAMES \'utf8\'');
Explanation:
If your connection charset is UTF-8, your database excepts UTF-8 encoded data. If you set the connection charset to macroman and the columns you write to are UTF-8, MySQL will automatically convert this for you.
From http://dev.mysql.com/doc/refman/5.5/en/charset-connection.html
SET NAMES 'charset_name' [COLLATE 'collation_name']
SET NAMES indicates what character set the client will use to send SQL statements to the server. Thus, SET NAMES 'cp1251' tells the server, “future incoming messages from this client are in character set cp1251.” It also specifies the character set that the server should use for sending results back to the client. (For example, it indicates what character set to use for column values if you use a SELECT statement.)
On my freeBSD machine, MySQL has the macroman character set compiled in, I suppose you'll also have this.
mysql> SELECT * FROM information_schema.COLLATIONS WHERE CHARACTER_SET_NAME = 'macroman';
+---------------------+--------------------+----+------------+-------------+---------+
| COLLATION_NAME | CHARACTER_SET_NAME | ID | IS_DEFAULT | IS_COMPILED | SORTLEN |
+---------------------+--------------------+----+------------+-------------+---------+
| macroman_general_ci | macroman | 39 | Yes | Yes | 1 |
| macroman_bin | macroman | 53 | | Yes | 1 |
+---------------------+--------------------+----+------------+-------------+---------+
Also see http://dev.mysql.com/doc/refman/5.5/en/charset-charsets.html
Hope this helps | unknown | |
d13896 | train | Solution
It looks like that I am faced with the issue mentioned in @EnableResourceServer creates a FilterChain that matches possible unwanted endpoints with Spring Security 4.0.3 Spring Security is a dependency of spring-boot-starter-security. Due to the update of the spring-boot-starter-parent I switched from Spring Security 3.2.8 to 4.0.3. A further interesting comment regarding this issue can be found here.
I changed the ResourceServer configuration like the code snippets below which solve the problem.
It would be great to replace the RegexRequestMatcher definition by using a negation of already existing code to match the login and logout form or Matchers like the spring NotOAuthRequestMatcher which is currently a private inner class of the ResourceServerConfiguration. Please do not hesitate to post suggestion. ;-)
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
// ... some code
private static final String RESOURCE_SERVER_MAPPING_REGEX = "^(?!(\\/?login|\\/?logout|\\/?oauth)).*$";
// ...some code
@Override
public void configure(HttpSecurity http) throws Exception {
http.requestMatcher(
new AndRequestMatcher(
new RegexRequestMatcher(RESOURCE_SERVER_MAPPING_REGEX, null)
)
).authorizeRequests().anyRequest().permitAll()
// ...some code
}
}
A: This should pretty straightforward.
POSTs and PUT requests would not be allowed if CSRF is enabled,and spring boot enables those by default.
Just add this to your ResourceServerConfig configuration code :
.csrf().disable()
This is also covered as an example problem here | unknown | |
d13897 | train | I would question why you NEED to populate the field period in your table.
In short, I wouldn't bother.
The period it is in can be derrived from the activity date field that is in the same record.
So you can write select statements that calc the period for the record in your MyTable as required.
SELECT TableWithPeriods.period, MyTable.activity_date
FROM MyTable
LEFT JOIN TableWithPeriods
ON MyTable.activity_date
BETWEEN TableWithPeriods.StartDate
AND TableWithPeriods.EndDate
If you need to access the period a lot then there is an argument for keeping a period value in the MyTable in step with the TableWithPeriods.
Keeping in step could be akward though as what if someone changes one of the period 's dates?
Keeping in step might mean writing a bit of SQL to update ALL MyTable rows that wither do not have the period set or when the period is now different.
A VBA update statement will look a bit like the SELECT above.
Or
you could use database the onchange macros that respond to data being added or updated in the MyTable (and the TableWithPeriods, if users can change dates).
Anyway, there's my opinion. I would NOT copy the value over.
PS I'm not 100% sure about the SQl I gave above, this might work though
SELECT TableWithPeriods.period, MyTable.activity_date
FROM MyTable
LEFT JOIN TableWithPeriods
ON ( MyTable.activity_date >= TableWithPeriods.StartDate
AND MyTable.activity_date <= TableWithPeriods.EndDate ) | unknown | |
d13898 | train | For anyone else struggling, this is the modified class function I used to generate a nice table with all rows and columns.
def GetHtmlText(self,text):
html_text = '<h3>Data Results:</h3><p><table border="2">'
html_text += "<tr><td>Domain:</td><td>Mail Server:</td><td>TLS:</td><td># of Employees:</td><td>Verified</td></tr>"
for row in root.ptglobal.to_csv():
html_text += "<tr>"
for x in range(len(row)):
html_text += "<td>"+str(row[x])+"</td>"
html_text += "</tr>"
return html_text + "</table></p>"
A: maybe try
`html_text = text.replace(' ',' ').replace('\n','<br/>')`
that would replace your spaces with html space characters ... but it would still not look right since it is not a monospace font ... this will be hard to automate ... you really want to probably put it in a table structure ... but that would require some work
you probably want to invest a little more time in your html conversion ... perhaps something like (making assumptions based on what you have shown)
def GetHtmlText(self,text):
"Simple conversion of text. Use a more powerful version"
text_lines = text.splitlines()
html_text = "<table>"
html_text += "<tr><th> + "</th><th>".join(text_lines[0].split(":")) + "</th></tr>
for line in text_lines[1:]:
html_text += "<tr><td>"+"</td><td>".join(line.split()) +"</td></tr>
return html_text + "</table>" | unknown | |
d13899 | train | First, find where you actually installed the OpenCV libraries. So, let's take libopencv_core.dylib and look for it in a bunch of likely places, i.e. $HOME, /usr and /opt:
find $HOME /usr /opt -name libopencv_core.dylib
Sample Output
/Users/mark/OpenCV/lib/libopencv_core.dylib
Now we know where it is (on my system), so we can tell the linker:
c++ -L/Users/mark/OpenCV/lib ... | unknown | |
d13900 | train | Do something like y = tf.stop_gradient(g(x)) and load the weights of g from a checkpoint by creating your own saver and passing the list of g's variables to it. | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.