id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23536500
|
I've installed devtoolset-8, llvm-toolset-7.0 and centos-release-scl.
I've also installed bazel 0.29.1 and made.
export CC=clang
export CXX=clang++
I have an shell script which run basel. Befor bazel build command in top of the script I have
source /opt/rh/llvm-toolset-7.0/enable
which enables LLVM-7.0/Clang-7.0. But build failes with:
/opt/rh/llvm-toolset-7.0/root/usr/bin/clang: error while loading
shared libraries: libLLVM-7.so: cannot open shared object file: No
such file or directory
But this lib exists! It's in /opt/rh/llvm-toolset-7.0/root/usr/lib64/
May someone pls help with this ?
A: Add below to .bash_profile or .bashrc:
source /opt/rh/llvm-toolset-7.0/enable
export CC=/opt/rh/llvm-toolset-7.0/root/usr/bin/clang
export CXX=/opt/rh/llvm-toolset-7.0/root/usr/bin/clang++
Run below as Root
echo /opt/rh/llvm-toolset-7.0/root/usr/lib64/ > /etc/ld.so.conf.d/llvm-toolset.conf
ldconfig
| |
doc_23536501
|
For a NumPy array, for each 'column', I want to modify the value to equal 1 and then output the modified array as well as the original column.
My code looks like this:
base_arr = (np.random.rand(4, 10) * 10).astype(np.int32)
array([[3, 7, 8, 2, 6, 7, 5, 4, 1, 1],
[6, 2, 9, 7, 6, 5, 4, 4, 5, 6],
[6, 2, 5, 6, 1, 4, 4, 3, 1, 3],
[5, 1, 7, 8, 7, 7, 8, 7, 2, 1]], dtype=int32)
mod_arrs = []
orig_vals = []
def modify_array(orig_array, col_idx):
mod_arr = orig_array
mod_arr[:, col_idx] = 1
return mod_arr, orig_array[:, col_idx]
for i in range(base_arr.shape[1]):
res = modify_array(base_arr, i)
mod_arrs.append(res[0])
orig_vals.append(res[1])
My expected output is:
mod_arrs = [array([[1, 7, 8, 2, 6, 7, 5, 4, 1, 1],
[1, 2, 9, 7, 6, 5, 4, 4, 5, 6],
[1, 2, 5, 6, 1, 4, 4, 3, 1, 3],
[1, 1, 7, 8, 7, 7, 8, 7, 2, 1]], dtype=int32)),
array([[3, 1, 8, 2, 6, 7, 5, 4, 1, 1],
[6, 1, 9, 7, 6, 5, 4, 4, 5, 6],
[6, 1, 5, 6, 1, 4, 4, 3, 1, 3],
[5, 1, 7, 8, 7, 7, 8, 7, 2, 1]], dtype=int32),
...
]
orig_vals = [array([3, 6, 6, 5]), array([7, 2, 2, 1]), ...]
However, instead I am getting:
mod_arrs = [array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], dtype=int32),
array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], dtype=int32),
...
]
orig_vals = [array([1, 1, 1, 1]), array([1, 1, 1, 1]), ...]
Can anyone explain why this is occurring? I was under the impression that the orig_array would not be modified. However, during the for loop I can see the 1s slowly taking over the orig_array!
Any explanations would be appreciated. :)
A: When you write mod_arr = orig_array that means both variables are referencing to the same memory address. if you modify one the other also modifies. you should use mod_arr = orig_array.copy() if you want not to be modified.
| |
doc_23536502
|
Yaml workflow:
jobs:
build:
name: Create Release
runs-on: windows-latest
steps:
- name: Setup Checkout
uses: actions/checkout@v2
- name: Setup .NET
uses: actions/setup-dotnet@v1
with:
dotnet-version: 6.0.x
- name: Restore .NET dependencies
run: dotnet restore
- name: Build .NET
run: dotnet build --no-restore
- name: Test .NET
run: dotnet test --no-build --verbosity normal
- name: Publish .NET
run: |
dotnet publish /p:PublishProfile=Release-win-x86 -c Release
dotnet publish /p:PublishProfile=Release-win-x64 -c Release
- name: Upload Published Artifact
uses: actions/upload-artifact@v2
with:
name: softwarename
path: |
/home/runner/work/solution/project/Software/win-x86/
/home/runner/work/solution/project/Software/win-x64/
The error:
Upload Published Artifact
Run actions/upload-artifact@v2
Warning: No files were found with the provided path:
/home/runner/work/solution/project/Software/win-x86/
/home/runner/work/solution/project/Software/win-x64/. No artifacts will be uploaded.
Download Published Artifact
Run actions/download-artifact@v2
Starting download for softwarename
Error: Unable to find any artifacts for the associated workflow
I read here that I need to change actions/upload-artifact@v2 to actions/upload-artifact@v2.2.4, that I tried and failed with the same error.
Any Idea how to fix this issue?
A: I give credit for @jessehouwing for making me a ware of the concept.
Regarding this thread, my solution needed ${{ github.workspace }}, so that my changes looks like this:
${{ github.workspace }}\Software\win-x86
${{ github.workspace }}\Software\win-x64
A: Don't rely on:
/home/runner/work/solution/project
Instead use
${{ github.workspace }}/project
That way it points to the correct path for the runner independent of the operating system and configuration
| |
doc_23536503
|
I have a catchall route that catches bad URLs, including all of the old ones. In a perfect world I would like to do a 301 redirect to the home page for all urls matching this catchall route, and I do have code for this that works properly on my development machine. However, I finally got someone at our ISP (Network Solutions) to tell me that they block 301 redirections (the web server returns a 404 instead).
So I think my only remaining option is to just accept any bad URL, and point it to the home page.
Here is my question: I know that the search engines (especially Google) are now penalizing duplicate content. If I just point all bad URLs to the home page, how much is this going to hurt us in the search rankings? Do I have any other technical options?
A: Honestly, I would suggest that you change ISP's. 301's are an important tool in any webmaster's toolbox, and for them to block that will penalize you terribly. You could easily transfer your domain to another IP address, wait for the DNS propagation, and then do your rollout.
From Google's Webmaster tools:
Use a 301 Redirect to permanently
redirect all pages on your old site to
your new site. This tells search
engines and users that your site has
permanently moved. We recommend that
you move and redirect a section or
directory first, and then test to make
sure that your redirects are working
correctly before moving all your
content.
Don't do a single redirect directing
all traffic from your old site to your
new home page. This will avoid 404
errors, but it's not a good user
experience. It's more work, but a
page-to-page redirect will help
preserve your site's ranking in Google
while providing a consistent and
transparent experience for your users.
If there won't be a 1:1 match between
pages on your old site and your new
site (recommended), try to make sure
that every page on your old site is at
least redirected to a new page with
similar content.
I'm sure that's much easier said then done, but I would never want an ISP that exerted that kind of filter against their clients.
A: Can you do a 302 redirect at least? I do agree with what womp says though, what ISP would block 301 redirects? Dump them. ISPs are a dime a dozen.
A: I completely agree with womp. I cannot believe that an ISP would block 301's.
I was so surprised that you can't do a 301 redirect on Network Solutions, because they're not exactly a two bit operation.
Their own marketing material suggests that you can. There's also a forum post by someone wanting to do a 301 redirect. Although they use a .htaccess, the reply from a Network Solutions tech support shows the user how to do a 301 redirect in ASP.
A: If you opt to not change ISP then the simples solution is to display a page where you say that the page has been moved with a link to the new page link, then you add a 5 second delay that re-directs using a HTML meta tag:
<html>
<head>
<title>Page moved</title>
<meta http-equiv="refresh" content="5;url=http://example.com/newurl">
</head>
<body>
The page has been moved, click <a href="http://example.com/newurl">here</a> if you have not been re-directed to the new page within 5 seconds.
</body>
</html>
Alternatively you could use a URL rewriter, that way the old url "points" to the new page, there are basically two ways of doing this, the programmatically way is to create your own VirtualPathProvider, the second way is to use a URL Rewriter module like the IIS Url Rewrite Module.
| |
doc_23536504
|
<div class="col-md-2 col-xs-12">
<div class="col-md-2 icon">
<i class="fa fa-bandcamp" aria-hidden="true"></i>
</div>
<div class="col-md-10 height hidden-xs">
<p>mycomp account number</p><span class="text">2000299999940</span>
</div>
<div class="visible-xs height">
<hr>
<p class="col-xs-5">mycomp account number:</p>
<p class="col-xs-7">2000299999940</p>
</div>
</div>
<div class="col-md-1">
<hr class="line" />
</div>
css:
.line {
width: 200px;
height: 3px;
background-color: #dadada;
margin-right:40px;
}
Because of the bootstrap columnstructure there are margins involved, but how can I make the line without all the space ie make it wider? Codepen here
A: well in case you want to ignore the default padding and margin in bootstrap make a class in css file as
.no-padding-margin
{
padding:0px;
margin: 0px;
}
and then apply this class to your bootstrap columns as
<div class="col-md-2 col-xs-12 no-padding-margin">
<div class="col-md-2 icon">
<i class="fa fa-bandcamp" aria-hidden="true"></i>
</div>
<div class="col-md-10 height hidden-xs">
<p>mycomp account number</p><span class="text">2000299999940</span>
</div>
<div class="visible-xs height">
<hr>
<p class="col-xs-5">mycomp account number:</p>
<p class="col-xs-7">2000299999940</p>
</div>
</div>
<div class="col-md-1 no-padding-margin">
<hr class="line" />
</div>
A: well as i understand you just want your line to be longer .
so why don't you remove the paddings from the col the line is in. and also add width:100% on the .line if you want.
code :
.line {
width: 100%;
height: 3px;
background-color: #dadada;
}
.col-md-1 {
padding-left:0;
padding-right:0;
}
| |
doc_23536505
|
Like .doc, .docx, .jpg?
Thanks
A: There is no general answer. Most file formats can be recognized by looking at the content, analysing the header. However, there is no 'standard' header, and many formats have no header at all (think CSV for example).
If the content comes from a file on disk, create a FileInfo and query its extension.
If you only have the content, you'll have to build you own analysers that look at headers and/or guess based on other facts (e.g. text with a lot of commas...).
A: Before getting files in byte array, get FileExtension, and use ID for your byte and extension to find with index.
| |
doc_23536506
|
My code is below, I also have a pseudocode for ease of understanding.
For ease of explaining and clearing up the messy code, here is a pseudocode:
recursive function{
if (!(dir = opendir(ca->SD))){{
return;
}
while ((ptr = readdir(dir)) != NULL) {
if (ptr->d_type == DT_DIR) {
if (strcmp(ptr->d_name, "..") == 0||strcmp(ptr->d_name, ".") == 0){
continue;
}
create thread/call recursive function
}else(if file){
create thread/call file handler function
}
}
thread join for any live threads;
}
I'm just confused as to where to properly put the join for any of the directory threads. I currently keep getting some sort of loop.
A: I think you shoudn't try to create an unknown number of threads because It will have poorly performance. In this case it's better to use a pool of threads where you can control the maximum number of threads and you will not be creating and destroying threads for every directory entry.
Take a look on this link for information of what a pool of threads is.
In your example you have to wait for the threads termination at the end of each recursive call. I mean each call of searchdirectory should wait for the termination of the threads it created before returning.
| |
doc_23536507
|
So I have a common Mapper class which has methods to map different objects. As Mappings are persisted in the application, I do all my CreateMap() in the static constructor so that the mappings are created only once and are ready by the time I might use them. The class looks like this
public class SomeMapper
{
static SomeMapper()
{
Mapper.CreateMap<SomeType1, SomeOtherType1>();
Mapper.CreateMap<SomeType2, SomeOtherType2>();
Mapper.CreateMap<SomeType3, SomeOtherType3>();
//...
}
public SomeOtherType1 MapSomeHierarchy1(SomeType1 source)
{ //... }
public SomeOtherType2 MapSomeHierarchy2(SomeType2 source)
{ //... }
}
Question 1: What can be a better way to create the mappings? (better in any way - performance, semantics, standard practices etc.)
Question 2: This code is also used in a Console application. In a particular run, it'll not need all the mappings. So, rather than creating all the mappings eagerly, can I create the map at run time if it does not exist already? Something like
public SomeOtherTypeN MapSomeHierarchyN(SomeTypeN source)
{
if (!AlreadyMapped(SomeTypeN, SomeOtherTypeN))
Mapper.CreateMap<SomeTypeN, SomeOtherTypeN>();
return Mapper.Map<SomeOtherTypeN>(source);
}
Is there a simple way to implement the method AlreadyMapped() ?
A: As you've said, mappings need only be created once during the lifecycle of the application. There are two main changes I would recommend:
Split your mappings into Profiles
These smaller units, and can be unit tested individually, so you can ensure all destination properties are either automatically mapped, explicitly mapped or ignored.
public class MyProfile : Profile
{
protected override void Configure()
{
// Note, don't use Mapper.CreateMap here!
CreateMap<SomeType1, SomeOtherType1>();
}
}
You then load individual profiles, allowing you to define these closer to where they are used in modular applications.
Mapper.AddProfile<MyProfile>();
Profiles can be tested individually:
Mapper.AssertConfigurationIsValid<MyProfile>();
I typically include a unit test with every profile - this way if your source or destination objects change in a way which break your mapping, you'll know about it immediately.
Create Mappings at Startup
While technically you can create mappings at any point during your application's lifecycle, AutoMapper makes various optimisations if you tell it that you're done. Some of these are essential if you perform any complex mappings with inheritance. Rather than creating mappings on the fly:
Mapper.CreateMap<SomeType1, SomeOtherType1>();
Mapper.AddProfile<MyProfile>();
You should load these using Mapper.Initialize instead:
Mapper.Initialize(cfg =>
{
cfg.CreateMap<SomeType1, SomeOtherType1>();
cfg.AddProfile<MyProfile>();
});
If you absolutely must add mappings on the fly, then you can force AutoMapper to perform its optimisations again after adding mappings using Mapper.Configuration.Seal().
Finally, if you're using an IoC container, then you can combine these two techniques by registering all of your Profiles in your AutoMapper container, then using this to locate and register them. Here's an example using Autofac:
// Register Components...
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<MyProfile>().As<Profile>();
// This could also be done with assembly scanning...
builder.RegisterAssemblyTypes(typeof<MyProfile>.Assembly).As<Profile>();
// Build container...
var container = builder.Build();
// Configure AutoMapper
var profiles = container.Resolve<IEnumerable<Profile>>();
Mapper.Initialise(cfg =>
{
foreach (var profile in profiles)
{
cfg.AddProfile(profile);
}
});
Regarding your second question, if you follow my point about creating mappings at startup then you won't need this, but defining a mapping which already exists overwrites the previous mapping, so shouldn't have any effect.
| |
doc_23536508
|
A: Another approach leverages the Qt metaobject system and the introspection into most enumerations in the Qt namespace. This works in both Qt 4 and Qt 5.
// https://github.com/KubaO/stackoverflown/tree/master/questions/keyname-21764138
#include <QMetaEnum>
namespace SO {
enum KeyNameOption { KeyNameNone = 0, AppendArrow = 1 };
Q_DECLARE_FLAGS(KeyNameOptions, KeyNameOption)
}
QString keyName(int index, SO::KeyNameOptions opt = {}) {
constexpr static auto const getEnum = [](const char *name) {
int enumIndex = qt_getQtMetaObject()->indexOfEnumerator(name);
return qt_getQtMetaObject()->enumerator(enumIndex);
};
static const auto keyEnum = getEnum("Key");
static const auto modifierEnum = getEnum("KeyboardModifiers");
auto name = modifierEnum.valueToKeys(index & Qt::KeyboardModifierMask);
index &= ~Qt::KeyboardModifierMask;
if (name == "NoModifier")
name.clear();
else {
name.replace('|', '+');
name.replace("Modifier", "");
name.append('+');
}
auto keyName = keyEnum.valueToKey(index);
if (keyName)
name.append(keyName + 4);
if ((opt & SO::AppendArrow) && index >= Qt::Key_Left && index <= Qt::Key_Down)
name.append(" Arrow");
return QLatin1String(name);
}
int main() {
Q_ASSERT(keyName(Qt::Key_Tab) == "Tab");
Q_ASSERT(keyName(Qt::ShiftModifier | Qt::Key_Up, SO::AppendArrow) == "Shift+Up Arrow");
Q_ASSERT(keyName(Qt::AltModifier | Qt::Key_Down) == "Alt+Down");
}
You'd then use it in, say, keyPressEvent, as follows:
void MyWidget::keyPressEvent(QKeyEvent * ev) {
qDebug() << keyName(ev->key());
}
A: Using human-readable names in your code
You can use the Qt::Key enum, or get the key as a string with QKeyEvent::text().
From QKeyEvent documentation:
int QKeyEvent::key () const
Returns the code of the key that was pressed or released.
See Qt::Key for the list of keyboard codes. These codes are independent of the underlying window system. Note that this function does not distinguish between capital and non-capital letters, use the text() function (returning the Unicode text the key generated) for this purpose.
...
Qt::Key is an enum that maps numeric key IDs (like the return value of QKeyEvent::key()) to programmer-readable names like Qt::Key_Up.
If you only care about alphanumeric keys, you can also use QKeyEvent::text() to get the value:
QString QKeyEvent::text () const
Returns the Unicode text that this key generated. The text returned can be an empty string in cases where modifier keys, such as Shift, Control, Alt, and Meta, are being pressed or released. In such cases key() will contain a valid value.
See also Qt::WA_KeyCompression.
Displaying human-readable names to the user
Use QKeySequence::toString() or build your own table of "nice" names.
The easiest way to get human-readable key names to show to the user is to use QKeySequence::toString().
Here's an example:
Qt::Key key = Qt::Key_Up;
qDebug() << QKeySequence(key).toString(); // prints "Up"
If you don't like the names that QKeySequence uses (e.g. you want to use "Up Arrow" instead of "Up"), you'll need to make your data table to remap the enum values to your preferred names.
| |
doc_23536509
|
My task is to implement polynomials with several functions....
The functions should be clear when you look at the code I think.
My exact problem is that i dont get a compiler error but a Segmentation Fault. I marked where my attempts to debug lead me to. But I have absolutely no clue on what I have to change. I hope someone can help me fix my code.
So here are the three code parts:
Number one: poly.c
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include "poly.h"
struct poly_t {
unsigned degree;
int *coeffs;
};
//constructor: heap
poly_t *poly_alloc(unsigned degree){
poly_t *heap_p;
heap_p = malloc(sizeof(*heap_p)+(degree+1)*sizeof(int)); //or malloc(sizeof(*heap_p)*(degree+1)) furthermore not sure if degree or degree +1
}
//free heap
void poly_free(poly_t *p){
int *coeffs = p->coeffs;
free(coeffs);
free(p);
}
void poly_set_coeff(poly_t *p, unsigned deg, int coeff){
p->degree = deg;
p->coeffs += deg;
p->coeffs[deg] = coeff;
//does not work Segmentation Fault not sure what to do
//p->coeffs += deg;
//*p->coeffs = coeff;
printf("%d",*p->coeffs);
}
//different variations
poly_t *poly_linear(poly_t *p, int a1, int a0){
p->degree=1;
*p->coeffs=a1;
p->coeffs++;
*p->coeffs=a0;
p->coeffs--;
}
poly_t *poly_quadratic(poly_t *p, int a2, int a1, int a0){
p->degree=2;
*p->coeffs=a2;
p->coeffs++;
*p->coeffs=a1;
p->coeffs++;
*p->coeffs=a0;
p->coeffs-=2;
}
//evaluate using horner
int poly_eval(poly_t const *p, int x){
int d = p->degree;
int next;
int adr = *p->coeffs;
int *arr = p->coeffs;
int res = arr[d];
for(int i=0; i<=d; i++){
adr+=(d-i);
next = arr[adr];
adr-=(d-i);
res = res*x+next;
}
return res;
}
//constructor : .txt
poly_t *poly_alloc_d(){
//needs to be finished
}
Number Two: main.c
#include <stdlib.h>
#include <stdio.h>
#include "poly.h"
int main(int argc, char** argv){
if(argc<3){
fprintf(stderr, "syntax: %s x coeffs...", argv[0]);
return 1;
}
poly_t *p = poly_alloc(argc-3);
for(int i = 2; i<argc; i++){
int coeff = atoi (argv[i]);
poly_set_coeff(p, i-2, coeff);
}
return 0;//for debugging
int x=atoi(argv[1]);
int y=poly_eval(p,x);
poly_free(p);
printf("%d\n", y);
return 0;
}
And at last my header file:
poly.h
#ifndef POLY_H
#define POLY_H
/* unvollständiger Verbund */
typedef struct poly_t poly_t;
poly_t *poly_alloc(unsigned degree);
void poly_free(poly_t *p);
void poly_set_coeff(poly_t *p, unsigned deg, int coeff);
int poly_eval(poly_t const *p, int x);
#endif /* POLY_H */
I appreciate every help. I hope you can help me sort this out and please be patient with me a newbie to C...
Thanks in advance
A: You have not allocated or freed memory correctly, and the function didn't even return the pointer! I think you were trying to allocate one block of memory for the struct and the array it contains, but the struct does not contain an array: only a pointer to an array. You have to allocate them separately:
typedef struct {
unsigned degree;
int *coeffs;
} poly_t;
//constructor: heap
poly_t *poly_alloc(unsigned degree){
poly_t *heap_p;
heap_p = malloc(sizeof(*heap_p));
if (heap_p == NULL)
exit (1); // allocation error
heap_p->coeffs = malloc(degree * sizeof(int));
if (heap_p->coeffs == NULL)
exit (1); // allocation error
return heap_p;
}
//free heap
void poly_free(poly_t *p){
free(p->coeffs);
free(p);
}
There are other mistakes too, for example
p->coeffs += deg;
You mustn't play with the allocated memory pointer, you already did it correctly like this
p->coeffs[deg] = coeff;
although you can use an intermediate pointer if you want:
int *ptr = p->coeffs + deg;
*ptr = coeff;
| |
doc_23536510
|
Desired output would be something like this:
index 3.0 3.0
+-------------------------------------------------------+
0 -23.4 -23.4
1 -2226.74 -2226.74
2 -1.93464e+07 -1.93464e+07
Code
class LogisticsFunction
puts "Enter two numbers, both between 0 and 1 (example: .25 .55)."
puts "After entering the two numbers tell us how many times you"
puts "want the program to iterate the values (example: 1)."
puts "Please enter the first number: "
num1 = gets.chomp
puts "Enter your second number: "
num2 = gets.chomp
puts "Enter the number of times you want the program to iterate: "
iter = gets.chomp
print "index".rjust(1)
print num1.rjust(20)
puts num2.rjust(30)
puts "+-------------------------------------------------------+"
(1..iter.to_i).each do |i|
print i
end
(1..iter.to_i).each do |i|
num1 = (3.9) * num1.to_f * (1-num1.to_f)
print num1
end
(1..iter.to_i).each do |i|
num2 = (3.9) * num2.to_f * (1-num2.to_f)
print num2
end
end
A: I think you don't have to run with three loop, following will give the desire output
(1..iter.to_i).each do |i|
print i
num1 = (3.9) * num1.to_f * (1-num1.to_f)
print num1.to_s.rjust(20)
num2 = (3.9) * num2.to_f * (1-num2.to_f)
print num2.to_s.rjust(30)
end
A: Your loops aren't actually nested. They are in fact one after the other. This is why they are running one after the other. To nest them - you have to put them inside of each other. eg:
Not nested
(1..iter.to_i).each do |i|
# stuff for loop 1 is done here
end # this closes the first loop - the entire first loop will run now
(1..iter.to_i).each do |j|
# stuff for loop 2 is done here
end # this closes the second loop - the entire second loop will run now
Nested:
(1..iter.to_i).each do |i|
# stuff for loop 1 is done here
(1..iter.to_i).each do |j|
# stuff for loop 2 is done here
end # this closes the second loop - the second loop will run again now
# it will run each time the first loop is run
end # this closes the first loop - it will run i times
A: Wouldnt something like this solve your problem?
(1..iter.to_i).each do |i|
num1 = (3.9) * num1.to_f * (1-num1.to_f)
print num1
num2 = (3.9) * num2.to_f * (1-num2.to_f)
print num2
end
From what I can see you dont even use the i variable. So in theory you could just do
iter.to_i.times do
# stuff
end
| |
doc_23536511
|
As is the error i recieve:
$ hello.rb
./hello.rb: line 8: class: command not found
./hello.rb: line 10: attr_accessor: command not found
./hello.rb: line 11: syntax error near unexpected token `('
./hello.rb: line 11: ` def initialize(name,cash,zip)'
and if i move my loop from the bottom to the top:
$ hello.rb
./hello.rb: line 6: syntax error near unexpected token `('
./hello.rb: line 6: `def main()'
hello.rb:
#
#
#
#
#
class Person
#Attribute accessor methods (accessor=writer+reader)
attr_accessor :name,:cash,:zip,:credit_card
def initialize(name,cash,zip)
@name=name
@cash=cash
@zip=zip
@credit_card=nil
end
end
#Ruby class naming convention: FirstLetterCapCamelCase
class Account
attr_accessor :account_name
#No writer attribute method for balance
attr_reader :balance
def initialize(Person)
time=Time.new
@key="Kudzu"
@Person=Person
@Atm=Atm.new
#seed the random number generator to get a new random set
#for each new instance of bank
srand(time.sec)
#Ruby naming convention for variables and methods is lowercase this_that
@name=Person.name
@balance=nil
@accounts=nil
# (#items, initial values) (ranndom range 100-999)
@credit_card = {"card_number"=>Array.new(4,1000+rand(9999)),"exp_month"=>time.month,"exp_year"=>time.year+4,"security_code"=>100+rand(999),"zip_code"=>Person.zip, "pin"=>@pin}
puts("Hello I'm glad you came in here's your new card #{@credit_card[card_number]}")
while(true)
puts("Please enter your pin so that i can initialize your card (1234) >> ")
temp = gets.chomp
if(temp.is_a?Numeric&&temp.lenth===4)
@pin = temp
break
puts("Pin must be a 4 digit number")
end
Person.credit_card=@credit_card
Atm.add_account(Person,credit_card,Base64::encode(key),Account)
puts("New account created, thanks for signing up #{account_name}!")
end
def withdraw(amount, Person, key)
if(Base64::decode(key)===@key)
if(@balance>=amount)
@balance-=amount
Person.cash+=amount
puts("Balance after withdraw: $#{this.balance}")
return true
else
puts("Insufficient Funds ):")
return false
end
else
puts("Access Denied")
return false
end
end
def deposit(amount, Person, key)
if(Base64::decode(key)===@key)
if(Person.cash>=amount)
# Negative amount
Person.cash+=amount-amount*2
@balance+=amount
puts("Balance after deposit: $#{this.balance}")
return true
else
puts("Show me the money!")
return false
end
else
puts("Access Denied")
return false
end
end
def transfer(ToAccount, ToPerson, FromPerson, amount, key)
if(Base64::decode(key)===@key)
if(withdraw(amount,FromPerson))
ToAccount.deposit(amount,ToPerson)
return "#{amount} has been transfered from #{account_name}'s account to #{ToAccount.name}'s account. Your remaining balance after this transaction is $#{@balance}"
end
else
puts("Access Denied")
return false
end
end
end
class Atm
@people={}
@accounts
@card={}
@Account
#Encoding is not encryption to do this: gem install encryptor
#I didn't take the time to learn how to implement encryption but..
#Neo "Do you know how to fly this thing?" Trinity "Not yet.."
@key="Kudzu"
#Ruby Convention is to use {} for a single line method body
def add_account(Person,credit_card,key,Account)
if(Base64::decode(key)===@key)
@people[credit_card]=Person
@accounts[credit_card]=Account
@Account=Account
else
puts("Access Denied")
return false
end
end
#Syntactical Sugar
def get_pin()
while(true)
puts("Ener Your Pin Number or (C)ancel >> ")
#The method chomp of the object gets returns user input without the trailing /n
temp=gets.chomp
if(temp===@card[pin])
@Person=@people[card]
req_action()
break
end
if(temp==="C")
break
end
puts("Didn't catch that try again")
end
def start_transaction(card)
get_pin()
end
private
def deposit()
puts("How much would you like to deposit >> ")
temp=gets.chomp
if(temp.is_a? Numeric)
@Account.deposit(temp, @Person, Base64::encode(key))
else
puts("Didn't catch that try again")
deposit()
end
end
def withdraw()
puts("How much would you like to withdraw >> ")
temp=gets.chomp
if(temp.is_a? Numeric)
@Account.deposit(temp, @Person, Base64::encode(key))
else
puts("Didn't catch that try again")
deposit()
end
end
def transfer()
puts("How much would you like to transfer >> ")
amount=gets.chomp
if(temp.is_a? Numeric)
puts("Card number of reciever (1234 5678 9123 4567)>> ")
temp=gets.chomp
#gsub = replace all
#\s+ = one more more white space characters
#m = multiline
#strip = remove white space from beg & end
#split will return the values split by given delimiter
temp=temp.gsub(/\s+/, ' ').strip.split(" ")
Person=@accounts[temp]
if(Person)
@Account.transfer()
deposit(@accounts[temp], @people[temp], @Person, amount, Base64::encode(key))
else
puts("We can only transfer to clients of the same bank (incorrect card number)")
transfer()
end
else
puts("Didn't catch that try again")
end
end
def req_action()
puts("Would you like to (W)ithdraw (D)eposit or (T)ransfer >> ")
temp=gets.chomp.upcase
temp=temp.upcase
#I wonder is it the Ruby convention to not have the when cases indented in the case conditional SublimeText seems to think so
case temp
when "W"
withdraw()
when "D"
deposit()
when "T"
Transfer()
else
puts("Didn't catch that try again")
req_action()
end
while(true)
puts("Leave Atm (y/n) Another Transaction >> ")
continue=true
temp=gets.chomp
temp=temp.upcase
case temp
when "Y"
puts("Returning Card")
continue=false
when "N"
req_action()
else
"Your fingers are too fat please try again"
end
if(!continue)break
end
end
end
while(true)
#return list of all instances of class Person in array people
$people=Person.all_offspring
$atm=Atm.all_offspring[0]
puts("would you like to go to the atm (a/r) or register a new account >> ")
temp=gets.chomp
temp=temp.upcase
case temp
when "A"
if(people)
while(true)
contine=true
puts("Who are you? #{people}")
temp=gets.chomp
for x in people
if(temp===people[x].name)
Person=people[x]
continue=false
end
end
if(!continue) break
end
end
$atm.start_transaction(Person.credit_card)
when "R"
puts("What is your name >> ")
name=gets.chomp
money=nil
zip=nil
loop do
done=false
puts("How much money do you have >> ")
temp=gets.chomp
if(temp.is_a?Numeric)
money=temp
done=true
break
else
"Not a number"
end
end
loop do
done=false
puts("What is your zip code >> ")
temp=gets.chomp
if(temp.is_a?Numeric)
if(temp.length===5)
money=temp
done=true
break
else
puts("invalid length")
end
else
puts("not a number")
end
end
else
"invalid input"
end
end
A: These are error messages from some shell, not Ruby. What you have there is a Ruby script. You need to run your Ruby script with Ruby. Your shell doesn't understand Ruby, it only understands its own language.
A: put
#!/usr/bin/env ruby
at the top of your script (assuming your using linux )
| |
doc_23536512
|
Can I do like this ?
var lst = (somecondition) ? _db.Employees
.Where(a => a.EmployeeID.Equals(employeeId))
: _db.Departments
.Where(a => a.deptsID.Equals(deptId));
If my trying to do this it is throwing an error like this
Type of conditional expression cannot be determined because there is
no implicit conversion between System.Linq.IQueryable<Employee> and
System.Linq.IQueryable<Department>
Can any one give me suggestion to me.
A: If those two entities don't share a common base class or a common interface, you cannot. Well technically you could put them both into a list of objects, but that's not what you want. Think about the program, how would you know if the list contains employees or departments and what would you do with them if they have nothing in common.
A: They should be of the same type (this is why the compiler complains).
var is a syntactic sugar expression, so instead of writing something like:
ObservableCollection<SomeLongTypeHere> myCollection = new
ObservableCollection<SomeLongTypeHere> ();
you can write
var myCollection = new
ObservableCollection<SomeLongTypeHere> ();
And the compiler will know that var stands for ObservableCollection<SomeLongTypeHere>
What you try to do is like doing this:
var someVar = (condition) ? (int) 5 : (string) "some string";
The compiler can't set a type (is it an int? is it a string?), and hence, complains.
Edit:
Ok, first of all, i'm sorry, but your variable names s**ks ...
As a general rule, you want your variables to be meaningful, especially if you're asking people to read them and help you out with your problems (note, your problems, not theirs) ...
So, don't use things like :
var query = (from a in lst ...
use variable names that make sense, and are meaningful, for example:
var query = (from employee in employee_list ...
Now, lst is just as bad... have a employees_list or departments_list (or if you must: empLst or dptLst, but i highly suggest using long names that are meaningful. You'll spend more time reading it than writing it ... trust me on this).
Having said that, your lst is basically all the entries where employee ID is the same as that variable I assume.
You could either use 2 lists, and then depending on your condition use the proper list, or better yet, fork on the condition with an if/else and get the data.
You wouldn't mix entities into a var, because you can't really use them that way. Your GUI will depend on the properties of those objects, and hence it makes no sense to dynamically try to get a list of employees or departments into a general (var) in order to process them.
Without more details, I can't help further, but my first part answered the question you've posted: You can't do it that way (and if you could, you really shouldn't, because it'll be a hack at best and just cause grief down the road)
A: This is useless, but you can :
object lst = (somecondition) ? (object)_db.Employees
.Where(a => a.EmployeeID.Equals(employeeId))
: _db.Departments
.Where(a => a.deptsID.Equals(deptId));
Both list will cast themselves to object. You will not be able to do anything with that variable, but it works.
A: Change the part to this:
object lst = (somecondition) ? (object)_db.Employees.**AsEnumerable()**
.Where(a => a.EmployeeID.Equals(employeeId))
: _db.Departments.**AsEnumerable()**
.Where(a => a.deptsID.Equals(deptId));
Notice this will change to "IEnumerable". LINQ-TO-OBJECT——because not every LINQ can be converted to a standard SQL.
A: In order to set the two different types into a single varaible, you will need to some how use polymorphism (you can read about it in Wikipedia).
If you think about it, after you assign the variable what would you do with it?
Lets assume Employee has method, Foo while Department has method Bar.
What would you do with the object returned from the query?
Will you attempt to call instance.Foo()? but what if it a Department?
So how about instance.Bar()? but what if it an Employee?
You need to call a method that you (and the compiler) know that exists in both classes.
This is where polymorphism kicks in.
You need to be able to refer to both in the same manner i.e. by the their common base class or by an interface they both Implement.
Of course, In .Net all object derives from the object class so you can always input them into an object list and than check for results. but IMHO this is not a very elegant solution.
| |
doc_23536513
|
Is there not a way to do this?
Here's my code for what I'm currently doing:
let requestMe = FBSDKGraphRequest(graphPath: "me",
parameters: ["fields": "first_name, last_name, email, picture.width(1080).height(1080)"])
let requestThumbnailSizedPhoto = FBSDKGraphRequest(graphPath: "me",
parameters: ["fields": "picture.width(100).height(100)"])
let connection = FBSDKGraphRequestConnection()
connection.addRequest(requestMe) { (connection, result, error) -> Void in
print("RequestMe complete")
}
connection.addRequest(requestThumbnailSizedPhoto) { (connection, result, error) -> Void in
print("RequestThumbnailSizedPhoto complete")
}
connection.start()
| |
doc_23536514
|
Below is my report function. Instead of declaring and setting the MaxRFWIDRange in the function, I'd rather reference a report variable with the same name.
Function ValidateRFWIDRange(FromRFW As Integer, ToRFW As Integer) As Boolean
Dim DiffRFW As Integer
Dim MaxRFWIDRange As Integer
MaxRFWIDRange = 10000
DiffRFW = ToRFW - FromRFW
If DiffRFW > MaxRFWIDRange Then
Return False
Else
Return True
End if
End Function
A: It looks like you can do this.
I tested this by adding a variable TestVariable to a report, then adding the following custom code:
Function TestVariableFunctionality(var as Microsoft.ReportingServices.ReportProcessing.OnDemandReportObjectModel.Variable) As String
Return var.Value
End Function
I called the function from a textbox like so:
=Code.TestVariableFunctionality(Variables!TestVariable)
This outputs the variable's value in the textbox as a string.
You must declare the full namespace as Microsoft.ReportingServices.ReportProcessing.OnDemandReportObjectModel.Variable, because Variable alone is not defined. See below for more info.
Accessing variable in SSRS function
From an MSDN blog:
Assume that you've created a report variable named "Reportvariable1".
All you need is a piece of custom code.
Public Function SetVariableValue(val as Microsoft.ReportingServices.ReportProcessing.OnDemandReportObjectModel.Variable)
val.Value = val.Value + 2
End Function
As simple as that. All i'm doing in the function is, take the report variable reference, add 2 to the existing value. That's it.
How you can call this function from your report item?
=Code.SetVariableValue(Variables!Reportvariable1)
This will do the magic. Also note that in the above expression i'm just passing the variable reference and not its value.
| |
doc_23536515
|
This works fine:
'{4,0,0}' < '{4,1,0}' # yields TRUE
Still, I am having issues when array lengths are different:
'{4}' < '{5,0,0}' # yields TRUE
'{4,1,2}' < '{4,1}' # also yields TRUE when it should be FALSE
I couldn't find anything related to this specific issue in the documentation. How can I achieve what I am after? Would be great if the array with fewer elements would get right padded with zeros (that would lead to my expected behaviour).
A: One approach is to standardize the array length for all versions such that when you make the array conversion'{4,1}' is '{4,1,0}'.
You can check the number of elements in each array after conversion using array_length(array,dimension) (in this case dimension is 1) and then append
using array_append(array, element) (in this case, element is 0) one or two zeros depending on the returned value.
Then when you make the comparisons:
'{4,0,0}' < '{5,0,0}' # will still yield TRUE
'{4,1,2}' < '{4,1,0}' # will now correctly yield FALSE
EDIT: as commented below, this is only the case where each element of the original array consists of a single digit integer or numeric character. Since the entire string is being compared, if the numeric elements of the string are more than a single characters in length, it could fail.
| |
doc_23536516
|
HTML
<div id="myDiv"></div> <button>Get info</button>
XML UPDATED*
<?xml version="1.0" encoding="utf-8"?>
<main><person>
<name>Bhupesh</name>
<last>Lohani</last>
</person>
<person>
<name>Kamal</name>
<last>Sandhu</last>
</person>
<person>
<name>Ravi</name>
<last>Kumar</last>
</person></main>
SCRIPT UPDATED*
$(document).ready(function(e) {
$("button").click(function(){
var htmlStr = '';
$.ajax({
type:'get',
url:"xml.xml",
cache: false,
dataType: "xml",
success:function(result){
var main = $(result).find('main');
$(main).each(function( index ) {
var person = $(this).find('person')
var name = $(person).find('name').text();
var lastName = $(person).find('last').text();
//console.log(name + ' | ' + lastName);
htmlStr += '<p><b>' + name + '</b> - ' + lastName + '</p><br/>';
});
$("#myDiv").append(htmlStr);
}});
});
});
Its not showing anything when i click on my button please help me guys
UPDATE
Friend i have did few modification in my code now its shoing like
BhupeshKamalRavi - LohaniSandhuKumar
I want every name and last name should be show like
Bhupesh - Lohani
Kamal - Snadhu
Ravi - Kumar
Please Help me friends
Thanks in advance..:)
A: Check the scope of htmlStr variable. Its only inside the each callback method. You need to define it outside the each call back scope. May be define it just under main variable.
var main= ... ;
var htmlStr = '';
As per your updated request. I see that you are not iterating over person, you are just iterating over 'main'. $(main).find('person') will result in assigning both person elements to 'person' variable. ANd subsequently, $(person).find('name') result in getting first name from both person elements.
you can quickly fix this by iterating over person.
var main = $(result).find('main');
var htmlStr = '';
$('person', main).each(function (index) {
var person = $(this);
var name = $(person).find('name').text();
var lastName = $(person).find('last').text();
console.log(name + ' | ' + lastName);
htmlStr += '<p><b>' + name + '</b> - ' + lastName + '</p><br/>';
});
$("#myDiv").append(htmlStr);
| |
doc_23536517
|
[cloudera@quickstart Desktop]$ ./launch_mapreduce.sh
# JMH 1.10 (released 5 days ago)
# VM invoker: /usr/java/jdk1.7.0_67-cloudera/jre/bin/java
# VM options: -Dproc_jar -Xmx1000m -Xms825955249 -Xmx825955249 -Djava.net.preferIPv4Stack=true -Dhadoop.log.dir=/usr/lib/hadoop-yarn/logs -Dyarn.log.dir=/usr/lib/hadoop-yarn/logs -Dhadoop.log.file=yarn.log -Dyarn.log.file=yarn.log -Dyarn.home.dir=/usr/lib/hadoop-yarn -Dhadoop.home.dir=/usr/lib/hadoop-yarn -Dhadoop.root.logger=INFO,console -Dyarn.root.logger=INFO,console -Djava.library.path=/usr/lib/hadoop/lib/native
# Warmup: 5 iterations, 1 s each
# Measurement: 5 iterations, 1 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Throughput, ops/time
# Benchmark: mgm.tp.bigdata.ma_mapreduce.MapReduceBenchmark.test
# Run progress: 0.00% complete, ETA 00:00:10
# Fork: 1 of 1
Error: Could not find or load main class org.openjdk.jmh.runner.ForkedMain
<forked VM failed with exit code 1>
<stdout last='20 lines'>
</stdout>
<stderr last='20 lines'>
Error: Could not find or load main class org.openjdk.jmh.runner.ForkedMain
</stderr>
# Run complete. Total time: 00:00:00
Benchmark Mode Cnt Score Error Units
my shell script is the following:
/usr/bin/yarn jar ma-mapreduce-benchmark.jar
and my benchmark options are:
public static void main(String[] args) throws Exception {
Options opt = new OptionsBuilder()
.include(MapReduceBenchmark.class.getSimpleName())
.warmupIterations(5)
.measurementIterations(5)
.forks(1)
.build();
new Runner(opt).run();
}
A: In my opinion jhm not wrok on hadoop cluster, because in each node of the cluster the benchmark want start a own jvm. That not work, the node communicate for the parallelization. First I measure the time for the execution of the program and repeat this, at the end I calculate the fault tolerance.
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class MapReduceBenchmarkLauncher {
private static List<Long> times = new ArrayList<Long>();
public static void main(String[] args) throws Exception {
Properties pro = new Properties();
pro.load(MapReduceBenchmarkLauncher.class.getResourceAsStream("/config.properties"));
int benchRounds = Integer.parseInt(pro.getProperty("benchmark.rounds"));
for(int i=0;i<benchRounds;i++) {
JobMain jm = new JobMain();// app being tested
long start = System.nanoTime();
jm.run();
long end = System.nanoTime();
times.add(end-start);
}
writeTimekeepingToFile(times, "mapreduce_benchmark");
}
public static void writeTimekeepingToFile(List<Long> times, String benchfile) throws Exception {
// arithmetic mean
double am = 0;
for(int i=0;i<times.size();i++) {
am = am + times.get(i);
}
am = am / times.size();
// varinaz calculation
double v = 0;
for(int i=0;i<times.size();i++) {
v = v + (times.get(i)-am)*(times.get(i)-am); // no math lib, cause long
}
v = v / times.size();
// calculating standard deviation
double s = Math.sqrt(v);
// output
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(benchfile), "utf-8"));
for(int i=0;i<times.size();i++) {
br.write("round "+(i+1)+": "+times.get(i)+" ns\n");
}
br.write("varianz: v="+v+"\n");
br.write("standard deviation: t=("+am+" \u00B1 "+s+") ns" );
br.close();
}
}
| |
doc_23536518
|
A: Take a look at ScanResult, it has field level which is "detected signal level in dBm".
You can use WifiManager.getScanResults() to get latest scan results.
A: In conjunction with the previous answer, you can add code inside of the following timer to check it every few seconds. Of course you can modify how long you want the timer to execute.
var timer = new Timer();
timer.Tick += new EventHandler(timer_Tick);
timer.Interval = 2000; //2 seconds
timer.Start();
void timer_Tick(object sender, EventArgs e)
{
..your code here..
}
| |
doc_23536519
|
I am loading Ads through an AdManager class which holds references of the loaded Ads. I also have a destroy() method in my AdManager class which I call to destroy all referenced Ads for the calling RecyclerView.
In my RecyclerView Adapter I also have a destroy() method where I call the destroy() method of the AdManager.
The destroy() method from my Adapter is called in the onDestroyView() method of the Fragment containing the RecyclerView. The Fragment lies within a Activity which has a parent activity.
When I go back to the parent activity the leak occurs.
┬───
│ GC Root: Local variable in native code
│
├─ Bu instance
│ Leaking: NO (PathClassLoader↓ is not leaking)
│ Thread name: 'CleanupReference'
│ ↓ Bu.contextClassLoader
├─ dalvik.system.PathClassLoader instance
│ Leaking: NO (AdManager↓ is not leaking and A ClassLoader is never leaking)
│ ↓ PathClassLoader.runtimeInternalObjects
├─ java.lang.Object[] array
│ Leaking: NO (AdManager↓ is not leaking)
│ ↓ Object[].[92]
├─ com.example.projects.utility.AdManager class
│ Leaking: NO (a class is never leaking)
│ ↓ static AdManager.mInstance
│ ~~~~~~~~~
├─ com.example.projects.utility.AdManager instance
│ Leaking: UNKNOWN
│ ↓ AdManager.mAdLoader
│ ~~~~~~~~~
├─ com.google.android.gms.ads.AdLoader instance
│ Leaking: UNKNOWN
│ ↓ AdLoader.zzacr
│ ~~~~~
├─ com.google.android.gms.internal.ads.zzcwt instance
│ Leaking: UNKNOWN
│ ↓ zzcwt.zzgpi
│ ~~~~~
├─ com.google.android.gms.internal.ads.zzcxj instance
│ Leaking: UNKNOWN
│ ↓ zzcxj.zzgpz
│ ~~~~~
├─ com.google.android.gms.internal.ads.zzcxr instance
│ Leaking: UNKNOWN
│ ↓ zzcxr.zzgqh
│ ~~~~~
├─ com.google.android.gms.internal.ads.zzbpi instance
│ Leaking: UNKNOWN
│ ↓ zzbpi.zzfph
│ ~~~~~
├─ com.google.android.gms.internal.ads.zzdod instance
│ Leaking: UNKNOWN
│ ↓ zzdod.zzhfl
│ ~~~~~
├─ com.google.android.gms.internal.ads.zzdtz instance
│ Leaking: UNKNOWN
│ ↓ zzdtz.value
│ ~~~~~
├─ com.google.android.gms.internal.ads.zzbph instance
│ Leaking: UNKNOWN
│ ↓ zzbph.zzfpg
│ ~~~~~
├─ java.util.ArrayList instance
│ Leaking: UNKNOWN
│ ↓ ArrayList.elementData
│ ~~~~~~~~~~~
├─ java.lang.Object[] array
│ Leaking: UNKNOWN
│ ↓ Object[].[0]
│ ~~~
├─ com.google.android.gms.internal.ads.zzdul instance
│ Leaking: UNKNOWN
│ ↓ zzdul.value
│ ~~~~~
├─ com.google.android.gms.internal.ads.zzccd instance
│ Leaking: UNKNOWN
│ ↓ zzccd.zzfwg
│ ~~~~~
├─ com.google.android.gms.internal.ads.zzcde instance
│ Leaking: UNKNOWN
│ ↓ zzcde.zzbnm
│ ~~~~~
├─ android.widget.FrameLayout instance
│ Leaking: YES (View.mContext references a destroyed activity)
│ mContext instance of com.example.projects.ui.DynamicActivity with mDestroyed = true
│ View#mParent is set
│ View#mAttachInfo is null (view detached)
│ View.mWindowAttachCount = 1
│ ↓ FrameLayout.mContext
╰→ com.example.projects.ui.DynamicActivity instance
Leaking: YES (ObjectWatcher was watching this because com.example.projects.ui.DynamicActivity
received Activity#onDestroy() callback and Activity#mDestroyed is true)
To be more precise, how can or better said when do I destroy my unified native ad view when it is in a RecyclerView Viewholder. I don't mean the ad object itself, I mean the ad view from xml file.
A: you should destroy the ad before the activity / fragment get destroyed
in activity
@Override
public void onDestroy() {
if (nativeAd != null) {
nativeAd.destroy();
}
super.onDestroy();
}
in fragment:
@Override
public void onDestroyView() {
if (nativeAd != null) {
nativeAd.destroy();
}
super.onDestroyView();
}
A: from official documentation:
Ensure that all NativeAd references are destroyed in your activity's
onDestroy() method.
In your onNativeAdLoaded callback, make sure to destroy any existing
native ads that will be dereferenced.
Another key check is if the activity is destroyed and if so, call
destroy() on the returned ad and return immediately:
final AdLoader adLoader = new AdLoader.Builder(this, "ca-app-pub-3940256099942544/2247696110")
.forNativeAd(new NativeAd.OnNativeAdLoadedListener() {
@Override
public void onNativeAdLoaded(NativeAd ad) {
// If this callback occurs after the activity is destroyed, you
// must call destroy and return or you may get a memory leak.
// Note `isDestroyed()` is a method on Activity.
if (isDestroyed()) {
ad.destroy();
return;
}
...
}
}).build();
| |
doc_23536520
|
There all separate locations: Africa | Wales, UK | Stockholm, Sweden and I want to search for locations that are the same and display them, the following code works if there is one word in the column but not if there are multiple.
<?php
$sessionid = $_SESSION['id'];
$sql = "SELECT * FROM users WHERE id = '$sessionid';";
$rsults = mysqli_query($conn, $sql);
$resultsCheck = mysqli_num_rows($rsults);
if ($resultsCheck > 0) {
while ($row = mysqli_fetch_assoc($rsults)){
$follow = $row['follow'];
$loc = $row['places'];
}
}
$sql = "SELECT * FROM posts WHERE ext LIKE '$loc' OR username LIKE '$follow' ORDER BY `a_date` DESC LIMIT 4";
$rsults = mysqli_query($conn, $sql);
$resultsCheck = mysqli_num_rows($rsults);
if ($resultsCheck > 0) {
while ($row = mysqli_fetch_assoc($rsults)){
echo '<div class="posts">';
echo '<img class="img"src='.$row['img'].' width="1500px">';
echo '</div>';
echo '<div class="contain">';
echo '<div class="over">';
echo '<div class="username2">';
echo '<img src="focus.png" width="25px" height="25px" style="padding-right: 10px;">'.'<a href="./Profile.php?data='.$row['username'].'">'.$row['username'].'</a>'.'<img src="loc.png" width="25px" height="25px" style="padding-right: 5px; padding-left: 10px;">'.'<a href="./Location.php?data='.$row['ext'].'">'.$row['ext'].'</a>';
echo '</div>';
echo '<div class="content">';
echo $row['content'];
echo '</div>';
echo '</div>';
}
}
?>
Also I know this is open to sql injection, it's just a proof of concept. Thanks for the help!!
A: When using LIKE you should add '%' sign at start and/or at end of LIKE parameter so it won't search for identical term but one starting or ending with the string you provided. Something like:
$sql = "SELECT * FROM posts WHERE ext LIKE '%$loc%' OR username LIKE '$follow' ORDER BY `a_date` DESC LIMIT 4";
So it will find location that contains your search criteria and not just those identical to it. '%' is replacing any number of characters here.
This goes if you have one search term and you have multiple terms in database column. But if you have multiple search terms you will have to generate your query dynamically, adding one "OR ext LIKE '%$loc%'" for every term.
A: like operator in mysql comes with wild card e.g. '%', '_' etc.
you can use mysql query like this
$sql = "SELECT * FROM posts WHERE ext LIKE '%$loc%' OR username LIKE '$follow' ORDER BY `a_date` DESC LIMIT 4";
for example if $loc = 'canada', it will return all the rows which have 'canada' in thier column whether the column contains 'canada, abc' or 'abc, canada'
A: Use an "%" sign when using the LIKE functionality.
$sql = "SELECT * FROM posts WHERE ext LIKE '%$loc%' OR username LIKE '$follow' ORDER BY `a_date` DESC LIMIT 4";
This would allow you to search through the content of a field.
| |
doc_23536521
|
*
*main.cpp
*template.sth
*much more
For each .cpp file I am generating .o file.
Thanks to that I could write simple rule for all .o targets (simplified, a little bit pseudcode version for more clarity):
OBJS = #list of all .o files needed
%.o: %.cpp
g++ -MM -MF %.d -MP -MT %.o %.cpp
g++ -c -o %.o %.cpp
Then I am including all existing .d files, so after each generation I am refreshing dependencies.
It worked unless I had template.sth. This file contains some template for generating h files and cpp files.
When one file, i.e. main.cpp includes file generated from template.sth (lets say gen.h):
*
*Instruction generating .d file doesn't work, because gen.h is missing:
fatal error: gen.h: No such file or directory include "gen.h"
*Even if these instructions would work there is a problem with my "workflow". Untill now I could generate .d file for next make. It worked, because adding new dependencies require to change one of current dependecnies. So after adding one .o is rebuilding and new .d is generated. Now I need to detect that before making .o I need to generate gen.h from template.sth.
Is there any way to do it automatically? Problem 1. could be solved if there is some way to tell g++ that if some .h file is missing it can just add it to dependencies.
After solving problem 1. executing make multiple times (I think twice is always enough) end up with built project (first make would generate dependencies files, then second make sees that main.cpp depends on gen.h, gen.h is missing and there is instruction how to create gen.h so it will create gen.h before building main.o).
If it can't be done somehow automatically, how can it be solved? Can I write in Makefile instructions which will build all generated files before any other or I need to manually add this generated file as dependencies in all .o instructions?
UPDATE:
After few changes, with -MG flag g++ generates correct files even for gen.h. I can build my project now with two make commands.
First one will create correct .d files and break, because gen.h is missing.
Second one will have .d files ready, so it will generate gen.h before building main.o, so building main.o will be successful.
Is there a way to generate .d file and then use it, before generating .o?
A: You need to add dependencies for the generated files:
gen.h: template.sth
...command to create gen.h from template.sth
If you have lots of generated files, you might want a way of creating those dependencies automatically, which would depend on how you are generating them.
In addition, you want to generate the .d files independently from the .o files and use the -MG flag while generating them to ignore missing files:
%.d: %.cpp
g++ -MM -MF $@ -MP -MG $<
-include $(OBJS:.o=.d)
This way, the first time you run make, it will generate the .d files with the dependencies and then reread them and recompute all the dependencies before trying to build anything else.
| |
doc_23536522
|
What I noticed was that for some C++ programs, when I have a memory overwrite bug in that program, it would usually (if not always) show up in a specific section of code which was often unrelated to the section of code with the bug. This is not a blanket observation. Not all C++ programs behave this way. But when I have one, it is pretty consistent. (No comment on why my code has enough memory overwrites that I have the opportunity to notice consistent-anything :) )
I'm not asking why a memory overwrite in function1 can show up in function2; that is understood. My observation is that over the life of a given program, we have discovered memory overwrites in function1, function2, function3, function4, and function5. But in each case, we discovered the problem because the code would crash in function6. Always in function6 and only in function6. None of those functions are related and do not touch anything that function6 uses.
Over my lifetime, I've encountered two C programs and one C++ program that behaved this way. These were years apart in unrelated systems and hardware. I just found it weird and wondered if anyone else has seen this. Plus, I suspect that I may be seeing the same pattern in a C++/JNI/Java program that I'm working on now, but it is young enough that I've not had enough hits to be sure of a pattern.
A: Perhaps the real question here is about what escalates "silent" memory corruption into an actual/formal crash (as opposed to "just" more subtle problems such as unexpected data values, that the user might or might not notice or recognize). I don't think that question can be answered generally, as it depends a lot on the specifics of the compiler, the code, the memory layout of the in-memory data structures, etc.
It can be said that in most modern (non-embedded) systems there is an MMU that handles translating virtual (i.e. per-process) memory addresses into physical memory addresses, and that many user-space crashes are the result of the MMU generating an unrecoverable page fault when the user program tries to dereference a virtual address that has no defined physical equivalent. So perhaps in this case function6() was trying to dereference a pointer whose value had been corrupted in such a way that the MMU couldn't translate it to a physical address. Note that the compiler often places its own pointers on the stack (to remember where the program's control flow should return to when a function returns), so a bad pointer dereference can happen even in code that doesn't explicitly dereference any pointers.
Another common cause for a crash would be a deliberately induced crash invoked by code that notices that the data it is working with is "in a state that should never happen" and calls abort() or similar. This can happen in user code that has assert() calls in it, or in system-provided code such as the code that manages the process's heap. So it could be that function6() tried to allocate or free heap memory, and in so doing gave the heap manager the chance to detect an "impossible state" in one of its data structures and crash out. Keep in mind that the process's heap is really just one big data structure that is shared by all parts of the program that use the heap, so it's not terribly surprising that heap corruption caused by one part of the program might result in a crash later on by another (mostly unrelated) part of the program that also uses the heap.
| |
doc_23536523
|
When I type python in the terminal it opens python version 2.6. I want it to open python 2.7
How do I make Python 2.7 open by default?
A: Because my account does not have the admin permission. I work around to set the config in ~/.zshrc or ~/.bashrc. Now I give a example that I assume you installed python 3.7. If you installed the other version, just change the version will be fine.
*
*~/.zshrc solution
$ echo "alias python=/usr/local/bin/python3.7" >> ~/.zshrc
$ source ~/.zshrc
*~/.bashrc solution
$ echo "alias python=/usr/local/bin/python3.7" >> ~/.bashrc
$ source ~/.bashrc
*check the result
$ python --version
# print result Python 3.7.1
The other solutions please refer to : https://opensource.com/article/19/5/python-3-default-mac
A: The python.org installers for Python 2.x on OS X by default modify shell profiles (for the standard shells like bash and csh) to add its framework bin directory to the front of your shell path. Assuming you did not deselect the option during installation, there should now be the following in your .bash_profile file.
# Setting PATH for Python 2.7
# The orginal version is saved in .profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/2.7/bin:${PATH}"
export PATH
But this profile is only executed by default when you launch a new terminal window; it won't apply to existing terminal sessions. So make sure you open a new one and then try again. If you are using a different shell, you may need to modify that shell's startup to do the equivalent.
The python.org installers for Python 3.x on OS X do not select the shell script modification option by default. You can enable it at installation or you can later run the Update Shell Profile.command file in the corresponding Python x.x folder in the Applications folder. Or you can just manually edit the right profile.
A: The easier solution is to install it via MacPorts:
sudo port install python_select
port search python # Search for version you are looking for
sudo port install python27
sudo port select --set python python27
A: Add followings to your ~/.bash_profile
# Setting PATH for Python 2.7
PATH="/path/to/your/python2.7/bin:${PATH}"
export PATH
Save the file and reopen the terminal.
| |
doc_23536524
|
Because I read from Tomcat documentation.
WebappX — A class loader is created for each web application that is deployed in a single Tomcat instance. All unpacked classes and resources in the /WEB-INF/classes directory of your web application, plus classes and resources in JAR files under the /WEB-INF/lib directory of your web application, are made visible to this web application, but not to other ones.
Eg. That multiple versions of a library called a-1.0.jar and a-2.0.jar that will be stored in WEB-INF/lib.
In WEB-INF/services, have myApp.arr and otherApp.arr.
myApp.arr will use a-1.0.jar only
otherApp.arr will use a-2.0.jar only
I had tried to put those libraries in WEB-INF/lib but it prompt errors NoSuchClassFound.
| |
doc_23536525
|
Similarly, I am aware that setting the WHERE clause to KEY-value that matches everything is supposed to work. However, doesn't appear to work on mysql-workbench - at least not the way I hoped (or the way it did work on the console).
For example, the following didn't work on mysql-workbench (but did on the console):
UPDATE FUEL_SOURCES AS FS
INNER JOIN
FUEL_CATEGORY FC ON FC.FUEL_CATEGORY = FS.FUEL_CATEGORY
SET
FS.FUEL_CATEGORY_ID = FC.ID
WHERE
FC.ID <> 0 AND FS.ID <> 0
...If I explicitly / exactly set the ID's (e.g. WHERE FC.ID = 20 AND FS.ID <> 10 for example) it would work in mysql-workbench. But doing this would involve iterating through every key-pair combination.
Be intereted to know what is causing this behaviour, or if I am doing something horribly wrong. Using mysql-workbench 6.3
A: From https://dev.mysql.com/doc/workbench/en/workbench-faq.html#faq-workbench-delete-safe
By default, Workbench is configured to not execute DELETE or UPDATE
queries that do not include a WHERE clause on a KEY column.
Such configuration prevents you from deleting or updating table mistakenly, since you are doing a batch update on data without a key.
To resolve this, as you may be already aware the following options.
*
*Open your Workbench Preferences, select the SQL Editor section, and disable the following preference: "Safe Updates" - Forbid UPDATEs and DELETEs with no key in WHERE clause or no LIMIT clause.
*Run SET SQL_SAFE_UPDATES=0;
A: If you are using workbech, you can first execute
SET SQL_SAFE_UPDATES = 0;
And then execute delete statement
A: If you want to still update your data with safe update on, you must retool your where clause so that it includes references to the table's primary key(s). See this page.
| |
doc_23536526
|
I was thinking of trying to get the inserted row as a result and then test if the result exists and if it matches the inserted values then it was successful -> call my cb function. I'm getting an error that there's something wrong with my query. Is there a better query for this?
var username = user.username;
var password = user.password;
var email = user.email;
client.query(
'INSERT INTO account (username, password, email) OUTPUT
INSERTED.username VALUES($1, $2, $3)',
[username, password, email], (err, res) =>{
if (err) {
console.log(err);
cb(err);
}
console.log(res); // this is undefined how do i test if it was inserted?
client.end();
});
the error that is thrown is "syntax error at or near \"OUTPUT\"
A: That is an invalid syntax for Postgres Insert to return a value. NO such thing as OUTPUT. Try
insert into account (username, password, email)
values($1, $2, $3) returning username;
But really why brother? If the insert doesn't work you can relay on Postgres to raise an exception; if a comparison of the returned value fails, where's the error? In the insert or the data sent, or data result compared to.
| |
doc_23536527
|
What happens now is somewhat of a UI/UX problem: the user logs out from my app but also automatically logged out from Facebook without warning, which can be annoying.
Has anyone resolved this using FB SDK methods or some other function within FB.logout();?
Thanks for helping.
A: Unfortunately this is as designed as noted here: http://developers.facebook.com/docs/reference/javascript/FB.logout/. As this is as designed in the Javascript SDK, I'm fairly confident in making an assumption that a server-side library will yield the same results.
A: You will have to make your own UI dialog for this (or use the deprecated connect javascript sdk). You could either pop up a UI dialog warning that they will be logged out of both your app & out of facebook, or specify a callback method in the FB.logout function which tells them afterwards that they have been logged out of both.
A: I found a trick, that logs the user out of your application just client side, but leaves him logged in on facebook:
FB._authResponse = null;
FB._userStatus = null;
After that, calls to FB.api will return the proper error:
>>> FB.api('me', log)
{"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException"}}
Also FB.getLoginStatus and FB.getAuthResponse are returning null or behave like the user is not logged in:
>>> FB.getLoginStatus(log)
{"status":null,"authResponse":null}
You can even log in the User again with FB.login()
But after a reload, the User will be logged in again automatically, if you have status : true in your FB.init config:
FB.init({
appId : 'yourappid',
status : false, // will not load the user automatically on pageload/refresh
cookie : true, // will leave the userid in FB._userID
oauth : true,
xfbml : true
});
Hope that helps a bit.
| |
doc_23536528
|
Example:$("#start").click();
When I write $("#start").click(); in the Chrome console it's working
Now I need to know how to fire this code from my toolbar button
I'm writing with C#.
I already have the JavaScript code.
I only need to know how to call this function from C#
Here is an image.
EDIT 3:
To be more clearer.
This is the function in C#
private void button1_Click(object sender, EventArgs e)
{
Fire_Javascript_Into_Html_Page("Alert();");
}
I'm guessing this is more clear.
I'm using an add-on to Visual Studio called "add-in-express"
This Add-on makes a toolbar for IE, after compile I have a .msi file that I can install the toolbar
This is what I have: Please look on the image below
A: Use the onclientclick="<scriptname>" property in the button.
Doing it from codebehind, I use something like this
/// <summary>
/// creates a javascript alert in the browser window.
/// </summary>
/// <param name="message">The message you wish the user to see in the alert.</param>
public void AMessage(string message)
{
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "info only", "alert('" + message + "');", true);
}
to fire off a javascript alert from codebehind whenever I want to.
The same principle applies for any script.
A: This is the basic structure of a jQuery click event. Just pass the selector for your button to the second parameter.
$(document).on("click", 'button[id="myButton"]', function () {
var $this = $(this);
var elementClicked = $this.attr("id");
alert(elementClicked);
callMyJavascriptFunction();
});
Here is basic javascript.
<html>
<head>
<script>
function clickButton()
{
alert("Button 1 was clicked!");
}
</script>
</head>
<body>
<form>
<input type="button" id="button1" onclick="clickButton()" value="Button 1" />
</form>
</body>
</html>
| |
doc_23536529
|
import concurrent.futures
import json
import requests
import datetime
import sys
from datetime import datetime
from time import sleep
executor = concurrent.futures.ThreadPoolExecutor(max_workers=5)
poll_worker = None
request_headers = {"Content-Type": "application/json"}
def addBulkListings(bulk_listings):
print("Adding listings")
future = executor.submit(runBulkListings, bulk_listings)
future.add_done_callback(addPollBulkID)
# Future callback
def addPollBulkID(future):
if not future.exception():
poll_id = future.result().json()['results']
print("Polling id: %s" % poll_id)
new_future = executor.submit(pollBulkListing, poll_id)
new_future.add_done_callback(callProcessMatches)
print(new_future.result())
else:
print("Error getting Poll ID")
print(future.exception())
# Future callback
def callProcessMatches(future):
print("callProcessMatches")
if not future.exception():
print("Processing matches")
result = future.result()
new_future = executor.submit(processMatches, result.json())
new_future.add_done_callback(finishBulkListing)
else:
print("Error polling")
print(future.exception())
# Future callback
def finishBulkListing(future):
if not future.exception():
print(future.result())
else:
print("Error processing matches")
print(future.exception())
# Executor called
def processMatches(response):
results = []
for product in response['results']:
processResults(product, results)
return results
# Executor called
def pollBulkListing(poll_id):
start = datetime.now()
overtime = False
while not overtime:
response = requests.get(MAIN_URL + poll_id,
headers = request_headers)
if response.status_code == requests.codes.ok:
return response
sleep(5)
overtime = (datetime.now() - start).seconds >= (1 * 60)
raise requests.exceptions.Timeout
# Executor called
def runBulkListings(bulk_listings):
response = requests.post(MAIN_URL,
data=json.dumps(bulk_listings),
headers = request_headers)
response.raise_for_status()
return response
"addBulkListing" is called by another script, which then begins working with the executor. I've had this work when I only call addBulkListing once, but if I call it twice things fail. Something will go wrong in the "addPollBulkID" method. The print statement there will be executed without an exception, but then the program just exits. Nothing in the "callProcessMatches" is called, with or without an exception. Like I said, when I only call addBulkListings once everything is fine.
Guesses: I've been fooling around with this for a while, but am not sure. In the examples I've seen people use:
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
But that creates a context I don't want. I don't have all of my parameters to the "addBulkListings" function when I first begin, and need to be able to add them in without recreating the executor. Maybe I'm misunderstanding something.
Thanks for any help!
A: Aha! So, I'll answer my own question incase anybody else needs it. Turns out I was able to fix it by switching to:
executor = concurrent.futures.ProcessPoolExecutor(max_workers=5)
Instead of the ThreadPoolExecutor. I'm thinking there was some memory overlap with the threads I was creating. This StackOverflow answer helped me a lot by pointing me in the right direction (Look at the 2nd answer).
| |
doc_23536530
|
How can I do, so that the main thread can not be preemptive by other process or threads ? Thanks a lot!
while(1)
{
auto start_time = std::chrono::high_resolution_clock::now();
LOG_F(INFO, "cyclic start time");
for(int j = 0; j < 150000; j++); //
auto end_time = std::chrono::high_resolution_clock::now();
auto exec_time = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);
LOG_F(INFO, "execution time: %dms", exec_time.count());
if (exec_time.count() < 10)
{
LOG_F(INFO, "i = %d", i);
std::this_thread::sleep_for(std::chrono::milliseconds(10 - exec_time.count()));
}
else
{
LOG_F(ERROR, "execution time was higher than 10ms (%dms)", exec_time.count());
break;
}
}
A: It is working after remove logging statements. Logging is really a mutex hog like @Frebreeze mentioned. Actually the logging statements can be kept in code, just call program with -v ERROR. Thank you very much for the Help !
It looks that the logging is the reason. But why does the logging statements take so long time, but not always, just like a heartbeat ?
A: Correct answer written in original answer in comments:
Shot in the dark. Logging mutex hog. There likely is a mutex/lock
within your logging system. Another thread may be a resource hog
acquiring the lock and not releasing it quickly. This would cause THIS
thread to wait much longer than expected. Check this behaviour by
disabling all other threads and see if behaviour continues.
Follow up help below:
@Jung Glad you figured it out!
If logging is taking variable amounts of time, look into the data you are passing to the logging system. General things to lookout for would be large data structs passed by value. Yes I know compilers are smart now, but just something to keep an eye out for.
One of the methods I sometimes use to reduce log hogs is to use a dedicated thread for writing log statements to file. This thread uses a std::vector or queue. When vector.size() > 8, then dump it to the file(s). If you have a method of setting priority, you can then also then assign prio. This gets us into RTOS ideas. Can look into that if you need strict timings.
Workflow
*
*Suppose sensor1 thread writes log statement.
*
*Sensor1 thread adds data to std::vec
*Suppose sensor2 thread writes log statement
*
*Sensor2 thread adds data to std::vec
....
*
*Once std::vec > 8 fire event to wake up thread
*Thread wakes up, and once given CPU time, begins writing to file
This will help minimize the time spent locking mutexs as well as minimize time spent opening files. However, it is at the cost of memory. Play with the queue size to reach your desired goals.
| |
doc_23536531
|
I am not very good with bash and I feel like this is quite a basic question.
Here is what I have so far:
for m in $(cat finalfile.csv)
do
if [ "$m" = "null" ]
then
m=cwearray[$counter]
let counter++
fi
done
This doesn't replace anything in the finalfile.csv.
For example if the file has:
"value1","value2","null","value3"\n
"value1","value2","null","value3"...
and the array has ["foo","bar"]
I would like it to be:
"value1","value2","foo","value3"\n
"value1","value2","bar","value3"...
A: It's easier in Perl where you can increase the index directly in the replacement part of a substitution:
printf '%s\n' 1,2,3,null null,2,3,4 null,null,null,null \
| perl -pe 'BEGIN { @cwe = qw( A B C D E F ) }
s/(?:^|(?<=,))null(?=,|$)/$cwe[$i++]/g'
Update: It seems you've updated your question with a sample input. If nulls are double quoted, it gets even easier, as there's no need to check whether they're surrounded with commas or beginning/end of the line.
perl -pe 'BEGIN{ @cwe = qw( foo bar ) }
s/"null"/"$cwe[$i++]"/g'
A: can be done with bash, even with multiple nulls per line:
$ cat finalfile.csv
"value1","value2","null","null"
"value1","value2","null","value3"
$ cwearray=( foo bar baz )
$ idx=0
$ while read -r line; do
while [[ $line == *null* ]]; do
line=${line/null/${cwearray[idx++]}}
# ...............^^^^^^^^^^^^^^^^^^
# replace the _first_ "null" with the _next_ array element
done
echo "$line"
done < finalfile.csv > updatedfinalfile.csv
$ cat updatedfinalfile.csv
"value1","value2","foo","bar"
"value1","value2","baz","value3"
A: Read the file line by line. If a line contains null, then use sed to replace all occurrences of null with the corresponding value, retrieved via array index.
#!/bin/bash
file="finalfile.csv"
counter=0
array=(
"foo"
"bar"
)
while read -r line; do
item="${array[$counter]}"
echo "$line" | sed "s/null/$item/g"
((counter++))
done < "$file"
A: An awk solution :
declare -a cwearray
cwearray=(foo bar)
awk -F, 'NR==FNR{repl[NR]=$0; next}{for(i=1;i<=NF;i++){if($i=="\"null\""){$i="\""repl[++counter]"\""}}}1' OFS="," <(for i in "${cwearray[@]}"; do echo "$i"; done) <file>
| |
doc_23536532
|
PageFinished = False
Cancelling = False
OKToUnload = False
WebBrowser.Navigate ("https://www.example.com/index.jsp")
Do While PageFinished = False 'set to true in document complete event
DoEvents
If Cancelling = True Then
OKToUnload = True
GoTo Endline
End If
Loop
PageFinished = False
WebBrowser.Document.All("UserId").Value = txtNumber.Text 'error here
A: Without seeing more of your sample code, I'd venture to guess that this is a timing issue that's "hidden" by the VB IDE. Test WebBrowser.Document.All("UserId") before setting the .Value property. It is probably not available (Nothing) at the time the non-IDE version of the code gets to that point.
"Object Variable or With Block Variable Not Set" is VB's way of telling you about a null reference, and in the line WebBrowser.Document.All("UserId") you have 3 separate objects that could be null.
A: You will need to add msgboxes showing the result of testing which variable are set to NOTHING or write to a text file and run the exe and see what is set to nothing.
It may be as simple as having a wait before the last line. A Wait subroutine looks like this.
Public Sub Wait(T As Double)
Dim StartTime As Double
StartTime = Timer
Do While Abs(Timer - StartTime) < T
Loop
End Sub
I would try a 1/10 of second and work your way up. i.e Wait .1 If have to wait a second or more then make sure you call DoEvents periodically to keep your application responsive.
The reason for this is that the IDE always uses PCODE so is a touch slower than a EXE complied to EXE. You may want to try compiling to PCODE as well to see if that makes a difference.
| |
doc_23536533
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *strrev(char *str)
{
if (!str || ! *str)
return str;
int i = strlen(str) - 1, j = 0;
char ch;
while (i > j)
{
ch = str[i];
str[i] = str[j];
str[j] = ch;
i--;
j++;
}
return str;
}
int main(){
long int a,b, ab, maxA, maxB, pal;
long int maxPal = 0;
char string[6];
char revString[6];
for(a=999; a>100; a--){
for(b=999; b>100; b--){
ab = a*b;
sprintf(string,"%ld",ab);
strcpy(revString, strrev(string));
strrev(string);
if((revString[0] != '0') && (strcmp(string, revString)== 0)){
printf("Palindrome %ld found!\n", ab);
pal = ab;
if(pal > maxPal){
maxPal = pal;
maxA = a;
maxB = b;
}
}
}
}
printf("Maximim palindrome is %ld from the product of a = %ld and b = %ld \n", maxPal, maxA, maxB);
return 1;
}
I am attempting this via a brute force method by going through all pairs of numbers from 100 to 999, converting the product to a string, and then seeing if the string is the same backwards. Doing this however I only find a 5 digit number as the largest palindrome instead of a 6 digit number. I think my logic seems pretty straightforward, but I am coming to the wrong conclusion. Instead of the right answer, I want to understand what is incorrect about my logic.
A: I have modified your code to count the number of palindroms found:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *strrev(char *str)
{
if (!str || ! *str)
return str;
int i = strlen(str) - 1, j = 0;
char ch;
while (i > j)
{
ch = str[i];
str[i] = str[j];
str[j] = ch;
i--;
j++;
}
return str;
}
int main(){
long int a,b, ab, maxA, maxB, pal;
long int maxPal = 0;
char string[6];
char revString[6];
int n6dp = 0;
int n5dp = 0;
for(a=999; a>100; a--){
for(b=999; b>100; b--){
ab = a*b;
sprintf(string,"%ld",ab);
strcpy(revString, strrev(string));
strrev(string);
if((revString[0] != '0') && (strcmp(string, revString)== 0)){
if (strlen(string) == 6)
{
n6dp++;
}
if (strlen(string) == 5)
{
n5dp++;
}
pal = ab;
if(pal > maxPal){
maxPal = pal;
maxA = a;
maxB = b;
}
}
}
}
printf("number of 5 digits palindroms found = %d\n", n5dp);
printf("number of 6 digits palindroms found = %d\n", n6dp);
printf("Max. palindrome is %ld from the product of a = %ld and b = %ld \n", maxPal, maxA, maxB);
return 0;
}
Here is what I get:
$ ./pal
number of 5 digits palindroms found = 1493
number of 6 digits palindroms found = 977
Max. palindrome is 906609 from the product of a = 993 and b = 913
Your code has found 6 digits palindroms.
| |
doc_23536534
|
An example JSON string I would want is:
[
{
"person": {
"name":"Jane Bloggs",
"previousSurnames": [
"Bloggy",
"Jones"
],
"Address":"I Live Here"
}
]
It is the "previousSurnames" I wish to retrieve as JSON but without any preceding labels... just a list of strings.
When I try the conventional way, it always puts the db field as the identifier (along with some extra curly braces which I also don't want!)...
[
{
"person": {
"name":"Jane Bloggs",
"previousSurnames": [
{"surname":"Bloggy"},
{"surname":"Jones"}
],
"Address":"I Live Here"
}
]
SQL Server must be able to do this as it recognises a simple string array as a correct JSON string e.g.
select isjson('["Bloggy","Jones"]')
returns 1 (Valid)
Help please...
A: I think what you're asking is that you want to retrieve the value of previousSurnames as a JSON String. If that is the case then one of these should work.
For a single-item array, such as in your example:
DECLARE @json NVARCHAR(MAX) = N'[
{
"person": {
"name":"Jane Bloggs",
"previousSurnames": ["Bloggy","Jones"],
"Address":"I Live Here"
}
}
]';
SELECT JSON_QUERY(@json, '$[0].person.previousSurnames')
Or, if your source JSON has multiple items in the array this should work:
DECLARE @json NVARCHAR(MAX) = N'[
{
"person": {
"name":"Jane Bloggs",
"previousSurnames": ["Bloggy","Jones"],
"Address":"I Live Here"
}
},
{
"person": {
"name":"Jane Bloggs 2",
"previousSurnames": ["Bloggy2","Jones2"],
"Address":"I Live Here"
}
}
]';
SELECT JSON_QUERY(value, '$.person.previousSurnames')
FROM OPENJSON(@json)
| |
doc_23536535
|
Error: listen EADDRINUSE: address already in use :::8081
at Server.setupListenHandle [as _listen2] (node:net:1372:16)
at listenInCluster (node:net:1420:12)
at Server.listen (node:net:1508:7)
at D:\RND\Mobile\node_modules\metro\src\index.js:164:16
at new Promise (<anonymous>)
at Object.exports.runServer (D:\RND\Mobile\node_modules\metro\src\index.js:163:10)
at async Object.runServer [as func] (D:\RND\Mobile\node_modules\@react-native-community\cli-plugin-metro\build\commands\start\runServer.js:121:26)
at async Command.handleAction (D:\RND\Mobile\node_modules\@react-native-community\cli\build\index.js:192:9)
info Run CLI with --verbose flag for more details.
A: You have an active process on that port
You should either change the port or find and kill the active process
netstat -aon | find "8081"
and when you find the PID of the process you can do
taskkill /F /PID <PID>
| |
doc_23536536
|
/***************************************************************************************/
#include <iostream>
#include <cstring>
#include <iomanip>
using namespace std;
//FUNCTION PROTOTYPES
int overlap(char *ptr1, char *ptr2);
int main()
{
//Declare and initialize objects
int count(0); // For DNA sequence
//DNA SEQUENCE
char DNA_sequence[] = "ATGCTAGTATTTGGATAGATAGATAGATAGATAGATAGATAAAAAAATTTTTTTT";
char thymine_group[] = "TT";
char *ptr1(DNA_sequence), *ptr2(thymine_group);
//Send QUOTE to function
count = overlap(ptr1, ptr2);
//Print number of occurences.
cout << "'TT' appears in DNA sequence " << count << " times" << endl;
return 0;
}
//FUNCTION 1 USING CHAR ARRAYS AND POINTERS
int overlap(char *ptr1, char *ptr2)
{
int count(0);
//Count number of occurences of strg2 in strg1.
//While function strstr does not return NULL
//increment count and move ptr1 to next section
//of strg1.
while ((ptr1=strstr(ptr1,ptr2)) != NULL)
{
count++;
ptr1++;
}
return count;
}
/**************************************************************************************************/
A: Just change ptr1++; in your loop to ptr1 += strlen(ptr2);
A: try
int overlap(char *ptr1, char *ptr2)
{
int count(0);
//Count number of occurences of strg2 in strg1.
//While function strstr does not return NULL
//increment count and move ptr1 to next section
//of strg1.
while ((ptr1=strstr(ptr1,ptr2)) != NULL)
{
count++;
ptr1 += strlen (ptr2);
}
return count;
}
A: int count(char *haystack, char* needle)
{ int c = 0;
for(;*haystack;haystack++){
if(strcmp(haystack, needle)==0){
c++;
haystack+=strlen(needle)-1;
}
}
return c;
}
| |
doc_23536537
|
First, what should I do to translate text to machine code.
For example:
text: 'If salary more than 5000 do op1'
should be translated to..
if salary > 5000:
op1
Is any way to do it? Maybe it other langs
A: what you are looking for is a compiler, Most popular compiler constructors are Yacc & Flex using BISON GNU.
Yacc:
Yacc wiki & BISON GNU Docs
But before going through that, you need to know about context free grammars.
Context Free Grammar
you can parse a language only if it is deterministic as in there is a single rule to parse that sentence
| |
doc_23536538
|
The question is - can you set the EJB container to let the concurrent access to the SFSB?
I know that I have a @AccessTimeout which allows me to configure that the SFSB may be accessed at the same time more than once by the particular client. However, it allows me to specify that the concurrent access is not allowed at all or let the container serialize the requests.
Does the EJB specification forbids such thing? I know I can achieve concurrent access with the Singleton EJB using @ConcurrencyManagement, but I'm just curious if it's possible to set some vendor-specific configuration property to allow such behavior for SFSBs.
Thanks in advance!
A: Just last month a JIRA issues was filed that proposes exactly this: http://java.net/jira/browse/EJB_SPEC-24
A: The EJB specification does not forbid vendor extensions, so in theory, a vendor could implement an extension to allow stateful session beans to be accessed concurrently. In practice, I'm not aware of any that allow that.
| |
doc_23536539
|
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
</script>
<?php
session_start();
if(isset($_SESSION['username1']))
{
include("../config/database.php");
if(isset($_GET["page"]))
{
$page = $_GET["page"];
$rows_per_page = 10;
}
else
{
$page=1;
}
$start_from = ($page * 10) -10;
$limit = ($page * 10);
$query=$conn->prepare("SELECT makeid,name,status,creation_date_and_time,created_by FROM carmake ORDER BY makeid desc LIMIT $start_from,10");
$query->execute();
$query->bind_result($makeid,$name,$status,$creation_date_and_time,$created_by);
//$result=$query->get_result();
?>
<?php
?>
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="table">
<tr>
<th width="6%" align="center" class="tbl_back"> Id</th>
<th width="12%" align="center" class="tbl_back">Name</th>
<th width="12%" align="center" class="tbl_back">Created by</th>
<th width="12%" align="center" class="tbl_back">Status</th>
<th width="12%" align="center" class="tbl_back">Edit</th>
<th width="12%" align="center" class="tbl_back">Delete</th>
</tr>
<?php
//$i = 0;
while($query->fetch())
{
/* Construct Data */
?>
<?php
/*$serviceid=$data['servicetype'];
$query2="select * FROM tblservicemaster where serviceid='$serviceid'";
$result2 = mysql_query($query2,$conn) or die(mysql_error());
$leadservice=mysql_fetch_array($result2);*/
?>
<tr>
<td class="tbl_back1"><?php echo $makeid ?></td>
<td class="tbl_back1"><?php echo $name ?></td>
<td class="tbl_back1"> <?php
$idd=$created_by;
$query1=$conn->prepare("select name,adminid from admintable where adminid=?");
$query1->bind_param("i",$idd);
$query1->execute();
$query1->bind_result($name,$adminid);
//$query1->store_result();
$query1->fetch();
/* $query1="select name from admintable where id=".$data[4];
$result1=mysql_query($query1) or die(mysql_error());
$data1=mysql_fetch_array($result1);*/
echo $name;
?> </td>
<td class="tbl_back1"><?php if($status==1){echo "Enabled";}if($status==0){echo "Disabled";} ?></td>
<td class="celledit"><a href="edit_carmakepages.php?id=<?php echo $makeid; ?>"><center><img src="images/editsign.jpg"/></center> </a></td>
<td class="celldelete"><a href="javascript:del_topic(<?php echo makeid; ?>)"><center><img src="images/deletesign.jpg"/></center> </a></td>
<?php
//$i++;
?>
</tr>
</tr>
<?php
} // end while
/*else
{
?>
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="table">
<tr>
<th width="6%" align="center" class="tbl_back"> Id</th>
<th width="12%" align="center" class="tbl_back">Name</th>
<th width="12%" align="center" class="tbl_back">Created by</th>
<th width="12%" align="center" class="tbl_back">Status</th>
<th width="12%" align="center" class="tbl_back">Edit</th>
<th width="12%" align="center" class="tbl_back">Delete</th>
</tr>
<tr>
<td colspan="15" align="center" style=" color:red" class="tbl_back12">
No Record Found
<!--<h4 class="aligncenter">No Record Found</h4>-->
</td>
</tr>
<?php
}*/
?>
</tbody>
</table>
<?php } ?>
</html>
A: Add th line $query->bind_param('i',$id); If your id is makeid then you use $makeid in place of $id.
$query=$conn->prepare("SELECT makeid,name,status,creation_date_and_time,created_by FROM carmake ORDER BY makeid desc LIMIT $start_from,10");
//Bind the variable to prepared statement
$query->bind_param('i',$id); // i corresponds to integer type variable
$query->execute();
$query->bind_result($makeid,$name,$status,$creation_date_and_time,$created_by);
Use it if you are having an id column
A: Try completely changing the while loop
while($query->fetch()){
$row[] = array('makeid' => $makeid, 'status' => $status, 'creation_date_and_time' => $creation_date_and_time, 'created_by' => $created_by);
} //end while
then change the while loop in its current form to a foreach and assign $iss the value of the current iteration of the arrays 'created_by' value like this:
foreach($row as $resultsFromArray){
/* Construct Data */
?>
<?php
/*$serviceid=$data['servicetype'];
$query2="select * FROM tblservicemaster where serviceid='$serviceid'";
$result2 = mysql_query($query2,$conn) or die(mysql_error());
$leadservice=mysql_fetch_array($result2);*/
?>
<tr>
<td class="tbl_back1"><?php echo $makeid ?></td>
<td class="tbl_back1"><?php echo $name ?></td>
<td class="tbl_back1"> <?php
$idd=$resultsFromArray['created_by']; //<--- Notice the change here
$query1=$conn->prepare("select name,adminid from admintable where adminid=?");
$query1->bind_param("i",$idd);
$query1->execute();
$query1->bind_result($name,$adminid);
//$query1->store_result();
$query1->fetch();
/* $query1="select name from admintable where id=".$data[4];
$result1=mysql_query($query1) or die(mysql_error());
$data1=mysql_fetch_array($result1);*/
echo $name;
?> </td>
<td class="tbl_back1"><?php if($status==1){echo "Enabled";}if($status==0){echo "Disabled";} ?></td>
<td class="celledit"><a href="edit_carmakepages.php?id=<?php echo $makeid; ?>"><center><img src="images/editsign.jpg"/></center> </a></td>
<td class="celldelete"><a href="javascript:del_topic(<?php echo makeid; ?>)"><center><img src="images/deletesign.jpg"/></center> </a></td>
<?php
//$i++;
?>
</tr>
</tr>
<?php
}// end foreach
| |
doc_23536540
|
poltergeist (1.17.0)
I have a feature test running with js: true
it fails with
Failure/Error:
within(page.find('#by_category')) do
select(category_2.name, from: 'q_category_id_eq')
end
Capybara::ElementNotFound:
Unable to find visible css "#by_category"
rails_heper.rb my set up is like this
Capybara.default_driver = :rack_test
require 'capybara/poltergeist'
options = { js_errors: true }
Capybara.register_driver :poltergeist do |app|
Capybara::Poltergeist::Driver.new(app, options)
end
Capybara.javascript_driver = :poltergeist
my test
scenario 'they can seach books by category', js: true do
visit root_url
puts page.body
within(page.find('#by_category')) do
select(category_2.name, from: 'q_category_id_eq')
end
within(page.find('.category')) do
expect(page).to have_content("#{category_2.name}")
end
end
the page body results an empty page and I don't see a any javascript errors either. Category selection is done via on change AJAX call.
root to: 'books#index'
| |
doc_23536541
|
W/libOpenSLES(10708): Leaving Object::GetInterface (SL_RESULT_FEATURE_UNSUPPORTED)
This happens on the line:
res = (*recorderObj)->GetInterface(recorderObj, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &recorderBufferQueueItf);
Does this mean that recording using OpenSL ES on a Galaxy Nexus device isn't supported, or did I merely make a mistake? Below is the relevant code:
static SLObjectItf recorderObj;
static SLEngineItf EngineItf;
static SLRecordItf recordItf;
static SLAndroidSimpleBufferQueueItf recorderBufferQueueItf;
static SLDataSink recDest;
static SLDataLocator_AndroidSimpleBufferQueue recBuffQueue;
static SLDataFormat_PCM pcm;
/* Setup the data source structure */
locator_mic.locatorType = SL_DATALOCATOR_IODEVICE;
locator_mic.deviceType = SL_IODEVICE_AUDIOINPUT;
locator_mic.deviceID = SL_DEFAULTDEVICEID_AUDIOINPUT;
locator_mic.device = NULL;
audioSource.pLocator = (void *) &locator_mic;
audioSource.pFormat = NULL;
/* Setup the data sink structure */
recBuffQueue.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE;
recBuffQueue.numBuffers = NB_BUFFERS_IN_QUEUE;
/* set up the format of the data in the buffer queue */
pcm.formatType = SL_DATAFORMAT_PCM;
pcm.numChannels = 1;
pcm.samplesPerSec = SL_SAMPLINGRATE_44_1;
pcm.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16;
pcm.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16;
pcm.channelMask = SL_SPEAKER_FRONT_CENTER;
pcm.endianness = SL_BYTEORDER_LITTLEENDIAN;
recDest.pLocator = (void *) &recBuffQueue;
recDest.pFormat = (void * ) &pcm;
/* Create audio recorder */
res = (*EngineItf)->CreateAudioRecorder(EngineItf, &recorderObj, &audioSource, &recDest, 0, iidArray, required);
CheckErr(res);
/* Realizing the recorder in synchronous mode. */
res = (*recorderObj)->Realize(recorderObj, SL_BOOLEAN_FALSE);
CheckErr(res);
/* Get the RECORD interface - it is an implicit interface */
LOGI("GetInterface: Recorder");
res = (*recorderObj)->GetInterface(recorderObj, SL_IID_RECORD, &recordItf);
CheckErr(res);
/* Get the buffer queue interface which was explicitly requested */
LOGI("GetInterface: Buffer Queue");
res = (*recorderObj)->GetInterface(recorderObj, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &recorderBufferQueueItf);
CheckErr(res);
Any help with this issue would be most welcome :)
A: When you create the Audio Recorder, you specify "0" as the third-to-last argument, which is the number of non-implicit interfaces to be supported. The buffer queue is not an implicit interface for a recorder.
Try changing
res = (*EngineItf)->CreateAudioRecorder(EngineItf, &recorderObj, &audioSource, &recDest, 0, iidArray, required);
to
res = (*EngineItf)->CreateAudioRecorder(EngineItf, &recorderObj, &audioSource, &recDest, 1, iidArray, required);
| |
doc_23536542
|
{
"meta": null,
"data": {
"type": "spaces_schema"
"attributes": {
"spaces": ["space1", "space2"]
}
}
}
I am transposing the call into PowerShell, and creating the body using a nested hash table. The call returns an error regarding the body when done in PowerShell:
$Body = @{
"meta" = "null"
"data" = @{
"type" = "spaces_schema"
"attributes" = @{
"spaces" = ["space1", "space2"]
}
}
}
The problem I am running into is the "spaces" attribute. I am not sure how to pass the brackets as literal characters in the hash table without wrapping them in quotes, since doing so puts out an error as well and interferes with the quotes used inside of the brackets.
Here is the error:
Invoke-WebRequest : {"errors":[{"additional_data":null,"detail":"Unhandled exception from route request: Expecting value: line 1 column 1 (char 0)"}]}
At C:\Users\{user}\Desktop\{Folder}\{Scriptname}.ps1:26 char:1
+ Invoke-WebRequest -URI 'https://{URL} ...
A: You are trying too hard to make the object look like JSON syntax.
As said, to define an element's value as array, you need to enclose it in @(). In Json syntax that would display inside square brackets.
Writing "meta" = "null" is wrong too, because you then define it as string with a literal value of "null".
What you should do in the object is meta = $null which wil translate to JSON as "meta": null
In your case, the default -Depth setting of the ConvertTo-Json cmdlet is not deep enough, so you need to set that to a value of at least 3 (in the example you gave).
Try
$Body = @{
meta = $null
data = @{
type = "spaces_schema"
attributes = @{
spaces = @("space1", "space2")
}
}
}
$Body | ConvertTo-Json -Depth 3
Since you will be uploading this data using Invoke-WebRequest or Invoke-RestMethod, I would advice to add switch -Compress to the ConvertTo-Json cmdlet as well. This will return a less human readable json, but the payload will be smaller because all extra whitespace will be removed:
{"meta":null,"data":{"type":"spaces_schema","attributes":{"spaces":["space1","space2"]}}}
| |
doc_23536543
|
But I was looking for an example where change in either of one affects other. This would help me increase my understanding over MVC.
Thanks in advance....
A: When we think of business logic in mvc, we are looking at the model part of mvc - which is based on the business domain objects. Therefore, if there is a change to the business domain - e.g. If we have an "asset" domain and add an asset number to the asset domain object and start recording details based on this, we would update our model with a new asset number property containing various attributes. Then our view would display the asset number based on those attributes e.g visible to asset administrators only - done by decorating the model attributes. In this way, changes in the business domain objects get reflected in the model part of mvc.
A: An example would be most Excel applications
For example some key piece of data is saved to cell C1
A macro is hard coded to pick up the data in cell C1 and perform operations on it
Then someone thinks it would look better if the sheet had a title so that information is moved to C3 fit the title in and all of the excel code stops working.
The logic in the code is tightly bound to the user interface and a change in the user interface requires a change to the business logic (the code or calculation).
| |
doc_23536544
|
It's a wordpress child theme and inside of the theme's "Options" settings.
Using this script
UPDATE wp_e4e5_options
SET option_value = REPLACE(option_value, 'Copyright | by <a href="https://company.com"', ' ')
a:1:{s:3:"copyright";s:17:"Copyright | by <a href="https://company.com"";}
I was certain, it would just find that part of the serialized data and replace. But it doesn't.
It reset the setting to the theme's standard setting. Even when I edit it manually by using Adminer.php in the table, it resets.
I'm aware, that this might be in the wrong forum, since it's Wordpress related, but I believe it's SQL that's the issue here.
So my question is:
*
*If i edit it manually using Adminer.php (simple version of
phpMyAdmin), it resets all the settings back to standard. How can I
edit only part of the serialized data and only the part shown above?
*What makes it "reset" to standard settings?
UPDATE:
Thanks to @Kaperto I got this working code now, which gave me a new issue.
UPDATE wp_e4e51a4870_options
SET option_value = REPLACE(option_value, 's:173:"© Copyright - Company name [nolink] | by <a href="https://company-name.com" target="_blank" rel="nofollow">Company Name</a>";', 's:40:"© Copyright - Company name [nolink]";')
The problem is, it's gonna be used as a code snippet with ManageWP looping through several hundreds of websites which all have different company names. So the first part of the string is unique but the rest is the same on all sites, after the pipe |.
So I somehow need to do this:
*
*Find whole series where this string is included | by <a href="https://company-name.com" target="_blank" rel="nofollow">Company Name</a>"
*Get the whole series s:173:"© Copyright -
Company name [nolink] | by <a href="https://company-
name.com" target="_blank"
rel="nofollow">Company Name</a>
*Replace with new series with updated character count, since company name is different
Is this even achievable with pure SQL commands?
| |
doc_23536545
|
public class Settings {
public string Foo { get; set; }
public int Bar { get; set; }
}
I might have the following instance:
new Settings {
Foo = "xxx",
Bar = 20
}
and I'd like to show that class in a DataGrid like this:
--------------------
| Settings | Value |
--------------------
| Foo | xxx |
| Bar | 20 |
What would be a proper way of doing it? I know I could create some temporarily class (with two properties), and using reflection create as many instances of that class as properties in Settings, but I perhaps there is a cleaner way of doing it, taking advantages of bindings (two way), etc.
I'm using WPF + MVVM.
A: If you're just showing a single class instance like this, it would be better to not use a DataGrid. Just build a custom DataTemplate for your class to display it how you choose based on a 2x3 grid.
A: You can bind the class into the DataGrid.
First you have to Bind the property to a column in the DataGrid.
<DataGrid Name="dtgSettings" Height="200">
<DataGrid.Columns>
<DataGridTextColumn Header="Foo" Width="150" Binding="{Binding Foo}" />
<DataGridTextColumn Header="Bar" Width="150" Binding="{Binding Bar}" />
</DataGrid.Columns>
</DataGrid>
After that its just add the new Settings dinamically.
dtgSettings.Items.Add( new Settings
{
Foo = "Foo",
Bar = 0,
};
| |
doc_23536546
|
in C# in Depth, Second Edition several times.
page 77,
When a type parameter is unconstrained (no constraints are applied to it), you can use == and != operators, but only to compare a value of that type with null. You can’t compare two values of type T with each other.
...
When a type parameter is constrained to be a value type, == and != can’t be used with it at all.
If I understand (I don't think so) it correctly, it basically tells me that you cannot
use == or != to compare two value types. Why why why?
It will be better if a simple example can be given for this case. Can someone give me
a little idea what the above paragraph tries to convey?
A: It simply means this when constraining to a value type (second paragraph)
static bool TryToCompare<T>(T first, T second) where T : struct
{
return first == second; // not legal
return first.Equals(second); // legal
}
Without the value-type constraint on the generic, it also says this (first paragraph)
static bool TryToCompare<T>(T first, T second)
{
return first == second; // not legal
return first == null; // legal
return first.Equals(second); // legal
}
If you constrain T to a reference type, you can get away with using ==
static bool TryToCompare<T>(T first, T second) where T : class
{
return first == second; // legal
return first == null; // legal
return first.Equals(second); // legal
}
A: Objects aren't comparable because a comparison using == is testing whether the reference is the same (the memory address). You would normally use if (string1.Equals(string2)).
Something I don't understand is that I have seen circumstances where == works with strings, and circumstances where it doesn't.
| |
doc_23536547
|
<<>[some text][newline][some text]<>>
here the catch is that newlines can be many before we find end tag <>>
I tried following regular expression
<(.*?\n.*?)>
it works perfectly to find expression divided by single line, but i need to also find expressions divided by various lines.
I tried following expression also:
<(.*?\n.*?)*>
but searching it is leading to timeout,
Please help?
Sample Text for searching:
<p class=3DMsoNormal style=3D'margin-top:12.0pt;margin-right:0cm;margin-bot=
tom:
0cm;margin-left:148.85pt;margin-bottom:.0001pt;text-indent:-148.85pt;
tab-stops:148.85pt right 16.0cm'><b style=3D'mso-bidi-font-weight:normal'><=
span
style=3D'font-family:"Calibri","sans-serif"'>RISK DETAILS<span style=3D'mso=
-tab-count:
1'> =
&nb=
sp; =
</span></span></b><span
style=3D'font-family:"Calibri","sans-serif"'>Your home is described as
<q_1><o:p></o:p></span></p>
<p class=3DMsoNormal style=3D'margin-top:0cm;margin-right:0cm;margin-bottom=
:0cm;
margin-left:148.85pt;margin-bottom:.0001pt'><span style=3D'font-family:"Cal=
ibri","sans-serif"'>The
construction of your home is <q_2><o:p></o:p></span></p>
<p class=3DMsoNormal style=3D'margin-top:0cm;margin-right:0cm;margin-bottom=
:0cm;
margin-left:148.85pt;margin-bottom:.0001pt'><span style=3D'font-family:"Cal=
ibri","sans-serif"'>The
main roof material is <q_3><o:p></o:p></span></p>
<p class=3DMsoNormal style=3D'margin-top:0cm;margin-right:0cm;margin-bottom=
:0cm;
margin-left:148.85pt;margin-bottom:.0001pt'><span style=3D'font-family:"Cal=
ibri","sans-serif"'>Your
home was built in <q_4><o:p></o:p></span></p>
<p class=3DMsoNormal style=3D'margin-top:0cm;margin-right:0cm;margin-bottom=
:0cm;
margin-left:148.85pt;margin-bottom:.0001pt'><span style=3D'font-family:"Cal=
ibri","sans-serif"'>Your
<span class=3DGramE>home <q_5> double</span> keyed deadlocks to all
external doors<o:p></o:p></span></p>
<p class=3DMsoNormal style=3D'margin-top:0cm;margin-right:0cm;margin-bottom=
:0cm;
margin-left:148.85pt;margin-bottom:.0001pt'><span style=3D'font-family:"Cal=
ibri","sans-serif"'>Your
home <q_6> keyed locks or grilles on all windows<o:p></o:p></span></p>
<p class=3DMsoNormal style=3D'margin-top:0cm;margin-right:0cm;margin-bottom=
:0cm;
margin-left:148.85pt;margin-bottom:.0001pt'><span style=3D'font-family:"Cal=
ibri","sans-serif"'>Your
home has <q_7> alarm installed<o:p></o:p></span></p>
<p class=3DMsoNormal style=3D'margin-top:0cm;margin-right:0cm;margin-bottom=
:0cm;
margin-left:148.85pt;margin-bottom:.0001pt'><span style=3D'font-family:"Cal=
ibri","sans-serif"'>Your
home <q_8> connected to mains water supply<o:p></o:p></span></p>
some examples:
Example 1:
Text to be searched:
<span
style=3D'color:blue'><o:p></o:p></span></span></p>
</td>
<td width=3D103 valign=3Dtop style=3D'width:77.5pt;padding:0cm 5.4pt 0cm =
0cm'>
<p class=3DMsoNormal align=3Dright style=3D'margin-top:3.0pt;margin-right=
:0cm;
margin-bottom:0cm;margin-left:0cm;margin-bottom:.0001pt;text-align:right;
tab-stops:155.95pt'><span style=3D'font-family:"Calibri","sans-serif"'><=
<span
class=3DSpellE>spec_contents_value</span>><span style=3D'color:blue'><=
o:p></o:p></span></span></p>
</td>
</tr>
</table>
<p class=3DMsoNormal style=3D'margin-top:0cm;margin-right:0cm;margin-bottom=
:0cm;
margin-left:148.85pt;margin-bottom:.0001pt;text-indent:-148.85pt;tab-stops:
148.85pt right 453.55pt'><span style=3D'font-family:"Calibri","sans-serif"'=
><o:p> </o:p></span></p>
<p class=3DMsoNormal style=3D'margin-top:0cm;margin-right:0cm;margin-bottom=
:0cm;
margin-left:148.85pt;margin-bottom:.0001pt;text-indent:-148.85pt;tab-stops:
148.85pt right 453.55pt'><span style=3D'font-family:"Calibri","sans-serif"'=
>Unspecified
Valuables<b style=3D'mso-bidi-font-weight:normal'><span style=3D'mso-tab-co=
unt:
1'> =
</=
span></b><valuables><o:p></o:p></span></p>
<p class=3DMsoNormal style=3D'margin-top:0cm;margin-right:0cm;margin-bottom=
:0cm;
margin-left:148.85pt;margin-bottom:.0001pt;text-indent:-148.85pt;tab-stops:
148.85pt right 453.55pt'><span style=3D'font-family:"Calibri","sans-serif"'=
>Specified
Valuables<b style=3D'mso-bidi-font-weight:normal'><span style=3D'mso-tab-co=
unt:
1'> =
&nb=
sp; </span></b><<spanclass=3DSpellE>spec_valuables_ni</span>>=
<o:p></o:p></span></p>
I want my Regex.Match pattern to be able to search:
<=
<span
class=3DSpellE>spec_contents_value</span>>
Or any of < ... > pattern spanning over more than one line. but not those present on same line.
A: Use DOTALL modifier to make dot to match even line breaks (\n, \r).
(?s)<(?:(?!&[gl]t;).)*?\n(?:(?!&[gl]t;).)*?>
DEMO
A: How about the regex
<[^&]*>
for example http://regex101.com/r/iV9lS4/3
*
*< matches <
*[^&]* matches anything other than & including newline
*> matches >
You can also use . to match anything by providing the DOTALL (?s) operator.
For the input
<=
<span
class=3DSpellE>spec_contents_value</span>>
It would match as http://regex101.com/r/iV9lS4/4
| |
doc_23536548
|
Now I want to count rows where ship_date is past date. And I am trying as follows:
$today = date('yy-m-d');
$sql = "SELECT count(*) as total FROM spot_shipment_order where date('ship_date') < '$today'";
Today's date is: 2020-04-27 and final SQL is:
SELECT count(*) as total FROM spot_shipment_order where date('ship_date') < '2020-04-27'. As 2020-04-29 is not past date with respect to today's date, hence the above SQL should count 0. it returns 1. Strange!. this problem make me cry. I think I am doing some mistakes and can't explore that mistake. Any help is appreciated. Thanks in advance.
| |
doc_23536549
|
I used tried a lot of codes but no one worked!
A: If it must be a file, integrate some file picker library in your app.
Android's built-in options, such as ACTION_GET_CONTENT and ACTION_OPEN_DOCUMENT, are for content, not files. Through those, the user may choose lots of things that are not files that your app can access.
In terms of displaying it, use an image-loading library such as Picasso to apply the image to an ImageView.
| |
doc_23536550
|
*
*Customer
*Product
*Product Price
*Payment Method
*Subscription
In payment method i provide following details:
async function createPaymentMethod(data) {
let body = {
type: 'card',
card: {
number: data.card?.number,
exp_month: data.card?.exp_month,
exp_year: data.card?.exp_year,
cvc: data.card?.cvc
}
};
return await stripe.paymentMethods.create(body);
}
Now i want to create payment method but want to use customer's bank account number but i am unable to find a way to do it. I want to add "type: bank_account"
Note: I am using Strip JS and Node JS. All of this I want to do on server side i.e node js
A: Collecting Credit Card server-side is a bad idea, since you will expose yourself to the burden on PCI-Compliance. You would want to review Stripe's Integration Security Guide. Generally you would want to use client-side SDK to collect credit card information instead.
To the question of a bank account, it depends on which specific PaymentMethod you're gonna use (which country's bank transfer?) Ie. If you are talking about ACH in the US, you should follow the ACH Guide. Similarly it will collect bank account information client-side in exchange of a token, then passing it up to your back end.
| |
doc_23536551
|
For logging purposes I check the scopes carefully at Complete() and Dispose() and record information whenever a TransactionScope has been Aborted. (Disposed without being Completed)
But I've found that my logging doesn't catch the case where a TransactionScope times out.
This isn't a SQLTimeout - individual SQL commands are all running fine. This is when I've got a collection of C# processing and SQL commands that I want to be bound together, and am using TransactionScope to manage that.
The symptom I end up with is that the next transaction scope tries to use a Transaction that has Aborted ... but by that time it's too late to log information.
How can I determine whether this scope that I'm looking at right now (which I'm about to Complete and then Dispose) has timed out?
| |
doc_23536552
|
When encoding the value '1455344' (as string not as integer) I get 'MTQ1NTM0NA=='.
When using the converter from this page: https://base64.guru/standards/base64url/encode
I get a slight different result 'MTQ1NTM0NA'.
What is wrong and what is correct? and what do I need to do to get the second results?
When encoding '799468', in both cases the result is 'Nzk5NDY4'
Any clarification would be very appreciated. Thanks Andreas
By mistake i had posted my question as answer instead of an additional question in the following topic:
Base64 encoding in SQL Server 2005 T-SQL
| |
doc_23536553
|
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$writer->save('storage/SomeExcelFile.xlsx');
Then I can download the file with..
return Storage::disk('public')->download('SomeExcelFile.xlsx');
But without being able to saves files locally on the production version of the application, how will I store my file?
I have my application connected to a storage bucket where I can upload files. But I need the file path to do this, and since this file was created scriptually in the application and was never stored prior to deployment, I can't find a way to store it.
As far as I found you can't write the xlsx file directly to a disk. For example I can write a text file with the text sample data to my google cloud storage bucket..
Storage::disk('gcs')->put('String.txt', 'sample data');
But can't find a way to do it with my excel file. Also the application is deployed in the Flex environment so I can't use the file url structure gs://
A: Found a work around streaming the file with Symfony
$response = new StreamedResponse(
function () use ($writer) {
$writer->save('php://output');
}
);
$response->headers->set('Content-Type', 'application/vnd.ms-excel');
$response->headers->set('Content-Disposition', 'attachment;filename="Services Reformatted.xlsx"');
$response->headers->set('Cache-Control', 'max-age=0');
return $response;
A: Try this way :
file_put_contents(public_path('filename.xlsx'), $writer);
| |
doc_23536554
|
This chart is a dinamic chart. I take the data of a database and I refresh the chart every 5 minut.
I have this problem: There are so many data in the X-axis and i can't watch nothing in the x-axis. This is a picture of my chart:
I need to reorganize the data of X-axis. I only have to put a tick every 4 hour. The x-axis have to be like this:
So, I have to change the format of the X-axis and only put a tick every 4 hours of the last 24 hours. Moreover, I have to put the day below.
Do you have any idea of How could I do this?
This is the code of my chart:
var svg = dimple.newSvg("#container", 500, 500);
var myChart = new dimple.chart(svg, data2);
var x = myChart.addCategoryAxis("x", "time");
x.addOrderRule(Date);
var y1 = myChart.addMeasureAxis("y", "Piranometro");
var piranometro = myChart.addSeries("Piranom.", dimple.plot.line,[x,y1]);
myChart.draw();
Thanks in advance
A: Try using
myChart.addTimeAxis()
instead of
myChart.addCategoryAxis()
Here is an advanced time axis example (both x and y are time axis):
Advanced Time Axis Sample
Documentation on addTimeAxis():
Dimple addTimeAxis() function
Related question:
Dimple Time Format Juggling
For displaying days below the hour axis, you can utilize second time axis.
Hope all this will help you find solution that fits your need.
| |
doc_23536555
|
This is my JSON response.
A: If the "0" key is a constant, you can map it to a valid property name using CodingKeys, like so:
struct Response: Codable {
let success: Bool
let data: DataClass
let error, message: String
}
struct ZeroKeyType: Codable {
// properties go here
}
struct DataClass: Codable {
let the0: ZeroKeyType
let searchField: [String]
enum CodingKeys: String, CodingKey {
case the0 = "0"
case searchField
}
}
| |
doc_23536556
|
Suppose you had the following pyspark DataFrame:
data= [('foo',), ('123',), (None,), ('bar',)]
df = sqlCtx.createDataFrame(data, ["col"])
df.show()
#+----+
#| col|
#+----+
#| foo|
#| 123|
#|null|
#| bar|
#+----+
The next two code blocks should do the same thing- that is, return the uppercase of the column if it is not null. However, the second method (using a udf) produces an error.
Method 1: Using pyspark.sql.functions.upper()
import pyspark.sql.functions as f
df.withColumn(
'upper',
f.when(
f.isnull(f.col('col')),
f.col('col')
).otherwise(f.upper(f.col('col')))
).show()
#+----+-----+
#| col|upper|
#+----+-----+
#| foo| FOO|
#| 123| 123|
#|null| null|
#| bar| BAR|
#+----+-----+
Method 2: Using str.upper() inside of a udf
df.withColumn(
'upper',
f.when(
f.isnull(f.col('col')),
f.col('col')
).otherwise(f.udf(lambda x: x.upper(), StringType())(f.col('col')))
).show()
This gives me AttributeError: 'NoneType' object has no attribute 'upper'. Why is the f.isnull() check in the call to when seemingly being ignored?
I know that I can change my udf to f.udf(lambda x: x.upper() if x else x, StringType()) to avoid this error, but I'd like to understand why it's happening.
Full Traceback:
Py4JJavaErrorTraceback (most recent call last)
<ipython-input-38-cbf0ffe73538> in <module>()
4 f.isnull(f.col('col')),
5 f.col('col')
----> 6 ).otherwise(f.udf(lambda x: x.upper(), StringType())(f.col('col')))
7 ).show()
/opt/SPARK2/lib/spark2/python/pyspark/sql/dataframe.py in show(self, n, truncate)
316 """
317 if isinstance(truncate, bool) and truncate:
--> 318 print(self._jdf.showString(n, 20))
319 else:
320 print(self._jdf.showString(n, int(truncate)))
/opt/SPARK2/lib/spark2/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py in __call__(self, *args)
1131 answer = self.gateway_client.send_command(command)
1132 return_value = get_return_value(
-> 1133 answer, self.gateway_client, self.target_id, self.name)
1134
1135 for temp_arg in temp_args:
/opt/SPARK2/lib/spark2/python/pyspark/sql/utils.py in deco(*a, **kw)
61 def deco(*a, **kw):
62 try:
---> 63 return f(*a, **kw)
64 except py4j.protocol.Py4JJavaError as e:
65 s = e.java_exception.toString()
/opt/SPARK2/lib/spark2/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
317 raise Py4JJavaError(
318 "An error occurred while calling {0}{1}{2}.\n".
--> 319 format(target_id, ".", name), value)
320 else:
321 raise Py4JError(
Py4JJavaError: An error occurred while calling o642.showString.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 51 in stage 77.0 failed 4 times, most recent failure: Lost task 51.3 in stage 77.0 (TID 5101, someserver.prod.somecompany.net, executor 99): org.apache.spark.api.python.PythonException: Traceback (most recent call last):
File "/opt/SPARK2/lib/spark2/python/lib/pyspark.zip/pyspark/worker.py", line 174, in main
process()
File "/opt/SPARK2/lib/spark2/python/lib/pyspark.zip/pyspark/worker.py", line 169, in process
serializer.dump_stream(func(split_index, iterator), outfile)
File "/opt/SPARK2/lib/spark2/python/lib/pyspark.zip/pyspark/worker.py", line 106, in <lambda>
func = lambda _, it: map(mapper, it)
File "/opt/SPARK2/lib/spark2/python/lib/pyspark.zip/pyspark/worker.py", line 92, in <lambda>
mapper = lambda a: udf(*a)
File "/opt/SPARK2/lib/spark2/python/lib/pyspark.zip/pyspark/worker.py", line 70, in <lambda>
return lambda *a: f(*a)
File "<ipython-input-38-cbf0ffe73538>", line 6, in <lambda>
AttributeError: 'NoneType' object has no attribute 'upper'
A: You have to remember that Spark SQL (unlike RDD) is not what-you-see-is-what-you-get. Optimizer / planner is free to schedule operations in the arbitrary order or even repeat stages multiple times.
Python udfs are not applied on a Row basis, but using batch mode. when is not so much ignored, but not used to optimize execution plan:
== Physical Plan ==
*Project [col#0, CASE WHEN isnull(col#0) THEN col#0 ELSE pythonUDF0#21 END AS upper#17]
+- BatchEvalPython [<lambda>(col#0)], [col#0, pythonUDF0#21]
+- Scan ExistingRDD[col#0]
Therefore function used with udf has to be robust to None inputs, for example:
df.withColumn(
'upper',
f.udf(
lambda x: x.upper() if x is not None else None,
StringType()
)(f.col('col'))
).show()
| |
doc_23536557
|
Inside my module project (AModul project):
[Export]
[Module(ModuleName = "AModule")]
public class AModule : IModule
{
ModuleSettingsModel ModuleSettings { get ; set; }
public AModule()
{
// throw new NotImplementedException();
}
public AModule(IUnityContainer container)
{
// Some codes ....
}
~AModule()
{
// some codes
}
public void Initialize()
{
var regionManager = _container.Resolve<IRegionManager>();
regionManager.RegisterViewWithRegion("WorkspaceRegion", typeof(ModuleAView));
ModuleSettings = DataFileManager.LoadModuleData();
}
It works well and i can use my settings inside AModule
Inside Main WPF Project:
But i need access this settings (ModuleSettings property) in my Main WPF project too. For example i need access to ModuleA»ModuleSettings in my Bootstrapper class of my WPF application. I need do some workd base on each module settings in my main project...
My question is what solutions are there to do? Should i register any type? Where? How?
Note1: ModuleSettings* is inherited from IModuleSettings and IModuleSettings is inside Infrastructure project.
Note2: I load my modules dynamically into prism (my main WPf project has not any reference to AModule);
A: You should put the ModuleSettings into a class library project that is referenced by the various modules/projects. You could use the singleton pattern to only load and maintain one instance of the settings.
A: After read GlenThomas answer & @BenediktSchroeder's first comment in question and reading some additional references like this & this, i could found & implement a good way for my question:
I solved it by adding a new custom Prism Service
*
*Create an Interface for our service class (eq. ISettingManager) in Infrastructure Project. Modules and Main App need reference to Infrastructure Project
*Create an Class for our service (eq. SettingManager)
*Define one property in ISettingManager to keep ModuleSetting like:
Dictionary<string,ModuleSettingsModel> ModuleSettingsPairs{get;set;}
*Add some methods in ISettingManager to Get, Add and Remove setting to/from the ModuleSettingsPairs dictionary.
*Register the new service type in ConfigureContainer inside the bootstraper as Singlton like:
RegisterTypeIfMissing(typeof(IAddonSettingsManager), typeof(AddonSettingsManager), true);
*Obtain reference to the IAddonSettingsManager service instance in the module project or main app project, it can do by one of following ways:
*
*Declaratively obtain references to services using constructor injection
*Programmatically obtain references to services (by use the Resolve method of the Unity container)
*Finally, play with custom Get, Add and Remove methods of our service instance (SettingManager)
| |
doc_23536558
|
function haveFilesBeenWrittenToBucket(bucketName, callback) {
s3.listObjects({ Bucket: bucketName }, function(err, data) {
const items = data.Contents;
callback(items);
});
}
and the readFile function:
OSClient.prototype.readFile = function(params, callback) {
haveFilesBeenWrittenToBucket(params.Bucket, items => {
console.log("Number of items " + items.length);
if (items.length > 0) {
const rl = readline.createInterface({
input: s3.getObject(params).createReadStream()
});
const myArray = [];
rl.on("line", function (line) {
const lineArray = line.split(",");
for (const value of lineArray) {
if (isNaN(value)) {
// line.split creates string elements, adding extraneous quotation marks in a string and converting
// number to string, so there is a need to reverse this process.
const slicedElement = value.slice(1, -1);
myArray.push(slicedElement);
} else {
const valueOfNumber = Number(value);
myArray.push(valueOfNumber);
}
}
})
.on("close", function () {
callback(myArray);
});
}
else{
var myfunction = this.readFile.bind(this, params, callback);
setTimeout(myfunction, 5000);
}
});
};
and lastly:
targetClient.readFile(params, function (arrayResult) {
logger.info("Read file:" + fileName + OS_FILE_SUFFIX);
readArray = arrayResult;
});
If I put a breakpoint on callback(items) (in 'haveFilesBeenWrittenToBucket') everything works fine and I get back the file written in the bucket, but if not, nothing seems to get written to S3. Seems like some race condition, but I'm really clueless and I really would appreciate some help. Is there a conflict between listing objects and writing to S3 (at least not until much later, in some other test, when it shouldn't be (it's part of a mocha test suite - the readFile is in async.waterfall). I have been on this for days and got nowhere. As I said, it's my first exposure to node, so please be patient with me. Thanks.
A: S3 provides eventual consistency for list after read. So, you might observe the following:
A process writes a new object to Amazon S3 and immediately lists keys within its bucket. Until the change is fully propagated, the object might not appear in the list.
The only situation in which S3 provides immediate consistency is read-after-write for PUTS of new objects (with a minor caveat, documented here).
More details at S3 consistency model.
Here is an example of how you can use async retry to wait for an object and then retrieve its contents (assumed to be text in this example).
var aws = require("aws-sdk");
var async = require("async");
var s3 = new aws.S3();
var bucket = 'mybucket';
var iteration = 0;
function waitForObjects(bucket, callback) {
console.error(`Iteration: ${++iteration}`);
s3.listObjects({Bucket:bucket}, function(err, data) {
if (err) {
callback(err);
} else if (!data.Contents || !data.Contents.length) {
callback(new Error("No objects"))
} else {
callback(null, data);
}
});
}
// Try calling waitForObjects 10 times with exponential backoff
// (intervals of 100, 200, 400, 800, 1600, ... milliseconds)
async.retry({
times: 10,
interval: function(retryCount) {
return 50 * Math.pow(2, retryCount);
}
}, async.apply(waitForObjects, bucket), function(err, data) {
if (err) {
console.error(`Error waitForObjects: ${err}`);
} else {
console.log(`Object count: ${data.Contents.length}`);
data.Contents.forEach(function(item, index) {
console.log(`Object ${index+1} key: ${item.Key}`);
s3.getObject({Bucket:bucket, Key:item.Key}, function(err, data) {
console.log(`Object ${index+1} txt: ${data.Body.toString()}`);
});
});
}
});
A: Two things. Firstly, it turns out that my issue was not nodeJS related. Sigh
Secondly, the API now provides a 'waitFor' method for polling whether a bucket or objects exists:
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#waitFor-property
| |
doc_23536559
|
mockObject.GetArgumentsForCallsMadeOn(x => x.MethodIWantToGetParametersFrom(null))
Which returns a IList of type object array. Great! I go and get what I want and process it how I wish. Now using the AAA syntax of TypeMock I cannot seem to work out a way to do this... Could anyone shed some light on this please? Should I be doing it differently?
Thanks for reading and I look forward to your responses!
Adam
A: you can use DoInstead():
Isolate.WhenCalled(()=>x.MethodIWantToGetParametersFrom).DoInstead(context => Console.WriteLine(context.Parameters[0].ToString())
You get a Context object that contains the param values.
you can also implement a method with the same name on your own class, and swap calls from the faked object to that method:
class MyOwnClass
{
void MethodIWantTOGetParametersFrom(string s){
Console.WriteLine(s);
} //this is NOT the real method
}
//in test:
MyOwnClass own = new MyOwnClass();
Isolate.Swap.CallsOn(realClassInstance).WithCallsTo(own); //only methods that are implemented in the OwnCalss will be redirected. others will be called on the original instance.
| |
doc_23536560
|
Private Sub Befehl80_Click()
Dim rst As DAO.Recordset
Set rst = CurrentDb.OpenRecordset("SELECT DISTINCT tb_KonzeptDaten.DFCC, tb_KonzeptDaten.OBD_Code AS Konzept_Obd,tb_KonzeptDaten.DFC INTO Test_Table FROM tb_KonzeptDaten", dbOpenDynaset)
Me.txtDs = rst.RecordCount
End Sub
Would you please tell me how can I solve this problem and why this error occures?
A: The sql is an action query, it creates a table. You cannot open a recordset from an action query. If you want to run the action query, you can say:
Set db=CurrentDB
ssql="SELECT DISTINCT tb_KonzeptDaten.DFCC, " _
& "tb_KonzeptDaten.OBD_Code AS Konzept_Obd,tb_KonzeptDaten.DFC " _
& "INTO Test_Table FROM tb_KonzeptDaten"
db.Execute ssql, dbFailOnerror
RecordsUpdated=db.RecordsAffected
| |
doc_23536561
|
for example this code is working good:
import Image from 'next/image';
<Image alt="shark image" src="/images/shark.png" width={1000} height={1000} />
But when providing a src with filename that contain Hebrew letters the image is not loading, for example:
import Image from 'next/image';
<Image alt="shark image" src="/images/כריש.png" width={1000} height={1000} />
and the following error is shown:
error - TypeError [ERR_INVALID_CHAR]: Invalid character in header content ["Content-Disposition"]
at ServerResponse.setHeader (_http_outgoing.js:470:3)
at setResponseHeaders (..\node_modules\next\dist\server\image-optimizer.js:442:13)
with network response of
Status Code: 500 Internal Server Error
| |
doc_23536562
|
Below is my example simplified.
The entity Program. A program can be part of other programs:
namespace Domain.Entities
{
using System;
using System.Collections.Generic;
public partial class Program
{
public Program()
{
this.Programs = new HashSet<Program>();
}
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public System.DateTime StartDate { get; set; }
public System.DateTime EndDate { get; set; }
public Nullable<int> ProgramId { get; set; }
public virtual ICollection<Program> Programs { get; set; }
public virtual Program OwnerProgram { get; set; }
}
}
The DbContext:
namespace Infrastructure.Model
{
public class ProgramContext : DbContext
{
public ProgramContext()
: base("name=MyContainer")
{
Configuration.LazyLoadingEnabled = false;
}
public DbSet<Program> Programs { get; set; }
}
}
Here is how I use it:
private ProgramContext _dbContext = new ProgramContext();
// GET api/program
public IEnumerable<Program> GetPrograms()
{
List<Program> list = _dbContext.Programs.ToList();
return list;
}
With the above sample, EF still loads the Programs and OwnerProgram properties of the Program class. I have tried removing the virtual keywords, disabling the proxy creation and also verified that LazyLoadingEnabled=false on the Model itself.
Am I missing something?
A: The effect you are seeing is called relationship fixup.
Actually the navigation properties are not loaded explicitly. The query _dbContext.Programs.ToList() only loads the whole Programs table from the database. This is just a simple SQL query (like SELECT * FROM ProgramsTable) without any WHERE clause and without any JOIN to related rows.
Also no lazy loading happens here (it really can't if you disable it and if you disable even dynamic proxies) when you access the program.Programs and program.OwnerProgram navigation properties.
The navigation properties get populated when the result from your query is materialized because your query (that loads all programs) will have loaded all programs that the navigation properties can refer to. EF detects that those related entities are already in memory and put them into the navigation properties automatically.
You can verify this if you don't load all programs but only, for example, a single one:
Program program = _dbContext.Programs.FirstOrDefault();
Now, program.Programs and program.OwnerProgram will be null - unless the loaded program is part of its own program.OwnerProgram collection or is its own OwnerProgram.
A:
"EF still loads the Programs and OwnerProgram properties of the Program
class"
This is the correct behavior, but instead of loading the navigation properties lazily, it loads them eagerly.
This means that the database queries required to retrieve the navigation property values are executed immediately when the Program entity is retrieved and the navigation properties are populated.
When LazyLoadingEnabled is set to true these queries aren't triggered until you attempt to access the navigation properties. This also applies to when you're hovering your mouse over navigation properties and the debugger is attached, which may lead you to think that the entities aren't being lazily loaded when in fact they are - the debugger is accessing the navigation property, so Entity Framework loads it.
You can run a SQL profiler such as this one to see exactly when queries are being triggered as you debug your code.
A:
With the above sample, EF still loads the Programs and OwnerProgram
properties of the Program class. I have tried removing the virtual
keywords, disabling the proxy creation and also verified that
LazyLoadingEnabled=false on the Model itself.
Am I missing something?
You need to remove default constructor that initializes these properties.
| |
doc_23536563
|
The code below seems close to what I want, but it always emits ONCE and then exits. What's odd is that I have a condition in takeUntil() which will NEVER be true -- I'd expect this observable to emit continuously and eventually time out, but it doesn't.
What am I missing/doing wrong here?
Observable.fromCallable(() -> getSendWindow())
.sample(10, TimeUnit.MILLISECONDS)
.timeout(30, TimeUnit.SECONDS)
.takeUntil(sendWindow -> 1==2)
.doOnError(throwable -> log.warn("Timed out waiting for send window to clear. Giving up."))
.doOnCompleted(() -> {
log.info("Send window cleared");
})
.toBlocking().forEach(sendWindow -> log.info("sendWindow={}, getSendWindow());
A: .sample does not do what you think it does. Sample rate limits the above Observable to (at most) once every 10 seconds.
Observable.fromCallable() only emits an event once, then completes.
.sample() waits 10 seconds and emits the last event (if there is one), every 10 seconds. Therefore it only emits one event, when you attach it to an Observable that only has one event. Then it completes.
What you probably actually want (I'm a .net programmer, so excuse my casing etc) is this.
Edit: Thanks for @akanokd for telling me that java uses interval for repeated events.
Observable.interval(10, timeUnit.MILLISECONDS)
.map(x -> getSendWindow())
.takeUntil(sendWindow -> 1==2)
.doOnError(throwable -> log.warn("Timed out waiting for send window to clear. Giving up."))
.doOnCompleted(() -> {
log.info("Send window cleared");
})
.toBlocking().forEach(sendWindow -> log.info("sendWindow={}, getSendWindow());
Feel free to edit this answer with the API calls to the JAVA specific version...
| |
doc_23536564
|
This is to prevent toddler's from pressing the tower reset/power button.
I'm using this program (Toddler Keys) right now to disable drive doors but unfortunately, the power option only works in XP
Update
I found ShutdownGuard which is close to the task.
A: A better solution for a tower is hardware - a piece of plexiglass in front of the tower, for example. Depending on your toddler and the supervision level you provide, you could just prop it in front, or velcro it in place. If the tower is on a shelf, attaching the plexiglass to the shelf is even better.
A: Here is two non coding solution: http://www.bleepingcomputer.com/forums/topic117236.html
*
*Pull the cable from the switch ;)
*Change the setting in the windows power options (look in the link for details).
A: I think you'll be out of luck with software solutions to this as reset and long-press power is handled by the motherboard. You'd be best off removing the buttons from their connections on the motherboard and replacing them your own buttons that you can put out of reach.
| |
doc_23536565
|
I save my webView content with saveWebArchive() method that in kitkat and above this method save webView as mhtml format. Here is my code that I don't have any problem with this part:
File internalStorage = getApplication().getDir("MyArchive",Context.MODE_PRIVATE);
File webUrlPath = new File(internalStorage.getAbsolutePath());
String urlFileName = webUrlPath.toString();
html_path = urlFileName + File.separator + article.Articlehtml.hashCode() +
".mht";
webView.saveWebArchive(html_path);
When I want to load saved files in webView I use Javascript for change font color that for lower of kitkat it works perfectly but for kitkat and above Changes will not apply. Here another part of my code that I have problem with it:
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setJavaScriptEnabled(true);
File file = new File(html_path);
//for Kitkat and above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
webView.loadUrl("file:///" + file);
}
else {
String rawData = null;
try {
rawData = getStringFromFile(html_url);
}catch (Exception e){
//e.printStackTrace();
}
webView.loadDataWithBaseURL(null, rawData,"application/x-webarchive-xml","UTF-8", null);
}
webView.setWebViewClient(new WebViewClient(){
public void onPageFinished(WebView view, String url){
view.setBackgroundColor(Color.parseColor("#212121"));
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { webView.evaluateJavascript("document.body.style.setProperty(\"color\", \"white\");", null);
} else {
webView.loadUrl("javascript:document.body.style.setProperty(\"color\", \"white\");");
}
I expect to apply javaScript for saved webView content for kitkat and above, that's mean I can change font color of the mhtml file after loaded it in a WebView.
Thanks for your attention.
A: You can use webArchiveReader (check it in GitHub) for lower 19 API. For KitKat and above just load file in webView but mht format doesn't support JavaScript.
A: Finally, I find a solution for my problem. It's use of ColorMatrixColorFilter for invert colors when webView is loaded.
| |
doc_23536566
|
Here is the relevant menu code:
<item
android:id="@+id/nav_dark"
android:checkable="true"
android:icon="@drawable/round_brightness_4_24"
android:title="@string/menu_dark"
app:actionViewClass="android.widget.Switch" />
The switch does appear on the right side of the menu item.
My listener:
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.nav_dark) {
// code to apply dark or light theme
// works as expected
}
else {
// code to handle regular menu items
// it works too
}
return true;
}
My problems:
*
*When I tap on R.id.nav_dark the item gets selected. I would like the colored overlay to stay on (or jump back to) the previous menu item, whose fragment is actually shown behind the drawer.
*The switch does not react accordingly, even if I use item.setChecked(true) manually. I would like the switch to be turned on when the dark theme is enabled and turned off when it's disabled.
*Tapping on the switch itself does not pass the event to the menu item. I would like them to work in sync.
I have seen checkboxes and swiches working like this in other applications, although, most of them were in the app bar's overflow menu. (I have tried mine with a checkbox too, but no difference.)
A: I solved this problem using this thread: Switch in Navigation drawer item with Design Support Library on Android
In this example the dedicated menu item switches between a light and dark theme, but you can use it to toggle any settings, of course.
Problems to solve
*
*Implement our own onNavigationItemSelected listener, because the default solution created by Android Studio prevents the use of a dedicated menu item.
*Implement the fragment transaction and toolbar handling logic.
*Implement the onCheckedChange listener of the switch.
What we do is capture clicks on the menu items. If it's a regular item, we change the fragment behind the drawer. If it's the dedicated item with the switch, we manually toggle the switch, which calls its listener.
The actual code (changing the theme in this case) is handled by the listener of the switch. If you click on the switch itself, the listener will be called directly.
Relevant code from activity_main_drawer.xml menu file
<item
android:id="@+id/nav_dark"
android:checkable="true"
android:icon="@drawable/round_brightness_4_24"
android:title="@string/menu_dark"
app:actionViewClass="android.widget.Switch" /> <!-- you can also use a CheckBox -->
Relevant code from MainActivity.java
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, Switch.OnCheckedChangeListener {
private Toolbar toolbar;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle toggle;
private NavigationView navigationView;
private Switch switchDark;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(getResources().getString(R.string.toolbar_title));
setSupportActionBar(toolbar);
// We have to handle the fragment changes manually,
// because what we do conflicts with the default solution created by Android Studio
drawerLayout = findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.setDrawerIndicatorEnabled(true);
toggle.syncState();
navigationView = findViewById(R.id.nav_view);
// Check the menu item connected to the default fragment manually
navigationView.getMenu().findItem(R.id.nav_item1).setChecked(true);
navigationView.setNavigationItemSelectedListener(this); // See below!
switchDark = (Switch)navigationView.getMenu().findItem(R.id.nav_dark).getActionView();
// Set the default state of the switch connected to the menu item
switchDark.setChecked(AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES);
switchDark.setOnCheckedChangeListener(this); // See below!
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
// Handle the menu item with the switch
if (item.getItemId() == R.id.nav_dark) {
((Switch)item.getActionView()).toggle(); // Call the onCheckedChangeListener of the switch and let it do the work
return false; // Prevent the menu item to get selected (No overlay indicator will appear)
}
// Handle the other menu items
// We have to do this, because we deleted the default solution created by Android Studio
Fragment newFragment = null;
if (item.getItemId() == R.id.nav_item1) {
newFragment = new CustomFragment();
toolbar.setTitle(getResources().getString(R.string.custom_fragment_title));
}
else if (item.getItemId() == R.id.nav_item2) {
newFragment = new OtherFragment();
toolbar.setTitle(getResources().getString(R.string.other_fragment_title));
}
// Start the fragment transition manually
if (newFragment != null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_host_fragment, newFragment);
transaction.addToBackStack(null);
transaction.commit();
drawerLayout.close();
}
return true; // The selected item will have the overlay indicator
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(buttonView.getContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
int themeID;
if (isChecked) {
themeID = AppCompatDelegate.MODE_NIGHT_YES;
}
else {
themeID = AppCompatDelegate.MODE_NIGHT_NO;
}
AppCompatDelegate.setDefaultNightMode(themeID); // Change the theme at runtime
editor.putInt("themeID", themeID); // Save it to be remembered at next launch
editor.apply();
}
}
A: try this one.
<item
app:actionViewClass="androidx.appcompat.widget.SwitchCompat"
android:icon="@drawable/message"
android:title="All inboxes"
android:id="@+id/inbox"
/>
this above is the menu item we need
in order to get click events follow below steps mentioned
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
if (item.getItemId()==R.id.inbox){
((SwitchCompat) item.getActionView()).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
Toast.makeText(buttonView.getContext(), "Checked", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(buttonView.getContext(), "unChecked", Toast.LENGTH_SHORT).show();
}
}
});
}
Toast.makeText(MainActivity.this, ""+item.getTitle(), Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
});
we already given our action class in menu item from xml .
we just need to verify which item it was and when it happens we can get the actionviewclass that we had assigned
and an onclicklistener on it .. this one worked for me .
| |
doc_23536567
|
$results = $conn->prepare("INSERT INTO book_loans
VALUES (:book_id, :branch_id, :card_no, CURDATE(), DATE_ADD(CURDATE(), INTERVAL 14 DAY))");
//Binding params and executing insert for checking out
$results->bindParam(':book_id', $book_id, PDO::PARAM_STR);
$results->bindParam(':branch_id', $branch_id, PDO::PARAM_INT);
$results->bindParam(':card_no', $card_no, PDO::PARAM_STR);
if($results->execute()) {
return array("success");
} else {
return array("failure");
}
I am returning arrays with strings to check back and display a message.
But even for valid elements, the query is failing.
A: What is the error message?
Usually the cause is an error in the SQL query! Check that the query actually works in the MySQL console.
If you require more specific help you need post the desription of the book_loans table. Can you post the create table statement for this table?
A: In stead of returning array ('failure') return array($results->errorInfo()), analyze the error text and then fix it
| |
doc_23536568
|
ddlEmp.SelectedIndexChanged += new EventHandler(grd_ddlEmp_SelectedIndexChanged);
but I do not know how to change Emp Code and Designation values inside the particular row in gridview.
A: You need to put your gridview in UpdatePanel and do it in code behind of SelectedIndexChanged event like I have done in datalist below :
<asp:DataList ID="dlstPassengers" runat="server" OnItemDataBound="dlstPassengers_ItemDataBound"
RepeatDirection="Horizontal" RepeatColumns="2" Width="100%">
<ItemTemplate>
<div class="form-linebg" style="line-height: 32px;">
<asp:DropDownList ID="ddlCountry" AutoPostBack="true" OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged"
CssClass="select-3" Style="width: 145px; margin-bottom: 9px;" runat="server">
</asp:DropDownList>
<br />
<asp:DropDownList ID="ddlCity" CssClass="select-3" Style="width: 145px; margin-bottom: 10px;"
runat="server">
</asp:DropDownList>
</div>
</ItemTemplate>
</asp:DataList>
In code behind :
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlCountry = (DropDownList)sender;
DropDownList ddlCity = (DropDownList)((DropDownList)sender).Parent.FindControl("ddlCity");
BindCity(ddlCity, ddlCountry.SelectedValue);
}
private void BindCity(DropDownList ddlCity, string countryCode)
{
// Binding code of city based selected country
}
You need to set EmpCode and Designation columns on SelectedIndexChanged event of dropdown by finding control in code behind.
A: In the SelectedIndexChanged function, find the selected value of the drop down box
DropDownList ddl = (GridView1.Rows[GridView1.SelectedIndex].FindControl("DropDownList1") AS DropDownList);
var selectedVal = ddl.SelectedValue;
Execute some code to determine the Emp Code and Desgination and then populate the relevant label ( or other control):
Label lbl = GridView1.Rows[GridView1.SelectedIndex].FindControl("Label1") as Label;
Assign value to the label.
A: Does these things inside the SelectedIndexChanged event of the DropDownList
*
*First find the row.
*Then access the controls and change accordingly.
Pseudo Code
protected void grd_ddlEmp_SelectedIndexChanged(object sender, EventArgs e)
{
GridView row = ((DropDownList)sender).NamingContainer as GridViewRow;
Label Designation = row.FindControl("id of the designation label") as Label;
Designation.Text = "new Designation Name";
}
A: use in your dropdown AutoPostBack="true"
| |
doc_23536569
|
it can be found there: https://github.com/buriy/spacy-ru
The problem is when I call the function
nlp = spacy.load('ru2')
doc = nlp(text)
I see the error
C:\ProgramData\Anaconda3\lib\importlib\_bootstrap.py:205: RuntimeWarning: spacy.tokens.span.Span size changed, may indicate binary incompatibility. Expected 72 from C header, got 80 from PyObject
return f(*args, **kwds)
Traceback (most recent call last):
File "C://.../nlp/src/ie/main.py", line 125, in <module>
main(examp_dict['Poroshenko'])
File "C://.../nlp/src/ie/main.py", line 92, in main
nlp = spacy.load('ru2')
File "C:\ProgramData\Anaconda3\lib\site-packages\spacy\__init__.py", line 27, in load
return util.load_model(name, **overrides)
File "C:\ProgramData\Anaconda3\lib\site-packages\spacy\util.py", line 133, in load_model
return load_model_from_path(Path(name), **overrides)
File "C:\ProgramData\Anaconda3\lib\site-packages\spacy\util.py", line 173, in load_model_from_path
return nlp.from_disk(model_path)
File "C:\ProgramData\Anaconda3\lib\site-packages\spacy\language.py", line 791, in from_disk
util.from_disk(path, deserializers, exclude)
File "C:\ProgramData\Anaconda3\lib\site-packages\spacy\util.py", line 630, in from_disk
reader(path / key)
File "C:\ProgramData\Anaconda3\lib\site-packages\spacy\language.py", line 781, in <lambda>
deserializers["tokenizer"] = lambda p: self.tokenizer.from_disk(p, exclude=["vocab"])
File "tokenizer.pyx", line 391, in spacy.tokenizer.Tokenizer.from_disk
File "tokenizer.pyx", line 432, in spacy.tokenizer.Tokenizer.from_bytes
File "C:\ProgramData\Anaconda3\lib\site-packages\spacy\util.py", line 606, in from_bytes
msg = srsly.msgpack_loads(bytes_data)
File "C:\ProgramData\Anaconda3\lib\site-packages\srsly\_msgpack_api.py", line 29, in msgpack_loads
msg = msgpack.loads(data, raw=False, use_list=use_list)
File "C:\ProgramData\Anaconda3\lib\site-packages\srsly\msgpack\__init__.py", line 60, in unpackb
return _unpackb(packed, **kwargs)
File "_unpacker.pyx", line 191, in srsly.msgpack._unpacker.unpackb
TypeError: unhashable type: 'list'
I was searching for similar questions in the Internet:
*
*https://github.com/explosion/spaCy/issues/2715
*https://spacy.io/usage#unhashable-list
But non of those solutions work for me.
I use
*
*msgpack==0.5.6 (even downgraded as suggested in the link above)
*spacy==2.1.4
A: Here is from https://spacy.io/usage#troubleshooting
If you’re training models, writing them to disk, and versioning them with git, you might encounter this error when trying to load them in a Windows environment. This happens because a default install of Git for Windows is configured to automatically convert Unix-style end-of-line characters (LF) to Windows-style ones (CRLF) during file checkout (and the reverse when committing). While that’s mostly fine for text files, a trained model written to disk has some binary files that should not go through this conversion. When they do, you get the error above. You can fix it by either changing your core.autocrlf setting to "false", or by committing a .gitattributes file] to your repository to tell git on which files or folders it shouldn’t do LF-to-CRLF conversion, with an entry like path/to/spacy/model/** -text. After you’ve done either of these, clone your repository again.
A: It might be because the version number of SpaCy used to generate your model is not the same as the version of SpaCy you have installed. (I don't know of course, just mentioning it in case it helps.)
A: Adding to the answer above, another quick fix would be to manually download the zip from the repository.
| |
doc_23536570
|
Table transactions:
+-------+--------+--------+
| month | cat_id | amount |
+-------+--------+--------+
| 1 | 2 | 3 |
| 1 | 2 | 8 |
| 2 | 1 | 7 |
| 2 | 1 | 5 |
+-------+--------+--------+
Table categories:
+--------+-------------+
| cat_id | cat_desc |
+--------+-------------+
| 1 | Stock |
| 2 | Consumables |
+--------+-------------+
What I would like is to construct a query that displays a sum of the amounts for each category, for each month, even if there is no expenditure in that category for that month like this:
+-------+-------------+--------+
| month | cat_desc | amount |
+-------+-------------+--------+
| 1 | Stock | 0 |
| 1 | Consumables | 11 |
| 2 | Stock | 12 |
| 2 | Consumables | 0 |
+-------+-------------+--------+
I suspect an outer join would need to be used but I haven't found a statement to do it yet.
Thank you for any help.
A: This one should provide you with the correct result. The inner select prepares a list of all months combined with all categories, and the LEFT JOIN handles the rest.
SELECT t.month, t.cat_desc, COALESCE(SUM(t2.amount), 0) amount
FROM (
SELECT DISTINCT t.month, c.cat_id, c.cat_desc
FROM categories c
CROSS JOIN transactions t
) t
LEFT JOIN transactions t2 ON ( t2.month = t.month AND t2.cat_id = t.cat_id )
GROUP BY t.month, t.cat_desc
Performance might be better with the following (using DISTINCT only where necessary), but you will have to try:
SELECT t.month, t.cat_desc, COALESCE(SUM(t2.amount), 0) amount FROM (
SELECT t.month, c.cat_id, c.cat_desc
FROM
(SELECT DISTINCT month FROM transactions) t
CROSS JOIN categories c
) t
LEFT JOIN transactions t2 ON ( t2.month = t.month AND t2.cat_id = t.cat_id )
GROUP BY t.month, t.cat_desc
A: SELECT c.cat_id, c.cat_desc,t.month, SUM(t.amount)
FROM categories c
LEFT JOIN transactions t ON (t.cat_id = c.cat_id)
GROUP BY c.cat_id,t.month
A: SELECT c.cat_id, c.cat_desc,t.month, SUM(t.amount)
FROM categories c
LEFT JOIN transactions t ON (t.cat_id = c.cat_id)
GROUP BY t.month,c.cat_id
Order By t.month
| |
doc_23536571
|
Is there any way to do the same?
A: in redis 4.0 there is a new command
MEMORY PURGE
that will defragment memory and release it to the OS.
also see
MEMORY HELP
A: You may reference to this issue compact memory use online
| |
doc_23536572
|
import sys
from multiprocessing.pool import ThreadPool
def handle_ip(ip_address):
print('Child Thread')
# Visit Web Page etc...
sys.exit()
print('HI')
ip_addresses = ['1234']
pool = ThreadPool(processes=6)
p_results = [pool.apply_async(handle_ip, (ip,)) for ip in ip_addresses]
for result in p_results:
result.get()
# Wait for ALL threads to finish
print('BYE')
For some reason it never stops running (BYE is never being printed), what's the problem?
I have 6 threads but only 1 is running as there is only one ip address in input, plus sys.exit() terminates current thread only so after it's terminated main thread should continue and end the program.
Please Note, I want to exit only the current thread, that's why I used sys.exit().
My code is much more complex and this is only a simple example to show the problem (even though it doesn't make much of a sense to immediately kill the thread)
A: Try calling pool.close() before your loop.
A: Why you don't use concurrent?
from concurrent.futures import ThreadPoolExecutor
def handle_ip(ip_address):
print('Child Thread')
print('HI')
ip_addresses = ['1234']
with ThreadPoolExecutor(max_workers=6) as executor:
results = executor.map(handle_ip, ip_addresses)
print('BYE')
| |
doc_23536573
|
Now, what I would like to do is to add a access check function much similar to the {if} tag.
What I would like to write is:
{userAccess module='MyModule' action='WriteMessage'}
Yeey.. I can write something. My name is {$myName}.
{/userAccess}
but I can't figure out how to. Can someone please point me into the right direction?
Also, if possible adding and {else} to it. So the code would be:
{userAccess module='MyModule' action='WriteMessage'}
Yeey.. I can write something. My name is {$myName}.
{else}
Nooo.. :( I don't have access.
{/userAccess}
A: I solved it creating my own "internal" function for smarty. This might not be the way Smarty intended it to be used, but it sure works for me... which is the most important thing for me.
This is my end result:
<?php
/**
* Smarty Internal Plugin Compile UserAccess
*
* Compiles the {useraccess} {useraccesselse} {/useraccess} tags
*
* @package Smarty
* @subpackage Compiler
* @author Paul Peelen
*/
/**
* Smarty Internal Plugin Compile useraccess Class
*/
class Smarty_Internal_Compile_useraccess extends Smarty_Internal_CompileBase {
// attribute definitions
public $required_attributes = array('module', 'action');
public $optional_attributes = array('userid'); // Not yet implemented
public $shorttag_order = array('module','action','userid');
/**
* Compiles code for the {useraccess} tag
*
* @param array $args array with attributes module parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
* @return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
$this->compiler = $compiler;
$tpl = $compiler->template;
// check and get attributes
$_attr = $this->_get_attributes($args);
$module = $_attr['module'];
$action = $_attr['action'];
if (!is_string($module) || !is_string($action))
{
exit ("ERROR");
}
$this->_open_tag('useraccess', array('useraccess', $this->compiler->nocache, $module, $action));
$this->compiler->nocache = $this->compiler->nocache | $this->compiler->tag_nocache;
$output = "<?php ";
$output .= "\$oAuth = \$GLOBALS['oAuth'];\n";
$output .= " \$_smarty_tpl->tpl_vars[$module] = new Smarty_Variable;\n";
$compiler->local_var[$module] = true;
$output .= " \$_smarty_tpl->tpl_vars[$action] = new Smarty_Variable;\n";
$compiler->local_var[$action] = true;
$output .= "if (\$oAuth->getUserSubRights($action,$module)) {";
$output .= "?>";
return $output;
}
}
/**
* Smarty Internal Plugin Compile UserAccessElse Class
*/
class Smarty_Internal_Compile_UserAccessElse extends Smarty_Internal_CompileBase {
/**
* Compiles code for the {useraccesselse} tag
*
* @param array $args array with attributes module parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
* @return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
$this->compiler = $compiler;
// check and get attributes
$_attr = $this->_get_attributes($args);
list($_open_tag, $nocache, $item, $key) = $this->_close_tag(array('useraccess'));
$this->_open_tag('useraccesselse', array('useraccesselse', $nocache, $item, $key));
return "<?php } else { ?>";
}
}
/**
* Smarty Internal Plugin Compile UserAccessclose Class
*/
class Smarty_Internal_Compile_UserAccessclose extends Smarty_Internal_CompileBase {
/**
* Compiles code for the {/useraccess} tag
*
* @param array $args array with attributes module parser
* @param object $compiler compiler object
* @param array $parameter array with compilation parameter
* @return string compiled code
*/
public function compile($args, $compiler, $parameter)
{
$this->compiler = $compiler;
// check and get attributes
$_attr = $this->_get_attributes($args);
// must endblock be nocache?
if ($this->compiler->nocache) {
$this->compiler->tag_nocache = true;
}
list($_open_tag, $this->compiler->nocache, $item, $key) = $this->_close_tag(array('useraccess', 'useraccesselse'));
unset($compiler->local_var[$item]);
if ($key != null) {
unset($compiler->local_var[$key]);
}
return "<?php } ?>";
}
}
I hope this helps anybody who has this problem in the future.
A: You could try registerPlugin.
$smarty->registerPlugin("block","userAccess", array('YourClass', 'your_function'));
and your class:
class YourClass {
static function your_function($params, $content, $smarty, &$repeat, $template) {
$module = $params['module'];
$action = $params['action'];
if ($action == 'WriteMessage' && $user_may_write_message) {
return $content;
else
return '';
}
}
The problem here is that you are not so easiliy able to use variables inside this block. Maybe you can send the inner content to smarty again, but since it only allows template files in the function fetch() I'm not quite sure if this works.
What could help though is the smarty function eval, but I have not worked with it yet.
| |
doc_23536574
|
Is there anyway to get data of my discord server using something like the Discord API or Webhook?
A: For users, you have guild.members
Further, you can iterate over it and get their name and discriminator
A: You can do a command that gets you all the members and then you can get their length and send it to the flask application.
@client.command()
async def get_members(ctx):
await ctx.message.delete()
#This will get you all the members in your server
for user in list(ctx.guild.members):
print(user)
#You can do whatever you want here
A: As far as I have seen, the only convenient way of passing your bot info to a website is to have an instance of a bot running simultaneously (You could, of course, also make native API calls, but I wouldn't recommend that). So as soon as you start your flask application, you would also have to initialize an instance of your bot.
Your bot, by default, fetches certain information on initialization, such as the servers it's on. You should be able to present that information then to your website.
You can also use the client.get_... methods to gain additional information.
So, if you flask app needs certain information, you could initialize your client, create functions like
def get_guild_names():
return [guild.name for guild in client.guilds]
and then call them from your flask application.
| |
doc_23536575
|
[System.CodeDom.Compiler.GeneratedCodeAttribute("MonoDevelop", "2.6.0.0")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute
(Name="CommonWebServicePortBinding", Namespace="http://mynamespace.com")]
public class CWebService : CommonWebService
{
public CWebService ()
{
try
{
this.Url = "Url to wsdl";
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString ());
}
}
protected override System.Xml.XmlWriter GetWriterForMessage (
SoapClientMessage message, int bufferSize )
{
message.Headers.Add(My Custom Header goes here);
return base.GetWriterForMessage(message, bufferSize);
}
}
but GetWriterForMessage hasn't been implemented in mono. Is there any other way?
A: Apparently there's no way to customize Soap Headers in Mono and GetWriterForMessage throws NotImplementedException.
| |
doc_23536576
|
item = items(:one)
,,, do some db manipulation to this object ...
Item.all.each do |i|
puts "#{i.inspect}"
end
updated_item = Item.find(id: item.id)
But the line
updated_Item = Item.find(id: item.id)
dies with the error
ActiveRecord::RecordNotFound: Couldn't find Item with 'id'={:id=>980190962}
What is odd is taht in the lines above, where I print out the records in my database, I can see the object in question with the ID that Rails claims not to find ...
#<Item id: 298486374, name: "MyString", rating: 0, score: 0, created_at: "2018-01-19 20:25:05", updated_at: "2018-01-19 20:25:05">
#<Item id: 980190962, name: "Item1", rating: 1, score: 5, created_at: "2018-01-19 20:25:05", updated_at: "2018-01-19 20:25:05">
What am I doing wrong? How do I lookup the updated object?
A: find() looks by id , no need to tell, so:
updated_Item = Item.find(item.id)
| |
doc_23536577
|
<jsp:useBean id = "questionSet" scope = "session" class="Questions.QuestionMaker"/>
to run the constructor. Now my problem is using the getProperty action to assign the 2d string array to an existing 2d array in the jsp. I honestly have no idea of how to do this. I tried something like
<%String[][] currenQuestions = (jsp:getProperty name = "user" property = "firstName"/)>
but needless to say that didn't work.
My teacher is insisting that we have to use getProperty to set the value and we can't do other things. If anyone can help me out please let me know.
Thanks in advance
| |
doc_23536578
|
for some reason it says the output started at the end of the google analytics tracking code for google experiments I had,
the full file of that file is this
<!-- Google Analytics Content Experiment code -->
<script>function utmx_section(){}function utmx(){}(function(){var
k='62393235-4',d=document,l=d.location,c=d.cookie;
if(l.search.indexOf('utm_expid='+k)>0)return;
function f(n){if(c){var i=c.indexOf(n+'=');if(i>-1){var j=c.
indexOf(';',i);return escape(c.substring(i+n.length+1,j<0?c.
length:j))}}}var x=f('__utmx'),xx=f('__utmxx'),h=l.hash;d.write(
'<sc'+'ript src="'+'http'+(l.protocol=='https:'?'s://ssl':
'://www')+'.google-analytics.com/ga_exp.js?'+'utmxkey='+k+
'&utmx='+(x?x:'')+'&utmxx='+(xx?xx:'')+'&utmxtime='+new Date().
valueOf()+(h?'&utmxhash='+escape(h.substr(1)):'')+
'" type="text/javascript" charset="utf-8"><\/sc'+'ript>')})();
</script><script>utmx('url','A/B');</script>
<!-- End of Google Analytics Content Experiment code -->
why would I be getting this error?
A: No output should be above the headers. There is a range of reasons why this could be caused. examples.
<?php
header ("Location: test.php");
?>
this wont throw an error
<?php
echo "blabla";
header ("Location: test.php");
?>
OR
<strong> test</strong>
<?php
header ("Location: test.php");
?>
the above will trigger an error.
A: Use ob_start(); as the first line of your code to avoid the error message 'headers already sent'.
| |
doc_23536579
|
I'm using the following code :
#include <iostream>
#include<opencv/cv.h>
#include <opencv/highgui.h>
using namespace cv;
using namespace std;
int main() {
cout << "!!!Hello World !!!" << endl; // prints !!!Hello World!!!
cvNamedWindow( "abc", 1 );
IplImage* img = cvLoadImage( "C:\\Users\\****\\Pictures\\123.jpg" );
cvShowImage( "abc", img );
while( 1 ) {
if( cvWaitKey( 100 ) == 27 ) break;
}
cvDestroyWindow( "abc" );
cvReleaseImage( &img );
return 0;
}
When i execute the above code i got the following Error:
Windows Not responding.
Other Information:
OS: Windows8
IDE : EClipse
openCV Vesion 2.4.0
c++ compiler : MinGW
Please let me know if more additional information is required.
A: try
bool stop = 0;
while( !stop) {
if( cvWaitKey( 100 ) == 27 ) stop=1;
}
What happens in debug mode? Expand the if statement and put a cout << "exit"; in, add a break point and then step through. Find out where it stops responding.
| |
doc_23536580
|
public class Main
{
public Student Student { get; set; }
public override bool Equals(object obj)
{
if (this.GetType() != obj.GetType()) throw new Exception();
return Student.Age == ((Student)obj).Age;
}
}
public class Student
{
public int Age { get; set; }
public Name Name { get; set; }
public override bool Equals(object obj)
{
if (this.GetType() != obj.GetType()) throw new Exception();
return Age == ((Student)obj).Age;
}
}
public class Name
{
public string FirstName { get; set; }
public string LastName { get; set; }
public override bool Equals(object obj)
{
if (this.GetType() != obj.GetType()) throw new Exception();
return FirstName == ((Name)obj).FirstName && LastName == ((Name)obj).LastName;
}
}
when I try and serialize
JsonConvert.SerializeObject(new Main{ ... });
I get different types in the Equals method of the Main type, and I would assume different types in the other Equals method.
The types that I get are, for
this.GetType() // => Main
obj.GetType() // => Student
Why does json act this why, why does it make use of Equals method and how to make it behave as it should ?
A: It is ultimately valid - if not common - to compare between different object types. The answer should simply be "no" (false). So:
public override bool Equals(object obj)
=> obj is Main other && Equals(Student, other.Student);
and
public override bool Equals(object obj)
=> obj is Student other && Age == other.Age; // && Equals(Name, other.Name) ?
and
public override bool Equals(object obj)
=> obj is Name other && FirstName == other.FirstName && LastName == other.LastName;
(or something like that, depending on what you want).
However! You should always ensure that GetHashCode() is compatible with Equals(), otherwise equality is not fully implemented (see CS0659)
| |
doc_23536581
|
class PlayerStateFlying
{
// Includes a function that sets Player::currentState = something
}
class PlayerStateHit
{
// Includes a function that sets Player::currentState = something
}
class Player : public PlayerStateFlying,
public PlayerStateHit
{
public:
STATE currentState; // Needs to be accessed by the State classes
}
Problem is, my State classes need access to one of Player's properties
How do I go about solving this problem?
---------EDIT-----------
So should it be something like this? P.S I can't quite get it to work
class IBaseStates
{
public:
STATE currentState;
}
class PlayerStateFlying : public IBaseStates
{
// Includes a function that sets IBaseStates::currentState = something
}
class PlayerStateHit : public IBaseStates
{
// Includes a function that sets IBaseStates::currentState = something
}
class Player : public IBaseStates
{
// Includes a function that checks what IBaseStates::currentState equals
}
Here is an example of my dilemma:
void Player::ChangeState( STATE state )
{
switch( state )
{
case FLYING:
currentState = FLYING;
break;
case HIT:
currentState = HIT;
break;
}
}
void Player::StateUpdate()
{
switch( currentState )
{
case FLYING:
PlayerStateFlying::Update( );
currentTextureIndex = PlayerStateFlying::current;
break;
case HIT:
PlayerStateHit::Update( );
currentTextureIndex = PlayerStateHit::current;
break;
}
}
void PlayerStateHit::Update( )
{
...
currentState = FLYING;
index = 0;
...
}
A: Do not forget about polymorphism. You don't need to implement any switch'es.
I think the solution should look like:
class PlayerState {
}
class PlayerStateFlying : public PlayerState {
}
class PlayerStateHit : public PlayerState {
}
Now your Player class (object) should contain (or access) a state object:
class Player {
protected:
PlayerState *playerState;
public:
void setPlayerState(PlayerState *newState);
}
setPlayerState() should look like:
Player::setPlayerState(PlayerState *newState) {
playerState = newState;
}
Now you can simply rewrite your methods for the future supporting variety of PlayerState subclasses:
void Player::StateUpdate() {
playerState->Update(); // Polymorphism!
currentTextureIndex = playerState->current;
}
In the next method you can still use a switch if you still really need to store your currentState variable and use it:
void Player::ChangeState( STATE state ) {
switch( state ) {
case FLYING:
currentState = FLYING;
playerState = new PlayerStateFlying();
break;
case HIT:
currentState = HIT;
playerState = new PlayerStateHit();
break;
}
}
... but there is another -- more convenient solution -- setPlayerState -- we already have it, but if we still need currentState enum (or int or whatever) variable, we can simply expand our PlayerState class (and subclasses) with a new field -- label:
class PlayerState {
public:
int label;
}
PlayerStateFlying::PlayerStateFlying() {
label = FLYING;
}
PlayerStateHit::PlayerStateHit() {
label = HIT;
}
Now it is possible to:
Player::setPlayerState(PlayerState *newState) {
playerState = newState;
currentState = playerState->label;
}
You can also try with constant fields, that is:
class PlayerState {
public:
const int label;
}
PlayerStateFlying::PlayerStateFlying() : label(FLYING) {};
PlayerStateHit::PlayerStateHit() : label(HIT) {};
Regards.
A: A player should be the one setting what the current state is. Not the state itself. And the state update function should look something like:
void Player::StateUpdate() {
mCurrentState->update(this);
}
void PlayerHitState(Player * player) {
player->setCurrentState(player->getStateFromListOfAvailableStates(FLYING))
}
A simple state machine should store all the needed states and transitions. Like you can't fly if you are in water or something similar.
A: Have a common class that stores the State and the information that is needed access to and inherit from it in both Player states.
| |
doc_23536582
|
SyntaxError: missing ; before statement
why do I need a ; before a statement arent these suppose to end statements?
here is the JS fiddle
https://jsfiddle.net/n5v84svm/10/
my code
checkIt(data){
var countriesByName = d3.nest()
.key(function(d) { return d.Country_Names; })
.entries(data);
console.log(countriesByName)
function makePie(){
var chart = c3.generate({
data: {
columns: [
function(m) {
var obj = [];
for (var i in m) {
obj.push('Road ' + m.countriesByName[i].key.values.Food and tobacco);
}
return obj;
}
],
type : 'donut'
}
});
}
makePie();
};
d3.json("https://gist.githubusercontent.com/heenaI/cbbc5c5f49994f174376/raw/82cd19eff7db367193cf8ce00144a40ea8d140ac/data.json", checkIt);
My data set looks like this (full data set could be seen in the fiddle)
[
{
"Continent": "Europe",
"Country_Names": "Albania",
"Total": "3.8",
"Change_total": "-38.7",
"Main activity electricity and heat production": "0.1",
"Main activity electricity plants": "",
"Main activity CHP plants": "",
"Unallocated autoproducers / Other energy industry own use": "0.1",
"Other": "1.4",
"Manufacturing industries and construction": "1",
"Iron and steel": "0",
"Chemical and petrochemical": "0",
"Machinery": "",
"Mining and quarrying": "",
"Food and tobacco": "0.1",
"Paper, pulp and printing": "",
"Construction": "0",
"Transport": "2.2",
"Road": "2.2",
"Domestic aviation": "",
"Rail": "0",
"Domestic navigation": "0.1",
"Residential": "0.2",
"Commercial and public services": "0",
"Agriculture/forestry": "0.2",
"Sub-bituminous coal / Lignite": "",
"Other bituminous coal": "",
"Natural gas": "0",
"Motor gasoline excl. bio": "0.3",
"Gas/diesel oil excl. bio": "2.2"
}]
A: Looks like you just had a few syntax errors...
This:
checkIt(data){
Should be:
function checkIt(data) {
And this:
obj.push('Road ' + m.countriesByName[i].key.values.Food and tobacco);
Should be:
obj.push('Road ' + m.countriesByName[i].key.values.Food + ' and tobacco');
| |
doc_23536583
|
"Exception in thread "main" java.lang.NoClassDefFoundError: phantomjs
Caused by: java.net.URLClassLoader$1.run(URLClassLoader.java.200) at ....."
and a series of ClassLoader errors.
I have scoured the net for clues as to what is causing this and I can't figure it out.
A: How did you come up with idea that phantomjs is Java app? phantomjs is Linux binary, just run it like phantomjs and that's it.
A: From the phantomjs Quick Start page.
This instruction assumes that PhantomJS is installed and its executable is placed somewhere in the PATH.
It is a native executable, not a Java application. So naturally, the java command can't run it. Do what the Quick Start document implies:
*
*Add the directory containing the executable to your $PATH.
*Type the "phantomjs" command using your Linux command shell.
| |
doc_23536584
|
To view objects in the JNDI tree:
In the left pane expand Environment > Servers.
On the Server summary page click the name of the server, for example, myserver.
On the server Settings page click View JNDI Tree.
The JNDI tree is displayed in a new window.
But its throwing class not found exception and not showing anything .
Same is working in 10.3.6 version.
Anyone knows how to fix this issue in 10.3.1 version ?
| |
doc_23536585
|
Environment Build: android-19 emulator spawned by the andorid emulator jenkins plugin
Build steps:
Appium starting in this way:
appium --full-reset --udid $ANDROID_AVD_DEVICE
Invoke Gradle script with on a cucumber task:
sourceSets {
test {
java {
srcDir 'src/java'
}
resources {
srcDir 'src/resources'
}
}
}
task cucumber() {
dependsOn assemble, compileTestJava
doLast {
javaexec {
main = "cucumber.api.cli.Main"
classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
args = ['-f', 'pretty', '--glue', 'gradle.cucumber', 'src/resources']
}
}
}
I created an android studio project with two modules: one with the android app sources and one cucumber-jvm "test" module with all the cucumber tests.
The problem is that, when i try to start a jenkins job that make this steps:
Compile android studio project --> Start Emulator --> Start Appium server --> compile cucumber test --> execute test
The build fail everytime and these are the logs:
https://gist.github.com/redirect11/9273079
and
https://gist.github.com/redirect11/9273043
These are the 200th job try.... and i don't remember what are the differences... but the error it's the same...
Appium server and jenkins started by the same user on the same machine... can some on help me pointing me in the right way?
A: Looking at:
[31mMessage: [0m[31morg.openqa.selenium.remote.UnreachableBrowserException: Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure.
I think I have seen that when the connection to Appium is failing. Try to just leave appium running without jenkins kicking it off to see if that solves the problem. With so many working parts try to isolate which is giving the issue. Please comment on the next issue if you have one.
If you want appium to run when a test is triggered try to run it within the test itself. Then have it close the connection when the test finishes. Just make sure your tests waits a couple seconds before trying to connect since appium has a slight boot time
| |
doc_23536586
|
Can anyone help me out
PS : Here i have a stride of 2
A: I have found the solution , hope this might be help full to others as well . As it was difficult to match padding in torch and padding in keras with stride = 2
X = Input(shape = (10,10,3))
X1 = ZeroPadding2D(padding=(1,1), input_shape=(10, 10, 3), data_format="channels_last")(X)
conv1 = Conv2D(16, 3, padding = 'valid', strides = (2,2))(X1)
| |
doc_23536587
|
A: ccmake curses UI
sudo apt-get install cmake-curses-gui
cd build
ccmake ..
Then:
*
*edit your options
*hit c to update the cache
*q to exit
And now you can make again with the new variables.
Tested in Ubuntu 16.10, cmake 3.5.2.
A: If you're building the latest from source, this is a lot harder than anyone else here suggests. I finally found this that got it working:
First, download the source from: https://cmake.org/download/
More specifically for Ubuntu 14.04 or higher, 64 bit get:
https://cmake.org/files/v3.5/cmake-3.5.2.tar.gz
Download it to the following directory (or any directory you like!):
/opt/dev-tools-sources
Unzip it there, using GUI archive manager or $ tar -zxvf cmake-3.5.2.tar.gz
You should have now a folder like this: /opt/dev-tools-sources/cmake-3.5.2
Go to this folder: $ cd /opt/dev-tools-sources/cmake-3.5.2
Install openssl to allow CMAKE have access to ssl protected websites
if it needs to download extra files $ sudo apt install openssl libssl-dev
Edit the bootstrap file and change the line:
cmake_options="-DCMAKE_BOOTSTRAP=1"
To this cmake_options="-DCMAKE_BOOTSTRAP=1 -DCMAKE_USE_OPENSSL=ON"
If you want cmake-gui, you will need qt4 libs an ncurses
$ sudo apt install libqt4-dev qt4-dev-tools libncurses5-dev
Run the configuration (you need to have gcc and g++ 4.7 or higher
installed. I recommend 4.8.4 or higher actually!)
$ ./configure --qt-gui
Make sure in the generated CMakeCache.txt, GUI is set to TRUE, open CMakeCache.txt with any editor and check the following line:
BUILD_QtDialog:BOOL=ON
If it was OFF or 0, make it ON or 1
It is time to build executables and libraries from source: $ make -j2
Now, install: $ sudo make install
Confirm you also got GUI version with $ cmake-gui
A: Update:
As of CMake 3.7.2, cmake-gui is still not built by default, but can easily be added to the build by specifying one additional flag. Qt is still required, I am using 4.8 but I'm sure other versions will work fine.
Download the source from the website, extract to a directory of your choosing, then run the following at the commmand line:
*
*./bootstrap --qt-gui
*gmake
*gmake install (optional - don't forget sudo if you need it)
Hey presto! cmake-gui is now present in the bin directory along with the other tools.
Note: if the build process fails in some way, just check the error message and work with it! There are too many pre-requisites and variables, attempting to detail them all would make the post tl;dr and would be out of date before being submitted (see one of the other posts for an example of this).
Basic installation for CMake
Under linux it comes with the default installation from the cmake website (at least for version 3.5.1)
It is installed in the same place as cmake, which on my machine is:
/usr/local/bin/cmake-gui
I built my cmake from source and by default, cmake-gui does not get built. To add as a target, the following variable must be set:
BUILD_QtDialog
eg. SET(BUILD_QtDialog TRUE) should do it
Note: cmake-gui is based on Qt so you must have Qt installed if you want to build it.
A: cmake is documented (type man cmake and see also cmake.org) as being a command, so it should not have any GUI interface:
DESCRIPTION
The "cmake" executable is the CMake command-line interface. It may be
used to configure projects in scripts. Project configuration settings
may be specified on the command line with the -D option.
And it is just generating a Makefile (to be used by the make command). I don't understand what kind of GUI are you expecting.
On Debian and derivatives like Ubuntu, you might install the cmake-gui or cmake-qt-gui package then run the cmake-gui command.
And make is often running GCC. Try make -p to understand the default rules of GNU make... So read documentation of GNU make and of GCC (and probably of GDB).
A: For Ubuntu (and I guess for more linux versions):
sudo apt-get install cmake-qt-gui
Can be started after installation as cmake-gui or by using the ubuntu GUI (just type cmake and it will show the typical cmake-gui-icon)
A: I also faced a similar problem. I did something like:
*
*Open https://apps.ubuntu.com/cat/applications/precise/cmake-qt-gui/ and click available on the software centre.
*new window opens and click install
*write cmake-gui on terminal
and it solved my problem.
| |
doc_23536588
|
try
{
IPAddress ip = IPAddress.Parse(deviceAddress);
_tcpClient.Connect(ip, devicePort);
}catch(SocketException ex)
{
Console.WriteLine(ex);
}
When mobile data is turned off on the smartphone, the connection with the sensor is correct, the data is read.
The problem occurs when Cellular data is turned on. Then the connection is not successful. The exception thrown is:
System.Net.Sockets.SocketException (0x80004005): Connection timed out
at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP) [0x000b0] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/System/System.Net.Sockets/Socket.cs:892
at System.Net.Sockets.TcpClient.Connect (System.Net.IPEndPoint remoteEP) [0x0002d] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/referencesource/System/net/System/Net/Sockets/TCPClient.cs:346
at System.Net.Sockets.TcpClient.Connect (System.Net.IPAddress address, System.Int32 port) [0x00048] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/referencesource/System/net/System/Net/Sockets/TCPClient.cs:329
Is anybody have similar issue?
| |
doc_23536589
|
first issue is that the stop button doesn't work and i tried many code but nothing works
then each time i click on reset instead of going from 1 to 2 to 3 it goes 1 then
2 and 4 then 8 and so on
i tried looking with the interval but the first time it goes right
so i checked the reset function
var timer = document.querySelector("#timer");
var start = document.querySelector("#start");
var pause = document.querySelector("#stop");
var stop = document.querySelector("#stop");
var time_stopped = true;
var hours = 0;
var minutes = 0;
var seconds = 0;
function start_timer() {
if (time_stopped == true){
time_stopped = false;
cycle();
}
console.log("timer started!");
pause.style.display = "unset";
}
function stop_timer() {
if (stop_timer == false) {
stop_timer = true;
}
console.log("time stopped!");
pause.style.display = "none";
}
function restart_timer() {
timer.innerHTML = "00 00 00";
hours = 0;
minutes = 0;
seconds = 0;
time_stopped = true;
cycle();
}
function cycle() {
if (time_stopped == false) {
hours = parseInt(hours);
minutes = parseInt(minutes);
seconds = parseInt(seconds);
seconds = seconds + 1;
if (seconds == 60) {
minutes += 1;
seconds = 0;
}
if (minutes == 60) {
hours += 1;
minutes = 0;
}
if (seconds < 10 || seconds == 0) {
seconds = "0" + seconds;
}
if (minutes < 10 || minutes == 0) {
minutes = "0" + minutes;
}
if (hours < 10 || hours == 0) {
hours = "0" + hours;
}
timer.innerHTML = `${hours}:${minutes}:${seconds}`;
setInterval(cycle,1000);
}
}
and here's the html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>stopwatch (timer)</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div>
<div id="timer">
00:00:00
</div>
<ul>
<button id="start" onclick="start_timer()">start</button>
<button id="stop" onclick="stop_timer()">stop</button>
<button id="restart" onclick="restart_timer()">restart</button>
</ul>
</div>
<script src="script.js"></script>
</body>
</html>
A: The function setInterval doesn't just setup one timeout event, it sets up a repeating schedule of them.
So, as noted in the comments, every time you call cycle() you are creating an additional timer schedule, causing them to effectively double every interval.
To fix this you need to change to setTimeout instead of set Interval, or alternatively call clearInterval before you make a new setInterval call (or just do neither, as setInterval is already doing the repeating for you). This doc explains all of these functions: https://javascript.info/settimeout-setinterval
| |
doc_23536590
|
class Class1 {
public:
Class1() {};
~Class1() {};
protected:
std::string name;
}
class Class2 : public Class1
{
public:
Class2() : number(id_generator++) {
name = "My-name"; // (1) want to access field inherited from Parent
};
private:
const unsigned int number;
static unsigned int id_generator;
}
a compiler complains for (1): 'name' was not declared in this scope. What is wrong? It look simple but i don't see it.
EDIT1: just i realized that the error is actually pronounced only here (here link to the code):
#include <string>
template<int dim>
class Class1 {
public:
Class1() {};
~Class1() {};
protected:
std::string name;
};
template<int dim>
class Class2 : public Class1<dim>
{
public:
Class2() : number(id_generator++) {
name = "My-name"; // (1) want to access field inherited from Parent
};
private:
const unsigned int number;
static unsigned int id_generator;
};
int main() {}
so apparently i mess up something with templates. Sorry, for not writing it first place.
A: In a template, for unqualified names that refer to members inherited from a base class, you should use the explicit syntax by dereferencing this:
Class2() : number(id_generator++) {
this->name = "My-name"; // (1) want to access field inherited from Parent
// ^^^^^^
};
Or, alternatively, you could qualify the name this way:
Class2() : number(id_generator++) {
Class1<dim>::name = "My-name";
// ^^^^^^^^^^^^^
};
Otherwise, the compiler will lookup name in the global namespace during the first phase of name lookup and, if not found, will issue an error.
A: Missing semicolons aside, the code is fine.
The only possible explanation is that Class1, as seen by the compiler, doesn't actually have the name member. Do you have multiple classes called Class1? Do you have multiple copies of the header file where Class1 is declared? Is it possible that you've forgotten to save the file before running the compiler?
| |
doc_23536591
|
However, if I have to slide the content from left to right, I have to click twice on left arrow button for the first time after that sliding left to right works with a single click.
Also, once I start sliding the content left to right, if I have to slide content from right to left, I have to double click the right arrow button twice for the first time.
Below is the code.
<head>
<title></title>
</head>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script type="text/javascript" src="js/jquery-1.8.1.min.js">
</script>
<script type="text/javascript" src="js/jquery.easing.1.3.js">
</script>
<!--script type="text/javascript" src="js/slidR.js"> </script-->
<body>
<div id="sliderBlock">
<div id="slide1" class="slide">
<img src="img/nmo.jpg" />
</div>
<div id="slide2" class="slide">
<img src="img/tys.jpg" />
</div>
<div id="slide3" class="slide">
<img src="img/ups.jpg" />
</div>
<div id="slide4" class="slide">
<img src="img/we.jpg" />
</div>
</div>
</body>
<script>
$(function () {
var count = $("#sliderBlock").children().length;
var slideWidth = $(".slide").outerWidth();
var slideHeight = $(".slide").outerHeight();
var totalWidth = count * slideWidth;
var easeFn = "swing";
var fs = 1;
var ls = count;
var currentSlide;
$("#sliderBlock").append("<div id='next'></div>")
$("#sliderBlock").append("<div id='prev'></div>")
$(".slide").wrapAll('<div id="allSlides">');
$("#allSlides").css({
"width": totalWidth,
"height": slideHeight
});
$("#sliderBlock").append("<ul id='pagination'>");
for (i = 1; i <= count; i++) {
$("#pagination").append("<li><a id='slide" + i + "'>" + i + "</a></li>")
}
$("#pagination li a#slide1").addClass("liveSlide");
var interval = 3000;
var timeInterval = setInterval(function () {
slidR()
}, interval);
$("#prev").on("click", slidR_L)
$("#next").on("click", slidR_R)
function slidR() {
// slidR_R();
// slidR_L();
}
var curSlide, curSlideNo, prevSlideNo, divReOrder;
divReOrder = 1;
function slidR_R() {
$("#allSlides").animate({
left: -slideWidth
}, 1000, function () {
$(".slide:first-child").clone().appendTo("#allSlides");
$(".slide:first-child").detach();
$("#allSlides").css('left', "0px");
});
}
function slidR_L() {
$("#allSlides").animate({
left: "0"
}, 1000, function () {
$(".slide:last-child").clone().prependTo("#allSlides");
$(".slide:last-child").detach();
$("#allSlides").css('left', -slideWidth);
});
}
});
</script>
A: Try with this one and see if helps:
<script>
function slidR_R() {
$("#allSlides").animate({
left: -slideWidth
}, 1000, function () {
$(".slide:first-child").clone().appendTo("#allSlides");
$(".slide:first-child").detach();
$("#allSlides").css('left', "0px");
});
}
function slidR_L() {
$("#allSlides").animate({
left: "0"
}, 1000, function () {
$(".slide:last-child").clone().prependTo("#allSlides");
$(".slide:last-child").detach();
$("#allSlides").css('left', -slideWidth);
});
}
$(function () {
var count = $("#sliderBlock").children().length;
var slideWidth = $(".slide").outerWidth();
var slideHeight = $(".slide").outerHeight();
var totalWidth = count * slideWidth;
var easeFn = "swing";
var fs = 1;
var ls = count;
var currentSlide;
$("#sliderBlock").append("<div id='next'></div>")
$("#sliderBlock").append("<div id='prev'></div>")
$(".slide").wrapAll('<div id="allSlides">');
$("#allSlides").css({
"width": totalWidth,
"height": slideHeight
});
$("#sliderBlock").append("<ul id='pagination'>");
for (i = 1; i <= count; i++) {
$("#pagination").append("<li><a id='slide" + i + "'>" + i + "</a></li>")
}
$("#pagination li a#slide1").addClass("liveSlide");
var interval = 3000;
var timeInterval = setInterval(function () {
slidR()
}, interval);
$("#sliderBlock").on("click", "#prev", slidR_L);
$("#sliderBlock").on("click", "#next", slidR_R);
var curSlide, curSlideNo, prevSlideNo, divReOrder;
divReOrder = 1;
});
</script>
| |
doc_23536592
|
Thank you so much.
A: The issue you're having is caused by the weighted edges in the graph. UCINET and the other programs make use of it automatically, but in igraph you need to specifically define it in the betweenness function. Add edge weight to your graph: E(g)$weight <- sum(ecount(g)).
Then you can call it in the function betweenness(g, weights = E(g)$weight).
This should resolve your issue and get your values to match up with the other programs.
| |
doc_23536593
|
I have 3 Features across 2 MSIs.
MSI 1
*
*Feature A
*Feature B
MSI 2
*
*Feature C
Users have the option to install A,B,AB,ABC or C.
To set the features as optional I have set the EnableFeatureSelection="yes" and set the PlanMsiFeature to Local/Absent depending on if the user wants to include them.
This is working for the 2 features in MSI 1, but not MSI 2. What am I missing?
Thanks
Bundle Code
<Chain>
<MsiPackage Id="1" Name="1.msi" SourceFile="1.msi" Vital="yes" Compressed="no" EnableFeatureSelection="yes"
DisplayName="1">
</MsiPackage>
<MsiPackage Id="2" Name="2.msi" SourceFile="2.msi" Vital="yes" Compressed="no" EnableFeatureSelection="yes"
DisplayName="2">
</MsiPackage>
</Chain>
BootstrapperApplication
PlanMsiFeature += SetupModel_PlanMsiFeature;
void SetupModel_PlanMsiFeature(object sender, PlanMsiFeatureEventArgs e)
{
switch (e.FeatureId)
{
case "FeatureA":
{
e.State = IncludeA ? FeatureState.Local : FeatureState.Absent;
return;
}
case "FeatureB":
{
e.State = IncludeB ? FeatureState.Local : FeatureState.Absent;
return;
}
case "FeatureC":
{
e.State = IncludeC ? FeatureState.Local : FeatureState.Absent;
return;
}
}
e.State = FeatureState.Local;
}
A: This took some trial and error. Mostly error.
Wix appears to require at least 1 feature in an MSI so I add an empty feature to both MSIs.
<Feature Id="blankFeature">
<Feature>
| |
doc_23536594
|
Then, How can i fix this problem? Please help me!!
A: Heroku flushes the filesystem to the latest commit. So you will have to use third-party plugins such as AWSBucket, etc.
A: With Heroku the filesystem is not persisted so you will lose media files occasionally. Use S3 or some other provider to store your user-uploaded media (also your static files if you want, otherwise use whitenoise). Django-storages makes it very easy.
| |
doc_23536595
|
A: I know it's pretty annoying but... You can't make a page on the actual blog in a plugin you make. you can however, make a shortcode like [contact-form] that will output the form. The user just needs to put that shortcode on a page and it will put the form there. Some reference for shortcodes can be found here: ShortCode API. But the main syntax for creating a shortcode is this:
//[foobar]
function foobar_func( $atts ){
return "foo and bar";
}
add_shortcode( 'foobar', 'foobar_func' );
Just put the form code inside the function and change the name. You don't need attributes though. For your case you would just need to do something like this:
function contact_form(){
//Code that process form
//Actual code that outputs the form
}
And there you go! Thanks!
Ethan Brouwer
| |
doc_23536596
|
to_update = models.Person.objects.select_for_update().get(pk=instance.pk)
e.g., in:
def UpdateAge(instance, new_age):
with transaction.atomic():
to_update = models.Person.objects.select_for_update().get(pk=instance.pk)
to_update.age = new_age
to_update.save()
A: The only way to shorten that would be to follow standard practice & import your model so do something like;
from myapp.models import Person
def UpdateAge(instance, new_age):
with transaction.atomic():
to_update = Person.objects.select_for_update().get(
pk=instance.pk
)
to_update.age = new_age
to_update.save()
Here are the docs on select_for_update
| |
doc_23536597
|
*
*How to set RPL into non storing mode from storing mode which is the default one? I'm trying with changing DAG mode in rpl-private.h but it seems it's not the correct way.
*Cooja Collect View works only with example simulation given in examples/rpl-collect and not in my custom simulation project. Is any setting required for it ?
A: This should do the trick:
#undef RPL_CONF_MOP
#define RPL_CONF_MOP RPL_MOP_NON_STORING /* Mode of operation*/
#undef UIP_CONF_MAX_ROUTES
#define UIP_CONF_MAX_ROUTES 0 /* Optional, but helps to save memory - no need for routes in the non-storing mode */
Leave comment if it does not work for any reasons.
| |
doc_23536598
|
<?php echo $form->labelEx($model,'emlevel'); ?>
<?php
echo $form->radioButtonList($model,'emlevel',
array('L'=>'Low','M'=>'Moderate','X'=>'Low Moderate', 'H'=>'High'),
array('separator' => " " ));
?>
<?php echo $form->error($model,'emlevel'); ?>
function chk()
{
// first I checked the value for emlevel to verify it get the value or not
//but it shows undefined
alert (document.forms["ConsultationNew"] ["ConsultationNew[enc_type]"].value);
if (document.forms["ConsultationNew"]["ConsultationNew[emlevel]"].value == null) {
alert ('choose one EMlevel'); return false;
}
}
I am not able to get value by document.getelement ....value. it shows undefined
A: You probably want to use CActiveForm. Clientside validation is configured as follows:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'login-form',
'enableAjaxValidation'=>false,
'enableClientValidation'=>true,
'clientOptions' => array (
'validateOnSubmit' => true,
'validateOnChange' => true,
'validateOnType' => true,
),
)); ?>
As you are working in Yii already, I would definitely use CActiveForm for client-side validation (and also for Ajax and server-side validation). It works like a charm. You must have better things to do than to reinvent the wheel in programming validation in Javascript.
| |
doc_23536599
|
1. Where's a good resource to learn Ajax? I've seen this site, but it doesn't contain much information:http://www.php-learn-it.com/tutorials/starting_with_php_and_ajax.html
2. Wheres a good resource to learn OOP? I've done all steps on this site:
http://www.killerphp.com/tutorials/object-oriented-php/ but it's from 2007.
*3 solved! *
3. And a question about the killerphp tutorial;
Why do I get this error:
Notice: Undefined variable: name in C:\xampp\htdocs\class_lib.php on line 11
Fatal error: Cannot access empty property in C:\xampp\htdocs\class_lib.php on line 11
with this code(index.php):
<?php
$william = new person("William N");
echo "<p>name: ". $william->get_name()."</p>";
?>
and this in class_lib.php:
class person {
var $name;
function __construct($persons_name)
{
$this->name = $persons_name;
}
public function get_name()
{
return $this->$name;
}
}
A: return $this->$name;
should be:
return $this->name;
A: try it like this:
class person {
protected $name;
public function __construct($persons_name)
{
$this->name = $persons_name;
}
public function get_name()
{
return $this->name;
}
Are you using PHP 5?
You should not use var anymore if so.
A: Since your 3rd question is answered already, as far as 2nd one goes I haven't read the book, but php.net as always gives you all the basics and even more with the examples that follow on almost each and every page. :)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.