id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_900
|
What's going on? Does someone know a fix? I tried already to cloning repository again too and still the same issue.
A: I managed to fix it, when installing i disabled some cache thing, and in phpstorm settings i chose ssh executable native from built-in. Not sure which one fixed it.
| |
doc_901
|
What is the proper way of handling this? Does Paperclip offer an option to automatically migrate data from old folders?
Thanks.
A: I had a similar dilemma. We were storing all our attachments in a certain path, and then business requirements changed and everything had to be moved and re-organized.
I'm surprised how little info there is on changing paperclip path and moving files. Maybe I'm missing the obvious?
Like Fernando I had to write a rake task. Here's what my code looks like (attachments model is Attachment, and the actual Paperclip::Attachment object is :file )
task :move_attachments_to_institution_folders => :environment do
attachments = Attachment.all
puts "== FOUND #{attachments.size} ATTACHMENTS =="
old_path_interpolation = APP_CONFIG[ 'paperclip_attachment_root' ] + "/:id_partition.:extension"
new_path_interpolation = APP_CONFIG[ 'paperclip_attachment_root' ] + "/:institution/reports/:id_:filename"
attachments.each do |attachment|
# the interpolate method of paperclip takes the symbol variables and evaluates them to proper path segments.
old_file_path = Paperclip::Interpolations.interpolate(old_path_interpolation, attachment.file, attachment.file.default_style) #see paperclip docs
puts "== Current file path: #{old_file_path}"
new_file_path = Paperclip::Interpolations.interpolate(new_path_interpolation, attachment.file, attachment.file.default_style)
if File.exists?(old_file_path)
if !File.exists?(new_file_path) #don't overwrite
FileUtils.mkdir_p(File.dirname(new_file_path)) #create folder if it doesn't exist
FileUtils.cp(old_file_path, new_file_path)
puts "==== File copied (^_^)"
else
puts "==== File already exists in new location."
end
else
puts "==== ! Real File Not Found ! "
end
end
The key thing for me was to have paperclip re-calculate the old path by using its default interpolations. From then it was just a matter of using standard FileUtils to copy the file over. The copy takes care of renaming.
P.S.
I'm on rails 2.3.8 branch, with paperclip -v 2.8.0
A: I ended up creating a small rake task to do this. Assuming that you have a model called User and your image file is called "image", place the following code in lib/tasks/change_users_folder.rb
desc "Change users folder"
task :change_users_folder => :environment do
@users = User.find :all
@users.each do |user|
unless user.image_file_name.blank?
filename = Rails.root.join('public', 'system', 'images', user.id.to_s, 'original', user.image_file_name)
if File.exists? filename
user.image = File.new filename
user.save
end
end
end
end
Them, run rake change_users_folder and wait.
Note that this won't delete old files. They will be kept at the original place and a copy will be created at the new folder. If everything went well, you can delete them later.
And for my future code, i will make sure i always set :path and :url when using paperclip :)
| |
doc_902
|
const getProfileImages = async () => {
for (let i = 0; i <= recommendedUsers.length; i++) {
console.log(recommendedUsers[0].userId)
const response = await UserService.downloadProfileImage(recommendedUsers[i].userId)
.then(res => res.blob())
.then(blob => {
const imgBlob = blob;
const reader = new FileReader();
reader.readAsDataURL(imgBlob);
reader.onloadend = () => {
const base64data = reader.result;
images[i] = base64data;
};
});
}
}
This method as is returns 'Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'userId')
at getProfileImages (SwipeCard.js:50:1)'
However, when I comment out the const response section:
const getProfileImages = async () => {
for (let i = 0; i <= recommendedUsers.length; i++) {
console.log(recommendedUsers[0].userId)
/*
const response = await UserService.downloadProfileImage(recommendedUsers[i].userId)
.then(res => res.blob())
.then(blob => {
const imgBlob = blob;
const reader = new FileReader();
reader.readAsDataURL(imgBlob);
reader.onloadend = () => {
const base64data = reader.result;
images[i] = base64data;
};
});
}
*/
}
}
The page renders fine (obviously without images) and the console.log(recommendedUsers[0].userId) statement prints out the user id's correctly.
If I try to console.log(recommendedUsers[i].userId) it suddenly has a meltdown again.
Are recommendedUsers[0] and recommendedUsers[i] where i = 0 not equivalent?
| |
doc_903
|
In the Programming guide of the MT7620 page 84 you can see that the GPIO base address is at 0x10000600 and the single registers have an offset of 4 Bytes.
MT7620 Programming Guide
Something like:
devmem 0x10000600
from the shell works absolutely fine but I cannot access it from inside of a c Programm.
Here is my code:
#define GPIOCHIP_0_ADDDRESS 0x10000600 // base address
#define GPIO_BLOCK 4
volatile unsigned long *gpiochip_0_Address;
int gpioSetup()
{
int m_mfd;
if ((m_mfd = open("/dev/mem", O_RDWR)) < 0)
{
printf("ERROR open\n");
return -1;
}
gpiochip_0_Address = (unsigned long*)mmap(NULL, GPIO_BLOCK, PROT_READ|PROT_WRITE, MAP_SHARED, m_mfd, GPIOCHIP_0_ADDDRESS);
close(m_mfd);
if(gpiochip_0_Address == MAP_FAILED)
{
printf("mmap() failed at phsical address:%d %s\n", GPIOCHIP_0_ADDDRESS, strerror(errno));
return -2;
}
return 0;
}
The Output I get is:
mmap() failed at phsical address:268436992 Invalid argument
What do I have to take care of? Do I have to make the memory accessable before? I´m running as root.
Thanks
EDIT
Peter Cordes is right, thank you so much.
Here is my final solution, if somebody finds a bug, please tell me ;)
#define GPIOCHIP_0_ADDDRESS 0x10000600 // base address
volatile unsigned long *gpiochip_0_Address;
int gpioSetup()
{
const size_t pagesize = sysconf(_SC_PAGE_SIZE);
unsigned long gpiochip_pageAddress = GPIOCHIP_0_ADDDRESS & ~(pagesize-1); //get the closest page-sized-address
const unsigned long gpiochip_0_offset = GPIOCHIP_0_ADDDRESS - gpiochip_pageAddress; //calculate the offset between the physical address and the page-sized-address
int m_mfd;
if ((m_mfd = open("/dev/mem", O_RDWR)) < 0)
{
printf("ERROR open\n");
return -1;
}
page_virtual_start_Address = (unsigned long*)mmap(NULL, pagesize, PROT_READ|PROT_WRITE, MAP_SHARED, m_mfd, gpiochip_pageAddress);
close(m_mfd);
if(page_virtual_start_Address == MAP_FAILED)
{
printf("ERROR mmap\n");
printf("mmap() failed at phsical address:%d %d\n", GPIOCHIP_0_ADDDRESS, strerror(errno));
return -2;
}
gpiochip_0_Address = page_virtual_start_Address + (gpiochip_0_offset/sizeof(long));
return 0;
}
A: mmap's file offset argument has to be page-aligned, and that's one of the documented reasons for mmap to fail with EINVAL.
0x10000600 is not a multiple of 4k, or even 1k, so that's almost certainly your problem. I don't think any systems have pages as small as 512B.
mmap a whole page that includes the address you want, and access the MMIO registers at an offset within that page.
Either hard-code it, or maybe do something like GPIOCHIP_0_ADDDRESS & ~(page_size-1) to round down an address to a page-aligned boundary. You should be able to do something that gets the page size as a compile-time constant so it still compiles efficiently.
| |
doc_904
|
I have two Follower ANEs: Leader ANE is finding the first one through reflection with no issues.
The second one however, is giving me an InvocationTargetException whenever I call invoke() method. Does that mean that there was an exception occurring inside Follower ANE?
Has someone had or seen this use case before?
| |
doc_905
|
I've created THREE.Group() that contains various THREE.Pointcloud(geometry, material). One of the Points is composed of THREE.BufferGeometry() and THREE.ShaderMaterial().
When I add a colour attribute to a BufferGeometry, only only red (1,0,0), white (1,1,1), or yellow (1,1,0) seem to work. This image is when I set the colour to (1,0,0). This image is when I set the colour to blue (0,0,1).
My question is, how do I resolve this? Is the issue in the shaders? Is the issue with how I build the BufferGeometry? Is it a bug? Thanks.
My shaders:
var vShader = `uniform float size;
varying vec3 vColor;
void main() {
vColor = color;
vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
gl_PointSize = size * ( size / (length(mvPosition.xyz) + 0.00001) );
gl_Position = projectionMatrix * mvPosition;
}`
var fShader = `varying vec3 vColor;
uniform sampler2D sprite;
void main() {
gl_FragColor = vec4(vColor, 1.0 ) * texture2D( sprite, gl_PointCoord );
if (gl_FragColor.x < 0.2) discard;
}`
My material:
var materialForBuffers = new THREE.ShaderMaterial( {
uniforms: {
size: { type: 'f', value: this.pointSize},
sprite: { type: 't', value: THREE.ImageUtils.loadTexture("../data/white.png") },
},
vertexShader: vShader,
fragmentShader: fShader,
transparent: true,
vertexColors: true,
});
How the color is added:
const colors = new Float32Array( [ 1.0, 0.0, 0.0 ] );
geometryForBuffers.addAttribute('color', new THREE.BufferAttribute( colors, 3 ));
Link to code
A: It looks like you may already be using parts of that sample code but if not, please refer to https://github.com/petrbroz/forge-point-clouds/blob/develop/public/scripts/extensions/pointcloud.js (live demo https://forge-point-clouds.autodesk.io). This sample code uses the color geometry attribute already to specify colors of individual points.
| |
doc_906
|
Thanks in advance.
A: While doing resizing the columns if you decrease it to minimum, there will be white space at right.
Following are some point that you can take care of
*
*Give the grid column width in percentage.
*You can set it to autofit, based on the data in the grid, the column width will be set automatically.
*you can handle resize event and set to autofit.
var grid = $("#GridName").data("kendoGrid");
for (var i = 0; i < grid.columns.length; i++) {
grid.autoFitColumn(i);
}
Hope it helps you
| |
doc_907
|
*
*------> tMap ------> tOracleOutput
I am facing an error the column name exists when creating the new destination table. the column name is written correctly; however, the db column name takes the old one. Your help is really appreciated.
| |
doc_908
|
nm = NearMiss(random_state=42)
X_bal,Y_bal = nm.fit_sample(x,y)
But I am getting an unexpected error:
TypeError: __init__() got an unexpected keyword argument 'random_state'
How to fix this problem?
Thanks!
A: we first import:
from imblearn import under_sampling as us
us.NearMiss(
*,
sampling_strategy='auto',
version=1,
n_neighbors=3,
n_neighbors_ver3=3,
n_jobs=None,
)
you have use this keyword/parameters in the .__init__()
so to your problem:
NearMiss custuctor dont take random_state as a parameter wich gives you that the init dont expect that as a keyword.
| |
doc_909
|
|toto/a |toto/b |titi/a |titi/b |
After modifying column headers with jquery in table post execution, I have these new headers displayed:
|toto |titi |
|a |b |a |b |
But when I use the export button or the table.queryState.exportData function, the exported file still with |toto/a | toto/b | titi/a | titi/b| header.
Any idea for having the displayed columns in the export file?
| |
doc_910
|
function url_vars() {
$bank = strtolower($_GET['bank']);
$bank = str_replace(',', '', $bank);
$bank = str_replace(' ', '_', $bank);
$type = $_GET['type'];
$term = $_GET['term'];
return array(
bank => $bank,
type => $type,
term => $term,
term_yrs => $term / 12
);
}
I tried to target one value from another function with $bank = url_vars()['bank']; but this seems to be incorrect as it is not working. How can I target a single value from this array? What is the correct way to do that?
A: In PHP 5.5 and higher, the url_vars()['bank'] syntax should work. However in lower version, you'll just have to assign the function return to a variable and then access the element from that.
$array = url_vars();
$bank = $array["bank"];
A: $vars = url_vars();
$bank = $vars['bank'];
| |
doc_911
|
"You need four JARs: the Lucene JAR, the queryparser JAR, the common analysis JAR, and the Lucene demo JAR.
Put all four of these files in your Java CLASSPATH.
I am trying to set classpath variable by entering the following variable value in classpath environment variable
"F:\Academic\KAU_ResearchGroups\PlagiarismDetection\Lucene\lucene-5.0.0\core; F:\Academic\KAU_ResearchGroups\PlagiarismDetection\Lucene\lucene-5.0.0\queryparser; F:\Academic\KAU_ResearchGroups\PlagiarismDetection\Lucene\lucene-5.0.0\analysis\common; F:\Academic\KAU_ResearchGroups\PlagiarismDetection\Lucene\lucene-5.0.0\demo;
but whenever I run the following command:
java org.apache.lucene.demo.IndexFiles -docs {path-to-lucene}/src
I get the error message "Error: Could not find or load main class org.apache.lucene.IndexFiles".
How can I sort out this problem
A: Looks like what you've added to the classpath isn't correct. Either add the jars directly, as in the instructions of the IndexFiles demo:
F:\Academic\KAU_ResearchGroups\PlagiarismDetection\Lucene\lucene-5.0.0\core\lucene-core-5.0.0.jar; ...
Or add the whole directory with a wildcard (see Setting multiple jars in java classpath):
F:\Academic\KAU_ResearchGroups\PlagiarismDetection\Lucene\lucene-5.0.0\core\*; ...
A: You should never trust them, upload previous versions, When I worked with Lucene I always had this type of errors so I uploaded all lucen versions from the first one till the last(lucen1.9, lucene 2......, Lucene 3.3, lucene 4) and I added them as jars and till now I don't know which one had resolved the problem ;)
don't worry about the difference between the declaration of functions when you use them, you can use the version like this
Query q = new QueryParser(Version.LUCENE_40, "title", analyzer).parse(querystr);
good luck
| |
doc_912
|
I'm sure its because the localID that gets pushed into the globalQ is different than the one that gets pushed in the local (directional) queue.
So this line "if ((localID == northQ.front()) && (localID == globalQ.front()))"
is never satisfied.
Reason I am introducing "usleep(getrand(100000, 3000000));" is because I want to add some randomness to the cars' speeds. I know it might be a bit confusing. But the major point is the program runs without the sleep command. But when I introduce it, nothing happens... Some starvation I guess.
EDIT: The main 4 functions are the same thing. Just different queue names.
EDIT2: The program works if I sleep for a certain amount of time. It doesn't work when that time is a random number in some interval that I specify.
The code:
// Instructions
// Change the CARS and RUN_TIME variable to the desired values.
// Compile in command line using: g++ -pthread Intelligent_Traffic_Light_System.cpp -o run.exe
// Run in command line by using: ./run.exe
#include <iostream>
#include <pthread.h>
#include <queue>
#include <cstdlib> //for rand()
#include <unistd.h> // for usleep()
#include <ctime> //for clock(), clock_t, CLOCKS_PER_SEC
#define CARS 10 // # cars coming from each direction. 40 cars total
#define RUN_TIME 125 // 125 seconds (5 seconds longer than it should take to run)
using namespace std;
int globalID; // global ID for each car arriving at the intersection
// a queue for each direction.
queue<int> northQ;
queue<int> eastQ;
queue<int> southQ;
queue<int> westQ;
queue<int> globalQ;
pthread_t threadID;
// a lock for each queue/direction.
pthread_mutex_t northLock;
pthread_mutex_t eastLock;
pthread_mutex_t southLock;
pthread_mutex_t westLock;
pthread_mutex_t globalQlock;
pthread_mutex_t globalIDLock; // lock for changing the globalid (i.e. car id)
pthread_mutex_t intersectionLock; // lock for one car passing through the intersection
int getrand(int min,int max) //random number generator between min and max
{
return(rand()%(max-min)+min);
}
void init()
{
globalID = 1; //first car will have ID = 1
pthread_mutex_init(&northLock, NULL);
pthread_mutex_init(&eastLock, NULL);
pthread_mutex_init(&southLock, NULL);
pthread_mutex_init(&westLock, NULL);
pthread_mutex_init(&globalIDLock, NULL);
pthread_mutex_init(&intersectionLock, NULL);
pthread_mutex_init(&globalQlock, NULL);
}
// Now will test to create an intersection with only 1 direction. North
void *north(void *null)
{
int localID;
double duration; //for checking how long a car will be waiting at the front of its lane
clock_t start; //variable will be used to calculate wait time
pthread_mutex_lock(&northLock); // locking the queue
pthread_mutex_lock(&globalIDLock); // locking globalIDLock mutex in order to update globalID
localID = globalID++; // update globalID after reserving that ID for a car in north lane
pthread_mutex_unlock(&globalIDLock);
northQ.push(localID); // pushing the local car into northQ.
pthread_mutex_unlock(&northLock);
//usleep(getrand(100000, 3000000)); //lets say it takes somewhere between 1/10th of a second and 3 seconds to get to the intersection.
start = clock(); // Now the car has arrived at intersection. Let's start the timer.
pthread_mutex_lock(&globalQlock);
globalQ.push(localID);//pushing car into global (intersection Q)
//cout << localID <<endl;
pthread_mutex_unlock(&globalQlock);
while(1) //Checking cars properties here
{
if ((localID == northQ.front()) && (localID == globalQ.front())) // Current Car is in the front of the lane... Lets Proceed
{
break;
}
else //Current car is not in front on its lane. Lets wait
{
usleep(10); // sleep for 10 microsecond to allow for other cars to proceed if they must
continue;
}
}
// Car is in the front so let's proceed to allow it to pass through intersection.
pthread_mutex_lock(&intersectionLock); // need to lock the intersection. Function call will block until mutex is available
duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
northQ.pop();
globalQ.pop();
cout << "Car from NORTH lane with ID: " << localID << " ENTERING the intersection." << endl;
cout << "It has been waiting at the light for: "<< duration<<" seconds."<<endl;
sleep(3);
cout << "Car from NORTH lane with ID: " << localID << " LEAVING the intersection." << endl<<endl;
pthread_mutex_unlock(&intersectionLock); // give other cars a chance to pass
}
void *east(void *null)
{
int localID;
double duration;
clock_t start;
pthread_mutex_lock(&eastLock); // locking the queue
pthread_mutex_lock(&globalIDLock); // locking globalIDLock mutex in order to update globalID
localID = globalID++; // update globalID after reserving that ID for a car in north lane
pthread_mutex_unlock(&globalIDLock);
eastQ.push(localID); // pushing the local car into northQ.
pthread_mutex_unlock(&eastLock);
//usleep(getrand(100000, 3000000)); //lets say it take 1/10th of a second to get to the intersection.
start = clock();
pthread_mutex_lock(&globalQlock);
globalQ.push(localID);//pushing car into global queue (i.e. intersection queue)
pthread_mutex_unlock(&globalQlock);
while(1) //Checking cars properties here
{
if ((localID == eastQ.front()) && (localID == globalQ.front())) // Current Car is in the front of the lane... Lets Proceed
{
break;
}
else //Current car is not in front on its lane. Lets wait
{
usleep(10); // sleep for 10 microsecond to allow for other cars to proceed if they must
continue;
}
}
// Car is in the front so let's proceed to allow it to pass through intersection.
pthread_mutex_lock(&intersectionLock); // need to lock the intersection. Function call will block until mutex is available
duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
eastQ.pop();
globalQ.pop();
cout << "Car from EAST lane with ID: " << localID << " ENTERING the intersection." << endl;
cout << "It has been waiting at the light for: "<<duration<<" seconds."<<endl;
sleep(3);
cout << "Car from EAST lane with ID: " << localID << " LEAVING the intersection." << endl <<endl;
pthread_mutex_unlock(&intersectionLock); // give other cars a chance to pass
}
void *south(void *null)
{
int localID;
double duration;
clock_t start;
pthread_mutex_lock (&southLock); // locking the queue
pthread_mutex_lock (&globalIDLock); // locking globalIDLock mutex in order to update globalID
localID = globalID++; // update globalID after reserving that ID for a car in north lane
pthread_mutex_unlock (&globalIDLock);
southQ.push(localID); // pushing the local car into northQ.
pthread_mutex_unlock (&southLock);
//usleep(getrand(100000, 3000000)); //lets say it take 1/10th of a second to get to the intersection.
start = clock();
pthread_mutex_lock(&globalQlock);
globalQ.push(localID);//pushing car into global (intersection Q)
pthread_mutex_unlock(&globalQlock);
while(1) //Checking cars properties here
{
if ((localID == southQ.front()) && (localID == globalQ.front())) // Current Car is in the front of the lane... Lets Proceed
{
break;
}
else //Current car is not in front on its lane. Lets wait
{
usleep(10); // sleep for 10 microsecond to allow for other cars to proceed if they must
continue;
}
}
// Car is in the front so let's proceed to allow it to pass through intersection.
pthread_mutex_lock(&intersectionLock); // need to lock the intersection. Function call will block until mutex is available
duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
southQ.pop();
globalQ.pop();
cout << "Car from SOUTH lane with ID: " << localID << " ENTERING the intersection." << endl;
cout << "It has been waiting at the light for: "<<duration<< " seconds."<<endl;
sleep(3);
cout << "Car from SOUTH lane with ID: " << localID << " LEAVING the intersection." << endl<<endl;
pthread_mutex_unlock(&intersectionLock); // give other cars a chance to pass
}
void *west(void *null)
{
int localID;
double duration;
clock_t start;
pthread_mutex_lock (&westLock); // locking the queue
pthread_mutex_lock (&globalIDLock); // locking globalIDLock mutex in order to update globalID
localID = globalID++; // update globalID after reserving that ID for a car in north lane
pthread_mutex_unlock (&globalIDLock);
westQ.push(localID); // pushing the local car into northQ.
pthread_mutex_unlock (&westLock);
//usleep(getrand(100000, 3000000));
start = clock();
pthread_mutex_lock(&globalQlock);
globalQ.push(localID);//pushing car into global (intersection Q)
pthread_mutex_unlock(&globalQlock);
while(1) //Checking cars properties here
{
if ((localID == westQ.front()) && (localID == globalQ.front())) // Current Car is in the front of the lane... Lets Proceed
{
break;
}
else //Current car is not in front on its lane. Lets wait
{
usleep(10); // sleep for 10 microsecond to allow for other cars to proceed if they must
continue;
}
}
// Car is in the front so let's proceed to allow it to pass through intersection.
pthread_mutex_lock(&intersectionLock); // need to lock the intersection. Function call will block until mutex is available
duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
westQ.pop();
globalQ.pop();
cout << "Car from WEST lane with ID: " << localID << " ENTERING the intersection." << endl;
cout << "It has been waiting for: "<< duration <<" seconds."<< endl;
sleep(3);
cout << "Car from WEST lane with ID: " << localID << " LEAVING the intersection." << endl<<endl;
pthread_mutex_unlock(&intersectionLock); // give other cars a chance to pass
}
int main()
{
init();
for(int i = 0; i < CARS; i++) //first car will be car with ID 1; Last ID is 40
{
pthread_create (&threadID, NULL, north, NULL);
pthread_create (&threadID, NULL, east, NULL);
pthread_create (&threadID, NULL, south, NULL);
pthread_create (&threadID, NULL, west, NULL);
}
sleep(RUN_TIME); //sleep for sufficient times to allow for all threads to finish running.
cout << "Finished." << endl;
return 0;
}
A: It seems that the main thread exits before the "north"-"east" etc threads terminate:
*
*When I put the sleep(RUN_TIME) inside the main loop, the program starts working.
*The reason of the early termination is the (localID == globalQ.front()) not synchronized code located inside each "north"-"east" function. This code, as you have correctly mentioned, is never (almost) satisfied and causes to busy wait inside the while(1) loop.
| |
doc_913
|
schema: ->
departments:
type: "Checkboxes"
title: "Department(s)*"
options: (new CPP.Collections.Departments) # Return ALL departments
The model's 'department' field is filled with a collection of the same type containing a subset of these departments.
For example if the schema options is a collection containing departments [d1, d2, d3, d4], the @model.get('departments') could return a collection with [d1, d3]
However in my Backbone Form, all the checkboxes are blank, shouldn't those which refer to departments belonging to the model be checked?
A: The Checkboxes form element populates values based on model ids, not models. In other words @model.get('departments') is expected to return [1, 3].
Edit: Here is a JSFiddle that shows both a working and non-working version.
| |
doc_914
|
this.books = new Backbone.Model();
this.books.fetch({
async: false,
url: user.get('booklist').href
});
I know I can just set this.books = this.books.get('userBookList') but that seems too hacky. What needs to go in the first line to parse? I've tried the parse function, but it's never called. Sorry, I've never used fetch.
| |
doc_915
|
handleInputs({ target: { name, value } }) {
handleInputs is a function that gets called on the onChange event of textfields. It's called as
onChange={this.handleInputs}
I tried to output the value of "target" in console but it threw an error. While the value of "name" and "value" is the name of the input control and the value in the control respectively.
Can someone please explain the function signature?
A: This is object destructuring assignment syntax. We can pass the object to the function as argument where it will be unpacked based on the function argument (object keys) specified. In your case this.handleInputs this should be an object having the keys target: { name, value }. Inside the function we can directly access the key values.
You can understand the syntax better with the following example from mozilla docs. Also see this link for more details
function whois({displayName, fullName: {firstName: name}}) {
console.log(displayName + ' is ' + name);
}
var user = {
id: 42,
displayName: 'jdoe',
fullName: {
firstName: 'John',
lastName: 'Doe'
}
};
console.log('userId: ' + userId(user)); // "userId: 42"
whois(user); // "jdoe is John"
| |
doc_916
|
<div class="ht2_icon ht2left" style="background: url(icons/img4.png) no-repeat center;" onClick="popup('#newTeam')">
<span class="tooltip" onmouseover="tooltip.pop(this, 'New Team', {position:0})">
<img src="icons/img4hover.png"/>
</span>
</div>
I should have the tooltip and the other image working on mouse hover but it is not the case.
A: To see other image only on hover please use separate css definition for ht2_icon or ht2left:
.ht2left:hover { background: url(icons/img_hover.png) no-repeat center; }
For lunching multiple events please use bind (it is tagged jquery so this is jquery solution, but with other frameworks it will be very similar)
$( ".ht2left" ).bind( "hover", popup('#newTeam'));
$( ".ht2left" ).bind( "hover", method2('#newTeam'));
A: You should keep your HTML, CSS and JavaScript separate and bind your callbacks programmatically. Your "clean" HTML would look like this (I added the class popup-trigger):
<div class="ht2_icon ht2left popup-trigger">
<span class="tooltip">
<img src="icons/img4hover.png"/>
</span>
</div>
In JavaScript, your can then add multiple event listener to an element, please check this example and the following code:
tooltips[i].addEventListener('mouseover', popTooltip);
tooltips[i].addEventListener('mouseover', doSomethingElse);
If you are using jQuery, you should use the .on() function, it will execute the callback for all current and future elements that match the selector.
var $triggers = $(".popup-triggers");
$triggers.on("click", function() {
// do something
});
| |
doc_917
|
org.eclipse.jgit.api.errors.TransportException: git@github.***.com:EA/entity-matching.git: invalid private key: [B@47822527
at org.eclipse.jgit.api.LsRemoteCommand.execute(LsRemoteCommand.java:222)
at org.eclipse.jgit.api.LsRemoteCommand.call(LsRemoteCommand.java:161)
at org.eclipse.egit.core.op.ListRemoteOperation.run(ListRemoteOperation.java:116)
at org.eclipse.egit.ui.internal.clone.SourceBranchPage$8.run(SourceBranchPage.java:340)
at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:122)
Caused by: org.eclipse.jgit.errors.TransportException: git@github.***.com:EA/entity-matching.git: invalid privatekey: [B@47822527
at org.eclipse.jgit.transport.JschConfigSessionFactory.getSession(JschConfigSessionFactory.java:191)
at org.eclipse.jgit.transport.SshTransport.getSession(SshTransport.java:140)
at org.eclipse.jgit.transport.TransportGitSsh$SshFetchConnection.<init>(TransportGitSsh.java:280)
at org.eclipse.jgit.transport.TransportGitSsh.openFetch(TransportGitSsh.java:170)
at org.eclipse.jgit.api.LsRemoteCommand.execute(LsRemoteCommand.java:200)
... 4 more
Caused by: com.jcraft.jsch.JSchException: invalid privatekey: [B@47822527
at com.jcraft.jsch.KeyPair.load(KeyPair.java:664)
at com.jcraft.jsch.KeyPair.load(KeyPair.java:561)
at com.jcraft.jsch.IdentityFile.newInstance(IdentityFile.java:40)
at com.jcraft.jsch.JSch.addIdentity(JSch.java:407)
at com.jcraft.jsch.JSch.addIdentity(JSch.java:367)
at org.eclipse.jgit.transport.JschConfigSessionFactory.getJSch(JschConfigSessionFactory.java:399)
at org.eclipse.egit.core.EclipseSshSessionFactory.createSession(EclipseSshSessionFactory.java:53)
at org.eclipse.jgit.transport.JschConfigSessionFactory.createSession(JschConfigSessionFactory.java:208)
at org.eclipse.jgit.transport.JschConfigSessionFactory.getSession(JschConfigSessionFactory.java:138)
... 8 more
I am sure the URI is correct. My ~/.ssh/congif is
Host *
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/id_rsa
Can anybody help me on this please?
A: Make sure, in Window > Preferences: General > Network Connections > SSH2 in the tab General that Private keys contains id_rsa.
Since Eclipse 2018-12 (which contains JGit/EGit 5.2) you can try in Window > Preferences: Team > Git to switch the SSH client from JSch to Apache MINA sshd (see this video showing it).
A: This error would not occur with the EGit 5.3.0 (Feb. 2019)
In the last release we had introduced a new SSH client based on the Apache MINA sshd library as an alternative to the JSch-based client.
In EGit 5.3.0 the default settings are switched: by default, the Apache MINA implementation is used.
We plan to remove the old JSch SSH implementation completely in a future release of EGit.
A: If someone not able to update it to Jsch (Like I am not able to do it in Spring Tool Suite) You may have to generate a new keypair using the -m PEM option like this:
ssh-keygen -t rsa -m PEM
so it can be used by Jsch.
Reference -
http://answers.neotys.com/questions/2218589-error-configure-git-connection-neoload-using-ssh-protocol-public-private-key
| |
doc_918
|
already added the jar in the dependency project already import mport com.google.gson.Gson; but still get the error
Handler processing failed; nested exception is java.lang.NoClassDefFoundError: com/google/gson/Gson
Here is my Pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.samples</groupId>
<artifactId>Siged.modelo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<spring-framework.version>3.2.3.RELEASE</spring-framework.version>
<jstl.version>1.2</jstl.version>
<servlet.version>2.5</servlet.version>
<jsp.version>2.2</jsp.version>
<slf4j.version>1.7.5</slf4j.version>
<logback.version>1.0.13</logback.version>
<hibernate.version>4.2.1.Final</hibernate.version>
<junit.version>4.11</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.3.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zkbind</artifactId>
<version>7.0.3</version>
</dependency>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zul</artifactId>
<version>7.0.3</version>
</dependency>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zkplus</artifactId>
<version>7.0.3</version>
</dependency>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zhtml</artifactId>
<version>7.0.3</version>
</dependency>
<dependency>
<groupId>org.zkoss.common</groupId>
<artifactId>zcommon</artifactId>
<version>7.0.3</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.4</version>
</dependency>
</dependencies>
</project>
My Restful Service
@RequestMapping(value="/insert",method=RequestMethod.POST)
public @ResponseBody String insert(@RequestParam(value="rif", required=true) String rif,
@RequestParam(value="donations", required=true) String donations ){
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json_ = gson.toJson(donations);
System.out.println("--------------------------------");
System.out.println(json_);
return donations;enter image description hereject][1]
A: Add <scope>runtime</scope> to the Gson dependency
| |
doc_919
|
Thank you.
The parfor loop cannot run due to the way variable "M" is used
The parfor loop cannot run due to the way variable "T" is used
Explanation
MATLAB runs loops in parfor functions by dividing the loop iterations into groups, and then sending them to MATLAB workers where they run in parallel. For MATLAB to do this in a repeatable, reliable manner, it must be able to classify all the variables used in the loop. The code uses the indicated variable in a way that is incompatible with classification.
parfor i=1:size(x,1)
if (ind(index(i)) == Index1)
para=lsqcurvefit(F, [M(index(i)) T(index(i))], t, SS(ind(index(i)):end,i), [0 0], [MaxiM(index(i)) maxT],options);
elseif (ind(index(i)) == Index2)
para=lsqcurvefit(F, [M(index(i)) T(index(i))], t2, SS(ind(index(i)):end,i), [0 0], [MaxiM(index(i)) maxT],options);
end
end
A: You should reorganize M and T in order to use them in a parallel loop. This should work:
M = M(index);
T = T(index);
parfor i=1:size(x,1)
if (ind(index(i)) == Index1)
para = lsqcurvefit(F, [M(i) T(i)], t, SS(ind(index(i)):end,i), ...
[0 0], [MaxiM(index(i)) maxT], options);
elseif (ind(index(i)) == Index2)
para = lsqcurvefit(F, [M(i) T(i)], t2, SS(ind(index(i)):end,i), ...
[0 0], [MaxiM(index(i)) maxT], options);
end
end
However, if you need return of function lsqcurvefit - then I would agree with the comment by Kleist that your code is meaningless.
UPDATE:
You can try to do similar rearrangements to further increase performance:
M = M(index);
T = T(index);
ind = ind(index);
MaxiM = MaxiM(index);
parfor i=1:size(x,1)
if (ind(i) == Index1)
para = lsqcurvefit(F, [M(i) T(i)], t, SS(ind(i):end,i), ...
[0 0], [MaxiM(i) maxT], options);
elseif (ind(i) == Index2)
para = lsqcurvefit(F, [M(i) T(i)], t2, SS(ind(i):end,i), ...
[0 0], [MaxiM(i) maxT], options);
end
end
| |
doc_920
|
Why doesn't EF add an Index to the Discriminator field?
A: Not always. You can find some people talking about this here: https://github.com/aspnet/EntityFramework/issues/4030.
Now, if you judge that will be better to create an index, you can use the convention delivery in the nuget Package EntityFramework.DiscriminatorIndex as described here: https://bytenosso.blogspot.com.br/2016/10/entity-framework-discriminator-index.html
A: i dont know i got your question right or not but its the default behaviour of ef. In the TPH mapping scenario,all types in an inheritance hierarchy are mapped to a single table. A discriminator column is used to identify the type of each row. When creating your model with Code First, TPH is the default strategy for the types that participate in the inheritance hierarchy.
and you modify this behaviour using Fluent Api
modelBuilder.Entity<Course>()
.Map<Course>(m => m.Requires("Type").HasValue("Course"))
.Map<OnsiteCourse>(m => m.Requires("Type").HasValue("OnsiteCourse"));
| |
doc_921
|
What am I doing wrong?
Thanks.
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.survery-questions {
display: flex;
flex-direction: row;
}
.home-price-footer {
width: 25%;
height: 45px;
margin-bottom: 3em;
}
#input {
background: #ffffff;
border: 1px solid #eaeaea;
}
<html>
<head>
</head>
<body>
<div class="survery-questions">
<form action="">
<div class="price-form">
<input name="price-1" type="text" placeholder="price 1" class="home-price-footer" id="input" required>
</div>
<div class="phone-form">
<input name="price-2" type="text" placeholder="price 2" class="home-price-footer" id="input" required>
</div>
<div class="email-form">
<input type="price-3" placeholder="price 3" class="home-price-footer" id="input" required>
</div>
<div class="price-form">
<input name="price-4" type="text" placeholder="price 4" class="home-price-footer" id="input" required>
</div>
<div class="phone-form">
<input name="price-5" type="text" placeholder="price 5" class="home-price-footer" id="input" required>
</div>
<div class="email-form">
<input type="price-6" placeholder="price 6" class="home-price-footer" id="input" required>
</div>
<div class="price-form">
<input name="price-7" type="text" placeholder="price 7" class="home-price-footer" id="input" required>
</div>
<div class="phone-form">
<input name="price-8" type="text" placeholder="price 8" class="home-price-footer" id="input" required>
</div>
<div class="email-form">
<input type="price-9" placeholder="price 9" class="home-price-footer" id="input" required>
</div>
</form>
</div>
</form>
</div>
</body>
</html>
A: Keeping your html intact, A little modification was needed where you gave display:flex, basically the display:flex works for immediate children only and not the the sub-children so immediate child of .survey-questions was <form> and <div> are children to <form> hence I added form to your existing selector and gave an additional attribute flex-wrap:wrap to maintain rows and columns layout as you had expected.
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* just a little modification in this part */
.survery-questions form {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
form > div{
width: 33.3%;
}
.home-price-footer {
width: 25%;
height: 45px;
margin-bottom: 3em;
}
#input {
background: #ffffff;
border: 1px solid #eaeaea;
}
<html>
<head>
</head>
<body>
<div class="survery-questions">
<form action="">
<div class="price-form">
<input name="price-1" type="text" placeholder="price 1" class="home-price-footer" id="input" required>
</div>
<div class="phone-form">
<input name="price-2" type="text" placeholder="price 2" class="home-price-footer" id="input" required>
</div>
<div class="email-form">
<input type="price-3" placeholder="price 3" class="home-price-footer" id="input" required>
</div>
<div class="price-form">
<input name="price-4" type="text" placeholder="price 4" class="home-price-footer" id="input" required>
</div>
<div class="phone-form">
<input name="price-5" type="text" placeholder="price 5" class="home-price-footer" id="input" required>
</div>
<div class="email-form">
<input type="price-6" placeholder="price 6" class="home-price-footer" id="input" required>
</div>
<div class="price-form">
<input name="price-7" type="text" placeholder="price 7" class="home-price-footer" id="input" required>
</div>
<div class="phone-form">
<input name="price-8" type="text" placeholder="price 8" class="home-price-footer" id="input" required>
</div>
<div class="email-form">
<input type="price-9" placeholder="price 9" class="home-price-footer" id="input" required>
</div>
</form>
</div>
</body>
</html>
A: The <form> element is the only child of your flex container, and is therefore the only element being influenced by it. By moving it outside the flex container things come closer to behaving as you'd like.
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.survey-questions {
display: flex;
flex-direction: row;
flex-wrap: wrap; /* added */
}
.survey-questions > div {
width: 33.33%; /* added */
padding: 0 10px; /* added */
}
.home-price-footer {
width: 100%; /* updated */
height: 45px;
margin-bottom: 3em;
}
#input {
background: #ffffff;
border: 1px solid #eaeaea;
}
<form action="">
<div class="survey-questions">
<div class="price-form">
<input name="price-1" type="text" placeholder="price 1" class="home-price-footer" id="input" required>
</div>
<div class="phone-form">
<input name="price-2" type="text" placeholder="price 2" class="home-price-footer" id="input" required>
</div>
<div class="email-form">
<input type="price-3" placeholder="price 3" class="home-price-footer" id="input" required>
</div>
<div class="price-form">
<input name="price-4" type="text" placeholder="price 4" class="home-price-footer" id="input" required>
</div>
<div class="phone-form">
<input name="price-5" type="text" placeholder="price 5" class="home-price-footer" id="input" required>
</div>
<div class="email-form">
<input type="price-6" placeholder="price 6" class="home-price-footer" id="input" required>
</div>
<div class="price-form">
<input name="price-7" type="text" placeholder="price 7" class="home-price-footer" id="input" required>
</div>
<div class="phone-form">
<input name="price-8" type="text" placeholder="price 8" class="home-price-footer" id="input" required>
</div>
<div class="email-form">
<input type="price-9" placeholder="price 9" class="home-price-footer" id="input" required>
</div>
</div>
</form>
| |
doc_922
|
I have a service that reads from blob storage. I basically need to be sure that when my service is restarted, it will check if there is anything in blob to read and process before running normally.
I can't seem to find a method that checks if the blockblob is empty. I came up with a way to do this, but I would like to know if there is a more elegant way of doing this:
here is my solution, just check if you were able to download anything. Sure it works..
public bool IsBlobEmpty()
{
string text;
using (var memoryStream = new MemoryStream())
{
blockBlob.DownloadToStream(memoryStream);
text = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
if (text.Length > 0)
{
return false;
}
}
return true;
}
A: You can use the Azure Storage Blob APIs to get the metadata information of the blob and check for its size - https://msdn.microsoft.com/en-us/library/azure/dd179394.aspx
Response headers from the server contains a Content-Length property
x-ms-meta-Name: myblob.txt
x-ms-meta-DateUploaded: Sun, 23 Oct 2013 18:45:18 GMT
x-ms-blob-type: BlockBlob
x-ms-lease-status: unlocked
x-ms-lease-state: available
Content-Length: 11
Content-Type: text/plain; charset=UTF-8
Date: Sun, 23 Oct 2013 19:49:38 GMT
ETag: "0x8CAE97120C1FF22"
Accept-Ranges: bytes
x-ms-version: 2013-08-15
Last-Modified: Wed, 23 Oct 2013 19:49
Server: Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.
A: You want to check inside the container. The following code returns the names of the blobs inside the given container. You can tweak the way you want.
private readonly CloudBlobClient _blobClient;
public List<string> GetBlockBlobNames(string containerName,
string prefix = null)
{
var names = new List<string>();
var container = _blobClient.GetContainerReference(containerName.ToLower());
if (container.Exists())
{
IEnumerable<IListBlobItem> collection = container.ListBlobs(prefix, true);
// Loop over items within the container and output the length and URI.
foreach (IListBlobItem item in collection)
{
if (item is CloudBlockBlob)
{
var blob = (CloudBlockBlob) item;
names.Add(blob.Name);
}
else if (item is CloudPageBlob)
{
var pageBlob = (CloudPageBlob) item;
names.Add(pageBlob.Name);
}
else if (item is CloudBlobDirectory)
{
var directory = (CloudBlobDirectory) item;
}
}
}
return names;
}
| |
doc_923
|
I've tried pretty much all of the resources I can find on both SO and the full Phusion guide, the closest I can come is "The page you were looking for doesn't exist." The app itself runs fine when I run it with script/rails server, initalizing a new rails app to a different sub_dir runs fine, but it'll only let me use index.html, nothing else. So it looks like some kind of routing issue, but when I tried the "scope do" it falls over on "scope".
What's the actual recommended and suggested way to have multiple rails sites on sub uris?
Apache2 Configuration File
NameVirtualHost *:80
<VirtualHost *:80>
ServerName www.cybershrike.co.uk/
DocumentRoot /web/rails
<Directory /web/rails>
Allow from all
</Directory>
RailsBaseURI /test
<Directory /web/rails/test>
Options -MultiViews
</Directory>
</VirtualHost>
NameVirtualHost *:80
<VirtualHost *:80>
ServerName www.cybershrike.co.uk/
DocumentRoot /web/rails
<Directory /web/rails>
Allow from all
</Directory>
RailsBaseURI /kinu
RailsEnv development
SetEnv RAILS_RELATIVE_URL_ROOT "/kinu"
PassengerAppRoot /web/rails/kinu
<Directory /web/rails/kinu/public>
Options MultiViews Indexes FollowSymLinks
</Directory>
</VirtualHost>
A: Have you tried the proposed default passenger option?
RailsBaseURI /kinu
RailsEnv development
<Directory /web/rails/kinu/public>
Options -MultiViews
</Directory>
</VirtualHost>
Also you have to ensure, that file-permission allow the apache-server (ususally wwwuser) to access all files recursively including /web ?
And, just to cover all bases here: did you restart apache?
| |
doc_924
|
I read MUI docs and Chip API but it's too complicated for me..
A: You could make use of Chip's exported CSS classes
import Chip, { chipClasses } from "@mui/material/Chip";
import { styled } from "@mui/material/styles";
// ..
const CustomChip = styled(Chip)({
[`&.${chipClasses.filled}`]: {
backgroundColor: "red"
}
});
Codesandbox demo
| |
doc_925
|
[Serializable]
public class ToolParameterEdit
{
protected ToolParameterEdit()
{
Initialize();
}
public CustomObservableCollection<ToolClasses> Classes { get; set; }
private void Initialize()
{
Classes = new CustomObservableCollection<ToolClasses>
{
IsReadOnly = () => this.IsReadOnly
};
}
}
If I modify the class on
[Serializable]
public class ToolParameterEdit : ISerializable
{
protected ToolParameterEdit()
{
Initialize();
}
public CustomObservableCollection<ToolClasses> Classes { get; set; }
public CustomObservableCollection<ToolTwinTypes> TwinTypes { get; set; }
private void Initialize()
{
Classes = new CustomObservableCollection<ToolClasses>
{
IsReadOnly = () => this.IsReadOnly
};
TwinTypes = new CustomObservableCollection<ToolTwinTypes>
{
IsReadOnly = () => this.IsReadOnly
};
}
protected ToolParameterEdit(SerializationInfo info, StreamingContext context)
{
Classes = (CustomObservableCollection<ToolClasses>)info.GetValue("<Classes>k__BackingField", typeof(CustomObservableCollection<ToolClasses>));
TwinTypes = Misc.TryGetSerializedVariableValue(info, nameof(TwinTypes), () => new CustomObservableCollection<ToolTwinTypes>());
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue(nameof(Classes), Classes);
info.AddValue(nameof(TwinTypes), TwinTypes);
}
}
there is the issue when I deserialize the stream with first version of class, I receave an exception like this:
System.Runtime.Serialization.SerializationException HResult=0x8013150C
Message=Cannot get the member 'b_29_0'. Source=mscorlib
StackTrace: at
System.Reflection.MemberInfoSerializationHolder.GetRealObject(StreamingContext
context) in
f:\dd\ndp\clr\src\BCL\system\reflection\memberinfoserializationholder.cs:line
282 at
System.Runtime.Serialization.ObjectManager.ResolveObjectReference(ObjectHolder
holder) in
f:\dd\ndp\clr\src\BCL\system\runtime\serialization\objectmanager.cs:line
302 at System.Runtime.Serialization.ObjectManager.DoFixups() in
f:\dd\ndp\clr\src\BCL\system\runtime\serialization\objectmanager.cs:line
941 at
System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler
handler, _BinaryParser serParser, Boolean fCheck, Boolean
isCrossAppDomain, IMethodCallMessage methodCallMessage) in
f:\dd\ndp\clr\src\BCL\system\runtime\serialization\formatters\binary\binaryobjectreader.cs:line
179 at
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream
serializationStream, HeaderHandler handler, Boolean fCheck, Boolean
isCrossAppDomain, IMethodCallMessage methodCallMessage) in
f:\dd\ndp\clr\src\BCL\system\runtime\serialization\formatters\binary\binaryformatter.cs:line
199 at
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream
serializationStream) in
f:\dd\ndp\clr\src\BCL\system\runtime\serialization\formatters\binary\binaryformatter.cs:line
113 at
Biesse.PlantConfigurator.Core.Misc.DeserializeFromByteArray[T](Byte[]
bytes, SerializationBinder serializationBinder) in
C:\SeedXP\Interfacce-GITBranch\Sviluppo\Componenti\Biesse.PlantConfigurator.Core\Misc.cs:line
1137 at
Biesse.PlantConfigurator.Core.Misc.DeserializeFromByteArray[T](Byte[]
bytes) in
C:\SeedXP\Interfacce-GITBranch\Sviluppo\Componenti\Biesse.PlantConfigurator.Core\Misc.cs:line
1112 at Biesse.PlantConf.Plugin.ToolingRegistry.Plugin.Read(IDataOwner
owner, Boolean isDiff) in
C:\SeedXP\Interfacce-GITBranch\Sviluppo\PlantConfPlugins\Biesse.PlantConf.Plugin.ToolingRegistry\Plugin.Persistence.cs:line
58
I'm sure that the member 'b__29_0' is
IsReadOnly = () => this.IsReadOnly
I used the ISerializationSurrogate to solve the issue
public static T DeserializeFromByteArray<T>(byte[] bytes, SerializationBinder serializationBinder)
{
using (MemoryStream ms = new MemoryStream(bytes))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Binder = serializationBinder;
var surrogateSelector = new SurrogateSelector();
surrogateSelector.AddSurrogate(typeof(ToolParameterEdit), new StreamingContext (StreamingContextStates.All),
new ToolParameterEditSerializationSurrogate ());
formatter.SurrogateSelector = surrogateSelector;
return (T)formatter.Deserialize(ms);
}
}
However the surrogate to ToolParameterEdit not resolve the problem.
enter image description here
Any suggestion?
Thanks
| |
doc_926
|
Now when I run the same app on iPHone5, i see lots of space at the bottom below the matrix of buttons. I would like collection view to increase the vertical spacing between the cells.
Can some one guide me please?
A: Make UICollectionViewFlowLayout by math, for example:
CGRect mainRect = [[UIScreen mainScreen] bounds];
CGFloat mainWidth = mainRect.size.width;
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
flowLayout.minimumLineSpacing = mainWidth/10;
flowLayout.itemSize = CGSizeMake(mainWidth/4, mainWidth/4);
Then just assign because UICollectionViewFlowLayout : UICollectionViewLayout
self.collectionView.collectionViewLayout = flowLayout;
| |
doc_927
|
I have a C# Windows Forms application (let's call it App) which starts and manages a C++ high-performance executable (let's call it Compute).
So the process tree in the task manager looks like
_App.exe | CPU | Mem | Disk | Network |
|_Compute.exe | CPU | Mem | Disk | Network |
I want the App to run automatically at startup. So far I've tried putting it in the shell-startup directory (can be found by win+R search 'shell:startup') or adding it to the HKeyLocalUser startup part of the registry. I found those solutions on Stackoverflow here.
When testing it out, the App starts just as expected when you log-on or startup the machine. But Compute.exe does not start properly. The process tree looks like:
_App.exe | CPU | Mem | Disk | Network |
|_App.exe | - | - | - | - |
It looks like the app is being started as a subprocess of itself, and with no resources. Again - the UI of the parent App starts just fine, is interactable, etc. But it is never able to restart the Compute process - even if forced to by the App process.
I believe it has to do with who starts the App, and that that ownership transfers to the child process. It goes without saying that manually clicking the startup shortcut launches the App and child Compute process no problem.
Any thoughts on what I'm missing here? Thanks for the advice!
A: Okay so this was a learning experience. Thanks to Johnny-Mopp for setting me on the right track.
I was launching the Compute process using
startInfo.FileName = Directory.GetCurrentDirectory() + processName;
This works fine in seemingly all cases but the start-on-login case described.
There is another, more explicit option which starts Compute process from the parent-process App's directory like so:
startInfo.FileName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + processName;
This works in when starting the Compute process from the parent App on-startup, at-login. Phew.
| |
doc_928
|
Eclipse 3.5
I have a problem reading data from my 2nd activity that is called from the 1st activity using intent. I have androidmanifest.xml setup correctly.
My First Activity has the following code:
Intent myIntent = new Intent(MainMenu.this, Testmenu.class);
myIntent.putExtra("com.tweaktool.MyAge",40);
myIntent.putExtra("com.tweaktool.Enabled", false);
startActivity(myIntent);
My 2nd Activity has the following code:
Bundle bun = getIntent().getExtras();
int myAge = bun.getInt("MyAge");
boolean enabled = bun.getBoolean("Enabled");
When I look at the above code in 2nd Activity it lists the following:
enabled = false
myAge = 0
Why is this doing this??? Am I doing something simple wrong??
A: Have your tried
int myAge = bun.getInt("com.tweaktool.MyAge");?
A: You're putting data with one keys ("com.tweaktool.MyAge", "com.tweaktool.Enabled") and trying to get it with others ("MyAge", "Enabled") -- the bundle then just returns you defaults (0, false). To get what you've put, use the keys you've used.
| |
doc_929
|
I have 2 repos, one is public, and the other is under company's Github Enterprise. Well I just cloned an HTTPs repo link from enterprise one and that went ok, which normally does not require any credentials.
However, when I realized I can also push, I started wondering where the credentials were stored. I checked .git/config
remote "origin"]
url = https://mygithub.blablacompany.com/blablaUsername/blabla.git
fetch = +refs/heads/*:refs/remotes/origin/*
Then I checked git config --list , lists bunch of other repo usernames and also:
remote.origin.url=https://mygithub.blablacompany.com/blablaUsername/blabla.git
remote.origin.fetch=+refs/heads/*:refs
branch.master.remote=origin
branch.master.merge=refs/heads/master
Then I checked whether ./git-credentials exist in home folder. Nope it does not. I searched for it all over the local drive, does not exist.
Then I checked whether git credentials manager for windows exist:
> git credential-manager version
> Git Credential Manager for Windows version 1.6.1
Ok so I assume it stored in Windows Credentials. But when I go to User credentials I see no records, nothing about git.
I tried running git config credential.helper which returns:
!github --credentials
So I assume everything after the exclamation mark is a shell command. Okay, so I tried checking the global config under /Users/Me:
There is one, but it is entirely for another, non-enterprise repo.
So how am I even able to push to this repo? How can I trace where the password/ssh key is stored?
A: You can view all of your Git settings, the files, and locations of the files with,
git config --list --show-origin
| |
doc_930
|
"-Dcom.sun.management.jmxremote=true
-Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Djava.net.preferIPv4Stack=true -Dcom.sun.management.jmxremote.port=0 org.apache.spark.deploy.SparkSubmit --conf
spark.metrics.conf=./metrics.properties --conf
spark.driver.extraJavaOptions=-Dcom.sun.management.jmxremote=true
-Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Djava.net.preferIPv4Stack=true -Dcom.sun.management.jmxremote.port=0`"
I can only see metrics related to JVM and Kafka (in my case spark in a producer for Kafka) for the executors, when I connect through JConsole. I am unable to see metrics related to spark for the executors. Is there anything that I am missing ?
Note: I can see JVM, Kafka and spark related metrics for the 'driver', when connected through JConsole.
| |
doc_931
|
<script type="text/javascript">
(function($) {
jQuery(document).ready(function(){
$(".inline").colorbox({inline:true, width:"50%"});
});
})(jQuery);
</script>
<p><a class='inline' href="#inline_content">Gift Wrapping</a></p>
<div style='display:none'>
<div id="inline_content">
<div class="product-options" id="product-options-wrapper">
<p style="font-size:15px;margin:0;font-weight: bold"><?php echo $this->__('Choose Your Options') ?></p>
<?php echo $this->getChildHtml('', true, true);?>
<?php if ($this->hasRequiredOptions()):?>
<span style="color:red">   <?php echo $this->__('* Required Fields') ?></span>
<?php endif;?>
</div>
<script type="text/javascript">decorateGeneric($$('#product-options-wrapper dl'), ['last']);</script>
</div>
</div>
A: After fooling with this I found out I was working on the wrong file. It doesn't work using /app/design/frontend/default/default/template/catalog/product/view/options/wrapper.phtml. I had to go deeper and use /app/design/frontend/default/default/template/catalog/product/view/options/type/select.phtml.
Here's hlow I got it working:
<?php /* @var $this Mage_Catalog_Block_Product_View_Options_Type_Select */ ?>
<script type="text/javascript">
(function($) {
jQuery(document).ready(function(){
$('#lnkButton').click(function () {
$(this).colorbox.close();});
$(".inline").colorbox({inline:true});
$('#cboxClose').remove();
});
})(jQuery);
</script>
<p><a class='inline' href="#inline_content"><img src="<?php echo $this->getSkinUrl('images/gift-wrap-avalible.png'); ?>" width="190" height="32" /></a></p>
<div style='display:none'>
<div id="inline_content" style="float:left;width:400px">
<h1>Gift Wrapping</h1>
<div style="float:right;width:400px">
<img src="<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA); ?>wysiwyg/GiftsWrap/blue-papper.png" width="100" height="100" />
<img src="<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA); ?>wysiwyg/GiftsWrap/blue-peace-papper.png" width="100" height="100" />
<img src="<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA); ?>wysiwyg/GiftsWrap/blue-stars-papper.png" width="100" height="100" />
</div>
<?php $_option = $this->getOption() ?>
<dt><?php if (!$_option->getType() == Mage_Catalog_Model_Product_Option::OPTION_TYPE_RADIO): ?><label<?php if ($_option->getIsRequire()) echo ' class="required"' ?>><?php if ($_option->getIsRequire()) echo '<em>*</em>' ?><?php echo $this->htmlEscape($_option->getTitle()) ?></label><?php endif; ?></dt>
<div style="float: left;
width: 370px;
border: 1px solid red;
text-align: left;
margin-left: 20px;">
<dd<?php if ($_option->decoratedIsLast){?> class="last"<?php }?>>
<div class="input-box">
<?php echo $this->getValuesHtml() ?>
<?php if ($_option->getIsRequire()): ?>
<?php if ($_option->getType() == Mage_Catalog_Model_Product_Option::OPTION_TYPE_RADIO || $_option->getType() == Mage_Catalog_Model_Product_Option::OPTION_TYPE_CHECKBOX): ?>
<span id="options-<?php echo $_option->getId() ?>-container"></span>
<?php endif; ?>
<?php endif;?>
</div>
</dd>
</div>
<button id="lnkButton"><span><span><?php echo $this->__('Okay') ?></span></span></button>
</div>
</div>
Not styled prefect but it works to popup a window to select Gift Wrapping options that I have created in administration.
| |
doc_932
|
for x in [1,2,3,4,5]:
if search==x:
print('element is found')
break
else:
print('element is not found')
why the else statement is not executed here as we know that adding else suite after for loop ,it gets executed anyway
enter the element to search4
element is found
A: The else part to the for doesn't get executed anyway.
It gets executed only when the loop completes fully and normally without breaking.
search = 4
for x in [1,2,3,5]:
if search==x:
print('element is found')
break
else:
print('Element is not found (from if)')
else:
print('element is not found (from for)')
Output:
Element is not found (from if)
Element is not found (from if)
Element is not found (from if)
Element is not found (from if)
element is not found (from for)
A:
... we know that adding else suite after for loop, it gets executed anyway.
You may think that, most seasoned Python developers would not agree :-)
You misunderstand when the else is executed. Specifically, it is not executed when you break from the loop, which you are for the input value of 4.
See here for more detail, in particular, this bit:
A break statement executed in the first suite terminates the loop without executing the else clause’s suite.
A:
somehow I can feel what u want to do here, to achieve that u need to write as below instead!
search = int(input('enter the element to search\n'))
for x in [1,2,3,4,5]:
if search==x:
print('element is found')
break
if search!=x:
print('element is not found')
| |
doc_933
|
I want to allow fields editable when EDIT button clicked otherwise it should be readonly.
Code changes but doesn't works
<label for="txtstartdate"><?php echo __("Start Date")?> <span class="required">*</span></label>
<input id="txtstartdate" name="txtstartdate" type="text" class="formInputText" disabled="disabled" value="<?php echo $project->getstartDate()?>" disabled />
<br class="clear"/>
function disableWidgets(){
$('#addProject_start_date').attr('disabled','disabled');
$('#addProject_end_date').attr('disabled','disabled');
}
function enableWidgets(){
$('#addProject_start_date').removeAttr('disabled');
$('#addProject_end_date').removeAttr('disabled');
}
In which file i have to change . Any one could help me to achieve this?
| |
doc_934
|
{
"current":{
...
"name": " - Kraftwerk - It's More Fun to Compute ",
...
}
}
I would like to decode this string to display it in my view in order to transform the It's into It's.
I tried to decode it with the JavaScript function decodeURIComponent before updating the state but unfortunately it doesn't work. My view still shows It's.
Here is my component (simplified)
import React, {useState, useEffect} from "react";
import { View, StyleSheet, Text, ActivityIndicator } from "react-native"
const Metadata = props => {
const [track, setTrack] = useState({
name: "",
type: ""
});
const trackinfo = (data) => {
let trackName = decodeURIComponent(data['current']['name']);
let trackType = data['current']['type'];
setTrack({
name: trackName,
type: trackType
});
useEffect(() => {
...
}, []);
return (
<View style={styles.container}>
<Text>
{track['name']}
</Text>
</View>
);
};
export default Metadata;
Any ideas why decodeURIComponent() as no effect ?
Thank you
A: You can use the decode function of html-entitites library.
import {decode} from 'html-entities';
let trackName = decode(data['current']['name']);
| |
doc_935
|
Remote Server returned '550 5.7.708 Service unavailable. Access denied, traffic not accepted from this IP. For more information please go to http://go.microsoft.com/fwlink/?LinkId=526653 AS(7171)
Sending emails manually through Outlook (web) from the organizer to the participants works fine.
The issue is intermittent. After changing the DNS server, everything worked fine for some time.
I checked https://protection.office.com/restrictedusers as suggested in the answers to similar posts, but this list is empty.
I also tried delisting the IP address (my own?) through https://sender.office.com/, but to no avail.
The tenant is linked to the Microsoft Developer Program and would allegedly have a 'bad reputation'. However, I don't understand how that would explain the fact that it sometimes works and sometimes doesn't when sending exactly the same API request and hence 'triggering' exactly the same emails...
A: I think the best way to overcome this would be to add a domain to your developer tenant as per the guidance here:
https://learn.microsoft.com/en-us/Exchange/mail-flow-best-practices/non-delivery-reports-in-exchange-online/fix-error-code-5-7-700-through-5-7-750#57750-client-blocked-from-sending-from-unregistered-domain
Add and validate all domains in Office 365 that you use to send email messages. For more information, see Add a domain to Office 365.
I'm not guaranteeing this will resolve it. You have to understand that those developer tenants are only meant for experimentation and so there are checks and balances to ensure they are used in a bad manor.
How many emails are you sending through this tenant?
A: Calendar events are sent out via email. Add the "Mail.Send" permission to you App Registration.
This solved it for me.
| |
doc_936
|
Thanks a lot.
| |
doc_937
|
I have no idea how to do this. If I delete that batch first, then exit cannot run. If I exit first, then I won't able to delete the batch.... Can I do this within the same batch file ? Thanks for any clue!!!
A: Use following command line as last line in your batch file:
del "%~f0" & exit
This line contains two commands on one line:
*
*DEL for deleting the batch file and
*EXIT for exiting command process.
The operator & results in execution of second command independent on result of first command. For more details about usage of multiple commands on one line see for example Single line with multiple commands using Windows batch file.
| |
doc_938
|
My first try was to make a round diamond, and then render a skybox by palcing a camera inside a diamond stone in 3dsmax and vray. This gave me a pretty looking skybox (full of faceted distortions, just like a diamond) but it didn't really look interesting once applied to a refractive/reflective lambert material in Three.js.
So I started looking into Custom Shaders, and I stumble upon this link
https://www.shadertoy.com/view/4sSGDc
Now my problem is that I can't find a way to make three.js compile the shader. Following other threads here, I found out how to setup some of the uniforms: (for example, Texture2D) but errors like this keep showing up:
THREE.WebGLShader: gl.getShaderInfoLog() ERROR: 0:163: 'textureCube' : no matching overloaded function found
ERROR: 0:163: 'assign' : cannot convert from 'const float' to 'highp 4-component vector of float'
ERROR: 0:168: 'textureCube' : no matching overloaded function found
ERROR: 0:168: 'r' : field selection requires structure, vector, or matrix on left hand side
ERROR: 0:169: 'textureCube' : no matching overloaded function found
ERROR: 0:169: 'g' : field selection requires structure, vector, or matrix on left hand side
ERROR: 0:170: 'textureCube' : no matching overloaded function found
ERROR: 0:170: 'b' : field selection requires structure, vector, or matrix on left hand side
ERROR: 0:185: 'textureCube' : no matching overloaded function found
ERROR: 0:185: 'assign' : cannot convert from 'const float' to 'highp 4-component vector of float'
ERROR: 0:196: 'fragCoord' : undeclared identifier
ERROR: 0:196: 'x' : field selection requires structure, vector, or matrix on left hand side
ERROR: 0:196: 'y' : field selection requires structure, vector, or matrix on left hand side
ERROR: 0:210: 'fragColor' : undeclared identifier
ERROR: 0:210: 'assign' : cannot convert from 'highp 4-component vector of float' to 'float'
Im not expecting to get someone to solve this for me, but I am asking for some lead into where to look first, or if there is some shortcut for converting this shader. This is a very important part of the project, so I will really appreciate any help!
Thank you!
A: These errors are not three.js related but just plain GLSL errors.
Maybe you broke something while you adjusted the uniforms? Just to make sure: you're aware of the fact that this shader uses raymarching to render its geometry. You cannot pass any geometry to it even if converted without errors. This is a screenspace effect using distance field algorithms to mathematically define the diamond shape. Its not working on any actual geometry.
As a side note this shader is very expensive on the hardware side. My Intel HD 4000 almost choked on it(running it in fullscreen), so be prepared to have smartphone browsers aswell as the fancy MacBook Air of your boss crashing.
If I were to implement a diamond effect i would use a cubemap with prebaked color abbreviations and a simple face normal - view direction reflection lookup in combination with a prebaced caustics texture applied to the "ground plane".
| |
doc_939
|
Following is not working:
<div text-wrap ion-item no-lines>
"No result found. <br/> Please enter your search criteria."
</div>
What am I doing wrong?
I tried with \n or br tag
A: I had a similar problem and had to put a div within the ion-item:
<ion-item>
<div>
first line
<br/>
second line
</div>
</ion-item>
You can also try this:
white-space: pre-line !important;
| |
doc_940
|
But when the user clicks on the "push notifications" link
It opens: https://pushpad.xyz/projects/3247/subscription/edit?uid=1&uid_signature=b537f55122d37236296c221342b552de26478d36
And the page says:
The page you were looking for doesn't exist. You may have mistyped the
address or the page may have moved.
A: If the project ID is correct, then it's because you're using the link for Pushpad Express, but your project and sender are configured to use Pushpad Pro. You can check that by going to the sender settings.
You need to do one of the following:
*
*keep your project and sender and use Pushpad Pro (Getting started); OR...
*delete your project and sender (to avoid further confusion); then create a new sender with Pushpad Express (enter a Pushpad subdomain as the domain, like my-project.pushpad.xyz) and create a new project associated to it; finally you can use the link for Pushpad Express
| |
doc_941
|
CLASS lcl_some_class DEFINITION. ""// <-- this is obviously lower case
PUBLIC SECTION.
CLASS-METHODS some_static_method. ""// <-- this is obviously lower case
PROTECTED SECTION.
PRIVATE SECTION.
ENDCLASS.
CLASS lcl_some_class IMPLEMENTATION.
METHOD some_static_method.
" nothing
ENDMETHOD.
ENDCLASS.
END-OF-SELECTION.
DATA: lc_class_name_upper TYPE string VALUE 'LCL_SOME_CLASS',
lc_class_name_lower TYPE string VALUE 'lcl_some_class',
lc_method_name_upper TYPE string VALUE 'SOME_STATIC_METHOD',
lc_method_name_lower TYPE string VALUE 'some_static_method'.
CALL METHOD LCL_SOME_CLASS=>SOME_STATIC_METHOD. ""ok
CALL METHOD (lc_class_name_upper)=>(lc_method_name_upper). ""ok
CALL METHOD lcl_some_class=>SOME_STATIC_METHOD. ""ok
CALL METHOD (lc_class_name_lower)=>(lc_method_name_upper). ""failure
CALL METHOD LCL_SOME_CLASS=>some_static_method. ""ok
CALL METHOD (lc_class_name_upper)=>(lc_method_name_lower). ""failure
CALL METHOD lCl_SoMe_ClAsS=>sOmE_sTaTiC_mEtHoD. ""ok
I expected the lines with comment "failure" to behave exactly like the corresponding lines above: To be case-insentive. But instead they fail with one of the following messages:
CX_SY_DYN_CALL_ILLEGAL_CLASS / DYN_CALL_METH_CLASS_NOT_FOUND
en: The class could not be found during the dynamic method call.
de: Die Klasse beim dynamischen Methodenaufruf konnte nicht gefunden werden.
CX_SY_DYN_CALL_ILLEGAL_METHOD / DYN_CALL_METH_NOT_FOUND
en: The method could not be found during the dynamic call.
de: Die Methode konnte beim dynamischen Aufruf nicht gefunden werden.
Is there a way to make the dynamic call case-insensitive (except for the obvious converting the strings to upper case)?
A: The official ABAP documentation of CALL METHOD - dynamic_meth is straight forward, concerning (class_name)=>(meth_name) and (class_name)=>meth:
class_name expects a character-like field that must contain the name of a class in uppercase letters when the statement is executed
I don't see any solution to make the kernel convert the name to upper case itself.
NB: I don't see why it is a problem to convert yourself the name to upper case before doing the dynamic call.
| |
doc_942
|
Is there a way that I can create a listener like "allimages.onload=function(){}" ?
Or is there any workaround?
A: You would have to maintain a count of how many images were yet to load, and call the final function when the outstanding image count reached 0. eg.
function nofunction() {}
function loadImages(srcs, callback) {
var images= [];
var imagen= srcs.length;
for (var i= 0; i<srcs.length; i++) {
var image= new Image();
image.onload=image.onerror= function() {
imagen--;
if (imagen==0) {
this.onload=this.onerror= nofunction;
callback();
}
};
image.src= srcs[i];
images.push(image);
}
return images;
}
...
var images= loadImages(['/img/1.gif', '/img/2.gif'], function() {
alert('yay');
});
for (var i= 0; i<images.length; i++)
mapelement.appendChild(images[i]);
A: A while ago I have written a blog post about detecting the load of a single image. You can use the example to build your function that checks if all images are loaded. I hope it will help.
| |
doc_943
|
Here is my code:
library(survival)
#> Warning: package 'survival' was built under R version 3.5.3
library(mlr)
#> Loading required package: ParamHelpers
data(veteran)
set.seed(24601)
task_id = "VET"
vet.task <- makeSurvTask(id = task_id, data = veteran, target = c("time", "status"))
vet.task <- createDummyFeatures(vet.task)
tuning = makeResampleDesc("CV", iters=2, stratify=TRUE)
outer = makeResampleDesc("CV", iters=2, stratify=TRUE)
filt = makeFilterWrapper(
makeLearner(cl="surv.coxph", id = "cox.filt.rfsrc", predict.type="response"),
fw.method="randomForestSRC_var.select",
fw.abs=4,
cache=TRUE,
ntree=500,
method="vh"
)
bmr = benchmark(filt, vet.task, outer, list(cindex), show.info = TRUE, models=TRUE, keep.extract=FALSE)
#> Task: VET, Learner: cox.filt.rfsrc.filtered
#> Resampling: cross-validation
#> Measures: cindex
#> Error in (function (task, method = "randomForestSRC_importance", fval = NULL, : formal argument "method" matched by multiple actual arguments
Created on 2019-09-25 by the reprex package (v0.3.0)
If I change argument method to "metho" to try and avoid the clash I get a different error:
library(survival)
#> Warning: package 'survival' was built under R version 3.5.3
library(mlr)
#> Loading required package: ParamHelpers
data(veteran)
set.seed(24601)
task_id = "VET"
vet.task <- makeSurvTask(id = task_id, data = veteran, target = c("time", "status"))
vet.task <- createDummyFeatures(vet.task)
tuning = makeResampleDesc("CV", iters=2, stratify=TRUE)
outer = makeResampleDesc("CV", iters=2, stratify=TRUE)
filt = makeFilterWrapper(
makeLearner(cl="surv.coxph", id = "cox.filt.rfsrc", predict.type="response"),
fw.method="randomForestSRC_var.select",
fw.abs=4,
cache=TRUE,
ntree=500,
metho="vh"
)
bmr = benchmark(filt, vet.task, outer, list(cindex), show.info = TRUE, models=TRUE, keep.extract=FALSE)
#> Task: VET, Learner: cox.filt.rfsrc.filtered
#> Resampling: cross-validation
#> Measures: cindex
#> Error in -im[, 1L]: invalid argument to unary operator
Created on 2019-09-25 by the reprex package (v0.3.0)
It seems that this error is coming from the line:
setNames(-im[, 1L], rownames(im))
in the RF min depth filter and I assume implies that variable im, the results of the filter, is NULL (although I am not sure why).
Is there any way around this problem? Apologies for posting here and on GH.
A: Fixed upstream in this Pull Request.
| |
doc_944
|
Can anyone spot any problems with my function?
fib :: Integer -> Integer
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n+1)
A: You have an error in your fibonacci formula:
fib :: Integer -> Integer
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)
Note the very last term where there is n-2 instead of n+1.
A: It's a very bad implementation, you should use tail recursion, start from 0 or 1 going upwards and passing the previous two fibonacci numbers. Also there is a bug, fib n depends on fib n+1.
fib :: Integer -> Integer
fib 0 = 0
fib n = iter 0 1 n
where iter :: Integer -> Integer -> Integer -> Integer
iter f1 f2 0 = f2
iter f1 f2 n = iter f2 (f1+f2) (n-1)
| |
doc_945
|
Deployment "Naming" is in error due to: javax.naming.NoInitialContextException: Cannot instantiate class: org.apache.naming.java.javaURLContextFactory [Root exception is java.lang.ClassNotFoundException: org.apache.naming.java.javaURLContextFactory ]
How to find out which jar file has that class?
A: According to this search result in FindJar, naming-factory-5.5.23.jar is the one that contains that class. Beware that the dependency scope is test in the example you provided. Are you doing the lookup in non test code?
| |
doc_946
|
the basic idea is, I type !generate and the bot dm's me with an account.
my problem is that my bot can't send any messages to the author of the message.
I'm getting "Cannot send messages to this user".
Lil code
let embed = new Discord.RichEmbed()
.addField("alt", `account: \n${random}`)
.setColor("#fffff");
message.author.send(embed);
random function picks random alt ( test:test for example from a txt file ).
any help is appreciated. thanks
A: The user you are sending the RichEmbed to likely has DM's from server members disabled.
Make sure that message.author does not have DM's from server members disabled in their privacy settings.
| |
doc_947
|
Name | Address | City |
--------------------------
A | A | C |
C | B | B |
B | C | A |
I would like it so that when I pass in the name of a column, I will be able to order by the column for the results of all rows. So for example, if I were to order by name, then it should return A B C not A C B.
The goal I'm trying is that when I pass in a parameter for my API so:
http://localhost:8080/api/person?sorting=city
Now I understand that this could be resolved using:
http://localhost:8080/api/person?sort=city,asc
However I am unable to use the sort paramemter for this case, since I am relying on information from multiple domains. So from that I decided to see if it's possible to create a query in my repository that could be used to sort the values. This is my attempt at it so far:
@Query("SELECT p FROM DePerson p, DeClass c, DeSchool s" +
"WHERE p.personId = c.id " +
"AND su.schoolId = s.id " +
"ORDER BY :ordering")
List<DePerson> sortingAll(String sorting);
With that, I'm trying to see if then I am able to pass in this query from my repository and use it in my service method as a sorting method for the results I have when passing the endpoint:
List<PersonDTO> result = new ArrayList<>();
Page<DePerson> page;
List<DePerson> personList = page.getContent();
for (DePerson person: personList) {
result.add(convertDTO(person));
}
return new PageImpl<>(result, pageable, page.getTotalElements());
To conclude, I'm trying to create a custom sort parameter using jpql which should be apply to the results when the endpoint is called.
A: For dynamic queries it's recommended to use criteria API so to achieve your goal you can do this.
First add an implementation to your PersonRepository and autowired Entity Manager to have something like that
PersonRepositoryImpl implements PersonRepository{
@Autowired
EntityManager em;
//here you can also pass Page object and modify some staff
private List<Person> getEntitiesOrder(String sortColumn){
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Person> query = cb.createQuery(Person.class);
Root<Person> people= query.from(Person.class);
query.select(people).orderBy(cb.desc(people.get(sortColumn)));
TypedQuery<Person> queryPeople =
entityManager.createQuery(query);
return queryPeople.getResultList();
}
}
then form your service or controller you can autowired this repository and you will get the desired behavior.
| |
doc_948
|
G.add_edges_from([[1,2], [2,3], [1,3], [1,4], [1,5], [3,5],
[6,7], [7,8], [8,9], [6,9], [6,8], [7,9],
[10,11], [11,12], [10,12],
[9, 12], [2, 7]
])
nx.draw(G, with_labels=True, node_color='r')
File "C:...\anaconda3\lib\site-packages\networkx\utils\decorators.py", line 396, in _random_state
random_state_arg = args[random_state_index]
IndexError: tuple index out of range
| |
doc_949
|
I am submitting form with handleRequest ($editForm->handleRequest($request)) and everything is working fine on dev. But on prod environment it is not working. I have debug everything and I found that it is not submitting this form.
I have managed to get this working with changing
$editForm->handleRequest($request)
to
$editForm->submit($request->request->get($editForm->getName()))
But could someone tell me why handleRequest is not working for me just in prod environment?
I have removed all cache.
EDIT:
I have also remind myself that it is working great on creating, but not on editing/updating.
A: Are you setting the method param when creating your $editForm?
$editForm = $this->createForm(new TaskType(), $task, array(
'action' => $this->generateUrl('edit_task'),
'method' => 'PUT',
));
$editForm->handleRequest($request);
Additionally you might need to set http_method_override in your config. http://symfony.com/doc/current/reference/configuration/framework.html#http-method-override
| |
doc_950
|
DECLARE @userID INT
DECLARE user_cursor CURSOR FOR SELECT userID FROM users
WHILE /* some condition */
BEGIN
...
FETCH NEXT FROM user_cursor INTO @userID
IF @@FETCH_STATUS = 0
BEGIN
/*... here goes the reset of the cursor ...*/
END
...
END
A: you need to declare your cursor as scroll, like this
declare c scroll cursor for (select statement);
then at any time for locating to the first just use the following
fetch first from c;
A: Another option that can be used that doesn't force you to change the type of cursor is simply to close the cursor and re-open it:
CLOSE user_cursor
OPEN user_cursor
But the scroll option will be cheaper in terms of resource usage, if that's a change you can accept.
A: The data retrieved by the cursor will not change.
STATIC
Defines a cursor that makes a temporary copy of the data to be used by the cursor. All requests to the cursor are answered from this temporary table in tempdb; therefore, modifications made to base tables are not reflected in the data returned by fetches made to this cursor, and this cursor does not allow modifications.
A: Use cursor loops and its taken care of for you...
cursor c_something IS
select * from somewhere
BEGIN
for some_row in c_something LOOP
-- do stuff with some_row.COLUMN;
END LOOP; -- this closes the cursor for you when it has gone all the way through
-- do other stuff
for some_row in c_something LOOP -- opens the cursor again from the top
-- do stuff with some_row.COLUMN;
END LOOP;
END;
| |
doc_951
|
Thanks for the help.
A: Lua do not support download itself, it must rely on extenal liabraries like luasocket. you can refer the answer download file by url in lua
| |
doc_952
|
Controler: user.php
public function profile() {
$wskey = sdafsda;
$companycode = 'sdafsd';
$client = 1;
$cardno = 'sdafsd';
$pin = 'sdaf';
$wsdl = 'http://example/service.asmx?wsdl';
$getdata = array(
'WSKey' => $wskey,
'CompanyCode' => $companycode,
'CardNo' => $this->EncryptData($cardno),
'Client' => $client,
'PIN' => $this->EncryptData($pin),
);
$soapClient = new SoapClient($wsdl);
try {
$result = $soapClient->GetProfile($getdata);
} catch (Exception $e) {
return $e;
}
}
And view is created in com_users->views->cprofile.
I want to show this data in default.php of cprofile views and Want to know how can I call a view with data.
Sorry might not be clear.
| |
doc_953
|
I am looking for this:
Input:
< Idoc >
< Elements >
< /Idoc >
The same has to be returned as output also, the whole content has to be stored in a variable as a string.
Output:
< Idoc >
< Elements >
< /Idoc >
and variable V1 with the whole content.
I will have another XSLT mapping, where I would like to retrieve the content of Variable.
Is that possible, if so, please let me know how to achieve it.
A: An XSLT variable is local to a stylesheet and can't be accessed in a different stylesheet.
Perhaps you should tell us what you are trying to achieve, rather than presenting us with a design approach that isn't going to work?
| |
doc_954
|
// build.gradle
`compile 'com.android.support:appcompat-v7:23.2.0'`
I'm trying to use this icon: @drawable/abc_ic_clear_mtrl_alpha
// styles.xml
<style name="MyTheme" parent="Theme.AppCompat.Light">
<item name="homeAsUpIndicator">@drawable/abc_ic_clear_mtrl_alpha</item>
</style>
But I get this error: Error:(12, 5) No resource found that matches the given name (at 'homeAsUpIndicator' with value '@drawable/abc_ic_clear_mtrl_alpha').
Any help is appreciated thanks.
A: Support library v7:23.2.0 now supports Vector Drawable.
This way, a lot of drawable become useless or obsolete and where removed.
I think that abc_ic_clear_mtrl_alpha was replaced by abc_ic_clear_material which uses vector:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0"
android:tint="?attr/colorControlNormal">
<path
android:pathData="M19,6.41L17.59,5,12,10.59,6.41,5,5,6.41,10.59,12,5,17.59,6.41,19,12,13.41,17.59,19,19,17.59,13.41,12z"
android:fillColor="@android:color/white"/>
</vector>
As you can see, the new icon uses vector and colorControlNormal.
You may want to check this question to check how to enable Vector and change the color of the icons.
A: For newest versions you can found abc_ic_clear_mtrl_alpha and a lot of other icons doing this:
android.support.v7.appcompat.R.drawable.abc_ic_clear_material
| |
doc_955
|
int i_;
Foo(int i) :i_(i) { std::cout << "Foo:" << i_ << "\n"; }
~Foo() { std::cout << "~Foo" << i_ << "\n"; }
};
class FooSingleton
{
public:
static std::weak_ptr<Foo> GetInstance()
{
auto tmp = std::atomic_load(&instance);
if (tmp == nullptr) {
std::lock_guard<std::mutex> lock(mutex1);
tmp = std::atomic_load(&instance);
if (tmp == nullptr) {
tmp = std::make_shared<Foo>(2);
std::atomic_store(&instance, tmp);
}
}
return tmp;
}
private:
static std::mutex mutex1;
static std::shared_ptr<Foo> instance;
};
Was reading Double-check locking http://preshing.com/20130930/double-checked-locking-is-fixed-in-cpp11/,
but I also need using shared_ptr to own raw pointer.
From documentation I know, that I can't use shared_ptr as template for std::atomic (§29.5 1 in N3290)
Update: my realization seems to be right (although it not elegant) - as it passed code review.Thanks to all!
A: You don't need a pointer be it raw or shared at all, just use a reference:
struct Foo {
int i_;
Foo(int i) :i_(i) { std::cout << "Foo:" << i_ << "\n"; }
~Foo() { std::cout << "~Foo" << i_ << "\n"; }
};
class FooSingleton
{
public:
static FooSingleton& GetInstance()
// ^
{
static FooSingleton theInstance;
return theInstance;
}
Foo foo() {
std::lock_guard<std::mutex> lock(mutex1);
return Foo;
}
void foo(const Foo& value) {
std::lock_guard<std::mutex> lock(mutex1);
foo_ = value;
}
private:
FooSingleton() : foo_(42) {
}
std::mutex mutex1;
Foo foo_;
};
The Meyers' Singleton is guaranteed to be thread safe.
Use the instance mutex to synch any operations done with your singleton in case thread safety is necessary.
| |
doc_956
|
A cars1 black NY
A cars2 W
A cars3 black SP
I would like to transform the last column into a new line and add the > symbol:
A cars1 black
>NY
A cars2
>W
A cars3 black
>SP
I tried the command below, but it did not work very well, maybe because of the missing values of the third column:
awk '{print $1,$2,$3,"\n"$4}'
A: In sed:
$ sed 's/[[:blank:]]*\([^[:blank:]]*\)$/\n>\1/' infile
A cars1 black
>NY
A cars2
>W
A cars3 black
>SP
This takes the last sequence of blanks followed by non-blanks and substitutes them by a newline, > and the captured non-blanks.
Notice that some seds complain about inserting a newline like this. Alternatives are:
*
*Insert a literal newline
sed 's/[[:blank:]]*\([^[:blank:]]*\)$/\
>\1/' infile
*Insert an ANSI-escaped newline
sed 's/[[:blank:]]*\([^[:blank:]]*\)$/'$'\n''>\1/' infile
*Command substitution
sed 's/[[:blank:]]*\([^[:blank:]]*\)$/'"$(printf '\n')"'>\1/' infile
A: In awk:
$ awk '{$NF=ORS ">" $NF; print}' file
The point is to modify the last field $NF and then just print the whole record $0.
A: In awk you can do it 'mechanically':
$ awk '{for(i=1;i<NF;i++) printf "%s%s",$i,i==NF-1 ? ORS : OFS; print ">" $NF}' file
A cars1 black
>NY
A cars2
>W
A cars3 black
>SP
| |
doc_957
|
Only Requirement: Project must be able to run on JRE 1.7 & Tomcat 7
I have not been able to do it because of Unsupported major.minor and countless other problems with versioning and terrible giter8 templates.
Here's my current dilemma:
Followed all the steps in "Starting From Scratch" section up until sbt jetty:start jetty:join. (Skip to last code snippet for error):
https://github.com/earldouglas/xsbt-web-plugin/blob/master/docs/3.0.x.md
Here's my java home and version:
$ echo $JAVA_HOME
/Library/Java/JavaVirtualMachines/jdk1.7.0_80.jdk/Contents/Home
$
$ java -version
java version "1.7.0_80"
Java(TM) SE Runtime Environment (build 1.7.0_80-b15)
Java HotSpot(TM) 64-Bit Server VM (build 24.80-b11, mixed mode)
Here's my build.sbt:
scalaVersion := "2.11.6"
libraryDependencies += "javax.servlet" % "javax.servlet-api" % "3.0.1" % "provided"
enablePlugins(JettyPlugin)
Here's my project/build.sbt:
addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "3.0.3")
Here's my project/build.properties:
sbt.version=0.13.8
servlet.scala and web.xml are exactly as they are in the link.
Here's my project structure:
.
├── build.sbt
├── project
│ ├── build.properties
│ └── build.sbt
└── src
└── main
├── scala
│ └── servlets.scala
└── webapp
└── WEB-INF
└── web.xml
6 directories, 5 files
Here's the BANE OF MY EXISTENCE:
$ sbt jetty:start jetty:join
[info] Loading project definition from /Users/dan/Projects/temp/ssltester/project
[info] Updating {file:/Users/dan/Projects/temp/ssltester/project/}ssltester-build...
[info] Resolving org.fusesource.jansi#jansi;1.4 ...
[info] Done updating.
[info] Set current project to ssltester (in build file:/Users/dan/Projects/temp/ssltester/)
[info] Updating {file:/Users/dan/Projects/temp/ssltester/}ssltester...
[info] Resolving jline#jline;2.12.1 ...
[info] Done updating.
[info] Compiling 1 Scala source to /Users/dan/Projects/temp/ssltester/target/scala-2.11/classes...
[info] Packaging /Users/dan/Projects/temp/ssltester/target/scala-2.11/ssltester_2.11-0.1-SNAPSHOT.jar ...
[info] Done packaging.
[info] starting server ...
Exception in thread "main" java.lang.UnsupportedClassVersionError: org/eclipse/jetty/runner/Runner : Unsupported major.minor version 52.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:482)
[success] Total time: 3 s, completed Nov 7, 2017 6:58:47 PM
[success] Total time: 0 s, completed Nov 7, 2017 6:58:48 PM
[info] waiting for server to shut down...
**Could someone please point out to me what's wrong? ** I completely deleted the java 1.8 jdk directory. Since it says version 52 (jdk 8) I don't know where it's coming from. jdk 7 should be 51, jdk 6 should be 50
If you're in Denver, I'll buy you a beer (if you're over 21) otherwise it's soda for you kid! :-)
A: Exception in thread "main" java.lang.UnsupportedClassVersionError: org/eclipse/jetty/runner/Runner : Unsupported major.minor version 52.0
My guess is that the version of Jetty that you're using was compiled for Java 8, which won't work if you're using Java 7. In xsbt-web-plugin 3.0.x, the default Jetty version is 9. Based on this table, you might want to try Jetty 8 (or older) instead.
Try adding this to your build.sbt:
containerLibs in Jetty := Seq("org.mortbay.jetty" % "jetty-runner" % "8.0.0.v20110901" intransitive())
Since your requirements include being able to run your project under Tomcat, you may prefer to use Tomcat instead of Jetty. The default version of Tomcat is 8, which looks like it should work with Java 7 according to this table.
To switch to Tomcat, change enablePlugins(JettyPlugin) to enablePlugins(TomcatPlugin) in your sbt configuration, and change jetty:start jetty:join to tomcat:start tomcat:join at the sbt prompt.
| |
doc_958
|
https://learn.microsoft.com/en-us/vsts/build-release/tasks/utility/service-fabric-versioning
Everything works fine except that changes are always detected for the class library's dll-file. Even though I haven't changed anything in the code library! This causes the build step to bump the version of every single service. Not just services that actually has updates.
The logs looks like bellow. 'MyClassLibrary.dll' is a .Net Framework Class Library that I haven't touched the code in.
2018-03-12T11:39:51.1989307Z Searching service 'MyServicePkg' for
changes...
2018-03-12T11:39:51.2247570Z Searching package 'Code' for changes...
2018-03-12T11:39:51.9878149Z The file 'MyClassLibrary.dll' has
changed.
2018-03-12T11:39:54.3850926Z Updated package 'MyServicePkg\Code'
from version '1.0.0' to '1.0.1'.
I'm aware that the check for changes in the code package is binary comparison. So the binary obviously change when the project is compiled. However, I don't know why. I also have code libraries that targets .Net Standard 2.0 and they don't cause this issue as changes are only detected when I actually have touched the code.
I'm also aware that it is possible to manually omit files that shouldn't update from the application package https://stackoverflow.com/a/34886586 However, that is not an option since the deployment chain is automated.
So I have the following questions:
*
*What causes the binary for a .Net Framework class library to change?
*In what way does it differ from a .Net Standard class library?
*How do I work around it so my services only updates when I make real changes? Port from .Net Framework to .Net Standard?
Some insight in the matter is greatly appreciated.
A: By default, the compiler will create different outputs even if you made no changes. Use the deterministic compiler flag to ensure builds with the same inputs produce the same outputs.
So, you need to specify /p:Deterministic=true argument in MSBuild Arguments.
The simple way is using Azure Service Fabric Application build template: Create a new build definition > Select Azure Service Fabric Application template, then you will find, there is /p:Deterministic=true /p:PathMap=$(Agent.BuildDirectory)=C:\ in MSBuild Arguments of Visual Studio Build task.
| |
doc_959
|
A: IntelliJ IDEA Community edition has no Spring support, you need IntelliJ IDEA Ultimate. Please check this page for the differences between the editions.
A: If you check the comparison chart here: https://www.jetbrains.com/idea/features/editions_comparison_matrix.html
you can see that Spring support is Ultimate edition feature only.
A: It doesn't appear because you need to create it, the documentation is quite clear about it..
You can add, remove or edit file sets in
File | Project Structure | Modules | | Spring
or
File | Project Structure | Facets | Spring ().
So you click the little green + sign and add a Spring facet/module
| |
doc_960
|
#include <stdio.h>
int main (int argc, char *argv[]) {
int phoneNumber;
char firstName[11];
char lastName[11];
char eMail[20];
int output;
int CSV;
int TSV;
int XML;
printf("Please enter the user's first name:");
scanf("%s", firstName);
printf("Please enter the user's last name:");
scanf("%s", lastName);
printf("Please enter the user's phone number:");
scanf("%i", &phoneNumber);
printf("Please enter the user's e-mail:");
scanf("%s", eMail);
printf("What output format would you like? (CSV,TSV/XML) ");
scanf("%d", &output);
if (output == 'CSV') {
printf("firstName,lastName,phoneNumber,eMail");
printf("%s,%s,%i,%s",firstName, lastName, phoneNumber, eMail);
}
else if (output == 'TSV') {
printf("firstName,\tlastName,\tphoneNumber,\teMail");
printf("%s,\t%s,\t%i,\t%s", firstName, lastName, phoneNumber, eMail);
}
}
A: First, as mentioned, you need to use the strcmp function to compare strings. == is testing whether the string is in the same place as the constant the compiler generated, which it won't be.
#include <string.h>
and then you can use
if(strcmp(output,"CSV")==0) { /*output CSV*/ }
Second, you need to use " rather than ' to delimit strings; ' is for single characters only.
Third, the CSV and TSV variables are never given values. Use
char output[256];
scanf("%s", output)
and then you can use strcmp(output, "CSV") (or strcasecmp depending on whether you want case-sensitivity).
A: here are the changes you need to make:
printf("What output format would you like? (CSV,TSV/XML) ");
scanf("%s", &output);
...
if (strcmp(output, "CSV") == 0) {
// ...
} else if (strcmp(output, "TSV") == 0) {
// ...
}
A: In C you perform string equality checks with strcmp(...).
Additionally, string literals must be enclosed with quotation marks ".
#include <string.h>
// ...
if (strcmp(output, "CSV") == 0) {
// ...
} else if (strcmp(output, "TSV") == 0) {
// ...
}
[Edit] If you are trying to use integers to represent those values (CSV, TSV, XML) then you should do something like this:
const int CSV = 1;
const int TSV = 2;
const int XML = 3;
// ...
printf("What output format would you like? (CSV=1,TSV=2,XML=3) ");
scanf("%d", &output);
// ...
if (output == 1/*CSV*/) {
// ...
} else if (output == 2/*TSV*/) {
// ...
}
A: int output;
/* ... */
printf("What output format would you like? (CSV,TSV/XML) ");
scanf("%d", &output);
You ask the user to enter CSV, TSV, or XML, but then you read an integer, which to be valid must be an optional + or - followed by a sequence of decimal digits.
if (output == 'CSV') {
'CSV' is a multi-character constant. It's of type int, and it has an implementation-defined value. That value has nothing to do with whatever the user entered at the previous prompt.
(It's unfortunate that this compiles without error. Multi-character constants are nearly useless.)
You can assign numbers to CSV, TSV, and XML, show the user those numbers, read numeric input, and then compare it. For example:
const int CSV = 1;
const int TSV = 2;
const int XML = 3;
printf("What output format would you like? (CSV,TSV/XML) ");
scanf("%d", &output); /* error checking omitted for now */
if (output == CSV) {
/* ... */
}
else if (output == TSV) {
/* ... */
}
/* ... */
Or you can change output to a character or a string, read that (using the appropriate scanf format), and then compare output to a character or to a string.
Note that if you go with strings, you'll need to use strcmp(), not ==, to compare them.
And be sure to check the value returned by scanf. It returns the number of items it was able to scan. For the calls you're using, if scanf returns something other than 1, it means there was an error of some sort (for example the user typed foo when you were expecting an integer), and you need to report the error and probably quit the program -- or perhaps use a loop to continue prompting the user until you get something valid.
| |
doc_961
|
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:theme="@style/Theme.AppCompat.Light.DarkActionBar"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_activity_main"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="@style/ThemeOverlay.AppCompat.ActionBar">
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<include
layout="@layout/content_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/test"/>
The test layout is LinearLayout which has a further Views
The problem is that the actionbar is overlapping the content of the Test Layout
Could this because of the themes ? (which i personally dont feel ) but then not sure
A: Try to add in your TestLayout xml definition the following line:
app:layout_behavior="@string/appbar_scrolling_view_behavior"
Update
To fix your problem, you can simply remove the android:layout_width="match_parent" and android:layout_height="wrap_content" from your include tag, so your include will look like this:
<include
layout="@layout/content_main"
android:id="@+id/test"/>
Alternatively, as suggested correctly below from @santosh kumar, you can move the line above from the LinearLayout definition to the include definition.
A: use marginTop="?attr/actionBarSize" to the included layout
A: you should try this,
Theme is not really a problem.
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:theme="@style/Theme.AppCompat.Light.DarkActionBar"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:id="@+id/main"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_activity_main"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.ActionBar">
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<include
layout="@layout/content_main"
android:layout_width="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
android:layout_height="wrap_content"
android:id="@+id/test"/>
</android.support.design.widget.CoordinatorLayout>
| |
doc_962
|
Strace clearly shows that timer_settime() was called by the binary:
[pid 30500] timer_settime(0x2, 0, {it_interval={30, 0}, it_value={30, 0}}, {it_interval={0, 0}, it_value={0, 0}}) = 0
It was called many times with different time intervals. I want to catch exactly the above one with an interval of 30 seconds.
Here's my code, timerwrap.c:
#define _GNU_SOURCE
#include <dlfcn.h>
#include <time.h>
#include <stdio.h>
int timer_settime(timer_t timerid, int flags, const struct itimerspec *new_value, struct itimerspec *old_value)
{
printf("Enter timer.\n");
if((new_value->it_interval).tv_sec == 30) {
printf("Catched!\n");
return 0;
}
int (*real_timer_settime)(timer_t, int, const struct itimerspec *, struct itimerspec *);
real_timer_settime = dlsym(RTLD_NEXT, "timer_settime");
return real_timer_settime(timerid, flags, new_value, old_value);
}
gcc commandline:
gcc -Wall -g -shared -fPIC -o timerwrap.so timerwrap.c -ldl -lrt
run program:
export LD_PRELOAD=/home/Work/C/timerwrap.so
./the_program
But it failed to intercept the call.
I ran it again with LD_DEBUG=all to further investigate. It turns out that for many other symbols, timerwrap.so was looked up, for example dlsym's lookup path looks like this in the debug output:
2006: symbol=dlsym; lookup in file=/.../the_program [0]
2006: symbol=dlsym; lookup in file=/home/Work/C/timerwrap.so [0]
2006: symbol=dlsym; lookup in file=./lib/libssl.so.6 [0]
2006: symbol=dlsym; lookup in file=/lib/i686/cmov/libdl.so.2 [0]
2006: binding file /.../the_program [0] to /lib/i686/cmov/libdl.so.2 [0]: normal symbol `dlsym' [GLIBC_2.0]
However, for timer_settime, the lookup takes only one step, and goes directly to /usr/lib/librt.so, bypasses timerwrap.so:
2006: symbol=timer_settime; lookup in file=/usr/lib/librt.so [0]
2006: binding file /usr/lib/librt.so [0] to /usr/lib/librt.so [0]: normal symbol `timer_settime'
So what happened here? Why is librt.so special? Any thoughts?
This is my first question. Thanks in advance for any help!
A: A simple example program shows me that everything works as it should.
The application you try to use, probably loads the timer_settime via dlsym.
Doing dlsym(dlopen("librt.so"), "timer_settime")
Solving this problem shouldn't be that hard, just add something like this to your source:
extern void *_dl_sym (void *handle, const char *name, void *who);
void *dlsym(void *handle, const char *symbol)
{
printf("Enter dlsym.\n");
void* result = _dl_sym(handle, symbol, 0); // the replacement we are going to use
if ((handle != RTLD_NEXT) || (handle != RTLD_DEFAULT))
if(!strcmp(symbol, "timer_settime")) {
printf("Return our timer_settime");
return timer_settime;
}
return result;
}
| |
doc_963
|
train$Sex_num <- as.character(train$Sex)
train$Sex_num[train$Sex=="male"]<-1
train$Sex_num[train$Sex=="female"]<-0
train$Sex_num <- as.numeric(train$Sex_num)
table(train$Sex_num)
EDIT
Efficient: Less lines of code.
A: just remove the Sex column and create an is_male column. You can directly coerce a logical vector to numeric without needing to specify female separately.
train$is_male <- as.integer(train$Sex == "male")
A: ifelse is pretty efficient. Try
train$Sex_num <- ifelse(train$Sex=="male", 1, 0)
A: There are many good & efficient answers already provided for the question. But sometimes I feel named-vector (vector with attributes) should be considered good alternatives in cases like this.
sexType <- c(female = 0, male = 1, other = 2)
train$Sex_num <- sexType[train$Sex]
I have added another option as other to demonstrate flexibility but that is not needed scenario mentioned by OP.
| |
doc_964
|
An example:
I'm connected with WLAN A, but I want the interface from WLAN B. How can I get that?
Currently I'm using netsh wlan show interface. But with that I just get the interface from the currently connected WLAN.
Is it also possible, that I can do that, when I'm connected with a LAN-cable and wanna get the interface of a WLAN?
A: # List all Network Adapters
Get-NetAdapter
# Get info on just Wireless Network
Get-NetAdapter -Name wi-fi | FL *
# Get more info on how to use Get-NetAdapter:
https://learn.microsoft.com/en-us/powershell/module/netadapter/get-netadapter?view=windowsserver2019-ps
| |
doc_965
|
"mongoose": "^6.6.1"
The query below works and returns 3 results with Model.find() as expected.
However, with aggregate and $match, it returns no results at all - WITH SAME FILTER QUERY
This is the filter query:
const filter = {
'$and': [
{
'$or': [
{
userId: {
'$in': [ '62fffec968d757addc8134fb' ]
},
sharedAt: {
'$exists': true
}
},
{
createdById: new ObjectId("62fffec968d757addc8134fb")
}
]
},
{ sharedAt: { '$exists': true } },
{
'$or': [
{
userId: {
'$in': [
'62fffec968d757addc8138db',
'62fffec968d757addc813614',
'62fffec968d757addc81348e',
'62fffec968d757addc8135b7'
]
}
},
{
createdById: {
'$in': [
'62fffec968d757addc8138db',
'62fffec968d757addc813614',
'62fffec968d757addc81348e',
'62fffec968d757addc8135b7'
]
}
}
]
}
]
}
Why is $match returning different results than .find(...) ?
I read here that find() and aggregate $match do the same thing with a query: https://www.mongodb.com/community/forums/t/what-are-differences-between-find-and-match/34964
A: From the $match documentation:
The $match query syntax is identical to the read operation query syntax; i.e. $match does not accept raw aggregation expressions. To include aggregation expression in $match, use a $expr query expression:
You have to work with the $expr operator.
Hence your query should be as below:
{
"$match": {
"$expr": {
"$and": [
{
"$or": [
{
"$in": [
"$userId",
[
"62fffec968d757addc8134fb"
]
]
},
{
"$ne": [
"$sharedAt",
undefined
]
},
{
"$eq": [
"$createdById",
new ObjectId("62fffec968d757addc8134fb")
]
}
]
},
{
"$ne": [
"$sharedAt",
undefined
]
},
{
"$or": [
{
"$in": [
"$userId",
[
"62fffec968d757addc8138db",
"62fffec968d757addc813614",
"62fffec968d757addc81348e",
"62fffec968d757addc8135b7"
]
]
},
{
"$in": [
"$createdById",
[
"62fffec968d757addc8138db",
"62fffec968d757addc813614",
"62fffec968d757addc81348e",
"62fffec968d757addc8135b7"
]
]
}
]
}
]
}
}
}
| |
doc_966
|
Please don't let the fact it is in f# detract from the problem. I'm using the standard cryptography libraries from the .NET 5 framework
module GenericCryptography =
let createRsa (res: GenericPublicKey) =
let rsa = RSA.Create()
// create params
let mutable rsaParams = RSAParameters()
rsaParams.Modulus <- res.Modulus
rsaParams.Exponent <- res.Exponent
rsa.ImportParameters(rsaParams)
// export final RSA class
rsa
let rsaFormatter =
let r = RSAPKCS1SignatureFormatter(rsa)
r.SetHashAlgorithm("SHA1") |> ignore
r
let rsaDeformatter =
let r = RSAPKCS1SignatureDeformatter(rsa)
r.SetHashAlgorithm("SHA1") |> ignore
r
let sha1 =
let crytProv = new SHA1CryptoServiceProvider()
crytProv.Initialize()
crytProv
let encrypt (data: byte[]) =
let hash = sha1.ComputeHash(data)
rsaFormatter.CreateSignature(hash)
let verify (data: byte[]) (signature: byte[]) =
let hash = sha1.ComputeHash(data)
rsaDeformatter.VerifySignature(hash, signature)
The encrypt & verify method is used like so
let signature = GenericCryptography.encrypt (message |> Helpers.getUTF8Bytes)
let encryptedMessage = GenericCryptography.encrypt (message |> Helpers.getUTF8Bytes)
let verifiedSignature = GenericCryptography.verify encryptedMessage signature
This fails with
Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: Key does not exist.
This isn't mentioned in the docs for verifying... I'm not sure why I'm getting that - I know I import the public key, and has something to do with that, but what is the question
To repro, just do var rsa = RSA.Create() and do rsa.ExportParameters(false), this will return you a structure where you can get the Modulus and Exponent from to pass to the createRsa function
Further Analysis
This happens on this line:
let encrypt (data: byte[]) =
let hash = sha1.ComputeHash(data)
rsaFormatter.CreateSignature(hash) //<-- this line
A: The issue as stated in the comments, is that when importing the RSA Parameters, only the public key was set, and in order encrypt it would need private key as well.
| |
doc_967
|
I have read other threads stating that array indexing in 7.4 is much stricter than previous versions, and it no longer allows unset indexes to be referenced. That's fine and I get why, but the problem is if I execute a sql query and columns are null for some rows I get the error 'Message: Trying to access array offset on value of type null'.
Example
col1
col2
'val'
null
If I execute the following query
select col1, col2 from table
sqlsrv_fetch_array will return [col1: 'val'] and col2 will be a null offset.
I know I can say
$row['col1'] = $row['col1'] ?? 0;
$row['col2'] = $row['col2'] ?? 0;
but if I am selecting many columns, this adds many lines of code to make sure everything gets set.
Is there a way to force sqlsrv_fetch_array to still return an array with all indexes?
A: Try passing SQLSRV_FETCH_ASSOC into sqlsrv_fetch_array. This should return an associative array in which null columns will be represented, but will hold empty values.
For example:
while($row = sqlsrv_fetch_array($results,SQLSRV_FETCH_ASSOC)){
foreach($row as $key=>$value){
echo $key . " = " . $value . "\n";
}
}
| |
doc_968
| ||
doc_969
|
The Setup:
I have a repository, IPartiesRepository. I have a Party object and a *Party_Identification* object. Party being a generic term for a person or organization.
On the SQL/physical model level, the Party table has a single primary key, PartyId. The Party_Identifications table has a composite key made up of three fields -- PartyId, IdentificationTypeCode, and IdentificationStartDate.
I have a strongly typed (to Party) view which lists Party information and associated identifications. A user can edit a party's identification; the edit links are generated via an ActionLink that looks like so:
<h3>Identification Data</h3>
<% foreach (var Identification in Model.Party_Identifications) { %>
<%: Identification.IdentificationTypeCode %>: <%: Identification.IdentificationValue %> - <%: Html.ActionLink("Edit", "EditIdentification", new { partyId = Identification.PartyId, idTypeCode = Identification.IdentificationTypeCode, startDate = Identification.PartyIdentificationStartDate })%><br />
<% } %>
The EditIdentification() method in the PartyController looks like:
public ActionResult EditIdentification(int partyId, string idTypeCode, string startDate)
{
var party = partiesRepository.GetPartyById(partyId);
var identification = party.Party_Identifications.Where(x => x.PartyId == partyId && x.IdentificationTypeCode == idTypeCode && x.PartyIdentificationStartDate == DateTime.Parse(startDate)).First();
return View("EditIdentification", identification);
}
The EditIdentification view allows the user to modify the identification record via a basic form:
<% using (Html.BeginForm("EditIdentification", "Party")) { %>
<%: Html.EditorForModel()%>
<input type="submit" value="Save" />
<% } %>
The Problem:
I have another EditIdentification() method in the PartyController that handles the save. I am attempting to see if there we are updating an existing identification record, or creating a new one (I also have a Create() method in the PartyController that returns the EditIdentification view with a Party_Identification object as the model).
I know there's a better way to do what I'm doing below (specifically, detecting a modified vs new record, and updating a modified record) -- how can I improve this?
[HttpPost]
public ActionResult EditIdentification(Party_Identification partyidentification)
{
TryUpdateModel(partyidentification);
if (partyidentification.CreationDate == DateTime.Parse("01/01/0001"))
{
partyidentification.CreationDate = DateTime.Now;
partyidentification.CreatedByName = User.Identity.Name.ToString();
partyidentification.ModificationDate = DateTime.Now;
partyidentification.ModifiedByName = User.Identity.Name.ToString();
}
// TODO: Validation goes here...
if (ModelState.IsValid)
{
var party = partiesRepository.GetPartyById(partyidentification.PartyId) as Party;
int partyCount = party.Party_Identifications
.Where(x => x.PartyId == partyidentification.PartyId &&
x.IdentificationTypeCode == partyidentification.IdentificationTypeCode &&
x.PartyIdentificationStartDate == partyidentification.PartyIdentificationStartDate)
.Count();
if (partyCount == 0)
{
party.Party_Identifications.Add(partyidentification);
}
else
{
var idtoupdate = party.Party_Identifications
.Where(x => x.PartyId == partyidentification.PartyId &&
x.IdentificationTypeCode == partyidentification.IdentificationTypeCode &&
x.PartyIdentificationStartDate == partyidentification.PartyIdentificationStartDate)
.First();
idtoupdate.IdentificationValue = partyidentification.IdentificationValue;
idtoupdate.PartyIdentificationEndDate = partyidentification.PartyIdentificationEndDate;
idtoupdate.ModificationDate = DateTime.Now;
idtoupdate.ModifiedByName = User.Identity.Name.ToString();
}
partiesRepository.SaveParty(party);
return View("Edit", party);
}
else
{
return View("Edit", partyidentification);
}
}
A: You appear to be repeating your code which it not needed:
if (ModelState.IsValid)
{
var party = partiesRepository.GetPartyById(partyidentification.PartyId) as Party;
int partyCount = party.Party_Identifications
.Where(x => x.PartyId == partyidentification.PartyId &&
x.IdentificationTypeCode == partyidentification.IdentificationTypeCode &&
x.PartyIdentificationStartDate == partyidentification.PartyIdentificationStartDate)
.first();
if (partyCount == null)
{
party.Party_Identifications.Add(partyidentification);
}
else
{
partyCount.IdentificationValue = partyidentification.IdentificationValue;
partyCount.PartyIdentificationEndDate = partyidentification.PartyIdentificationEndDate;
partyCount.ModificationDate = DateTime.Now;
partyCount.ModifiedByName = User.Identity.Name.ToString();
}
partiesRepository.SaveParty(party);
return View("Edit", party);
}
else
{
return View("Edit", partyidentification);
}
| |
doc_970
|
I need to use native JS and display:block,none.
var e = document.getElementById('calendarPickerContainer');
if (e.className == 'visible') {
e.className = 'hidden';
} else {
e.className = 'visible';
}
need to adapt to this css
.visible{
display:block;
}
.hidden {
display:none;
}
A: If you wanna use a pure JavaScript fadeIn and fadeOut, try this:
transition: opacity 1s linear;
This is a pure CSS method.
#cont {-webkit-transition: opacity 1s linear; -o-transition: opacity 1s linear; transition: opacity 1s linear;}
#cont.hidden {opacity: 0;}
<button onclick="cont.classList.add('hidden'); setTimeout('cont.style.display=\'none\'', 1000);">Click</button>
<div id="cont">
Hello
</div>
Working Snippet (includes toggle):
#cont {-webkit-transition: opacity 1s linear; -o-transition: opacity 1s linear; transition: opacity 1s linear; opacity: 1;}
#cont.hidden {opacity: 0; -webkit-transition: opacity 1s linear; -o-transition: opacity 1s linear; transition: opacity 1s linear;}
<button onclick="if (cont.style.display != 'none') { cont.classList.add('hidden'); setTimeout('cont.style.display=\'none\'', 1000); } else {cont.style.display='block'; setTimeout('cont.classList.remove(\'hidden\')', 10);}">Click</button>
<div id="cont">
Hello
</div>
A: You can achieve this easily with CSS3
.visible {
visibility: visible;
opacity: 1;
transition: opacity 2s linear;
}
.hidden {
visibility: hidden;
opacity: 0;
transition: visibility 0s 2s, opacity 2s linear;
}
A: Native JS fade function:
var s = document.getElementById('calendarPickerContainer').style;
s.opacity = 1;
(function fade(){(s.opacity-=.1)<0?s.display="none":setTimeout(fade,40)})();
A: You can simplfy this with classList
document.querySelector('.toggle').addEventListener('click',function(e) {
e.target.classList.toggle('hide');
})
Css:
div {
transition:all 0.3s ease-in;
}
.hide {
opacity: 0;
}
We're using opacity since display cannot be animated.
Example
| |
doc_971
|
**SBU **SBU_Users
*id | *SBU_Name *users_id | *sbu_id
1 | SBU1 1 | 3
:
4 | SBU4
And this my code:
$query = "SELECT sbu.SBU_Name, sbu_users.sbu_id FROM sbu, sbu_users WHERE sbu_users.sbu_id=sbu.id AND sbu_users.users_id=".$users_id."";
$result = mysql_query($query, $db) or die (mysql_error($db));
while ($row = mysql_fetch_array($result))
{
extract($row);
}
echo "<select name=sbuuser>";
echo "<option value='1' ";if ($sbu_id==1){echo "selected";} else {echo "";}echo ">SBU1</option>";
echo "<option value='2' ";if ($sbu_id==2){echo "selected";} else {echo "";}echo ">SBU2</option>";
echo "<option value='3' ";if ($sbu_id==3){echo "selected";} else {echo "";}echo ">SBU3</option>";
echo "<option value='4' ";if ($sbu_id==4){echo "selected";} else {echo "";}echo ">SBU4</option>";
I have a problem in selecting the right SBU_Name, because my code keeps selecting the last SBU_Name. Please help me.
A: Maybe something like this?
$query = "SELECT sbu.SBU_Name, sbu_users.sbu_id FROM sbu, sbu_users WHERE sbu_users.sbu_id=sbu.id AND sbu_users.users_id=".$users_id."";
$result = mysql_query($query, $db) or die (mysql_error($db));
echo "<select name=sbuuser>";
while ($row = mysql_fetch_array($result))
{
extract($row);
echo "<option value='1' ";if ($sbu_id==1){echo "selected";} else {echo "";}echo ">SBU1</option>";
echo "<option value='2' ";if ($sbu_id==2){echo "selected";} else {echo "";}echo ">SBU2</option>";
echo "<option value='3' ";if ($sbu_id==3){echo "selected";} else {echo "";}echo ">SBU3</option>";
echo "<option value='4' ";if ($sbu_id==4){echo "selected";} else {echo "";}echo ">SBU4</option>";
}
echo "</select>";
| |
doc_972
|
for example :
line a = 1365
line b = 3487
How would I write a code that tells me that 3 is in line a and in line b but not in the same position
| |
doc_973
|
Example:
Input: Hello There, General Kenobie!
Output: xxxxx There, xxxxxxx Kenobie!
I can get this to work if I replace it with a preset string:
const text = "'Hello' There, 'General' Kenobie!"
const pattern = /(?:'([^']*)')|(?:"([^"]*)")/g;
console.log(text.replace(pattern, "xxx"));
Output: xxx There, xxx Kenobie!
What am I missing wrapping my head around.
Thanks!
A: You are using a hard-coded string of 'xxx' as your replacement string. So, that's what you are seeing... the string(s) replaced with 'xxx'.
The .replace() method actually supports a function as the replacement, instead of a string, so that's what you need here.
Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter
const text = "'Hello' There, 'General' Kenobie!"
const pattern = /(?:'([^']*)')|(?:"([^"]*)")/g;
const newText = text.replace(pattern, (str, m) => 'x'.repeat(m.length));
console.log(newText);
A: You can always loop through the matches and replace each separately.
let text = "'Hello' There, 'General' Kenobie!"
const pattern = /(?:'([^']*)')|(?:"([^"]*)")/g;
let array1;
while ((array1 = pattern.exec(text)) !== null) {
wrap = array1[0][0];
text = text.replace(array1[0],wrap + "x".repeat(array1[0].length-2) + wrap);
}
console.log(text)
| |
doc_974
|
file.txt is input file which contains executable root files with their paths, others are output. My problem is I have almost 30 input files and i do not want to write down the command each time to run the code. Bash script would be nice but I did not manage. It gives an error. see an example of the code below, I try to run:
#!/bin/bash
do
echo
./analyze runlist1.txt runlist1.root log1.txt
./analyze runlist2.txt runlist2.root log.txt
./analyze runlist3.txt runlist3.root log.txt
./analyze runlist4.txt runlist4.root res4.txt
done
I get the error "syntax error near unexpected token `do' ", Any help would be appreciated.
A: Like others indicated in comments, the do out of context is a syntax error (it is a valid keyword right after a for, while, and until control statement).
Apparently, there is no systematic mapping between input file names and the corresponding log file names, so you need a script which maintains this mapping. Something like this, then:
while read suffix logfile; do
./analyze "runlist$suffix.txt" "runlist$suffix.root" "$logfile"
done <<'____HERE'
1 log1.txt
2 log.txt
3 log.txt
4 res4.txt
____HERE
The here document (the stuff between << delimiter and the delimiter alone on a line) is just like a text file, except it is embedded as part of the script.
A: Check it out the primitive but the modified version.
!/bin/bash
for file in Brunsplit1.txt Brunsplit2.txt
do
echo $file
./analyze Brunsplit1.txt runlist1.root res1.txt
./analyze Brunsplit2.txt runlist2.root res2.txt
done
Thanks.
A: When all files are called Brunsplit.txt, the following will help
for file in Brunsplit*.txt; do
tmp=${file%.txt}
nr=${tmp#Brunsplit}
./analyze ${file} runlist${nr}.root res${nr}.txt
done
The tmp and nr vars are filled with special syntax, it is something like cutting off .txt at the end and Brunsplit from the start.
| |
doc_975
|
Now I want to disable a particular day, i.e., If Monday is holiday or something, the user can not select any event on that day.
For that I want to disable the whole day, Because of that reason, the user can't select any timeslot.
Thanks in advance
A: First thing I would do is tap into your dayPropGetter to apply some sort of class or style, showing the user if that date is unavailable. The next thing I would do is tap into your onSelectSlot to check the start/end dates on selection, and just return 'false' from the method if it's outside your acceptance boundaries.
| |
doc_976
|
Model:
public class A {
int id;
string name;
byte[] data;
}
API:
[HttpGet]
[Route("~/api/getdata")]
public IActionResult GetData()
{
A a = new A
{ id= 1,
name = "JOHN",
data = { 0, 0, 0, 25 }
};
return Ok(a);
}
When I call the same API in my angular application as:
getData(): Observable<A> {
return this.http.get<A>(`${API_URL}/api/getdata`).pipe(
map(data => data)
);
}
I have defined the same model A in my Client Side as well:
A:
export interface A {
id: number;
name: string;
data: ArrayBuffer;
}
But when I am calling the API the data is getting converted to base64 encoded string.
Is there a way so that I get Array Buffer only and I need not to write any extra method for conversion from base 64 string to Array Buffer.
I tried using :
getData(): Observable<A> {
const httpOptions = {
'responseType': 'arraybuffer' as 'json'
};
return this.http.get<A>(`${API_URL}/api/getdata`, httpOptions).pipe(
map(data => data)
);
}
but it's converting complete response to array buffer, where as I want arraybuffer just for data which is ArrayBuffer type.
A: In respect of you comment
@MoxxiManagarm The problem is I have 200MB of data in array buffer, so at front end side, converting the base 64 string to array buffer is crashing my browser.
This is a serious architecture issue then. No one should transfer 200MB of data in a json. Please think about providing the id of the data only and concat another requests with a respective response type (arraybuffer or blob) to retrieve the data.
See also: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data
| |
doc_977
|
Here is my code sample:
trigger:
- development
schedules:
- cron: '0 0 * * *' # will run midnight every day
displayName: 'Midnight tests' (UTC - 7:00)'
branches:
include:
- development
always: true
stages:
### do some work
A: We could add task bash and enter script printenv to print all pipeline env variable. Then we could see the variable BUILD_REASON, we can track this variable to check how the build pipeline is triggered.
Schedule is trigger from cron, IndividualCI is trigger from commit push. You could check the pic below.
| |
doc_978
|
I have an array in json format and i want to access its value in my different form fields
{"title":"title2","assessment_type":"type2","no_of_words":"250","deadline":"2017-01-04"}
how can i get the values i have wasted a whole day for this please help
i am saving session like this
$order = new Order();
$order->title = $request->get('subject');
$order->assessment_type = $request->get('assessment_type');
$order->no_of_words = $request->get('no_of_words');
$order->deadline = $request->get('date');
Session::put('order_info', $order);
return redirect()->route('update-order');
for getting i have tried
{{Session::get("order_info")[$title]}},
{{ json_decode(Session::get('order_info')->title) }},
{{ in_array('order_info', $title)}}
all in vain please help
| |
doc_979
|
prompt = "Enter the key and value of a dictionary like this: 'key:value':"
list = [];list_rev = [];i = 0
while True:
element = raw_input(prompt).strip().split(':')
if element == ['.']:
break
list.append([]);list_rev.append([])
print element
print list(reversed(element))
list[i] = element
list_rev[i] = list(reversed(element))
i += 1
print 'The dictionary you input is:'
print dict((list))
print '\nThe dictionary whose key and value are reversed is:'
print dict((list_rev))
dictrev()
This is the code of the question in Core Python Programming 7-7.
However, when I run the program, I got a TypeError: 'list' object is not callable in the code
print list(reversed(element))
What I have done are as follows:
*
*search the 'list is not callable' topic in Stackoverflow and google, but I don't get the method;
*goole the method of list() and reversed(), but I don't think there is anything wrong with my code
*print the variable element, element_reversed and the type of element.
*take the code alone in another program like this:
l = ['a','b']
print l
print list(reversed(l))
there is nothing wrong like 'list object is not callable.' I am puzzled!!!
I have done what I can do to solve this problem. Thanks for everyone's help.
A: Look at this line:
list = []
You overrode the built in type list
| |
doc_980
|
public class ProfileFragment extends Fragment {
private DatabaseReference mUserDatabase;
private FirebaseUser mCurrentUser;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_profile, container, false);
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
}
On the mCurrentUser = FirebaseAuth.getInstance().getCurrentUser(); i am getting the error unreachable statement is there any way that i can still use a fragment for this activity?
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_profile, container, false);
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
String current_uid = Objects.requireNonNull(mCurrentUser).getUid();
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid);
ValueEventListener valueEventListener = mUserDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("name").getValue().toString();
String image = dataSnapshot.child("image").getValue().toString();
String status = dataSnapshot.child("status").getValue().toString();
String thumb_image = dataSnapshot.child("thumb_image").getValue().toString();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
return view;
});}}
error on return view;
A: Update this
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_profile, container, false);
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
}
To
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile, container, false);
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
String current_uid = Objects.requireNonNull(mCurrentUser).getUid();
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid);
ValueEventListener valueEventListener = mUserDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("name").getValue().toString();
String image = dataSnapshot.child("image").getValue().toString();
String status = dataSnapshot.child("status").getValue().toString();
String thumb_image = dataSnapshot.child("thumb_image").getValue().toString();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
// you are calling return view inside the Value Listner that why you are getting the error
});
return view;
}
A: Just move mCurrentUser = FirebaseAuth.getInstance().getCurrentUser() line before return statement.
A: Move the below line before return statment in onCreateView() method.
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
Anything after return statement is unreachable, as error statement states.
A: Let onActivityCreated() method handles additional job.
ValueEventListener is an inner class of DatabaseReference, hence, you don't necessary need to create object before instantiating it. So, remove the line.
Also, be reminded that return view; should be the last statement in your onCreateView(). Make sure that before closing it you have return statement.
Now do this. After onCreateView(), create another copy and past the below code.
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mUserDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("name").getValue().toString();
String image = dataSnapshot.child("image").getValue().toString();
String status = dataSnapshot.child("status").getValue().toString();
String thumb_image =
dataSnapshot.child("thumb_image").getValue().toString();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
});
}
| |
doc_981
|
i want that if notification came on the IOS device then the image in the notification will show accordingly
A: this text from iOS Human Interface Guidelines
A banner is a small translucent view that appears onscreen and then disappears after a few seconds. Users can also see a version of the banner on the lock screen and in the Notifications view of Notification Center. In the banner, iOS displays your notification message and the small version of your app icon (to learn more about the small app icon, see App Icon). Users tap the banner to dismiss it and switch to the app that sent the notification.
I believe that you can't change it, but may be if you change some pictures in App icon source, you will achieve the necessary result, but I repeat, hardly everything will correctly work
for example
U can try to change Spotlight images or any else....
| |
doc_982
|
A: Not that I've ever done it - by my approach would be to:
In your full screen 'mode' do this:
switch off the form border
set controlbox to false (gets rid of the titlebar and top-left window menu)
make the menu/toolstrip invisible.
This is done with the 'Visible' property of those controls.
Now, you should be able to set the window state of the form to Maximized.
EDIT - Code Sample:
Paste this into the code file of a new forms app
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.ControlBox = false;
this.FormBorderStyle = FormBorderStyle.None;
this.WindowState = FormWindowState.Maximized;
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
//example of how to programmatically reverse the full-screen.
//(You will have to add the event handler for KeyDown for this to work)
//if you are using a Key event handler, then you should set the
//form's KeyPreview property to true so that it works when focus
//is on a child control.
if (e.KeyCode == Keys.Escape)
{
this.ControlBox = true;
this.FormBorderStyle = FormBorderStyle.Sizable;
this.WindowState = FormWindowState.Normal;
}
}
}
A: In addition to that, before maximizing, do this:
this.TopMost = true;
...to put your control over the windows bottom panel and start button (basically this will fill the entire screen).
A: I would programmatically change UI, hiding all container panels except the work-area container panel, where user control is located.
| |
doc_983
|
cvs -z3 -d :pserver:anoncvs@sourceware.org:/cvs/src co gdb
... cvs creates a directory 'src' at the path where it is called from, and checks out all the files from cvs/src in there..
In svn, you can do something like (pseudocode)
svn co http://.../TheProject LocalProjectName
... in which case, svn creates a directory 'LocalProjectName' at the path where it is called from, and checks out all the files from .../TheProject in there..
Is there a similar option for cvs (so that the top-level local directory has a different name from that in the repository?)
Thanks in advance for any answers,
Cheers!
A: cvs co -d LocalProjectName TheProject
This will check out a repository named TheProject into a directory named LocalProjectName.
| |
doc_984
|
function showDateTime() {
var myDiv = document.getElementById("time");
var event = new Date();
console.log(event.toLocaleString('en-GB', { timeZone: 'Europe/London' }));
I've shared this with some friends in the US and the time is showing local to them rather than the UK/time.
https://jsfiddle.net/xgwsk2b3/
A: With Intl API https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl
https://jsfiddle.net/danailvidev/vmo6cyh2/1/
function showDateTime() {
var date = new Date();
var formatter = new Intl.DateTimeFormat('en-GB', {
dateStyle: 'full',
timeStyle: 'long',
});
console.log(formatter.format(date));
}
setInterval(showDateTime, 1000);
// "Thursday, 6 January 2022 at 12:00:24 GMT"
A: UTC solves your problem:
*
*https://www.google.com/search?q=uk+utc+time
*https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC
I live in Germany and UTC+1 is my timezone, for the UK you need UTC+0
| |
doc_985
|
5000001 \t 1133938 \t 1273719 \t 2008-06-01 00:03:35.0
I want to take the last value (2008-06-01 00:03:35.0) and extract the month. Loading it as a DateTime produces a blank field. So I want to import it as a chararray and then use toDate to turn it into dateTime field that I can use getMonth on.
when I try in the shell I get this:
grunt> orders = load '/home/cloudera/Desktop/orders1' using PigStorage('\t') AS (orderID:int, cusID:int, productId:chararray, time:chararray);
grunt> to_date = FOREACH orders GENERATE toDate(time,'yyyy-MM-dd HH:mm:ss.S') as (dTime:DateTime), cusID;
2017-04-19 01:13:46,206 [main] ERROR org.apache.pig.tools.grunt.Grunt - ERROR 1070: Could not resolve toDate using imports: [, java.lang., org.apache.pig.builtin., org.apache.pig.impl.builtin.]
Details at logfile: /home/cloudera/pig_1492588751037.log
The log file contains this:
ERROR 1070: Could not resolve toDate using imports: [, java.lang.,
org.apache.pig.builtin., org.apache.pig.impl.builtin.]
Failed to parse: Pig script failed to parse: <line 9, column 34>
Failed to generate logical plan. Nested exception:
org.apache.pig.backend.executionengine.ExecException: ERROR 1070:
Could not resolve toDate using imports: [, java.lang.,
org.apache.pig.builtin., org.apache.pig.impl.builtin.] at
org.apache.pig.parser.QueryParserDriver.parse(QueryParserDriver.java:196)
at org.apache.pig.PigServer$Graph.validateQuery(PigServer.java:1660)
at org.apache.pig.PigServer$Graph.registerQuery(PigServer.java:1633)
at org.apache.pig.PigServer.registerQuery(PigServer.java:587) at
org.apache.pig.tools.grunt.GruntParser.processPig(GruntParser.java:1093)
at
org.apache.pig.tools.pigscript.parser.PigScriptParser.parse(PigScriptParser.java:501)
at
org.apache.pig.tools.grunt.GruntParser.parseStopOnError(GruntParser.java:198)
at
org.apache.pig.tools.grunt.GruntParser.parseStopOnError(GruntParser.java:173)
at org.apache.pig.tools.grunt.Grunt.run(Grunt.java:69) at
org.apache.pig.Main.run(Main.java:547) at
org.apache.pig.Main.main(Main.java:158) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606) at
org.apache.hadoop.util.RunJar.run(RunJar.java:221) at
org.apache.hadoop.util.RunJar.main(RunJar.java:136) Caused by: <line
9, column 34> Failed to generate logical plan. Nested exception:
org.apache.pig.backend.executionengine.ExecException: ERROR 1070:
Could not resolve toDate using imports: [, java.lang.,
org.apache.pig.builtin., org.apache.pig.impl.builtin.] at
org.apache.pig.parser.LogicalPlanBuilder.buildUDF(LogicalPlanBuilder.java:1507)
at
org.apache.pig.parser.LogicalPlanGenerator.func_eval(LogicalPlanGenerator.java:9372)
at
org.apache.pig.parser.LogicalPlanGenerator.projectable_expr(LogicalPlanGenerator.java:11051)
at
org.apache.pig.parser.LogicalPlanGenerator.var_expr(LogicalPlanGenerator.java:10810)
at
org.apache.pig.parser.LogicalPlanGenerator.expr(LogicalPlanGenerator.java:10159)
at
org.apache.pig.parser.LogicalPlanGenerator.flatten_generated_item(LogicalPlanGenerator.java:7488)
at
org.apache.pig.parser.LogicalPlanGenerator.generate_clause(LogicalPlanGenerator.java:17590)
at
org.apache.pig.parser.LogicalPlanGenerator.foreach_plan(LogicalPlanGenerator.java:15982)
at
org.apache.pig.parser.LogicalPlanGenerator.foreach_clause(LogicalPlanGenerator.java:15849)
at
org.apache.pig.parser.LogicalPlanGenerator.op_clause(LogicalPlanGenerator.java:1933)
at
org.apache.pig.parser.LogicalPlanGenerator.general_statement(LogicalPlanGenerator.java:1102)
at
org.apache.pig.parser.LogicalPlanGenerator.statement(LogicalPlanGenerator.java:560)
at
org.apache.pig.parser.LogicalPlanGenerator.query(LogicalPlanGenerator.java:421)
at
org.apache.pig.parser.QueryParserDriver.parse(QueryParserDriver.java:188)
... 16 more Caused by:
org.apache.pig.backend.executionengine.ExecException: ERROR 1070:
Could not resolve toDate using imports: [, java.lang.,
org.apache.pig.builtin., org.apache.pig.impl.builtin.] at
org.apache.pig.impl.PigContext.resolveClassName(PigContext.java:653)
at
org.apache.pig.impl.PigContext.getClassForAlias(PigContext.java:769)
at
org.apache.pig.parser.LogicalPlanBuilder.buildUDF(LogicalPlanBuilder.java:1504)
... 29 more
A: Pig function names are case-sensitive. It is ToDate().
grunt> to_date = FOREACH orders GENERATE ToDate(time,'yyyy-MM-dd HH:mm:ss.S') as (dTime:DateTime), cusID;
| |
doc_986
|
I have a one-to-one relationship between a User class and a Shop class and the foreign key shopId in the User table but when i try to fetch the user the shop related to it is not being fetched what should I do?
My User class is as follows:
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column('text')
name: string;
@Column('text')
email: string;
@Column('text')
phoneNumber: string;
@Column('text')
password: string;
@Column('boolean')
isAdmin: boolean;
@OneToOne(() => Shop, (shop) => shop.user)
@JoinColumn()
shop: Shop;
constructor(
name: string,
email: string,
phoneNumber: string,
password: string,
) {
this.name = name;
this.email = email;
this.phoneNumber = phoneNumber;
this.password = password;
}
}
My Shop class is as follows:
export class Shop {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@OneToOne(() => User, (user) => user.shop) // specify inverse side as a second parameter
user: User;
@OneToMany(() => Order, (order) => order.shop)
orders: Order[];
@OneToMany(() => Product, (product) => product.shop)
products: Product[];
constructor(name: string) {
this.name = name;
}
the function in UserService that fetches the needed User is:
export class UserService {
constructor(
@InjectRepository(User)
private userRepository: Repository<User>,
private dataSource: DataSource,
) {}
findOneByPhoneNumber(phoneNumber: string): Promise<User> {
return this.userRepository.findOneBy({ phoneNumber });
}
...
}
when the function returns a user the shop related to it is not there and only the other fields in the user class are sent.
this is what am getting:
{
name: 'test',
email: 'test@gmail.com',
phoneNumber:'+251912345678',
password: '$2b$10$Q5FR7cleRkJebMPy.cPWIuPLQrNTMB3kxXWXPiRlFH99U4WfFqyd6',
id: 1,
isAdmin: false
}
but i was expecting the related shop object to be in the response as well, what am i missing or doing wrong here?
A: had to change the function in the UserService class to
findOneByPhoneNumber(phoneNumber: string): Promise<User> {
return this.userRepository.findOne({
relations: { shop: true },
where: { phoneNumber },
});
}
and the result was as follows
{
name: 'Ameen Zuber',
email: 'ameen.oumer@gmail.com',
phoneNumber: '+251939881843',
password: '$2b$10$Q5FR7cleRkJebMPy.cPWIuPLQrNTMB3kxXWXPiRlFH99U4WfFqyd6',
id: 1,
isAdmin: false,
shop: Shop { name: 'Box', id: 1 }
}
| |
doc_987
|
The below shown code creates three strings which should be forwarded to a ZeroMQ PUSH socket. However, it only sends the live_trades string via the socket. Both the account_info and the historical_trades strings are not sent.
While debugging the weirdness only increased:
*
*When I print the historical_trades string, it is shown in the MT4 expert journal, but not in the MT4 log editor
*When I add Print( historical_trades ) before or after the pushSocket.send(StringFormat("%s", historical_trades, true)); it sends the string.
Possible issues which I actually exclude:
*
*The PUSH socket is too slow: I decreased the timer to 10 seconds and more, same result
*MT4 itself is too slow to create the strings: It prints them correctly, so it is fast enough
*The ZeroMQ SNDHWM ( HighWaterMark ) blocks the EA/socket from sending multiple strings in no time: Already increased it to 100 which should be more than sufficient
Any other ideas I cannot verify with debugging:
*
*The MT4 Print() function does some other stuff behind the scenes which enables the EA to send the string?
*Maybe there is a maximum string size in MT4 which blocks the string creation loop (my string is around 35.000 characters long). But then why does it work when I just Print() the string once within the onTimer() function?...
*Any chance that the account related information is not accessible on weekends?
Or it is just my code which might be buggy..
Any ideas much appreciated!
int OnInit()
{
//---
EventSetTimer(2); // Set Second Timer as push intervall
context.setBlocky(false);
// Send data to PULL_PORT that consumer is listening to.
Print("Connecting MT4 Dashex Feeder to Dashboard on Port " + IntegerToString(PUSH_PORT) + "..");
pushSocket.connect(StringFormat("%s://%s:%d", ZEROMQ_PROTOCOL, HOSTNAME, PUSH_PORT));
pushSocket.setSendHighWaterMark(100);
pushSocket.setLinger(0);
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
Print("Disconnecting MT4 Dashex Feeder on Port " + IntegerToString(PUSH_PORT) + "..");
pushSocket.disconnect(StringFormat("%s://%s:%d", ZEROMQ_PROTOCOL, HOSTNAME, PUSH_PORT));
// Shutdown ZeroMQ Context
context.shutdown();
context.destroy(0);
EventKillTimer();
}
//---
//+------------------------------------------------------------------+
//| Expert timer function |
//+------------------------------------------------------------------+
void OnTimer()
{
/*
1.) Account information
*/
string account_info = "";
account_info = account_info +
"account_info|" +
version + "|" +
DID + "|" +
IntegerToString(AccountNumber()) + "|" +
AccountInfoString(ACCOUNT_COMPANY) + "|" +
IntegerToString(AccountInfoInteger(ACCOUNT_LEVERAGE)) + "|" +
DoubleToString(AccountInfoDouble(ACCOUNT_BALANCE),2) + "|" +
DoubleToString(AccountInfoDouble(ACCOUNT_PROFIT),2) + "|" +
DoubleToString(AccountInfoDouble(ACCOUNT_EQUITY),2) + "|" +
DoubleToString(AccountInfoDouble(ACCOUNT_MARGIN),2) + "|" +
DoubleToString(AccountInfoDouble(ACCOUNT_MARGIN_FREE),2) + "|" +
DoubleToString(AccountInfoDouble(ACCOUNT_MARGIN_LEVEL),2) + "|" +
AccountInfoString(ACCOUNT_CURRENCY) + "|" +
IntegerToString(IsDemo()) + "|" +
pushSocket.send(StringFormat("%s", account_info, true));
Print("Pushing Account Information To Dashex.Finance Dashboard For Account No. " + IntegerToString(AccountNumber()));
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
/*
2.) Pending and running trades
*/
int live_orders = OrdersTotal();
string live_trades = "";
for(int i=live_orders; i >= 0; i--)
{
if(OrderSelect(i,SELECT_BY_POS)==false) continue;
live_trades = live_trades +
"live_trades|" +
version + "|" +
DID + "|" +
IntegerToString(AccountNumber()) + "|" +
IntegerToString(OrderTicket()) + "|" +
TimeToString(OrderOpenTime(), TIME_DATE|TIME_SECONDS) + "|" +
TimeToString(OrderCloseTime(), TIME_DATE|TIME_SECONDS) + "|" +
IntegerToString(OrderType()) + "|" +
DoubleToString(OrderLots(),2) + "|" +
OrderSymbol() + "|" +
DoubleToString(OrderOpenPrice(),5) + "|" +
DoubleToString(OrderClosePrice(),5) + "|" +
DoubleToString(OrderStopLoss(),5) + "|" +
DoubleToString(OrderTakeProfit(),5) + "|" +
DoubleToString(OrderCommission(),2) + "|" +
DoubleToString(OrderSwap(),2) + "|" +
DoubleToString(OrderProfit(),2) + "|" +
"<" + OrderComment() + ">|";
}
pushSocket.send(StringFormat("%s", live_trades, true));
Print("Pushing Live Trades To Dashex.Finance Dashboard For Account No. " + IntegerToString(AccountNumber()));
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
/*
3.) History Trades
*/
int hstTotal = OrdersHistoryTotal();
string historical_trades = "";
Print(hstTotal);
for(int i=hstTotal; i >= 0; i--)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false) continue;
historical_trades = historical_trades +
"historical_trades|" +
version + "|" +
DID + "|" +
IntegerToString(AccountNumber()) + "|" +
IntegerToString(OrderTicket()) + "|" +
TimeToString(OrderOpenTime(), TIME_DATE|TIME_SECONDS) + "|" +
TimeToString(OrderCloseTime(), TIME_DATE|TIME_SECONDS) + "|" +
IntegerToString(OrderType()) + "|" +
DoubleToString(OrderLots(),2) + "|" +
OrderSymbol() + "|" +
DoubleToString(OrderOpenPrice(),5) + "|" +
DoubleToString(OrderClosePrice(),5) + "|" +
DoubleToString(OrderStopLoss(),5) + "|" +
DoubleToString(OrderTakeProfit(),5) + "|" +
DoubleToString(OrderCommission(),2) + "|" +
DoubleToString(OrderSwap(),2) + "|" +
DoubleToString(OrderProfit(),2) + "|" +
"<" + OrderComment() + ">|";
}
pushSocket.send(StringFormat("%s", historical_trades, true));
Print("Pushing History Trades To Dashex.Finance Dashboard For Account No. " + IntegerToString(AccountNumber()));
Sleep(1);
}
MetaTrader 4 log.editor:
MetaTrader 4 console:
A:
Q : Any chance that the account related information is not accessible on weekends?
This has an easy proof: do a Comment( aStringUnderTEST ); + check all account / Broker-related items.
Q : Maybe there is a maximum string size in MT4 which blocks the string creation loop...?
This is, except a case of an MT4-Build-X.Y.Z release-bug awaiting a BugFIX, very low probability hypothesis.
Yet it has an easy proof: do a loop of growing string-lengths and test until what size the processing keeps working. The indirectly proved size-limit will help you track the root cause, MT4 not being the SPoF here, is it?
Q : The MT4 Print function does some other stuff behind the scenes which enables the EA to send the string?
The MT4 Support ought be contacted if this is to get confirmed or denied. The software is licensed as an as-is product, so do not expect any rapid response or a rocket science to take place if you try to drill down to the bolts and nuts, inside their closed and sealed product.
| |
doc_988
|
a b c d Tot
1 2 3 3 2 10
2 3 4 2 3 12
3 4 2 5 3 14
4 4 3 5 1 13
The dput version is as follows:
structure(list(a = c(2L, 3L, 4L, 4L), b = c(3L, 4L, 2L, 3L),
c = c(3L, 2L, 5L, 5L), d = c(2L, 3L, 3L, 1L), Tot = c(10L,
12L, 14L, 13L)), .Names = c("a", "b", "c", "d", "Tot"), class = "data.frame", row.names = c(NA,
-4L))
I want to iterate through each row of the Tot column and if the value is greater than 9, I want to reduce the value of column a to 1, take the sum of row 1 again. If the value of Tot is still greater than nine, reduce the value of column b to 1 and take the total of row 1 again. if the value of column Tot is 9, move to the second row to repeat the process.
I tried using the While loop, for loop with an if condition, i am getting errors. Most commonly,
In while (test$Tot > 9) { ... :
the condition has length > 1 and only the first element will be used
For loop:
for (i in 1:nrow(test)) {
if (test$Tot[i] > 9) {
ifelse(test$a[i] > 1, 1, test$a[i])
test$Tot[i] <- apply(test[,c(1:4)][i], 1, sum)
}
}
Thought if this iteration works for the first column can extend it to subsequent columns till such time that the Tot column value is 9. But I am getting the following error:
In test$Tot[i] <- apply(test[, c(1:4)][i], 1, sum) :
number of items to replace is not a multiple of replacement length
Another version of the forloop:
for (i in 1:nrow(test)) {
if (test$Tot[i] > 9) {
test$a[i] <- ifelse(test$a[i] > 1, 1, test$a[i])
test$Tot[i] <- apply(test[,c(1:4)][i], 1, sum)
}
}
While this changes the value of column a to 1 and and resets the value of column Tot to 9 but the sum function doesn't seem to work.
A: This does the trick, although it may be slow with big data:
for(i in 1:nrow(df)){
for(j in 1:(ncol(df)-1)){
df[i, j] <- ifelse(df[i, ncol(df)] > 9, 1, df[i, j])
df[i, ncol(df)] <- rowSums(df[i, 1:(ncol(df)-1)])
}
}
Basically, you iterate through every row in the outer loop, and through every cell except Tot in the inner loop, and check whether Tot is > 10, if so set the cell to 1, recalculate Tot in this row, and move on to the next cell.
Result:
> df
a b c d Tot
1 1 3 3 2 9
2 1 1 2 3 7
3 1 1 1 3 6
4 1 1 5 1 8
The code works with any amount of columns and rows, only necessity is that Tot is the last column in the data.
| |
doc_989
|
Is there a better Base64 code such as avoiding Byte[]? What is best practice for url to filename? I suppose there's an issue with exceeding filename length limit.
string encoded =
System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(url));
string decoded =
System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(encoded));
if (decoded != url)
throw(new SomeException());
A: I would say that the best practice is that if possible, the filename hould not have a direct relation with the URL. Unless you control the URL's with which this method will be called, you open yourself upon to a security danger. It would be best if you could generate some local ID, use that as the filename and then link that ID to the URL. That way you are always completely in control on what filenames are being written, whereas using the URL opens you up to potential attackers.
A: If/when you need to translate the name back to the original Url you might want to create a separate mapping table. Generate a unique file name and store it in the table with the original Url next to it. You could use an API (Guid, Random, DateTime) or a simple counter to get a unique file name.
This way do do not have to worry about duplicates and illegal characters because you are in control of the file name generation.
As you are caching JSON request/responses be care full with POSTs: the urls of two requests might be the same but the contents might be different so you might not want to use the cache for the first one for the next.
In general you wouldn't cache POST's but some REST APIs use POSTs to bypass the maximum Url GET request length.
| |
doc_990
|
A: http://repo.typesafe.com/typesafe/releases/com/typesafe/play/anorm_2.11/
or
http://repo.typesafe.com/typesafe/maven-releases/com/typesafe/play/anorm_2.11/
libraryDependencies ++= Seq(
jdbc,
// anorm,
"com.typesafe.play" % "anorm_2.11" % "2.3.2",
"mysql" % "mysql-connector-java" % "5.1.31"
)
I'm not sure that this version compatible with 2.3.1
A: It should be in "com.typesafe.play" %% "anorm" % "2.3.2" . It was merge by last June and 2.3.2 was released in July. Otherwise you may need to consider cleaning your ivy/m2 repository to be sure you don't have some obselete libraries on the way.
| |
doc_991
|
The application main purpose is to allow a customer to view/edit different kind of items, each item view being a more or less complicated form.
To make sure everything works right I am planning to do:
*
*unitary tests using QUnit
*functional/integration tests
What frameworks/tools do you recommend for integration testing in this case ? I started with Selenium but I didn't like it too much. I just started to look at PhantomJS and CasperJS and they seem pretty nice for basic stuff like navigating, clicking on links, ...
What's your advice ?
A: You didn't say what you didn't like about Selenium, but I'm guessing you are confident with JavaScript, so my recommendation would be to use CasperJS as the main tool. It does work well with one-page web apps, and comes with its own testing tool. The code can still get a bit convoluted at times, when using nested wait clauses; deal with that by making sure you don't try to do too much in each test, and then if still complex, refactor. And don't forget design-for-testing: if your selector is horribly complex, consider adding a <span id="xxxx">...</span> around it, so your tests can go straight to it!
You can use CasperJS with both PhantomJS and SlimerJS. My preference is for SlimerJS currently, as:
*
*PhantomJS 1.x is stuck on an old WebKit (equivalent to Safari 5.1 and Chrome 13), so testing any more modern features is frustrating.
*SlimerJS can either work with the Gecko engine, or directly with a version of Firefox you have installed. This allows you to configure a Firefox profile with extra plugins, security certificates, etc.
*SlimerJS is written in JavaScript, so easier to hack if you have the need.
Once PhantomJS 2.0 comes out (around the end of 2013, hopefully), or if your site does not rely on any recent HTML5 APIs, you can run CasperJS twice, to get double coverage. (BTW, PhantomJS is naturally headless; SlimerJS needs to use Xvfb, which is Linux or Mac only.)
What Selenium gives you extra is you can control other browsers, IE in particular. (Though of course for IE you need to run a Windows machine.) Selenium, like SlimerJS, needs Xvfb to be headless (again, excluding Windows). (BTW, the Selenium docs on supported browsers has not been updated in ages, but I'm assuming later versions of each browser have at least the same support shown there.)
| |
doc_992
|
//time is a variable used in my code
UIView.animate(withDuration: time, delay: 0, options: [.curveLinear, .allowUserInteraction], animations: {
//this class is ofType UIScrollView
self.setContentOffset(CGPoint(x: self.contentSize.width-self.frame.width, y: 0), animated: false)
//Completion Handler
}, completion: { finished in
//It's always true, not sure a way to fix this
if(finished ) {
But, later in my code, I have a method to remove certain animations, specifically from this scrollView.
self.layer.removeAllAnimations()
It gets called, and I would assume it is suppose to make the above
if(finished ) { //Here
return false, therefore it should not go inside the finished. But, finished is ALWAYS true. Whether I cancel this animation, continue the animation, doesn't matter what I do to the animation, the completion handler is always true. Any tips on this matter?
A: Your call to setContentOffset specifies animated:false, if that is the only property you are changing, then there are no actual animations going on, so the call to .animate(...) will always complete with a value of true. If you set this property (or another one) with animated:true and your duration is too short for the animation to finish, then it could complete with a false value for the parameter.
| |
doc_993
|
11-14 17:47:33.332: E/chromium(32126): [ERROR:layer_tree_host_impl.cc(2206)] Forcing zero-copy tile initialization as worker context is missing
11-14 17:47:35.954: E/chromium(32126): [ERROR:xwalk_autofill_client.cc(121)] Not implemented reached in virtual void xwalk::XWalkAutofillClient::OnFirstUserGestureObserved()
11-14 17:47:36.064: E/chromium(32126): [ERROR:xwalk_autofill_client.cc(121)] Not implemented reached in virtual void xwalk::XWalkAutofillClient::OnFirstUserGestureObserved()
11-14 17:47:36.555: E/AndroidRuntime(32126): FATAL EXCEPTION: pool-2-thread-1
11-14 17:47:36.555: E/AndroidRuntime(32126): Process: com.ionicframework.coopiapp955107, PID: 32126
11-14 17:47:36.555: E/AndroidRuntime(32126): java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.ionicframework.coopiapp955107-1/base.apk"],nativeLibraryDirectories=[/data/app/com.ionicframework.coopiapp955107-1/lib/arm, /vendor/lib, /system/lib]]] couldn't find "libsqlc-native-driver.so"
11-14 17:47:36.555: E/AndroidRuntime(32126): at java.lang.Runtime.loadLibrary(Runtime.java:367)
11-14 17:47:36.555: E/AndroidRuntime(32126): at java.lang.System.loadLibrary(System.java:988)
11-14 17:47:36.555: E/AndroidRuntime(32126): at io.liteglue.SQLiteConnector.<init>(SQLiteConnector.java:8)
11-14 17:47:36.555: E/AndroidRuntime(32126): at io.sqlc.SQLiteConnectorDatabase.<clinit>(SQLiteConnectorDatabase.java:36)
11-14 17:47:36.555: E/AndroidRuntime(32126): at io.sqlc.SQLitePlugin.openDatabase(SQLitePlugin.java:211)
11-14 17:47:36.555: E/AndroidRuntime(32126): at io.sqlc.SQLitePlugin.access$000(SQLitePlugin.java:32)
11-14 17:47:36.555: E/AndroidRuntime(32126): at io.sqlc.SQLitePlugin$DBRunner.run(SQLitePlugin.java:327)
11-14 17:47:36.555: E/AndroidRuntime(32126): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
11-14 17:47:36.555: E/AndroidRuntime(32126): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
11-14 17:47:36.555: E/AndroidRuntime(32126): at java.lang.Thread.run(Thread.java:818)
11-14 17:47:38.807: E/chromium(32126): [ERROR:runtime_javascript_dialog_manager.cc(70)] Not implemented reached in virtual void xwalk::RuntimeJavaScriptDialogManager::ResetDialogState(content::WebContents*)
A: The problem was solved uninstalling the cordova plugin and installing it again from the repository (justo to get the last version).
The steps I have followed are the following:
1) Open cmd in admin mode.
2) Go to the project root folder.
3) Execute the command cordova plugin list . This will list all the plugins installed. Pay atention to the sqlite-storage one, you will need the name in the following step.
4) Execute cordova plugin remove [pluginName] ("cordova-sqlite-storage" in my case)
5) Install again the plugin with the command:
cordova plugin add https://github.com/litehelpers/Cordova-sqlite-storage
| |
doc_994
|
Hello friends,
I draw a line using canvas.drawPath(mPath, mPaint); method.
but having some problem, i want to get whether line intersect with itself or not.
so please help.
thanks in advance
A: For better performance and UI response create a separate Thread with a Handler and Looper. Also use a HashSet to store the path which tells you of an intersection when you add a position since add() returns a boolean.
Here is some code which should hopefully give better performance.
public class MainActivity extends Activity {
private Handler mHandler;
private String position, lastPosition;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
protected void onResume() {
super.onResume();
Tracker t = new Tracker();
t.start();
}
@Override
protected void onPause() {
if (mHandler != null)
mHandler.getLooper().quit();
super.onPause();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_MOVE:
position = event.getX()+","+event.getY();
if (position.equals(lastPosition)) break;
if (mHandler != null) {
Message msg = Message.obtain();
msg.obj = position;
mHandler.sendMessage(msg);
}
lastPosition = position;
break;
}
return true;
}
private class Tracker extends Thread {
HashSet<String> path = new HashSet<String>();
@Override
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
String position = String.valueOf(msg.obj);
if (!path.add(position))
Log.w("Intersection", position);//Handle the intersection
}
};
Looper.loop();
}
}
}
A: save the coordinates from events
@Override
public boolean onTouchEvent(MotionEvent event) {
event.getX();event.getY()`
}
to a Hashmap and compare
A: I think you're best bet would be to:
1) Keep one path representing what's currently on the canvas, and every time you use canvas.drawPath(nextPath), also add it to your global path and do something like globalPath.addPath(nextPath)
2) Take a look at this post: Collision detection with bitmaps on SurfaceView's canvas in Android. It seems that you should be able to compare the globalPath to the nextPath and tell if they ever collide.
3) If instead you wanted to just know if a single path collides with itself and don't care about adding new paths or anything, we'd need more information on how you're drawing this path. With lines, arcs, circles??
| |
doc_995
|
A:
Is there anything similar to Rails 'Flash Messages' for Dart?
Unfortunately, no. Your question kind of implies that the server is generating HTML in a response to the client. The Web UI team is pretty focused on client-side applications where much of the logic resides on the client. This is pretty different than how Rails works. Hence, we don't ourselves have a framework like Rails that is focused on generating HTML on the server side. Hence, we don't have a feature like flash messages.
Instead, if you build a client-side application, you can use XHR requests to talk to the server, and then the client can decide what message to show to the user without even reloading the page.
| |
doc_996
|
public static int calc(int a, int b) {
if (a >= b)
return a - b;
return 0;
}
I want to know the condition that is used on a known line number. In this case my expected result is the name of the condition, something like ">=".
I know how to parse the CompilationUnit of a given ICompilationUnit. But how can I get the condition(s)?
A: For this you have to create an ASTVisitor which will visit all the infix expressions. In the visitor class the visit method will have the following:
@Override
public boolean visit(InfixExpression node) {
Operator op= node.getOperator();
if(op.equals(Operator.GREATER) || op.equals(Operator.EQUALS) || ....)
conditionalInfixExpressionList.add(node);
return super.visit(node);
}
In the if statement inside of the visit method, you have to check, if the infix expression is a conditional variables and accordingly add it to the list.
| |
doc_997
|
Array(
[4:3] =>Array(
[0] => 800x600
[1] => 1024x768
[2] => 1600x1200
[3] => 2048x1536
)
[16:9] => Array(
[0] => 1366x768
[1] => 1920x1080
)
[Apple] => Array(
[iPad2] => 1024x768
[iPad3] => 2048x1536
)
)
How formatted output should look:
<p>4:3</p>
<ul>
<li><a href="800x600.jpg">800x600</a></li>
<li><a href="1024x768.jpg">1024x768</a></li>
<li><a href="1600x1200.jpg">1600x1200</a></li>
<li><a href="2048x1536.jpg">2048x1536</a></li>
</ul>
<p>16:9</p>
<ul>
<li><a href="1366x768.jpg">1366x768</a></li>
<li><a href="1920x1080.jpg">1920x1080</a></li>
</ul>
<p>Apple</p>
<ul>
<li><a href="1024x768.jpg">iPad2</a></li>
<li><a href="2048x1536.jpg">iPad3</a></li>
</ul>
Problem:
I can iterate through array, but I have no idea how can I get output as shown above.
A: foreach ($arr as $key => $row) {
echo '<p>'. $key .'</p>';
echo '<ul>';
foreach ($row as $v) {
echo '<li><a href="' . $v . '.jpg">' . $v . '</a></li>';
}
echo '</ul>';
}
A: use echo "" and concate it with array values.using . operator
| |
doc_998
|
I am working with a simple Active Directory server and am testing the ability to create a new user and then authenticate that user using the credentials I just set.
I can successfully authenticate an existing user (created via the admin interface on the server); I can create a new user and set the password (see code snippet below); I can find that user successfully
However, when I attempt to authenticate using the credentials I provided, I am getting the
javax.naming.AuthenticationException: [LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db0]
Below is the code to authenticate a user
public UserEntity authenticate ( @NotNull final String username,
@NotNull final String password )
throws NamingException
{
try
{
Hashtable<String, Object> env = new Hashtable<>();
env.put( Context.SECURITY_AUTHENTICATION,"simple" );
env.put( Context.SECURITY_PRINCIPAL, username );
env.put( Context.SECURITY_CREDENTIALS, password );
env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" );
env.put( Context.PROVIDER_URL, "ldaps://<host>:636" );
env.put( Context.SECURITY_PROTOCOL, "ssl" ) ;
LdapContext context = new InitialLdapContext( env, null );
// find the account now that the user is authenticated to
// construct the UserEntity
// note: code for findAccountByAccountName() not included as
// the creation of the context is what generates the
// exception
return findAccountByAccountName( context, "<search-base>", username );
}
}
Here is the code that creates a new user
public static void addUser( @NotNull final String username,
@NotNull final String firstName,
@NotNull final String password )
throws NamingException
{
// Create a container set of attributes
//
Attributes container = new BasicAttributes(true); // case ignore
// Create the object class to add
Attribute objClasses = new BasicAttribute( "objectClass" );
objClasses.add( "top" );
objClasses.add( "person" );
objClasses.add( "organizationalPerson" );
objClasses.add( "user" );
// Assign the username and first name
//
Attribute givenName = new BasicAttribute( "givenName", firstName );
Attribute sAMAccountName = new BasicAttribute( "sAMAccountName", username );
// Make the account active
//
Attribute userAccountControl = new BasicAttribute( "userAccountControl", "512" ) ;
// Add these to the container
//
container.put( objClasses );
container.put( givenName );
container.put( sAMAccountName );
container.put( userAccountControl ) ;
// only can do this if connecting via secure ldap
//
if ( isSecureLdap() )
{
try
{
final String quotedPassword = String.format( "\"%s\"", password ) ;
Attribute pwd = new BasicAttribute( "unicodePwd", quotedPassword.getBytes( "UTF-16LE" ) );
container.put( pwd );
}
catch ( UnsupportedEncodingException e )
{
LOGGER.error( "Unable to encode password" );
}
}
// creates a context using the Admin credentials.
LdapContext context = setup() ;
// Create the entry
//
context.createSubcontext( getUserDN( username ), container );
}
Then in my test code:
// authenticate a known user
//
try
{
// existing user 'dev' and this works just fine
authenticate( "dev", "password" ) ;
}
catch ( NamingException e )
{
// if authentication fails, which it does not in this case
}
// create new user
//
final String username = "myTestUser" ;
final String password = "myTestPassword" ;
try
{
addUser( username, "test", password ) ;
}
catch ( NamingException e )
{
// if creation fails, which it does not in this case
}
// try to find that user
//
try
{
// code for find() not included since it works
final UserEntity user = findUser( username ) ;
}
catch ( NoSuchUserException e )
{
// thrown by find() if it fails -- again, this part still works
}
// attempt to authenticate the newly created user
//
try
{
authenticate( username, password ) ;
}
catch ( NamingException e )
{
// this is the part that throws the exception
}
I am sure it is something minor that is missing, but after searching around quite a bit on SO and other places, I have not found the magic bean to fix this.
A: Try using the code for the password:
private byte[] encodePassword(String pass) throws UnsupportedEncodingException
{
final String ATT_ENCODING = "Unicode";
// Agree with MS's ATTRIBUTE_CONSTRAINT
String pwd = "\"" + pass +"\"";
byte bytes[] = pwd.getBytes(ATTENCODING);
// strip unicode marker
byte bytes[] = new byte [_bytes.length - 2];
System.arraycopy(_bytes, 2, bytes, 0,_bytes.length - 2);
return bytes;
}
Microsoft Active Directory is funny about passwords.
We usually add the user first then modify the password.
-jim
| |
doc_999
|
A: You can do it using XOR operator as:
if( x != y) { // this check is very important.
x ^= y;
y ^= x;
x ^= y;
}
EDIT:
Without the additional check the above logic fails to swap the number with itself.
Example:
int x = 10;
if I apply the above logic to swap x with itself, without the check I end up having x=0, which is incorrect.
Similarly if I put the logic without the check in a function and call the function to swap two references to the same variable, it fails.
A: The xor trick is the standard answer:
int x, y;
x ^= y;
y ^= x;
x ^= y;
xoring is considerably less clear than just using a temp, though, and it fails if x and y are the same location
A: If you have 2 variables a and b: (each variable occupies its own memory address)
a = a xor b
b = a xor b
a = a xor b
There are also some other variations to this problem but they will fail if there is overflow:
a=a+b
b=a-b
a=a-b
a=a*b
b=a/b
a=a/b
The plus and minus variation may work if you have custom types that have + and - operators that make sense.
Note: To avoid confusion, if you have only 1 variable, and 2 references or pointers to it, then all of the above will fail. A check should be made to avoid this.
Unlike a lot of people are saying it does not matter if you have 2 different numbers. It only matters that you have 2 distinct variables where the number exists in 2 different memory addresses.
I.e. this is perfectly valid:
int a = 3;
int b = 3;
a = a ^ b;
b = a ^ b;
a = a ^ b;
assert(a == b);
assert(a == 3);
A: Since no langauge was mentioned, in Python:
y, x = x, y
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.