id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_5400
|
I've verified that the path to svn.exe is correct (detected) and i'm using my explicit login creds.
I've also been flipping through the manual but am not finding the appropriate information easily. (although i'm fairly certain i'm just looking for it wrong)
Anyone else have this problem? what else should i be looking for?
As a note, this machine had a copy of VisualSVN installed which has since expired.
Thanks
A: after some more troubleshooting and it appears that no one else has this problem, increasing my permissions on the teamcity server seemed to correct my problem.
| |
doc_5401
|
Then each time an item on the page is clicked the certain variable from the field in the database is caught within a JavaScript variable so a new window pops up with the SQL field 'channel_name' as the url.
I believe I am almost there but the JavaScript variable is only holding the variable from the last SQL 'channel_name'.
I hope I am making sense...
Here is my code which goes trough the database and prints out each element:
$chResult = mysql_query($chSQL);
if ($chResult) {
$chNum = mysql_num_rows($chResult);
if ($chNum>0) {
while($row = mysql_fetch_array($chResult)) {
if ($row['is_live']=="1") {
$whatIsLive = "true";
} else {
$whatIsLive = "false";
}
//CREATE THE ARRAY
$chName = array();
//ADD ARRAY VARS FROM CHANNEL_TITLE FIELD
$chName[] = ($row['channel_title']);
//PRINT CHANNEL INFORMATION TO PAGE
echo
'<li id="'.$row['channel_id'].'" class="list-group-item col-xs-12 col-sm-6 col-md-4 col-lg-3">
<div class="item">
<div class="item-head">
<div class="badges">';
if ($row['is_live']=="1") {
echo '<span class="badge-live">Live</span>';
}
echo '
</div>
</div>
<div class="item-image">
<a href="'.SERVERPATH.'channels/'.urlencode($row['channel_title']).'"
//TARGET FOR JAVASCRIPT POPUP WINDOW
target="PromoteFirefoxWindowName"
onclick="openFFPromotionPopup();
return false;"
data-islive="'.$whatIsLive.'"
title="'.$row['channel_title'].'">';
$activeSSImage = 'userData/'.$row['user_id'].'/channelImages/ss_'.$row['channel_id'].'_t.jpg';
$defaultSSImage = 'images/ss_default.jpg';
if (file_exists($activeSSImage)) {
echo '<img src="'.$activeSSImage.'?rand='.rand(0, 99999999).'" alt="'.$row['channel_title'].'" width="250" height="200">';
} else {
echo '<img src="'.$defaultSSImage.'" alt="'.$row['channel_title'].'" width="250" height="200">';
}
echo '
<span class="image-cover"></span>
<span class="play-icon"></span>
</a>
</div>
</div>
</div>
</li>';
}
} else {
echo '';
}
} else {
echo '';
}
The variable is then caught in JavaScript to allow the the link with channels/channel_name to popup in a new window:
<script type="text/javascript">
var theChannel = <?php echo(json_encode($chName)); ?>;
var windowObjectReference = null; // global variable
function openFFPromotionPopup() {
if(windowObjectReference == null || windowObjectReference.closed)
/* if the pointer to the window object in memory does not exist
or if such pointer exists but the window was closed */
{
windowObjectReference = window.open("channels/"+theChannel,
"PromoteFirefoxWindowName", "resizable,scrollbars,status");
/* then create it. The new window will be created and
will be brought on top of any other window. */
}
else
{
windowObjectReference.focus();
/* else the window reference must exist and the window
is not closed; therefore, we can bring it back on top of any other
window with the focus() method. There would be no need to re-create
the window or to reload the referenced resource. */
};
console.log( "function complete" );
console.log( theChannel );
}
</script>
Say I get two channels printed to the page but when I click on either of them the variable is only holding the name of the channel which was outputted last. Therefore only opening the last outputting channel window.
The effect I am trying to achieve is like what happens on http://onperiscope.com/ to give you a better idea.
I realize I may not have given enough information so please ask and I will try to give as much info as possible.
Thank you
A: I'm not going to pretend to have fully investigated what you are trying to do but from what you're describing is your problem simply that you are calling
//CREATE THE ARRAY
$chName = array();
for every row. When perhaps you mean.
if($chNum>0){
//CREATE THE ARRAY
$chName = array();
while($row = mysql_fetch_array($chResult)) {
//some code
//ADD ARRAY VARS FROM CHANNEL_TITLE FIELD
$chName[] = ($row['channel_title']);
I'd also suggest looking to use mysqli functions instead of the deprecated mysql functions
EDIT1
In response to your comment, perhaps since you already appear to including the URL for the channel_title in your href value, the easiest thing to do would be ditch the array and just pass the clicked object to your function and then access this property from within the openFFPromotionPopup function. So change your PHP to;
<a href="'.SERVERPATH.'channels/'.urlencode($row['channel_title']).'"
//TARGET FOR JAVASCRIPT POPUP WINDOW
target="PromoteFirefoxWindowName"
onclick="openFFPromotionPopup(this);return false;"
data-islive="'.$whatIsLive.'"
title="'.$row['channel_title'].'">';
And you javascript to;
function openFFPromotionPopup(elem) {
if(windowObjectReference == null || windowObjectReference.closed)
/* if the pointer to the window object in memory does not exist
or if such pointer exists but the window was closed */
{
windowObjectReference = window.open(elem.href,
"PromoteFirefoxWindowName", "resizable,scrollbars,status");
/* then create it. The new window will be created and
will be brought on top of any other window. */
}
| |
doc_5402
|
A: import pandas as pd
pd.read_csv(file_name,sep='rows separator')
see http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html for details.
A: I assume the rows are delimited by new-lines and that columns are delimited by commas. In which case just python already knows how to read it line by line which in your case means row by row. Then each row can be split where there are commas.
item_sets=[] #Will put the data in here
with open(filename, "r") as file: # open the file
for data_row in file: #get data one row at a time
# split up the row into columns, stripping whitespace from each one
# and store it in item_sets
item_sets.append( [x.strip() for x in data_row.split(",")] )
A: import csv
with open('eggs.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in spamreader:
print row
will printout all rows of a csv file as lists
I assume pandas impelmentation of read_csv is more efficient, but the csv module is built into python so if you don't want any dependencies, you can use it.
| |
doc_5403
|
Not sure if the input tag for the slider is messing something up?
<div class="slider" id="slider-1" tabIndex="1">
<input class="slider-input" id="slider-input-1"
name="slider-input-1"/>
</div>
A: If I were you, I'd try tweaking the <input> tag's type attribute, setting it to text or hidden.
(I don't know enough about the framework/environment you're using to say for sure.)
A: OK got it:
<form action="/cgi-bin/Lib.exe" method=POST name="slider" ID="Form2">
<input type="hidden" name="user" value="" ID="Text1">
</form>
<input type="button" value="Delete" class="btn" onclick="setval()" onmouseover="hov(this, 'btn btnhov')" onmouseout="hov(this, 'btn')" ID="Button1" NAME="Button1"/>
function setval()
{
//alert(s.getValue());
document.slider.user.value = s.getValue();//set value of hidden text box to value of slider
document.slider.submit();
}
| |
doc_5404
|
<img src onerror="fetch('https://i.pximg.net/img-original/img/2020/11/28/06/04/23/85949640_p0.png', {headers: {Referer: 'https://www.pixiv.net/en/'}}).then(r=>r.blob()).then(d=> this.src=window.URL.createObjectURL(d));" />
This however, still fails to load the image. Checking the code of some extensions that promise to fix this error by installing scripts shows that they're just changing the referral, and that this should get things working.
A:
Sometimes websites won't let you load images without proper a referrer.
Yes. Plenty of websites do not want to pay to store images and transfer them over the network so that freeloaders can display them on their websites without shouldering the cost.
In a similar question I have found this answer, that suggests doing something like this
That fails for two reasons.
*
*It is a forbidden header. Browsers are designed to prevent your JavaScript from lying about where requests are being triggered from.
*Most sites hosting images don't grant permission, via CORS, to third-parties to read them with JS. They are even more unlikely to if they do referer checking to stop freeloading!
If a website doesn't want you displaying images they host, you need to respect that.
Pay for your own image hosting instead.
Don't copy the images from the third-party to your own site unless you are sure they aren't protected by copyright (or you have permission).
| |
doc_5405
|
ex. : "word" and "letter" have common "r"
"word" and "email" haven't any common chars
This code is wrong because if two words have 2 common chars I get 4 in the result
int numberOfCommonChars = (from c1 in word1.ToCharArray()
from c2 in word2.ToCharArray()
where c1 == c2
select c1).Count();
A: Your code isn't working becasue using multiple from clauses creates a full outer join
You need to use Intersect:
int commonCount = word1.Intersect(word2).Count();
Although it doesn't show in IntelliSense, String implements IEnumerable<char>, so you don't need to call ToCharArray().
Note that this will only count each character once, so if both strings contain the same character twice, this will only count it once.
If you want to count multiple occurrences, use the following code:
var commonChars = word1.Intersect(word2);
var commonCount = commonChars.Sum(c => Math.Min(
word1.Count(q => q == c),
word2.Count(q => q == c)
));
A: int numberOfCommonChars = (from c1 in word1.ToCharArray()
from c2 in word2.ToCharArray()
where c1 == c2
select c1).Distinct().Count();
| |
doc_5406
|
*******order table**************
id client order_date
5 7 2015-12-27
6 7 2015-12-28
8 7 2015-12-27
9 7 2016-01-27
10 7 2016-01-28
11 7 2016-01-27
12 7 2016-02-27
13 7 2016-02-28
14 7 2016-02-27
15 9 2016-01-27
16 9 2016-01-27
17 9 2016-01-27
18 9 2016-02-02
19 9 2016-02-04
20 9 2016-02-04
21 11 2015-12-27
22 11 2015-12-27
I am trying to write a query:
SELECT count(*) as regular_client FROM
( SELECT count(*) as totalCount, client
FROM order
where `order_date` >= (DATE_FORMAT(CURDATE(), '%Y-%m-01') - INTERVAL 3 MONTH)
GROUP BY `client`
) subq WHERE totalCount >= 3;
Expected Output:
regular_client
2
| |
doc_5407
|
$collections->filter(function($obj){
if($obj->getAttr() == X){
return $obj;
}
});
if the $collections contains, for example, one million of records then the performance is degraded. What the solution for filter big collections ?
A: make a query should be great solutions but if you have one million of records you should implement a pagination too
| |
doc_5408
|
But I get a name error global name 'Prefetch' is not defined.
My query looks like this:
prefetch = Observation.objects.prefetch_related(Prefetch('flowers__observations'))
What am I missing here? I cannot find any examples anywhere using the Prefetch object.
I want to use Prefetch because it allows you to pass it a custom queryset. I need to filter the results from prefetch_related, and the Prefetch objects seems like the best way to do it.
A: You need to import Prefetch
Add this along with your list of imports:
from django.db.models import Prefetch
| |
doc_5409
|
The problem seems to be related to the XmlSerializer performing worse when running in 64bit, and googling around, people have advised to use sgen.exe to generate a *.XmlSerializers.dll at compile time. Unfortunately though, this doesn't seem to work as running the sgen post built event :
“$(SDK40ToolsPath)\x64\sgen.exe” /a:"$(TargetPath)" /force /r "Xceed.Wpf.AvalonDock.dll"
produces the following error :
1>EXEC : error : Cannot deserialize type 'Microsoft.Windows.Shell.SystemParameters2' because it contains property 'IsGlassEnabled' which has no public setter.
I don't really want to have to use the /t command to target every type.
Have any other people experienced the issue and have a solution?
A: I ran into this problem as well and the only solution I found was to specify the types individually. I found this article by Mikhail Shilkov which shows a succinct way to specify multiple types for the post build tasks in the .csproj file. I specified only the types referenced in new XmlSerializer() constructor calls:
<Target Name="AfterBuild" DependsOnTargets="AssignTargetPaths;Compile;ResolveKeySource" Inputs="$(MSBuildAllProjects);@(IntermediateAssembly)" Outputs="$(OutputPath)$(_SGenDllName)">
<!-- This contents of this list was determined by looking at the new XmlSerializer() calls in the code. -->
<ItemGroup>
<SgenTypes Include="Xceed.Wpf.AvalonDock.Layout.LayoutRoot" />
<SgenTypes Include="Xceed.Wpf.AvalonDock.Layout.LayoutAnchorablePaneGroup" />
<SgenTypes Include="Xceed.Wpf.AvalonDock.Layout.LayoutAnchorablePane" />
<SgenTypes Include="Xceed.Wpf.AvalonDock.Layout.LayoutAnchorable" />
<SgenTypes Include="Xceed.Wpf.AvalonDock.Layout.LayoutDocumentPaneGroup" />
<SgenTypes Include="Xceed.Wpf.AvalonDock.Layout.LayoutDocumentPane" />
<SgenTypes Include="Xceed.Wpf.AvalonDock.Layout.LayoutDocument" />
<SgenTypes Include="Xceed.Wpf.AvalonDock.Layout.LayoutAnchorGroup" />
<SgenTypes Include="Xceed.Wpf.AvalonDock.Layout.LayoutPanel" />
</ItemGroup>
<Delete Files="$(TargetDir)$(TargetName).XmlSerializers.dll" ContinueOnError="true" />
<SGen BuildAssemblyName="$(TargetFileName)" BuildAssemblyPath="$(OutputPath)" References="@(ReferencePath)" ShouldGenerateSerializer="true" UseProxyTypes="false" KeyContainer="$(KeyContainerName)" KeyFile="$(KeyOriginatorFile)" DelaySign="$(DelaySign)" ToolPath="$(SGenToolPath)" Types="@(SgenTypes)">
<Output TaskParameter="SerializationAssembly" ItemName="SerializationAssembly" />
</SGen>
</Target>
After making these changes, I ran into another error:
Generated serialization assembly is not signed
This was resolved by disabling signing by removing the following lines from AssemblyInfo.cs:
#pragma warning disable 1699
[assembly: AssemblyDelaySign( false )]
[assembly: AssemblyKeyFile( @"..\..\sn.snk" )]
[assembly: AssemblyKeyName( "" )]
#pragma warning restore 1699
Another solution may be to enable signing in Project Properties > Signing, but I have not tried this.
| |
doc_5410
|
Could you please give me a hint what i am doing wrong?
The parts of my presenter related to the DataGrid are:
// Create a list data provider.
final ListDataProvider<String> dataProvider = new ListDataProvider<String>();
public interface MyView extends PopupView, HasUiHandlers<DeviceLogfileUiHandlers> {
DataGrid<String> getDataGrid();
}
@Inject
DeviceLogfilePresenterWidget(final EventBus eventBus, final MyView view) {
super(eventBus, view);
getView().setUiHandlers(this);
}
protected void onBind() {
super.onBind();
// Add the cellList to the dataProvider.
dataProvider.addDataDisplay(getView().getDataGrid());
TextColumn<String> stringColumn = new TextColumn<String>() {
@Override
public String getValue(String s) {
return s;
}
};
getView().getDataGrid().addColumn(stringColumn);
}
@Override
protected void onReveal() {
super.onReveal();
}
public void setDeviceLog(List<String> logEntries) {
getView().getDataGrid().setRowData(0, logEntries);
//These entries make the presenter not show up any more:
dataProvider.addDataDisplay(getView().getDataGrid());
dataProvider.setList(logEntries);
getView().getDataGrid().setRowCount(logEntries.size(), true);
getView().getDataGrid().setVisibleRange(0, logEntries.size());
getView().getDataGrid().setPageSize(logEntries.size());
getView().getDataGrid().redraw();
}
| |
doc_5411
|
Basically I have an account table with and id a username and a password and another table which stores a user id and the user id of its friend. For my next objective I have to be able to get the username of the friend of the first user with only one query and I don't know how to do that. I've tried a few options with inner join but still haven't been able to select the usernames. Down below you can find attached images of the database, and the two tables.
Account Table
Friends Table
Query I tried
A: You were close.
You have Accounts => Friends => Friends
It should be Accounts => Friends => Accounts
Since you are using the accounts table twice, you need to set an alias each time. In this query, I use acc1 and acc2.
SELECT acc1.username, acc2.username FROM
accounts acc1
INNER JOIN friends ON acc1.id = friends.idUser
INNER JOIN accounts acc2 ON friends.idUserFriend = acc2.id
WHERE acc1.username = 'paRa'
| |
doc_5412
|
public class LaunchListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String input;
int coInput;
input = integerInput.getText();
coInput = Integer.parseInt(input);
JTextArea textArea = new JTextArea();
JFrame frame=new JFrame("Add JTextArea into JFrame");
if (convInput == 2)
{
String output = "Show output";
frame.add(textArea);
textArea.setText(output);
frame.setVisible(true);
A: you forget the method
setBounds(x,y,width,height);
actually setBounds can be dividen in 2 methods
setSize(w,h);
setLocation(x,y);
| |
doc_5413
|
Edit: Here is the version where I tried to set up a second array with the original values and it didn't work http://jsfiddle.net/a8YTa/5/
Edit: As requested here is the code in question:
var numIngred = document.getElementsByClassName('ingred');
var initServ = document.getElementsByClassName('servnumber')[0].innerHTML;
var newServ = document.getElementById('newserv');
var divider = 0;
function changeServ(){
divider = initServ/newServ.value;
var i=0;
for(i=0; i<numIngred.length; i++){
numIngred[i].innerHTML = numIngred[i].innerHTML/divider;
}
}
newServ.oninput = changeServ;
html which has the original values:
Serves: <span class="servnumber">8</span><br/><br/>
How many would you like to serve?:<input id="newserv" />
<br/><br/>
<span class="ingred">1</span> Apple <br/>
<span class="ingred">3</span> Peaches <br/>
<span class="ingred">.5</span> Pineapples <br/>
<span class="ingred">2</span>lbs nuts <br/>
<span class="ingred">6</span> small peppers <br/>
A: The problem with your solution is that your array consists of references to objects in the page:
var numIngred = document.getElementsByClassName('ingred'); //array of HTML elements
So, when you do numIngred[index].innerHTML, it access the current value of the property.
To solve this, you just have to create a new array to store the actual value of innerHTML, not a reference to the objects:
var defaultValues = [];
for(var i = 0; i < numIngred.length; i++) {
defaultValues[i] = numIngred[i].innerHTML;
}
Here is the fiddle:
http://jsfiddle.net/a8YTa/7/
A: You are calculating your ingredients from the last array, thus your recipe is soon going to become a big mush. :)
You need to create an array which contains the original ingredients and remains unchanged and then calculate your new values from this array when a value (Amount to serve) is entered into the textbox.
Hope this helps.
A: Re. your comment above:
origingred is the same as numingred. It's a (live) node list containing the same (live) span.ingred elements. Changing them in numingred changes origingred too.
What you need is a real static data source.
You could either store youre ingredient in a real array, like this:
http://jsfiddle.net/EmWeG/
or use extra attributes in your markup:
<span class="ingred" data-orig="1">1</span>
then base your calculation on
parseFloat(numIngred[i].getAttribute('data-orig'))
// i.e. numIngred[i].innerHTML = <the above> / divider;
| |
doc_5414
|
Below is the response before server change
{
"current_page": 1,
"data": [
{
"Id": "127",
"Title": "Test",
"AuthorName": "Test",
"AuthorDesignation": "dg",
"Description": "Test",
"Image": "1535538907.JPG",
"MediaType": "0",
"Date": "2018-08-29 05:35:07",
"Status": "1",
"DonateLink": null,
"created_at": "-0001-11-30 00:00:00",
"updated_at": "2018-08-29 10:35:07",
"delete_at": "0000-00-00 00:00:00",
"Thumbnail": "1535538907.JPG"
}
],
"from": 1,
"last_page": 1,
"next_page_url": "",
"path": "myurl/api/news",
"per_page": 10,
"prev_page_url": "",
"to": 5,
"total": 5,
"status": true
}
After changed the server below is the response
{
"current_page": 1,
"data": [
{
"Id": 127,
"Title": "Test",
"AuthorName": "Test",
"AuthorDesignation": "dg",
"Description": "test",
"Image": "1535538907.JPG",
"MediaType": 0,
"Date": "2018-08-29 10:35:07",
"Status": 1,
"DonateLink": null,
"created_at": "-0001-11-30 00:00:00",
"updated_at": "2018-08-29 15:35:07",
"delete_at": "0000-00-00 00:00:00",
"Thumbnail": "1535538907.JPG"
}
],
"from": 1,
"last_page": 1,
"next_page_url": "",
"path": "my_url/api/news",
"per_page": 10,
"prev_page_url": "",
"to": 5,
"total": 5,
"status": true
}
The Issue is that ID,MediaType,Status all changed from string to int.how could i get back response with same datatype.
A: Perhaps you've also changed the PHP version to 7.x+ and your functions/methods are using type-hinting?
Unlike the previous versions of PHP, 7+ versions allow you to type-hint strings, ints, etc and PHP would try to convert the value to the appropriate type. For example:
public function test(string $name)
expects a string and even if you pass test(1), you will still receive a string with a value of 1. The other way around is also valid, if you pass a string "1" and the function expects an int, it will try to cast it to an int.
You can easily check if this is the case by enabling the PHP strict mode by adding
declare(strict_types = 1);
In strict mode, PHP will rise a TypeError exception, so it would probably break your code, but you will now this is what is causing the issue.
In any case, as Tschitsch commented, you can always type cast the integers to strings, but it does indeed look like these should be ints, rather than strings.
| |
doc_5415
|
The following permissions have not been approved for use and are not being shown to people using your app: user_likes.
Submit them for review or learn more.
But according to documentation it shouldn't, because my app created before April 30th, 2014.
Link to app: https://www.facebook.com/brights.com.ua/app_327215967365892
Js code:
window.fbAsyncInit = function () {
FB.init({
appId: FB_APP_ID,
status: true,
cookie: true,
xfbml: true
});
};
(function (d) {
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) { return; }
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/ru_RU/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
function facebookLogon(callback, callbackCancel) {
FB.login(function (response) {
if (response.authResponse) {
callback(response.authResponse.accessToken);
} else {
if (callbackCancel) {
callbackCancel();
}
}
}, { scope: FB_PERMISSIONS, privacy: "{ 'value': 'EVERYONE' }" });
};
| |
doc_5416
|
const [checkbox, setCheckbox] = React.useState(false);
...
<TouchableHighlight underlayColor="transparent" onPress={() => {setCheckbox(!setCheckbox)}}>
{added ? <MaterialIcons name="playlist-add-check" size={40} />
: <MaterialIcons name="playlist-add" size={40} />}
</TouchableHighlight>
However I have made some changes, and now I can't seem to replicate this behavior. I am using AsyncStorage class to storage and get arrays of objects for display. For simplification, in the example below I removed the storage code, and the objects each have an 'id' and an 'added' attribute, which is essentially the boolean value of the checkbox.
I am now attempting to update the icon shown to the user whenever it is pressed. I know the function is being called, but it will not update the icon. I am using array.map to create the list of icons. I created a demo here, and the code is below: https://snack.expo.dev/@figbar/array-map-icon-update
const templateObject = {
id: 0,
added: false,
};
const templateObject2 = {
id: 1,
added: true,
};
export default function App() {
const [savedNumbers, setSavedNumbers] = React.useState([]);
React.useEffect(() => {
setSavedNumbers([templateObject,templateObject2]);
}, []);
const populateSavedNumbers = () =>
savedNumbers.map((num, index) => <View key={index}>{renderPanel(num.id,num.added)}</View>);
const updateNumber = (id) => {
let capturedIndex = -1;
for(var i = 0; i < savedNumbers.length; i += 1) {
if(savedNumbers[i].id === id) {
capturedIndex = i;
break;
}
}
let _tempArray = savedNumbers;
_tempArray[capturedIndex].added = !_tempArray[capturedIndex].added;
setSavedNumbers(_tempArray);
}
const renderPanel = (id:number, added:boolean) => {
return (
<View>
<TouchableHighlight underlayColor="transparent" onPress={() => {updateNumber(id);}}>
{added ? <MaterialIcons name="playlist-add-check" size={40} />
: <MaterialIcons name="playlist-add" size={40} />}
</TouchableHighlight>
</View>
);
}
return (
<View>
<View>buttons:</View>
<View>{populateSavedNumbers()}</View>
</View>
);
}
A: This is a common React pitfall where things don't re-render when it seems like they should. React does shallow comparisons between new and old states to decide whether or not to trigger a re-render. This means that, when declaring a variable to simply equal a state variable which is an object or an array, a re-render is not triggered since those two variables now reference the same underlying data structure.
In this case, you are setting _tempArray to reference the array savedNumbers rather than creating a new array. Therefore, React's shallow comparison comes back as "equal", and it doesn't believe that a re-render is necessary.
To fix this, change this line:
let _tempArray = savedNumbers;
to this:
let _tempArray = [...savedNumbers];
| |
doc_5417
|
Assuming I have the following class:
public class Person
{
public int Account { get; set; }
public string BirthCity { get; set; }
public string Name { get; set; }
public Family Family { get; set; }
}
Each Person that gets to the DAL will automatically be assigned with Status according to that algorythm. My real problem is much more complex, but this example does explain it well I think.
The graph describes scenarios and I need to translate it to code. I want my solution to be as flexible to changes as possible. Ofcourse writing ifs and switch case is the easiest yet its not a good solution.
One idea I had was creating an Xml file suting the scenarios, but I think that it might not be that good.
Does anyone have any Ideas about this issue?
| |
doc_5418
|
Example
input: Stack Overflow helps%me(a lot
output: Stack_Overflow_helps_me_a_lot
I wrote the code below but it doesn't seem to be working.
set varname $origVar
puts "Variable Name :>> $varname"
if {$varname != ""} {
regsub -all {[\s-\]\[$^?+*()|\\%&#]} $varname "_" $newVar
}
puts "New Variable :>> $newVar"
one issue is that, instead of replacing the string in $varname, it is deleting the data after first space encountered inside $origVar instead of $varname. Also there is no value stored in $newVar. No idea why, and also i read the example code (for proper syntax) in my tcl book and according to that it should be something like this
regsub -all {[\s-][$^?+*()|\\%&#]} $varname "_" newVar
so i used the same syntax but it didn't work and gave the same result as modifying the $origVar instead of required $varname value.
A: The second version is closer. By putting the result in $newVar you're actually setting a variable named whatever is stored in $newVar, i.e. you would then have to access it by $$newVar, so to speak (not valid in Tcl). Anyway, the issue is probably that in your second version, you don't seem to be escaping certain characters. Try this:
regsub -all {[\s\-\]\[$^?+*()|\\%&#]} $varname "_" newVar
Another way to organize that to minimize escaping is this:
regsub -all {[][\s$^?+*()|\\%&#-]} $varname "_" newVar
And, I don't know if this is too general, but you can try this too:
regsub -all {\W} $varname "_" newVar
A: Another solution is to use the string map command, which is simpler: the string map command takes in a list of old/new and a string:
set varname [string map {% _ ( _ " " _} $varname]
In the above example, for the sake of brievity, I only replaced %, (, and space " " with an underscore. The disadvantage of this solution is the old/new list can be somewhat long. The advantage is easier to understand.
| |
doc_5419
|
Currently, my naming convention for generated .o files is $(SOURCE_FULLPATH).$(CONFIGURATION).o. For instance, ABC.cpp generates ABC.cpp.debug.o in debug mode.
Now I would like to write the pattern rule for generating those object files in a configuration-independent way. What I did was: from each XX.o filename, I strip the .debug or .release suffix from XX, and use the remaining part of XX as the source filename.
%.o: $$(basename %)
$(CC) $(CC_FLAGS) $(INCLUDE_FOLDERS) -c -o $@ $<
With this trick, I can build the executable correctly, except that I get one warning message from make:
make: Circular makefile.o <- makefile dependency dropped.
I am puzzled because I do not list makefile or makefile.o as a target or dependency anywhere in my makefile. I did a search on SO, but most questions about Circular dependency is on a specific user source file, rather than the makefile itself. Can anyone help me understand what causes the circular dependency, and how to get rid of this warning message?
A sample makefile that can reproduce this issue is listed below.
.SECONDEXPANSION:
PROJECT := helloworld
CC := clang++
BUILD_FOLDER := Build
OBJ_FILE_SUFFIX := .o
# Source
CPP_FILES :=\
Source/hello.cpp \
Source/mysqrt.cpp \
INCLUDE_FOLDERS := \
-IInclude
# MMD outputs the dependency files (".d" files). These files will be used by
# this makefile to allow for dependency checking on .h files.
CC_FLAGS += -MMD
EXISTING_OBJ_FILES = $(wildcard $(addsuffix *.o, $(basename $(CPP_FILES))))
##--------------------
## Targets definition
##--------------------
.PHONY:default
default: all
.PHONY:all
all: debug release
.PHONY:debug release
# Add a 'debug'/'release' suffix to the name of the object file
# e.g. hello.cpp -> hello.cpp.debug.o
debug release: OBJ_FILES=$(addsuffix .$@$(OBJ_FILE_SUFFIX), $(CPP_FILES))
debug release: $${OBJ_FILES} # Use Secondary Expansion to get the obj names
$(CC) $^ -o $(BUILD_FOLDER)/$(PROJECT)_$@
# Strip configuration name from the end of the object file name
%.o: $$(basename %)
$(CC) $(CC_FLAGS) $(INCLUDE_FOLDERS) -c -o $@ $<
## clean: remove executable, all object files, and all dependency files
.PHONY:clean
clean:
-rm -f $(BUILD_FOLDER)/$(PROJECT) $(EXISTING_OBJ_FILES) $(EXISTING_OBJ_FILES:.o=.d)
# Include the dependent files so that in later builds, modified .h files
# will cause all .cpp dependent on them to rebuild
-include $(OBJ_FILES:.o=.d)
The folder structure is
makefile
Source
- hello.cpp
- mysqrt.cpp
Include
- mysqrt.h
The full output of make debug is
make: Circular makefile.o <- makefile dependency dropped.
clang++ -MMD -IInclude -c -o Source/hello.cpp.debug.o Source/hello.cpp
clang++ -MMD -IInclude -c -o Source/mysqrt.cpp.debug.o Source/mysqrt.cpp
clang++ Source/hello.cpp.debug.o Source/mysqrt.cpp.debug.o -o Build/helloworld_debug
Everything is good except for the first line.
I would also really appreciate it if anyone can point to me if there is any bad practice in my makefile (I am still a newbie in makefile). Thank you in advance!
A: GNU Make always attempts to update the makefile(s) it has read before
making anything else. If it finds rules and prerequisites that tell it
to update makefile(s), then it does so and then starts again from scratch -
including attempting to update the makefile(s). See 3.5 How Makefiles Are Remade.
In your recipe:
%.o: $$(basename %)
$(CC) $(CC_FLAGS) $(INCLUDE_FOLDERS) -c -o $@ $<
you have provided make with a rule for making makefile.o from makefile.
It is also the inverse of the rule in the builtin recipe
%: %.o
$(LINK.o) $^ $(LOADLIBES) $(LDLIBS) -o $@
which makes an executable from a single object file. So your recipe has introduced the circularity:
makefile.o <- makefile <- makefile.o
when make is considering makefile itself as a target.
You could suppress the circularity by expressly deleting the builtin inverse rule,
by writing the empty rule:
%: %.o
in the makefile. Then you could observe the following confusion on the part of the
compiler:
$ make makefile.o
clang++ -c -o makefile.o makefile
clang: warning: makefile: 'linker' input unused
And the same would occur if you attempted to make any target that depended
on makefile.o.
It is probably safe to assume that you will have no targets that depend on
makefile.o. Nevertheless a rule that would attempt to
compile foo.o from any existing file foo is clearly more sweeping that you
want or need. For the particular pattern of dependency that you wish to capture:
foo.cpp.{debug|release}.o: foo.cpp
You'd be better off with:
%.o: $$(basename $$(basename %)).cpp
$(CC) $(CC_FLAGS) $(INCLUDE_FOLDERS) -c -o $@ $<
Note, BTW, that in GNU Make conventions - the conventions that are
assumed by GNU Make's builtin rules - CC denotes your C compiler while
CXX denotes your C++ compiler. Likewise flags for the C compiler are
denoted CFLAGS and flags for the C++ compiler are denoted CXXFLAGS.
Flags for the preprocessor are denoted CPPFLAGS, and -Ipath options
- which are preprocessor options - are conventionally be passed through CPPFLAGS.
| |
doc_5420
|
Date 1 Date 2 Date 3 Date 4 Date 5
A NA 0.1 0.2 NA 0.3
B 0.1 NA NA 0.3 0.2
C NA NA NA NA 0.3
D 0.1 0.2 0.3 0.1 NA
E NA NA 0.1 0.2 0.1
I would like to change the NA values of my data based on the first date a value is registered. So for example for A, the first registration is Date 2. Then I want that before that registration the values of NA in A are 0, and after the first registration the values of NA become the mean of the registered values.
In the case of C all NA values will become 0 since the first registration is on the last date.
Get something like this:
Date 1 Date 2 Date 3 Date 4 Date 5
A 0 0.1 0.2 0.2 0.3
B 0.1 0.2 0.2 0.3 0.2
C 0 0 0 0 0.3
D 0.1 0.2 0.3 0.1 0.175
E 0 0 0.1 0.2 0.1
Can you help me? I'm not sure how to do it in R.
EDIT:
what if I want the mean of the values NA is in between? In this case for A, change the NA in Date 4 for the mean of Date 3 and 5.
A: A tidyverse approach, we create an index to gather by assigning a row_number() to every row. We then group_by every row and find the first non-NA value in the row and replace every NA value before that to 0 and all other NA values after that to mean. We finally spread the variables back to wide format by removing unnecessary columns created during calculation.
library(tidyverse)
df %>%
mutate(row = row_number()) %>%
gather(key, value, -row) %>%
group_by(row) %>%
mutate(value1 = replace(value, is.na(value) & row_number() < which.max(!is.na(value)), 0),
value2 = replace(value1, is.na(value1), mean(value, na.rm = TRUE))) %>%
ungroup() %>%
select(-value1, -value) %>%
spread(key, value2) %>%
select(-row)
# Date1 Date2 Date3 Date4 Date5
# <dbl> <dbl> <dbl> <dbl> <dbl>
#1 0. 0.100 0.200 0.200 0.300
#2 0.100 0.200 0.200 0.300 0.200
#3 0. 0. 0. 0. 0.300
#4 0.100 0.200 0.300 0.100 0.175
#5 0. 0. 0.100 0.200 0.100
A base R approach using apply for each row
t(apply(df, 1, function(x) {
inds <- which.max(!is.na(x))
x[inds:length(x)] <- replace(x[inds:length(x)], is.na(x[inds:length(x)]),
mean(x[inds:length(x)], na.rm = TRUE))
x[1:inds] <- replace(x[1:inds], is.na(x[1:inds]), 0)
x
}))
# Date1 Date2 Date3 Date4 Date5
#A 0.0 0.1 0.2 0.2 0.300
#B 0.1 0.2 0.2 0.3 0.200
#C 0.0 0.0 0.0 0.0 0.300
#D 0.1 0.2 0.3 0.1 0.175
#E 0.0 0.0 0.1 0.2 0.100
| |
doc_5421
|
I have a segment of code I am trying to run and basically without the popup, the locking system works. There is no issue, the haslock will indeed return false when the first user has the lock, but then you introduce a popup box and the locking system doesn't work like it should, and grants a lock to the 2nd user even tho the popup box and that line of code, or any lines of code after it for that matter, have not been executed..
I tried it with a delay after the popup box because I originally thought that maybe it's not waiting for the input back so therefore it just kinda skips over the popup box after it has pushed it out to the sheet... but even with a long delay after the popup box portion of the code the 2nd user is still granted a lock.. Maybe I am doing this wrong but the popup box is the only thing that throws my code off.
I tried the try...catch, I found an equivalent if...else if and no luck, i even tried just an if...else... I know it is not because the trylock is too long, or too short I've tried a range of values, I also know it is not the sleep because I've tried a range of values, as well as different placements within my code.
Tested these quite heavily, on different google user accounts on multiple different days bc I originally thought it was me just being dumb or something, but it really just seems like the popup box is the only thing that sends it off the reservation.
Examples of when the locking system works
function myFunction() {
var lock = LockService.getScriptLock();
lock.tryLock(5000);
if (!lock.hasLock()) {
Logger.log('Could not obtain lock after 5 seconds.');
return;
}
else if (lock.hasLock()) {
Logger.log('got the lock');
//Browser.inputBox("TESTING123");
Utilities.sleep(10000);
}
lock.releaseLock();
}
2
function myFunction() {
var lock = LockService.getScriptLock();
lock.tryLock(5000);
if (!lock.hasLock()) {
Logger.log('Could not obtain lock after 5 seconds.');
}
else {
Logger.log('got the lock');
//Browser.inputBox("TESTING123");
Utilities.sleep(10000);
}
lock.releaseLock();
}
with the proposed try,catch statement
function myFunction() {
var lock = LockService.getScriptLock();
try {
lock.waitLock(5000); // wait 5 seconds try to get lock
} catch (e) {
Logger.log('Could not obtain lock after 5 seconds.');
}
Utilities.sleep(10000);
//Browser.inputBox("TESTING123");
lock.releaseLock();
}
it does indeed catch the error and display the popup saying it couldn't get it
Examples when it doesn't work
function myFunction() {
var lock = LockService.getScriptLock();
lock.tryLock(5000);
if (!lock.hasLock()) {
Logger.log('Could not obtain lock after 5 seconds.');
return;
}
else if (lock.hasLock()) {
Logger.log('got the lock');
Browser.inputBox("TESTING123");
Utilities.sleep(10000);
}
lock.releaseLock();
}
2
function myFunction() {
var lock = LockService.getScriptLock();
lock.tryLock(5000);
if (!lock.hasLock()) {
Logger.log('Could not obtain lock after 5 seconds.');
}
else {
Logger.log('got the lock');
Browser.inputBox("TESTING123");
Utilities.sleep(10000);
}
lock.releaseLock();
}
with the proposed try catch statement
function myFunction() {
var lock = LockService.getScriptLock();
try {
lock.waitLock(5000); // wait 5 seconds try to get lock
} catch (e) {
Logger.log('Could not obtain lock after 5 seconds.');
}
Utilities.sleep(10000);
Browser.inputBox("TESTING123");
lock.releaseLock();
}
the popup box appears in all cases. It shouldn't, because the popup box hasn't been filled in and resolved... even with putting a delay after the popup box line. I have decided to take to making my own locking system as it doesn't seem that the google system will be working for me since I need the lock to remain valid after popups.
@OlegValter not a worry with prompt, if users don't input info into the popup boxes as of the testing I've currently done it errors out and then doesn't input anything into the sheet anyways. I have come up with a work around for lock using properties service(thank you again)
function myFunction() {
var properties = PropertiesService.getScriptProperties();
const lock = properties.getProperty('Lock');
Logger.log(lock);
//if no one else has the lock
if(lock == null){
//set the value of the kvp to locked
properties.setProperty('Lock', 'Locked');
Logger.log('got the lock');
Utilities.sleep(5000);
}
else{
Logger.log('Could not obtain lock');
return;
}
//after we have ran the body of the code we want to delete the KVP bc we want the script to be open to other users
properties.deleteProperty('Lock');
}
I am currently using ScriptProperties for now as I have different users running the same script. I am finalizing most of the backend functionality for the infrastructure I have built. I plan to do some sort of app control. Ex: I want my users to basically click on a link, or open up an app on their phone that will take them to a UI that will run some of these updates, instead of needing to have every user have a google account. Any recommendations with what to go thru for UI, app control, or website.. really not sure what direction would be best at the moment I plan to feel things out.
Thank you again for your help, tried to format things a bit better this time around.
| |
doc_5422
|
function getSelectedText(){
if(window.getSelection){
select = window.getSelection().getRangeAt(0);
var st_span = select.startContainer.parentNode.getAttribute("id").split("_")[1];
var end_span = select.endContainer.parentNode.getAttribute("id").split("_")[1];
console.log(select.endContainer);
var ret_urn=[st_span,end_span];
return ret_urn
}
else if(document.getSelection){
return document.getSelection();
}
}
$(document).ready(function() {
$("div#check_button button").click(function () {
var loc = getSelectedText();
console.log(loc);
});
});
Here is my whole html file: http://pastebin.com/acdiU623
It is hard to explain it, so I prepared short movie: http://www.youtube.com/watch?v=tVk4K70JO80
In a few words: when I press left mouse button and hold it to select text/numbers and start selection from the half of letter/number, although this letter/number is not highlighted, it is added to selection. I have to start selection precisely. It is ok with wide letters, but hard with letters like i,j or l.
This is second example of my movie. I pressed left button on 3/4 of length of number 5, although 5 is not highlighted, it is selected.
Tested on FF and Opera.
A: Ok just tried this demo. and it works flawlessly. it even works on firefox. Just tested opera and safari and it works on both of them as well. Even if i select half a letter or number, it just returns the highlighted text which is what is expected when you make a selection.
try it out on a fresh webpage though just for testing purposes. then when it works and you are satisfied with the results then start making changes to your existing page.
Its a lot more simpler than your code. This is a cross-browser script to get text selected by the user
<script language=javascript>
function getSelText()
{
var txt = '';
if (window.getSelection)
{
txt = window.getSelection();
}
else if (document.getSelection)
{
txt = document.getSelection();
}
else if (document.selection)
{
txt = document.selection.createRange().text;
}
else return;
document.aform.selectedtext.value = txt;
}
</script>
<input type="button" value="Get selection" onmousedown="getSelText()">
<form name=aform >
<textarea name="selectedtext" rows="5" cols="20"></textarea>
</form>
http://www.codetoad.com/javascript_get_selected_text.asp
Hope this helps.
PK
A: There are multiple different boundary points for a selection that will look the same to the user. What you're seeing is probably the difference between the following, where | is a selection boundary:
<span>5</span><span>|6</span><span>7|</span><span>8</span>
and
<span>5|</span><span>6</span><span>7</span><span>|8</span>
In both cases, calling toString() on the selection will give you the same result ("67").
| |
doc_5423
|
A: Add --prod when you build the app. It will minify css and js files.
A: Updating to the most recent version of Ionic Cloud and building with the production flag will reduce your cold start time dramatically.
npm install @ionic/cloud-angular@latest --save
ionic build --prod
It will take longer to build but you'll have a much faster cold start time.
A: Are you mass importing in app.component.ts? Usually when you have a ton of imports, you slow down the entire application. I would check when you test in the browser, all of the unused imports. That would at least help speed up the initial load time.
| |
doc_5424
|
A couple of view holders have image views which I pass into Glide to display images.
The problem is, when the recycler view starts recycling views, the imageview width/height are that of the recycled view they then display the image incorrectly.
Here is my ImageView:
<ImageView
android:id="@+id/image"
android:layout_marginTop="@dimen/feed_item_margin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
This is passed into Glide
Glide.with(itemView.getContext())
.load(Uri.parse(MediaUtils
.getMedia(feedContent).getMediaUrl()))
.placeholder(R.drawable.placeholder)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.crossFade().into(image);
This works well until the Recyclerview starts Recycling so the first image in the recyclerview looks like this which is how it's meant to look.
however, when you scroll away from the item and scroll back it looks like this:
So the image has become distorted and is not not the full width of the parent.
I want the image view to wrap content because all the images will be different heights etc..
To test this I added this line holder.setIsRecyclable(false); to prevent recycling of this particular holder and all the images displayed as the should, however, as expected this gave the jarring effect.
So I then tried resetting the params of the image view in the OnViewRecycled method like so:
@Override
public void onViewRecycled(AbstractHolder viewHolder){
super.onViewRecycled(viewHolder);
int position = viewHolder.getAdapterPosition();
IFeedContent content = mFeedContentList.get(position);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(0, (int) Utils.dpTopx(mContext,10),0,0);
params.gravity = Gravity.CENTER;
if(isImage(content)){
viewHolder.getImageView().setImageURI(null);
viewHolder.getImageView().setImageDrawable(null);
viewHolder.getImageView().setImageResource(0);
viewHolder.getImageView().setLayoutParams(params);
}
}
In this I recreate the params in the xml but it doesn't work. The method isImage() this just checks the mimetype of the object.
Can anyone help on this? It's very frustrating.
Any help on this is appreciated.
EDIT Adapter added
public class ContentFeedAdapter extends RecyclerView.Adapter<AbstractHolder> {
private List<IFeedContent> mFeedContentList;
private Context mContext;
private Activity mMainActivity;
private UserHomeFragment mUserHomeFragment;
private UserStreamFragment mUserStreamFragment;
private AbstractHolder mAbstractHolder;
private final Map<YouTubeThumbnailView, YouTubeThumbnailLoader> mThumbnailViewToLoaderMap;
private ArrayList<MyMediaPlayer> mMediaPlayerList = new ArrayList<>();
public ContentFeedAdapter(Context ctx, List<IFeedContent> contentList, Activity mainActivity, UserHomeFragment userHomeFragment, UserStreamFragment userStreamFragment){
this.mContext = ctx;
this.mFeedContentList = contentList;
this.mMainActivity = mainActivity;
this.mThumbnailViewToLoaderMap = new HashMap<YouTubeThumbnailView, YouTubeThumbnailLoader>();
this.mUserHomeFragment = userHomeFragment;
this.mUserStreamFragment = userStreamFragment;
}
@Override
public AbstractHolder onCreateViewHolder(ViewGroup parent, int viewType) {
mAbstractHolder = createAbstractHolder(viewType, parent);
return mAbstractHolder;
}
@Override
public void onBindViewHolder(final AbstractHolder holder, final int position) {
final IFeedContent content = mFeedContentList.get(position);
holder.bindData(content);
if((content.getMedia()!=null) && !content.getMedia().isEmpty()){
String mimeType = MediaUtils.getMedia(content).getMimeType();
if(mimeType.contains(mContext.getString(R.string.video)) || mimeType.contains(mContext.getString(R.string.audio)) && !mimeType.contains(mContext.getString(R.string.youtube))){
final ProgressBar progressBar = holder.getProgress();
final ImageView playButton = holder.getPlayImage();
final Button retryButton = holder.getRetryImage();
final RelativeLayout playerOverLay = holder.getPlayerOverlay();
final ImageView mediaThumb = holder.getMediaThumbnail();
final MyMediaPlayer player = new MyMediaPlayer(mContext, holder.getTextureView(), holder.getMediaControllerAnchor(), holder.getProgress(),
mimeType, MyConstants.SEEK_TO_DEFAULT, retryButton, playButton, playerOverLay, mediaThumb);
player.setRecyclerViewPosition(position);
mMediaPlayerList.add(player);
playButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
player.startVideo(MediaUtils.getMedia(content).getMediaUrl());
holder.getPlayImage().setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
}
});
}
}
}
/**
* Release all holders used for the
* thumbnail views
*/
public void releaseYouTubeHolders(){
mAbstractHolder.releaseHolders();
}
@Override
public int getItemViewType(int position){
int viewType = -1;
//Instantiate ViewHolder Utils
//
viewType = ViewHolderUtils.selectViewHolder(mFeedContentList.get(position));
return viewType;
}
@Override
public int getItemCount() {
return mFeedContentList.size();
}
@Override
public void onViewRecycled(AbstractHolder viewHolder){
super.onViewRecycled(viewHolder);
int position = viewHolder.getAdapterPosition();
IFeedContent content = mFeedContentList.get(position);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(0, (int) Utils.dpTopx(mContext,10),0,0);
params.gravity = Gravity.CENTER;
if(isImage(content)){
viewHolder.getImageView().setImageURI(null);
viewHolder.getImageView().setImageDrawable(null);
viewHolder.getImageView().setImageResource(0);
viewHolder.getImageView().setLayoutParams(params);
}
}
/**
* Create instance of
* compatible viewholder
*
* @param viewType
* @param parent
* @return
*/
private AbstractHolder createAbstractHolder(int viewType, ViewGroup parent) {
AbstractHolder holder = null;
switch (viewType) {
case MyConstants.HOLDER_TYPE_1:
holder = ViewHolder_Var1.create(parent, mUserHomeFragment, mUserStreamFragment);
break;
case MyConstants.HOLDER_TYPE_2:
holder = ViewHolder_Var2.create(parent, mUserHomeFragment, mUserStreamFragment);
break;
case MyConstants.HOLDER_TYPE_3:
holder = ViewHolder_Var3.create(parent, mUserHomeFragment, mUserStreamFragment);
L.i(getClass().getSimpleName(), "HOLDER 3");
//holder.setIsRecyclable(false);
break;
case MyConstants.HOLDER_TYPE_4:
holder = ViewHolder_Var4.create(parent, mUserHomeFragment, mUserStreamFragment);
L.i(getClass().getSimpleName(), "HOLDER 4");
break;
case MyConstants.HOLDER_TYPE_5:
holder = ViewHolder_Var5.create(parent, mUserHomeFragment, mUserStreamFragment);
L.i(getClass().getSimpleName(), "HOLDER 5");
break;
case MyConstants.HOLDER_TYPE_6:
holder = ViewHolder_Var6.create(parent, mUserHomeFragment, mUserStreamFragment);
L.i(getClass().getSimpleName(), "HOLDER 6");
break;
case MyConstants.HOLDER_TYPE_7:
holder = ViewHolder_Var7.create(parent, mUserHomeFragment, mUserStreamFragment);
L.i(getClass().getSimpleName(), "HOLDER 7");
break;
case MyConstants.HOLDER_TYPE_8:
holder = ViewHolder_Var8.create(parent, mUserHomeFragment, mUserStreamFragment);
L.i(getClass().getSimpleName(), "HOLDER 8");
break;
case MyConstants.HOLDER_TYPE_9:
holder = ViewHolder_Var9.create(parent, mUserHomeFragment, mUserStreamFragment);
break;
case MyConstants.HOLDER_TYPE_10:
holder = ViewHolder_Var10.create(parent, mThumbnailViewToLoaderMap, mUserHomeFragment, mUserStreamFragment);
}
return holder;
}
private boolean isImage(IFeedContent contentItem) {
if (MediaUtils.getMedia(contentItem) != null) {
String mimeType = MediaUtils.getMedia(contentItem).getMimeType();
if (mimeType.contains("image")) {
L.i(getClass().getSimpleName(), "IMAGE HERE");
return true;
} else {
L.i(getClass().getSimpleName(), "NO IMAGE HERE");
}
}
return false;
}
}
EDIT 2 ViewHolder 3
public class ViewHolder_Var3 extends AbstractHolder {
@Bind(R.id.text_holder1) TextView heading;
@Bind(R.id.text_holder2) TextView body;
@Bind(R.id.image)ImageView image;
@Bind(R.id.tabs_layout)LinearLayout tabsLayout;
@Bind(R.id.hot)TextView hot;
@Bind(R.id.comments)TextView children;
@Bind(R.id.gif_label)TextView gifTag;
@Bind(R.id.user_name)TextView userName;
@Bind(R.id.tag1)TextView tag1;
@Bind(R.id.tag2)TextView tag2;
@Bind(R.id.tag3)TextView tag3;
@Bind(R.id.profile_pic) SimpleDraweeView profilePic;
private boolean mEllipsize;
private boolean mExpanded;
private UserHomeFragment mUserHomeFragment;
private UserStreamFragment mUserStreamFragment;
public ViewHolder_Var3(View itemView, UserHomeFragment userHomeFragment, UserStreamFragment userStreamFragment) {
super(itemView);
ButterKnife.bind(this, itemView);
mUserHomeFragment = userHomeFragment;
this.mUserStreamFragment = userStreamFragment;
}
@Override
public void bindData(final IFeedContent feedContent) {
userName.setText(feedContent.getAuthor().getDisplayName());
image.setImageResource(0);
image.setImageDrawable(null);
image.setImageURI(null);
TextView [] tagsArray = {tag1, tag2, tag3};
if (feedContent.getName() != null) {
heading.setText(feedContent.getName());
} else {
heading.setText(feedContent.getUrl());
}
if (feedContent.getName() != null) {
body.setText((feedContent.getMessage()));
} else {
body.setText(feedContent.getUrl());
}
Log.i(ViewHolder_Var3.class.getSimpleName(), "Number of lines: " + String.valueOf(body.getLineCount()));
if(!MediaUtils.getMedia(feedContent).getMimeType().equals("image/gif")){
gifTag.setVisibility(View.GONE);
Glide.with(itemView.getContext()).load(Uri.parse(MediaUtils.getMedia(feedContent).getMediaUrl())).placeholder(R.drawable.placeholder).diskCacheStrategy(DiskCacheStrategy.SOURCE).crossFade().into(image);
}else {
Glide.with(itemView.getContext()).load(Uri.parse(MediaUtils.getMedia(feedContent).getMediaUrl())).asGif().placeholder(R.drawable.placeholder).diskCacheStrategy(DiskCacheStrategy.RESULT).crossFade().into(image);
}
displayProfilePic(feedContent, profilePic);
Glide.with(itemView.getContext()).load(Uri.parse(MediaUtils.getMedia(feedContent).getMediaUrl())).placeholder(R.drawable.placeholder).diskCacheStrategy(DiskCacheStrategy.ALL).crossFade().into(image);
if(mUserHomeFragment==null){
userName.setEnabled(false);
profilePic.setEnabled(false);
}else{
userName.setEnabled(true);
profilePic.setEnabled(true);
}
userName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(mUserHomeFragment, feedContent.getAuthor().getId(), feedContent.getParentId());
}
});
profilePic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(mUserHomeFragment, feedContent.getAuthor().getId(), feedContent.getParentId());
}
});
long hotAmt = feedContent.getLikeCount() - feedContent.getDislikeCount();
hot.setText(String.valueOf(hotAmt));
children.setText(String.valueOf(feedContent.getChildCount()));
List<String> tagsList = feedContent.getTags();
populateTags(tagsList, tagsArray);
// if (feedContent.getTags().size() > 0) addTags(tags, tabsLayout);
ViewTreeObserver vto = body.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
ViewTreeObserver obs = body.getViewTreeObserver();
obs.removeOnGlobalLayoutListener(this);
Layout layout = body.getLayout();
if(layout!=null){
int lines = layout.getLineCount();
if(lines>0){
if(layout.getEllipsisCount(lines-1)>0){
mEllipsize = true;
}
}
}
}
});
body.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mEllipsize) {
if (!mExpanded) {
ObjectAnimator animation = ObjectAnimator.ofInt(body, "maxLines", 20);
//animation.setInterpolator(new BounceInterpolator());
animation.setDuration(200).start();
// Toast.makeText(itemView.getContext(), "I AM CLICKED", Toast.LENGTH_LONG).show();
mExpanded = true;
} else {
ObjectAnimator animation = ObjectAnimator.ofInt(body, "maxLines", 4);
//animation.setInterpolator(new BounceInterpolator());
animation.setDuration(200).start();
// Toast.makeText(itemView.getContext(), "I AM CLICKED", Toast.LENGTH_LONG).show();
mExpanded = false;
}
}
}
});
}
@Override
public ImageView getImageView(){
return image;
}
public static ViewHolder_Var3 create(ViewGroup parent, UserHomeFragment homeFragment, UserStreamFragment userStreamFragment){
View root = LayoutInflater.from(parent.getContext()).inflate(R.layout.feed_content_item_layout_var3, parent, false);
return new ViewHolder_Var3(root, homeFragment, userStreamFragment);
}
}
A: I ran into the same issue and i solved it as below,
Glide.with(mContext)
.load(model.getImage())
.asBitmap()
.fitCenter()
.placeholder(R.drawable.ic_placeholder)
.error(R.drawable.ic_placeholder)
.into(holder.ivImage);
I just added .asBitmap() and .fitCenter() , Issue Resolved.
A: Add this line
android:adjustViewBounds="true"
to the imageview in layout file it will automatically resize image view.
in glide change .crossFade() to .fitCenter()
A: 1 .
add android:adjustViewBounds="true" to ImageView
<ImageView
android:id="@+id/img_item_my_show_img"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:src="@drawable/backgrund_banner"/>
2.Change the following code to Glide
Glide.with(context).asBitmap().load(imgUrl)
.apply(RequestOptions()
.fitCenter()
.placeholder(R.drawable.default_img)
.error(R.drawable.error_img))
.into(ImageView)
A: you must in onBindViewHolder set width of image
for example:
yourImageView.getLayoutParams().width = GetScreenWidthPx();
public int GetScreenWidthPx() {
DisplayMetrics displayMetrics = MyApp.GetContext().getResources().getDisplayMetrics();
return displayMetrics.widthPixels - DpToPx(your_margin_in_dp);
}
public static int DpToPx(int dp) {
DisplayMetrics displayMetrics =
MyApp.GetContext()
.getResources()
.getDisplayMetrics();
return (int) (dp * displayMetrics.density + 0.5f);
}
A: Try giving your recyclerview's item ImageView an attribute as:
android:scaleType="fitXY"
| |
doc_5425
|
Rows interface{}
In the Rows interface i put ProductResponse struct.
type ProductResponse struct {
CompanyName string `json:"company_name"`
CompanyID uint `json:"company_id"`
CompanyProducts []*Products `json:"CompanyProducts"`
}
type Products struct {
Product_ID uint `json:"id"`
Product_Name string `json:"product_name"`
}
I want to access Product_Name value. How to access this.
I can access outside values (CompanyName , CompanyID) by using "reflect" pkg.
value := reflect.ValueOf(response)
CompanyName := value.FieldByName("CompanyName").Interface().(string)
I am not able to access Products struct values. How to do that?
A: You can use type assertion:
pr := rows.(ProductResponse)
fmt.Println(pr.CompanyProducts[0].Product_ID)
fmt.Println(pr.CompanyProducts[0].Product_Name)
Or you can use the reflect package:
rv := reflect.ValueOf(rows)
// get the value of the CompanyProducts field
v := rv.FieldByName("CompanyProducts")
// that value is a slice, so use .Index(N) to get the Nth element in that slice
v = v.Index(0)
// the elements are of type *Product so use .Elem() to dereference the pointer and get the struct value
v = v.Elem()
fmt.Println(v.FieldByName("Product_ID").Interface())
fmt.Println(v.FieldByName("Product_Name").Interface())
https://play.golang.org/p/RAcCwj843nM
A: Instead of using reflection you should use type assertion.
res, ok := response.(ProductResponse)
if ok { // Successful
res.CompanyProducts[0].Product_Name // Access Product_Name or Product_ID
} else {
// Handle type assertion failure
}
A: You can access Product_Name value without even using "reflect" pkg by simply iterating over the CompanyProducts slice by using for loop.I have created a simple program for you scenario as follows:
package main
import (
"fmt"
)
type ProductResponse struct {
CompanyName string `json:"company_name"`
CompanyID uint `json:"company_id"`
CompanyProducts []*Products `json:"CompanyProducts"`
}
type Products struct {
Product_ID uint `json:"id"`
Product_Name string `json:"product_name"`
}
func main() {
var rows2 interface{} = ProductResponse{CompanyName: "Zensar", CompanyID: 1001, CompanyProducts: []*Products{{1, "prod1"}, {2, "prod2"}, {3, "prod3"}}}
for i := 0; i < len(rows2.(ProductResponse).CompanyProducts); i++ {
fmt.Println(rows2.(ProductResponse).CompanyProducts[i].Product_Name)
}
}
Output:
prod1
prod2
prod3
| |
doc_5426
|
The issue is with the "ops_function" bit throwing a 'str' object is not callable error.
Let me know if you need more info and thank you for any insight!
from art import logo
print(logo)
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
return a / b
operations = {
"+": "add",
"-": "subtract",
"*": "multiply",
"/": "divide"
}
first = int(input("Enter a number: "))
second = int(input("Enter another number: "))
for op in operations:
print(op)
op_choice = input("Select an operator from the list above: ")
ops_function = operations[op_choice]
answer = ops_function(first, second)
print(f"{first} {op_choice} {second} = {answer}")
A: Your operations dictionary maps strings to strings. You want it to map strings to functions. For example, "add" is a string, while add is a function. In effect, you're trying to do "add"(first, second), when what you want is add(first, second). So change operations to:
operations = {
"+": add,
"-": subtract,
"*": multiply,
"/": divide
}
I.e. remove the quotes from the function names. That way they'll be functions rather than strings.
| |
doc_5427
|
<root>
<initialAmount>1000</initialAmount>
<Amortization_List>
<Amortization Index="0">10</Amortization>
<Amortization Index="1">25</Amortization>
<Amortization Index="2">-10</Amortization>
</Amortization_List>
</root>
Now, I want to add to the initialAmount the nodes Amortization consecutively, so my output looks something like this:
<result>
<amount>1010</amount>
<amount>1035</amount>
<amount>1025</amount>
</result>
How can I do this in xslt 2.0?
Thanks very much!
A: Use
<xsl:template match="root">
<result>
<xsl:variable name="amount" select="initialAmount"/>
<xsl:apply-templates select="Amortization_List/Amortization[1]">
<xsl:with-param name="sum" select="$amount"/>
</xsl:apply-templates>
</result>
</xsl:template>
<xsl:template match="Amortization">
<xsl:param name="sum"/>
<xsl:variable name="amount" select=". + $sum"/>
<amount><xsl:value-of select="$amount"/></amount>
<xsl:apply-templates select="following-sibling::Amortization[1]">
<xsl:with-param name="sum" select="$amount"/>
</xsl:apply-templates>
</xsl:template>
| |
doc_5428
|
I have the following code coming from an external dependency and can't modify it.
Seen few examples here but they reference Junit4.
Or asking to use PowerMock which I do not want to use.
Is there a way to mock this or some way around this? Please advice. Thanks.
A method in my class using the legacy class and method
public class MyClass {
void myMethod() {
// I need to use this legacyMethod
Map<String, String> map = ExternalClass.externalMethod();
// some logic
}
}
External class which I can't change.
public class ExternalClass {
public static Map<String, String> externalMethod() {
// other logic
// I want to mock this so that the variable name can get a value out of this.
String name = System.getenv("SOME_ENV_VALUE");
if(name == null) {
// test fails cos I end up inside here currently.
throw new RuntimeException();
}
// other logic
return new HashMap<>();
}
}
| |
doc_5429
|
How to submit html code to a textbox and output as text without compromising security?
This is what I'm currently trying:
DATA GOES IN (SUBMITTED INTO TEXTBOX)
Dim txtInput As String = Server.HtmlEncode(Me.txtInput.Text)
DATA COMES OUT (READ AS TEXT ON PAGE)
txtOutput.Text = Server.HtmlDecode(MyText)
Desired output is for the format to be the same as initially entered.
A: You should HtmlEncode text you are setting in a textbox:
txtOutput.Text = Server.HtmlEncode(MyText)
And HtmlDecode text you are getting from a textbox:
MyText = Server.HtmlDecode(txtOutput.Text)
If you're storing the data in sql then I recommend using parameterized queries as well. It handles most security concerns, such as SQL injection, for you.
| |
doc_5430
|
me = graphene.Field(UserType)
def resolve_user(root, info):
logger.info("***** Inside resolve ****")
return info.context.user
and my UserType is defined like this.
class UserType(DjangoObjectType):
fields = ["id", "name", "email", "username"]
class Meta:
model = User
I'm on Django==3.0 if it helps
I'm authenticated and the cookies are present. It's not even printing the log which is confusing me.
A: Graphene fields use resolve_<field> pattern to resolve the values. Check more here
me = graphene.Field(UserType)
^^
def resolve_me(root, info):
logger.info("***** Inside resolve ****")
return info.context.user
| |
doc_5431
|
A: You'll have to migrate from TFS 2008 to TFS 2018, at which point you can delete whatever projects you want from TFS 2018. That's going to be the easiest way to do it. Besides there being no really solid work item migration tools, everything has changed significantly since TFS 2008, including things like APIs, work item layouts, fields, features, etc. You're looking at a miserable process to get data from 2008 to 2018 without signficant effort.
The TFS 2008 -> TFS 2018 upgrade process is going to be a bit fiddly, because you can't go directly from 2008 -> 2018, you'll have to go from 2008 to 2012, then 2012 to 2018. However, it's totally supported and is relatively painless, outside of having to do it in multiple steps.
A: If you want to maintain all version and check-in history. The only way is upgrading TFS server 2008 with database.
Direct upgrade to Team Foundation Server 2018 Update 2 is supported from TFS 2012 and newer. Since your TFS deployment is on TFS 2008, you will need to perform some interim steps before upgrading to TFS 2018 Update 2. Please see the chart below for more information.
If you want to change the hardware which is a restoration-based move, and you should never combine the two move types. First complete the hardware move, and then change the environment: https://learn.microsoft.com/en-us/vsts/tfs-server/admin/move-across-domains?view=tfs-2015v
Would it be best to do the upgrade in-place before moving hardware/domain?
You could do in place upgrade, or move to new hardware. If you're upgrading in place, consider doing a dry run of your upgrade in a pre-production environment, and make sure the system environment is meet.
Are there any particular pitfalls I should be wary of?
Before upgrade, you can read this article first, and be sure you have full backup of your database.
| |
doc_5432
| ||
doc_5433
|
For example if the user ID# is '50624' is it possible to convert it to 7 characters text value, something like 'DEGXCVG'?
If I use MD5 for this function I get 16-byte hash value.
The result value should not be longer than 7 or 8 characters.
Edit:
I want that each user has a different text code obtained from the id number.
A: Try changing the integer into a Hexadecimal value using dechex
Anyway if u able to explain your scenario more clear, we may able to provide best solution
A: What are you trying to accomplish with this?
First of all MD5 is not "encryption" it is a one-way hash function. It cannot be reversed. If that is OK for you, why not simply hash your IDs and then take 7-8 characters from the hash? You could MD5 your ID and then take the first 8 characters of the resulting MD5.
A: what you are looking for is called base transformation ... your ID is a base 10 number with the numbers from 0 to 9 represent the digits of that base.
other common bases would be 2 (binary), 16(hexadecimal), or 64(often called base 64 encoding) but you could also take some other base if you like.
i've written a somewhat general base transform code in c# (uint to whatever base string and vice versa) ... shouldn't be that hard to port it to php:
static void Main(string[] args)
{
foreach (var item in UintToOtherBase(0xDEADBEEF, "01").Reverse())
{
Console.Write(item);
}
Console.WriteLine();
Console.WriteLine(OtherBaseToInt(UintToOtherBase(0xDEADBEEF, "01"), "01").ToString("X"));
Console.WriteLine(UintToOtherBase(0xDEADBEEF, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"));
}
public static string UintToOtherBase(uint input, string newBaseDigits)
{
char[] uniqueDigits = newBaseDigits.ToCharArray().Distinct().ToArray();
uint newBase = (uint)uniqueDigits.Length;
if (newBase < 2)
{
throw new ArgumentException("otherBaseDigits has to contain at least 2 unique chars");
}
else
{
StringBuilder sb = new StringBuilder();
while (input != 0)
{
uint digit = input % newBase;
sb.Append(uniqueDigits[digit]);
input /= newBase;
}
return sb.ToString();
}
}
public static uint OtherBaseToInt(string input, string otherBaseDigits)
{
string uniqueDigits = new String(otherBaseDigits.ToCharArray().Distinct().ToArray());
int otherBase = uniqueDigits.Length;
if (otherBase < 2)
{
throw new ArgumentException("otherBaseDigits has to contain at least 2 unique chars");
}
else if (input.ToCharArray().Any(x => !uniqueDigits.Contains(x)))
{
throw new ArgumentException("an input char was not found in otherBaseDigits");
}
else
{
uint result = 0;
int pow = 0;
foreach (var c in input)
{
result += (uint)uniqueDigits.IndexOf(c) * (uint)Math.Pow(otherBase, pow++);
}
return result;
}
}
//edit:
but just to point it out, this is an encoding ... no encryption
A: If a hash function such as MD5 can be used instead of encryption, you could try crc32() instead, which produces shorter (but with much higher chances of collisions) strings.
If you just care about encoding, you could do something simpler:
function encode($id) {
$id_str = (string) $id;
$offset = rand(0, 9);
$encoded = chr(79 + $offset);
for ($i = 0, $len = strlen($id_str); $i < $len; ++$i) {
$encoded .= chr(65 + $id_str[$i] + $offset);
}
return $encoded;
}
function decode($encoded) {
$offset = ord($encoded[0]) - 79;
$encoded = substr($encoded, 1);
for ($i = 0, $len = strlen($encoded); $i < $len; ++$i) {
$encoded[$i] = ord($encoded[$i]) - $offset - 65;
}
return (int) $encoded;
}
Example:
var_dump(encode(50624)); // string(6) "TKFLHJ"
Encryption version:
define('CRYPTO_KEY', 'Secret key');
function encrypt($id) {
return base64_encode(mcrypt_encrypt(MCRYPT_BLOWFISH, CRYPTO_KEY, (string) $id, MCRYPT_MODE_ECB));
}
function decrypt($encrypted) {
return (int) base64_decode(mcrypt_decrypt(MCRYPT_BLOWFISH, CRYPTO_KEY, $encrypted, MCRYPT_MODE_ECB));
}
A: If obscuring is good enough, convert the number to base62 after permuting its bits.
A: I think you can design your own encryption method or take part of md5 hash value.
Btw, the way to encrypt an integer has been discussed in the following post.
Way to encrypt a single int
| |
doc_5434
|
ggplot(aes(x = Sepal.Length, y = Petal.Length, color = Species), data =
trainData)+
geom_point()+
geom_smooth()
AND
ggplot(aes(x = Sepal.Length, y = Petal.Length), data = trainData)+
geom_point(aes(color = Species))+
geom_smooth()
The graph I am getting:
Output for the first code
Output for the second code
A: It's probably because the aes() call in the second case colours the points but this is not carried forward to the colour for the smooth line. Changing the second example to add an explicit call to aes(color...) for the geom_smooth() call results in the same result as the first example.
ggplot(aes(x = Sepal.Length, y = Petal.Length), data = trainData) +
geom_point(aes(color = Species)) +
geom_smooth(aes(color=Species))
| |
doc_5435
|
When I destroy the Transform stream sometimes I get an error because the destroy function unpipes the Transfrom stream itself but do this async and if it's not quick enough the Readable stream pushes some new data during the disposing, that causing the following error:
Uncaught Error: write after end
Do I do something wrong, you write your code like unpipe before destroying, or how should I make sure the readable does not push data after I called the destroying and do not get any error?
A: Using node v8.11.1 I can replicate this problem with Readable when attempting to destroy() a stream from inside the on("data", (chunk) => void) callback. The errors disappeared when I deferred the call.
// Calling stream.destroy() directly causes "Error: write after end".
Promise.resolve()
.then(() => stream.destroy())
.catch(console.log)
A: A similar error due to closing the stream abruptly in the on handler is
Error [ERR_STREAM_DESTROYED]: Cannot call write after a stream was destroyed
The solution for both errors is to defer the destroy() call to the next tick:
process.nextTick(() => stream.destroy());
| |
doc_5436
|
What's unique is they claim that they are able to track what actions the end user took, how long the end user read it for, and if they deleted or forwarded the email. They claim they do this without JavaScript, and purely using embedded images. They claim that the method works across most major email clients.
What could they be doing to track this? Obviously, if they're doing it with third party applications that they don't control, whatever they are doing should be replicable.
I'm thinking that they realized that when an email client forwards or deletes an email, it 'opens' the email in a different way then normal, creating a unique user string on the server log of some kind? I'm grasping at strings, though.
http://litmusapp.com/email-analytics
Details here http://litmusapp.com/help/analytics/how-it-works
EDIT: It also looks like they track Prints. Maybe they do this by tracking calls to the 'print' css?
A: One way I can think of doing that is having an embedded image that loads from a script on a server. The script would not return anything or maybe send data really slowly to keep the connection open. Once the email is deleted the connection would be closed. This way they could know how long the email was open. Maybe they just assume if it's open for less than 10 seconds it was deleted?
Another way is tracking the referrer - this would give a lot of data on what a webmail client is doing, but I doubt it would be useful with a desktop client.
A: It's all done with good ol' image bugs. Breaking down how they find out...
*
*Which client was used: Check the user-agent
*Whether an email was forwarded: Done by attaching image bugs to divs that are loaded only when the message is forwarded.
*Whether an email was printed: bug attached to print stylesheet
*How long it takes to read an email: A connection that's kept open, as pointed out by Forrest (this is also how Facebook tracks(ed?) whether or not you are online on chat).
*Whether an email was deleted: Check If a message was read for a short period of time or not opened. In fact, they group "glanced" and "deleted" together.
Of course none of this will work if email clients disable images in emails.
EDIT: Here's another question on this:
The OP actually has their tracking code, and this answer here explains how it works.
A: They know when the email is opened (it's when the image is called from their http server).
They also know what the user do and when since they can easily replace all links with their own tracking URLs redirecting to the original link.
There is nothing exceptional here. They are just a bit more advanced than their compatitors. There is no magic.
I have only one doubt: how they track delete. Technically, there is no way to know what happened to the message after it was read.
I suspect that a "deleted" mail is a mail that is never opened.
| |
doc_5437
|
boys_fashion
girls_fashion
gents_fashion
ladies_fashion
girls_accessories
gents_accessories
ladies_accessories
based on some fields I need to use different collection. So for that I thought to create a collection which will map to a specific collection. Below is the collection I have created for that.
{
"type" : "Fashion",
"gender" : "Gents",
"kids" : "true",
"collection" : "boys_fashion"
}
{
"type" : "Accessories",
"gender" : "Ladies",
"kids" : "false",
"collection" : "ladies_accessories"
}
{
"type" : "Fashion",
"gender" : "Gents",
"kids" : "false",
"collection" : "gents_fashion"
}
{
"type" : "Accessories",
"gender" : "Ladies",
"kids" : "true",
"collection" : "girls_accessories"
}
{
"type" : "Accessories",
"gender" : "Gents",
"kids" : "true",
"collection" : "gents_accessories"
}
{
"type" : "Accessories",
"gender" : "Gents",
"kids" : "false",
"collection" : "gents_accessories"
}
Is this is the right way to do this? or please suggest me some other ways
If I stored like below(the above option is similar to RDBMS. Since its mongo I guess I used this way). How can I write a query for fetching the collection?
{
"fashion" : {
"gents" : {
"true" : "boys_fashion",
"false" : "gents_fashion"
}
},
"accessories" : {
"ladies" : {
"true" : "girls_accessories",
"false" : "ladies_accessories"
}
}
}
A: *
*Assumptions:
*
*There were one collection before and you split them into multiple collections as they are getting large and you want to solve it without sharing.
*I would not even create a collection for the following data. This data is static reference data and will act as a router. On start up, application loads this data and creates a router.
{
"type" : "Fashion",
"gender" : "Gents",
"kids" : "true",
"collection" : "boys_fashion"
}
{
"type" : "Accessories",
"gender" : "Ladies",
"kids" : "false",
"collection" : "ladies_accessories"
}
...
*
*What do I mean by creating a kind of router by that static configuration file? Lets say you receive a query fashionable items for baby girls. This router will tell you, hey you need to search girls_accessories collection. And you send the query to girls_accessories collection and return the result.
*Lets take another example, you receive a query for fashionable items for female. This router will tell you hey you need to search, ladies_accessories and girls_accessories. You send the query to both collections and combine the result and send it back.
Conclusion
If my assumptions are correct, you don't need a collection to store the reference data. What you have done is manual sharding by splitting the data across different collections, the reference data will act as router to tell you where to search and combine
Update based on comments
*
*Query does not involve multiple collections
*Administrator can add new collection and application should query it without modifying code.
Solution 1
*
*You create a collection for the reference data too
*Downside to this is that every query involves two calls to database. First to fetch the static data and second to the data collection
Solution 2
*
*You create a collection for the reference data too
*You also build a Dao on top of that which uses @Cacheable for the method that return this data.
*You also add a method in Dao to clear the cache with @CacheEvict and have a rest endpoint like /refresh-static-data that will call this method`
*Downside to this method is that whenever administrator add new collection, you need to call the endpoint.
Solution 3
*
*Same as solution 2 but instead of having an endpoint to clear the cache, you combine it with scheduler
@Scheduled(fixedRate = ONE_DAY)
@CacheEvict(value = { CACHE_NAME })
public void clearCache() {
}
*
*Downside to this solution is that you have to come up with a period for fixedRate which is acceptable to your business
A: I added the collection like below.
/* 1 */
{
"type" : "fashion",
"category" : [
{
"value" : "gents",
"true" : "boys_fashion",
"false" : "gents_fasion"
}
]
}
/* 2 */
{
"type" : "accessories",
"category" : [
{
"value" : "ladies",
"true" : "girls_accessories",
"false" : "ladies_accessories"
}
]
}
and will fetch the data using the below query
findOne({"type":type,"category.value":cvalue},{"_id": 0, "category": {"$elemMatch": {"value": cvalue}}})
A: Try to make subdocuments in MongoDB, instead of nested objects
https://mongoosejs.com/docs/subdocs.html
| |
doc_5438
|
My toolchain-raspberrypi.cmake looks like this:
SET(CMAKE_SYSTEM_NAME Linux)
SET(CMAKE_SYSTEM_VERSION 1)
# Specify the cross compiler
SET(CMAKE_C_COMPILER $ENV{HOME}/rpi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/bin/arm-linux-gnueabihf-gcc)
#SET(CMAKE_C_FLAGS "-L$ENV{HOME}/rpi/rootfs/usr/lib/arm-linux-gnueabihf -I$ENV{HOME}$ENV{HOME}/rpi/rootfs/usr/include")
# Where is the target environment
SET(CMAKE_FIND_ROOT_PATH $ENV{HOME}/rpi/rootfs)
SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} --sysroot=${CMAKE_FIND_ROOT_PATH}")
SET(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} --sysroot=${CMAKE_FIND_ROOT_PATH}")
SET(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} --sysroot=${CMAKE_FIND_ROOT_PATH}")
# Search for programs only in the build host directories
SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
# Search for libraries and headers only in the target directories
SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
CMake generates the Makefiles and seems to find all the required libraries:
$ cmake -D CMAKE_BUILD_TYPE=Debug -D CMAKE_TOOLCHAIN_FILE=/home/unknown/rpi/toolchain-raspberrypi.cmake ..
-- The C compiler identification is GNU 4.8.3
-- Check for working C compiler: /home/unknown/rpi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/bin/arm-linux-gnueabihf-gcc
-- Check for working C compiler: /home/unknown/rpi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/bin/arm-linux-gnueabihf-gcc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Looking for include file stdlib.h
-- Looking for include file stdlib.h - found
-- Looking for sys/types.h
-- Looking for sys/types.h - found
-- Looking for stdint.h
-- Looking for stdint.h - found
-- Looking for stddef.h
-- Looking for stddef.h - found
-- Check size of intmax_t
-- Check size of intmax_t - done
-- Check size of uintmax_t
-- Check size of uintmax_t - done
-- Check size of pid_t
-- Check size of pid_t - done
-- Found Lua51: /home/unknown/rpi/rootfs/usr/lib/arm-linux-gnueabihf/liblua5.1.so;/home/unknown/rpi/rootfs/usr/lib/arm-linux-gnueabihf/libm.so (found version "5.1.5")
-- Luaudio_INCLUDE_DIRS: /home/unknown/rpi/rootfs/usr/include/lua5.1
-- LUA_LIBRARIES: /home/unknown/rpi/rootfs/usr/lib/arm-linux-gnueabihf/liblua5.1.so;/home/unknown/rpi/rootfs/usr/lib/arm-linux-gnueabihf/libm.so
-- Found libusb-1.0:
-- - Includes: /home/unknown/rpi/rootfs/usr/include/libusb-1.0
-- - Libraries: /home/unknown/rpi/rootfs/usr/lib/libusb-1.0.a
-- Found PkgConfig: /usr/bin/pkg-config (found version "0.26")
-- checking for one of the modules 'check'
-- Looking for include file pthread.h
-- Looking for include file pthread.h - found
-- Looking for pthread_create
-- Looking for pthread_create - not found
-- Looking for pthread_create in pthreads
-- Looking for pthread_create in pthreads - not found
-- Looking for pthread_create in pthread
-- Looking for pthread_create in pthread - found
-- Found Threads: TRUE
-- Found libusb-1.0:
-- - Includes: /home/unknown/rpi/rootfs/usr/include/libusb-1.0
-- - Libraries: /home/unknown/rpi/rootfs/usr/lib/libusb-1.0.a
-- Configuring done
-- Generating done
-- Build files have been written to: /home/unknown/projects/ha/workspace/ha/build-rpi
But when I run make I get an error trying to locate a library header:
$ make
Scanning dependencies of target ha
[ 2%] Building C object src/CMakeFiles/ha.dir/log.c.o
[ 5%] Building C object src/CMakeFiles/ha.dir/cm.c.o
/home/unknown/projects/ha/workspace/ha/src/cm.c:13:31: fatal error: libusb-1.0/libusb.h: No such file or directory
#include <libusb-1.0/libusb.h>
^
compilation terminated.
make[2]: *** [src/CMakeFiles/ha.dir/cm.c.o] Error 1
make[1]: *** [src/CMakeFiles/ha.dir/all] Error 2
make: *** [all] Error 2
I'm totally stuck here. The files are there:
$ ls ~/rpi/rootfs/usr/include/libusb-1.0/ -l
total 72
-rw-r--r-- 1 unknown unknown 70156 jun 22 2014 libusb.h
$ ls ~/rpi/rootfs/usr/lib/libusb-1.0.a -l
-rw-r--r-- 1 unknown unknown 109920 jun 22 2014 /home/unknown/rpi/rootfs/usr/lib/libusb-1.0.a
And when running CMake with the --trace flag, it seems to find libusb related files:
/home/unknown/projectes/ha/workspace/ha/src/CMakeLists.txt(8): find_package(libusb-1.0 REQUIRED )
/usr/share/cmake-2.8/Modules/Findlibusb-1.0.cmake(46): if(LIBUSB_1_LIBRARIES AND LIBUSB_1_INCLUDE_DIRS )
/usr/share/cmake-2.8/Modules/Findlibusb-1.0.cmake(49): else(LIBUSB_1_LIBRARIES AND LIBUSB_1_INCLUDE_DIRS )
/usr/share/cmake-2.8/Modules/Findlibusb-1.0.cmake(50): find_path(LIBUSB_1_INCLUDE_DIR NAMES libusb.h PATHS /usr/include /usr/local/include /opt/local/include /sw/include PATH_SUFFIXES libusb-1.0 )
/usr/share/cmake-2.8/Modules/Findlibusb-1.0.cmake(62): find_library(LIBUSB_1_LIBRARY NAMES usb-1.0 usb PATHS /usr/lib /usr/local/lib /opt/local/lib /sw/lib )
/usr/share/cmake-2.8/Modules/Findlibusb-1.0.cmake(72): set(LIBUSB_1_INCLUDE_DIRS ${LIBUSB_1_INCLUDE_DIR} )
/usr/share/cmake-2.8/Modules/Findlibusb-1.0.cmake(75): set(LIBUSB_1_LIBRARIES ${LIBUSB_1_LIBRARY} )
/usr/share/cmake-2.8/Modules/Findlibusb-1.0.cmake(79): if(LIBUSB_1_INCLUDE_DIRS AND LIBUSB_1_LIBRARIES )
/usr/share/cmake-2.8/Modules/Findlibusb-1.0.cmake(80): set(LIBUSB_1_FOUND TRUE )
/usr/share/cmake-2.8/Modules/Findlibusb-1.0.cmake(83): if(LIBUSB_1_FOUND )
/usr/share/cmake-2.8/Modules/Findlibusb-1.0.cmake(84): if(NOT libusb_1_FIND_QUIETLY )
/usr/share/cmake-2.8/Modules/Findlibusb-1.0.cmake(85): message(STATUS Found libusb-1.0: )
-- Found libusb-1.0:
/usr/share/cmake-2.8/Modules/Findlibusb-1.0.cmake(86): message(STATUS - Includes: ${LIBUSB_1_INCLUDE_DIRS} )
-- - Includes: /home/unknown/rpi/rootfs/usr/include/libusb-1.0
/usr/share/cmake-2.8/Modules/Findlibusb-1.0.cmake(87): message(STATUS - Libraries: ${LIBUSB_1_LIBRARIES} )
-- - Libraries: /home/unknown/rpi/rootfs/usr/lib/libusb-1.0.a
/usr/share/cmake-2.8/Modules/Findlibusb-1.0.cmake(96): mark_as_advanced(LIBUSB_1_INCLUDE_DIRS LIBUSB_1_LIBRARIES )
/home/unknown/projectes/ha/workspace/ha/src/CMakeLists.txt(10): INCLUDE_DIRECTORIES(${LIBUSB_1_INCLUDE_DIRS} )
I'm a newcomer to CMake and so far I've not been able to find any helpful entry in this site nor anywhere else regarding this same problem.
Any clue?
A: Problem
From the cmake --trace output one can see, that Findlibusb-1.0.cmake script, which search libusb-1.0 library, detects include directory for the library's headers via
find_path(LIBUSB_1_INCLUDE_DIR NAMES libusb.h ...)
This means, that the script expects libusb.h header to be included as
#include <libusb.h>
(The same conclusion can be deduced from the output of cmake call: line
- Includes: /home/unknown/rpi/rootfs/usr/include/libusb-1.0
already includes libusb-1.0 suffix for the include path.)
But error message shows, that cm.c file actually includes the header as
#include <libusb-1.0/libusb.h>
This means, that Findlibusb-1.0.cmake script you use (which is shipped with CMake itself) is not compatible with actual usage of the library in you project.
Ideal solution
You need to ship your project with compatible Findlibusb-1.0.cmake script, which uses
find_path(LIBUSB_1_INCLUDE_DIR NAMES libusb-1.0/libusb.h ...)
for detect include path. E.g., the one from PCL library. (At the beginning of your project's CMakeLists.txt you need to adjust CMAKE_MODULE_PATH variable for find the script.)
As fast workaround
You may replace path /home/unknown/rpi/rootfs/usr/include/libusb-1.0 with /home/unknown/rpi/rootfs/usr/include in the CMake cache. (After modification of the cache you need to rerun cmake).
Because cached value is likely used in include_directories() call from your project, proper directory will be used instead.
I'm wondering why find_package works differently when cross compiling.
More likely that find_package works identical on PC and when cross-compiling, but on PC you get path /usr/include being included by other means (e.g., it is included by default).
| |
doc_5439
|
Now what happens when I've got it just the way I like it to look? How can I see everything I did? My changes are scattered all throughout the DOM with rule modifications throughout. How can I see only what was changed so I can understand the changes and migrate them back to my stylesheets on disk?
| |
doc_5440
|
for i in *.txt
do
ops.....
done
There are thousands of files and they are always processed in alphanumerical order because of '*.txt' expansion.
Is there a simple way to random the order and still insure that I process all of the files only once?
A: You could pipe your filenames through the sort command:
ls | sort --random-sort | xargs ....
A: Assuming the filenames do not have spaces, just substitute the output of List::Util::shuffle.
for i in `perl -MList::Util=shuffle -e'$,=$";print shuffle<*.txt>'`; do
....
done
If filenames do have spaces but don't have embedded newlines or backslashes, read a line at a time.
perl -MList::Util=shuffle -le'$,=$\;print shuffle<*.txt>' | while read i; do
....
done
To be completely safe in Bash, use NUL-terminated strings.
perl -MList::Util=shuffle -0 -le'$,=$\;print shuffle<*.txt>' |
while read -r -d '' i; do
....
done
Not very efficient, but it is possible to do this in pure Bash if desired. sort -R does something like this, internally.
declare -a a # create an integer-indexed associative array
for i in *.txt; do
j=$RANDOM # find an unused slot
while [[ -n ${a[$j]} ]]; do
j=$RANDOM
done
a[$j]=$i # fill that slot
done
for i in "${a[@]}"; do # iterate in index order (which is random)
....
done
Or use a traditional Fisher-Yates shuffle.
a=(*.txt)
for ((i=${#a[*]}; i>1; i--)); do
j=$[RANDOM%i]
tmp=${a[$j]}
a[$j]=${a[$[i-1]]}
a[$[i-1]]=$tmp
done
for i in "${a[@]}"; do
....
done
A: Here's an answer that relies on very basic functions within awk so it should be portable between unices.
ls -1 | awk '{print rand()*100, $0}' | sort -n | awk '{print $2}'
EDIT:
ephemient makes a good point that the above is not space-safe. Here's a version that is:
ls -1 | awk '{print rand()*100, $0}' | sort -n | sed 's/[0-9\.]* //'
A: Here's a solution with standard unix commands:
for i in $(ls); do echo $RANDOM-$i; done | sort | cut -d- -f 2-
A: If you have GNU coreutils, you can use shuf:
while read -d '' f
do
# some stuff with $f
done < <(shuf -ze *)
This will work with files with spaces or newlines in their names.
Off-topic Edit:
To illustrate SiegeX's point in the comment:
$ a=42; echo "Don't Panic" | while read line; do echo $line; echo $a; a=0; echo $a; done; echo $a
Don't Panic
42
0
42
$ a=42; while read line; do echo $line; echo $a; a=0; echo $a; done < <(echo "Don't Panic"); echo $a
Don't Panic
42
0
0
The pipe causes the while to be executed in a subshell and so changes to variables in the child don't flow back to the parent.
A: Here's a Python solution, if its available on your system
import glob
import random
files = glob.glob("*.txt")
if files:
for file in random.shuffle(files):
print file
| |
doc_5441
|
<textarea name="edit><?php echo news; ?></textarea>
This is my current code:
function divClicked() {
var divHtml = $(this).html();
var editableText = $("<textarea name="edit" />");
editableText.val(divHtml);
$(this).replaceWith(editableText);
editableText.focus();
// setup the blur event for this new textarea
editableText.blur(editableTextBlurred);
}
$(document).ready(function() {
$("#editable").click(divClicked);
});
<form method="post" action="newsedit.php">
<div id="editable"><?php echo $news; ?></div>
<input type="submit" value="Edit News" />
</form>
Now, this does work in the sense that when I click on the text it does convert into a textarea. The problem is that it doesn't give it the "edit" name so when I hit the sumbit button, it is as if I submitted nothing and it deletes all the data out of the table because
<textarea name="edit"></textarea>
is technically empty. Are there any ways to make it so when I click on the text it will convert the code to textarea with that specific name so there is actual data when I hit submit?
A: Change the form to:
<form method="post" action="newsedit.php">
<div id="<?php echo $newsID;?>"><?php echo nl2br($news); ?></div>
<input type="submit" value="Edit News" />
</form>
Where $newsID is returned along with the $news text.
The nl2br($news) will just make sure the line breaks are honored.
A: var editableText = $("<textarea name='edit' />");
http://jsfiddle.net/H5aM4/ inspect the textarea
A: TRY This
$("#editable").click( function(){
$(this).replaceWith(function() {
return $("<textarea name='edit'>").text(this.innerHTML);
});
});
Here is the working example
| |
doc_5442
|
So in each cell there will be 10 digits, then an enter, then the 10 next digits, and so on.
=SPLIT(REGEXREPLACE(REGEXREPLACE(A1&"","(?s)(.{10})","$1"&TEKEN(127)),"'","''"),TEKEN(127))
| |
doc_5443
|
In my template file I am calling:
{{ render(controller('FOSUserBundle:Security:login')) }}. This is correctly rendering the login form within the relevant pages.
However I have two problem I am unable to figure out how to overcome...
*
*If the user enters invalid credentials, how can I return the user to the page they were on rather than the /login route?
*How can I intercept the error message (Invalid credentials etc.)? I would want to make it a flash message and then display it elsewhere in the master template.
Happy to provide further information if required.
t2t
A: You can create an eventListener on 'onAuthenticationFailure'.
You will get the request and referer.
A: In your case; you need to create custom Login page.
To do that;
1- Create your own SecurityController.php. Then copy 'loginAction' and 'renderLogin' method from the original SecurityController friendsofsymfony/user-bundle/SecurityController.php paste into it and add /login path to loginAction.
2- Create your own login.html.twig. Then copy content of login_content.html.twig from friendsofsymfony/user-bundle/Resources/Security/login_content.html.twig paste into your own.
3- Change return of renderLogin to your own login.html.twig
After these steps you can modify whatever you want. If you want to different route after wrong credentials then check the $error variable and make redirection.
| |
doc_5444
|
Expected a value of type 'Map<String, dynamic>', but got one of type 'Null'
Flutter version 3.0.4
Code used to convert the response body:
getRequestedQuoteList() async {
var path = 'enquiryForQuotesList/';
var responseData = await DioHandler.dioPost(path);
if (responseData != null) {
if (responseData['status'] == "success") {
log(responseData.toString());
await Future.delayed(Duration(seconds: 3));
quoteModel = QuoteModel.fromJson(responseData);
isLoading = false;
update();
}
} else {
log("Null");
}
}
QuoteModel class:
import 'package:freezed_annotation/freezed_annotation.dart';
import 'dart:convert';
part 'quote_model.freezed.dart';
part 'quote_model.g.dart';
QuoteModel quoteModelFromJson(String str) =>
QuoteModel.fromJson(json.decode(str));
String quoteModelToJson(QuoteModel data) => json.encode(data.toJson());
@freezed
class QuoteModel with _$QuoteModel {
const factory QuoteModel({
required String status,
required List<Result> result,
}) = _QuoteModel;
factory QuoteModel.fromJson(Map<String, dynamic> json) =>
_$QuoteModelFromJson(json);
}
@freezed
class Result with _$Result {
const factory Result({
required int id,
required FromBuyer fromBuyer,
String? specification,
required ForBatch forBatch,
required bool responded,
required double quantity,
dynamic respondedBy,
}) = _Result;
factory Result.fromJson(Map<String, dynamic> json) => _$ResultFromJson(json);
}
@freezed
class ForBatch with _$ForBatch {
const factory ForBatch({
required int id,
required String name,
required String state,
required String district,
required String village,
required int quantity,
required DateTime dateOfHarvest,
required double latitude,
required double longitude,
required DateTime timestamp,
dynamic farmer,
required int raithaSahayak,
required Map<String, double> result,
}) = _ForBatch;
factory ForBatch.fromJson(Map<String, dynamic> json) =>
_$ForBatchFromJson(json);
}
@freezed
class FromBuyer with _$FromBuyer {
const factory FromBuyer({
required int id,
required String username,
required String mobile,
String? address,
}) = _FromBuyer;
factory FromBuyer.fromJson(Map<String, dynamic> json) =>
_$FromBuyerFromJson(json);
}
Response body:
{
"status": "success",
"result": [
{
"id": 1,
"fromBuyer": {
"id": 3,
"username": "srk",
"mobile": "1",
"address": null
},
"specification": "test",
"forBatch": {
"id": 34,
"name": "IndirCDsreeh35108",
"state": "Karnataka",
"district": "Bangalore Urban",
"village": "Indiranagar",
"quantity": 3000,
"dateOfHarvest": "2022-02-08",
"latitude": 77.6415813,
"longitude": 77.6415813,
"timestamp": "2022-02-18T08:08:03.538064Z",
"farmer": 6,
"raithaSahayak": 3,
"result": {
"total": 40,
"good": 20,
"infested": 19,
"discolored": 0,
"fungal": 0,
"broken": 0,
"mixed": 0,
"foreignParticles": 0,
"goodPercent": 50.0,
"infestedPercent": 47.5,
"discoloredPercent": 0.0,
"fungalPercent": 0.0,
"brokenPercent": 0.0,
"mixedPercent": 0.0,
"foreignParticlesPercent": 0.0,
"batch": 34
}
},
"responded": false,
"quantity": 100.0,
"respondedBy": null
},
{
"id": 2,
"fromBuyer": {
"id": 3,
"username": "srk",
"mobile": "1",
"address": null
},
"specification": "test",
"forBatch": {
"id": 27,
"name": "IndirCDsreeh68704",
"state": "Karnataka",
"district": "Bangalore Urban",
"village": "Indiranagartest",
"quantity": 1500,
"dateOfHarvest": "2022-02-09",
"latitude": 77.6415988,
"longitude": 77.6415988,
"timestamp": "2022-02-09T12:20:30.419288Z",
"farmer": null,
"raithaSahayak": 3,
"result": {
"total": 475,
"good": 350,
"infested": 37,
"discolored": 16,
"fungal": 7,
"broken": 41,
"mixed": 19,
"foreignParticles": 21,
"goodPercent": 73.6842105263158,
"infestedPercent": 7.7894736842105265,
"discoloredPercent": 0.0,
"fungalPercent": 1.4736842105263157,
"brokenPercent": 8.631578947368421,
"mixedPercent": 4.0,
"foreignParticlesPercent": 4.421052631578948,
"batch": 27
}
},
"responded": false,
"quantity": 200.0,
"respondedBy": null
},
{
"id": 3,
"fromBuyer": {
"id": 3,
"username": "srk",
"mobile": "1",
"address": null
},
"specification": "test",
"forBatch": {
"id": 31,
"name": "IndirCDsreeh21671",
"state": "Karnataka",
"district": "Bangalore Urban",
"village": "Indiranagar",
"quantity": 1500,
"dateOfHarvest": "2022-02-18",
"latitude": 77.6415778,
"longitude": 77.6415778,
"timestamp": "2022-02-18T07:51:56.082605Z",
"farmer": 7,
"raithaSahayak": 3,
"result": {
"total": 74,
"good": 25,
"infested": 48,
"discolored": 0,
"fungal": 0,
"broken": 0,
"mixed": 0,
"foreignParticles": 0,
"goodPercent": 33.78378378378378,
"infestedPercent": 64.86486486486487,
"discoloredPercent": 0.0,
"fungalPercent": 0.0,
"brokenPercent": 0.0,
"mixedPercent": 0.0,
"foreignParticlesPercent": 0.0,
"batch": 31
}
},
"responded": false,
"quantity": 300.0,
"respondedBy": null
},
{
"id": 4,
"fromBuyer": {
"id": 3,
"username": "srk",
"mobile": "1",
"address": null
},
"specification": "test",
"forBatch": {
"id": 45,
"name": "IndirCDsreeh23015",
"state": "Karnataka",
"district": "Bangalore Urban",
"village": "Indiranagar",
"quantity": 1000,
"dateOfHarvest": "2022-03-16",
"latitude": 77.6415324,
"longitude": 77.6415324,
"timestamp": "2022-03-24T11:59:06.908914Z",
"farmer": 11,
"raithaSahayak": 3,
"result": {
"total": 338,
"good": 297,
"infested": 41,
"discolored": 0,
"fungal": 0,
"broken": 0,
"mixed": 0,
"foreignParticles": 0,
"goodPercent": 87.8698224852071,
"infestedPercent": 12.1301775147929,
"discoloredPercent": 0.0,
"fungalPercent": 0.0,
"brokenPercent": 0.0,
"mixedPercent": 0.0,
"foreignParticlesPercent": 0.0,
"batch": 45
}
},
"responded": false,
"quantity": 640.0,
"respondedBy": null
},
{
"id": 5,
"fromBuyer": {
"id": 1,
"username": "admin",
"mobile": "2",
"address": null
},
"specification": "A Grade Channadal",
"forBatch": {
"id": 2,
"name": "ThirdBatch",
"state": "Karnataka",
"district": "Bangalore Rural",
"village": "Anneshwara",
"quantity": 1000,
"dateOfHarvest": "2022-01-02",
"latitude": 46.18,
"longitude": 73.15,
"timestamp": "2022-01-21T08:17:50.960403Z",
"farmer": null,
"raithaSahayak": 1,
"result": null
},
"responded": false,
"quantity": 500.0,
"respondedBy": null
},
{
"id": 6,
"fromBuyer": {
"id": 1,
"username": "admin",
"mobile": "2",
"address": null
},
"specification": "A Grade Channadal",
"forBatch": {
"id": 2,
"name": "ThirdBatch",
"state": "Karnataka",
"district": "Bangalore Rural",
"village": "Anneshwara",
"quantity": 1000,
"dateOfHarvest": "2022-01-02",
"latitude": 46.18,
"longitude": 73.15,
"timestamp": "2022-01-21T08:17:50.960403Z",
"farmer": null,
"raithaSahayak": 1,
"result": null
},
"responded": false,
"quantity": 500.0,
"respondedBy": null
}
]
}
Flutter doctor -v
[√] Flutter (Channel stable, 3.0.4, on Microsoft Windows [Version 10.0.19043.1586], locale en-IN)
• Flutter version 3.0.4 at C:\Users\DELL\Documents\flutter
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision 85684f9300 (7 days ago), 2022-06-30 13:22:47 -0700
• Engine revision 6ba2af10bb
• Dart version 2.17.5
• DevTools version 2.12.2
[√] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
• Android SDK at C:\Users\DELL\AppData\Local\Android\sdk
• Platform android-31, build-tools 31.0.0
• Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
• Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)
• All Android licenses accepted.
[√] Chrome - develop for the web
• Chrome at C:\Program Files\Google\Chrome\Application\chrome.exe
[X] Visual Studio - develop for Windows
X Visual Studio not installed; this is necessary for Windows development.
Download at https://visualstudio.microsoft.com/downloads/.
Please install the "Desktop development with C++" workload, including all of its default components
[√] Android Studio (version 2020.3)
• Android Studio at C:\Program Files\Android\Android Studio
• Flutter plugin can be installed from:
https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)
[√] VS Code (version 1.69.0)
• VS Code at C:\Users\DELL\AppData\Local\Programs\Microsoft VS Code
• Flutter extension version 3.44.0
[√] Connected device (4 available)
• sdk gphone x86 (mobile) • emulator-5554 • android-x86 • Android 11 (API 30) (emulator)
• Windows (desktop) • windows • windows-x64 • Microsoft Windows [Version 10.0.19043.1586]
• Chrome (web) • chrome • web-javascript • Google Chrome 103.0.5060.114
• Edge (web) • edge • web-javascript • Microsoft Edge 103.0.1264.49
[√] HTTP Host Availability
• All required HTTP hosts are available
A: You might have some things defined in your model as non-nullable that are actually null in the JSON example. For instance, ForBatch.result.
Possibly making that nullable in your model could solve the issue.
| |
doc_5445
|
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)`
but I cannot see the righthand columns, there is no scrollbar (see image). How can I get them to display?
TIA!
A: Try this
import pandas as pd
from IPython.display import display
pd.options.display.max_columns = None
display(data)
To enable scrolling :
You can try Cell -> Current Outputs -> Toggle Scrolling in the Jupyter UI to enable the scrolling for the output of one cell.
| |
doc_5446
|
I've used below code in view it will word as well but if I used in Controller I will get errors
$routes = Route::getRoutes();
dd($routes);
Errors happen when I used this method in Controller.
FatalErrorException in Handler.php line 26:
Uncaught TypeError: Argument 1 passed to App\Exceptions\Handler::report() must be an instance of Exception, instance of Error given,
called in vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php on line 73 and defined in
.../app/Exceptions/Handler.php:26
Stack trace:
#0 /vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php(73): App\Exceptions\Handler->report(Object(Error))
#1 [internal function]: Illuminate\Foundation\Bootstrap\HandleExceptions->handleException(Object(Error))
#2 {main}
thrown
This is the result if i used those methods inside of views
#routes: array:3 [▶]
#allRoutes: array:329 [▶]
#nameList: array:260 [▶]
#actionList: array:325 [▶]
A: Try adding the following line in your controller:
use Illuminate\Support\Facades\Route;
| |
doc_5447
|
*
*Internally using local state;
*Using v-model to keep track on the parent component.
I also have a child component called MenuItem. This MenuItem (one or more) is to be passed into the Menu default slot. The MenuItem has a slot of its own, for an icon.
The Menu also has a slot for the "activator", an element which toggles the menu visibility. This can be a regular slot, or a scoped slot.
If the visibility of the menu is handled through the scoped slot:
<Menu>
<template v-slot:activator="{ on }">
<button v-on="on" type="button">Click me</button>
</template>
</Menu>
Then the icon for MenuItem will render the first time the menu is visible, but subsequent changes to visibility won't render the icon. The icon slot is optional, so I am checking for it's presences using this.$slots['icon-left'], and after the first render this is undefined.
However, if I manage the visibility on the parent component using v-model, this behaviour is not present.
<Menu v-model="isMenuVisible">
<template v-slot:activator>
<button @click="isMenuVisible = !isMenuVisible" type="button">Click me</button>
</template>
</Menu>
I am using v-if for toggling the visibility of the dropdown menu. This behaviour is not present if I use v-show. This behaviour is also not present if I do not check for the existence of this.$slots['icon-left'].
I have a full demo of the issue.
Basically I am very confused as to why this is happening, and I don't even know what to Google.
| |
doc_5448
|
php composer.phar install --verbose
Warning: This development build of composer is over 30 days old. It is recommended to update it by running "composer.phar self-update" to get the latest version.
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Nothing to install or update
Generating autoload files
Fatal error: Class 'Config' not found in D:\projects\campaygn\src\fuel\core\classes\error.php on line 146
Fatal error: Class 'Config' not found in D:\projects\campaygn\src\fuel\core\bootstrap.php on line 47
Script php oil r install handling the post-install-cmd event returned with an error
[RuntimeException]
Error Output:
Exception trace:
() at phar://D:/projects/campaygn/src/composer.phar/src/Composer/EventDispatcher/EventDispatcher.php:186
Composer\EventDispatcher\EventDispatcher->doDispatch() at phar://D:/projects/campaygn/src/composer.phar/src/Composer/EventDispatcher/EventDispatcher.php:121
Composer\EventDispatcher\EventDispatcher->dispatchCommandEvent() at phar://D:/projects/campaygn/src/composer.phar/src/Composer/Installer.php:337
Composer\Installer->run() at phar://D:/projects/campaygn/src/composer.phar/src/Composer/Command/InstallCommand.php:131
Composer\Command\InstallCommand->execute() at phar://D:/projects/campaygn/src/composer.phar/vendor/symfony/console/Symfony/Component/Console/Command/Command.php:252
Symfony\Component\Console\Command\Command->run() at phar://D:/projects/campaygn/src/composer.phar/vendor/symfony/console/Symfony/Component/Console/Application.php:874
Symfony\Component\Console\Application->doRunCommand() at phar://D:/projects/campaygn/src/composer.phar/vendor/symfony/console/Symfony/Component/Console/Application.php:195
Symfony\Component\Console\Application->doRun() at phar://D:/projects/campaygn/src/composer.phar/src/Composer/Console/Application.php:146
Composer\Console\Application->doRun() at phar://D:/projects/campaygn/src/composer.phar/vendor/symfony/console/Symfony/Component/Console/Application.php:126
Symfony\Component\Console\Application->run() at phar://D:/projects/campaygn/src/composer.phar/src/Composer/Console/Application.php:83
Composer\Console\Application->run() at phar://D:/projects/campaygn/src/composer.phar/bin/composer:43
require() at D:\projects\campaygn\src\composer.phar:25
install [--prefer-source] [--prefer-dist] [--dry-run] [--dev] [--no-dev] [--no-plugins] [--no-custom-installers] [--no-autoloader] [--no-scripts] [--no-progress] [-v|vv|vvv|--verbose] [-o|--optimize-autoloader] [--ignore-platform-reqs] [packages1] ... [packagesN]
A: this error might come when you have more than 1 composer.phar file in your project folder.
Have a thorough look in your folder and update and install all composer. Specially src/fuel/app :p
A: I can't really help a lot, but here it says:
Command Line Installation
This currently only works on *nix systems (Linux, OS X, Unix, etc).
| |
doc_5449
|
I try to do it this way:
Views:
subject = get_object_or_404(Subject, slug=slug)
subject_board_ids = subject.board.values_list('id', flat=True)
related_subjects = Subject.objects.filter(board__in=subject_board_ids).exclude(id=subject.id)
Model:
class Subject(models.Model):
title = models.CharField(max_length=255, verbose_name='Tytuł')
slug = AutoSlugField(populate_from='title', unique=True)
body = HTMLField(blank=True, verbose_name='Treść')
image = models.ImageField(upload_to='subject', null=True, blank=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
board = models.ForeignKey(Board, on_delete=models.CASCADE, related_name='subjects', verbose_name='Kategoria')
votes = GenericRelation(LikeDislike, related_query_name='subjectsvotes')
featured = models.BooleanField(default=False)
Actual result is error: 'Board' object has no attribute 'values_list'.
I try to create max 6 related posts.
A: Of course you have error, because your Subject link on Board with using FK. And you expression subject.board give you 'Board' object not 'Board' Queryset. To get related subject just use:
subject = get_object_or_404(Subject, slug=slug)
related_subjects = Subject.objects.filter(board=subject.board).exclude(id=subject.id)
| |
doc_5450
|
I've searched in the existing questions but could not make this work.
I have this function :
SpreadsheetApp.getActiveSheet().getRange(5,1).activate(); that works fine.
But instead of (5,1) I would like to have a dynamic value for the row number.
I would like to return the row number of a specific text that I chose in a list in A1.
Here is what I do :
function GoTo () {
var sheet = SpreadsheetApp.getActiveSheet();
var c = "EQUIV($A$1,A2:A100,0)+1";
{ SpreadsheetApp.getActiveSheet().getRange(c,1).activate(); }
}
If I put = EQUIV($A$1,A2:A100,0)+1 in a cell, i do get the right number I'm looking for.
Thanks a lot !
Could you help me ?
A: If I understand what you want the following function looks in column A starting at A2 and searches for what you entered in A1. If found, it activates the cell of the found value. It also returns the row number of the found row in cell B1.
function findText() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var find = sheet.getRange("A1").getValue()// cell of value to find in column A
var values = sheet.getRange(2, 1, sheet.getLastRow()-1).getValues();
for (var i = 0; i < values.length; i++) {
var row = "";
for (var j = 0; j < values[i].length; j++) {
if (values[i][j] == find) {
row = i+2;
sheet.getRange(1, 2).setValue(row); //row number found to C2
var range=sheet.getRange("A"+row)
range.activate() //activate cell of found value
}
}
}}
You could run this with an onEdit trigger.
| |
doc_5451
|
When I (locally, from the server that will host the endpoint) load the model in the Python script and use it for inference everything is working. Because I have the same conda env which has been used on the training server.
When I however lunch fast API server from the same server and same conda env I get the attribute error:
File "/Users/hrobar/PYTHON/anaconda3/envs/DOPRAVA/lib/python3.8/site-packages/joblib/numpy_pickle.py", line 587, in load
obj = _unpickle(fobj, filename, mmap_mode)
File "/Users/hrobar/PYTHON/anaconda3/envs/DOPRAVA/lib/python3.8/site-packages/joblib/numpy_pickle.py", line 506, in _unpickle
obj = unpickler.load()
File "/Users/hrobar/PYTHON/anaconda3/envs/DOPRAVA/lib/python3.8/pickle.py", line 1212, in load
dispatch[key[0]](self)
File "/Users/hrobar/PYTHON/anaconda3/envs/DOPRAVA/lib/python3.8/pickle.py", line 1537, in load_stack_global
self.append(self.find_class(module, name))
File "/Users/hrobar/PYTHON/anaconda3/envs/DOPRAVA/lib/python3.8/pickle.py", line 1581, in find_class
return _getattribute(sys.modules[module], name)[0]
File "/Users/hrobar/PYTHON/anaconda3/envs/DOPRAVA/lib/python3.8/pickle.py", line 331, in _getattribute
raise AttributeError("Can't get attribute {!r} on {!r}"
AttributeError: Can't get attribute 'FormulaicTransformer' on <module '__mp_main__' from '/Users/hrobar/PYTHON/anaconda3/envs/DOPRAVA/bin/uvicorn'>
I see the problem in the FormulaicTransformer which uses formulaic package under the hood. (I made sure that same version of formulaic is used during training and inference!)
I am also importing this class before loading the binary file.
When I run the script in Python the loading of the model works without any problem!
(DOPRAVA) czpcggspri52b5f :: scripts/MODEL1/main ‹main*› » python main_inference.py
/Users/hrobar/PYTHON/anaconda3/envs/DOPRAVA/lib/python3.8/site-packages/sklearn/base.py:329: UserWarning: Trying to unpickle estimator Pipeline from version 1.0.1 when using version 1.1.1. This might lead to breaking code or invalid results. Use at your own risk. For more info please refer to:
https://scikit-learn.org/stable/model_persistence.html#security-maintainability-limitations
warnings.warn(
When running using fastapi:
(DOPRAVA) czpcggspri52b5f :: scripts/MODEL1/main ‹main*› » uvicorn main_inference:app --reload --port 8882
INFO: Will watch for changes in these directories: ['/Users/hrobar/PYTHON/DOPRAVA/DOPRAVA/scripts/MODEL1/main']
INFO: Uvicorn running on http://127.0.0.1:8882 (Press CTRL+C to quit)
INFO: Started reloader process [68843] using statreload
Process SpawnProcess-1:
Traceback (most recent call last):
File "/Users/hrobar/PYTHON/anaconda3/envs/DOPRAVA/lib/python3.8/multiprocessing/process.py", line 315, in _bootstrap
self.run()
File "/Users/hrobar/PYTHON/anaconda3/envs/DOPRAVA/lib/python3.8/multiprocessing/process.py", line 108, in run
self._target(*self._args, **self._kwargs)
File "/Users/hrobar/PYTHON/anaconda3/envs/DOPRAVA/lib/python3.8/site-packages/uvicorn/subprocess.py", line 76, in subprocess_started
target(sockets=sockets)
File "/Users/hrobar/PYTHON/anaconda3/envs/DOPRAVA/lib/python3.8/site-packages/uvicorn/server.py", line 60, in run
return asyncio.run(self.serve(sockets=sockets))
File "/Users/hrobar/PYTHON/anaconda3/envs/DOPRAVA/lib/python3.8/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/Users/hrobar/PYTHON/anaconda3/envs/DOPRAVA/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "/Users/hrobar/PYTHON/anaconda3/envs/DOPRAVA/lib/python3.8/site-packages/uvicorn/server.py", line 67, in serve
config.load()
File "/Users/hrobar/PYTHON/anaconda3/envs/DOPRAVA/lib/python3.8/site-packages/uvicorn/config.py", line 458, in load
self.loaded_app = import_from_string(self.app)
File "/Users/hrobar/PYTHON/anaconda3/envs/DOPRAVA/lib/python3.8/site-packages/uvicorn/importer.py", line 21, in import_from_string
module = importlib.import_module(module_str)
File "/Users/hrobar/PYTHON/anaconda3/envs/DOPRAVA/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "./main_inference.py", line 74, in <module>
model_long_inf = load(file_name)
File "/Users/hrobar/PYTHON/anaconda3/envs/DOPRAVA/lib/python3.8/site-packages/joblib/numpy_pickle.py", line 587, in load
obj = _unpickle(fobj, filename, mmap_mode)
File "/Users/hrobar/PYTHON/anaconda3/envs/DOPRAVA/lib/python3.8/site-packages/joblib/numpy_pickle.py", line 506, in _unpickle
obj = unpickler.load()
File "/Users/hrobar/PYTHON/anaconda3/envs/DOPRAVA/lib/python3.8/pickle.py", line 1212, in load
dispatch[key[0]](self)
File "/Users/hrobar/PYTHON/anaconda3/envs/DOPRAVA/lib/python3.8/pickle.py", line 1537, in load_stack_global
self.append(self.find_class(module, name))
File "/Users/hrobar/PYTHON/anaconda3/envs/DOPRAVA/lib/python3.8/pickle.py", line 1581, in find_class
return _getattribute(sys.modules[module], name)[0]
File "/Users/hrobar/PYTHON/anaconda3/envs/DOPRAVA/lib/python3.8/pickle.py", line 331, in _getattribute
raise AttributeError("Can't get attribute {!r} on {!r}"
AttributeError: Can't get attribute 'FormulaicTransformer' on <module '__mp_main__' from '/Users/hrobar/PYTHON/anaconda3/envs/DOPRAVA/bin/uvicorn'>
Does anyone has similar experience?
| |
doc_5452
|
Launching lib\main.dart on SM G610F in debug mode... Running Gradle
task 'assembleDebug'...
FAILURE: Build failed with an exception.
*
*What went wrong: Execution failed for task ':app:compileDebugKotlin'.
Could not resolve all artifacts for configuration ':app:debugCompileClasspath'. . . .
*Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
*Get more help at https://help.gradle.org
BUILD FAILED in 14s Finished with error: Gradle task assembleDebug
failed with exit code 1
This is my flutter doctor:
[√] Flutter (Channel stable, v1.12.13+hotfix.5, on Microsoft Windows
[Version 10.0.10586], locale en-US)
• Flutter version 1.12.13+hotfix.5 at E:\flutter\flutter
• Framework revision 27321ebbad (6 weeks ago), 2019-12-10 18:15:01 -0800
• Engine revision 2994f7e1e6
• Dart version 2.7.0
[√] Android toolchain - develop for Android devices (Android SDK
version 29.0.2)
• Android SDK at C:\Users\208046\AppData\Local\Android\sdk
• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-29, build-tools 29.0.2
• Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
• Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b03)
• All Android licenses accepted.
[√] Android Studio (version 3.5)
• Android Studio at C:\Program Files\Android\Android Studio
• Flutter plugin version 42.1.1
• Dart plugin version 191.8593
• Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b03)
[√] VS Code, 64-bit edition (version 1.41.1)
• VS Code at C:\Program Files\Microsoft VS Code
• Flutter extension version 3.7.1
[√] Connected device (1 available)
• SM G610F • 33005566b2b5c3df • android-arm • Android 8.1.0 (API 27)
• No issues found!
edit: for my complete logs you can see here:
Flutter github issues
A: Go to your build.gradle file in the root of your Android directory and upgrade your Kotlin_version to the latest. As of the time of typing this, the latest is 1.5.10, so it should look like this:
ext.kotlin_version = '1.5.10'
A: For me, I found that when building that 2 different MainActivity.kt files were in andriod/app/src/main/kotlin. One had a default MainActivity.kt file with the package name that was originally generated for my project. Something like 'example.project_name' . The other one had what I changed my project name into. I went ahead and deleted the folder with the MainActivity.kt containing the import starting with 'example.project_name' and that resolved the issue for me.
A: in android folder of your project run in terminal
gradlew clean
Then build. This worked for me.
A: It was fixed after I upgraded my build.gradle file ext.kotlin_version = '1.5.10'
First of all run
flutter clean
flutter pub get
Go to andriod/build.gradle
then upgrade ext.kotlin_version
buildscript {
ext.kotlin_version = '1.5.10'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.1.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
A: Solved the problem by deleting android/.gradle and then run the app in debug mode
A: I Update Flutter from 2.10.4 to Flutter 3.0.0 and I found All My Project Has Same Error
ensure that your ext.kotlin_version is '1.6.10'
ext.kotlin_version = '1.6.10'
and run in terminal
flutter pub cache repair
and show that your libraries in pubspec.yamel take last version
and run in terminal
1 - flutter clean
2 - flutter pub get
in android studio open File --> invalidate cashes..
this worked for me !!
if this not work for you
you may be need to
Delete android/.gradle
thank you .
A: I solved it. It was because of my network blocked non secured http download request. I changed my network and the gradle build completed itself.
A: I Solved it by upgrading kotlin version in root build.gradle file:
ext.kotlin_version = '1.5.10'
A: First of make sure that you have latest version of flutter.
For confirmation,
please run flutter upgrade in command prompt / terminal:
flutter upgrade
Then visit the site Click Here
and copy the new latest version of kotlin.
For now: in March 02, 2022 current kotlin version is 1.6.10
Then after it:
-> Go to android/build.gradle
-> change to ext.kotlin_version = '1.6.10'
Click here to view Screenshot example
A: A possible fix can be upgrading the project/android/build.gradle
Steps to fix,
*
*flutter clean
*Delete android/.gradle
*Go to android/build.gradle, upgrade ext.kotlin_version to latest. In my case(1.3.0 -> 1.5.10), ext.kotlin_version = '1.5.10'
After doing this as well, I was getting `A problem occurred evaluating project ':app'.
Failed to apply plugin [id 'kotlin-android']
The current Gradle version 5.6.2 is not compatible with the Kotlin Gradle plugin. Please use Gradle 6.1 or newer, or the previous version of the Kotlin plugin.`
To fix this,
*
*Go to android/gradle/wrapper/gradle-wrapper.properties
*Update the distributionUrl to the latest version.In my case((5.6.2 -> 6.1.1) it is,
distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip
A: It was fixed after I upgraded my Flutter by running flutter upgrade
A: I have been facing this issue for couple of hours. At the end right now my issue solved by executing following steps -
- change Settings -> Build, Execution, Development -> Compiler -> Kotlin Compiler -> Kotlin to JVM -> check Enable incremental comilation -> Target JVM version 1.6 to 1.8
- add to build.gradle under repositories in both buildscript and allprojects section
maven {
url 'http://download.flutter.io'
}
-and lastly run on command line 'flutter pub cache repair'
A: I got the problem after migrating to null-safety. I fixed it by updating the kotlin version in the file android\build.gradle
ext.kotlin_version = '1.3.50'
Then run 'flutter clean' and the app worked fine.
A: I encountred the same problem and tried all the solutions proposed here in this post ... and still not working.
but only after upgrading the packages in pubspec.yaml with:
flutter pub upgrade
it worked !!
A:
Just increase the ext.kotlin.version from whatever version you have, to '1.4.32' or whatever the latest version is available
kotline version
A: Update to the latest version in my case it is 1.6.10 or create dummy project and check android/build.gradle and update.
ext.kotlin_version = '1.6.10'
A: when I ran flutter upgrade in the command line prompt it was fixed and ran my app .. try it
A: Faced the same issue:
Execution failed for task ':app:compileDebugKotlin'.
Execution failed for task ':app:compileDebugKotlin'.
solution:
Changed the company domain with only one dot.
solution
A: I was using JRE for Java. I just install the AdoptOpenJDK 11 and it works
A: For me, my package name imported twice automatically in MainActivity file under app>main>kotlin directory. I just delete duplicates and it works fine now!
A: In our case, the package flutter_appcenter_bundle caused this issue.
To fix it, you need to run flutter precache.
This needs to be done only once and it will be effective as long as the Flutter version remains unchanged and the precached artifacts are not deleted (e.g. by deleting the Flutter root folder).
Also, the environment variable FLUTTER_ROOT needs to be set to the Flutter root folder. On Windows it's usually C:\src\flutter.
If you use AndroidStudio, you can do that in Settings > Languages & Frameworks > Flutter.
If you don't use AndroidStudio, you need to set FLUTTER_ROOT manually.
| |
doc_5453
|
public Bitmap flip(Bitmap bitmap) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix matrix = new Matrix();
float[] mirrorY = {-1, 0, 0, 0, 1, 0, 0, 0, 1};
Matrix matrixMirrorY = new Matrix();
matrixMirrorY.setValues(mirrorY);
matrix.postConcat(matrixMirrorY);
matrix.postRotate(90);
return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
}
I can't figure out how to flip videos taken by MediaRecorder, I know I can run a ffmpeg command:
-i /pathtooriginalfile/originalfile.mp4 -vf hflip -c:a copy /pathtosave/flippedfile.mp4
but I don't know how to run a ffmpeg command from code and I can't find a different way. There are a lot of topics discussing this issue but I couldn't find a solution to work. Notice: It is possible, Snapchat got this to work somehow.
Thanks.
P.S Sorry for my English
A: Capturing images or recording video using front camera will always gives flipped images, which is expected as front camera works like you are looking at the mirror.
After getting the picture from the camera, flip the image back by drawing the image into a new context.
Please try below code snippets. Refer Android- Taking a picture from front facing camera rotates the photo
Matrix rotateRight = new Matrix();
rotateRight.preRotate(90);
if(android.os.Build.VERSION.SDK_INT>13 && CameraActivity.frontCamera) {
float[] mirrorY = { -1, 0, 0, 0, 1, 0, 0, 0, 1};
rotateRight = new Matrix();
Matrix matrixMirrorY = new Matrix();
matrixMirrorY.setValues(mirrorY);
rotateRight.postConcat(matrixMirrorY);
rotateRight.preRotate(270);
}
final Bitmap rImg= Bitmap.createBitmap(img, 0, 0,
img.getWidth(), img.getHeight(), rotateRight, true);
| |
doc_5454
|
When using regular characters as the record separator, there is one unusual case that occurs when gawk is being fully POSIX-compliant (see section Command-Line Options). Then, the following (extreme) pipeline prints a surprising ‘1’:
$ echo | gawk --posix 'BEGIN { RS = "a" } ; { print NF }'
-| 1
There is one field, consisting of a newline. The value of the built-in variable NF is the number of fields in the current record. (In the normal case, gawk treats the newline as whitespace, printing ‘0’ as the result. Most other versions of awk also act this way.)
I checked it but it does not work to me on my GNU Awk 5.0.0:
$ gawk --version
GNU Awk 5.0.0, API: 2.0 (GNU MPFR 4.0.2, GNU MP 6.1.2)
$ echo | gawk --posix 'BEGIN { RS = "a" } ; { print NF }'
0
That is, the behaviour is exactly the same as without the POSIX mode:
$ echo | gawk 'BEGIN { RS = "a" } ; { print NF }'
0
I understand the point it makes, in which the content of just a new line is considered as a field when the record separator is not the default (that is, it is not a new line). However, I cannot reproduce it.
How should I reproduce the example? I also tried with gawk --traditional or gawk -P but the result was always 0.
Since the GNU Awk User's guide I was checking is for the 5.1 version and I have the 5.0.0, I also checked an archived version for 5.0.0 and it shows the same lines, so it is not something that changed between 5.0 and 5.1.
A: When reading the POSIX standard, then we find:
The awk utility shall interpret each input record as a sequence of fields where, by default, a field is a string of non-<blank> non-<newline> characters. This default <blank> and <newline> field delimiter can be changed by using the FS built-in variable
If FS is <space>, skip leading and trailing <blank> and <newline> characters; fields shall be delimited by sets of one or more <blank> or <newline> characters.
source: POSIX awk standard: IEEE Std 1003.1-2017
Having that said, the proper behaviour should be the following:
$ echo | awk 'BEGIN{RS="a"}{print NR,NF,length}'
1 0 1
*
*a single record: no <a>-character has been encountered
*no fields: FS is the default space so all leading and trailing <blank> and <newline> characters; are skipped
*length one: there is only a single character in the record.
When defining the FS, the story is completely different:
$ echo | awk 'BEGIN{FS="b";RS="a"}{print NR,NF,length}'
1 1 1
$ echo | awk 'BEGIN{FS="\n";RS="a"}{print NR,NF,length}'
1 2 1
In conclusion: I believe the GNU awk documentation is wrong.
| |
doc_5455
|
The code is not fully optimized I know, I just want to know why it is not working as a dfs should be, thank you.
function depthFirstSearch(currentState, finalState)
{
var stack = [];
var visited = [];
delete currentState["prev"];
stack.push(currentState);
while(stack.length)
{
var node = stack.pop();
visited.push(node);
if(compare(node, finalState))
{
return visited;
}
else
{
var successors = getSuccessors(node);
for(var i = 0; i < successors.length; i++)
{
delete successors[i]["prev"];
}
var realSuccessors = [];
for(var i = 0; i < visited.length; i++)
{
for(var j = 0; j < successors.length; j++)
{
if(compare(successors[j], visited[i]))
{
continue;
}
else
{
realSuccessors.push(successors[j]);
}
}
}
for(var i = 0; i < realSuccessors.length; i++)
{
stack.push(realSuccessors[i]);
}
console.log(stack.length);
}
}
}
A: I'm going to answer myself since I realized that the number of combinations considering that im traversing my graph in depth could lead me to an infinite or long number of combinations and never reach the solution since I'm going just in one direction, therefore I thought about doing an iterative DFS which traverses each children by levels.
| |
doc_5456
|
But i cannot response write the values in the list for debugging purposes...
public void LottoWinners(object sender, EventArgs e)
{
Dictionary<int, int> number = new Dictionary<int, int>();
Random generator = new Random();
while (number.Count < 6)
{
number[generator.Next(1, 49)] = 1;
}
int[] lotto = number.Keys.OrderBy(n => n).ToArray();
List<int> lst = lotto.OfType<int>().ToList();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < lst.Count; i++) // Loop through List with for
{
builder.Append(lst).Append("|"); // Append string to StringBuilder
}
string result = builder.ToString(); // Get string from StringBuilder
Response.Write(result);
}
But all i see is as my result. I should be seeing the values of my list!
System.Collections.Generic.List`1
A: You need to do this:
builder.Append(lst[i])
to get the list element you're trying to access. Currently you're just Appending the whole list, which isn't meaningful.
A: This is what happens when you are calling ToString on List<T>. In your code this is happening right here:
builder.Append(lst)
All you have to do is to replace it with:
builder.Append(lst[i])
BTW you can replace this:
StringBuilder builder = new StringBuilder();
for (int i = 0; i < lst.Count; i++) // Loop through List with for
{
builder.Append(lst).Append("|"); // Append string to StringBuilder
}
string result = builder.ToString(); // Get string from StringBuilder
with this:
string result = string.Join("|", lst) + "|";
A: Here you are appending the list object:
builder.Append(lst)
Instead of one item:
builder.Append(lst[i])
Other than this, your code seems fine
A: builder.append(lst) is appending the list, which internally calls ToString(). ToString()on a list returns
System.Collections.Generic.List`1
so this is the correct behavior. What you want to do is this instead, use the indexer:
for (int i = 0; i < lst.Count; i++) // Loop through List with for
{
builder.Append(lst[i]).Append("|"); // Append string to StringBuilder
}
| |
doc_5457
|
the relevant code I used is given:-
PinData is just a class containing functions to set and get pin and pinEnable
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool pinEnable;
PinData pinData = PinData();
updatePinEnable() async {
pinEnable = await pinData.getPinEnable();
print(pinEnable);
}
@override
void initState() {
super.initState();
updatePinEnable();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(...),
home: pinEnable == false ? MyTabbedHome() : PinCodePage());
}
}
In the last code statement pinEnable is not false but it's null, therefore it returns PinCodePage()
Is there any way to fix this, or any ideas to get around this. Thanks!!
A: You don't need stateful widget
,and this is a better solution using a FutureBuilder to return the correct widget only when the async process is completed:
Edit: edited the code to address fact that you are not setting initial value in shared prefs
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
PinData pinData = PinData();
Future<bool> isPinEnabled() async => pinData.getPinEnable();
@override
Widget build(BuildContext context) {
return FutureBuilder<bool>(
future: isPinEnabled(),
builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
}
else if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
return snapshot.data ?
PinScreen() //if true returned from shared prefs go to pin screen
:
HomeScreen(); //if false returned from shared prefs go to home screen
}
else {
return HomeScreen(); //if null returned from shared prefs go to home screen
}
}
}
);
}
}
| |
doc_5458
|
private void setZoneValues(System.Windows.Forms.Button button, Settings1 setting)
{
if (button.BackColor == System.Drawing.Color.Lime)
{
button.BackColor = System.Drawing.Color.Tomato;
Settings1.Default.<**setting**> = false;
}
else if (btnZone1.BackColor == System.Drawing.Color.Tomato)
{
btnZone1.BackColor = System.Drawing.Color.Lime;
Settings1.Default.<**setting**>= true;
}
}
A: You can just pass in the setting name as a string, and then do:
private void setZoneValues(System.Windows.Forms.Button button, string setting)
{
...
Settings1.Default[setting] = true;
...
}
A: *
*Select your button in designer.
*In the properties window find '(Application Settings)' and expand it
*Select '(PropertyBinding)'
*Find property Backcolor in list and create new setting for it with name e.g. "MyButtonColor"
TThat creates color property with name 'MyButtonColor' in defatult application settings and binds it to button's BackColor property.
Next goes coding:
private void setZoneValues(Button button, string setting)
{
// change button color
button.BackColor = (button.BackColor == Color.Lime) ?
Color.Tomato : Color.Lime;
}
That's all. When you call Settings.Default.Save(); current button's BackColor value will be saved to setting file. When you start application again, value from settings file will be assigned to button's BackColor.
UPDATE: Of course, you can add settings manually, but then you'll need to load and update them manually. E.g. in Form_Load event handler:
button1.BackColor = Settings.Default.MyButtonColor;
And after changing color in setZoneValues method:
Settings.Default.MyButtonColor = button.BackColor;
A: Suppose you have specified a setting with name "Test" in Settings.settings. You can access that setting using following line of code:
Properties.Settings.Default.Test
Your setting will act like a property in c#. You will be able to get and set value to it.
| |
doc_5459
| ||
doc_5460
|
However, in Visual C++ 2008, when adding resource, there is a language called German(Neutral).
So, how can I find the code for German(Neutral)?
| |
doc_5461
|
In the following program the console prints lots of !!!!! but no ?????, why?
Also I'm assuming that the byte with the invalid parity bit will still be included in the stream?
using (var serialPort = new SerialPort())
{
serialPort.PortName = "COM2";
serialPort.BaudRate = 562500;
serialPort.Parity = Parity.Space;
serialPort.DataBits = 8;
serialPort.StopBits = StopBits.One;
serialPort.ErrorReceived += (s, e) => Console.WriteLine("!!!!!");
serialPort.Open();
var thread = new Thread(() =>
{
while (isRunning)
{
var b = serialPort.ReadByte();
if (b == 126)
Console.WriteLine("?????");
}
});
thread.Start();
Console.WriteLine("");
Console.WriteLine("Press any key to exit.");
Console.ReadKey(true);
isRunning = false;
thread.Join();
}
A: It is a documentation bug. The actual replacement character is '?', ASCII code 63.
| |
doc_5462
|
{
"data": [{
"datatype": "AccessoryProduct",
"values": {
"identifier": "access8770009prd",
"shortdescription": "<p>Hybrid Dual Injection Cover and a Tempered Glass.<\/p>",
"displayname": "Protection Essentials Bundle - Samsung Galaxy S9 (Clear) 822445132623"
}
},
{
"datatype": "AccessoryProduct",
"values": {
"identifier": "access8530068prd",
"shortdescription": "String.class",
"displayname": "JBL UA Flex Headphones (Gray) - 050036342735"
}
}, {
"datatype": "AccessoryProduct",
"values": {
"identifier": "access8630012prd",
"shortdescription": "<p>This slim case has everything you want - style and protection.<\/p>",
"displayname": "Otterbox Symmetry Series Case - Samsung Galaxy S9 (Clear) - 660543444121"
}
}
]
}
From the above object, I need to get this below array.
identifierList = [ 'access8770009prd', 'access8530068prd', 'access8630012prd' ]
as a single dimensional array. Can anyone please provide an efficient approach.
A: if a is the json you have you can do the follwing
identifierList = a.data.map(x => x.values.identifier)
A: You can use map() with array destructuring to get that array of identifier.
var data = [{
"datatype": "AccessoryProduct",
"values": {
"identifier": "access8770009prd",
"shortdescription": "<p>Hybrid Dual Injection Cover and a Tempered Glass.<\/p>",
"displayname": "Protection Essentials Bundle - Samsung Galaxy S9 (Clear) 822445132623"
}
},
{
"datatype": "AccessoryProduct",
"values": {
"identifier": "access8530068prd",
"shortdescription": "String.class",
"displayname": "JBL UA Flex Headphones (Gray) - 050036342735"
}
}, {
"datatype": "AccessoryProduct",
"values": {
"identifier": "access8630012prd",
"shortdescription": "<p>This slim case has everything you want - style and protection.<\/p>",
"displayname": "Otterbox Symmetry Series Case - Samsung Galaxy S9 (Clear) - 660543444121"
}
}
];
var identifierList = data.map(({values}) => values.identifier);
console.log(identifierList);
USING forEach()
var data = [{
"datatype": "AccessoryProduct",
"values": {
"identifier": "access8770009prd",
"shortdescription": "<p>Hybrid Dual Injection Cover and a Tempered Glass.<\/p>",
"displayname": "Protection Essentials Bundle - Samsung Galaxy S9 (Clear) 822445132623"
}
},
{
"datatype": "AccessoryProduct",
"values": {
"identifier": "access8530068prd",
"shortdescription": "String.class",
"displayname": "JBL UA Flex Headphones (Gray) - 050036342735"
}
}, {
"datatype": "AccessoryProduct",
"values": {
"identifier": "access8630012prd",
"shortdescription": "<p>This slim case has everything you want - style and protection.<\/p>",
"displayname": "Otterbox Symmetry Series Case - Samsung Galaxy S9 (Clear) - 660543444121"
}
}
];
var identifierList = [];
data.forEach(({values}) => identifierList.push(values.identifier));
console.log(identifierList);
| |
doc_5463
|
start-service Netlogon
has error :
erroe : Start-Service : Service 'Netlogon (Netlogon)' cannot be started due
to the following error: Cannot open Netlogon service on computer '.'.
At line:1 char:1
+ Start-Service Netlogon
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError:
(System.ServiceProcess.ServiceController:ServiceController) [Start-Service],
ServiceCommandException
+ FullyQualifiedErrorId :
CouldNotStartService,Microsoft.PowerShell.Commands.StartServiceCommand
A: Just try this:
net start Netlogon
Though it is a batch command but worked in Powershell as well. I run as local account not required to run PS as administrator
| |
doc_5464
|
MyObject objects[] = new MyObject[6];
for (MyObject o: objects) {
o = new MyObject();
}
MyObject objects[] = new MyObject[6];
for(int i = 0; i < objects.length; i++) {
objects[i] = new MyObject();
}
A: I added a comment into each example to clarify what's going on.
First example:
MyObject objects[] = new MyObject[6];
for(MyObject o: objects) {
// Construct a new object of type MyObject and assign a reference to it into
// the iteration variable o. This has no lasting effect, because the foreach
// loop will automatically assign the next value into the iteration variable
// in the the next iteration.
o = new MyObject();
}
Second example:
MyObject objects[] = new MyObject[6];
for(int i = 0; i < objects.length; i++) {
// Construct a new object of type MyObject and store a reference to it into the
// i-th slot in array objects[]:
objects[i] = new MyObject();
}
A: The first one isn't allocating your array objects because foreach loops iterate over elements in a collection.
When you enter that foreach loop you don't have any elements in your collection, it is just an empty array initialized to size 6, so no objects will be added to your array.
Also, note that even if you had elements in the array the foreach loop wouldn't assign over top of them:
o = new MyObject();
basically means assign to o a new instance of MyObject, but o itself isnt part of the array objects it is only a temporary container used to iterate over the elements of the array, but in this case, there are none.
A: Objects are only "copied" when you explicitly state you want to clone an object (and this object explicitly implements cloning feature).
You seem to confuse references and names.
In the first example, inside a foreach, local o variable refers to the area of memory some object from objects is stored. When you're doing o = new MyObject(), a new MyObject is initialized in some other area of memory, and then o reference is rewritten to point on this new area of memory.
In the second example, by writing objects[i] = new MyObject(), you're saying that objects[i] reference should be rewritten, not some local o variable.
A: Java works a little bit different than many other languages. What o is in the first example is simply a reference to the object.
When you say o = new MyObject(), it creates a new Object of type MyObject and references o to that object, whereas before o referenced objects[index].
That is, objects[index] itself is just a reference to another object in memory. So in order to set objects[index] to a new MyObject, you need to change where objects[index] points to, which can only be done by using objects[index].
Image: (my terrible paint skills :D)
Explanation:
This is roughly how Java memory management works. Not exactly, by any means, but roughly. You have objects, which references A1. When you access the objects array, you start from the beginning reference point (A1), and move forward X blocks. For example, referencing index 1 would bring you to B1. B1 then tells you that you're looking for the object at A2. A2 tells you that it has a field located at C2. C2 is an integer, a basic data type. The search is done.
o does not reference A1 or B1, but C1 or C2. When you say new ..., it will create a new object and put o there (for example, in slot A3). It will not affect A1 or B1.
Let me know if I can clear things up a little.
A: The short answer: yes, there is something like a copy going on.
The long answer: The Java foreach loop you posted is syntactic sugar for
MyObject objects[] = new MyObject[6];
Iterator<MyObject> it = objects.iterator();
while (it.hasNext()) {
MyObject o = it.next();
// The previous three lines were from the foreach loop
// Your code inside the foreach loop
o = new MyObject();
}
As the desugared version shows, setting a reference equal to something inside a foreach loop does not change the contents of the array.
A: First thing I want to mentioned is that non zero length arrays are always mutable.And inside the foreach loop
for(MyObject o in objects)
what it does is in each iteration it works as following.
o = objects[0] // first iteration
o = objects[1] // 2nd iteration
But in your case you assign another object to the reference o. Not to the objects in the array.Its simply like following.
ObjeMyObject objects[] = new MyObject[6];
MyObject o = Object[0];
0 = new MyObject();
But your original objects[0] still point to a null object.
A: Every time when you use "new" operator JVM will create a new instance and it will be assigned to the Left hand side operand of assignment operator.
it doesn't matter on for each loop or for loop.
In for each loop
for(MyObject O : Object)
O will be created once only that will be of MyObject it will not be instantiated and the values from the Object array will be keep copying in O
like
O = Object[0]
O = Object[1]
O = Object[2]
O = Object[3]
O = Object[4]
O = Object[5]
We do not need to tack care of increasing the counter, thats the beauty of for Each loop.
| |
doc_5465
|
{
geocoded_waypoints: [
{},
{}
],
routes: [
{
bounds: {},
copyrights: "Dados do mapa ©2017 Google, Inst. Geogr. Nacional",
legs: [],
overview_polyline: {
points: "cxwnFtdct@dAQlAf@fAf@|Aq@l@]pCcFhCjA|LfJlAT~@IpDi@jAb@f@HXi@t@kBhBeBx@Qz@z@dClHzFpW`H|RvTpj@`AxAdBdAnAXhB?fBk@rAcAnG_HhCgAjAKrATbA`Al@lBHnAc@rFgBhIkCxMBfIlBvHnBtCnB|AnEdCrJxFj@fB@h@OhAgCtHGfCl@jAlA\jE]tDBzBb@tLxFtK~E`d@hShIzEtDhDxDrEfDpFlFjNvDtRdDjThF`TzH`QhEhG|EvFhL`JpJtE|LpEdOpFjOzGlPfJlHzE~NjLfQvPfP|RtHrKxDjGfI|NdHbOvGjPfCbHpCtIvJh_@vG|[|CtNvFvSvE~MfI|QzLbTfNxQbKlKrRzP|NnNvNlQjIzMnLfV`T|h@nDbHhIdMxFjH~JrMnEfHzIrQfHvOtEjI|MnQfNzP`FzI~EnLrKp[nDlHvErHzL~MbRbM`EjCjFxEtRnX|D~EjIhI~WrRxGlGdFnG`JjNxHzKfTxVfKfRfMbRlErHtBlFxIjYvHnPpBtFxF~WpCjHjGhJfDzClF~CnDlArDl@pC\vHXvX[lOaB|GcBdFqBxQwJbDmAxE_ApJ_@jEXtItBrQ~EbQbDlUfBpMfA|IxCbF`DhGlGnJjKtJrF`SpFbRnDdUxAbGrAlEjBnFpDtNnMfGlE~[lTbRdQjTpUxH`GjHfEnGlC`O|DrUxEnEzAfFrBnSpIjPnDxSlAf\lAl~@hDzRrAjOpBvKrBrQtEv^pM``@rPrR|JxSdMlGnGfGtH~HxFdFlBtGfApGp@bG|AnHxD|FzFrH`L~FvH|HrFrFtBtFjA~Mt@pHR|FhA`IfDpEbDzFxGrHrKhEtErF`EnS`MzMvItSdUfF~DtE~B|SrInEnBzDtCxN`QpQfVtQ~Yjn@~fAnK`RvLlRzEjF|GlFrc@vUfRjKfIvGxDhEjIxKdN~T`L~MrFvE~LhIlp@fb@xCtBzFtFbEzFbDrGhH`TfF|JnGfHzEdD|UdIpTdHtKtFj]nUrEzC~[pTfLfG|EbB~KfCnTvDpmAxSzs@~LhOfDzOdFfOxGdY`O`k@zYnVzMlK|HrFjFbXj[rCbCvDfB|FfBbD^xRBlb@nBrIdArJvDfD|B|FzFvFzHnCbIDrCk@dA_A_@q@mHz@sAvAJ^f@r@n@x@UR_@fBGjET`S~@ro@pCpXpAfFp@dEhCnGtE@HXl@n@H^W|ASpShAbZxAtPp@~SjAzGZKdDStBd@x@dC@nEVz@HtAp@b@\OZ|AbBxDnFJf@"
},
summary: "A1",
warnings: [ ],
waypoint_order: [ ]
}
],
status: "OK"
}
How do I draw with that value?
A: This help me,you can use it..
Firstly create a google server key from google developer account
GoogleDirection.withServerKey(getResources().getString(R.string.SERVER_KEY))
.from(SourceLatlng)
.to(DestinationLatlng)
.execute(new DirectionCallback() {
@Override
public void onDirectionSuccess(Direction direction, String message) {
if (direction.isOK()) {
routeSucess2(direction, message,SourceLatlng,DestinationLatlng);
} else {
//selectedRawLine = ERROR;
}
}
@Override
public void onDirectionFailure(Throwable t) {
t.printStackTrace();
}
});
then draw a route using google direction
private void routeSucess2(Direction direction, String message,LatLng sourceLatlng,LatLng DestinationLng) {
for (Route route : direction.getRouteList()) {
PolylineOptions polyoptions = new PolylineOptions();
polyoptions.color(getResources().getColor(R.color.primary__dark));
polyoptions.width(5);
polyoptions.addAll(route.getOverviewPolyline().getPointList());
poly = googleMap.addPolyline(polyoptions);
poly.setClickable(true);
}
LatLngBounds.Builder latLngBuilder = new LatLngBounds.Builder();
if(sourceLatlng!=null)
latLngBuilder.include(sourceLatlng);
if(DestinationLng!=null)
latLngBuilder.include(DestinationLng);
try {
LatLngBounds bounds = latLngBuilder.build();
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds,
UiHelper.dpToPixel(getActivity(), 135));
googleMap.animateCamera(cu);
} catch (Exception e) {
e.printStackTrace();
}
}
This would help you.
A: @alb First you should parse lat,long from JSON. You can see this link:
https://developers.google.com/maps/documentation/directions/
Then you have to get lat, long values & put them in List<>.
After that you can use below code for draw polyline on map:
PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
for (int z = 0; z < list.size(); z++) {
LatLng point = list.get(z);
options.add(point);
}
line = myMap.addPolyline(options);
A: I already have replied on similar question on below link
How to buffer a polyline in Android or draw a polygon around a polyline?
It will resolve your Issue probably
| |
doc_5466
|
You say how I can resolve it?
This is the code
public class SearchResult
{
public string url;
public string title;
public string content;
public FindingEngine engine;
public enum FindingEngine { google, bing, google_and_bing };
public SearchResult(string url, string title, string content, FindingEngine engine)
{
this.url = url;
this.title = title;
this.content = content;
this.engine = engine;
}
}
public static List<SearchResult> GoogleSearch(string search_expression,
Dictionary<string, object> stats_dict)
{
var url_template = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=large&safe=active&q={0}&start={1}";
Uri search_url;
var results_list = new List<SearchResult>();
int[] offsets = { 0, 8, 16, 24, 32, 40, 48 };
foreach (var offset in offsets)
{
var searchUrl = new Uri(string.Format(url_template, search_expression, offset));
var page = new WebClient().DownloadStringAsync(searchUrl);
var o = (JObject)JsonConvert.DeserializeObject(page);
var results_query =
from result in o["responseData"]["results"].Children()
select new SearchResult(
url: result.Value<string>("url").ToString(),
title: result.Value<string>("title").ToString(),
content: result.Value<string>("content").ToString(),
engine: SearchResult.FindingEngine.google
);
foreach (var result in results_query)
results_list.Add(result);
}
return results_list;
}
Thanks!
A: DownloadStringAsync doesn't return anything i.e. a void so you cannot simply assign a variable to it.
You need to add an event handler to DownloadStringCompleted which will be fired when DownloadStringAsync completes.
var client = new WebClient();
client.DownloadStringCompleted += client_DownloadStringCompleted;
client.DownloadStringAsync(searchUrl);
static void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) {
// e.Result will contain the returned JSON. Move the code that parse the result to here.
}
| |
doc_5467
|
int mask = ~0 >> n;
I was playing on using this to mask n left side of another binary like this.
0000 1111
1010 0101 // random number
My problem is that when I print var mask it still negative -1. Assuming n is 4. I thought shifting ~0 which is -1 will be 15 (0000 1111).
thanks for the answers
A: Performing a right shift on a negative value yields an implementation defined value. Most hosted implementations will shift in 1 bits on the left, as you've seen in your case, however that doesn't necessarily have to be the case.
Unsigned types as well as positive values of signed types always shift in 0 bits on the left when shifting right. So you can get the desired behavior by using unsigned values:
unsigned int mask = ~0u >> n;
This behavior is documented in section 6.5.7 of the C standard:
5 The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative
value, the value of the result is the integral part of the quotient
of E1 / 2E2 .If E1 has a signed type and a negative value, the
resulting value is implementation-defined.
A: Right-shifting negative signed integers is an implementation-defined behavior, which is usually (but not always) filling the left with ones instead of zeros. That's why no matter how many bits you've shifted, it's always -1, as the left is always filled by ones.
When you shift unsigned integers, the left will always be filled by zeros. So you can do this:
unsigned int mask = ~0U >> n;
^
You should also note that int is typically 2 or 4 bytes, meaning if you want to get 15, you need to right-shift 12 or 28 bits instead of only 4. You can use a char instead:
unsigned char mask = ~0U;
mask >>= 4;
A: In C, and many other languages, >> is (usually) an arithmetic right shift when performed on signed variables (like int). This means that the new bit shifted in from the left is a copy of the previous most-significant bit (MSB). This has the effect of preserving the sign of a two's compliment negative number (and in this case the value).
This is in contrast to a logical right shift, where the MSB is always replaced with a zero bit. This is applied when your variable is unsigned (e.g. unsigned int).
From Wikipeda:
The >> operator in C and C++ is not necessarily an arithmetic shift. Usually it is only an arithmetic shift if used with a signed integer type on its left-hand side. If it is used on an unsigned integer type instead, it will be a logical shift.
In your case, if you plan to be working at a bit level (i.e. using masks, etc.) I would strongly recommend two things:
*
*Use unsigned values.
*Use types with specific sizes from <stdint.h> like uint32_t
| |
doc_5468
|
When you set the mnemonic to KeyEvent.VK_F3, the user has to press Alt+F3.
If you have a menu item, you can set an accelerator, rather than a mnemonic, and choose whether to use a meta key. Buttons don't let you set an accelerator, however.
Is there a way to turn of the meta-key for button mnemonics?
A: Actions can bind a chunk of code to a menu item, a keystroke, a button and anything else you are interested.
In general, don't think of your code as tied to a specific keypress/event--and don't use anonymous inner classes. Instead use real classes where your code can be reused for different types of things. That pattern used by the Action class gives some good examples of this.
A: Well behind the scenes, whether you use an accelerator or a mnemonic on a component, the method will create a Key Binding for you.
So there is nothing to prevent you from binding a KeyStroke and Action to whatever component you want and manually create the Key Binding. It can even be a component that doesn't have the setMNemonic(...) method.
A: Are you sure that accelerators cannot be defined on buttons if the button was configured using an Action? (I know this was true at one point, but I thought this may be different in later versions of Java.)
In any event, here is another method to set it on a button:
button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(myKeyStroke, "actionName");
button.getActionMap().put("actionName", myAction);
Where myKeyStroke is a keystroke such as F3, "actionName" is a label (String), and myAction is the action it invokes.
| |
doc_5469
|
Here is the test code I wrote, it works fine with UIPickerView but does not show anything with UITableView.. thanks for your support !
class ViewController: UIViewController, UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource, UITableViewDelegate, UITableViewDataSource {
var itemPicker = UIPickerView()
var playerTableView = UITableView()
@IBOutlet weak var textFieldOne: UITextField!
@IBOutlet weak var textFieldTwo: UITextField!
var firstTextField = ["a", "b", "c", "d"]
var secondTextField = ["A", "B", "C", "D"]
override func viewDidLoad() {
super.viewDidLoad()
textFieldOne.delegate = self
textFieldTwo.delegate = self
itemPicker.delegate = self
itemPicker.dataSource = self
playerTableView.register(UITableViewCell.self, forCellReuseIdentifier: "playerCell")
playerTableView.delegate = self
playerTableView.dataSource = self
textFieldOne.inputView = itemPicker
textFieldTwo.inputView = playerTableView
}
// PickerView
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return firstTextField.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return firstTextField[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
textFieldOne.text = firstTextField[row]
}
// TableView
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return firstTextField.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = playerTableView.dequeueReusableCell(withIdentifier: "playerCell")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "playerCell")
}
cell?.textLabel?.text = firstTextField[indexPath.row]
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
textFieldTwo.text = firstTextField[indexPath.row]
}
}
| |
doc_5470
|
But How can I change the background color of the panel.i need to change the color of that white space.Please help
A: I have solved this by changing the styles.less less file.
.mat-menu-panel.ng-trigger {
background: transparent;
min-width: 1%;
min-height: 1%;
}
A: You haven't really provided enough clear information here but it is probably
.mat-menu-content{
background-color: red;
}
| |
doc_5471
|
The structure of the objects is exactly the same, there is a key, a timestamp, and some other stuff
arr1 = [{key: 2, timestamp:2020-07-07T02:00:00.000Z},other stuff:....}...]
arr2 = [{key: 7, timestamp:2020-07-07T02:00:00.000Z},other stuff:....}...]
arr1 tracks things by the hour so each timestamp is an hourly one
arr2 tracks things every 15 mins so there are timestamps in there that are like 2020-07-07T02:45:00.000Z
What im trying to do is find were the timestamps match in both arrays
Im looping through 1 array then passing in the timestamp to search for it in the other
Problem is its not finding a matching value even though I know its there
arr1.map(function (e) {
console.log(e.timestamp, arr2[3].timestamp, e.timestamp == arr2[3].timestamp )
});
So the above code goes through all of the timestamp values in arr1 and then console logs them, plus a specific value that I know is in arr1 from arr2, I then console log a comparison
What the console log prints is the following
2020-07-07T02:00:00.000Z 2020-07-07T02:00:00.000Z false
That false should be true shouldn't it????
NB: Ive tried with == and === but both produce false
A: You can't compare the timestamp like that, because timestamp is object.
new Date('2020-07-07T02:00:00.000Z') == new Date('2020-07-07T02:00:00.000Z')
// false
Let's try
(e.timestamp - arr2[3].timestamp) == 0)
arr1.map(function (e) {
console.log(e.timestamp, arr2[3].timestamp, (e.timestamp - arr2[3].timestamp) == 0);
});
| |
doc_5472
|
Json code:
"{\"Statistics\":{\"76561198047386802\":{\"LastUpdate\":1557255652}}}"
jscode:
const obj = JSON.parse(jsonData)
const object = obj.Statistics.76561198047386802;
console.log(object.LastUpdate);
I am trying to pass this code through to get the lastupdate value. I keep trying to use the numbers above but getting errors on the output. Can you please show me my idiotic mistake lol.
A: You can try:
...
const object = obj.Statistics['76561198047386802'];
...
| |
doc_5473
|
when i give row even and odd color it became non scrollable what should i do for this that when I add even and odd class name it should not became non scrollable
Here is my code
<head>
<link rel="stylesheet" type="text/css" href="styles.css" />
<script src="jquery.js"></script>
<style type="text/css">
.wrap {
width: 320px;
}
.wrap table {
width: 300px;
table-layout: fixed;
}
table tr td {
padding: 5px;
border: 1px solid #eee;
width: 100px;
word-wrap: break-word;
}
table.head tr td {
background: #eee;
}
.inner_table {
height: 150px;
overflow-y: auto;
}</style
</head>
<?php
include('conn.php');
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT * FROM mesagerecord';
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
?>
<div class="wrap">
<table class="head">
<tr>
<td>Message</td>
</tr>
</table>
<div class="inner_table">
<table>
<?php
$i=0;
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
if($i%2==0)
$classname="evenRow";
else
$classname="oddRow";
?>
<tr>
<td class="<?php echo $classname;?>"><?php echo $row['message']; ?></td>
</tr>
<?php
$i++;}
?>
</table>
</div>
</div>
<?php
mysql_close($conn);
?>
If I remove even odd class name it works fine.
A: You have to use tbody and give the overflow will be auto and display to be block.
Can you check it?
Example:
Css
<style>
tbody {
height: 100px;
overflow: auto;
display:block;
}
</style>
HTML
<table border="1">
<thead>
<tr>
<td>Test Cases</td>
</tr>
</thead>
<tbody>
<tr>
<td>Test 1</td>
</tr>
<tr>
<td>Test 2</td>
</tr>
<tr>
<td>Test 3</td>
</tr>
<tr>
<td>Test 4</td>
</tr>
</tbody>
</table>
| |
doc_5474
|
For example, I am glad to use git as a tool to update my remote site from my git repository. The problem is there is a .git directory at the root of my website, external users can simply visit it using site/.git, that is terrible, since they can easily get my code history, and basically the current code, they can even get passwords and private informations from the configuration files.
So what is the right way to use git which can make full use of git, but without introducing these threats?
Using git clone git://repo site_root to initialize web site, and git pull to get changes is of great convenience, but also brings huge security problems.
Is there any methods that can be as convenient as the steps shown above, but without security pitfalls?
A: Apache, at least, defaults its configuration to forbidding web access to any file starting with a ., and this could be done in any other webserver as well.
Additionally, it's best to keep sensitive files outside the web root, i.e.:
.git/
config.file
public/
public/index.html
and have the document root for the site be the public/ directory.
A: See http://www.clientcide.com/best-practices/exporting-files-from-git-similar-to-svn-export/
From the above:
Here’s my one-line command for taking the archive and sending it to a
different location:
git archive HEAD | (cd ~/path/where/I/want/it/ && tar -xvf -)
This will extract the ENTIRE library to the specified path (without
the .git files and whatnot).
Sometimes, however, I want to pull out just a portion of the library.
git archive always gives you the whole enchilada which kinda sucks,
and in this case I use rsync, like this:
rsync path/I/want/to/export/ -ri --del -m --exclude ".*"
~/path/where/I/want/it/ |grep sT
That last bit – the grep sT will limit the output of what I see so
that I only see the files that are updated. I use that just to sanity
check my export. If I see a TON of stuff go to update a path that
already has the library and I know I only changed one file, then I
know I got the path wrong.
A: Well, I'm not really fond of using directly git to automatically deploy the last version of your code, but that's another question.
Regarding your security issue, a really basic solution would be to just remove access to your .git file (with htaccess files?).
Another thing would be to remove your passwords from the git repository, there is probably no use of then in your version control system.
A: A combination of @JaredPar's comment, and @Chris Shain's answer above (+1 for the git archive).
I use git archive also, and then use Chef for the actual deployment. Couldn't be simpler.
*
*git archive <tag_name> | gzip > rc.tar.gz
*mv rc.tar.gz to my cookbook
*upload cookbook
The chef-client running on my server runs the recipe to copy the zipped file to a chache location and extract it into my web server directory.
Note to self: publish the recipe on github
A: If having the complete repo in the production server is a requirement, then there is a solution.
You can have the whole history somewhere in the file system and have git "point" to it.
$ cd /public # go to the public directory
$ git clone git://repo # to initialize the web site
$ mv .git /private/repo.git # move sensible information to a private place
$ export GIT_DIR=/private/repo.git # make git "point" to the history
$ git pull # update changes
If you do that, your history will be in /private/repo.git that is not accessible through the web, and your working directory will be in /public, serving only the version of the files you specify.
For more information, you can read progit.
A: I'll resurrect this question because I'm also looking into security issues.
You should use a detached work tree, as explained here. You can create your git repository outside the web root, and have git point to the source code at a different directory.
| |
doc_5475
|
public class MyNode {
public MyNode(@NamedArg("pane") Pane pane) {
//<code>
}
}
The following code doesn't work:
<MyNode>
<pane>
<Pane/>
</pane>
</MyNode>
Cannot resolve sumbol pane
When I change MyNode to:
public class MyNode {
private final Pane pane;
public MyNode(@NamedArg("pane") Pane pane) {
//<code>
}
}
It is properly detected.
IMPORTANT: I don't even have to use the field, just initialize it. Is there any workaround to get it working without creating a dummy field just to get it working with FXML?
It doesn't have to be a Pane obviously, it can be any other Object. For types like double, I'm able to get it working without creating a field, like this: <pane myDoubleValue="100.0"/>
| |
doc_5476
|
I have 2 JSP files:
*
*1st JSP (named: home.jsp) file has only 1 button which will load the content of second JSP file using AJAX (Jquery load() method).
*2nd JSP (named: second.jsp) file has actual HTML for tab effect.
Problem is I am unable to show the first tab and hide rest of others. Whats happening is that all the panels(divs) to which the tabs are linked are shown one after the other.
I also want to tell, that problem is fixed when I click any one of them(tabs)..i.e when I click any 1 tab rest of others get hide.
But what i want is that when my second.jsp file is loaded using ajax, I got to see only first tab panel not other by default.
Actually, I am unable to post images due to my low reputation..but to have a clear view of my problem you can watch the video at YOUTUBE at https://www.youtube.com/watch?v=useXgTzEAZg
Following is the file wise code:
home.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<style type="text/css">
#homeDiv {
width: 1000px;
height: 1000px:
}
</style>
<link href="css/styles.css" rel="stylesheet" type="text/css">
<script src="js/jquery-1.10.2.js" type="text/javascript"></script>
<script src="js/jkl.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#but').click(function() {
$('#homeDiv').load('folder2/second.jsp #main');
return false;
});
});
</script>
</head>
<body>
<button id="but">press</button>
<br>
<div id="homeDiv"></div>
</body>
</html>
second.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="UTF-8">
<title>News Headlines</title>
</head>
<body>
<div>...</div>
<div class="wrapper">
<div class="content">
<div id="main">
<script src="js/jkl.js" type="text/javascript"></script>
<h1>Tabbed Panels</h1>
<div class="tabbedPanels" id="tabbed1">
<ul class="tabs">
<li><a href="#panel1" tabindex="1">Tab 1</a></li>
<li><a href="#panel2" tabindex="2">Tab 2</a></li>
<li><a href="#panel3" tabindex="3">Tab 3</a></li>
</ul>
<div class="panelContainer">
<div id="panel1" class="panel">
<h2>Panel 1 content</h2>
<p>Apples</p>
</div>
<div id="panel2" class="panel">
<h2>Panel 2 content</h2>
<p>Mango</p>
</div>
<div id="panel3" class="panel">
<h2>Panel 3 content</h2>
<p>Potato</p>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
jkl.js (JavaScript file)
$(document).ready(function() {
//alert('outside');
//$('.tabs a').bind('click focus',function() {
$(document).on('click', '.tabs a', function()
{
var $this = $(this);
//alert('?????');
// hide panels
$this.parents('.tabbedPanels')
.find('.panel').hide().end()
.find('.active').removeClass('active');
// add active state to new tab
$this.addClass('active').blur();
// retrieve href from link (is id of panel to display)
var panel = $this.attr('href');
// show panel
$(panel).show();
// don't follow link
return false;
}); // end click
$('.tabs').find('li:first a').click();
}); // end ready
styles.css
.tabbedPanels {
width: 70%;
float: left;
margin-right: 10px;
}
.tabs {
margin: 20;
padding: 20;
zoom : 1;
}
.tabs li {
float: left;
list-style: none;
padding: 0;
margin: 0;
-webkit-border-top-left-radius:8px;
-webkit-border-top-right-radius:8px;
-moz-border-radius-topleft:8px;
-moz-border-radius-topright:8px;
}
.tabs a {
display: block;
text-decoration: none;
padding: 3px 5px;
/* background-color: red;; */
margin-right: 1px;
border: 2px solid rgb(100,20,135);
margin-bottom: -2px;
width: 60px;
-webkit-border-top-left-radius:8px;
-webkit-border-top-right-radius:8px;
-moz-border-radius-topleft:8px;
-moz-border-radius-topright:8px;
}
.tabs .active {
border-bottom: 1px solid white;
background-color: white;
color: red;
position: relative;
}
.panelContainer {
clear: both;
margin-bottom: 25px;
border: 1px solid red;
background-color: white;
padding: 10px;
}
.panel h2 {
color: red;
text-shadow: none;
}
.panel p {
color: black;
}
A: to achieve this, I gave the ID to first tab <a id='first_a'> in second.jsp file.
then replace the script in home.jsp to this:
$(document).ready(function() {
$('#but').click(function() {
$('#homeDiv').load('folder2/second.jsp #main', function() {
$('#first_a').click();
});
return false;
});
});
| |
doc_5477
|
@JsonClass(generateAdapter = true)
data class SearchResult(
@field:Json(name = "1. symbol") val symbol: String,
@field:Json(name = "2. name") val name: String,
@field:Json(name = "4. region") val region: String,
)
When I build my application, I have this SearchResultJsonAdapter generated with a line breaker after 4.. This line breaker make my code not compilable...
class SearchResultJsonAdapter(
moshi: Moshi
) : JsonAdapter<SearchResult>() {
private val options: JsonReader.Options = JsonReader.Options.of("1. symbol", "2. name", "4.
region")
What can I do to disable line breaking in my JSonAdapter. Many thanks
A: It was an issue fix after 1.9.3. Using version 1.11.0 in gradle's app helps me to fix this problem:
kapt 'com.squareup.moshi:moshi-kotlin-codegen:1.11.0'
| |
doc_5478
|
df = pd.read_sql_query('SELECT member, sku, quantity FROM table GROUP BY member, csvdatabase')
This works and gives me three columns; however, the problem is that I want to convert this from Long to Wide format. I tried using pivot function, but my machine does not have the memory to handle this:
df_new = df.pivot(index = 'member', columns = 'sku', values = 'quantity')
Is there a way to make the SQL query do this? I came across several examples where the pivot function is used or the MAX(CASE WHEN Key..., but the number of sku's is too large to type into a sql query
| |
doc_5479
|
In my work, We made a app which show a high resolution image into a UIScrollVIew. Besides, the user can play a MP3 that animate the position and zoom of UIScrollView from one second with a specific duration showing the detail of image that MP3 is talking about. Currently, the audio play from second 0 to the end sequently. User can´t interactuate with UIScrollView when the MP3 is playing
Now we want that the user can change the current time when is playing, I´m not sure how calculate the position when the user select a second placed in the midst of one animation.
Example:
Second 1: Duration 4; Second 8: Duration 2; Second 20 Duration 10; Second 31 Duration 3;
If the user select the second 24, we would want animate during 6 seconds, but keeping in mind the original position that UIScrollView should have since second 20 to 24 from original animation.
We are using uiview animation (animateWithDuration) with zoomToRect (animated:NO) method from UIScrollView
I´m not sure how calculate those intermediate values.
Thanks.
A: I do not know, whether I really get you right or wrong. But you can set the animations progress to a progress value that is in relation to the start point and the total duration of the animation. I. e. in your case
float animationStartPoint = 20.0; // Start of the animation
float duration = 10.0; // Its duration
float partialStartPoint = 24.0; // user selected start point
NSAnimation *animation = …;
…
animation.currentProgress = (partialStartPoint-animationStartPoint)/duration;
[animation startAnimation];
| |
doc_5480
|
When www.domain1.nl/page-old is visited it redirects to: www.domain2.nl/page-old.
So the redirect sort of works, but only half. The domain is redirected, the page is not.
*
*Domain1 only has a .htaccess file in the root.
*Domain2 is a WordPress website.
We use apache 2.4 + php7.3 + CloudFlare (no rules set)
We tried multiple htaccess rules texts: Redirect 301, Redirect, RedirectMatch, RewriteRule. All same result.
In the .htaccess file of domain1.com:
Redirect 301 /page-old/ https://www.domain2.com/page-new/
Expected result would be:
www.domain1.nl/page-old >> www.domain2.nl/page-new
Actual result:
www.domain1.nl/page-old >> www.domain2.nl/page-old
A: Posting my answer in comment section here so that readers can find it easily later
You need to use this rule instead for precise matching:
RedirectMatch 301 ^/page-old/ https://www.domain2.com/page-new/
Redirect is non-regex directive that works with starts-with match.
| |
doc_5481
| ||
doc_5482
|
I have gone through several documents to get a clear idea of shell form and exec form. But all looked confusing to me. Can anyone help to figure out what are the difference between these two form?
PS: Although I came across these terms while I was going through the docker file instructions(ex: RUN, CMD, ENTRYPOINT), I want to know the difference between them in general, not in docker context.
A: The docker shell syntax (which is just a string as the RUN, ENTRYPOINT, and CMD) will run that string as the parameter to /bin/sh -c. This gives you a shell to expand variables, sub commands, piping output, chaining commands together, and other shell conveniences.
RUN ls * | grep $trigger_filename || echo file missing && exit 1
The exec syntax simply runs the binary you provide with the args you include, but without any features of the shell parsing. In docker, you indicate this with a json formatted array.
RUN ["/bin/app", "arg1", "arg2"]
The advantage of the exec syntax is removing the shell from the launched process, which may inhibit signal processing. The reformatting of the command with /bin/sh -c in the shell syntax may also break concatenation of your entrypoint and cmd together.
The entrypoint documentation does a good job covering the various scenarios and explaining this in more detail.
A: These following explanation are from the Kubernetes In Action book(chapter 7).
Firstly, They have both two different forms:
*
*
shell form—For example, ENTRYPOINT node app.js
*
exec form—For example, ENTRYPOINT ["node","app.js"]
Actually The difference is whether the specified command is invoked inside a shell or not. I want to explain main difference between them with an example, too.
ENTRYPOINT ["node", "app.js"]
This runs the node process directly (not inside a shell), as you can see by listing the processes running inside the container:
$ docker exec 4675d ps x
PID TTY STAT TIME COMMAND
1 ? Ssl 0:00 node app.js
12 ? Rs 0:00 ps x
ENTRYPOINT node app.js
If you’d used the shell form (ENTRYPOINT node app.js), these would have been the container’s processes:
$ docker exec -it e4bad ps x
PID TTY STAT TIME COMMAND
1 ? Ss 0:00 /bin/sh -c node app.js
7 ? Sl 0:00 node app.js
13 ? Rs+ 0:00 ps x
As you can see, in that case, the main process (PID 1) would be the shell process instead of the node process. The node process (PID 7) would be started from that shell. The shell process is unnecessary, which is why you should always use the exec form of the ENTRYPOINT instruction.
A: Expanding on the top rated answer in this thread,
These are the recommended forms to use for each instruction:
*
*RUN: shell form
*ENTRYPOINT: exec form
*CMD: exec form
Shell features, variable substitution, signal trapping and forwarding, command and entrypoint concatenation are explained with examples in the below.
Variable substitution
In the shell form, Dockerfile instructions will inherit environment variables from the shell, such as $HOME and $PATH:
FROM alpine:latest
# Shell: echoes "/root" as set by the shell
RUN echo $HOME
# Exec: echoes "$HOME" because nothing is set
RUN ["echo", "$HOME"]
However, both forms behave the same when it comes to environment
variables set by the ENV instruction in the Dockerfile:
FROM alpine:latest
ENV VERSION=1.0.0
# Shell: echoes "1.0.0" because Docker does the substitution
RUN echo $VERSION
# Exec: echoes "1.0.0" because Docker does the substitution
RUN ["echo", "$VERSION"]
Shell features
The main thing you lose with the exec form is all the useful shell
features: sub commands, piping output, chaining commands, I/O
redirection, and more. These kinds of commands are only possible with
the shell form:
FROM ubuntu:latest
# Shell: run a speed test
RUN apt-get update \
&& apt-get install -y wget \
&& wget -O /dev/null http://speedtest.wdc01.softlayer.com/downloads/test10.zip \
&& rm -rf /var/lib/apt/lists/*
# Shell: output the default shell location
CMD which $(echo $0)
RUN instruction can make use of shell form for all the other features mentioned above and to reduce overall size of the image. Every Dockerfile directive will generate an intermediate container, committed into an intermediate image. Chaining multiple RUN instructions can help reduce the overall image size.
Signal trapping & forwarding
Most shells do not forward process signals to child processes, which
means the SIGINT generated by pressing CTRL-C may not stop a child
process:
# Note: Alpine's `/bin/sh` is really BusyBox `ash`, and when
# `/bin/sh -c` is run it replace itself with the command rather
# than spawning a new process, unlike Ubuntu's `bash`, meaning
# Alpine doesn't exhibit the forwarding problem
FROM ubuntu:latest
# Shell: `bash` doesn't forward CTRL-C SIGINT to `top`. so it will not stop.
ENTRYPOINT top -b
# Exec: `top` traps CTRL-C SIGINT and stops
ENTRYPOINT ["top", "-b"]
This is the main reason to use the exec form for both ENTRYPOINT and
SHELL.
Docker docs has more examples on this.. Signal trapping is also needed for docker stop command to work and for any cleanup task that needs to be done before stopping the container.
CMD as ENTRYPOINT parameters
Below concatenation will only work in exec form. It will not work in shell form.
FROM alpine:latest
# Exec: default container command
ENTRYPOINT ["sleep"]
# Exec: passed as parameter to the sleep command. At the end 'sleep 2s' will be run on the container.
CMD ["2s"]
However if you need to use some shell features in the exec form for CMD then below can be done.
CMD ["sh", "-c", "echo ${SLEEP_DURATION}"]
This does variable substitution to echo contents of SLEEP_DURATION environmental variable in the container while retaining the feature of exec form.
Source:
Above quoted examples are from this blog: source
Official docs now has lot more info on these differences - docker docs for entrypoint and docker docs for CMD
| |
doc_5483
|
Is there some compiler flag/setting that will ignore these errors? Also does anyone know how to find the documentation on the VC++ compiler?
Edit
This isn't a warning, it's an error. However, for me it's not an issue since my program is only dealing with numbers that come out as integers, so I don't care that they aren't floats. If it was just warnings I would move on with my life, but it's not letting me compile. Can I suppress errors somehow? Like I said, the errors aren't coming up on my Mac and the program is fine.
A: Regarding other answers here, it is not a good idea to tell the question author to turn off this warning. His code is broken - he's passing an unsigned int instead of a float. You should be telling him to fix his code!
This isn't a warning, it's an error. However, for me it's not an issue since my
program is only dealing with numbers that come out as integers, so I don't care that
they aren't floats. If it was just warnings I would move on with my life, but it's not
letting me compile. Can I suppress errors somehow? Like I said, the errors aren't
coming up on my Mac and the program is fine.
Integers and floats use different representations internally. If you have the same number in an int and a float, the bit pattern inside the storage for them is completely different. You cannot under any circumstances whatsoever expect your code to work if you are passing an integer when you should be passing a float.
Furthermore, I assert your Mac code either is silently using an overloaded version of that function (e.g. you are on that platform compiling with C++) or you believe it works when in fact it is working by chance or is not actually working.
Addendum
No compilers ever written has the ability to turn off errors.
A warning means the compiler thinks you're making a mistake.
An error means the compiler doesn't know what to do.
A: There are a couple of options:
In C, the solution is simply to cast the ints to doubles:
pow((double)i, (double)j)
In C++, you can do the same, although you should use a C++-style cast:
pow(static_cast<double>(i), static_cast<double>(j))
But a better idea is to use the overload C++ provides:
std::pow(static_cast<double>(i), j);
The base still has to be a floating-point value, but the exponent can be an int at least
The std:: prefix probably isn't necessary (most compilers make the function available in the global namespace as well).
Of course, to access the C++ versions of the function, you have to include the C++ version of the header.
So instead of #include <math.h> you need to #include <cmath>
C++ provides C++ versions of every C header, using this naming convention. If the C header is called foo.h, the C++ version will be cfoo. When you're writing in C++, you should always prefer these versions.
A: I don't know of a flag, but getting rid of the warnings was easy enough for me. Just double click on each of the warnings in the "Task List" and add the appropriate casting, whether you prefer
(double) my_variable
or
static_cast<double>(my_variable)
I'm guessing if you're getting the ambiguous warning, there are multiple pow functions defined somewhere. It's better to be explicit in my opinion anyway. For what it's worth, my vote goes with the static_cast option.
A: As Mehrdad mentioned, use the #pragma warning syntax to disable a warning. Documentation is here - http://msdn.microsoft.com/en-us/library/2c8f766e.aspx
I would be inclined to fix the warnings rather than hide them though!
A: C++ has overloads for pow/powf for int exponents. Heed the warning.
A: Don't ignore this or any warnings. Fix them. The compiler is your friend, trying to get you to write good code. It's a friend that believes in tough love, but it is your friend.
If you have an unsigned int and need a float, convert your unsigned in to a float.
And the MSDN Library is the documentation for both the VC++ implementation of the language and the IDE itself.
| |
doc_5484
|
Here is the code I quickly wrote for the site:
payload = {'firstname': 'Ryanous', 'lastname': 'Smti','email': 'thingy7237@gmail.com', 'PASSWORD': 'yaya7893478934',}
r = requests.post(WHAT_URL??? , data = payload)
time.sleep(1.7834734)
print(r.content)
So lets say I'm trying to sign up here (https://reg.ebay.com/reg/PartialReg) with Python Requests. So when I look into the Network tab to see what happens when I sign up 3 things happen. When I type my first name and last name that I type what I type is sent to https://reg.ebay.com/reg/track . When I type my email it posts to https://reg.ebay.com/reg/track as well as https://reg.ebay.com/reg/ajax . When I type my password the network console shows that it POST's to only https://reg.ebay.com/reg/ajax . However when I POST to any of these url's it doesn't work. What is going on?
Thanks in advance!!!
A: Here is the complete request sent to ebay intercepted with fiddler,
POST https://reg.ebay.com/reg/PartialReg HTTP/1.1
Host: reg.ebay.com
Connection: keep-alive
Content-Length: 741
Cache-Control: max-age=0
Origin: https://reg.ebay.com
Upgrade-Insecure-Requests: 1
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Referer: https://reg.ebay.com/reg/PartialReg
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Cookie: aam_uuid=60231779855192746434487614328071690113; cid=o48ObOkRdLGL6CaS%231913659548; AMCV_A71B5B5B54F607AB0A4C98A2%40AdobeOrg=-1758798782%7CMCIDTS%7C17777%7CMCMID%7C60242666160665362384488940468295249468%7CMCAAMLH-1536475733%7C3%7CMCAAMB-1536475733%7CRKhpRz8krg2tLO6pguXWp5olkAcUniQYPHaMWWgdJ3xzPWQmdj0y%7CMCCIDH%7C-1206723612%7CMCOPTOUT-1535878133s%7CNONE%7CMCAID%7CNONE; npii=btguid/a9479d531640ad4ba1dfdf77fff991ba5d6cbc38^cguid/a947a4721640aa46a1733082f26b543a5d6cbc38^; JSESSIONID=1163EA25E5D28E6D3FEFE265DC42CA03; __gads=ID; BidWatchConf=CgADJACBbloHkOTYwNmFiNzhmMTM3NDBjNzgyY2I1ZmE4MTk2MjdiMDDXi0VO; ns1=BAQAAAWWsLakOAAaAAKUADV12Y+QxODE1MTcyNTc4LzA7ANgAWF12Y+RjODR8NjAxXjE1MzI2MjQwODExNDJeWldNM1pHSXROUT09XjFeM3wyfDV8NHw3fDExXjFeMl40XjNeMTJeMTJeMl4xXjFeMF4xXjBeMV42NDQyNDU5MDc1q4Mtw+9aMn7pnSq6mpxylOOxeMc*; dp1=bkms/in5f579764^u1f/ANUJ5d7663e4^u1p/ZWM3ZGItNQ**5d7663e4^bl/INen-US5f579764^expt/00015326240648785c4a9681^pbf/%235280000000e000e000008180c20000045d7663e4^; s=CgAD4ACBbloHkYmVjNDM4N2YxNjUwYWRhMWY1MTJhOGFiZmZmYTQ0NzW5qXev; nonsession=BAQAAAWWsLakOAAaAAJ0ACF12Y+QwMDAwMDAwMQFkAAJddmPkI2EACAAcW7y9ZDE1MzQzNTQ4MzN4MzMyNjQzNDYxOTEzeDB4Mk4AMwAJXXZj5DkwMDAxLFVTQQDLAAFblTdsOABAAAdddmPkZWM3ZGItNQAQAAdddmPkZWM3ZGItNQDKACBk+zHkYTk0NzlkNTMxNjQwYWQ0YmExZGZkZjc3ZmZmOTkxYmEABAAHXT6SeGVjN2RiLTUAnAA4XXZj5G5ZK3NIWjJQckJtZGo2d1ZuWStzRVoyUHJBMmRqNkFNa1llZ0Q1S0hwZ1NkajZ4OW5ZK3NlUT09eh5LsYJBoaoQK/KuV1EGI2Ak2B4*; ebay=%5Esbf%3D%23%5Ejs%3D1%5Epsi%3DAxDh%2FH1E*%5E; ds2=sotr/b7r1Uzzzzzzz^
isSug=false&countryId=1&userid=&ru=http%3A%2F%2Fwww.ebay.com&firstname=Ryanous&lastname=Smti&email=thingy7237%40gmail.com&PASSWORD=yaya7893478934&checkbox-default=on&mblChk=0&promotion=true&iframeMigration1=true&mode=1&frmaction=submit&tagInfo=ht5%253DAQAAAWSqr7ETAAUxNjRkNzgyZjgyNi5hZDc4ZWEyLjNhOGMuZmZmZjc3Yjm7B%25252BT3Tthy8Kdb8nvEHRiRxsMukQ**%257Cht5new%253Dfalse%2526usid%253Dbec438aa1650ada1f517e302ffff91fc&hmvb=&isGuest=0&idlstate=&profilePicture=&agreement=Terms+and+conditions&signInUrl=https%253A%252F%252Fsignin.ebay.com%252Fws%252FeBayISAPI.dll%253FSignIn%2526regUrl%253Dhttps%25253A%25252F%25252Freg.ebay.com%25252Freg%25252FPartialReg&personalFlag=true&isMobilePhone=&_trksid=p2052190&ets=AQADAAAAEOLzuussjt0oS0JDE3e8D_o%0D%0A
From the above raw request you can see, that you need to POST all these values to https://reg.ebay.com/reg/PartialReg. Some of the keys in data dictionary can be extracted from ebay's html page source.
data = {
"isSug": "false",
"countryId": "1",
"userid": "",
"ru": "http%3A%2F%2Fwww.ebay.com",
"firstname": "Ryanous",
"lastname": "Smti",
"email": "thingy7237%40gmail.com",
"PASSWORD": "yaya7893478934",
"checkbox-default": "on",
"mblChk": "0",
"promotion": "true",
"iframeMigration1": "true",
"mode": "1",
"frmaction": "submit",
"tagInfo": "ht5%253DAQAAAWSqr7ETAAUxNjRkNzgyZjgyNi5hZDc4ZWEyLjNhOGMuZmZmZjc3Yjm7B%25252BT3Tthy8Kdb8nvEHRiRxsMukQ**%257Cht5new%253Dfalse%2526usid%253Dbec438aa1650ada1f517e302ffff91fc",
"hmvb": "",
"isGuest": "0",
"idlstate": "",
"profilePicture": "",
"agreement": "Terms+and+conditions",
"signInUrl": "https%253A%252F%252Fsignin.ebay.com%252Fws%252FeBayISAPI.dll%253FSignIn%2526regUrl%253Dhttps%25253A%25252F%25252Freg.ebay.com%25252Freg%25252FPartialReg",
"personalFlag": "true",
"isMobilePhone": "",
"_trksid": "p2052190",
"ets": "AQADAAAAEOLzuussjt0oS0JDE3e8D_o%0D%0A",
}
| |
doc_5485
|
id
123246512378
632746378456
378256364036
159204652855
327445634589
I want to make data that consist of data that consist dual three consecutive numbers like 123246512378, 3274456|34589 is reduced
id
632746378456
378256364036
159204652855
A: First, turn df.id into a an array of single digit integers.
a = np.array(list(map(list, map(str, df.id))), dtype=int)
Then check to see if one digit is one less than the next digit... twice
first = a[:, :-2] == a[:, 1:-1] - 1
second = a[:, 1:-1] == a[:, 2:] - 1
Create a mask for when we have this happen more than once
mask = np.count_nonzero(first & second, axis=1) < 2
df[mask]
id
1 632746378456
2 378256364036
3 159204652855
A: Not sure if this is faster than @piRSquared as I'm not good enough with pandas to generate my own test data, but it seems like it should be:
def mask_cons(df):
a = np.array(list(map(list, df.id.astype(str))), dtype = float)
# same as piRSquared, but float
g_a = np.gradient(a, axis = 1)[:,1:-1]
# 3 consecutive values will give grad(a) = +/-1
mask = (np.abs(g_a) == 1).sum(1) > 1
# this assumes 4 consecutive values count as 2 instances of 3 consecutive values
# otherwise more complicated methods are needed (probably @jit)
return df[mask]
| |
doc_5486
|
Are the following counter implementations functionally equivalent?
type Counter interface {
Inc()
Load() int64
}
// Atomic Implementation
type AtomicCounter struct {
counter int64
}
func (c *AtomicCounter) Inc() {
atomic.AddInt64(&c.counter, 1)
}
func (c *AtomicCounter) Load() int64 {
return atomic.LoadInt64(&c.counter)
}
// Mutex Implementation
type MutexCounter struct {
counter int64
lock sync.Mutex
}
func (c *MutexCounter) Inc() {
c.lock.Lock()
defer c.lock.Unlock()
c.counter++
}
func (c *MutexCounter) Load() int64 {
c.lock.Lock()
defer c.lock.Unlock()
return c.counter
}
I have run a bunch of test cases (Playground Link) and haven't been able to see any different behaviour. Running the tests on my machine the numbers get printed out of order for all the PrintAll test functions.
Can someone confirm whether they are equivalent or if there are any edge cases where these are different? Is there a preference to use one technique over the other? The atomic documentation does say it should only be used in special cases.
Update:
The original question that caused me to ask this was this one, however it is now on hold, and i feel this aspect deserves its own discussion. In the answers it seemed that using a mutex would guarantee correct results, whereas atomics might not, specifically if the program is running in multiple threads. My questions are:
*
*Is it correct that they can produce different results? (See update below. The answer is yes.).
*What causes this behaviour?
*What are the tradeoffs between the two approaches?
Another Update:
I've found some code where the two counters behave differently. When run on my machine this function will finish with MutexCounter, but not with AtomicCounter. Don't ask me why you would ever run this code:
func TestCounter(counter Counter) {
end := make(chan interface{})
for i := 0; i < 1000; i++ {
go func() {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for j := 0; j < 10000; j++ {
k := int64(r.Uint32())
if k >= 0 {
counter.Inc()
}
}
}()
}
go func() {
prevValue := int64(0)
for counter.Load() != 10000000 { // Sometimes this condition is never met with AtomicCounter.
val := counter.Load()
if val%1000000 == 0 && val != prevValue {
prevValue = val
}
}
end <- true
fmt.Println("Count:", counter.Load())
}()
<-end
}
A: Atomics are faster in the common case: the compiler translates each call to a function from the sync/atomic package to a special set of machine instructions which basically operate on the CPU level — for instance, on x86
architectures, an atomic.AddInt64 would be translated to some plain
ADD-class instruction prefixed with the LOCK instruction (see this for an example) —
with the latter ensuring coherent view of the updated memory location
across all the CPUs in the system.
A mutex is a much complicated thing as it, in the end, wraps some bit
of the native OS-specific thread synchronization API
(for instance, on Linux, that's futex).
On the other hand, the Go runtime is pretty much optimized when
it comes to synchronization stuff (which is kinda expected —
given one of the main selling points of Go), and the mutex implementation
tries to avoid hitting the kernel to perform synchronization
between goroutines, if possible, and carry it out completely in
the Go runtime itself.
This might explain no noticeable difference in the timings
in your benchmarks, provided the contention over the mutexes
was reasonably low.
Still, I feel oblidged to note — just in case — that atomics and
higher-level synchronization facilities are designed to solve different
tasks. Say, you can't use atomics to protect some memory state during
the execution of a whole function — and even a single statement,
in the general case.
A: There is no difference in behavior. There is a difference in performance.
Mutexes are slow, due to the setup and teardown, and due to the fact that they block other goroutines for the duration of the lock.
Atomic operations are fast because they use an atomic CPU instruction (when possible), rather than relying on external locks to.
Therefore, whenever it is feasible, atomic operations should be preferred.
A: Alright, I'm going to attempt to self-answer for some closure. Edits are welcome.
There is some discussion about the atomic package here. But to quote the most telling comments:
The very short summary is that if you have to ask, you should probably
avoid the package. Or, read the atomic operations chapter of the
C++11 standard; if you understand how to use those operations safely
in C++, then you are more than capable of using Go's sync/atomic
package.
That said, sticking to atomic.AddInt32 and atomic.LoadInt32 is safe as
long as you are just reporting statistical information, and not
actually relying on the values carrying any meaning about the state of
the different goroutines.
And:
What atomicity does not guarantee, is any ordering of
observability of values. I mean, atomic.AddInt32() does only guarantee
that what this operation stores at &cnt will be exactly *cnt + 1 (with
the value of *cnt being what the CPU executing the active goroutine
fetched from memory when the operation started); it does not provide any
guarantee that if another goroutine will attempt to read this value at
the same time it will fetch that same value *cnt + 1.
On the other hand, mutexes and channels guarantee strict ordering
of accesses to values being shared/passed around (subject to the rules
of Go memory model).
In regards to why the code sample in the question never finishes, this is due to fact that the func that is reading the counter is in a very tight loop. When using the atomic counter, there are no syncronisation events (e.g. mutex lock/unlock, syscalls) which means that the goroutine never yields control. The result of this is that this goroutine starves the thread it is running on, and prevents the scheduler from allocating time to any other goroutines allocated to that thread, this includes ones that increment the counter meaning the counter never reaches 10000000.
| |
doc_5487
|
We are now planning to take this 'manipulation of data' out of the application and delegate this responsibility to a stored procedure in ORACLE DBMS. Their procedure, on other hand, will take help of different in-built and explicitly written functions to do its job.
Now my concern is how efficient is the 'procedure run' in ORACLE DBMS. I am supposing Oracle will invoke different functions call from the stored procedure in an in-line fashion, or otherwise , but will definitely not make those calls as part of some child process, which will otherwise give a big hit to the performance of this stored-procedure.
Note:This procedure will be called through-out the day, with hundreds of thousand of row to be updated. This make the performance of this stored-procedure very crucial for the application.
Can you comment on the performance of the stored procedure in general as compared to when manipulation is part of an application.
EDIT:
Manipulation is as simple as taking few values out from a map, collating them together and update them in a particular column of a table.
Many Thanks,
Mawia
A: The PL/SQL code will access data with lower latency than the application, and you're unlikely to have a problem If you follow good practice's. Do as much as possible in SQL, and use implicit cursors instead of explicit cursors.
| |
doc_5488
|
<max:MaxTabControl Grid.Column="1" Margin="2">
<max:MaxTabItem FieldDescription="Enum:PayrollProvincesType.Federal">
<ScrollViewer>
</ScrollViewer>
</max:MaxTabItem>
<max:MaxTabItem FieldDescription="Enum:PayrollProvincesType.Quebec">
</max:MaxTabItem>
<!-- more provinces here -->
</max:MaxTabControl>
A: Just grab a Visibility converter and bind to IsChecked of the relevant CheckBox
<CheckBox x:Name="Ontario"/>
<Object Visibility="{Binding Path=IsChecked,
ElementName=Ontario,
Converter={StaticResource VisibilityBooleanConverter}}"/>
| |
doc_5489
|
public class ProfileForm
{
// these are the fields that will hold the data
// we will gather with the form
[Prompt("What is your first name? {||}")]
public string FirstName;
[Prompt("What is your last name? {||}")]
public string LastName;
[Prompt("What is your gender? {||}")]
public Gender Gender;
// This method 'builds' the form
// This method will be called by code we will place
// in the MakeRootDialog method of the MessagesControlller.cs file
public static IForm<ProfileForm> BuildForm()
{
return new FormBuilder<ProfileForm>()
.Message("Please complete your profile!")
.OnCompletion(async (context, profileForm) =>
{
BotData bt = new BotData();
await context.PostAsync("Your profile is complete.\n\n"+profileForm.FirstName+profileForm.LastName+profileForm.Gender);
SessionInfo.botUserData.SetProperty<bool>("ProfileComplete", true);
SessionInfo.botUserData.SetProperty<string>("FirstName", profileForm.FirstName);
SessionInfo.botUserData.SetProperty<string>("LastName", profileForm.LastName);
SessionInfo.botUserData.SetProperty<string>("Gender", profileForm.Gender==Gender.Male? "Male" :"Female");
await context.PostAsync("Before Saving");
await SessionInfo.userStateClient.BotState.SetPrivateConversationDataWithHttpMessagesAsync(
SessionInfo.ChannelID, SessionInfo.ConversationID, SessionInfo.FromID, SessionInfo.botUserData);
// Tell the user that the form is complete
await context.PostAsync("Your profile is complete.");
})
.Build();
}
}
// This enum provides the possible values for the
// Gender property in the ProfileForm class
// Notice we start the options at 1
[Serializable]
public enum Gender
{
Male = 1, Female = 2
};
I've got the following error at line SetPrivateConversationDataWithHttpMessagesAsync() method call, Please help.
Object reference not set to an instance of an object.
at
Microsoft.Bot.Builder.FormFlow.FormDialog1.<MessageReceived>d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.ThunkResume1.d4.MoveNext()
— End of stack trace from previous location where exception was thrown
— at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Bot.Builder.Internals.Fibers.Wait2.<Microsoft-Bot-Builder-Internals-Fibers-IWait<C>-PollAsync>d19.MoveNext()
— End of stack trace from previous location where exception was thrown
— at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Bot.Builder.Internals.Fibers.Frame1.<Microsoft-Bot-Builder-Internals-Fibers-IFrameLoop<C>-PollAsync>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Bot.Builder.Internals.Fibers.Fiber1.<Microsoft-Bot-Builder-Internals-Fibers-IFiberLoop<C>-PollAsync>d16.MoveNext()
— End of stack trace from previous location where exception was thrown
— at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
Microsoft.Bot.Builder.Internals.Fibers.Wait2.Microsoft.Bot.Builder.Internals.Fibers.IAwaiter<T>.GetResult() at
Microsoft.Bot.Builder.Dialogs.Chain.FromDialog1.<ResumeAsync>d3.MoveNext()
— End of stack trace from previous location where exception was thrown
— at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.ThunkResume1.<Rest>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Bot.Builder.Internals.Fibers.Wait2.<Microsoft-Bot-Builder-Internals-Fibers-IWait<C>-PollAsync>d19.MoveNext()
— End of stack trace from previous location where exception was thrown
— at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Bot.Builder.Internals.Fibers.Frame1.-PollAsync>d9.MoveNext()
— End of stack trace from previous location where exception was thrown
— at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Bot.Builder.Internals.Fibers.Fiber1.<Microsoft-Bot-Builder-Internals-Fibers-IFiberLoop<C>-PollAsync>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
Microsoft.Bot.Builder.Internals.Fibers.Wait2.Microsoft.Bot.Builder.Internals.Fibers.IAwaiter.GetResult()
at
Microsoft.Bot.Builder.Dialogs.Chain.LoopDialog1.<ResumeAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.ThunkResume1.d4.MoveNext()
— End of stack trace from previous location where exception was thrown
— at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Bot.Builder.Internals.Fibers.Wait2.<Microsoft-Bot-Builder-Internals-Fibers-IWait<C>-PollAsync>d19.MoveNext()
— End of stack trace from previous location where exception was thrown
— at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Bot.Builder.Internals.Fibers.Frame1.<Microsoft-Bot-Builder-Internals-Fibers-IFrameLoop<C>-PollAsync>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Bot.Builder.Internals.Fibers.Fiber1.<Microsoft-Bot-Builder-Internals-Fibers-IFiberLoop<C>-PollAsync>d16.MoveNext()
— End of stack trace from previous location where exception was thrown
— at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IDialogStack-PollAsync>d20.MoveNext()
— End of stack trace from previous location where exception was thrown
— at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d221.MoveNext()
— End of stack trace from previous location where exception was thrown
— at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Bot.Builder.Dialogs.Internals.ReactiveDialogTask.d31.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Bot.Builder.Dialogs.Internals.ScoringDialogTask1.d31.MoveNext()
— End of stack trace from previous location where exception was thrown
— at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Bot.Builder.Dialogs.Internals.PersistentDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d31.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
Microsoft.Bot.Builder.Dialogs.Internals.PersistentDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__31.MoveNext()
— End of stack trace from previous location where exception was thrown
— at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Bot.Builder.Dialogs.Internals.SerializingDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d41.MoveNext()
— End of stack trace from previous location where exception was thrown
— at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Bot.Builder.Dialogs.Internals.ExceptionTranslationDialogTask.d21.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Bot.Builder.Dialogs.Internals.LocalizedDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__21.MoveNext()
— End of stack trace from previous location where exception was thrown
— at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Bot.Builder.Dialogs.Internals.PostUnhandledExceptionToUserTask.d5`1.MoveNext()
— End of stack trace from previous location where exception was thrown
— at
Microsoft.Bot.Builder.Dialogs.Internals.PostUnhandledExceptionToUserTask.d51.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Bot.Builder.Dialogs.Internals.LogPostToBot.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__31.MoveNext()
— End of stack trace from previous location where exception was thrown
— at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Bot.Builder.Dialogs.Conversation.d4.MoveNext() —
End of stack trace from previous location where exception was thrown —
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.Bot.Builder.Dialogs.Conversation.d2.MoveNext() —
End of stack trace from previous location where exception was thrown —
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task
task) at LUISBotAppTesting.MessagesController.d__1.MoveNext()
A: It's a little bit hard to understand the problem, but I would like to mention, that function botUserData.SetProperty<>() doesn't save property it just edits property of current object. You should use BotState.SetUserData() and pass him the object to save it.
Here is a working example of saving bot state:
public static bool saveData(Activity activity, string key, string value)
{
StateClient stateClient = activity.GetStateClient();
BotData userData = stateClient.BotState.GetUserData(activity.ChannelId, activity.From.Id);
userData.SetProperty<string>(key, value);
BotData updateResponse = stateClient.BotState.SetUserData(activity.ChannelId, activity.From.Id, userData);
return value == updateResponse.GetProperty<string>(key);
}
| |
doc_5490
|
But most of the files i'm reading follow this format:
ServerName(1) = "Example1"
ServerName(2) = "Example1"
ServerName(3) = "Example3"
ServerName(4) = "Example4"
ServerName(5) = "Example5"
The 'cut' variable in the code below is supposed to cut the string at the "=" delimiter and return the value that comes after the "=" delimeter.
It should write to the duplicate file "Example1" but instead writes nothing. How would I make it so that the script below reads a file and only finds the duplicate in values after the "=" delimeter.
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
FileName = "Test.txt"
PathToSave = "C:"
Path = (PathToSave & FileName)
Set objFile = objFSO.OpenTextFile(Path, ForReading)
Set objOutputFile = objFSO.OpenTextFile(PathToSave & "Noduplicates.txt", 2, True)
Set objOutputFile2 = objFSO.OpenTextFile(PathToSave & "Duplicates.txt", 2, True)
objOutputFile.WriteLine ("This document contains the " & path & " file without duplicates" & vbcrlf)
objOutputFile2.WriteLine ("This document contains the duplicates found. Each line listed below had a duplicate in " & Path & vbcrlf)
Dim DuplicateCount
DuplicateCount = 0
Set Dict = CreateObject("Scripting.Dictionary")
Do until objFile.atEndOfStream
strCurrentLine = LCase(Trim(objFile.ReadLine))
Cut = Split(strCurrentline,"=")
If not Dict.Exists(LCase(Trim(cut(strCurrentLine)))) then
objOutputFile.WriteLine strCurrentLine
Dict.Add strCurrentLine,strCurrentLine
Else Dict.Exists(LCase(Trim(cut(strCurrentLine))))
objOutputFile2.WriteLine strCurrentLine
DuplicateCount = DuplicateCount + 1
End if
Loop
If DuplicateCount > 0 then
wscript.echo ("Number of Duplicates Found: " & DuplicateCount)
Else
wscript.echo "No Duplicates found"
End if
A: Cut is your array, so Cut(1) is the portion after the =. So that's what you should test for in your dictionary.
If InStr(strCurrentline, "=") > 0 Then
Cut = Split(strCurrentline,"=")
If Not Dict.Exists(Cut(1)) then
objOutputFile.WriteLine strCurrentLine
Dict.Add Cut(1), Cut(1)
Else
objOutputFile2.WriteLine strCurrentLine
DuplicateCount = DuplicateCount + 1
End if
End If
A: I makes no sense at all to ask Split to return an array with one element by setting the 3rd parameter to 1, as in
Cut = Split(strCurrentline,"=",1)
Evidence:
>> WScript.Echo Join(Split("a=b", "=", 1), "*")
>>
a=b
>> WScript.Echo Join(Split("a=b", "="), "*")
>>
a*b
BTW: ServerName(5) = "Example5" should be splitted on " = "; further thought about the quotes may be advisable.
Update wrt comments (and downvotes):
The semantics of the count parameter according to the docs:
count
Optional. Number of substrings to be returned; -1 indicates that all substrings are returned. If omitted, all substrings are returned.
Asking for one element (not an UBound!) results in one element containing the input.
Evidence wrt the type mismatch error:
>> cut = Split("a=b", "=", 1)
>> WScript.Echo cut
>>
Error Number: 13
Error Description: Type mismatch
>>
So please think twice.
| |
doc_5491
|
Part of the file text is:
Predicted XXX Area (NM): 88,0644
A 37 2.61 N, 1 12.75 W
XXX Track Vertices:
37 3.99 N, 1 13.02 W
Lines of interest
\tA\t37 2.61 N, 1 12.75 W
\t37 3.99 N, 1 13.02 W
I apply the following pattern
pat = re.compile(r'\s\s[1-9]?[0-9]\s[0-9]\.[0-9]{2}\s[NS],.+')
matcher = re.search(pat,text)
sol:
37 2.61 N, 1 12.75 W
How can I use regex to skip the the first line and catch the second one as follows ?
37 3.99N, 1 13.02W
Thanks
A: Going off the data you provided: You can use the beginning of string ^ anchor in multiline mode.
>>> import re
>>> s = '''Predicted XXX Area (NM): 88,0644
A 37 2.61 N, 1 12.75 W
XXX Track Vertices:
37 3.99 N, 1 13.02 W'''
>>> p = re.compile(r'^\s+([1-9]?[0-9]\s[0-9]\.[0-9]{2}\s[NS],.+)', re.M)
>>> re.search(p, s).group(1)
'37 3.99 N, 1 13.02 W'
A: If you are looking for lines that begin with whitespace and digits:
pat = re.compile(r'^\s+[1-9]?[0-9]\s[0-9]\.[0-9]{2}\s[NS],.+')
^^^^
The ^ matches beginning of line. The \s+ is for one or more whitespace.
You can't always trust consistency of whitespace, especially:
*
*In this case when you specified \t in your lines of interest
*In some cases when the source data is generated, shorter numbers could be padded with whitespace, and longer numbers would reduce whitespace to keep output looking even.
| |
doc_5492
|
In the file there is a block:
public void prepare(){
if (this.GenericObjectID != null)
doStuff();
else{
this.GenericObjet = new GenericObject();
}
However, when I look through GenericObject.java there is no constructor at all. The code runs, but I didn't write it, so I'm not positive how (yet!). So my question is: how is this possible? What is the java compiler doing when it sees this call but then no constructor in the file that describes the object?
A: If there are no explicit constructors, then the compiler creates an implicit default constructor, with no arguments, that does nothing but implicitly call the superclass constructor.
Section 8.8.9 of the JLS talks about default constructors:
If a class contains no constructor declarations, then a default constructor is implicitly declared. The form of the default constructor for a top level class, member class, or local class is as follows:
*
*The default constructor has the same accessibility as the class (§6.6).
*The default constructor has no formal parameters, except in a non-private inner member class, where the default constructor implicitly declares one formal parameter representing the immediately enclosing instance of the class (§8.8.1, §15.9.2, §15.9.3).
*The default constructor has no throws clauses.
*If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.
A: new GenericObject(); is the default constructor for the class GenericObject. It is automatically created by the compiler unless you explicitly define a constructor in your class.
This constructor will call the parent class' constructor, and will initialize class member variables to their default values.
| |
doc_5493
|
The PHP code below pulls the most current value for my Monday list.
<h2>Monday</h2>
<ul class="editme" contenteditable="true">
<?php
$result = mysqli_query($connection,"SELECT monday FROM schedule WHERE ID='1'");
$row = mysqli_fetch_array($result);
echo $row['monday'];
?>
</ul>
The JavaScript/jQuery/PHP code below will send an update to the MySQL database after the keyup event timer runs. I pass the HTML of the "editme" element to a JS variable and then post that to PHP for updating the db.
<script type="text/javascript">
$('.editme').keyup(function() {
delay(function(){
var send = $('.editme').html();
$.post('schedule.php', {content: send});
<?php
$text = $_POST['content'];
$sql="UPDATE schedule SET monday='$text' WHERE ID='1'";
if (is_null($text)) {
}
else {
mysqli_query($connection,$sql);
}
?>
}, 50 );
});
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
</script>
A: Instead of PHP's
htmlspecialchars($your_string_here)
use this instead:
htmlentities($your_string_here, ENT_QUOTES);
ENT_QUOTES will ensure that both double and single quotes are properly encoded.
| |
doc_5494
|
itemString
[{"_id":"1e12345","a":"abc","b":def","c":ghi"},{"_id":"1e678910","a":"xzx","b":sed","c":ert"}]
var item=itemString.split("},{").map(function(i){
return i
})
console.log(item)
what i need to get from from console.log(item)
0:{_id:"1e12345",a:"abc",b:"def",c:"ghi"}
1:{_id:"1e678910",a:"xzx",b:"sed",c:"ert"}
what i get from console.log(item)
0:"[{"_id":"1e12345","a":"abc","b":"def","c":"ghi""
1:""_id":"1e678910","a":"xzx","b":"sed","c":"ert"}]"
| |
doc_5495
|
at CreateRendezvousComponent_Template (create-rendezvous.component.html:45:9)
at executeTemplate (core.mjs:12114:9)
at refreshView (core.mjs:11977:13)
at refreshComponent (core.mjs:13073:13)
at refreshChildComponents (core.mjs:11767:9)
at refreshView (core.mjs:12027:13)
at refreshComponent (core.mjs:13073:13)
at refreshChildComponents (core.mjs:11767:9)
at refreshView (core.mjs:12027:13)
at refreshEmbeddedViews (core.mjs:13027:17)
the error comes from the HTML of "create-rendezvous" component
<label>Etat</label>
<input type="text" class="form-control" id="etat"
[(ngModel)]= "rendezvous.etat" name="etat">
</div>
<div class="form-group">
<label>user id</label>
<input type="number" class="form-control" id="user.id"
[(ngModel)]= "rendezvous.user.id" name="user.id">
</div>
<button class="btn btn-success" type="submit">Ajouter</button>
</form>
</div>
this is my "Create" function in the "create-rendezvous" component
saveRendezVous(){
this.rendezvousService.createRendezvous(this.rendezvous).subscribe(data=>{
console.log(data);
this.goToRendezvousList();
},
error=>console.log(error));
}
and this is my function in the angular service
createRendezvous(rendezvous:Rendezvous): Observable<Object>{
return this.httpClient.post(`${this.baseUrl}`, rendezvous);
}
i appreciate your help.
A: undefined would mean that you were trying to call the id property of an object that has not been initialized yet. Verify that not only is your rendezvous object is defined and initialized, but that the user object for it is initialized as well.
Likewise verify the user object itself is defined. If it is something that is only defined after some sort of API call to load the data then add some sort of loading state
A: Try with the Safe navigation operator to all the places where you are using the user.id
For example user?.id
| |
doc_5496
|
I seem to be successful at extracting the package, as I am able to eradicate all possible pre-compilation-errors in the project and build the .jar artifact.
I can also import this .jar as external library in my other project.
Edit: every private class from outside java.util.jar (i.e.: SharedSecrets) that was needed was also extracted and put in the .jar
However, when I try to run it (by replacing the import java.util.jar.*; in order to use my own version of it)
I get this error: java.lang.IllegalAccessError: class SharedSecrets (in unnamed module @0x2b546384) cannot access class jdk.internal.misc.Unsafe (in module java.base) because module java.base does not export jdk.internal.misc to unnamed module @0x2b546384
I tried both adding this: --add-exports=java.base/jdk.internal.misc=ALL-UNNAMED and adding this: --add-exports=java.base/jdk.internal.misc.Unsafe=ALL-UNNAMED to the Compilation options of both, the project consisting of the extracted java.util.jar package and the project I want to import it as external library, none worked -> the error persists.
All other --add-exports which are in the Compilation Options do work fine on both projects.
What am I doing wrong? What do I have to change in order for it to work?
N.B.: if things are unclear, feel free to ask!
Edit: The code where I try to use my own 'java.util.jar' instead of the official one (note at the moment both are identical, the only difference is that one remains inside the jdk while the other is just the 'minimal viable product')
This is not a duplicate of this as I (and I already pointed that out) tried the --add-exports which are suggested as answer in the other question.
The error occurs in the 4. line where the JarFile constructor is called which will not call the one from the jdk but the one from the selfmade library I imported.
public boolean verifyJar(String jarName)
throws Exception {
boolean anySigned = false; // if there exists entry inside jar signed
Map<String, String> digestMap = new HashMap<>();
Map<String, PKCS7> sigMap = new HashMap<>();
try (JarFile jf = new JarFile(jarName, true)) { // error
Vector<JarEntry> entriesVec = new Vector<>();
byte[] buffer = new byte[8192];
Enumeration<JarEntry> entries = jf.entries();
while (entries.hasMoreElements()) {
JarEntry je = entries.nextElement();
entriesVec.addElement(je);
try (InputStream is = jf.getInputStream(je)) {
String name = je.getName();
if (MySignatureFileVerifier.isSigningRelated(name)
&& MySignatureFileVerifier.isBlockOrSF(name)) {
String alias = name.substring(name.lastIndexOf('/') + 1,
name.lastIndexOf('.'));
try {
if (name.endsWith(".SF")) {
Manifest sf = new Manifest(is);
for (Object obj : sf.getMainAttributes().keySet()) {
String key = obj.toString();
if (key.endsWith("-Digest-Manifest")) {
digestMap.put(alias,
key.substring(0, key.length() - 16));
break;
}
}
} else {
sigMap.put(alias, new PKCS7(is));
}
} catch (IOException ioe) {
throw ioe;
}
} else {
while (is.read(buffer, 0, buffer.length) != -1) {
// we just read. this will throw a SecurityException
// if a signature/digest check fails.
}
}
}
}
Manifest man = jf.getManifest();
boolean hasSignature = false;
if (man != null) {
Enumeration<JarEntry> e = entriesVec.elements();
while (e.hasMoreElements()) {
JarEntry je = e.nextElement();
String name = je.getName();
hasSignature = hasSignature
|| MySignatureFileVerifier.isBlockOrSF(name);
CodeSigner[] signers = getCodeSigners(je, sigMap.get("SIGNER"));
boolean isSigned = (signers != null);
anySigned |= isSigned;
}
}
if (man == null) {
System.out.println();
}
// Even if the verbose option is not specified, all out strings
// must be generated so seeWeak can be updated.
if (!digestMap.isEmpty()
|| !sigMap.isEmpty()) {
for (String s : digestMap.keySet()) {
PKCS7 p7 = sigMap.get(s);
if (p7 != null) {
String history;
try {
SignerInfo si = p7.getSignerInfos()[0];
X509Certificate signer = si.getCertificate(p7);
String digestAlg = digestMap.get(s);
String sigAlg = AlgorithmId.makeSigAlg(
si.getDigestAlgorithmId().getName(),
si.getDigestEncryptionAlgorithmId().getName());
PublicKey key = signer.getPublicKey();
PKCS7 tsToken = si.getTsToken();
if (tsToken != null) {
SignerInfo tsSi = tsToken.getSignerInfos()[0];
X509Certificate tsSigner = tsSi.getCertificate(tsToken);
byte[] encTsTokenInfo = tsToken.getContentInfo().getData();
TimestampToken tsTokenInfo = new TimestampToken(encTsTokenInfo);
PublicKey tsKey = tsSigner.getPublicKey();
String tsDigestAlg = tsTokenInfo.getHashAlgorithm().getName();
String tsSigAlg = AlgorithmId.makeSigAlg(
tsSi.getDigestAlgorithmId().getName(),
tsSi.getDigestEncryptionAlgorithmId().getName());
}
} catch (Exception e) {
throw e;
}
}
}
}
System.out.println();
if (!anySigned) {
if (hasSignature) {
System.out.println("jar.treated.unsigned");
} else {
System.out.println("jar.is.unsigned");
return false;
}
} else {
System.out.println("jar.verified.");
return true;
}
return false;
} catch (Exception e) {
throw e;
}
}
A: As pointed out by Nicolai's answer to this question --add-exports java.base/jdk.internal.misc=ALL-UNNAMED has to be done when compiling (javac) and when running (java) the code.
A: A little late, but I since I bumped into this issue when trying out the OpenCV tutorial for Java and JavaFX, I will share what worked for me.
*
*To be able to compile I needed to add the OpenJFX and OpenCV libraries to classpath
*Not necessary to configure special module compilation - Eclipse handles it well with Java 11
*To be able to run I created a launch shortcut that adds the VM arguments as below
--module-path /javafx-sdk-11.0.2/lib
--add-modules=javafx.controls,javafx.fxml
--add-exports java.base/jdk.internal.misc=ALL-UNNAMED
A: I am sharing my solution around this issue. I faced this problem with a different package. However, this is how I came around it (I am using Eclipse):
Assuming that my classes are in a package called stack.overflow.test and my module name is stack,
I added "exports overflow.test" to module-info.java file following the instructions from https://jenkov.com/tutorials/java/modules.html
| |
doc_5497
|
code
<script>
$(document).ready(function () {
$('#example').DataTable();
});
</script>
<table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>deviceid</th>
<th>status</th>
<th>UpdatedTime</th>
</tr>
</thead>
<tfoot>
<tr>
<th>deviceid</th>
<th>status</th>
<th>UpdatedTime</th>
</tr>
</tfoot>
@foreach (var item in Model)
{
<tbody>
<tr>
<td>@Html.DisplayFor(modelItem => item.deviceid)</td>
<td>@Html.DisplayFor(modelItem => item.status)</td>
<td>@Html.DisplayFor(modelItem => item.UpdatedTime)</td>
</tr>
</tbody>
}
</table>
A: Try this:
$(document).ready(function () {
$('#example').DataTable();
});
A: <table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>deviceid</th>
<th>status</th>
<th>UpdatedTime</th>
</tr>
</thead>
<tfoot>
<tr>
<th>deviceid</th>
<th>status</th>
<th>UpdatedTime</th>
</tr>
</tfoot>
<tbody>
@foreach (var item in Model)
{
<tr >
<td>@Html.DisplayFor(modelItem => item.deviceid)</td>
<td>@Html.DisplayFor(modelItem => item.status)</td>
<td>@Html.DisplayFor(modelItem => item.UpdatedTime)</td>
</tr>
}
</tbody>
</table>
A: you add all of the following
//cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css
//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js
//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js
//cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js
Example link: https://jsfiddle.net/r8gd2227/3/
| |
doc_5498
|
| | Date | Open | High | Low | Close_DAILY | SMA200 | 4H | 1H | BUY |
|-----+---------------------+---------+---------+---------+---------------+----------+---------+---------+-------|
| 0 | 2021-02-26 00:00:00 | 234.761 | 239.4 | 209.105 | 221.717 | nan | 247.751 | 253.4 | nan |
| 1 | 2021-02-27 00:00:00 | 221.959 | 237.77 | 219.011 | 225.385 | nan | 247.886 | 251.655 | nan |
| 2 | 2021-02-28 00:00:00 | 225.457 | 229.4 | 195 | 210.214 | nan | 254.707 | 244.716 | nan |
| 3 | 2021-03-01 00:00:00 | 210.118 | 260 | 209.12 | 254.964 | nan | 246.808 | 250.706 | nan |
| 4 | 2021-03-02 00:00:00 | 254.949 | 264.9 | 227 | 239.684 | nan | 234.915 | 248.799 | nan |
| 5 | 2021-03-03 00:00:00 | 239.72 | 254.848 | 236.002 | 240.57 | nan | 228.379 | 247.751 | nan |
| 6 | 2021-03-04 00:00:00 | 240.48 | 249.988 | 225.531 | 229.637 | nan | 215.144 | 241.73 | nan |
....
| 214 | 2021-09-28 00:00:00 | 335.5 | 344.6 | 330 | 333 | 395.051 | 334.799 | 226.795 | nan |
| 215 | 2021-09-29 00:00:00 | 332.9 | 375.4 | 331.2 | 367.7 | 395.508 | 343.926 | 225.282 | nan |
| 216 | 2021-09-30 00:00:00 | 367.7 | 388.8 | 366.4 | 387.5 | 396.13 | 351.528 | 225.025 | nan |
| 217 | 2021-10-01 00:00:00 | 387.5 | 423.4 | 381.5 | 421.5 | 396.965 | 346.839 | 223.853 | nan |
| 218 | 2021-10-02 00:00:00 | 421.4 | 438.2 | 410.6 | 427.1 | 397.807 | 346.885 | 227.023 | nan |
| 219 | 2021-10-03 00:00:00 | 427 | 437.2 | 421.5 | 430.5 | 398.611 | 337.361 | 228.571 | nan |
| 220 | 2021-10-04 00:00:00 | 430.5 | 430.9 | 410.9 | 426.3 | 399.435 | 338.293 | 228.754 | nan |
| 221 | 2021-10-05 00:00:00 | 426.4 | 444 | 424 | 442.1 | 400.331 | 339.057 | 229.552 | nan |
| 222 | 2021-10-06 00:00:00 | 442 | 442.8 | 414.7 | 434.9 | 401.184 | 342.6 | 225.848 | nan |
| 223 | 2021-10-07 00:00:00 | 434.9 | 450 | 423.6 | 438.5 | 402.053 | 346 | 224.936 | YESSS |
in the BUY column i want to get a yesss if the close of that row is lower than the Low of 7 days before and if the Close_DAILY is above the SMA200. I am using the code below but as you can see in the last row of the data frame it is returning a YESSS although the low of 7 days before is higher than that days close.
daily.loc[(daily['Low'].shift(-7)>daily['Close_DAILY']) & (daily['Close_DAILY']>daily['SMA200']), 'BUY']='YESSS'
Basically, what I want to do is that to get a YESSS in the BUY column if the Close_DAILY is lower than the low of 7 days before.
A: To get the Low value of 7 days before you should use daily['Low'].shift(7).
Please check out pandas documentation for more details: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.shift.html
| |
doc_5499
|
I've tried a few different view of telling what the value I get out of the json is, but none of them seems to be able to tell the value is null.
if (!isNull(json.get("id"))) {
orderDataMap.put("id", json.get("id"));
} else {
orderDataMap.put("id", "");
}
if (!isNull(json.get("sr"))) {
orderDataMap.put("sr", json.get("sr"));
} else {
orderDataMap.put("sr", "");
}
if (!isNull(json.get("systemOrderId"))) {
orderDataMap.put("systemOrderId", json.get("systemOrderId"));
} else {
orderDataMap.put("systemOrderId", "");
}
in the if statement I've also tried using json.get("id") != NULL as well as json.get("id").equals(null)
Here's how it looks while debugging:
A: Use JSONObject.isNull to check if a value is not present or is null.
if (json.isNull("id")) {
orderDataMap.put("id", json.get("id"));
} else {
orderDataMap.put("id", "");
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.