text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Negative scaling mirror alternative Unity I am trying to set up an airplane model downloaded from the sketchup warehouse, and in order to mirror the wings (the imported mirror setup had lighting and texture bugs) I have to scale the wings by -1. I want to attach parts of the plane via fixed joints to the fuselage, but when I scale the rigidbody/joint by -1 it freaks out on load. Is there an alternative mirror method or something that needs to be changed on the joints.
If this belongs on another forum (other than unity answers) tell me and I will repost there.
Thanks.
A: I found a solution, in which I put the rigidbody in a gameobject that parented the negatively scaled mesh.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47398642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Login Example with nodejs and jsonwebtoken: can't read the token verification result My MIDDLEWARE checks if the tokens provided by users are correct.
The secuirity control, implemented by using jsonwebtoken, was inside the middleware and it was working fine.
After I decided to move all this security checks in another file: TokenManger.js
But I don't know how to set the code between the two files.
I tried many ways but no one is working.
So just for a better understanding I paste in the following an example code, which is not working. This is about the middleware:
...
router.use(function(req,res,next){
var token = req.body.token || req.query.token || req.headers['x-access-token'];
//decode token
if(token){
TokenManager.verifyToken(token,true,function(err,key){
if(err) return res.json({ success : false, message : "Failed to authenticate token"});
else next();
});
}else{
// no token, return error
return res.status(403).send({
success : false,
message: 'No token provided!'
});
}
});
...
In the other hand this is an example (and not working) implementation of the TokenManager.js:
var _ = require('lodash');
var jwt = require('jsonwebtoken');
var config = require('../../config.js');
var TokenManager = {
createToken: function(user) {
if(user.admin){
var token = jwt.sign(user, config.SECRET_WORD.ADMIN,{expiresIn:config.EXPIRE_TIME.ADMIN_TOKEN});
}else{
var token = jwt.sign(user, config.SECRET_WORD.USER,{expiresIn:config.EXPIRE_TIME.USER_TOKEN});
}
return token;
},
verifyToken: function(token, admin, decode){
if(admin){
//admin authentication
jwt.verify(token, config.SECRET_WORD.ADMIN, function(err,key){
if(err){
return false;
}else{
return true;
}
});
}else{
//user authentication
jwt.verify(token, config.SECRET_WORD.USER, function(err,key){
if(err){
return false;
}else{
return true;
}
});
}
}
}
module["exports"] = TokenManager;
Actually the createToken(user) function is working fine with the previous code, there is a problems only with the verifyToken(token, admin, decode) function. But I care about the design so if you have suggestions about the creation too, they are more than welcome.
Just to complete the picture, this is how I call the createToken(user) function:
...
.post(function(req,res){
User.findOne({ username: req.body.username }, function(err,user){
if(err) throw err;
if(!user){
res.json({ success: false, message: 'Authentication failed. User not found!' });
}else{
if(user.password != req.body.password){
res.json({ success: false, message: 'Authentication failed. Wrong password!' });
}else{
//token creation
var token = TokenManager.createToken(user);
res.json({
success: true,
token: token
});
}
}
});
});
...
A: You are passing function(err, key) to verifyToken, but there is not callback in the signature of verifyToken.
Try changing the verifyToken function to
verifyToken: function(token, admin, callback){
if(admin){
//admin authentication
jwt.verify(token, config.SECRET_WORD.ADMIN, callback);
}else{
//user authentication
jwt.verify(token, config.SECRET_WORD.USER, callback);
}
}
Update : Without callback
verifyToken: function(token, admin){
try {
if(admin){
//admin authentication
jwt.verify(token, config.SECRET_WORD.ADMIN, callback);
}else{
//user authentication
jwt.verify(token, config.SECRET_WORD.USER, callback);
}
return true;
} catch(err)
return false;
}
}
And use like this in your middleware:
if (TokenManager.verifyToken(token,true)){
return next();
} else {
return res.json({ success : false, message : "Failed to authenticate token"});
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41913318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Jquery Daily Timer Failing I am using this jQuery code to display the left left until 10am locally.
Between 10am and 14:00pm it removes some images.
Then after 14:00 it should display time left until 10am. It also adds an offset to account for weekends.
It works brilliantly most of the time, however it seems after 14:00 it goes way over the time...
Can anyone see why this is failing, I've been looking at it for to long... now I'm just confussed! Please help!
$(document).ready(function() {
// 24 hour based
var targetTime = 1000;
var targetHour = 10;
var openingTime = 1400;
var openingHour = 14;
var currentTime = new Date();
// sun 0 mon 1 ... fri 5 sat 6
var currentDay = currentTime.getDay();
var offset = 24;
// friday
if (currentDay === 5) {
offset = 60;
} // saturday
else if (currentDay === 6) {
offset = 48;
}
var the_current_time = ''+ currentTime.getHours() + '' + currentTime.getMinutes() + '';
if( the_current_time > targetTime && the_current_time < openingTime ) {
var time_hours = (openingHour + offset) - currentTime.getHours() - 1;
var time_min = 60 - currentTime.getMinutes();
var time_seconds = 60 - currentTime.getSeconds();
$('#hours_left').append(time_hours, ':',time_min < 10 ? "0" : "" , time_min , ':' , time_seconds < 10 ? "0" : "" , time_seconds);
$('#watch_image').attr('src','http://cdn.shopify.com/s/files/1/0085/1702/t/1/assets/closed-until-icon.png');
$('#time-left-banner').css('width','275px');
$('.add-to-button').css('display','none');
$('#purchase').css('display','none');
}
else if( the_current_time > targetTime && the_current_time > openingTime ) {
var time_hours = (targetHour + offset) - currentTime.getHours() - 1;
var time_min = 60 - currentTime.getMinutes();
var time_seconds = 60 - currentTime.getSeconds();
$('#hours_left').append(time_hours, ':',time_min < 10 ? "0" : "" , time_min , ':' , time_seconds < 10 ? "0" : "" , time_seconds);
}
else {
var time_hours = (targetHour + offset) - currentTime.getHours() - 1;
var time_min = 60 - currentTime.getMinutes();
var time_seconds = 60 - currentTime.getSeconds();
$('#hours_left').append(time_hours, ':',time_min < 10 ? "0" : "" , time_min , ':' , time_seconds < 10 ? "0" : "" , time_seconds);
}
});
A: First, I would simplify the code a bit. The three var calculation in all three branches seem to be the same. So is the updating of #hours_left. You should be able to factor them out of the if. This will also reduce the number of if branches from 3 to 1 - if I am not missing something.
As for the problem, I would look at the_current_time. You are not zero padding the minutes, so 10:05 will become 105, or 1:05. I can't see how this would cause any dramas, as the calculations do not depend on this value, but it will change the if branch you will take.
Ah, I missed the time_hours calculation difference in the first branch of if. It uses opening_hours instead of target_hours. This explains why a bad the_current_time will make a difference on the reported value.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7276331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SessionNotCreatedException in Eclipse "Appium" code My Code to execute a simple click button automation is given below , I am very new to appium so I am just trying to get my app and click one button , as i have given my exception down it is stopping me to proceed
public class IOSTester {
public static void main(String[] args) throws Exception {
WebDriver driver;
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.BROWSER_NAME, "iOS");
capabilities.setCapability(CapabilityType.VERSION, "8.1");
capabilities.setCapability("deviceName","iPadAir Simulator");
capabilities.setCapability("app", "/Users/AZ-Admin/Documents/test.app");
driver = new RemoteWebDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
if(driver!=null)
{
driver.quit();
}
driver.findElement(By.xpath("//UIAApplication[1]/UIAWindow[1]/UIAButton[1]")).click();
}
}
I Got the below exception when the compiler reached "driver = new RemoteWebDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);" , can anyone help me
Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: A new session could not be created. (Original error: Requested a new session but one was in progress) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 1.19 seconds
Build info: version: '2.44.0', revision: '76d78cf', time: '2014-10-23 20:02:37'
System info: host: 'CodeWarrior.local', ip: '192.168.0.114', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.10.1', java.version: '1.7.0_71'
Driver info: org.openqa.selenium.remote.RemoteWebDriver
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:204)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:156)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:599)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:240)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:126)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:153)
at CalculatorTest.IOSTester.main(IOSTester.java:28)
Thank you
A: Change the code to
public class IOSTester {
public static void main(String[] args) throws Exception {
AppiumDriver driver;
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.BROWSER_NAME, "iOS");
capabilities.setCapability(CapabilityType.VERSION, "8.1");
capabilities.setCapability("platformName", "iOS");
capabilities.setCapability("deviceName","iPad Air");
capabilities.setCapability("app", "/Users/AZ-Admin/Documents/test.app");
driver = new AppiumDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
driver.findElement(By.xpath("//UIAApplication[1]/UIAWindow[1]/UIAButton[1]")).click();
}
}
Download Appium Driver.jar and attach it to your code file and Import AppiumDriver
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27834932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Updating caller's argument array from within a function In Bash I can set $@ this way:
set -- a b c
Then, I can inspect the content of $@:
printf '%s\n' "$@"
which would show:
a
b
c
However, if I do this in a function:
f() {
set d e f
}
set a b c
f
printf '%s\n' "$@"
I still get
a
b
c
and not
d
e
f
How can I make my function update caller's $@? I tried with BASH_ARGV, but it didn't work.
I am trying to write a function that processes the command line arguments and removes certain items from there (while setting a variable) so that the caller doesn't need to bother about them. For example, I want all my scripts to turn on their debug logging if I invoke them with --debug without having to write the code to process that in each script and placing that logic in a common "sourced" function instead.
Note: I don't want to fork a subshell.
A: You cannot change the values of arguments, as they are passed by reference
in bash functions.
The best you can do is to pass the arguments you want to process, and return
the ones not processed yet.
Something in the lines of:
process_arguments() {
# process the arguments
echo "original arguments : $@"
local new_arguments=(a c)
echo ${new_arguments[@])
}
new_arguments=$(process_arguments a b c)
set -- $new_arguments
If you don't want the trouble of a "subshell", you can use a global var:
arguments=""
process_arguments() {
# process the arguments
echo "original arguments : $@"
local new_arguments=(a c)
arguments="${new_arguments[@]}"
}
process_arguments a b c # no subshell
set -- $arguments
As suggested by @ruakh, you can also use arguments as an array, like this:
arguments=()
process_arguments() {
# process the arguments
echo "original arguments : $@"
local new_arguments=(a c)
arguments=( "${new_arguments[@]}" )
}
process_arguments a b c # no subshell
set -- "${arguments[@]}"
A: This is a matter of scope: Functions each have their own parameter array, independently of the script:
$ cat test.bash
#!/usr/bin/env bash
f() {
printf '%s\n' "Function arguments:" "$@"
}
printf '%s\n' "Script arguments:" "$@"
f 'a b' 'c d'
$ chmod u+x test.bash
$ ./test.bash 'foo bar' baz
Script arguments:
foo bar
baz
Function arguments:
a b
c d
So when you set the parameter array, that only applies within the current scope. If you want to change the script parameter array, you need to set it outside of any function. Hacks like set -- $(f) are not going to work in general, because it can't handle whitespace in arguments.
A general solution gets much uglier: you'd need to printf '%s\0' "$parameter" in the function and while IFS= read -r -d'' -u9 in the script to put the returned values into an array, and then set -- "${arguments[@]}".
I hope this is possible to do reliably some other way, but that's all I got.
A: vfalcao's approach is good, though the code in that answer wouldn't handle whitespaces accurately.
Here is the code based on the same idea that does handle whitespaces well:
wrapper() {
# filter args
args=()
for arg; do
if [[ $arg = arg1 ]]; then
# process arg1
elif [[ $arg = arg2 ]]; then
# process arg2
elif ...
# process other args
else
args+=("$arg")
fi
# call function with filtered args
wrapped_function "$args[@]"
done
}
wrapper "$@"
An example implementation here: base-wrapper
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55152951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Retrieving command invocation in AWS SSM I am trying to send command to a running ubuntu ec2 instance. I have configured the appropriate role and I have an ssm agent running on the ec2 instance. Using the boto3 SDK I am able to use the client.send_command() function to successfully send a shell command and was subsequently able to get the command Id. Now the challenge is polling for the result. I am trying to use the client.get_command_invocation() function but keep getting a InvocationDoesNotExist error. I am confident that I am using the correct command ID and instance ID because I have tested these using the AWS CLI as in aws ssm list-command-invocations --command-id #### --instance-id i-##### and this worked. Here is a snippet of my code:
`ssm_client = boto3.client('ssm')
target_id = "i-####"
response = ssm_client.send_command(
InstanceIds=[
target_id
],
DocumentName="AWS-RunShellScript",
Comment="Code to run" ,
Parameters={
"commands": ["ls -l"]
}
)
cmd_id= response['Command']['CommandId']
response = ssm_client.get_command_invocation(CommandId=cmd_id,
InstanceId=target_id)
print(response)`
Here is the returned error:
botocore.errorfactory.InvocationDoesNotExist: An error occurred (InvocationDoesNotExist) when calling the GetCommandInvocation operation
Thanks in advance.
A: Just add these 2 line.
import time
time.sleep(2)
Then It'll work properly generally it take only 0.65sec but it's better to give 2 sec. To make it better you can add some cool stuffs like some print statement in for loop and sleep inside it something like that.
A: The following worked for me. Check out the API documentation for how to update the default delays and max attempts at https://boto3.amazonaws.com.
from botocore.exceptions import WaiterError
ssm_client = boto3.client(
"ssm",
region_name=REGION,
aws_access_key_id=KEY,
aws_secret_access_key=SECRET,
)
waiter = ssm_client.get_waiter("command_executed")
try:
waiter.wait(
CommandId=commands_id,
InstanceId=instance_id,
)
except WaiterError as ex:
logging.error(ex)
return
A: I had the same issue, I fixed it by adding a time.sleep() call before calling get_command_invocation(). A short delay should be enough.
A: time.sleep does the job 99% of the time. Here is a better way to do this:
MAX_RETRY = 10
get_command_invocation_params = {
'CommandId': 'xxx',
'InstanceId': 'i-xxx'
}
for i in range(MAX_RETRY):
try:
command_executed_waiter.wait(**get_command_invocation_params)
break
except WaiterError as err:
last_resp = err.last_response
if 'Error' in last_resp:
if last_resp['Error']['Code'] != 'InvocationDoesNotExist' or i + 1 == MAX_RETRY:
raise err
else:
if last_resp['Status'] == 'Failed':
print(last_resp['StandardErrorContent'], file=sys.stderr)
exit(last_resp['ResponseCode'])
continue
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50067035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Can't Access CSS Selector's Properties from Javascript Here's a very basic question: why is the finishLoading() function in the code below not able to access the 'opacity' property for the #myStyle CSS selector? The alert doesn't display anything, and I've verified that the 'opacity' property is 'false'.
Thanks very much!
<html>
<head>
<style type="text/css">
<!--
#myStyle
{
opacity: 0.50;
}
-->
</style>
<script type="text/javascript">
<!--
function finishedLoading()
{
alert(document.getElementById('myStyle').style.opacity);
}
-->
</script>
</head>
<body onload="finishedLoading();">
<div id="myStyle">
hello
</div>
</body>
</html>
A: You can get the values set through class only after their computation.
var oElm = document.getElementById ( "myStyle" );
var strValue = "";
if(document.defaultView && document.defaultView.getComputedStyle)
{
strValue = document.defaultView.getComputedStyle(oElm, null).getPropertyValue("-moz-opacity");
}
else if(oElm.currentStyle) // For IE
{
strValue = oElm.currentStyle["opacity"];
}
alert ( strValue );
A: The problem is, that element.style.opacity only stores values, that are set inside the element's style attribute. If you want to access style values, that come from other stylesheets, take a look at quirksmode.
Cheers,
A: I suggest you take a look at jQuery and some of the posts at Learning jQuery, it will make doing things like this very easy.
A: Opacity should be a number rather than a boolean. Is it working in any other browseR?
A: this link help
http://www.quirksmode.org/js/opacity.html
function setOpacity(value) {
testObj.style.opacity = value/10;
testObj.style.filter = 'alpha(opacity=' + value*10 + ')';
}
opacity is for Mozilla and Safari, filter for Explorer. value ranges from 0 to 10.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1048336",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Keep AVAudioPlayer sound in the memory I use AVAudioPlayer to play a click sound if the user taps on a button.
Because there is a delay between the tap and the sound, I play the sound once in viewDidAppear with volume = 0
I found that if the user taps on the button within a time period the sound plays immediately, but after a certain time there is a delay between the tap and the sound in this case also.
It seems like in the first case the sound comes from cache of the initial play, and in the second case the app has to load the sound again.
Therefore now I play the sound every 2 seconds with volume = 0 and when the user actually taps on the button the sound comes right away.
My question is there a better approach for this?
My goal would be to keep the sound in cache within the whole lifetime of the app.
Thank you,
A: If you save the pointer to AVAudioPlayer then your sound remains in memory and no other lag will occur.
First delay is caused by sound loading, so your 1st playback in viewDidAppear is right.
A: To avoid audio lag, use the .prepareToPlay() method of AVAudioPlayer.
Apple's Documentation on Prepare To Play
Calling this method preloads buffers and acquires the audio hardware
needed for playback, which minimizes the lag between calling the
play() method and the start of sound output.
If player is declared as an AVAudioPlayer then player.prepareToPlay() can be called to avoid the audio lag. Example code:
struct AudioPlayerManager {
var player: AVAudioPlayer? = AVAudioPlayer()
mutating func setupPlayer(soundName: String, soundType: SoundType) {
if let soundURL = Bundle.main.url(forResource: soundName, withExtension: soundType.rawValue) {
do {
player = try AVAudioPlayer(contentsOf: soundURL)
player?.prepareToPlay()
}
catch {
print(error.localizedDescription)
}
} else {
print("Sound file was missing, name is misspelled or wrong case.")
}
}
Then play() can be called with minimal lag:
player?.play()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37928518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Automatic Link conversion with preg_replace - but without last bracket, period and comma The php q2a software www.question2answer.org parses links in text with the following preg_replace:
function qa_html_convert_urls($html, $newwindow=false) {
return substr(preg_replace('/([^A-Za-z0-9])((http|https|ftp):\/\/([^\s&<>"\'\.])+\.([^\s&<>"\']|&)+)/i', '\1<A HREF="\2" '.($newwindow ? ' target="_blank"' : '').'>\2</A>', ' '.$html.' '), 1, -1);
}
The only problem is that text such as "look here http://www.mydomain.com/." will link like https://www.mydomain.com/. or "look here (http://www.mydomain.com/)" will link http://www.mydomain.com/) the last char (period, comma or bracket) gets part of the link. And breaks the correct link.
Could you provide a solution for this issue?
Thanks a lot :)
A: The working solution is:
function qa_html_convert_urls($html, $newwindow=false) {
return substr(preg_replace('/([^A-Za-z0-9])((http|https|ftp):\/\/([^\s&<>\(\)\[\]"\'\.])+\.([^\s&<>\(\)\[\]"\']|&)+)/i', '\1<a href="\2" '.($newwindow ? ' target="_blank"' : '').'>\2</a>', ' '.$html.' '), 1, -1);`
}
Thanks and credits to gidgreen.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20198654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: apply a jQuery function on a CkEditor I have a textarea in my html file, and I need to send the data in the textarea to the database. However, the textarea send the data without the enter spaces. so a data like this:
Shortly after reading a few books on web design, I was hooked. I wanted to know everything and anything about it. I was designing websites any chance I could.
I spent almost all of my savings buying more books on different programming languages and other nerdy computer gear.
would be like this in the database.
Shortly after reading a few books on web design, I was hooked. I wanted to know everything and anything about it. I was designing websites any chance I could. I spent almost all of my savings buying more books on different programming languages and other nerdy computer gear.
So I decided to change the textarea to a ckeditor to send the data as html. But the problem now that I have a jQuery method on the textarea, and now it won't work.
HTML :
<td>
<textarea maxlength="5000" id="blah" cols="100" rows="20" name="essay_content" class="ckeditor" onkeyup="words();">
</textarea></td>
jQuery:
function words(content)
{
var f = $("#blah").val()
$('#othman').load('wordcount.php?content='+ encodeURIComponent(f));
}
now it won't work with me because the text area is a CkEditor ... any suggestions ?
A: This should get you the contents of the CkEditor textarea:
function words(content)
{
var f = CKEDITOR.instances.blah.getData();
$('#othman').load('wordcount.php?content='+ encodeURIComponent(f));
}
But,I don't think the onkeyup will work, because CkEditor replaces the textarea. You would need to create a plugin for CkEditor to catch the key up trigger within the editor instance.
A: I have used nlbr and everything works.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11355788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: getting response from Facebook is getting timed out Hi I am using a facebook posts feeding application which will read all the new posts from my facebook page and will save to my sharepoint list. Earlier, i.e, before June it has worked properly it feeds all the posts from fabebook to my Share point list. But nowadays its throws an error while getting response from the Facebook authorize url. I don't know what went wrong. Please help me if you guys have any suggestion to resolve this issue. I am appending my code part below.
private void btnSendToList_Click(object sender, EventArgs e)
{
try
{
if (ConfigurationSettings.AppSettings["fbClientID"] != null)
strClientID = ConfigurationSettings.AppSettings["fbClientID"];
if (ConfigurationSettings.AppSettings["fbRedirectURL"] != null)
strURL = ConfigurationSettings.AppSettings["fbRedirectURL"];
if (ConfigurationSettings.AppSettings["fbCltSecret"] != null)
strCltSecret = ConfigurationSettings.AppSettings["fbCltSecret"];
if (ConfigurationSettings.AppSettings["fbUserId"] != null)
strUserId = ConfigurationSettings.AppSettings["fbUserId"];
if (ConfigurationSettings.AppSettings["SPSiteURL"] != null)
strSiteURL = ConfigurationSettings.AppSettings["SPSiteURL"];
CookieCollection cookies = new CookieCollection();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.facebook.com");
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
//Get the response from the server and save the cookies from the first request..
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
cookies = response.Cookies;
string getUrl = "https://www.facebook.com/login.php?login_attempt=1";
string postData = String.Format("email={0}&pass={1}", "[email protected]", "test123$"); // Masking credentials.
getRequest = (HttpWebRequest)WebRequest.Create(getUrl);
getRequest.CookieContainer = request.CookieContainer;
getRequest.CookieContainer.Add(cookies);
getRequest.Method = WebRequestMethods.Http.Post;
getRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
getRequest.AllowWriteStreamBuffering = true;
getRequest.ProtocolVersion = HttpVersion.Version11;
getRequest.AllowAutoRedirect = true;
getRequest.ContentType = "application/x-www-form-urlencoded";
byteArray = Encoding.ASCII.GetBytes(postData);
getRequest.ContentLength = byteArray.Length;
newStream = getRequest.GetRequestStream(); //open connection
newStream.Write(byteArray, 0, byteArray.Length); // Send the data.
getResponse = (HttpWebResponse)getRequest.GetResponse();
getRequest = (HttpWebRequest)WebRequest.Create(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}", strClientID, "http://www.facebook.com/connect/login_success.html"));
getRequest.Method = WebRequestMethods.Http.Get;
getRequest.CookieContainer = request.CookieContainer;
getRequest.CookieContainer.Add(cookies);
getRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
getRequest.AllowWriteStreamBuffering = true;
//getRequest.ProtocolVersion = HttpVersion.Version11;
getRequest.AllowAutoRedirect = true;
getRequest.ContentType = "application/x-www-form-urlencoded";
getResponse = (HttpWebResponse)getRequest.GetResponse();
The above line throws WebExceptopn which is teeling like Process has timed out.
strAccessToken = getResponse.ResponseUri.Query;
strAccessToken = strAccessToken.Replace("#_=_", "");
strAccessToken = strAccessToken.Replace("?code=", "");
newStream.Close();
if (!string.IsNullOrEmpty(strAccessToken))
strCode = strAccessToken;
if (!string.IsNullOrEmpty(strCode) && !string.IsNullOrEmpty(strClientID) &&
!string.IsNullOrEmpty(strURL) && !string.IsNullOrEmpty(strCltSecret) &&
!string.IsNullOrEmpty(strUserId))
{
SaveToList();
}
}
catch (Exception ex)
{
LogError(ex);
}
}
A: Hi Finally i got the solution.
Here i am using getResponse = (HttpWebResponse)getRequest.GetResponse();
The problem is we can use only one HttpWebResponse at a time. In my case i am using the same object in two times without any disposing and closing. That's make me the error.
So I updated my code like this.
byteArray = Encoding.ASCII.GetBytes(postData);
getRequest.ContentLength = byteArray.Length;
newStream = getRequest.GetRequestStream(); //open connection
newStream.Write(byteArray, 0, byteArray.Length); // Send the data.
getResponse = (HttpWebResponse)getRequest.GetResponse();
getresponse.Close();
This solved my error. Thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18756136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can I create a mutable slice &mut [u8] from a single byte (u8)? Sometimes I want to read a single byte from a std::io::Reader. If I try to do this:
use std::io::{self, Read};
fn main() {
let mut byte: u8 = 0;
io::stdin().read(&mut byte).unwrap();
println!("byte: {}", byte);
}
I get the following error (which is clear, as byte is not a slice):
error[E0308]: mismatched types
--> src/main.rs:6:22
|
6 | io::stdin().read(&mut byte).unwrap();
| ^^^^^^^^^ expected slice, found u8
|
= note: expected type `&mut [u8]`
found type `&mut u8`
Is there a way I can keep byte as a simple u8 and just take a slice of it, which I can then pass to read()? The obvious way to make this code work is to use an array of length 1:
use std::io::{self, Read};
fn main() {
let mut byte: [u8; 1] = [0];
io::stdin().read(&mut byte).unwrap();
println!("byte: {}", byte[0]);
}
But that's kinda weird feeling throughout the rest of the code, and it would be more natural to use a single u8 rather than a [u8; 1] that I have to index into.
If it's not possible to create a slice from the simple u8 that's okay, but I don't know if it's possible or not and would like to know.
A: To answer your actual question: no, you can’t do that, and there’s almost never any need to. Even if you couldn’t get an iterable out of a readable, you could just put byte[0] into another variable and use that.
Instead, you can use the Bytes iterator:
let byte: u8 = io::stdin().bytes().next().unwrap();
A: Rust 1.28+
slice::from_mut is back and it's stable!
use std::{
io::{self, Read},
slice,
};
fn main() {
let mut byte = 0;
let bytes_read = io::stdin().read(slice::from_mut(&mut byte)).unwrap();
if bytes_read == 1 {
println!("read byte: {:?}", byte);
}
}
Rust 1.0+
But that's kinda weird feeling throughout the rest of the code, and it would be more natural to use a single u8 rather than a [u8; 1] that I have to index into.
Creating an array of length 1 would be the most natural way of doing it:
use std::io::{self, Read};
fn main() {
let mut bytes = [0];
let bytes_read = io::stdin().read(&mut bytes).unwrap();
let valid_bytes = &bytes[..bytes_read];
println!("read bytes: {:?}", valid_bytes);
}
However, it is possible to unsafely create a slice from a reference to a single value:
use std::io::{self, Read};
use std::slice;
fn mut_ref_slice<T>(x: &mut T) -> &mut [T] {
// It's important to wrap this in its own function because this is
// the only way to tell the borrow checker what the resulting slice
// will refer to. Otherwise you might get mutable aliasing or a
// dangling pointer which is what Rust is trying to avoid.
unsafe { slice::from_raw_parts_mut(x, 1) }
}
fn main() {
let mut byte = 0u8;
let bytes_read = io::stdin().read(mut_ref_slice(&mut byte)).unwrap();
if bytes_read != 0 {
println!("byte: {}", byte);
}
}
Remember that a slice is basically two things: a pointer to an area of memory and a length. With a slice of length one, you simply need to add a length to a mutable reference and bam! you got yourself a slice.
Earlier versions of Rust had the ref_slice and mut_ref_slice functions. They were removed because their utility was not yet proven (this isn't a common problem), but they were safe to call. The functions were moved to the ref_slice crate, so if you'd like to continue using them, that's one possibility.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32939974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Recording from tv tuner/webcam with gstreamer and audio/video going out of sync I have a TV tuner card that shows up as /dev/video1. I am trying to digitize some old VHS tapes. The TV tuner doesn't do audio, I have a wire connected to my microphone in.
This is the gstreamer pipeline I'm using to capture video & audio and save it to a file. I'm using motion jpeg because I don't want it to drop frames and lose content. I'll re-encode it better later.
gst-launch-0.10 v4l2src device=/dev/video1 ! \
queue ! \
video/x-raw-yuv,width=640,height=480 ! \
ffmpegcolorspace ! \
jpegenc ! \
avimux name=mux ! \
filesink location=output.avi \
pulsesrc ! \
queue ! \
audioconvert ! \
audio/x-raw-int,rate=44100,channels=2 ! \
mux.
This all works well and good. I have files that play that have video and audio. However sometimes when playing the output files, the audio & video goes out of sync. It happens at the same place in the video, on numerous different media players (totem, mplayer). So I think this is a problem in how I'm saving and recording the file.
Is there anything I can do to the pipeline to make it less likely to suffer from audio/video sync problems? I'm a bit of a newbie to gstreamer and video/audio codecs, so I might be doing something stupid here (please point out!). Is there any video/audio/muxer codec that would be better?
A: Try adding an audiorate element in the audio branch, and a videorate element in the video branch, to see if that makes a difference, or try a different muxer, like qtmux or matroskamux.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8826738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: cordova-plugin-file on IONIC2 with externalDataDirectory the file is not visible with a file manager I try to write a log file using IONIC2, all seems to work, not error, with IONIC2 the file exist the directory is created, but I can not see the file with a file explorer. See my source there :
File.checkDir(cordova.file.externalDataDirectory, 'mydir')
.then(_ => {
trace.info('yay')
})
.catch(err => {
trace.error('BackgroundGeolocationService','constructor',`boooh`);
File.createDir(cordova.file.externalDataDirectory, "mydir", false)
.then(function (success) {
// success
trace.info('create mydir success');
}, function (error) {
// error
trace.error('BackgroundGeolocationService','constructor',`unable to create mydir`);
}.bind(this));
});
File.createFile(cordova.file.externalDataDirectory, "new_file.txt", true)
.then(function (success) {
// success
trace.info('write file success');
}, function (error) {
// error
trace.error('BackgroundGeolocationService','constructor',`error:${error}`)
});
A: Your source checks for a folder called myDir being created, but when you create new_file.txt, it isn't creating it in the myDir folder, it looks to be creating it in the externalDataDirectory folder.
So check the externalDataDirectory folder rather than your myDir folder, and you'll probably see your file there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40715265",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: docker images are stored in root user thus consuming my disk space Hi my server is configured such that the free space for root user in it is very less. However the user created(suppose user1) has lot of space.
The docker images which are getting created by docker are saved in the root user thus consuming space and making my jobs to fail.How can i make docker images use user1?
Do i need to restart the registry in anyway?
I am unable to understand how to use docker groups and -G tag for this purpose.
Can i mention something in dockerfile and make images up using user1 ?
A: Checkout the -g option on the daemon process. Can be used to locate the docker home on an alternative disk volume.
Explained in the following documentation links:
*
*http://docs.docker.com/reference/commandline/cli/#daemon
*http://docs.docker.com/articles/systemd/#custom-docker-daemon-options
A: Linked /var to /user1/var.
The mounts and the volumes stay the same.
I did this:
`telinit 1
cp -pR /var /user1/var
mv /var /var.old
ln -s /user1/var /var
telinit 2`
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27919828",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Facebook Graph API - IG Media Getting Metadata Issue I have some issues about IGMedia getting metadatas. I followed the instructions in documentations. But I am getting an error like "400" "Bad Request". Before try to getting IGMedia metadatas , I took the recent media datas. But ı dont get an error. Its worked perfectly. So ı need to help about why ı am getting that error? Because of permissions or another things? Please help me. Here is the code. And ı get the error, line of // Get IGMedia Metadata
string access_token = "ACCESS_TOKEN";
var values = new Dictionary<string, string>
{
{ "access_token", access_token},
{ "scope","instagram_basic,manage_pages"},
{ "redirect_uri","" },
};
var content = new FormUrlEncodedContent(values);
var response = new HttpClient().PostAsync("https://graph.facebook.com/v2.6/device/login", content);
response.Wait();
if (!response.Result.IsSuccessStatusCode)
throw new Exception("Auth failed");
var responseString = response.Result.Content.ReadAsStringAsync();
responseString.Wait();
dynamic data = Json.Decode(responseString.Result);
Console.WriteLine("Code : " + data.code);
Console.WriteLine("User Code : " + data.user_code);
Console.WriteLine("Verification Uri : " + data.verification_uri);
Console.WriteLine("Expires in : " + data.expires_in + " seconds");
Console.WriteLine("Interval : " + data.interval);
int interval = Convert.ToInt32(data.interval) * 1000;
int expires_in = Convert.ToInt32(data.expires_in);
string longCode = data.code;
bool loggedIn = false;
DateTime dtCodeGenerated = DateTime.Now;
string TokenCall = "";
int TokenExpireTime;
while (!loggedIn)
{
Thread.Sleep(interval);
// Poll Login Status
values = new Dictionary<string, string>
{
{ "access_token", access_token },
{ "code",longCode}
};
content = new FormUrlEncodedContent(values);
response = new HttpClient().PostAsync("https://graph.facebook.com/v2.6/device/login_status", content);
response.Wait();
if (!response.Result.IsSuccessStatusCode)
throw new Exception("Login Status failed");
responseString = response.Result.Content.ReadAsStringAsync();
responseString.Wait();
data = Json.Decode(responseString.Result);
if (data.access_token != null)
{
loggedIn = true;
TokenCall = data.access_token;
TokenExpireTime = Convert.ToInt32(data.expires_in);
break;
}
else
{
if (data.error != null)
{
Console.WriteLine(data.error.error_user_title);
}
}
Console.WriteLine(String.Format("Expires in : {0:000} seconds", (expires_in - (DateTime.Now - dtCodeGenerated).TotalSeconds)));
}
// Get Profile
response = new HttpClient().GetAsync("https://graph.facebook.com/v2.3/me?fields=name,picture&access_token=" + TokenCall);
response.Wait();
if (!response.Result.IsSuccessStatusCode)
throw new Exception("Profile Get failed");
responseString = response.Result.Content.ReadAsStringAsync();
responseString.Wait();
data = Json.Decode(responseString.Result);
Console.WriteLine("Name : " + data.name);
Console.WriteLine("User picture : " + data.picture.data.url);
Console.WriteLine("Id : " + data.id);
string userID = data.id;
// Get User's Pages
response = new HttpClient().GetAsync("https://graph.facebook.com/v5.0/me/accounts?access_token=" + TokenCall);
response.Wait();
if (!response.Result.IsSuccessStatusCode)
throw new Exception("Profile Get failed");
responseString = response.Result.Content.ReadAsStringAsync();
responseString.Wait();
data = Json.Decode(responseString.Result);
string selectedBusinessAccountID = "";
if (data.data.Length > 0)
{
for (int i = 0; i < data.data.Length; i++)
{
Console.WriteLine("PAGE " + i.ToString());
Console.WriteLine("Name : " + data.data[i].name);
Console.WriteLine("Category : " + data.data[i].category);
Console.WriteLine("Id : " + data.data[i].id);
Console.WriteLine();
Console.WriteLine();
string pageID = data.data[i].id;
// get Instagram Business Account
response = new HttpClient().GetAsync(String.Format("https://graph.facebook.com/v5.0/{0}?fields=instagram_business_account&access_token={1}", pageID, TokenCall));
response.Wait();
if (!response.Result.IsSuccessStatusCode)
throw new Exception("Profile Get failed");
responseString = response.Result.Content.ReadAsStringAsync();
responseString.Wait();
dynamic data_instagram_business = Json.Decode(responseString.Result);
if (data_instagram_business.instagram_business_account != null)
{
selectedBusinessAccountID = data_instagram_business.instagram_business_account.id;
Console.WriteLine("selectedBusinessAccountID : " + selectedBusinessAccountID);
break;
}
}
// Get Hashtag id
response = new HttpClient().GetAsync(String.Format("https://graph.facebook.com/ig_hashtag_search?user_id={0}&q={2}&access_token={1}", selectedBusinessAccountID, TokenCall, "hisseliharikalar"));
response.Wait();
if (!response.Result.IsSuccessStatusCode)
throw new Exception("Hashtag ID Failed");
responseString = response.Result.Content.ReadAsStringAsync();
responseString.Wait();
data = Json.Decode(responseString.Result);
string hashtagID = "";
if (data.data.Length > 0)
{
for (int i = 0; i < data.data.Length; i++)
{
Console.WriteLine("Id : " + data.data[i].id);
hashtagID = data.data[i].id;
Console.WriteLine();
Console.WriteLine();
break;
}
}
// Get Medias of hashtag
response = new HttpClient().GetAsync(String.Format("https://graph.facebook.com/{0}/recent_media?user_id={1}&fields={3}&access_token={2}", hashtagID, selectedBusinessAccountID, TokenCall, "id,media_type,comments_count,like_count,media_url,caption,children"));
response.Wait();
if (!response.Result.IsSuccessStatusCode)
throw new Exception("Hashtag Medias Failed");
responseString = response.Result.Content.ReadAsStringAsync();
responseString.Wait();
data = Json.Decode(responseString.Result);
if (data.data.Length > 0)
{
for (int i = 0; i < data.data.Length; i++)
{
Console.WriteLine("Id : " + data.data[i].id);
Console.WriteLine("like_count : " + data.data[i].like_count);
Console.WriteLine("caption : " + data.data[i].caption);
Console.WriteLine("media_type : " + data.data[i].media_type);
Console.WriteLine("media_url : " + data.data[i].media_url);
if (data.data[i].media_url == null)
{
Console.WriteLine("children : " + data.data[i].children);
}
Console.WriteLine();
Console.WriteLine();
**// Get IGMedia Metadata**
response = new HttpClient().GetAsync(String.Format("https://graph.facebook.com/{0}?fields={3}&access_token={2}", data.data[i].id, selectedBusinessAccountID, TokenCall, "id,like_count,caption,media_type,media_url,comments_count"));
response.Wait();
if (!response.Result.IsSuccessStatusCode)
throw new Exception("IGMedia metadata Failed");
responseString = response.Result.Content.ReadAsStringAsync();
responseString.Wait();
data = Json.Decode(responseString.Result);
Console.WriteLine("Id : " + data.data[i].id);
Console.WriteLine("like_count : " + data.data[i].like_count);
Console.WriteLine("caption : " + data.data[i].caption);
Console.WriteLine("media_type : " + data.data[i].media_type);
Console.WriteLine("media_url : " + data.data[i].media_url);
Console.WriteLine("comment_count : " + data.data[i].comments_count);
Console.WriteLine();
Console.WriteLine();
}
}
//
}
//End
Console.ReadKey();
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59930562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android bitmap - out of memory I have a problem with a function that I implemented. On some phones I get a out of memory error.
private Bitmap getIconMarkerOfPlayer(Player p) {
Drawable drawable = getIconOfPlayer(p);
Bitmap img = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_4444);
Canvas canvas = new Canvas(img);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
drawable.draw(canvas);
final float scale = this.getResources().getDisplayMetrics().density;
int heigthPixels = (int) (24 * scale + 0.5f);
int widthPixels = (int) (24 * scale + 0.5f);
return Bitmap.createScaledBitmap(img, widthPixels, heigthPixels, false);
}
The getIconMarkerOfPlayer(Player p) function gives a "programmed" drawable depending on the player's status (dead, alive, offline, ...) and its color. Each player has a unique color assigned to it in the early games.
How can I resize my bitmap from a Drawable object without having a out of memory error?
A: I suggest you to use some ImageLibraries to load Bitmaps efficiently.
Some of them are Fresco, Glide, Piccasio.
I suggest you to go with Glide. Have a look at it here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33487354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Should I use Boost.GIL or is it dead? I actually like the clean approach of Boost.GIL, standardized libraries are cool and Adobe certainly put some thought in it but when comparing to libs such as OpenCV its feature set is marginal. Do you use GIL and for what purposes?
A: Boost.GIL is not dead. There is a few maintainers interested in keeping the project up to date, fixing bugs, helping contributors to bring new features, etc.
Boost.GIL is preparing for refreshing release as part of the upcoming Boost 1.68, including new I/O implementation accepted to Boost.GIL during the official Boost review a longer while ago.
Stay tuned and if you have any specific questions, feel free to post to the official boost-gil mailing list
A: Boost is a widely accepted set of libraries, but it's not in the C++ standard. So don't feel that you've violated the ANSI/ISO code of conduct by using something that better suits your needs.
A: Do not use boost gil, recently I tried to use it to do a "complex" task of reading a png file, but for that it requires installing a bunch of libraries that have no install documentation for Windows, and to make matters worse gil documentation suggest the following regarding libpng and libjpeg(in year 2020):
The user has to make sure this library is properly installed. I
strongly recommend the user to build the library yourself. It could
potentially save you a lot of trouble.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3959151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Waiting on asynchronous methods using NSCondition I am downloading four plist files asynchronously over the internet. I need to wait until all four files are downloaded, until I either on the first run, push a UIViewController, or on all subsequent runs, refresh the data, and reload all my UITableViews.
On the first run, everything works perfectly. When refreshing though, all four url requests are called, and started, but never call their completion or failure blocks, and the UI freezes. Which is odd since I preform all operations in a background thread. I have not been able to figure out why this is happening.
The first load and the refresh methods call the four "update" methods in the same way, and use NSCondition in the same way.
For the first run:
- (void)loadContentForProgram:(NSString *)programPath
{
NSLog(@"Start Load Program");
AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
hud = [[MBProgressHUD alloc] initWithView:myDelegate.window];
[myDelegate.window addSubview:hud];
hud.labelText = @"Loading...";
hud.detailsLabelText = @"Loading Data";
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
//Do stuff here to load data from files
//Update From online files
hud.detailsLabelText = @"Updating Live Data";
resultLock = NO;
progressLock = NO;
recallLock = NO;
stageLock = NO;
condition = [[NSCondition alloc] init];
[condition lock];
[self updateCurrentCompsText];
[self updateCompetitionResults];
[self updateCompetitionRecalls];
[self updateCompetitionProgress];
while (!resultLock) {
[condition wait];
}
NSLog(@"Unlock");
while (!stageLock) {
[condition wait];
}
NSLog(@"Unlock");
while (!recallLock) {
[condition wait];
}
NSLog(@"Unlock");
while (!progressLock) {
[condition wait];
}
NSLog(@"Unlock");
[condition unlock];
updateInProgress = NO;
//Reset Refresh controls and table views
self.refreshControlsArray = [[NSMutableArray alloc] init];
self.tableViewsArray = [[NSMutableArray alloc] init];
NSLog(@"Finished Loading Program");
[[NSNotificationCenter defaultCenter] postNotificationName:@"WMSOFinishedLoadingProgramData" object:nil]; //Pushes view controller
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD hideHUDForView:myDelegate.window animated:YES];
});
});
}
When refreshing data:
- (void)updateProgramContent
{
if (!updateInProgress) {
updateInProgress = YES;
for (int i = 0; i < self.refreshControlsArray.count; i++) {
if (!((UIRefreshControl *)self.refreshControlsArray[i]).refreshing) {
[self.refreshControlsArray[i] beginRefreshing];
[self.tableViewsArray[i] setContentOffset:CGPointMake(0.0, 0.0) animated:YES];
}
}
resultLock = NO;
stageLock = NO;
recallLock = NO;
progressLock = NO;
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
condition = [[NSCondition alloc] init];
[condition lock];
[self updateCompetitionProgress];
[self updateCompetitionRecalls];
[self updateCompetitionResults];
[self updateCurrentCompsText];
while (!resultLock) {
[condition wait];
}
NSLog(@"Unlock");
while (!stageLock) {
[condition wait];
}
NSLog(@"Unlock");
while (!recallLock) {
[condition wait];
}
NSLog(@"Unlock");
while (!progressLock) {
[condition wait];
}
NSLog(@"Unlock");
[condition unlock];
});
for (int i = 0; i < self.refreshControlsArray.count; i++) {
[self.refreshControlsArray[i] performSelector:@selector(endRefreshing) withObject:nil afterDelay:1.0];
[self.tableViewsArray[i] performSelector:@selector(reloadData) withObject:nil afterDelay:1.0];
}
updateInProgress = NO;
}
}
The block below that appears in each loading method above, corresponds to a method that will download and update a specific piece of data.
[self updateCompetitionProgress];
[self updateCompetitionRecalls];
[self updateCompetitionResults];
[self updateCurrentCompsText];
which runs:
- (void)updateCompetitionResults
{
__block NSDictionary *competitionResultsData = nil;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"Some URL",[self.programName stringByReplacingOccurrencesOfString:@" " withString:@"%20"]]] cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:20.0];
AFPropertyListRequestOperation *operation = [AFPropertyListRequestOperation propertyListRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList) {
competitionResultsData = (NSDictionary *)propertyList;
[competitionResultsData writeToFile:[@"SOME LOCAL PATH"] atomically:NO];
[self updateCompetitionResultsWithDictionary:competitionResultsData];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList) {
competitionResultsData = [NSDictionary dictionaryWithContentsOfFile:[@"SOME LOCAL PATH"]];
NSLog(@"Failed to retreive competition results: %@", error);
[self updateCompetitionResultsWithDictionary:competitionResultsData];
}];
[operation start];
}
and the completion and failure blocks call the same method to update the data
- (void)updateCompetitionResultsWithDictionary:(NSDictionary *)competitionResultsData
{
//Do Stuff with the data here
resultLock = YES;
[condition signal];
}
So, Why does this work on the first run, but not any of the subsequent runs?
A: As I mentioned in my comments, above, the most obvious problem is that you're invoking methods that use condition before you initialize condition. Make sure initialize condition before you start calling updateCompetitionResults, etc.
In terms of a more radical change, I might suggest retiring NSCondition altogether, and use operation queues:
*
*I might use NSOperationQueue (or you can use dispatch groups, too, if you want, but I like the operation queue's ability to configure how many concurrent operations you can operate ... also if you get to a point that you want to cancel operations, I think NSOperationQueue offers some nice features there, too). You can then define each download and processing as a separate NSOperation (each of the downloads should happen synchronously, because they're running in an operation queue, you get the benefits of asynchronous operations, but you can kick off the post-processing immediately after the download is done). You then just queue them up to run asynchronously, but define a final operation which is dependent upon the other four will kick off as soon as the four downloads are done. (By the way, I use NSBlockOperation which provides block-functionality for NSOperation objects, but you can do it any way you want.)
*And whereas your updateProgramContent might download asynchronously, it processes the four downloaded files sequentially, one after another. Thus, if the first download takes a while to download, it will hold up the post-processing of the others. Instead, I like to encapsulate both the downloading and the post processing of each of the four plist files in a single NSOperation, each. Thus, we enjoy maximal concurrency of not only the downloading, but the post-processing, too.
*Rather than using the AFNetworking (which I'm generally a big fan of) plist-related method, I might be inclined to use NSDictionary and NSArray features that allow you to download a plist from the web and load them into the appropriate structure. These dictionaryWithContentsOfURL and arrayWithContentsOfURL run synchronously, but because we're doing this in a background operation, everything runs asynchronously like you want. This also bypasses the saving them to files. If you wanted them saved to files in your Documents directory, you can do that easily, too. Clearly, if you're doing something sophisticated in your downloading of the plist files (e.g. your server is engaging in some challenge-response authentication), you can't use the convenient NSDictionary and NSArray methods. But if you don't need all of that, the simple NSDictionary and NSArray methods, ___WithContentsOfURL make life pretty simple.
Pulling this all together, it might look like:
@interface ViewController ()
@property (nonatomic, strong) NSArray *competitions;
@property (nonatomic, strong) NSDictionary *competitionResults;
@property (nonatomic, strong) NSDictionary *competitionRecalls;
@property (nonatomic, strong) NSDictionary *competitionProgress;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self transfer];
}
- (void)allTransfersComplete
{
BOOL success;
if (self.competitions == nil)
{
success = FALSE;
NSLog(@"Unable to download competitions");
}
if (self.competitionResults == nil)
{
success = FALSE;
NSLog(@"Unable to download results");
}
if (self.competitionRecalls == nil)
{
success = FALSE;
NSLog(@"Unable to download recalls");
}
if (self.competitionProgress == nil)
{
success = FALSE;
NSLog(@"Unable to download progress");
}
if (success)
{
NSLog(@"all done successfully");
}
else
{
NSLog(@"one or more failed");
}
}
- (void)transfer
{
NSURL *baseUrl = [NSURL URLWithString:@"http://insert.your.base.url.here/competitions"];
NSURL *competitionsUrl = [baseUrl URLByAppendingPathComponent:@"competitions.plist"];
NSURL *competitionResultsUrl = [baseUrl URLByAppendingPathComponent:@"competitionresults.plist"];
NSURL *competitionRecallsUrl = [baseUrl URLByAppendingPathComponent:@"competitionrecalls.plist"];
NSURL *competitionProgressUrl = [baseUrl URLByAppendingPathComponent:@"competitionprogress.plist"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
queue.maxConcurrentOperationCount = 4; // if your server doesn't like four concurrent requests, you can ratchet this back to whatever you want
// create operation that will be called when we're all done
NSBlockOperation *completionOperation = [NSBlockOperation blockOperationWithBlock:^{
// any stuff that can be done in background should be done here
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// any user interface stuff should be done here; I've just put this in a separate method so this method doesn't get too unwieldy
[self allTransfersComplete];
}];
}];
// a variable that we'll use as we create our four download/process operations
NSBlockOperation *operation;
// create competitions operation
operation = [NSBlockOperation blockOperationWithBlock:^{
// download the competitions and load it into the ivar
//
// note, if you *really* want to download this to a file, you can
// do that when the download is done
self.competitions = [NSArray arrayWithContentsOfURL:competitionsUrl];
// if you wanted to do any post-processing of the download
// you could do it here.
NSLog(@"competitions = %@", self.competitions);
}];
[completionOperation addDependency:operation];
// create results operation
operation = [NSBlockOperation blockOperationWithBlock:^{
self.competitionResults = [NSDictionary dictionaryWithContentsOfURL:competitionResultsUrl];
NSLog(@"competitionResults = %@", self.competitionResults);
}];
[completionOperation addDependency:operation];
// create recalls operation
operation = [NSBlockOperation blockOperationWithBlock:^{
self.competitionRecalls = [NSDictionary dictionaryWithContentsOfURL:competitionRecallsUrl];
NSLog(@"competitionRecalls = %@", self.competitionRecalls);
}];
[completionOperation addDependency:operation];
// create progress operation
operation = [NSBlockOperation blockOperationWithBlock:^{
self.competitionProgress = [NSDictionary dictionaryWithContentsOfURL:competitionProgressUrl];
NSLog(@"competitionProgress = %@", self.competitionProgress);
}];
[completionOperation addDependency:operation];
// queue the completion operation (which is dependent upon the other four)
[queue addOperation:completionOperation];
// now queue the four download and processing operations
[queue addOperations:completionOperation.dependencies waitUntilFinished:NO];
}
@end
Now, I don't know which of your plist's are arrays and which are dictionaries (in my example, I made competitions an array and the rest were dictionaries keyed by the competition id), but hopefully you get the idea of what I was shooting for. Maximize concurrency, eliminate NSCondition logic, really make the most of NSOperationQueue, etc.
This may be all to much to take in, but I only mention it as an alternative to NSCondition. If your current technique works, that's great. But the above outlines how I would tackle a challenge like this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14013947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Concerns about Ajax use in ASP.NET MVC3 I have looked into Ajax only recently (laugh at me you experts), and I feel excited about all the added functions. But there are a few concerns.
*
*Form submission
In the Ajax examples, a json object is created either automatically (serialize the form) or manually built by retrieving val() from each DOM items. And data validation is performed using javascript. I think we can probably still use Html.EditorFor (and Html.TextboxFor etc.) to build the form. But is it possible to still use the DataAnnotation attributes added on the model/viewmodel? The MVC+Ajax examples I have seen usually don't perform any type of server side validation. Is it okay to omit that part? I guess it is fine because a user has to have javascript enabled to submit the form now. But we need some professional suggestions.
*View Models
In the Ajax world, the View Models are usually expressed as a JSON object. (Please correct me if I am wrong.) Then, what is the best way to map between our domain model and the view model? Is there any tools like AutoMapper?
Okay, I need to add something here...........
The reason for this concern is that I have found some examples use something called Knockout.js (See its website) Instead of return Json(model) to return a json object of our view model into the $.Ajax call, its examples shows a view model is built in javascript.
// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function AppViewModel() {
this.firstName = "Bert";
this.lastName = "Bertington";
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
What is the benefit of such practice?
---- end of my update ----
Thank you for any helpful suggestions.
A: 1) Do not omit server side validation. MVC has some capabilities built in to do some of that for you on the server side, but it's a good idea to test that it's working. Normally this just tests for type, length, range, and some other basic validation. Any complex validation should be done by you. Either way TEST IT to make sure the correct validation is indeed occurring.
2) Json is most common since it works with JavaScript and is easy to serialize in .Net. I Recommend Newtonsoft.Json as your serialization library. You can use whatever language you can parse however, from protobuff to XML.
A ViewModel is a model that is sent to the view, for what the view needs and generally only goes one way, to the view.
The domain models are the objects you persist, and generally travel both ways, from client to server.
A good example might be that your view requires the current date, manager data, and employee data, so your view model contains properties for all of these, but the form only edits the employee which is a domain model that gets sent back from the client to the server to be persisted.
MVC has ModelBinders that will take your post data and turn them into whatever type you need (supposing you properly follow its conventions.) It's unlikely you'll have to map viewmodels to domain models.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10398816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JHipster not adding field search capabilities As mentioned in the documentation, if we use Elasticsearch, JHipster shall create search capabilities for Angular/React UIs. I have tried both of them but search by fields is not added in any screens. I have put the entities in filter and search ... with elasticsearch list in JDL. Tried everything, but it's not generating. Can somebody please list down the steps to include search by entity fields in listing screens. May be I am missing something. I am following documentation, no change in the code, so far everything is in default condition.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56999027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Kotlin: How to inherit from RxJava Subscriber I want my NewsListSubscriber to inherit from an RxJava Subscriber which use a generic type but I get a "Type mismatch" error when I call the UseCase execute method. I read many times the generics page from the Kotlin documentation but I can't find the solution.
Here is my UseCase:
abstract class UseCase(private val threadExecutor: IThreadExecutor,
private val postExecutionThread: IPostExecutionThread) {
private var subscription = Subscriptions.empty()
fun execute(UseCaseSubscriber: rx.Subscriber<Any>) {
subscription = buildUseCaseObservable()
.subscribeOn(Schedulers.from(threadExecutor))
.observeOn(postExecutionThread.getScheduler())
.subscribe(UseCaseSubscriber)
}
protected abstract fun buildUseCaseObservable(): Observable<out Any>
fun unsubscribe() {
if (!subscription.isUnsubscribed) {
subscription.unsubscribe()
}
}
}
And here is how I call it:
override fun loadNewsList() {
getNewsListInteractor.execute(NewsListSubscriber())
}
private inner class NewsListSubscriber : rx.Subscriber<List<NewsModel>>() {
override fun onCompleted() {// TODO}
override fun onError(e: Throwable) {// TODO}
override fun onNext(t: List<NewsModel>) {// TODO}
}
The error is
"Type mismatch. Required: rx.Subscriber. Found: Presenters.NewsListPresenter.NewsListSubscriber"
in the "execute(NewsListSubscriber())" line. I tried playing with the "in" and "out" keywords but I still have the same error.
A: There is actually a better way to solve this problem. I ran into the same issue and a type cast inside every derived subscriber class was not an option.
Just update the abstract UseCase class with an generic type parameter.
abstract class UseCase<T>(private val threadExecutor: IThreadExecutor,
private val postExecutionThread: IPostExecutionThread) {
private var subscription = Subscriptions.empty()
fun execute(UseCaseSubscriber: rx.Subscriber<T>) {
subscription = buildUseCaseObservable()
.subscribeOn(Schedulers.from(threadExecutor))
.observeOn(postExecutionThread.getScheduler())
.subscribe(UseCaseSubscriber)
}
protected abstract fun buildUseCaseObservable(): Observable<T>
fun unsubscribe() {
if (!subscription.isUnsubscribed) {
subscription.unsubscribe()
}
}
}
When you declare your derived UseCase classes, use your concrete type for the generic parameter when calling the super class.
class ConcreteUseCase(val threadExecutor: IThreadExecutor,
val postExecutionThread: IPostExecutionThread)
: UseCase<ConcreteType>(threadExecutor, postExecutionThread)
Doing so, you can use typed Subscribers in your execute call.
getNewsListInteractor.execute(NewsListSubscriber())
...
private inner class NewsListSubscriber : rx.Subscriber<List<NewsModel() {
override fun onCompleted() {// TODO}
override fun onError(e: Throwable) {// TODO}
override fun onNext(t: List<NewsModel>) {// TODO}
}
A: I found the solution that is pretty simple actually: my NewsListSubscriber class has to extends from rx.Subscriber<Any> instead of rx.Subscriber<MyWantedClass>. It means I need to cast the received objects to the wanted type.
private inner class NewsListSubscriber : DefaultSubscriber<Any>() {
override fun onCompleted() {}
override fun onError(e: Throwable) {}
override fun onNext(t: Any?) {
val newsList = t as List<News>
...
}
}
In Java the cast is done in background but in Kotlin we need to do it ourself.
I also removed all "in" or "out" keywords in my UseCase class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35661625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to deploy to a VM running a microk8s cluster with kubectl? I have a Windows 10 machine running a Hyper-V virtual machine with Ubuntu guest.
On Ubuntu, there is a Microk8s installation for my single node Kubernetes cluster.
I can't figure out how to set up my kubectl on the Win10 to allow deploying on the microk8s cluster in the vm.
Atm, from outside, I can ssh into the vm and I can reach the dashboard-proxy for microk8s (in this case locally https://ubuntuk8s:10443 ).
How to configure kubectl on my windows to deploy to microk8s inside the vm?
A: In short, you can copy the file from microk8s instance that kubectl is using (kubeconfig) to the Windows machine in order to connect to your microk8s instance.
As you already have full connectivity between the Windows machine and the Ubuntu that microk8s is configured on, you will need to:
*
*Install kubectl on Windows machine
*Copy and modify the kubeconfig file on your Windows machine
*Test the connection
Install kubectl
You can refer to the official documentation on that matter by following this link:
*
*Kubernetes.io: Docs: Tasks: Tools: Install kubectl Windows
Copy and modify the kubeconfig file on your Windows machine
IMPORTANT!
After a bit of research, I've found easier way for this step.
You will need to run microk8s.config command on your microk8s host. It will give you the necessary config to connect to your instance and you won't need to edit any fields. You will just need to use it with kubectl on Windows machine.
I've left below part to give one of the options on how to check where the config file is located
This will depend on the tools you are using but the main idea behind it is to login into your Ubuntu machine, check where the kubeconfig is located, copy it to the Windows machine and edit it to point to the IP address of your microk8s instance (not 127.0.0.1).
If you can SSH to the VM you can run following command to check where the config file is located (I would consider this more of a workaround solution):
*
*microk8s kubectl get pods -v=6
I0506 09:10:14.285917 104183 loader.go:379] Config loaded from file: /var/snap/microk8s/2143/credentials/client.config
I0506 09:10:14.294968 104183 round_trippers.go:445] GET https://127.0.0.1:16443/api/v1/namespaces/default/pods?limit=500 200 OK in 5 milliseconds
No resources found in default namespace.
As you can see in this example, the file is in (it could be different in your setup):
*
*/var/snap/microk8s/2143/credentials/client.config
You'll need to copy this file to your Windows machine either via scp or other means.
After it's copied, you'll need to edit this file to change the field responsible for specifying where the kubectl should connect to:
*
*before:
*
* server: https://127.0.0.1:16443
*after:
*
* server: https://ubuntuk8s:16443
Test the connection
One of the ways to check if you can connect from your Windows machine to microk8s instance is following:
PS C:\Users\XYZ\Desktop> kubectl --kubeconfig=client.config get nodes -o wide
NAME STATUS ROLES AGE VERSION INTERNAL-IP EXTERNAL-IP OS-IMAGE KERNEL-VERSION CONTAINER-RUNTIME
ubuntu Ready <none> 101m v1.20.6-34+e4abae43f6acde 192.168.0.116 <none> Ubuntu 20.04.2 LTS 5.4.0-65-generic containerd://1.3.7
Where:
*
*--kubeconfig=client.config is specifying the file that you've downloaded
Additional resources:
*
*Kubernetes.io: Docs: Concepts: Configuration: Organize cluster access kubeconfig
*Github.com: Ubuntu: Microk8s: Issues: Cannot connect to microk8s from another machine - this link pointed me to microk8s.config
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67407556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SwiftUI & Unit test fails: Can't add the same store twice when using core data stack After updating Xcode to 13.4 my core data persistence stack started to fail for SwiftUI previews and Xcode Unit tests.
Error message:
Unresolved error Error Domain=NSCocoaErrorDomain Code=134081 "(null)" UserInfo={NSUnderlyingException=Can't add the same store twice}, ["NSUnderlyingException": Can't add the same store twice ...
Persistence stack:
struct PersistenceController {
static let shared = PersistenceController()
let container: NSPersistentContainer
init(inMemory: Bool = false) {
container = NSPersistentContainer(name: "Persistence")
if inMemory {
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
}
let description = NSPersistentStoreDescription()
description.shouldInferMappingModelAutomatically = true
description.shouldMigrateStoreAutomatically = true
container.persistentStoreDescriptions.append(description)
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
container.viewContext.automaticallyMergesChangesFromParent = true
}
}
Usage for SwiftUI previews:
struct MyScreen_Previews: PreviewProvider {
static var previews: some View {
MyScreen()
.environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
}
}
Extension to support SwiftUI preview:
extension PersistenceController {
static var preview: PersistenceController = {
let result = PersistenceController(inMemory: true)
// Pre-fill core data with required information for preview.
}
}
A: There's a mistake in your code, when you append to the array of descriptions you now have 2 descriptions.
Change it to:
let description = container.persistentStoreDescriptions.first!
description.shouldInferMappingModelAutomatically = true
description.shouldMigrateStoreAutomatically = true
// Load
A: I noticed, that after loading persistence storage error generated. This error (Can't add the same store twice), can be ignored for SwiftUI previews and Unit Tests.
To ignore this type of error needs to check XCTestSessionIdentifier and XCODE_RUNNING_FOR_PREVIEWS in the process info.
if let error = error as NSError? {
if ProcessInfo.processInfo.environment["XCTestSessionIdentifier"] == nil &&
ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == nil {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72461766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: F# Set not returning the correct difference. Likely an issue with my CompareTo implementation I start with two sets, abc and zxc. "unmodified" has the correct number (1) of items.
Set abc has two items, one of which is the unmodified item
let unmodified = Set.intersect abc zxc
let newAndModified = a - unmodified
I expect newAndModified to contain one item, but instead it has two. It appears to be an identical set to abc.
Even though my Set.intersect worked fine, other Set functions are not returning the right result and I believe there is something wrong with how I implemented CompareTo for this object.
type Bar =
{ Id : int
Name : string
}
[<CustomEquality; CustomComparison>]
type Foo =
{ Name : string
Id : int
Bars : Bar list
}
override x.Equals(y) =
match y with
| :? Foo as y -> x.Id.Equals y.Id
&& x.Name.Equals y.Name
&& x.Bars.Head.Name.Equals y.Bars.Head.Name
| _ -> invalidArg "y" "cannot compare object to one that is not a Foo"
member x.CompareTo (y: obj) =
match y with
| null -> nullArg "y"
| :? Foo as y -> x.CompareTo(y)
| _ -> invalidArg "y" "Must be an instance of Foo"
member x.CompareTo (y: Foo) =
match x.Equals y with
| true -> 0
| false -> -1
interface IComparable<Foo> with
member x.CompareTo y = x.CompareTo y
interface System.IComparable with
member x.CompareTo y =
match y with
| :? Foo as y -> (x:> IComparable<_>).CompareTo y
| _ -> invalidArg "y" "cannot compare values of different types"
A: Your CompareTo implementation is definitely not going to work here. You return 0 when two objects are equal (which is good), but if they are not equal, you always return -1. This means that the first one is smaller than the last one.
However, this is not going to work. If you have objects a and b, then your comparison is saying that a < b and b < a (which is breaking the requirements on the ordering relation).
The F# set requires the objects to be orderable, because it keeps the data in a balanced tree (where smaller elements are on the left and greater are on the right) - so with CompareTo that always returns -1, it ends up creating a tree that makes no sense.
Why do you want to implement custom comparison for the type? I suppose you're doing that to only consider some of the fields and ignore some others. There is actually a nice trick you can do in this case, which is to create a tuple with the fields you're interested and call the built-in hash and compare functions on them. For example:
compare (x.Id, x.Name, x.Bars.Head.Name)
(y.Id, y.Name, y.Bars.Head.Name)
This will use default F# comparison on the tuples, which is a correctly defined ordering relation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31327191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Run code block in a transaction in postgres I want to run the following code block in a transaction so that if any of the sql statements fail the entire transaction is aborted. If I run the following block as it is, does it run in a transaction or do I need to run it inside BEGIN; ... COMMIT;
DO $$
DECLARE
readonly_exists int;
BEGIN
SELECT COUNT(*) INTO readonly_exists FROM information_schema.enabled_roles
WHERE role_name = 'readonly';
IF readonly_exists = 0 THEN
<SQL STATEMENT 1>
<SQL STATEMENT 2>
<SQL STATEMENT 3>
ELSE
RAISE EXCEPTION 'readonly role already exists';
END IF;
END$$;
A: Any SQL statement always runs in a single transaction (the exception to this rule is CALL).
So your DO statement will run in a single transaction, and either all three SQL statements are successful, or all will be rolled back.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60443200",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there any reson to not reduce Ping Maximum Response Time in IIS 7 IIS includes a worker process health check "ping" function that pings worker processes every 90 seconds by default and recycles them if they don't respond. I have an application that is chronically putting app pools into a bad state and I'm curious if there is any reason not to lower this time to force IIS to recycle a failed worker process quicker. Searching the web all I can find is people that are increasing the time to allow for debugging. It seems like 90 seconds is far to high for a web application, but perhaps I'm missing something.
A: Well the obvious answer is that in some situations requests would take longer than 90 seconds for the worker process to return. If you can't imagine a situation where this would be appropriate, then feel free to lower it.
I wouldn't recommend going too much lower than 30 seconds. I can see situations where you get in recycle loops. However you can do testing and see what makes sense in your situation. I would recommend Siege for load testing to see how your application behaves.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9167740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: My asp.net core app is not writing stdout logs when error occurs I am getting error HTTP Error 500.0 - Internal Server Error when I try to run an asp.net core application on my server.
To debug this I enabled stdout log files as per this article
https://learn.microsoft.com/en-us/aspnet/core/test/troubleshoot-azure-iis?view=aspnetcore-3.0#aspnet-core-module-stdout-log-iis
But it is not writing any log in the logs folder
It is empty
Why?
A: Set stdoutlogEnabled to true and stdoutLogFile to \?\%home%\LogFiles\stdout like below:
If the LogFiles folder is not present Stdoutlog is not written so please create it explicitly.
Set environment variables ASPNETCORE_DETAILEDERRORS = 1 in to see more information around the http 500.0 error and debug it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58777059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can i resolve this problem in Android studio - Flutter How can i resolve this problem in Android studio - Flutter - dart
Iam using Android studio, flutter, firebase
Running Gradle task 'assembleDebug'...
√ Built build\app\outputs\apk\debug\app-debug.apk.
Debug service listening on ws://127.0.0.1:56274/zuPzwT257Jk=/ws
Syncing files to device Android SDK built for x86...
D/EGL_emulation(19266): eglMakeCurrent: 0xa9d06620: ver 2 0 (tinfo 0xa9d03620)
I/BiChannelGoogleApi(19266): [FirebaseAuth: ] getGoogleApiForMethod() returned Gms: com.google.firebase.auth.api.internal.zzaq@3211e85
W/DynamiteModule(19266): Local module descriptor class for com.google.firebase.auth not found.
W/GooglePlayServicesUtil(19266): Google Play services out of date. Requires 12451000 but found 11743470
A: updating the googlePlayService should solve the problem.
If its your emulator than you can try this way
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62329371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Powershell regex to match vhd or vhdx at the end of a string I'm brand new to powershell and I'm trying to write a script to copy files ending in vhd or vhdx
I can enumerate a directory of files like so:
$NEWEST_VHD = Get-ChildItem -Path $vhdSourceDir | Where-Object Name -match ".vhdx?"
This will match
foo.vhd
foo.vhdx
However this will also match
foo.vhdxxxx
How can I write a match that will only match files ending in exactly vhd or vhdx ?
Unsuccessful attempts
Where-Object Name -match ".vhdx?"
Where-Object Name -like ".vhdx?"
Where-Object Name -match ".[vhd]x?"
Where-Object Name -match ".[vhd]\^x?"
Resources I've investigated
http://ss64.com/ps/syntax-regex.html
https://technet.microsoft.com/en-us/library/ff730947.aspx
http://www.regexr.com/
A: Put a $ at the end of your pattern:
-match ".vhdx?$"
$ in a Regex pattern represents the end of the string. So, the above will only match .vhdx? if it is at the end. See a demonstration below:
PS > 'foo.vhd' -match ".vhdx?$"
True
PS > 'foo.vhdx' -match ".vhdx?$"
True
PS > 'foo.vhdxxxx' -match ".vhdx?$"
False
PS >
Also, the . character has a special meaning in a Regex pattern: it tells PowerShell to match any character except a newline. So, you could experience behavior such as:
PS > 'foo.xvhd' -match ".vhdx?$"
True
PS >
If this is undesirable, you can add a \ before the .
PS > 'foo.xvhd' -match "\.vhdx?$"
False
PS >
This tells PowerShell to match a literal period instead.
A: If you only want to check extension, then you can just use Extension property instead of Name:
$NEWEST_VHD = Get-ChildItem -Path $vhdSourceDir | Where-Object Extension -in '.vhd','.vhdx'
A: Mostly just an FYI but there is no need for a regex solution for this particular issue. You could just use a simple filter.
$NEWEST_VHD = Get-ChildItem -Path $vhdSourceDir -Filter ".vhd?"
Not perfect but if you dont have files called ".vhdz" then you would be safe. Again, this is not meant as an answer but just useful to know. Reminder that ? in this case optionally matches a single character but it not regex just a basic file system wildcard.
Depending on how many files you have here you could argue that this would be more efficient since you will get all the files you need off the get go instead of filtering after the fact.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29521950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: MSVC 10 range based for loop Currently in a large c++ project we are working on we have a bunch of the new style for loops like the following:
for (auto& value : values)
Up till now we have been compiling exclusively with gcc 4.6. Recently some of the codebase is being ported to windows and some of the developers want to compile in msvc++ 10 but it seems as though the new for loop syntax is not fully supported yet.
It would be highly desirable to not have to re-write all the places where this syntax occurs.
What is the best way to work around this problem?
Update: It looks as though this issue is resolved in MSVC11.
A: You could use Boost.Foreach:
//Using Xeo's example:
BOOST_FOREACH (auto& e, values) {
std::cout << e << " ";
}
A: One way would be to replace them with std::for_each and lambdas, where possible. GCC 4.6 and MSVC10 both support lambda expressions.
// before:
for(auto& e : values){
std::cout << e << " ";
}
// after:
std::for_each(values.begin(), values.end(),
[](a_type& e){
std::cout << e << " ";
});
The only caveat is that you need to actually type the element name (a_type here), and that you can't use control flow structures (break, continue, return).
Another way would be, when you need those control flow structures, to use old-style for-loops. Nothing wrong with them, especially with auto to infer the iterator type.
Yet another way might be to use the Visual Studio 11 beta when it's out, it supports range-based for loops IIRC. :)
A: You don't have to use boost.
Here's a simple macro for backwards compatibility with vs2010:
// 1600 is VS2010
#if _MSC_VER == 1600
#define FOR_EACH(var , range) for each(var in range)
#else
#define FOR_EACH(var , range) for (var : range)
#endif
Use it like this:
FOR_EACH(auto& e, values) {
std::cout << e << " ";
}
A: You can use for each itself
for each (auto value in values) {
std::cout << value << endl;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9221842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Node JS my-sql query time is a lot slower than MySQL workbench query Basically, I have a table of around 70k rows - when I perform a select all query in nodejs using mysql it takes around 2s. However, MySQL workbench reports the same query takes around 0.05s. I'm pretty new to using nodejs - but here's some code.
this.acquire = function (callback) {
this.pool.getConnection(function (err, connection) {
callback(err, connection);
});
};
this.init = function () {
this.pool = mysql.createPool({
multipleStatements: true,
connectionLimit: 100,
host: 'localhost',
user: 'root',
password: 'example',
database: 'example',
});
}
Then the query itself:
connection.acquire(function (err, con) {
var table = "test"
var query = "SELECT * FROM `" + table + "`";
console.time("test");
con.query(query, function (err, result) {
console.timeEnd("test");
con.release();
});
}
which prints out test: 1969ms
And the result from MySQL workbench:
17:31:48 SELECT * FROM example.test 70001 row(s) returned 0.000 sec / 0.031 sec
The data structure itself is only 3 columns, an id, timestamp and an int.
The question is, why is nodeJS query so much slower? Is it simply the connection time from the nodeJs app to the MySQL server, or is my nodeJs not setup properly?
Any help would be greatly appreciated!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42492831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there an equivalent to Visual SourceSafe's Shadow Directories in other VCS? I have been asked to save the current versions of all files in all repositories on our Subversion server to a network drive.
This is in addition to our backups of the repositories themselves.
Visual SourceSafe did this automatically by means of shadow folders.
Is there a way to accomplish this for a Subversion repository?
Is there an equivalent to shadow folders in any of the other current or popular VCS solutions?
A: I'm happy to say that I've forgotten how SourceSafe works, but Subversion has an export feature that will copy the current version of all files. You can also set up commit hooks that will perform tasks whenever someone commits changes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2887042",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to open "Class browser" in Pharo2 I am reading Pharo by Example the book.
Yet I didn't find the "Class browser" in my "World" menu in my Pharo2.
Is it replaced by the "System Browser"?
A: Yes it is. System browser is Nautilus, a new advanced alternative for old class browser created by Benjamin Van Ryseghem.
You can still open the old one in Pharo 2.0 by executing Browser open but I would highly recommend to use Nautilus which is default for 2.0 version of Pharo.
A: You should not use Pharo 2.0 to follow Pharo by Example book, it has it's own image, which is an older version of Pharo.
You can download the right image from here: http://pharobyexample.org/image/PBE-OneClick-1.1.app.zip
After finishing learning with it, you can then use 2.0 safely :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16959981",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Reset variable after for error message I am attempting to create a PHP method/function/property that I can call with JS to display a message to the user such as "Invalid user login" which will then reset after it has displayed.
So far I have below - problem is when the user goes to the next page, or reloads they are given the message again, so I am wanting away of setting it back to null;
<script>
window.setTimeout(displayErrorMessage(), 2000);
function displayErrorMessage(){
if(!displayErrorMessage.called)
{
var errorMessage = ("<?php echo "ERROR: ".$_SESSION['error'] ?>");
document.getElementById('errormessage').innerHTML = errorMessage;
resetErrorMessage();
}
displayErrorMessage.called = true;
}
function resetErrorMessage()
{
var errorMessage = null;
setTimeout(function()
{
document.getElementById('errormessage').innerHTML = "";
}, 5000);
}
</script>
A: Try removing the session variable after display.
<script>
<?php if(isset($_SESSION['error'])) { ?>
window.setTimeout(displayErrorMessage(), 2000);
function displayErrorMessage(){
if(!displayErrorMessage.called) {
var errorMessage = ('<?php echo "ERROR: ".$_SESSION['error']; ?>');
// Here is where you remove the error so it won't persist to the
// next pages when user continues to navigate through
<?php if(isset($_SESSION['error'])) unset($_SESSION['error']); ?>
document.getElementById('errormessage').innerHTML = errorMessage;
resetErrorMessage();
}
displayErrorMessage.called = true;
}
<?php } ?>
function resetErrorMessage() {
var errorMessage = null;
setTimeout(function(){
document.getElementById('errormessage').innerHTML = "";
}, 5000);
}
</script>
A: Try this:
<?php if( isset($_SESSION['error']) ) : ?>
<script>
window.setTimeout(displayErrorMessage(), 2000);
function displayErrorMessage()
{
if(!displayErrorMessage.called)
{
var errorMessage = ("<?php echo "ERROR: ".$_SESSION['error'] ?>");
document.getElementById('errormessage').innerHTML = errorMessage;
resetErrorMessage();
}
displayErrorMessage.called = true;
}
function resetErrorMessage()
{
var errorMessage = null;
setTimeout(function() {
document.getElementById('errormessage').innerHTML = "";
}, 5000);
}
</script>
<?php endif; ?>
<?php
unset($_SESSION['error']);
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26370690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: handle unhandled exceptions in Android In Windows phone 7, developers are provided an Application_UnhandledException event that provides an exception object containing information and stack trace of any unhandled exception that occurs. There is an opportunity to store this object in local storage. On next startup we can check for such an object and email it to the developer. Obviously this is valuable in diagnosing production crashes.
Does such a thing exist in Android?
Thanks, Gary
A: java.lang.Thread.setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler handler)
Is this what you want?
A: Extend Application class
import android.app.Application;
import android.util.Log;
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
Log.e("MyApplication", ex.getMessage());
}
});
}
}
Add the following line in AndroidManifest.xml file as Application attribute
android:name=".MyApplication"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14249035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Inserting text in a Word Doc does not work (vb.net) I have a document a.docx with a bookmark "bmTest".
This is a part of my .net-Code:
oWord = CreateObject("Word.Application")
oDoc = oWord.Documents.Open("a.docx")
oDoc.Bookmarks("bmTest").Range.InsertAfter("XXX")
...
Word is started, a.docx is loaded, but no text is inserted at that bookmark.
When I rename the bookmark in my code or in the Word document VB throws an error that it does not exist. So the names seem to be right.
What am I doing wrong? How can I insert text remotely in a Word document?
A: Okay, the problem is solved. The code shown above is working. There seems to be a problem with the opened docx document (a customer form) - it may be corrupt.
After using another form the code works :/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36065676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Publish the slides file using apps script slide (GAS) service I need to publish the Slide file to website and get the published URL, But I am not getting the published URL as a return response.
The Drive service is turned on already.
I tried with
function doGet(e) {
var ppt = SlidesApp.openByUrl('https://docs.google.com/presentation/d/1fIQpQJ8QaIqt3fibTGmlAndZuvDG3ry8maAm_0CgSLE/edit#slide=id.p');
var fileId = ppt.getId();
var revisions = Drive.Revisions.list(fileId);
var items = revisions.items;
var revisionId =items[items.length-1].id;
var resource = Drive.Revisions.get(fileId, revisionId);
resource.publishAuto = true;
resource.publishedOutsideDomain = true;
resource.published = true;
return ContentService.createTextOutput(JSON.stringify(Drive.Revisions.update(resource, fileId, revisionId).publishedLink));
}
A: This might be a bug:
The publishedLink from a published Revision (for Sheets, Docs and Slides, at least) is not populated. This seems to be the case for both V2 and V3.
This behaviour was reported some time ago in Issue Tracker:
*
*Visible to Public After publishing the publishedlink is undefined
I'd suggest you to star the issue in order to give it more visibility.
In this case, I think a workaround could be to work with one of the Revision exportLinks instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63717442",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: An anchor over image not clickable in IE 10 but works in IE 11, Firefox and Chrome I have a tile created like:
<div>
<img src="http://blog.caranddriver.com/wp-content/uploads/2016/01/BMW-i8-Mirrorless-cameras-101-876x535.jpg" width="400" alt="img" />
<a href="http://www.google.com"></a>
</div>
with css:
div {
width: 500px;
border: 1px;
height: 500px;
position: relative;
}
img {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
z-index: -1;
margin: auto;
}
a {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
display: block;
z-index: 2;
margin: auto;
}
Or jsfiddle: https://jsfiddle.net/fvguL0hn/
You'll see that you cannot click over that image, in IE 10, but in IE 11 works and other browsers too.
If you mouse out image then you can click, but you go back with cursor to image, then the pointer cursor becomes normal one and you cannot click like somehow anchor is hidden back to the image even I changed z-index.
This happens only in IE 10 ...
What is my mistake ? I changed the z-index but same thing.
A: why not do this?
<div>
<a href="http://www.google.com"><img src="http://blog.caranddriver.com/wp-content/uploads/2016/01/BMW-i8-Mirrorless-cameras-101-876x535.jpg" width="400" alt="img" /></a>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37190930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to change the default highlight color of drop down in html from blue to some other color for tag How to change the default highlight color of drop down in HTML from blue to some other color for <select><option> tags, using some CSS properties or from Javascript?
The requirement is I have to use the <select> <option> tags only. I tried the code below, but it didn't work for me:
<html>
<head>
<title>Dropdown Colour</title>
<style type="text/css">
option:hover {
background:#C6C4BD;
}
</style>
</head>
<body>
<select>
<option>Shell</option>
<option>Cabbage</option>
<option>Beans</option>
<option>Cheese</option>
<option>Clock</option>
<option>Monkey</option>
</select>
</body>
</html>
A: try setting outline and/or border properties of select.
select{outline:1px solid green;border:1px solid black;}
A: Currently there is no way I know of that this can be accomplished using only CSS.
However, using jQuery I was able to achieve a similar effect.
Live Demo
Your dropdown changes because i have to set the size of the select element which makes it look like a list-box. Maybe somebody can improvise on this.
Here is the jQuery i used
$(document).ready(function (event) {
$('select').on('mouseenter', 'option', function (e) {
this.style.background = "limegreen";
});
$('select').on('mouseleave', 'option', function (e) {
this.style.background = "none";
});
});
A: Try to change like this, hope it may help you
select option{
background: red;
color: #fff;
outline:1px solid green;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19289723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: ModelState Clear, Remove an array item, TryValidateModel My model has some property, one of them is Array of Class, and for some Property in Model and array class use from datannotation attribute. In view user fill some row as array and other model property, and may delete some of row(arrayProperty), me set for deleted row Status:delete, and in action remove deleted row from array, steps in action is:
*
*in first time action all thing is Ok(validation done)
*modelState.Clear
*remove items in array that status is delete
*use TryValidateModel for validate refined model
this work for all proprty in Model except array property
Action code:
public ActionResult Test(ViewModel model)
{
ModelState.Clear();
model.Array = model.Array.Where(p => p.Status != false).ToArray();
if(ModelState.IsValid){}
TryValidateModel(model);
return View();
}
Class code:
public class ViewModel
{
public TestClass[] Array { get; set; }
[Required]
public string Family { get; set; }
}
public class TestClass
{
[Required]
public string Name { get; set; }
public int? Age { get; set; }
public bool Status { get; set; }
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13796962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: adobe premiere fails to import "one" footage, but works fine importing "two or more", why? whenever I try to drag a file into adobe premiere timeline, the mouse pointer turns in to a "you cant do it" shape and I cannot put "one single media" in my timeline. but as soon as i choose two or more media and drag them into the time line, everything is fine. can anybody help me why this happens? its so annoying.
A: Is your problem for every files?
it's weird but you may try clearing cache, Go to Preferences> Media Cache and click delete.
if not works try:
restart your pc
close and reopen premiere (The most useful method)
test with other projects
and also check if you can drag it into project panel
if you can't, try another file that already worked.
hope this helps :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73318125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: react-google-maps Customize Marker Icon Currently, I have rendered the map component into a reusables component successfully using InfoModal to show an icon, however, the standard red Google Map icon I have not modified, and I want to create a custom icon myself. I'm not sure with ES6 and JSX syntax what I need to do. I looked into react-google-maps Issues and attempted to see if there were any current or updated material anywhere for how to do this (which is probably simple), but I'm not sure if react-google-maps has something for custom marker creation in addons or the correct format.
import React, { Component } from 'react'
import { withGoogleMap, GoogleMap, Marker, InfoWindow } from 'react-google-maps'
import { DEFAULT_MARKER } from '../../constants/mapDefaults'
const MapGoogleMap = withGoogleMap(props => (
<GoogleMap
defaultZoom={16}
center={props.center}
>
{props.markers.map((marker, index) => (
<Marker
key={index}
position={marker.position}
onClick={() => props.onMarkerClick(marker)}
>
{marker.showInfo && (
<InfoWindow onCloseClick={() => props.onMarkerClose(marker)}>
<div>{marker.infoContent}</div>
</InfoWindow>
)}
</Marker>
))}
</GoogleMap>
))
export default class Map extends Component {
state = {
center: {
lat: 28.3421135,
lng: -80.6149092
},
markers: [
{
position: new google.maps.LatLng(28.3431165, -80.6135908),
showInfo: false,
infoContent: (
<svg
id="Layer_1"
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 16 16"
>
<path
d="M3.5 0c-1.7 0-3 1.6-3 3.5 0 1.7 1 3 2.3 3.4l-.5 8c0
.6.4 1 1 1h.5c.5 0 1-.4 1-1L4 7C5.5 6.4 6.5 5 6.5
3.4c0-2-1.3-3.5-3-3.5zm10 0l-.8 5h-.6l-.3-5h-.4L11
5H10l-.8-5H9v6.5c0 .3.2.5.5.5h1.3l-.5 8c0 .6.4 1 1 1h.4c.6 0
1-.4 1-1l-.5-8h1.3c.3 0 .5-.2.5-.5V0h-.4z"
/>
</svg>
)
}, DEFAULT_MARKER
]
}
handleMarkerClick = this.handleMarkerClick.bind(this);
handleMarkerClose = this.handleMarkerClose.bind(this);
handleMarkerClick (targetMarker) {
this.setState({
markers: this.state.markers.map(marker => {
if (marker === targetMarker) {
return {
...marker,
showInfo: true
}
}
return marker
})
})
}
handleMarkerClose (targetMarker) {
this.setState({
markers: this.state.markers.map(marker => {
if (marker === targetMarker) {
return {
...marker,
showInfo: false
}
}
return marker
})
})
}
render () {
return (
<MapGoogleMap
containerElement={
<div style={{ height: `500px` }} />
}
mapElement={
<div style={{ height: `500px` }} />
}
center={this.state.center}
markers={this.state.markers}
onMarkerClick={this.handleMarkerClick}
onMarkerClose={this.handleMarkerClose}
/>
)
}
}
A: Franklin you can use in react google maps. It has two advantages that takes it to use over info window or simple Marker component. We have Icon options to customize our marker. We have div elements that are fully customizable. You just pass icon url. LabelStyling is optional. Feel free to ask any question.
import { MarkerWithLabel } from 'react-google-maps/lib/components/addons/MarkerWithLabel';
var markerStyling= {
clear: "both", display: "inline-block", backgroundColor: "#00921A", fontWeight: '500',
color: "#FFFFFF", boxShadow: "0 6px 8px 0 rgba(63,63,63,0.11)", borderRadius: "23px",
padding: "8px 16px", whiteSpace: "nowrap", width: "160px", textAlign: "center"
};
<MarkerWithLabel
key={i}
position={marker.position}
labelAnchor={new google.maps.Point(75, 90)}
labelStyle={markerStyling}
icon={{
url: '/build/icon/markPin.svg',
anchor: new google.maps.Point(5, 58),
}}
>
<div>
<p> My Marker </p>
</div>
</MarkerWithLabel>
A: The Marker spread operator was missing above key={index}. This is the correct code. The icon itself is defined in another file called mapDefaults.js if anyone comes across this issue don't hesitate to reach out to me.
<Marker
{...marker}
key={index}
position={marker.position}
onClick={() => props.onMarkerClick(marker)}
>
A: this is how I fixed that
let iconMarker = new window.google.maps.MarkerImage(
"https://lh3.googleusercontent.com/bECXZ2YW3j0yIEBVo92ECVqlnlbX9ldYNGrCe0Kr4VGPq-vJ9Xncwvl16uvosukVXPfV=w300",
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new window.google.maps.Size(32, 32)
);
return(
<Marker
icon={iconMarker}
key={marker.id}
onClick={onClick}
position={{ lat: parseInt(marker.latitude), lng: parseInt(marker.longitude)}}>
{props.selectedMarker === marker &&
<InfoWindow>
<div style={{'color':'black'}}>
Shop {marker.name} {stretTexte}
</div>
</InfoWindow>}
</Marker>
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45337158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Page methods in asp.net not working I have a page method like following,
protected void authUser(string uid,string pass)
{}
And I am making call from javascript like this
PageMethods(uid,pass,success,error)
But it's not working
A: There are a few steps to ensure your page methods will work.
*
*Ensure you have a script manager defined with page methods enabled
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True" />
*Define your code behind with the web method attribute
[System.Web.Services.WebMethod]
public static bool authUser(string uid,string pass)
{
return true; // Do validation returning true if authenticated
}
*Define methods in client script to call the web method.
PageMethods.authUser(uid, pass, function(result) { /* succeed */ }, function(error) { });
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26794931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unity How to declare propertly Input Actions in Script CS0246 I was following a tutorial for scripting Input Actions in Unity
After finished coding what the tutorial told I've got this error in the declarations of Input System's stuff CS0246 The type or namespace name 'InputActions' could not be found
The code that causes the error is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class GameInput : MonoBehaviour
{
private InputActions InputActions;
private InputAction StartAction;
void Start() {
InputActions = new InputActions();
}
private void OnEnable() {
StartAction = InputActions.Start.Start;
StartAction.Enable();
InputActions.Start.Start.performed += StartGame;
InputActions.Start.Start.Enable();
}
public void StartGame(InputValue value) {
// CODE HERE
}
}
The error is caused by the declaration private InputActions InputActions;
I think it is by the variable type InputActions that may not exist.
But the tutorial also uses a type that doesen't exist.
How can I make Unity to recognize the InputActions type?
A: Typo: Unity does not have an InputActions Type, but it has a InputAction Type. See how you spelled the type different in your example. InputActions does not exist so you can't use it.
Change InputActions to InputAction.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68793550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Drag and Drop Knowing children.length I'm trying to allow users to order categories by dragging and dropping.
I have a code working but it just drags and drop a div into another, I need to make sure if there's a div there already he switches instead of dropping but I'm having a lot of problems.
I tried to count the children of the div before dropping but it always returns 0.
Here's my code:
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
var kids = $(data > "div").length;
alert(kids);
ev.target.appendChild(document.getElementById(data));
}
I have a cycle generating a number of this divs (div's id is managed)
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>
<div id="<%=categoria_prato.id%>" draggable="true" ondragstart="drag(event)" style = "width:100px; height:25px">Ola</div>
A: The problem with your code was that you were checking to see if the dragging div had child divs rather than the drop div. The check should be in the allowDrop which will set ev.preventDefault() if it will accept drops. There are much better examples out there for drag and drops but here is an example based on your scenario:
HTML
<div id="drop1" class="dropDiv" ondrop="drop(event)" ondragover="allowDrop(event)">
</div>
<div id="drop2" class="dropDiv" ondrop="drop(event)" ondragover="allowDrop(event)">
</div>
<div id="draggable1" draggable="true" class="dragDiv" ondragstart="drag(event)">
Drag me #1
</div>
<div id="draggable2" draggable="true" class="dragDiv" ondragstart="drag(event)">
Drag me #2
</div>
JS
function drop(ev) {
var id = ev.dataTransfer.getData("text");
$('#' + id).appendTo(ev.target);
}
function allowDrop(ev) {
// Only check the parent div with id starting with drop and not the child div
if(ev.target.id.indexOf('drop') == 0) {
var count = $('#' + ev.target.id + ' > div').length;
if(count < 1) {
//allow the drop
ev.preventDefault();
}
else
{
// NOPE
}
}
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
https://jsfiddle.net/astynax777/dq3emchj/23/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37414970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Initializing in Constructor I have seen lots of codes where the coders define an init() function for classes and call it the first thing after creating the instance.
Is there any harm or limitation of doing all the initializations in Constructor?
A: Usually for maintainability and to reduce code size when multiple constructors call the same initialization code:
class stuff
{
public:
stuff(int val1) { init(); setVal = val1; }
stuff() { init(); setVal = 0; }
void init() { startZero = 0; }
protected:
int setVal;
int startZero;
};
A: Just the opposite: it's usually better to put all of the initializations
in the constructor. In C++, the "best" policy is usually to put the
initializations in an initializer list, so that the members are
directly constructed with the correct values, rather than default
constructed, then assigned. In Java, you want to avoid a function
(unless it is private or final), since dynamic resolution can put
you into an object which hasn't been initialized.
About the only reason you would use an init() function is because you
have a lot of constructors with significant commonality. (In the case
of C++, you'd still have to weigh the difference between default
construction, then assignment vs. immediate construction with the
correct value.)
A: In Java, there's are good reasons for keeping constructors short and moving initialization logic into an init() method:
*
*constructors are not inherited, so any subclasses have to either reimplement them or provide stubs that chain with super
*you shouldn't call overridable methods in a constructor since you can find your object in an inconsistent state where it is partially initialized
A: It's a design choice. You want to keep your constructor as simple as possible, so it's easy to read what it's doing. That why you'll often see constructors that call other methods or functions, depending on the language. It allows the programmer to read and follow the logic without getting lost in the code.
As constructors go, you can quickly run into a scenario where you have a tremendous sequence of events you wish to trigger. Good design dictates that you break down these sequences into simpler methods, again, to make it more readable and easier to maintain in the future.
So, no, there's no harm or limitation, it's a design preference. If you need all that initialisation done in the constructor then do it there. If you only need it done later, then put it in a method you call later. Either way, it's entirely up to you and there are no hard or fast rules around it.
A: It is a design pattern that has to do with exceptions thrown from inside an object constructor.
In C++ if an exception is thrown from inside an object costructor then that object is considered as not-constructed at all, by the language runtime.
As a consequence the object destructor won't be called when the object goes out of scope.
This means that if you had code like this inside your constructor:
int *p1 = new int;
int *p2 = new int;
and code like this in your destructor:
delete p1;
delete p2;
and the initialization of p2 inside the constructor fails due to no more memory available, then a bad_alloc exception is thrown by the new operator.
At that point your object is not fully constructred, even if the memory for p1 has been allocated correctly.
If this happens the destructor won't be called and you are leaking p1.
So the more code you place inside the constructor, the more likely an error will occur leading to potential memory leaks.
That's the main reason for that design choice, which isn't too mad after all.
More on this on Herb Sutter's blog: Constructors exceptions in C++
A: If you have multiple objects of the same class or different classes that need to be initialized with pointers to one another, so that there is at least one cycle of pointer dependency, you can't do all the initialization in constructors alone. (How are you going to construct the first object with a pointer/reference to another object when the other object hasn't been created yet?)
One situation where this can easily happen is in an event simulation system where different components interact, so that each component needs pointers to other components.
Since it's impossible to do all the initialization in the constructors, then at least some of the initialization has to happen in init functions. That leads to the question: Which parts should be done in init functions? The flexible choice seems to be to do all the pointer initialization in init functions. Then, you can construct the objects in any order since when constructing a given object, you don't have to be concerned about whether you already have the necessary pointers to the other objects it needs to know about.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10494166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: C++ Qt program design issue In C++ Qt there is a class QWidget
*
*class A inherits QWidget and adds some features
*class B inherits A and adds some features
*class C inherits B and adds some features, C must be of type QWidget and should do all things done by B
For some reason C is not behaving as expected, I have to rewrite class C. I can not modify code up to class B creation.
How can I solve this problem? Any design pattern, or anything else?
If I try to inherit QWidget and B, a multiple inheritance, there will be two QWidget which leads to problem (QObject - moc does not allow it).
If I inherit from QWidget and pass object of B to C's constructor, whatever operation B performs applies to another QWidget coming through B, which is not desired, all features provided by B should apply to my C's QWidget.
A:
Suppose there is a temperature sensor, when that gets disconnected from machine, class B draws a content blocker image on the whole area of QWidget that it owns, I can monitor sensor connect /disconnect and suppose C's fun. OnDisconnect() gets called, I will call B::OnDisconnect(), B will draw blocker image on its own QWidget, not on the one which is owned by C.
This has everything to do with C++'s rather inflexible method implementation inheritance when compared e.g. to the Common LISP Object System.
Since B's obscuration is always meant to be on top of B's contents, what you effectively need is for B to provide an overlay that draws on top of its contents, even if paintEvent is overriden in derived classes.
See this answer for a simple example, or another answer for an overlay with blur graphical effect.
This is fairly easy to accomplish by having B add an optional overlay widget to itself.
Example:
class OverlayWidget; // from https://stackoverflow.com/a/19367454/1329652
class ObscureOverlay : public OverlayWidget
{
public:
ObscureOverlay(QWidget * parent = {}) : OverlayWidget{parent} {}
protected:
void paintEvent(QPaintEvent *) override {
QPainter p{this};
p.fillRect(rect(), {Qt::black});
}
};
class A : public QWidget {
...
protected:
void paintEvent(QPaintEvent *) override { ... }
};
class B : public A {
...
ObscureOverlay m_obscure{this};
public:
B() {
m_obscure.hide();
}
Q_SLOT void OnDisconnect() {
m_obscure.show();
...
}
};
class C : public B {
...
protected:
void paintEvent(QPaintEvent * event) override {
B::paintEvent(event);
...
}
};
If you don't have the source code to B, you can add the overlay to C, replicating original B's functionality when obscured. All of Qt's slots are effectively virtual, so if you pass a C to someone expecting B and connecting to its OnDisconnect slot, it will be C's slot that will get invoked.
class C : public B {
Q_OBJECT
...
ObscureOverlay m_obscure{this};
public:
explicit C(QWidget * parent = {}) : B{parent} {
m_obscure.hide();
}
Q_SLOT void OnDisconnect() { // slots are effectively virtual
m_obscure.show();
B::OnDisconnect();
}
protected:
void paintEvent(QPaintEvent * event) override {
B::paintEvent(event);
QPainter p{this};
...
}
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43642285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: read multiple audio file (wav) and convert using wiener filtering to different name and audio I am trying to use wiener filtering to convert the 824 audio in one folder to a different folder. How can I create a module for accessing these audio, running the wiener and save it to different folder by python? What I am doing right now just convert it one by one. Here's the code:
import numpy as np
import wave
import matplotlib.pyplot as plt
import math
from scipy.io import wavfile
import glob
import tqdm
#import nextpow2
'''
# input wave file (clean)
f1 = wave.open('p232_006.wav')
# read format information
# (nchannels, sampwidth, framerate, nframes, comptype, compname)
params1 = f1.getparams()
nchannels1, sampwidth1, framerate1, nframes1 = params1[:4]
fs1 = framerate1
# read wave data
str_data1 = f1.readframes(nframes1)
# close .wav file
f1.close()
# convert waveform data to an array
x1 = np.fromstring(str_data1, dtype=np.short)
'''
# noisy speech FFT
#x1_FFT = abs(np.fft.fft(x1))
# input wave file (noise)
f = wave.open('p257_434ch0_16k.wav')
#test_wav = sorted(glob.glob("./noisy_testset_wav_16*.wav"))
#for i, (test_wav) in tqdm(enumerate(zip(test_wav))):
# f = wavfile.read(test_wav)
# read format information
# (nchannels, sampwidth, framerate, nframes, comptype, compname)
params = f.getparams()
nchannels, sampwidth, framerate, nframes = params[:4]
fs = framerate
# read wave data
str_data = f.readframes(nframes)
# close .wav file
f.close()
# convert waveform data to an array
x = np.fromstring(str_data, dtype=np.short)
# noisy speech FFT
x_FFT = abs(np.fft.fft(x))
# calculation parameters
len_ = 20 * fs // 1000 # frame size in samples
PERC = 50 # window overlop in percent of frame
len1 = len_ * PERC // 100 # overlop'length
len2 = len_ - len1 # window'length - overlop'length
# setting default parameters
Thres = 3 # VAD threshold in dB SNRseg
Expnt = 1.0
beta = 0.002
G = 0.9
# hamming window
#win = np.hamming(len_)
# sine window
i = np.linspace(0,len_ - 1,len_)
win = np.sqrt(2/(len_ + 1)) * np.sin(np.pi * (i + 1) / (len_ + 1))
# normalization gain for overlap+add with 50% overlap
winGain = len2 / sum(win)
# nFFT = 2 * 2 ** (nextpow2.nextpow2(len_))
nFFT = 2 * 2 ** 8
noise_mean = np.zeros(nFFT)
j = 1
for k in range(1, 6):
noise_mean = noise_mean + abs(np.fft.fft(win * x[j:j + len_], nFFT))
j = j + len_
noise_mu = noise_mean / 5
# initialize various variables
k = 1
img = 1j
x_old = np.zeros(len1)
Nframes = len(x) // len2 - 1
xfinal = np.zeros(Nframes * len2)
# === Start Processing ==== #
for n in range(0, Nframes):
# Windowing
insign = win * x[k-1:k + len_ - 1]
# compute fourier transform of a frame
spec = np.fft.fft(insign, nFFT)
# compute the magnitude
sig = abs(spec)
# save the noisy phase information
theta = np.angle(spec)
# Posterior SNR
SNRpos = 10 * np.log10(np.linalg.norm(sig, 2) ** 2 / np.linalg.norm(noise_mu, 2) ** 2)
# --- wiener filtering --- #
# 1 spectral subtraction(Half wave rectification)
sub_speech = sig ** Expnt - noise_mu ** Expnt
# When the pure signal is less than the noise signal power
diffw = sig ** Expnt - noise_mu ** Expnt
# beta negative components
def find_index(x_list):
index_list = []
for i in range(len(x_list)):
if x_list[i] < 0:
index_list.append(i)
return index_list
z = find_index(diffw)
if len(z) > 0:
sub_speech[z] = 0
# Priori SNR
SNRpri = 10 * np.log10(np.linalg.norm(sub_speech, 2) ** 2 / np.linalg.norm(noise_mu, 2) ** 2)
# parameter to deal mel
mel_max = 10
mel_0 = (1 + 4 * mel_max) / 5
s = 25 / (mel_max - 1)
# deal mel
def get_mel(SNR):
if -5.0 <= SNR <= 20.0:
a = mel_0 - SNR / s
else:
if SNR < -5.0:
a = mel_max
if SNR > 20:
a = 1
return a
# setting mel
mel = get_mel(SNRpri)
# 2 gain function Gk
#G_k = (sig ** Expnt - noise_mu ** Expnt) / sig ** Expnt
G_k = sub_speech ** 2 / (sub_speech ** 2 + mel * noise_mu ** 2)
#wf_speech = G_k * sub_speech ** (1 / Expnt)
wf_speech = G_k * sig
# --- implement a simple VAD detector --- #
if SNRpos < Thres: # Update noise spectrum
noise_temp = G * noise_mu ** Expnt + (1 - G) * sig ** Expnt # Smoothing processing noise power spectrum
noise_mu = noise_temp ** (1 / Expnt) # New noise amplitude spectrum
# add phase
#wf_speech[nFFT // 2 + 1:nFFT] = np.flipud(wf_speech[1:nFFT // 2])
x_phase = wf_speech * np.exp(img * theta)
# take the IFFT
xi = np.fft.ifft(x_phase).real
# --- Overlap and add --- #
xfinal[k-1:k + len2 - 1] = x_old + xi[0:len1]
x_old = xi[0 + len1:len_]
k = k + len2
# save wave file
wf = wave.open('p257_434.wav','w')
# setting parameter
wf.setparams(params)
# set waveform file .tostring()Convert array touput data
wave_data = (winGain * xfinal).astype(np.short)
wf.writeframes(wave_data.tostring())
# close wave file
wf.close()
# enchanced speech FFT
es_FFT = abs(np.fft.fft(winGain * xfinal))
any help would be appreaciated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75394157",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: TF_NewTensor Segmentation Fault: Possible Bug? I'm using Tensorflow 2.1 git master branch (commit id:db8a74a737cc735bb2a4800731d21f2de6d04961) and compile it locally. Playing around with the C API to call TF_LoadSessionFromSavedModel but seems to get segmentation fault. I've managed to drill down the error in the sample code below.
TF_NewTensor call is crashing and causing a segmentation fault.
int main()
{
TF_Tensor** InputValues = (TF_Tensor**)malloc(sizeof(TF_Tensor*)*1);
int ndims = 1;
int64_t* dims = malloc(sizeof(int64_t));
int ndata = sizeof(int32_t);
int32_t* data = malloc(sizeof(int32_t));
dims[0] = 1;
data[0] = 10;
// Crash on the next line
TF_Tensor* int_tensor = TF_NewTensor(TF_INT32, dims, ndims, data, ndata, NULL, NULL);
if(int_tensor == NULL)
{
printf("ERROR");
}
else
{
printf("OK");
}
return 0;
}
However, when i move the TF_Tensor** InputValues = (TF_Tensor**)malloc(sizeof(TF_Tensor*)*1); after the TF_NewTensor call, it doesn't crash. Like below:
int main()
{
int ndims = 1;
int64_t* dims = malloc(sizeof(int64_t));
int ndata = sizeof(int32_t);
int32_t* data = malloc(sizeof(int32_t));
dims[0] = 1;
data[0] = 10;
// NO more crash
TF_Tensor* int_tensor = TF_NewTensor(TF_INT32, dims, ndims, data, ndata, NULL, NULL);
if(int_tensor == NULL)
{
printf("ERROR");
}
else
{
printf("OK");
}
TF_Tensor** InputValues = (TF_Tensor**)malloc(sizeof(TF_Tensor*)*1);
return 0;
}
Is it a possible bug or I'm using it wrong? I don't understand how mallocq an independent variable could cause a segmentation fault.
can anybody reproduce?
I'm using gcc (Ubuntu 9.2.1-9ubuntu2) 9.2.1 20191008 to compile.
UPDATE:
can be further simplified the error as below. This is even without the InputValues being allocated.
#include <stdlib.h>
#include <stdio.h>
#include "tensorflow/c/c_api.h"
int main()
{
int ndims = 1;
int ndata = 1;
int64_t dims[] = { 1 };
int32_t data[] = { 10 };
TF_Tensor* int_tensor = TF_NewTensor(TF_INT32, dims, ndims, data, ndata, NULL, NULL);
if(int_tensor == NULL)
{
printf("ERROR Tensor");
}
else
{
printf("OK");
}
return 0;
}
compile with
gcc -I<tensorflow_path>/include/ -L<tensorflow_path>/lib test.c -ltensorflow -o test2.out
Solution
As point up by Raz, pass empty deallocater instead of NULL, and ndata should be size in terms of byte.
#include "tensorflow/c/c_api.h"
void NoOpDeallocator(void* data, size_t a, void* b) {}
int main(){
int ndims = 2;
int64_t dims[] = {1,1};
int64_t data[] = {20};
int ndata = sizeof(int64_t); // This is tricky, it number of bytes not number of element
TF_Tensor* int_tensor = TF_NewTensor(TF_INT64, dims, ndims, data, ndata, &NoOpDeallocator, 0);
if (int_tensor != NULL)\
printf("TF_NewTensor is OK\n");
else
printf("ERROR: Failed TF_NewTensor\n");
}
checkout my Github on full code of running/compile TensorFlow's C API here
A: You set ndata to be sizeof(int32_t) which is 4.
Your ndata is passed as len argument to TF_NewTensor() which represents the number of elements in data (can be seen in GitHub). Therefore, it should be set to 1 in your example, as you have a single element.
By the way, you can avoid using malloc() here (as you don't check for return values, and this may be error-pront and less elegant in general) and just use local variables instead.
UPDATE
In addition, you pass NULL both for deallocator and deallocator_arg. I'm pretty sure this is the issue as the comment states "Clients must provide a custom deallocator function..." (can be seen here). The deallocator is called by the TF_NewTensor() (can be seen here) and this may be the cause for the segmentation fault.
So, summing it all up, try the next code:
void my_deallocator(void * data, size_t len, void * arg)
{
printf("Deallocator called with data %p\n", data);
}
void main()
{
int64_t dims[] = { 1 };
int32_t data[] = { 10 };
... = TF_NewTensor(TF_INT32, dims, /*num_dims=*/ 1, data, /*len=*/ 1, my_deallocator, NULL);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59874176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: PHP time diffrence hourly competetion on site I am working on a small app in php using codeigniter.
App have a jquery countdown timer which countdown time left for current competition. Competition is hourly based and Gloabal(I am saying Global here to indicate that for everyone competition will finish at same time - Taking server time)
Here is logic I am using:
As competition is hourly and will be 24 competitions in a day. So what I am doing is: I made a timestamps field in database and updating (current timestamp + 1 hr) each hour using cron job. This time is end time of competition.
Then when user is going to app I am calling a function which getting competition end time and current time. Then getting difference of this time and time left i am putting in java script count downer to show time left.
Now problem:
Everthing is working fine except when time is at 12 to 1. Counter always shows negative time. Means time diffrece is coming to negative.
What I tried:
I tried to put
date_default_timezone_set('Europe/London');
but no luck!
Here is my code:
$query="SELECT comp_end_time FROM competetions WHERE comp_type=1 ORDER BY comp_id DESC LIMIT 1";
$sql=mysql_query($query);
$row=mysql_fetch_array($sql);
date_default_timezone_set('Europe/London');
$end_time=strtotime($row['comp_end_time']);
$now=date("Y-m-d g:i:s");
$current_time=strtotime($now);
$time_diff=$end_time-$current_time;
$minutes=floor($time_diff / 60);
$sec = $time_diff - ($minutes * 60);
$minutes=(strlen($minutes) == 1) ? '0'.$minutes: $minutes;
$sec=(strlen($sec) == 1) ? '0'.$sec: $sec;
$min1=substr($minutes, 0, 1);
$min2=substr($minutes, 1, 2);
$sec1=substr($sec, 0, 1);
$sec2=substr($sec, 1, 2);
$data=array(
'min1'=>$min1,
'min2'=>$min2,
'sec1'=>$sec1,
'sec2'=>$sec2
);
return $data;
}
And here is code to update time using cron:
function update_timer(){
date_default_timezone_set('Europe/London');
$now=date("Y-m-d g:i:s");
$currentTime=strtotime($now);
$timeAfterOneHour=$currentTime+60*60;
$new_hr=date("Y-m-d g:i:s",$timeAfterOneHour);
echo date("Y-m-d g:i:s",$currentTime).'<br>';
echo $new_hr;
mysql_query("UPDATE `zaggora1_hotpant`.`competetions` SET `comp_end_time` = '$new_hr' WHERE `competetions`.`comp_id` =1;");
}
Anybody know why time difference is coming negative?
Any suggestion to use some different way to accomplish this task? Do i have to use codeigniter date helped etc?
A: Here are a few things I would change:
$now=date("Y-m-d g:i:s");
$current_time=strtotime($now);
This can be reduced to simply:
$current_time = time();
For your cron script:
$now=date("Y-m-d g:i:s");
$currentTime=strtotime($now);
$timeAfterOneHour=$currentTime+60*60;
$new_hr=date("Y-m-d g:i:s",$timeAfterOneHour);
Can be changed to:
$currentTime = time();
$timeAfterOneHour=$currentTime+60*60;
$new_hr=date("Y-m-d H:i:s",$timeAfterOneHour);
Notice the H instead of g in the date() format? That's because times are easier to compare if you use a 24hr clock with leading zeroes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12087800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: ng-if shows both elements I have two buttons that are using ng-if to determine if they should be shown or not. For a brief second, both elements are shown even though they should not be shown together ever. In isolated examples, this works fine, but in my project it has some latency. Very similar to this post: Angular conditional display using ng-if/ng-show/ng-switch briefly shows both elements but that didn't have any answers that were different than what I tried.
<button class="btn btn-primary drop_shadow" ng-if="vm.ingestReady == true"
ng-click="vm.ingestReady = !vm.ingestReady" ng-cloak> Start Ingest
</button>
<button class="btn btn-danger drop_shadow" ng-if="vm.ingestReady == false"
ng-click="vm.ingestReady = !vm.ingestReady" ng-cloak>Cancel Ingest
</button>
And controller code is
vm.ingestReady = true;
on page load. So clicking the button should just toggle the view, but for a hot second, both are visible.
A: This is caused by ngAnimate. Try to remove it, if you are not using it.
If you don't want to remove ngAnimate, add the following css to your app.
.ng-leave {
display:none !important;
}
For more detailed answer angular ng-if or ng-show responds slow (2second delay?)
A: ng-cloak works using CSS, so you'll need to add this to your styles:
[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
display: none !important;
}
On a side note, ng-bind (and ng-class for the btn-primary/btn-danger) may be a better solution for this type of problem. You can bind the button's contents to a JS variable or function like so:
<button class="btn drop_shadow"
ng-class="getButtonClass()"
ng-bind="getButtonText()"
ng-click="vm.ingestReady = !vm.ingestReady"></button>
And then, in the button's scope, you'd just have to add the two referenced JS functions (cleaner than putting this logic inline):
$scope.getButtonClass = function() {
return vm.ingestReady ? 'btn-primary' : 'btn-danger';
};
$scope.getButtonText = function() {
return vm.ingestReady ? 'Start Ingest' : 'Cancel Ingest';
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38021648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Simple fraction definition in Scilab but the answer is wrong I have the following function f(x)=1/(x^5+1) like in this youtube video, but when I try to implement it in Scilab, I get the wrong answers:
-->deff('y=f(x)','y=1/(1+(x.^5))')
-->x=0:.5:3
x =
0. 0.5 1. 1.5 2. 2.5 3.
-->w=f(x)
w =
0.0000142
0.0000146
0.0000284
0.0001220
0.0004685
0.0014006
0.0034640
The w vector should have the following values:
1
0.96969697
0.5
0.116363636
0.03030303
0.010136205
0.004098361
What I have made wrong? I suppose it is because of the fraction.
A: Defining the function like this :
-->deff('y=f(x)','y=ones(x)./(1+(x.^5))')
Will give the expected result :
-->f(0:.5:3)
ans =
1. 0.9696970 0.5 0.1163636 0.0303030 0.0101362 0.0040984
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23971557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Symfony routing: _controller special param What is the use cases of _controller special param in Symfony routing system ?
The doc says:
As you've seen, this parameter is used to determine which controller is executed when the route is matched.
But I already have controller configuration key to determine which controller to execute:
homepage:
path: /
controller: App\Controller\DefaultController::homepageAction
Using _controller param the very same result can be achived this way:
homepage:
path: /
defaults:
_controller: App\Controller\DefaultController::homepageAction
So, this is it ? Or does it has some other scenarios it can be used for ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51150191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Flyway exception with flyway.clean() - Can't drop without CASCADE specification While using flyway.clean() -
I get the following error:
Message : SAP DBTech JDBC: [417]: can't drop without CASCADE
specification: cannot drop table referenced by foreign key.
Is there a way to make Flyway cascade drop all objects?
A: This sounds like a bug. Please file an issue in the issue tracker including the smallest possible bit of SQL that triggers this.
A: If you want to drop tables that have foreign key constraints on SAP HANA you either have to drop those constraints before or you have to specify the CASCADE command option.
This is documented in the SAP HANA SQL reference guide.
Note, that CASCADE will drop all dependent objects, not just constraints.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47839445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to apply different section to a radio button I have this project for school, to show different drop-down option for each selected radio button. I tried few JavaScript code but it wasn't working at all.
I need when clicked on Sizes radio button to show the correspondent sizes drop-down selectors.
As well for the colors. To show only colors drop-down selectors
Thank you in advance for the help.
Bellow is the code
<form>
<fieldset>
<p>
<input type = "radio"
name = "sizes"
id = "sizes"
value = ""
checked = "checked">
<label for = "sizes"> Sizes </label>
<input type = "radio"
name = "colors"
id = "colors"
value = "">
<label for = "colors"> Colors </label>
</p>
</fieldset>
</form>
<label for="small-size"> Small Size </label>
<select name="size" id="size">
<option value="1" selected> Size 1 </option>
<option value="2"> Size 2 </option>
<option value="3"> Size 3 </option>
</select>
<label for="big-size"> Big Size </label>
<select name="size" id="size">
<option value="1" selected> Size 1 </option>
<option value="2"> Size 2 </option>
<option value="3"> Size 3 </option>
</select>
<label for="dark"> Dark Colors </label>
<select name="canvas" id="canvas">
<option value="1" selected> Color 1</option>
<option value="2"> Color 2 </option>
<option value="3"> Color 3 </option>
</select>
<label for="light"> Light Colors </label>
<select name="canvas" id="canvas">
<option value="1" selected> Color 1</option>
<option value="2"> Color 2 </option>
<option value="3"> Color 3 </option>
</select>
https://jsfiddle.net/Farsoun/dw813ky2/9/
A: You should really show at least an attempt of some sort when posting something like this, especially with the JavaScript tag.
Anyways, to do this you would want to listen to when a user clicks on a radio button and show/hide the corresponding elements.
Here's a sample:
document.getElementById('colors').addEventListener("click", function(e){
document.getElementById("colors-selections").style.display = "block";
document.getElementById("size-selections").style.display = "none";
});
If you have more than two elements in the future, I'd recommend using an onchange so you can hide it once it's untoggled rather than hiding everything else everytime a new radio button is clicked.
If you want to use just CSS you're going to have to used the :checked attribute and hide or display another element also:
Other users already have asked about this, ex:
https://stackoverflow.com/a/50921066/4107932
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62190529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Servicestack user session not working I have an API written in ServiceStack and I am attempting to build in authentication for clients. At the moment this API will only be accessed by Android clients (Xamarin / C#). The API itself is running on a Debian server with Apache / mod_mono
After reading up on Github, I am still not 100% sure how to put this together in such a way that... once the client has provided valid credentials (For testing, basic HTTP authentication) the user gets a session and the credentials are not checked again on subsequent requests from the same session.
AppHost Class:
{
public class AppHost
: AppHostBase
{
public AppHost() //Tell ServiceStack the name and where to find your web services
: base("Service Call Service", typeof(ServiceCallsService).Assembly) { }
public override void Configure(Funq.Container container)
{
//Set JSON web services to return idiomatic JSON camelCase properties
ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;
// Session storage
container.Register<ICacheClient>(new MemoryCacheClient());
// auth feature and session feature
Plugins.Add(new AuthFeature(
() => new AuthUserSession(),
new[] { new userAuth() }
) { HtmlRedirect = null } );
}
public class userAuth : BasicAuthProvider
{
public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
{
peruseAuth peruseAuthHandler= new peruseAuth();
errorLogging MyErrorHandler = new errorLogging() ;
if (peruseAuthHandler.ValidateUser(authService, userName, password))
{
try
{
var session = (AuthUserSession)authService.GetSession(false);
session.UserAuthId = userName;
session.IsAuthenticated = true;
return true;
}
catch(Exception ex)
{
MyErrorHandler.LogError(ex, this) ;
return false ;
}
}
else
{
Console.Write("False");
return false;
}
}
}
The JsonServiceClient: (Just the "login" event)
btnLogin.Click += (sender, e) =>
{
// Set credentials from EditText elements in Main.axml
client.SetCredentials(txtUser.Text, txtPass.Text);
// Force the JsonServiceClient to always use the auth header
client.AlwaysSendBasicAuthHeader = true;
};
I've been doing a bit of logging, and it seems that every time the client performs an action their username/password is being checked against the database. Is there something wrong here, or is this the expected result?
A: For Basic Auth where the credentials are sent on each request it's expected.
In order for the ServiceClient to retain the Session cookies that have been authenticated you should set the RememberMe flag when you authenticate, e.g using CredentialsAuthProvider:
var client = new JsonServiceClient(BaseUrl);
var authResponse = client.Send(new Authenticate {
provider = "credentials",
UserName = "user",
Password = "p@55word",
RememberMe = true,
});
Behind the scenes this attaches the user session to the ss-pid cookie (permanent session cookie), which the client retains and resends on subsequent requests from that ServiceClient instance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19032720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Scala self implemented Boolean shows several errors I have follow the coursera course of "Funcitonal Programming Principles in Scala" by Martin Odersky. For its week4 4.2 video of "Objects Everywhere", I have follow the step to implement my own Boolean class, but the eclipse shows several errors as following:
package week4
object Main{
abstract class Boolean{
def ifThenElse[T](e1: => T, e2: => T): T
def && (b2: => Boolean): Boolean = ifThenElse(b2,False)
def || (b2: => Boolean): Boolean = ifThenElse(True,b2)
def unary_!: Boolean = ifThenElse(False,True) //error1
def == (b2: Boolean): Boolean = ifThenElse(b2, b2.unary_!) //error2
def != (b2: Boolean): Boolean = ifThenElse(b2.unary_!, b2) //error3
}
object True extends Boolean{
def ifThenElse[T](e1: => T, e2: => T): T = e1
}
object False extends Boolean{
def ifThenElse[T](e1: => T, e2: => T): T = e2
}
def main(args: Array[String]) {
println("Hello, world!2")
True.ifThenElse(println("True"), println("Flase"))
}
}
error1: = expected by identifier found.
error2:
multiple markers at this line
*
*illegal start of simple expression
*call-by-name parameter creation():=>b2
*value unary! is not a member of week4.Main.Boolean
error3:
multiple markers at this line
*
*call-by-name parameter creation():=>b2
*value unary! is not a member of week4.Main.Boolean
Does anyone have any idea why this happens?
A: You just need a space between unary_! and the :
def unary_! : Boolean = ifThenElse(False,True)
Alternatively, as pointed out by hezamu in the comments you can use parentheses (with or without the space)
def unary_!(): Boolean = ifThenElse(False,True)
This will work although it is worth noting that there is a convention in Scala that parentheses on a no-args method indicate that it has side effects which is not the case here.
A third option where the return type can be inferred by the compiler (as is the case in this example) is to omit the return type entirely:
def unary_! = ifThenElse(False, True)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37088478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Creating dynamic context menu item in jstree I wanted to create a dynamic context menu based on my server response. The static menu works fine without any issues. The below is my jstree content and it calls customMenu method
$("#myList").jstree({
"core" : {
"animation" : 0,
"check_callback" : true,
//"themes" : "default" ,
'data': {
"data": function (node) {
return { "id": node.id };
}
}
},
"plugins" : [ "search", "contextmenu"],
"contextmenu" : { "items" : customMenu }
});
My customMenu function
function customMenu(node) {
var menuitems=[];
$.ajax({
url : "DynamicMenu",
dataType : 'json',
data: {menu: node.id, node: node.children.length},
error : function() {
alert("Error Occured");
},
success : function(data) {
$.each(data, function(index, value) {
//Want to populate my menu here
});
}
});
// The default set of all items. This works fine
menuitems = {
restartItem: {
label: "Restart",
action: function () {
}
},
stopItem: {
label: "Stop",
action: function () {}
}
};
return menuitems;
}
I tried creating a dynamic menu by using below 2 options, but it didnt help.
*
*menuitems.push()
menuitems.push({restartItem: {
label: "Restart",
action: function () {
}
}});
*menuitems[index]={mydata}
menuitems[0] = {restartItem: {
label: "Restart",
action: function () {
}
}};
Both the above options didn't help ? I will replace the values dynamically based on my ajax response. But first I need one this option to work
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46278052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Create new column with binary data based on several columns I have a dataframe in which I want to create a new column with 0/1 (which would represent absence/presence of a species) based on the records in previous columns. I've been trying this:
update_cat$bobpresent <- NA #creating the new column
x <- c("update_cat$bob1999", "update_cat$bob2000", "update_cat$bob2001","update_cat$bob2002", "update_cat$bob2003", "update_cat$bob2004", "update_cat$bob2005", "update_cat$bob2006","update_cat$bob2007", "update_cat$bob2008", "update_cat$bob2009") #these are the names of the columns I want the new column to base its results in
bobpresent <- function(x){
if(x==NA)
return(0)
else
return(1)
} # if all the previous columns are NA then the new column should be 0, otherwise it should be 1
update_cat$bobpresence <- sapply(update_cat$bobpresent, bobpresent) #apply the function to the new column
Everything is going fina until the last string where I'm getting this error:
Error in if (x == NA) return(0) else return(1) :
missing value where TRUE/FALSE needed
Can somebody please advise me?
Your help will be much appreciated.
A: By definition all operations on NA will yield NA, therefore x == NA always evaluates to NA. If you want to check if a value is NA, you must use the is.na function, for example:
> NA == NA
[1] NA
> is.na(NA)
[1] TRUE
The function you pass to sapply expects TRUE or FALSE as return values but it gets NA instead, hence the error message. You can fix that by rewriting your function like this:
bobpresent <- function(x) { ifelse(is.na(x), 0, 1) }
In any case, based on your original post I don't understand what you're trying to do. This change only fixes the error you get with sapply, but fixing the logic of your program is a different matter, and there is not enough information in your post.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16222438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to enable JSON calls in my ASP.NET MVC 2 application? I'm trying to make a dynamic chart using HighCharts, but as it seems to be, is impossible to include ASP tags inside a JavaScript, so I'm trying to use JSon. I followed this tutorual step-by-step, but when I try to load the page, I get the following message:
This request has been blocked because
sensitive information could be
disclosed to third party web sites
when this is used in a GET request. To
allow GET requests, set
JsonRequestBehavior to AllowGet.
So now I'm wondering if I have to set something in Web.Config or somewhere else.
Could you guys help me?
A: There is a pretty simple fix. In your request-handling functions, where you would have:
return Json(myStuff);
Replace it with the overload that takes a JsonRequestBehavior:
return Json(myStuff, JsonRequestBehavior.AllowGet);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4444390",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: error deploying meteor app on heroku I have deployed my app on heroku and locally it works just fine, however when I open my app I get this message "Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details."
when I type "heroku logs" I get this
2016-12-30T15:44:46.897189+00:00 app[web.1]: npm ERR! Linux 3.13.0-105-generic
2016-12-30T15:44:46.897612+00:00 app[web.1]: npm ERR! argv "/app/.heroku/node/bin/node" "/app/.heroku/node/bin/npm" "start"
2016-12-30T15:44:46.897905+00:00 app[web.1]: npm ERR! node v6.9.1
2016-12-30T15:44:46.898079+00:00 app[web.1]: npm ERR! npm v3.10.8
2016-12-30T15:44:46.898366+00:00 app[web.1]: npm ERR! file sh
2016-12-30T15:44:46.898559+00:00 app[web.1]: npm ERR! code ELIFECYCLE
2016-12-30T15:44:46.898734+00:00 app[web.1]: npm ERR! errno ENOENT
2016-12-30T15:44:46.898904+00:00 app[web.1]: npm ERR! syscall spawn
2016-12-30T15:44:46.899048+00:00 app[web.1]: npm ERR! microscope@ start: `meteor run`
2016-12-30T15:44:46.899172+00:00 app[web.1]: npm ERR! spawn ENOENT
2016-12-30T15:44:46.899311+00:00 app[web.1]: npm ERR!
2016-12-30T15:44:46.899449+00:00 app[web.1]: npm ERR! Failed at the microscope@ start script 'meteor run'.
2016-12-30T15:44:46.899572+00:00 app[web.1]: npm ERR! Make sure you have the latest version of node.js and npm installed.
2016-12-30T15:44:46.899691+00:00 app[web.1]: npm ERR! If you do, this is most likely a problem with the microscope package,
2016-12-30T15:44:46.899815+00:00 app[web.1]: npm ERR! not with npm itself.
2016-12-30T15:44:46.899940+00:00 app[web.1]: npm ERR! Tell the author that this fails on your system:
2016-12-30T15:44:46.900061+00:00 app[web.1]: npm ERR! meteor run
2016-12-30T15:44:46.900422+00:00 app[web.1]: npm ERR! Or if that isn't available, you can get their info via:
2016-12-30T15:44:46.900183+00:00 app[web.1]: npm ERR! You can get information on how to open an issue for this project with:
2016-12-30T15:44:46.900301+00:00 app[web.1]: npm ERR! npm bugs microscope
2016-12-30T15:44:46.900543+00:00 app[web.1]: npm ERR! npm owner ls microscope
2016-12-30T15:44:46.900664+00:00 app[web.1]: npm ERR! There is likely additional logging output above.
2016-12-30T15:44:46.903931+00:00 app[web.1]:
2016-12-30T15:44:46.904248+00:00 app[web.1]: npm ERR! Please include the following file with any support request:
2016-12-30T15:44:46.904362+00:00 app[web.1]: npm ERR! /app/npm-debug.log
2016-12-30T15:44:46.985527+00:00 heroku[web.1]: Process exited with status 1
2016-12-30T15:44:46.999587+00:00 heroku[web.1]: State changed from starting to crashed
2016-12-30T15:45:19.580505+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=hellohellohell.herokuapp.com request_id=33676d4a-942f-4621-b3e0-c3eaa486b0f1 fwd="41.217.180.223" dyno= connect= service= status=503 bytes=
2016-12-30T15:45:23.940363+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=hellohellohell.herokuapp.com request_id=d9096c8d-16df-48b3-89a6-98cdf989150c fwd="41.217.180.223" dyno= connect= service= status=503 bytes=
2016-12-30T15:48:05.018401+00:00 heroku[web.1]: State changed from crashed to starting
2016-12-30T15:48:06.814270+00:00 heroku[web.1]: Starting process with command `npm start`
2016-12-30T15:48:10.009640+00:00 app[web.1]:
2016-12-30T15:48:10.009656+00:00 app[web.1]: > microscope@ start /app
2016-12-30T15:48:10.009657+00:00 app[web.1]: > meteor run
2016-12-30T15:48:10.009658+00:00 app[web.1]:
2016-12-30T15:48:10.017655+00:00 app[web.1]: sh: 1: meteor: not found
2016-12-30T15:48:10.033331+00:00 app[web.1]: npm ERR! Linux 3.13.0-105-generic
2016-12-30T15:48:10.023737+00:00 app[web.1]:
2016-12-30T15:48:10.033621+00:00 app[web.1]: npm ERR! argv "/app/.heroku/node/bin/node" "/app/.heroku/node/bin/npm" "start"
2016-12-30T15:48:10.033903+00:00 app[web.1]: npm ERR! node v6.9.1
2016-12-30T15:48:10.034339+00:00 app[web.1]: npm ERR! npm v3.10.8
2016-12-30T15:48:10.034605+00:00 app[web.1]: npm ERR! file sh
2016-12-30T15:48:10.034877+00:00 app[web.1]: npm ERR! code ELIFECYCLE
2016-12-30T15:48:10.035062+00:00 app[web.1]: npm ERR! errno ENOENT
2016-12-30T15:48:10.035240+00:00 app[web.1]: npm ERR! syscall spawn
2016-12-30T15:48:10.035417+00:00 app[web.1]: npm ERR! microscope@ start: `meteor run`
2016-12-30T15:48:10.035590+00:00 app[web.1]: npm ERR! spawn ENOENT
2016-12-30T15:48:10.035809+00:00 app[web.1]: npm ERR!
2016-12-30T15:48:10.035964+00:00 app[web.1]: npm ERR! Failed at the microscope@ start script 'meteor run'.
2016-12-30T15:48:10.036091+00:00 app[web.1]: npm ERR! Make sure you have the latest version of node.js and npm installed.
2016-12-30T15:48:10.036215+00:00 app[web.1]: npm ERR! If you do, this is most likely a problem with the microscope package,
2016-12-30T15:48:10.036338+00:00 app[web.1]: npm ERR! not with npm itself.
2016-12-30T15:48:10.036495+00:00 app[web.1]: npm ERR! Tell the author that this fails on your system:
2016-12-30T15:48:10.036615+00:00 app[web.1]: npm ERR! meteor run
2016-12-30T15:48:10.036738+00:00 app[web.1]: npm ERR! You can get information on how to open an issue for this project with:
2016-12-30T15:48:10.036857+00:00 app[web.1]: npm ERR! npm bugs microscope
2016-12-30T15:48:10.036979+00:00 app[web.1]: npm ERR! Or if that isn't available, you can get their info via:
2016-12-30T15:48:10.037103+00:00 app[web.1]: npm ERR! npm owner ls microscope
2016-12-30T15:48:10.037225+00:00 app[web.1]: npm ERR! There is likely additional logging output above.
2016-12-30T15:48:10.040737+00:00 app[web.1]:
2016-12-30T15:48:10.040940+00:00 app[web.1]: npm ERR! Please include the following file with any support request:
2016-12-30T15:48:10.041058+00:00 app[web.1]: npm ERR! /app/npm-debug.log
2016-12-30T15:48:10.159157+00:00 heroku[web.1]: State changed from starting to crashed
2016-12-30T15:48:10.123673+00:00 heroku[web.1]: Process exited with status 1
2016-12-30T15:48:15.546228+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=hellohellohell.herokuapp.com request_id=6b38141e-14fc-4c21-aae5-c89c077e83b9 fwd="41.217.180.223" dyno= connect= service= status=503 bytes=
2016-12-30T15:48:16.814073+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=hellohellohell.herokuapp.com request_id=8403ae63-2852-4da6-88f0-f539a0f11520 fwd="41.217.180.223" dyno= connect= service= status=503 bytes=
2016-12-30T15:58:23.234351+00:00 heroku[web.1]: State changed from crashed to starting
2016-12-30T15:58:24.581443+00:00 heroku[web.1]: Starting process with command `npm start`
2016-12-30T15:58:25.714966+00:00 app[web.1]:
2016-12-30T15:58:25.714978+00:00 app[web.1]: > microscope@ start /app
2016-12-30T15:58:25.714979+00:00 app[web.1]: > meteor run
2016-12-30T15:58:25.714980+00:00 app[web.1]:
2016-12-30T15:58:25.721137+00:00 app[web.1]: sh: 1: meteor: not found
2016-12-30T15:58:25.725436+00:00 app[web.1]:
2016-12-30T15:58:25.732613+00:00 app[web.1]: npm ERR! Linux 3.13.0-105-generic
2016-12-30T15:58:25.732802+00:00 app[web.1]: npm ERR! argv "/app/.heroku/node/bin/node" "/app/.heroku/node/bin/npm" "start"
2016-12-30T15:58:25.732942+00:00 app[web.1]: npm ERR! node v6.9.1
2016-12-30T15:58:25.733067+00:00 app[web.1]: npm ERR! npm v3.10.8
2016-12-30T15:58:25.733189+00:00 app[web.1]: npm ERR! file sh
2016-12-30T15:58:25.733304+00:00 app[web.1]: npm ERR! code ELIFECYCLE
2016-12-30T15:58:25.733430+00:00 app[web.1]: npm ERR! errno ENOENT
2016-12-30T15:58:25.733533+00:00 app[web.1]: npm ERR! syscall spawn
2016-12-30T15:58:25.733637+00:00 app[web.1]: npm ERR! microscope@ start: `meteor run`
2016-12-30T15:58:25.733717+00:00 app[web.1]: npm ERR! spawn ENOENT
2016-12-30T15:58:25.733985+00:00 app[web.1]: npm ERR! Make sure you have the latest version of node.js and npm installed.
2016-12-30T15:58:25.733809+00:00 app[web.1]: npm ERR!
2016-12-30T15:58:25.733903+00:00 app[web.1]: npm ERR! Failed at the microscope@ start script 'meteor run'.
2016-12-30T15:58:25.734066+00:00 app[web.1]: npm ERR! If you do, this is most likely a problem with the microscope package,
2016-12-30T15:58:25.734247+00:00 app[web.1]: npm ERR! not with npm itself.
2016-12-30T15:58:25.734328+00:00 app[web.1]: npm ERR! Tell the author that this fails on your system:
2016-12-30T15:58:25.734412+00:00 app[web.1]: npm ERR! meteor run
2016-12-30T15:58:25.734491+00:00 app[web.1]: npm ERR! You can get information on how to open an issue for this project with:
2016-12-30T15:58:25.734572+00:00 app[web.1]: npm ERR! npm bugs microscope
2016-12-30T15:58:25.734650+00:00 app[web.1]: npm ERR! Or if that isn't available, you can get their info via:
2016-12-30T15:58:25.734723+00:00 app[web.1]: npm ERR! npm owner ls microscope
2016-12-30T15:58:25.737966+00:00 app[web.1]:
2016-12-30T15:58:25.734832+00:00 app[web.1]: npm ERR! There is likely additional logging output above.
2016-12-30T15:58:25.738116+00:00 app[web.1]: npm ERR! Please include the following file with any support request:
2016-12-30T15:58:25.738194+00:00 app[web.1]: npm ERR! /app/npm-debug.log
2016-12-30T15:58:25.824057+00:00 heroku[web.1]: State changed from starting to crashed
2016-12-30T15:58:25.784111+00:00 heroku[web.1]: Process exited with status 1
A: The error you're getting says that the meteor command is not found. This happens if your application doesn't have meteor listed as a dependency in your project's package.json file.
If you add meteor as a dependency to your project, then push this change up to Heroku, that will cause meteor to get installed, and it should now have access to the meteor command.
A: the problem was resolved when using this build https://github.com/AdmitHub/meteor-buildpack-horse.git and changing the package.json to
{
"name": "microscope",
"engines": {
"node": "6.9.2",
"npm": "3.10.9"
},
"scripts": {
"start": "meteor run"
},
"dependencies": {
"babel-runtime": "^6.20.0",
"meteor-node-stubs": "~0.2.0"
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41399497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: HoloEverywhere does not work with ActionbarSherlock any more I have download the latest version HoloEveryWhere from github
then i added the ActionbarSherlock library to it . Now i errors in themes-core.xml files
and thats what it looks like :
<style name="Holo.Base.Theme" parent="Theme.AppCompat">
....
<style name="Holo.Base.Theme.Light" parent="Theme.AppCompat.Light">
.....
obviously it seems that HoloEveryWhere is configured to work with ActionBarCompt library .
for me I'd rather use ActionbarSherlock instead .
should i change the parent values to equivalent sherlock theme's ?
what about the countless errors in attrs.xml :
Attribute "activatedBackgroundIndicator" has already been
defined
how could i solve them ?
I have been trying to integrate this library for 2 days now with no success !!
A: I had a similar problem when I added HoloEverywhere 2.0.0 SNAPSHOT and ActionBarCompat as dependencies to my project. I believe HoloEverywhere already has the ActionBarCompat dependency and when I removed ActionBarCompat, the problem duplicates errors went away.
Gradle is driving me crazy, I am very new to Android and have never used ActionBarSherlock, but from my trawling and searching the code, it seems ActionBarSherlock includes references to HoloEverywhere in pom.xml as a plugin. Maybe it has already included HoloEverywhere and you are including another version and this is why you are getting the already defined error?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18739175",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Insert blank line before line matching pattern in sed I am attempting to insert blank line above a line when we match a pattern. We have a grep statement that will find the line and store the line number in a variable.
In this example I want to insert a blank line above line 1 which is the happy line and then insert a line above line 3 which has the text sad.
This works fine with a sed command however I want to use variable substitution for the line number in the sed statement and that is where it fails. Let me move on and show the example that
I have created to show what issue I am having.
Here is our sed command that works when using it without the variable:
sed '1i\\' test # insert blank line at top of file:
Here is our file named: test which has 3 lines:
Line1=happy
Line2=mad
Line3=sad
We have two variables for our sed statement:
1: this has the line of happy - which is 1.
2. this has the line of sad - which is 3.
Here is the variables that we want the sed statment to use:
h=$(grep -n happy test | cut -d : -f 1)
s=$(grep -n sad test | cut -d : -f 1)
Show that the h and s variables seem to work:
user@host:~$ echo $h
1
user@host:~$ echo $s
3
Show that our sed statement works properly to output a blank line at the beginning of the file - which is line 1 & then also for line 3.
sed '1i\\' test # we test that it outputs a blank line on the top of the file first - without our variable:
user@host:~$ sed '1i\\' test
# here is our blank line.
happy
mad
sad
user@host:~$ sed '3i\\' test
happy
mad
# here is our blank line for line 3.
sad
Now we move onto testing it with our variables defined in the command substitution variables h and s so we can try to do the same thing as we did above.
This is where it does not work - I will not test with both variables since it does not work with the first variable. I have tried different syntax that I have researched heavily but cannot get sed to work with the variable.
sed "$si\\" test # try to insert the blank line with the variable at top of file
user@host:~$ sed '$hi\\' test # we test that it outputs a blank line on the top of the file first - with our variable with ticks ' ':
sed: -e expression #1, char 3: extra characters after command
user@host:~$ sed "$hi\\" test # we test that it outputs a blank line on the top of the file first - with our variable with quotes " " :
sed: -e expression #1, char 1: unterminated address regex
user@host:~$ sed "'$hi\\'" test # we test that it outputs a blank line on the top of the file first - with our variable with quotes/ticks "' '" :
sed: -e expression #1, char 1: unknown command: `''
I have tried several other forms of quotes/ticks ect to try to get it to work. I read around on stack-overflow significanly and found that I should use quotes around my command if using variables.
I have been given a comment to utilize the { } around my variable however when doing this it does not output a line above like it does with the real text:
user@host:~$ sed "${h}i\\" test # the command does not error now but does not output the line either - variable h.
happy
mad
sad
user@host:~$ sed "${s}i\\" test # the command does not error now but does not output the line either - variable s.
happy
mad
sad
user@host:~$ sed '1i\\' test
# blank line here
happy
mad
sad
A: Getting the line number with grep so you can pass it to sed is an antipattern. You want to do all the processing in sed.
sed -e '/happy/i\\' -e '/sad/i\\' file
If indeed the action is the same in both cases, you can conflate it to a single regular expression.
sed '/\(happy\|sad\)/i\\' file
(The precise syntax will vary between sed dialects but you get the idea. If your sed has -r or -E you can avoid the backslashes.)
A: Your first problem is that "$gi" is looking for the variable $gi, which doesn't exist. To avoid that, you have to either put curly braces around the variable name, as in "${g}i", or put a space between the variable name and the sed command, as in "$g i".
Then, because your tests that work use single quotes, the double backslash is interpreted literally. In double quotes, backslashes have to be escaped, resulting in
sed "${h}i\\\\" test
And finally, it seems this is overly complicated. To insert a blank line before a line containing a pattern, you can use this (for the example happy):
sed '/happy/s/^/\n/' test
This "replaces" the beginning of the line with a newline if the line matches happy.
Notice that inserting a newline like this doesn't work with every sed; for macOS sed, you could probably use something like
sed 'happy/s/^/'$'\n''/' test
A: This should work perfectly. I tested it on Ubuntu with no issues.
number=3
sed $number'i\\' test.txt
Regards!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45620124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Error running Spacy entity linking example I was trying the entity linking example in spacy.
This is the information about spaCy in my system.
============================== Info about spaCy ==============================
spaCy version 2.2.2
Location C:\Users\manimaran.p\AppData\Local\Continuum\anaconda3\envs\spacy\lib\site-packages\spacy
Platform Windows-8.1-6.3.9600-SP0
Python version 3.7.3
Models
Using this example to train the entity linker and generating the knowledge base for the same with this example.
I can create a knowledge base with the available en_core_web_md, this is the output for the same.
# python "create kb.py" -m en_core_web_md -o pret_kb
Loaded model 'en_core_web_md'
2 kb entities: ['Q2146908', 'Q7381115']
1 kb aliases: ['Russ Cochran']
Saved KB to pret_kb\kb
Saved vocab to pret_kb\vocab
Loading vocab from pret_kb\vocab
Loading KB from pret_kb\kb
2 kb entities: ['Q2146908', 'Q7381115']
1 kb aliases: ['Russ Cochran']
When I try to train the entity linker with the knowledge base from above, I get this error.
# python "entity linker.py" ./pret_kb/kb ./pret_kb/vocab
Created blank 'en' model with vocab from 'pret_kb\vocab'
Loaded Knowledge Base from 'pret_kb\kb'
Traceback (most recent call last):
File "entity linker.py", line 156, in <module>
plac.call(main)
File "C:\Users\manimaran.p\AppData\Local\Continuum\anaconda3\envs\spacy\lib\site-packages\plac_core.py", line 328, in call
cmd, result = parser.consume(arglist)
File "C:\Users\manimaran.p\AppData\Local\Continuum\anaconda3\envs\spacy\lib\site-packages\plac_core.py", line 207, in consume
return cmd, self.func(*(args + varargs + extraopts), **kwargs)
File "entity linker.py", line 113, in main
sgd=optimizer,
File "C:\Users\manimaran.p\AppData\Local\Continuum\anaconda3\envs\spacy\lib\site-packages\spacy\language.py", line 515, in update
proc.update(docs, golds, sgd=get_grads, losses=losses, **kwargs)
File "pipes.pyx", line 1219, in spacy.pipeline.pipes.EntityLinker.update
KeyError: (0, 12)
I did follow the instructions specified here. I used the en_core_web_md to create the knowledge base since I do not have a pre-trained model.
I did not write any custom code just trying to run this example, Can someone point me to the right direction.
A: This was asked and answered in the following issue on spaCy's GitHub.
It looks like the script no longer worked after a refactor of the entity linking pipeline as it now expects either a statistical or rule-based NER component in the pipeline.
The new script adds such an EntityRuler to the pipeline as an example. I.e.,
# Add a custom component to recognize "Russ Cochran" as an entity for the example training data.
# Note that in a realistic application, an actual NER algorithm should be used instead.
ruler = EntityRuler(nlp)
patterns = [{"label": "PERSON", "pattern": [{"LOWER": "russ"}, {"LOWER": "cochran"}]}]
ruler.add_patterns(patterns)
nlp.add_pipe(ruler)
However, this can be replaced with your own statistical NER model.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59050554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Object methods in android extended array adapter I am having the following object in my activity class:
/**
* Item object
*/
class OrderItem {
/**
* Private params
*/
private String item_name;
private Double item_price;
private Integer quantity;
public void OrderItem(String name, Double price, Integer qt){
/**
* Init the object properties
*/
this.item_name = name;
this.item_price = price;
this.quantity = qt;
}
/**
* Getters and setters
*/
public String getName(){
return this.item_name;
}
public void setName(String name){
this.item_name = name;
}
public Double getPrice(){
return this.item_price;
}
public void setPrice(Double price){
this.item_price = price;
}
public Integer getQuantity(){
return this.quantity;
}
public void setQuantity(Integer qt){
this.quantity = qt;
}
}
and I am using this object to update a ListView item. So I've set up a custom adapter for the list, to handle the current object, and add the data to the given view. Here is the code of my adapter:
class OrderObjectAdapter<OrderItem> extends ArrayAdapter<OrderItem>{
private final Context context;
private final List<OrderItem> object;
public OrderObjectAdapter(Context context,List<OrderItem> object){
super(context, R.layout.order_object_layout, object);
this.context = context;
this.object = object;
}
@Override
public View getView(int position, View conertView, ViewGroup parent){
LayoutInflater inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.order_object_layout, parent, false);
/** Gather items from the view */
TextView p_name = (TextView) rowView.findViewById(R.id.product_name);
TextView p_value = (TextView) rowView.findViewById(R.id.product_value);
TextView p_quantity = (TextView) rowView.findViewById(R.id.product_quantity);
/** Asign data to the text views */
OrderItem item = (OrderItem) object.get(position);
p_name.setText("");
return rowView;
}
}
and this is how I use it:
/**
* Init the order_items adapter
*/
order_details_list_view = (ListView)findViewById(R.id.order_details_list_view);
order_items = new ArrayList<OrderItem>();
order_items_adapter = new OrderObjectAdapter(
this,order_items
);
/** Set the list adapter to the order items */
order_details_list_view.setAdapter(order_items_adapter);
My problem is that in the method getView of my custom adapter, if I want to assign the object data to my view, the object property from that adapter, is always returning me out an object pointer(i think) instead of the object on wich I can call my getter methods to get the data.
Here is a sample of what it is returned if I put a Log.e on it:
E/item﹕ com.avicolaarmeli.armeli.OrderItem@41561f98
Even if I typecast that into OrderItem or create a new var like: OrderItem item = object.get(position); I still cannot access the object's methods.
I've been trying to sort this out all the day and couldn't understand why. Can somebody please let me know what's wrong with my code?
Thanks
A: What you are seeing is the this.toString(), that is the default implementation of Object.toString(), since you are not overriding it.
add
@Override
public String toString() {
return this.item_name != null ? this.item_name : "name not set";
}
to your OrderItem add see what difference it makes
@Override
public View getView(int position, View conertView, ViewGroup parent){
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.order_object_layout, parent, false);
}
/** Gather items from the view */
TextView p_name = (TextView) convertView.findViewById(R.id.product_name);
TextView p_value = (TextView) convertView.findViewById(R.id.product_value);
TextView p_quantity = (TextView) convertView.findViewById(R.id.product_quantity);
/** Asign data to the text views */
OrderItem item = (OrderItem) object.get(position);
p_name.setText(item.getName());
return convertView;
}
Also it should be
class OrderObjectAdapter extends ArrayAdapter<OrderItem>{
not
class OrderObjectAdapter<OrderItem> extends ArrayAdapter<OrderItem>{
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22539015",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Kafka Stream topology optimization While readying about topology optomization, i stumble upon the following:
Currently, there are two optimizations that Kafka Streams performs
when enabled:
1 - The source KTable re-uses the source topic as the changelog topic.
2 - When possible, Kafka Streams collapses multiple repartition topics
into a single repartition topic.
This question is for the first point. I do not fully understand what is happening under the hood here. Just to make sure that i am not making any assumption here. Can someone explain, what was the state before:
1 - Do the KTable, use an internal changelog topic ? if yes, can someone point me to a doc about that ? Next, what is in that changelog topic ? Is it the actually upsert log, comsposed of update operation ?
2 - If my last guess is true, i do not understand how that changelog composed of upsert can be replace by the source topic only ?
A: A changelog topic is a Kafka topic configured with log compaction. Each update to the KTable is written into the changelog topic. Because the topic is compacted, no data is ever lost and re-reading the changelog topic allows to re-create the local store.
The assumption of this optimization is, that the source topic is a compacted topic. For this case, the source topic and the corresponding changelog topic would contain the exact same data. Thus, the optimization removes the changelog topic and uses the source topic to re-create the state store during recovery.
If your input topic is not compacted but applies a retention time, you might not want to enable the optimization as this could result in data loss.
About the history: Initially, Kafka Streams had this optimization hardcoded (and thus "forced" users to only read compacted topics as KTables if potential data loss is not acceptable). However, in version 1.0 a regression bug was introduced (via https://issues.apache.org/jira/browse/KAFKA-3856: the new StreamsBuilder behavior was different to old KStreamBuilder and StreamsBuilder would always create a changelog topic) "removing" the optimization. In version 2.0, the issue was fixed and the optimization is available again. (cf https://issues.apache.org/jira/browse/KAFKA-6874)
Note: the optimization is only available for source KTables. For KTables that are the result of an computation, like an aggregation or other, the optimization is not available and a changelog topic will be created (if not explicitly disabled what disables fault-tolerance for the corresponding store).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57164133",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: DES_ENCRYPT with CodeIgniter ActiveRecord When I query my database with a query like this:
SELECT username, DES_DECRYPT(password) as password FROM accounts WHERE 1;
I will get my results like:
username | password
-------------------
testUser | pwtest
When I do the same in CodeIgniters Active Record like this:
$this->db->select("username, DES_DECRYPT(password) as password");
return $this->db->get("accounts")->result_array();
I will get the following array:
[0] => Array
(
[username] => testUser
[password] =>
)
Any ideas why this isn't working or how to get this work?
Some additional info: the function will also be completely with an insert:
$this->db->insert("accounts", array("username" => "test", "password" => "DES_ENCRYPT(wachtwoord)"));
This will insert (in plain text) "DES_ENCRYPT(wachtwoord)"
PS. To prevent the standard "It's better to use a hash than save the password" discussion: I agree, but in this case is hashing not an option.
A: codeigniter is not 100% complete and chances are its not using all of mysql functions. instead of writing it like this:
$this->db->select("username, DES_DECRYPT(password) as password");
write it like this:
$this->db->select("username, " . decrypt(password) . " as password");
where decrypt is the php equivalent of DES_DECRYPT. The php equivalent is Mcrypt more info found here:
https://answers.yahoo.com/question/index?qid=20071201215913AAG8QKF
also avoid encrypting your password in such a way where it can be decrypted. its bad practice no one but the user should know their password.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22748806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to cut character string with whitespace.. php ( sorry my bad english )
I try to cut a large character string with whitespace like this:
hola como estas 0001 hola 02hola como estas
well, I need to cut between 10 space and save that in a txt file.
some like this:
enter link description here
I try :
<?php
$pago = $_POST["texto"];
//$salto_de_linea = chr(13).chr(10);
//$pago_a_txt = wordwrap($pago, 11, $salto_de_linea, false);
//$pago_a_txt=preg_split('//', $pago, 0, PREG_SPLIT_NO_EMPTY);
$pago_a_txt=substr($pago, -610);
$txt = fopen("file.txt", "w");
fwrite($txt, $pago_a_txt);
fclose($txt);
?>
A: substr() is the key to your answer here.
You will want to loop through the input string 10 characters at a time to create each line.
<?php
$input = 'hola como estas 0001 hola 02hola como estas';
$output = '';
$stringLength = strlen($input) / 10; // 10 is for number of characters per line
$linesProcessed = 0;
while ($linesProcessed < $stringLength) {
$output .= substr($input, ($linesProcessed * 10), 10) . PHP_EOL;
$linesProcessed++;
}
echo $output;
The output is:
hola como
estas 0001
hola 02ho
la como es
tas
(Note: Use nl2br() or use the CSS style whitespace: pre if you're displaying this in HTML).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32770885",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to convert an string to a Char(20) sql datatype I am trying to insert a string into a char(20) column in my SQL Server database.
I set the string to be equal to a value and then add it to a parameter
thisstring = "1914"
cmd.Parameters.AddWithValue("@code", thisstring)
However every time I try it ends up looking like this in the database
I need it to look like the 1913, 000000, 000001 ones.
When I try to pad the string with spaces
thisstring= thisstring.PadLeft(20, " ")
or
thisstring = " " & thisstring
I am getting
String or binary data would be truncated
even if the field wasn't 20 characters total
What am I doing wrong?
Edit*** here is the column in SQL Server
http://imgur.com/BbV6VQv
A: I am not absolutely sure, but I think the problem lies in the AddWithValue.
While convenient this method doesn't allow to specify the exact datatype to pass to the database engine and neither the size of the parameter. It pass always an nvarchar parameter for a C# UNICODE string.
I think you should try with the standard syntax used to build a parameter
Dim p = new SqlParameter("@code", SqlDbType.Char, 20)
p.Value = thisstring.PadLeft(20, " ")
See this very interesting article on MSDN
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17242581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to set nls variables in adonisjs I'm trying to use adonisjs as a backend. For oracle database i need to set nls variables when connection is established.
ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY.MM.DD'
How and where is it better to do it?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74207942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: plotting real time Data on (qwt )Oscillocope I'm trying to create a program, using Qt (c++), which can record audio from my microphone using QAudioinput and QIODevice.
Now, I want to visualize my signal
Any help would be appreciated. Thanks
[Edit1] - copied from your comment (by Spektre)
*
*I Have only one Buffer for both channel
*I use Qt , the value of channel are interlaced on buffer
*this is how I separate values
for ( int i = 0, j = 0; i < countSamples ; ++j)
{
YVectorRight[j]=Samples[i++];
YVectorLeft[j] =Samples[i++];
}
*after I plot YvectorRight and YvectorLeft. I don't see how to trigger only one channel
A: hehe done this few years back for students during class. I hope you know how oscilloscopes works so here are just the basics:
*
*timebase
*
*fsmpl is input signal sampling frequency [Hz]
Try to use as big as possible (44100,48000, ???) so the max frequency detected is then fsmpl/2 this gives you the top of your timebase axis. The low limit is given by your buffer length
*draw
Create function that will render your sampling buffer from specified start address (inside buffer) with:
*
*Y-scale ... amplitude setting
*Y-offset ... Vertical beam position
*X-offset ... Time shift or horizontal position
This can be done by modification of start address or by just X-offsetting the curve
*Level
Create function which will emulate Level functionality. So search buffer from start address and stop if amplitude cross Level. You can have more modes but these are basics you should implement:
*
*amplitude: ( < lvl ) -> ( > lvl )
*amplitude: ( > lvl ) -> ( < lvl )
There are many other possibilities for level like glitch,relative edge,...
*Preview
You can put all this together for example like this: you have start address variable so sample data to some buffer continuously and on timer call level with start address (and update it). Then call draw with new start address and add timebase period to start address (of course in term of your samples)
*multichannel
I use Line IN so I have stereo input (A,B = left,right) therefore I can add some other stuff like:
*
*Level source (A,B,none)
*render mode (timebase,Chebyshev (Lissajous curve if closed))
*Chebyshev = x axis is A, y axis is B this creates famous Chebyshev images which are good for dependent sinusoidal signals. Usually forming circles,ellipses,distorted loops ...
*miscel stuff
You can add filters for channels emulating capacitance or grounding of input and much more
*GUI
You need many settings I prefer analog knobs instead of buttons/scrollbars/sliders just like on real Oscilloscope
*
*(semi)Analog values: Amplitude,TimeBase,Level,X-offset,Y-offset
*discrete values: level mode(/,),level source(A,B,-),each channel (direct on,ground,off,capacity on)
Here are some screenshots of my oscilloscope:
Here is screenshot of my generator:
And finally after adding some FFT also Spectrum Analyser
PS.
*
*I started with DirectSound but it sucks a lot because of buggy/non-functional buffer callbacks
*I use WinAPI WaveIn/Out for all sound in my Apps now. After few quirks with it, is the best for my needs and has the best latency (Directsound is too slow more than 10 times) but for oscilloscope it has no merit (I need low latency mostly for emulators)
Btw. I have these three apps as linkable C++ subwindow classes (Borland)
*
*and last used with my ATMega168 emulator for my sensor-less BLDC driver debugging
*here you can try my Oscilloscope,generator and Spectrum analyser If you are confused with download read the comments below this post btw password is: "oscill"
Hope it helps if you need help with anything just comment me
[Edit1] trigger
You trigger all channels at once but the trigger condition is checked usually just from one Now the implementation is simple for example let the trigger condition be the A(left) channel rise above level so:
*
*first make continuous playback with no trigger you wrote it is like this:
for ( int i = 0, j = 0; i < countSamples ; ++j)
{
YVectorRight[j]=Samples[i++];
YVectorLeft[j] =Samples[i++];
}
// here draw or FFT,draw buffers YVectorRight,YVectorLeft
*Add trigger
To add trigger condition you just find sample that meets it and start drawing from it so you change it to something like this
// static or global variables
static int i0=0; // actual start for drawing
static bool _copy_data=true; // flag that new samples need to be copied
static int level=35; // trigger level value datatype should be the same as your samples...
int i,j;
for (;;)
{
// copy new samples to buffer if needed
if (_copy_data)
for (_copy_data=false,i=0,j=0;i<countSamples;++j)
{
YVectorRight[j]=Samples[i++];
YVectorLeft[j] =Samples[i++];
}
// now search for new start
for (i=i0+1;i<countSamples>>1;i++)
if (YVectorLeft[i-1]<level) // lower then level before i
if (YVectorLeft[i]>=level) // higher then level after i
{
i0=i;
break;
}
if (i0>=(countSamples>>1)-view_samples) { i0=0; _copy_data=true; continue; }
break;
}
// here draw or FFT,draw buffers YVectorRight,YVectorLeft from i0 position
*
*the view_samples is the viewed/processed size of data (for one or more screens) it should be few times less then the (countSamples>>1)
*this code can loose one screen on the border area to avoid that you need to implement cyclic buffers (rings) but for starters is even this OK
*just encode all trigger conditions through some if's or switch statement
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21656397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Handling erroneous user input such as float and number length I'm trying to handle a user's erroneous input such as floats and integers of length inferior to say 4 and superior to 4 so that whenever it happens, I ask the user to re-enter the 4 digits number.
The expected outcome.
>>> beginning = input('Enter date: ')
>>> Enter date: 1985.0
>>> Please give a four digit integer for date.
>>> Enter date: 19.8
>>> Please give a four digit integer for date.
>>> Enter date: blabla
>>> Please give a four digit integer for date.
>>> Enter date: 200
>>> Please give a four digit integer for date.
>>> Enter date: 20000
>>> Please give a four digit integer for date.
>>> Enter date: 1980
>>> # This is good
Here's my attempt.
def reading_ans():
while True:
try:
ans = input('Enter date: ')
if float(ans) != float(int(float((ans)))):
print("Please give a four digit integer for date.")
elif len(ans) != 4:
print("Please give a four digit integer for date.")
else:
return ans
A: I would suggest that your condition use the fact that ans.isdigit() is only True if ans consists solely of digits.
def reading_ans():
while True:
ans = input('Enter date: ')
if len(ans) == 4 and ans.isdigit():
return ans
print("Please give a four digit integer for date.")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40701113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Spring Session & Spring Security - session timeout handling not working When attempting to add spring-session to an existing Spring MVC project with spring-security, I get the following behavior (EDIT: with tomcat's session-timeout set to 1 minute for testing):
*
*With the springSessionRepositoryFilter filter in web.xml commented-out, I am correctly booted to the login screen after a minute of inactivity
*With the springSessionRepositoryFilter filter in web.xml active, I can continue to use the app at least 5 minutes after the last activity
Besides that, everything seems to work as expected - the session is persisted in redis & across webapp restarts, and logging out manually correctly invalidates the session.
Some snippets of my configuration - here is the invalid session handler configuration for spring-security, that will cause expired sessions to be redirected to a login page:
...
<beans:bean id="sessionManagementFilter" class="org.springframework.security.web.session.SessionManagementFilter">
<beans:constructor-arg name="securityContextRepository">
<beans:bean class="org.springframework.security.web.context.HttpSessionSecurityContextRepository"/>
</beans:constructor-arg>
<beans:property name="invalidSessionStrategy">
<beans:bean class="my.CustomInvalidSessionStrategy"/>
</beans:property>
</beans:bean>
...
<http>
...
<custom-filter position="SESSION_MANAGEMENT_FILTER" ref="sessionManagementFilter"/>
...
<logout delete-cookies="true" invalidate-session="true" logout-url="/signout.html" success-handler-ref="logoutSuccessHandler"/>
</http>
The web.xml 's filter chain looks like:
<filter>
<filter-name>springSessionRepositoryFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSessionRepositoryFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
And (one of) the spring context files loaded contains:
<bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"/>
<bean class="org.springframework.security.web.session.HttpSessionEventPublisher"/>
<bean class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"/>
Hopefully I'm just missing something really obvious!
Edit: The versions I used for the attempt was spring-security-4.0.4.RELEASE and spring-session-1.1.1.RELEASE
A: When using Redis session timeout is configured like this:
<bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
<property name="maxInactiveIntervalInSeconds" value="10"></property>
</bean>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37030912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Detecting if is zoom-in or zoom-out with leaflet How can I know when the user is zooming in or zooming out? I want to start an animation if the user zooms after some level. Is it possible to know this when the event zoomstart is triggered?
A:
How can I know when the user is zooming in or zooming out?
At every zoom level, calculate how much map.getZoom() has changed.
Is it possible to know this when the event zoomstart is triggered?
No.
Consider the following scenario: A user, using a touchscreen (phone/tablet).
The user puts two fingers down on the screen. Half a frame after, one of the fingers moves a couple of pixels towards the center, triggering a pinch-zoom with a tiny change in the zoom level.
Your code catches the zoomstart and zoom events that happen inmediately after. "I know!" - your code says - "The user is zooming out!".
And then the user starts moving their fingers wider and wider, zooming in. And your code gets confused.
But the user changes their mind, and then starts zooming out for whatever reason. And then in again. And then out again. And then they lift the fingers and the zoom snaps to a zoom level.
This is why you can not know what the final zoom level is going to be when you listen to a zoomstart or zoom event in Leaflet.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39893070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to convert UTC timestamp string to pandas datetime? I have a panda dataframe with a column with date format as below:
PublishDateTime= 2018-08-31 12:00:00-UTC
I used panda to_gbq() function to dump data into a bigquery table. Before dumping data, I make sure that the format of columns match with table scheme. publishedate is timestamp in bigquery table. How can achieve something similar to:
df['PublishDateTime'] = df['PublishDateTime'].astype('?????')
I tried datetime[ns] but that didn't work!
A: The main challenge in the conversion here is the format of your datetime. Pass format="%Y-%m-%d %H:%M:%S-%Z" as an argument to pd.to_datetime and convert your column to datetime.
df['PublishDateTime'] = pd.to_datetime(df['PublishDateTime'],
format='%Y-%m-%d %H:%M:%S-%Z',
errors='coerce')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52730806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: R Studio 'source' button fails with escape error I have a fresh install of R Studio. Editing a file and clicking the 'source' button produces the error below.
How do I fix the default behavior of R Studio to properly escape the path?
The output in the R console is:
source('~/pull tfs data.r')
Error: '\L' is an unrecognized escape in character string starting ""Z:\L"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26812877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Checking a sentence if it is a pangram by using a Jframe I would like to create a case where the user needs the enter a sentence.
The code should validate if the sentence is :
*
*a pangram
*not a complete pangram
*not a pangram
In the text area: the system should display which option the sentence is.
In the attachment a screenshot of how the JFrame looks like.
Can someone help me with how I can implement this?
A: Introduction
I went ahead and created the following GUI.
The GUI consists of a JFrame with one main JPanel. The JPanel uses a GridBagLayout and consists of a JLabel, JTextArea, JLabel, JTextArea.
The GUI processes the sentence as it's typed by using a DocumentListener. The code in the DocumentListener is simple since I do the work of processing the sentence in a separate class.
Here's the GUI after I've typed a few characters.
A few more characters
The final result
Explanation
When I create a Swing GUI, I use the model / view / controller (MVC) pattern. This pattern allows me to separate my concerns and focus on one part of the application at a time.
I created one model class, one view class, and one controller class. The PangramModel model class produces a result String for any input sentence String. The PangramGUI view class creates the GUI. The SentenceDocumentListener controller class updates the result JTextArea.
The most complicated code can be found in the model class. There are probably many ways to process a sentence String. This was the way I coded.
Code
Here's the complete runnable code. I made the classes inner classes so I could post this code as one block.
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class PangramGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new PangramGUI());
}
private JTextArea sentenceArea;
private JTextArea resultArea;
@Override
public void run() {
JFrame frame = new JFrame("Pangram Analysis");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.weightx = 1.0;
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 0;
JLabel label = new JLabel("Type the sentence to analyze");
panel.add(label, gbc);
gbc.gridy++;
sentenceArea = new JTextArea(3, 40);
sentenceArea.setLineWrap(true);
sentenceArea.setWrapStyleWord(true);
sentenceArea.getDocument().addDocumentListener(
new SentenceDocumentListener());
panel.add(sentenceArea, gbc);
gbc.gridy++;
label = new JLabel("Pangram result");
panel.add(label, gbc);
gbc.gridy++;
resultArea = new JTextArea(4, 40);
resultArea.setEditable(false);
resultArea.setLineWrap(true);
resultArea.setWrapStyleWord(true);
panel.add(resultArea, gbc);
return panel;
}
public class SentenceDocumentListener implements DocumentListener {
private PangramModel model;
public SentenceDocumentListener() {
this.model = new PangramModel();
}
@Override
public void insertUpdate(DocumentEvent event) {
processSentence(sentenceArea.getText());
}
@Override
public void removeUpdate(DocumentEvent event) {
processSentence(sentenceArea.getText());
}
@Override
public void changedUpdate(DocumentEvent event) {
processSentence(sentenceArea.getText());
}
private void processSentence(String text) {
String result = model.processSentence(text);
resultArea.setText(result);
}
}
public class PangramModel {
private String alphabet;
public PangramModel() {
this.alphabet = "abcdefghijklmnopqrstuvwxyz";
}
public String processSentence(String sentence) {
int[] count = new int[alphabet.length()];
for (int index = 0; index < sentence.length(); index++) {
char c = Character.toLowerCase(sentence.charAt(index));
int charIndex = alphabet.indexOf(c);
if (charIndex >= 0) {
count[charIndex]++;
}
}
if (isEmpty(count)) {
return "Not a pangram";
} else {
List<Character> missingCharacters = getUnusedCharacters(count);
if (missingCharacters.size() <= 0) {
return "A pangram";
} else {
StringBuilder builder = new StringBuilder();
builder.append("Not a complete pangram");
builder.append(System.lineSeparator());
builder.append(System.lineSeparator());
builder.append("Missing characters: ");
for (int index = 0; index < missingCharacters.size(); index++) {
builder.append(missingCharacters.get(index));
if (index < (missingCharacters.size() - 1)) {
builder.append(", ");
}
}
return builder.toString();
}
}
}
private boolean isEmpty(int[] count) {
for (int index = 0; index < count.length; index++) {
if (count[index] > 0) {
return false;
}
}
return true;
}
private List<Character> getUnusedCharacters(int[] count) {
List<Character> output = new ArrayList<>();
for (int index = 0; index < count.length; index++) {
if (count[index] <= 0) {
output.add(alphabet.charAt(index));
}
}
return output;
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67820428",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Paypal DirectPayment returning error while using PayPal sandbox DirectPayment method I am getting the following error message:
Direct credit card payment API call failed: Please enter a valid postal code in the billing address.Short Error Message: Invalid DataError Code: 10712
I have changed my Zipcode and address but no use. Does anyone know why this is happening?
A: This error is often caused by the zip code not matching the city and state format. I would suggest using usps.com zip code verfication to make sure the zip matches the postal service city and state. You can find this tool here:
https://tools.usps.com/go/ZipLookupAction!input.action
Using this tool usually helps me clear the error. If this doenst help resolve the issue, please show the address and zip details that you are currently sending. Hope this helps.
Thanks,
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14973544",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Search for value contained in array of objects in property of object contained in array can someone help me with this?
I need a function that given a fieldID, searchs within objects and returns the objectID that fieldID is in.
const objects = [
{
objectID: 11,
fields: [
{ id: 12, name: 'Source ID' },
{ id: 12, name: 'Source ID' },
],
},
{objectID: 14,
fields: [
{ id: 15, name: 'Creator' },
],},
{objectID: 16,
fields: [
{ id: 17, name: 'Type' },
{ id: 18, name: 'Name' },
{ id: 19, name: 'Description' },
],},
];
SOLVED:
Got it working like this:
const getObjectID = fieldId => {
for (const object of objects) {
if (object.fields.find(field => field.id === fieldId)) {
return object.objectID;
}
}
};
A: This will work:
const getObjectId = (fieldID) => {
const object = objects.find(object => object.fields.find(field => field.id === fieldID )!== undefined)
if(object) return object.objectID;
return null
}
A: Using the find array method:
const objects = [
{ objectId: 1, fields: ["aaa"] },
{ objectId: 2, fields: ["bbb"] },
{ objectId: 3, fields: ["ccc"] },
];
const getObjectId = (id) => objects.find(object.objectId === id);
console.log(getObjectId(2));
// { objectId: 2, fields: ["bbb"] }
Read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71068262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make onClick perform multiple similar functions at once? I'm trying to make the Button onClick fill both #box elements, with the same input from the forms. And potentially add more boxes in the future. But it just seems to only be calling the first 2 functions.
Here's the codepen example!
Tried changing the syntax of the onclick call a few different ways. Didn't help
function myFunction() {
var str = document.getElementById("myname").innerHTML;
var res = str.replace("_____",
document.querySelector('input[name="name"]').value);
document.getElementById("myname").innerHTML = res;
}
function myFunction2() {
var str = document.getElementById("theirname").innerHTML;
var res = str.replace("_____",
document.querySelector('input[name="theirname"]').value);
document.getElementById("theirname").innerHTML = res;
}
function lovely2() {
var str = document.getElementById("myname1").innerHTML;
var res = str.replace("_____",
document.querySelector('input[name="name"]').value);
document.getElementById("myname1").innerHTML = res;
}
function lovely5() {
var str = document.getElementById("theirname1").innerHTML;
var res = str.replace("_____",
document.querySelector('input[name="theirname1"]').value);
document.getElementById("theirname1").innerHTML = res;
}
<div id="form1">
<form>
<p>
<br><input type="text" class="name1" name="name" placeholder="VXA Name">
<br>
</p>
<p><br><input type="text" class="name2" placeholder="CX Name" name="theirname"></p>
</form>
<div class="forms">
<button onclick="myFunction(); myFunction2(); lovely2(); lovely5()">Fill Names</button>
<button class="2" onclick="#">Reset</button>
</div>
</div>
<div id="box1">
<a>Thank you, </a> <a id="theirname">_____</a>, for contacting Us. My name is<a id="myname"> _____, and I'd be more than happy to assist you today.
<a class="copy">Copy text</a>
</a>
</div>
<div id="box2">
<a>Thank you, </a> <a id="theirname1">_____</a>, for contacting Us. My name is<a id="myname1"> _____, and I'd be more than happy to assist you today.
<a class="copy">Copy text</a>
</a>
</div>
A: Instead of trying to call multiple functions on you click event, you can simply refactor it by doing this. onClick() serves as the function that handles the click event.
<button onclick="onClick()">Fill Names</button>
And on your JavaScript,
function onClick() {
myFunction();
myFunction2();
lovely2();
lovely5();
}
onClick() will be fired when the user clicks on that button, and this will ensure that all the 4 functions will be called.
A: You can call all the functions within another function and fire that when the button is clicked. I don't think it is possible to call all functions within the html event at once.
<button onclick="clicked()">Click me</button>
function clicked() {
myFunction();
myFunction2();
lovely2();
lovely5();
}
This code will still not work thought because in your current javascript, lovely2() and lovely() are nested within myFunction2() so you cannot call them and calling myFunction2() will not call them either. You will need to move them outside, like this
function myFunction() {
var str = document.getElementById("myname").innerHTML;
var res = str.replace("_____",
document.querySelector('input[name="name"]').value);
document.getElementById("myname").innerHTML = res;
}
function myFunction2() {
var str = document.getElementById("theirname").innerHTML;
var res = str.replace("_____",
document.querySelector('input[name="theirname"]').value);
document.getElementById("theirname").innerHTML = res;
}
function lovely2() {
var str = document.getElementById("myname1").innerHTML;
var res = str.replace("_____",
document.querySelector('input[name="name"]').value);
document.getElementById("myname1").innerHTML = res;
}
function lovely5() {
var str = document.getElementById("theirname1").innerHTML;
var res = str.replace("_____",
document.querySelector('input[name="theirname1"]').value);
document.getElementById("theirname1").innerHTML = res;
}
A: There is a few typo in your code - incorrect position of } and input[name="theirname1"].
function myFunction() {
var str = document.getElementById("myname").innerHTML;
var res = str.replace("_____",
document.querySelector('input[name="name"]').value);
document.getElementById("myname").innerHTML = res;
}
function myFunction2() {
var str = document.getElementById("theirname").innerHTML;
var res = str.replace("_____",
document.querySelector('input[name="theirname"]').value);
document.getElementById("theirname").innerHTML = res;
}
function lovely2() {
var str = document.getElementById("myname1").innerHTML;
var res = str.replace("_____",
document.querySelector('input[name="name"]').value);
document.getElementById("myname1").innerHTML = res;
}
function lovely5() {
var str = document.getElementById("theirname").innerHTML;
var res = str.replace("_____",
document.querySelector('input[name="theirname"]').value);
document.getElementById("theirname1").innerHTML = res;
}
<div id="form1">
<form>
<p><br><input type="text" class="name1" name="name" placeholder="VXA Name">
<br>
</p>
<p><br><input type="text" class="name2" placeholder="CX Name" name="theirname">
</form>
<div class="forms">
<button onclick="myFunction(); myFunction2(); lovely2(); lovely5()">Fill Names</button>
<button class="2" onclick="#">Reset</button>
</div>
</div>
<div id="box1">
<a>Thank you, </a> <a id="theirname">_____</a>, for contacting Us. My name is<a id="myname"> _____, and I'd be more than happy to assist you today.
<a class="copy">Copy text</a>
</a>
</div>
<div id="box2">
<a>Thank you, </a> <a id="theirname1">_____</a>, for contacting Us. My name is<a id="myname1"> _____, and I'd be more than happy to assist you today.
<a class="copy">Copy text</a>
</a>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56420610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ClassNotFoundException on class inside gae endpoint client library I am developing in Java on Eclipse Luna. The packaging process is managed by Proguard.
The app is working fine running against the local datastore repository and on a physical device.
However, I rolled the app out to the Google Play as beta. The app crashes with ClassNotFoundException. The exception is calling against a class that is generated by the GAE's endpoint client library process.
Here are what I have tried so far, but no luck...
*
*Rearrange the build path to put all client library on the top of the list, uncheck the Dependencies and clean the project.
*I also tried using the -keepclass option with the full package and class name in the proguard-project.txt.
*I added the following entries to my proguard-project.txt...still no luck
-keep public class * extends com.google.api.client.json.GenericJson
# Needed by google-api-client to keep generic types and @Key annotations accessed via reflection**
-keepclassmembers class * {
@com.google.api.client.util.Key ;
}
-keepattributes Signature,RuntimeVisibleAnnotations,AnnotationDefault
Anyone has any clue what I am missing? Thanks!
A: This is what I ended up adding to my proguard-project.txt file:
# Needed by google-api-client to keep generic types and @Key annotations accessed via reflection
-keep public final class *
-keep public class *
-keepclassmembers class * {
public <fields>;
static <fields>;
public <methods>;
protected <methods>;
}
-keepclassmembers class * extends com.google.api.client.json.GenericJson{
public <fields>;
static <fields>;
public <methods>;
}
-keepattributes Signature,RuntimeVisibleAnnotations,AnnotationDefault
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32555686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to retrieve PAYLOAD for a Google Cloud Task via API Is it possible to retrieve the PAYLOAD (see image below of what I can view in GCP's Cloud Tasks UI) for a GCP Cloud Task via Google's API? If so, how? Here's the Task documentation I've been looking through (I can't see anything that would get me the PAYLOAD): https://cloud.google.com/java/docs/reference/google-cloud-tasks/latest/com.google.cloud.tasks.v2.Task
I also ran gcloud tasks describe [TASK] --response-view=full and couldn't see the PAYLOAD anywhere in the response.
This seems like obvious functionality, so I'm hoping I'm missing something (different API, perhaps). Thanks!
A: I suspect (!?) this is excluded from Task on retrieval perhaps for security reasons but, it appears not possible to get the request body from tasks in the queue.
Note: On way to investigate this is to use e.g. Chrome's Developer Tools to understand how Console achieves this.
You can validate this using gcloud and APIs Explorer:
gcloud tasks list \
--queue=${QUEUE} \
--location=${LOCATION} \
--project=${PROJECT} \
--format=yaml \
--log-http
Note: You don't need the --format to use --log-http but I was using both.
Or: projects.locations.queues.tasks.list and filling in the blanks (you don't need to include API key).
Even though all should be Task in my case (using HttpRequest, the response does not include body.
IIRC, when I used Cloud Tasks a while ago, I was similarly perplexed at being unable to access response bodies.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73112098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MySQL GROUP BY…exclude values in other field i have a problem with a MySQL query for my statistic-page. I want to use a query similar to the following to retrieve all rows to "version" but i want to exclude values in other field "platform" if is not the same value.
Example values:
| platform | version | ...
----------------------
| Windows | 1.0.1 |
| Windows | 1.0.1 |
| Windows | 1.0.1 |
| Windows | 1.0.2 |
| Windows | 1.0.3 |
| Linux | 1.0.1 |
| Linux | 1.0.1 |
| Linux | 1.0.2 |
| Mac | 1.0.1 |
| Mac | 1.0.1 |
Query:
SELECT
platform,
version,
COUNT(*) AS count
FROM
user
GROUP BY
version
Result:
| platform | version | count |
------------------------------
| Windows | 1.0.1 | 7 |
| Windows | 1.0.2 | 2 |
| Windows | 1.0.3 | 1 |
I need the following result:
| platform | version | count |
------------------------------
| Windows | 1.0.1 | 3 |
| Windows | 1.0.2 | 1 |
| Windows | 1.0.3 | 1 |
| Linux | 1.0.1 | 2 |
| Linux | 1.0.2 | 1 |
| Mac | 1.0.1 | 2 |
I hope you can help me... and sorry for my english.
A: I think you just need the right group by clause:
SELECT platform, version, COUNT(*) AS count
FROM user
GROUP BY platform, version;
Your query is not actually syntactically correct SQL. The column platform is in the SELECT but it is not in the GROUP BY. Almost any database other than MySQL would correctly return an error.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45787089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What is the is the difference between -copyFromLocal and -put Is it possible to explain difference between -copyFromLocal and -put command in Hadoop. I am not able to find any good document which says the difference between two commands.
A: Well one can explain if there is a difference and i don't think there is.
Look at the code below all that CopyFromLocal does is extends Put with no additional functionality.
public static class CopyFromLocal extends Put {
public static final String NAME = "copyFromLocal";
public static final String USAGE = Put.USAGE;
public static final String DESCRIPTION = "Identical to the -put command.";
}
https://github.com/apache/hadoop/blob/trunk/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/shell/CopyCommands.java
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40569034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Framework for handling HTTP responses in C# The project is a C# desktop application that interacts with a webpage.
The last time I did anything like this, I used WatiN and HTMLAgilityPack. But WatiN isn't very elegant as it opens a browser window to interact with the website. It's more designed for Integration Testing, still it got the job done.
This time I'm looking at AngleSharp to parse the HTML, but I still need to write code that logs into the website, presses a couple of buttons and does some POSTS.
Are there any frameworks I can use to make this straightforward?
A: If you want to interact with a web site, filling text boxes, clicking buttons etc, I think a more logical solution would be using and managing an actual web browser.
Selenium.WebDriver NuGet Package
C# Tutorial 1
C# Tutorial 2
A: Well - it looks like I underestimated the power of AngleSharp
There's a wonderful post here which describes how to use it to log into a website, and post forms.
The library has been updated since so a few things have changed, but the capability and approach is the same.
I'll include my "test" code here which demonstrates usability.
public async Task LogIn()
{
//Sets up the context to preserve state from one request to the next
var configuration = Configuration.Default.WithDefaultLoader().WithDefaultCookies();
var context = BrowsingContext.New(configuration);
/Loads the login page
await context.OpenAsync("https://my.website.com/login/");
//Identifies the only form on the page (can use CSS selectors to choose one if multiple), fills in the fields and submits
await context.Active.QuerySelector<IHtmlFormElement>("form").SubmitAsync(new
{
username = "CharlieChaplin",
pass = "x78gjdngmf"
});
//stores the response page body in the result variable.
var result = context.Active.Body;
EDIT - after working with this for a while, I've discovered that Anglesharp.IO has a more robust HttpRequester in it. The above code then becomes
public async Task LogIn()
{
var client = new HttpClient();
var requester = new HttpClientRequester(client);
//Sets up the context to preserve state from one request to the next
var configuration = Configuration.Default
.WithRequester(requester)
.WithDefaultLoader()
.WithDefaultCookies();
var context = BrowsingContext.New(configuration);
/Loads the login page
await context.OpenAsync("https://my.website.com/login/");
//Identifies the only form on the page (can use CSS selectors to choose one if multiple), fills in the fields and submits
await context.Active.QuerySelector<IHtmlFormElement>("form").SubmitAsync(new
{
username = "CharlieChaplin",
pass = "x78gjdngmf"
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62659008",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: google-auto-placed div breaking react hydration React hydration seems to be hooking up divs incorrectly because of a div with class google-auto-placed on some pages. It seems to be the auto ad div coming from adsense. How can we avoid this situation?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72774850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How should I require modules effectively from outside of node_modules folder? I have a bunch of modules in my application, what I require relatively from the current script. The problem with this if I want to restructure my application then I have to change tons of require statements.
So I started to use something like this:
//loader.js in root
"use strict";
exports.Logger = require('./core/logger');
exports.Module = require('./core/module');
And in my files I use require it like this:
"use strict";
var Loader = require('../../loader');
var Logger = Loader.Logger;
var logger = new Logger();
So now if I want to restructure the shared codes in my application then I have to change the require only in the loader.js file. Is this a good solution? What do you use?
Is there any way to make require fully automatic when the required module name is unique?
A: Why are your modules not stored in directories? For example:
/
app.js
lib
--/logger
----/index.js
then in app.js you can just require(./lib/logger)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32739305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How specify element name in list? Here is a model and data list definitions:
<!-- DataLists-->
<type name="sc:contractType">
<title>Options</title>
<parent>dl:dataListItem</parent>
<properties>
<property name="sc:type">
<title>Type</title>
<type>d:text</type>
</property>
</properties>
</type>
<!-- workflow model-->
<type name="sc:startProcesstask">
<parent>bpm:startTask</parent>
<properties>
<property name="sc:helloName">
<type>d:text</type>
<mandatory>true</mandatory>
<multiple>false</multiple>
</property>
</properties>
<associations>
<child-association name="sc:requestCategory"">
<target>
<class>sc:contractType</class>
<mandatory>true</mandatory>
<many>false</many>
</target>
</child-association>
</associations>
</type>
When I edit model and try select data list item value I have to:
*
*browse entire repository for finding data list item.
*see UUID value instead of type property in item list.
Is there a way to tell alfresco to show type property insted of UUID during browsing for list items?
A: The problem is that the default form control for selecting the target of that child association is not sufficient for your needs. So, you need to provide an alternative custom form control. The docs show how to do this using a very simplified example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40103524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get table data from another website through wordpress I was just wondering if it is possible to get the data from a table from another website through wordpress? And what would be the catch if I do that? And if it possible, How can I achieve it?
A: Yes, it's highly possible and I did it like this:
*
*Create page template in Wordpress
*Connect to remote database and check from backend first
*Write UI code + server code + Mysql queries to grab the data in template
*Create UI in page which will grab data from DB/server
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39065115",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to parse podupti.me´s json via Gson? How can I parse this json via Gson?
Here is my PodModel.class
And this is my for retrieve the json.
This is the gson part.
gson = new Gson();
PodsModel pods = gson.fromJson(builder.toString(), PodsModel.class);
System.out.println(pods.getPods().getDomain());
Logcat returns with this: logcat-output
A: It seems, that Gson failed here:
"pods":[{"id":
^
This [ is unexpected because in your model PodModel pods field is plain field, not an array.
May be you have to change pods to by an array, and in this case you will be able to parse such json.
UPD: Just change pods definition to this one:
private List<ItemPod> pods;
*
*change according way getter and setter.
This solution should work (tested).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14315793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to sync files matching glob pattern like `foo*/bar*/yaz*.gz` I'm trying to sync a set of files which are found by the linux fileglob foo*/bar*/yaz*.gz.
The standard rsync trick of --include='yaz*.gz' --include='*/' --exclude='*' --prune-empty-dirs does work, but it is quite slow since there are many other uninteresting directories and files that it finds.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57841321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to create a singleton object in Scala with runtime params I'm trying to create a singleton object with parameters which are specified by runtime.
Example:
object NetworkPusher {
val networkAdress = ???
...
}
Imagine the networkAdress param comes from the command-line. How can I make a workaround to do this?
A: Singletons are initialized lazily.
scala> :pa
// Entering paste mode (ctrl-D to finish)
object Net {
val address = Config.address
}
object Config { var address = 0L }
// Exiting paste mode, now interpreting.
defined object Net
defined object Config
scala> Config.address = "1234".toLong
Config.address: Long = 1234
scala> Net.address
res0: Long = 1234
FWIW.
A: Using lazy:
object Program {
var networkAdress: String = _
def main(args: Array[String]): Unit = {
networkAdress = args(0)
println(NetworkPusher.networkAdress)
}
object NetworkPusher {
lazy val networkAdress = Program.networkAdress
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27801150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Trouble Installing Nginx and php5-fpm on Debian 7.3 I have a Debian 7.3 installation in a VM that I am practising installing Nginx and php5-fpm on. I got the Nginx working, by assigning it a manual port of :8080 and that points to /var/www/ for data and in that directory is an index.html and info.php file.
The config file for my Nginx is located at /etc/nginx/conf.d/default.conf and looks like this:
server {
listen 8080;
root /var/www;
index index.php index.html index.htm;
server_name localhost;
location / {
try_files $uri $uri/ /index.html;
}
location /doc/ {
alias /usr/share/doc/;
autoindex on;
allow 127.0.0.1;
allow ::1;
deny all;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/www;
}
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass 127.0.0.1:9000;
#fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
location ~ /\.ht {
deny all;
}
}
I have tried changing fastcgi_pass both ways:
fastcgi_pass 127.0.0.1:9000;
and also as:
fastcgi_pass unix:/var/run/php5-fpm.sock;
In my /etc/php5/fpm/pool.d/www.conf file I have the following configuration:
[www]
user = www-data
group = www-data
listen = 127.0.0.1:9000
;listen = /var/run/php5-fpm.sock
Here too, I have uncommented the line to match in the Nginx default.conf file.
In my php.ini file I have edited it so that it shows cgi.fix_pathinfo = 0 as required by most of the guides I have seen.
When I try to load nginx, it runs OK. When I try to run php5-fpm this is what happens:
root@debianx86:/# /etc/init.d/php5-fpm status
[FAIL] php5-fpm is not running ... failed!
root@debianx86:/# /etc/init.d/php5-fpm reload
[ ok ] Reloading PHP5 FastCGI Process Manager: php5-fpm.
root@debianx86:/# /etc/init.d/php5-fpm restart
[FAIL] Restarting PHP5 FastCGI Process Manager: php5-fpm failed!
root@debianx86:/# /etc/init.d/php5-fpm start
root@debianx86:/# /etc/init.d/php5-fpm status
[FAIL] php5-fpm is not running ... failed!
root@debianx86:/#
I then open up any of the browsers on my VM and point them to either 127.0.0.1:8080 or localhost:8080 and I get the custom index.html loading that I made and it works! So I then try to load theinfo.php file and I get presented with a 404 Not Found - nginx/1.4.4.
I don't understand what I'm doing wrong. Is there something I'm missing from all this?
I installed nginx from sudo apt-get -y install nginx and sudo apt-get -y install php5-fpm too. Any dependencies they required would have been installed along with that.
Is there a script that I can run on a fresh install of Debian 7.3 that someone has got that will install it properly for me, and make all the modifications so that nginx and php5-fpm are up and running? I've looked over many of the websites with the instructions and I seem to be doing pretty much everything they do, except for the default-sites and enabled-sites, as neither of those folders exist for me, and I don't want to run my virtual hosts like that. I will run them with their own servers listed in the default.conf file.
EDIT: I have even tried following this article at DigitalOcean and it still doesn't work.
EDIT #2: I also did chown -R www-data:www-data /var/www to ensure that the user and group match the information in the www.conf file. I also tried by changing it back to the original root:root specs too. Still nothing.
A: I think maybe port 9000 is already being used, so php5-fpm can't bind with that port and fails to start.
in the fpm pool settings swap the line of port 9000 with the line with the sock file, then try to start php5-fpm like you were doing, if it works then all you need is to update the nginx configuratuin to proxy pass to the sock file instead of the port.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21323530",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: some Errors after migration to AndroidX some errors after migration to AndroidX
I downloaded LeafPic-master project( it is a gallery source code for Android studio)and try to change minsdkversion and targetSdkVersion( I want to install my app on android 4.4 to newest android api).So I add the google() repo in the repositories to solve some problems then migrate to AndroidX.
the list of my errors is:
ERROR: Failed to resolve: androidx.recyclerview:recyclerview:1.0.0
Show in Project Structure dialog
Affected Modules: app
ERROR: Failed to resolve: com.google.android.material:material:1.0.0
Show in Project Structure dialog
Affected Modules: app
ERROR: Failed to resolve: androidx.palette:palette:1.0.0
Show in Project Structure dialog
Affected Modules: app
ERROR: Failed to resolve: androidx.legacy:legacy-support-v4:1.0.0
Show in Project Structure dialog
Affected Modules: app
ERROR: Failed to resolve: androidx.browser:browser:1.0.0
Show in Project Structure dialog
Affected Modules: app
ERROR: Failed to resolve: androidx.exifinterface:exifinterface:1.0.0
Show in Project Structure dialog
Affected Modules: app
ERROR: Failed to resolve: com.google.android.gms:play-services-iid:[17.0.0]
Show in Project Structure dialog
Affected Modules: app
ERROR: Failed to resolve: androidx.vectordrawable:vectordrawable-animated:1.0.0
Show in Project Structure dialog
Affected Modules: app
ERROR: Failed to resolve: fragment
Affected Modules: app
and my Build.gradle is:
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.0'
}
}
apply plugin: 'com.android.application'
repositories {
google()
jcenter()
maven { url "http://repo1.maven.org/maven2" }
maven { url "http://dl.bintray.com/dasar/maven" }
maven { url 'https://maven.google.com' }
}
android {
compileSdkVersion 29
buildToolsVersion '27.0.3'
defaultConfig {
minSdkVersion 15
targetSdkVersion 29
versionCode 1
versionName "1.0.0"
vectorDrawables.useSupportLibrary = true
}
lintOptions {
disable 'MissingTranslation'
disable 'ExtraTranslation'
}
// This is handled for you by the 2.0+ Gradle Plugin
aaptOptions {
additionalParameters "--no-version-vectors"
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_6
targetCompatibility JavaVersion.VERSION_1_6
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'androidx.vectordrawable:vectordrawable:1.0.1'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.recyclerview:recyclerview:1.0.0'
implementation 'com.google.android.material:material:1.0.0'
implementation 'androidx.palette:palette:1.0.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.browser:browser:1.0.0'
implementation "androidx.exifinterface:exifinterface:1.0.0"
implementation "androidx.appcompat:appcompat:1.0.0"
implementation 'com.github.bumptech.glide:glide:4.9.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
implementation 'com.koushikdutta.ion:ion:2.1.7'
implementation 'com.mikepenz:iconics-core:3.0.3@aar'
implementation 'com.mikepenz:google-material-typeface:3.0.1.2.original@aar'
implementation 'com.mikepenz:community-material-typeface:2.0.46.1@aar'
implementation 'com.mikepenz:fontawesome-typeface:4.7.0.2@aar'
implementation "com.mikepenz:iconics-views:3.0.3@aar"
implementation 'com.github.paolorotolo:appintro:3.4.0'
implementation 'com.yalantis:ucrop:1.5.0'
implementation 'uz.shift:colorpicker:0.5@aar'
implementation 'com.balysv:material-ripple:1.0.2'
implementation 'com.commit451:PhotoView:1.2.5'
implementation 'com.google.android.exoplayer:exoplayer:r1.5.7'
implementation 'de.psdev.licensesdialog:licensesdialog:1.8.3'
implementation 'com.davemorrissey.labs:subsampling-scale-image-view:3.10.0'
implementation 'de.hdodenhof:circleimageview:2.2.0'
implementation 'com.drewnoakes:metadata-extractor:2.11.0'
implementation 'org.jetbrains:annotations-java5:15.0'
implementation 'co.ronash.android:pushe-base:1.3.3'
api 'com.google.android.gms:play-services-gcm:17.0.0'
}
other Errors is:
cannot resolve symbole 'material'
cannot resolve symbole 'appcompat'
cannot resolve symbole 'cardview'
cannot resolve symbole 'recyclerview'
in this lines:
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.appcompat.widget.SwitchCompat;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
A: try to change
sourceCompatibility JavaVersion.VERSION_1_6
targetCompatibility JavaVersion.VERSION_1_6
to
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
A: This can be a gradle issue.
Consider deleting gradle cache and retrying.
Gradle cache is at C:\Users\yourUserName\.gradle\caches (windows) or ~/.gradle/caches (linux)
Note: If your area is under sanction, you must bypass this using proxy or VPN.
A: At first, there is no need to inject the recyclerView's, CardView's and material libraries into the gradle file because in the android studio i.e. 3.4 and above all these libraries are already inserted by default. Just replace your this library -> implementation 'com.android.support:appcompat-v7:28.0.0' with implementation 'androidx.appcompat:appcompat:1.1.0' and plus, go into the gradle.properties file and add this line -> "android.useAndroidX=true" and your project will work fine. In my case it worked.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58075940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: No suitable driver found for jdbc:sqlserver… (intellij, gradle) I want to connect to SQL Server by java, Intellij, i add repository in .gradle file like this:
// https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc
testCompile group: 'com.microsoft.sqlserver', name: 'mssql-jdbc', version: '6.2.2.jre7'
// https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc
testCompile group: 'com.microsoft.sqlserver', name: 'mssql-jdbc', version: '6.2.2.jre8'
Libraries was downloaded successfully, so i could see jar files in project external libraries path:
After that, i try to connect by follow code:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://IpAddress:1433;databaseName=DbName";
String username = "user";
String password = "pass";
Connection conn = DriverManager.getConnection(url,username,password);
And i got this error:
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
I'm surprised because this code works in Eclipse with the same jar file, but not in intellij!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48850389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Two WP Issues: Redirect Loop and Can't Login Recently uploaded my site from localhost to the live server, and it's not quite working. When I visit the home page, the browser says Im stuck in a redirect loop. I've tried the default fixes like resetting .htaccess file, disabling all plugins, switching to default theme, and clearing cookies, and none of these worked.
Second issue (maybe related?) is when I try to login via wp-admin and hit Login, it basically just refreshes the page and nothing happens. Definitely using the right credentials.
I was using the Understrap theme if that matters, with some of my own plugins.
A: Did you import the same database of your local Installation on the live Server? Maybe some worng paths in options table could be wrong causing your problems, if you migrated your local database to the live server. Maybe you also need to check wp-config.php and set your base url here or sth.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49373376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Trying to iterate through a DataGridView by Selected row; Receiving Index out of Bounds I originally created a foreach DGVrow to iterate through the DGV, but this would take long since it iterates through the entire data grid which contains thousands of rows. I switched up the for each into the following:
if (DGVmain.RowCount > 0)
{
if (DGVmain.SelectedCells.Count <= 0)
{
return;
}
//Source
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Excel Files|*.xls;*.xlsx";
openFileDialog.ShowDialog();
lblSuccess.Text = openFileDialog.FileName;
lblPathings = Path.ChangeExtension(openFileDialog.FileName, null);
int count = DGVmain.SelectedRows.Count;
foreach (DataGridViewRow selectedRow in DGVmain.SelectedRows)
{
//Drag
if (lblSuccess.Text == null)
return;
//Drag
if (lblSuccess.Text == null)
return;
string dragsy = Convert.ToString(selectedRow.Cells[1].Value);
string drag = Convert.ToString(selectedRow.Cells[2].Value);
string drag2 = Convert.ToString(selectedRow.Cells[3].Value);
string drag3 = Convert.ToString(selectedRow.Cells[4].Value);
string drag4 = Convert.ToString(selectedRow.Cells[5].Value);
string drag5 = Convert.ToString(selectedRow.Cells[6].Value);
string drag6 = Convert.ToString(selectedRow.Cells[7].Value);
string drag7 = Convert.ToString(selectedRow.Cells[8].Value);
string drag8 = Convert.ToString(selectedRow.Cells[9].Value);
string drag9 = Convert.ToString(selectedRow.Cells[10].Value);
string drag10 = Convert.ToString(selectedRow.Cells[11].Value);
Persona = drag;
generateID();
}
}
}
I cut out the part with where the function manipulates the data to insert it into an Excel file. It's not throwing an error, so I assume everything is sound with the syntax arrangement? What's wrong with this loop?
I only receive an index is out of bounds of the array.
A: In C#,all arrays are 0 based. So the problem must be that you are trying to access from selectedRow.Cells[1] to selectedRow.Cells[11], when you should use selectedRow.Cells[0]to selectedRow.Cells[10]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42020031",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android- HttpUrlConnection addRequestProperty not working After doing more research I am now able to clarify my question. I have a code segment that I know works with every other file I try it on except one text file. The code checks the file I send it using the URL and HTTPURLConnection. I use addRequestProperty("Range", "bytes=0-0") to get just enough of the file on the server so I can check the LastModified field without having to download the file again. Here is the code for the checking of the file:
private void getFileDetails() throws IOException, ParseException {
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.addRequestProperty("Range", "bytes=0-0");
con.connect();
String cr = con.getHeaderField("Content-Range");
URL url2 = new URL("url for json file");
URL url3 = new URL("url for txt file");
Map<String, List<String>> map = con.getHeaderFields();
if(url.equals(url2) || url.equals(url3)) {//This is just for seeing if it added Range
Log.i("HTTP", url.toString());
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
Log.i("HTTP", "Key : " + entry.getKey() +
" ,Value : " + entry.getValue());
}
Log.i("HTTP", "----------------------------------------------------------\n");
}
if (cr == null)//Fails Right here
throw new IOException();
length = Long.parseLong(cr.substring(cr.indexOf('/')+1, cr.length()));
String date = con.getHeaderField("Last-Modified");
String pattern = "EEE, dd MMM yyyy HH:mm:ss Z";
SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.ENGLISH);
Date javaDate = format.parse(date);
lastModified = javaDate.getTime();
}
Here is the output of my test on the fields for the file that worked:
I/HTTP: Key : null ,Value : [HTTP/1.1 206 Partial Content]
I/HTTP: Key : Accept-Ranges ,Value : [bytes]
I/HTTP: Key : Connection ,Value : [Keep-Alive]
I/HTTP: Key : Content-Length ,Value : [1]
I/HTTP: Key : Content-Range ,Value : [bytes 0-0/15431]
I/HTTP: Key : Content-Type ,Value : [application/json]
I/HTTP: Key : Date ,Value : [Thu, 11 Jan 2018 17:54:00 GMT]
I/HTTP: Key : ETag ,Value : ["3c47-560c8525e5d0b"]
I/HTTP: Key : Keep-Alive ,Value : [timeout=5, max=100]
I/HTTP: Key : Last-Modified ,Value : [Wed, 20 Dec 2017 16:46:15 GMT]
I/HTTP: Key : Server ,Value : [Apache/2.4.18 (Ubuntu)]
I/HTTP: Key : X-Android-Received-Millis ,Value : [1515693240969]
I/HTTP: Key : X-Android-Response-Source ,Value : [NETWORK 206]
I/HTTP: Key : X-Android-Selected-Protocol ,Value : [http/1.1]
I/HTTP: Key : X-Android-Sent-Millis ,Value : [1515693240804]
Now here is the result of the text file that doesn't work:
I/HTTP: Key : null ,Value : [HTTP/1.1 200 OK]
I/HTTP: Key : Accept-Ranges ,Value : [bytes]
I/HTTP: Key : Connection ,Value : [Keep-Alive]
I/HTTP: Key : Content-Type ,Value : [text/plain]
I/HTTP: Key : Date ,Value : [Thu, 11 Jan 2018 17:55:44 GMT]
I/HTTP: Key : ETag ,Value : ["1370000-560b66148adf5-gzip"]
I/HTTP: Key : Keep-Alive ,Value : [timeout=5, max=100]
I/HTTP: Key : Last-Modified ,Value : [Tue, 19 Dec 2017 19:21:56 GMT]
I/HTTP: Key : Server ,Value : [Apache/2.4.18 (Ubuntu)]
I/HTTP: Key : Transfer-Encoding ,Value : [chunked]
I/HTTP: Key : Vary ,Value : [Accept-Encoding]
I/HTTP: Key : X-Android-Received-Millis ,Value : [1515693344544]
I/HTTP: Key : X-Android-Response-Source ,Value : [NETWORK 200]
I/HTTP: Key : X-Android-Selected-Protocol ,Value : [http/1.1]
I/HTTP: Key : X-Android-Sent-Millis ,Value : [1515693344397]
You can see that the Content-Range field is missing from the text files headers and the status message is OK instead of Partial Content. I know that because I'm getting the true for cr == null means that it doesn't exist in the header files for the text file. I don't understand what is going wrong with the add. Everywhere I've looked where people have had similar problems the whole thing doesn't work. Any help would be appreciated.
Edit: Ok so the real problem is that the text file has no Length field. It checks the LastModified and the size of the file to see if it needs an update.
Edit: I know what's wrong now. The text file is chunked encoded and has no Content-Length
A: After much work and research, I discovered that the file I was trying to check the Content-Length tag on was chunked encoded which takes that tag away. The Apache server the files are hosted on automatically chunks .txt files that are too large. A workaround to this problem was to simply change the file extension from .txt to a .bin file. Doing that gave me the Content-Length header allowing me to check the size of the file without having to actually download the file. Apparently, the automated chunked encoding is something that is standard in HTTP 1.1. I'm not sure if that's the best way to get around this issue, but it worked in my case. Hope this helps someone else.
A: You're doing this the wrong way. You should be using a HEAD request. That way nothng is sent in reply except the headers, so no chunk encoding, and no Range header is necessary either,
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48213503",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Excel: If I open two windows on the same workbook, why do macros stop working in the first window? I am trying to set up a button in Excel to show a dual view of two separate worksheets at the same time. This is the code I've written so far (see below). So far the code seems to work. The problem is that the top window has some activex controls on the worksheet, and they seem to stop working until the bottom window is closed again. Why is this happening, and what can I do to fix it? Thanks.
Private Sub DualViewButton_Click()
Dim windowToPutOnTimeline As Window
If Windows.Count = 1 Then
ThisWorkbook.NewWindow
Windows.Arrange xlArrangeStyleHorizontal, True, False, False
Set windowToPutOnTimeline = Windows(1)
If Windows(1).Top < Windows(2).Top Then
Set windowToPutOnTimeline = Windows(2)
End If
With windowToPutOnTimeline
.Activate
HorizontalTimelineSheet.Activate
.DisplayGridlines = False
.DisplayRuler = False
.DisplayHeadings = False
.DisplayWorkbookTabs = False
'.EnableResize = False
End With
Windows(2).Activate 'go back to the right focus the user expects.
Else
If Windows(1).Top = Windows(2).Top Then
Windows.Arrange xlArrangeStyleHorizontal, True, False, False
Else
Windows.Arrange xlArrangeStyleVertical, True, False, False
End If
End If
End Sub
EDIT: if I switch the window that's being assigned to windowToPutOnTimeline then the problem goes away. So I've essentially worked around the problem without knowing why it works the other way. (see code snippet below)
With ThisWorkbook
Set windowToPutOnTimeline = .Windows(1)
Set windowToPutOnDataSheet = .Windows(2)
tmp = .Windows(1).Top
.Windows(1).Top = .Windows(2).Top
.Windows(2).Top = tmp
End With
A: This behavior is a bug in ActiveX control.
As a work around, use a button from the Forms Controls, rather than an ActiveX button
Using the Forms button you will need to add a Module, declare a Sub with your code and assign the Sub as the action macro to your button (as apposed to putting your code in the click event of an ActiveX button)
I tried this on Excel 2007, seem to work OK - the button appears and works on both windows
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4877869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Subsets and Splits